Parse functions when loading file restoring then to js valid objects.

@param {array} db Ambush functions db
@returns {arrat} Parsed db ready to use.
488133
function restoreFn(db) {
	return db.map(function(amb) {
		return Object.assign({}, amb, {action: JSONfn.parse(amb.action)});
	});
}
936173
function normalize(args) {
  let result = {
    queries:  null,
    callback: null
  };

  if (args.length === 1 && Array.isArray(args[0])) {
    result.queries = args[0];
  } else if (args.length === 2 && Array.isArray(args[0])) {
    result.queries = args[0];

    if (typeof args[1] === 'function') {
      result.callback = args[1];
    }
  } else {
    result.queries = args;

    if (typeof result.queries[result.queries.length - 1] === 'function') {
      result.callback = result.queries.pop();
    }
  }

  return result;
}
1148384
function parseFile (file, callback) {
  file.schema.plugins.parseFile({ file: file });

  // Find all JSON References ($ref) to other files, and add new File objects to the schema
  resolveFileReferences(file);

  safeCall(readReferencedFiles, file.schema, callback);
}
255467
function parseCover(str) {
    str = str.split(EOL);
    var obj = {};
    var reg = /(\w+)\s?:\s?(.+)/;
    str.forEach(function(val) {
        if (val = reg.exec(val)) {
            obj[val[1]] = val[2];
        }
    });
    return obj;
}
661068
function updates (qs0, callback0) {
    const { opts, callback } = getCallback(qs0, callback0)
    return relax({
      db: '_db_updates',
      qs: opts
    }, callback)
  }
1076161
function db(op, fn){
  if(!indexedDB){
    return fn(new Error('store `indexeddb` not supported by this browser'));
  }
  if(typeof op === 'function'){
    fn = op;
    op = 'readwrite';
  }

  if(source !== null){
    return fn(null, source.transaction(module.exports.prefix, op).objectStore(module.exports.prefix));
  }
  var req = indexedDB.open(module.exports.prefix, 1);
  req.onerror = function(e){
    fn(e);
  };
  req.onupgradeneeded = function(){
    // First time setup: create an empty object store
    req.result.createObjectStore(module.exports.prefix);
  };
  req.onsuccess = function() {
    source = req.result;
    db(op, fn);
  };
}
713084
function ArrayDB( a ){

            var init = [], i, _l;

            if ( arguments.length === 1 && arguments[0] instanceof Array ) {

                init = a;

            } else if ( arguments.length >= 1 ) {

                init = arguments;

            }

            for ( i=0, _l=init.length; i<_l; i++ ) {

                this[ this.length++ ] = init[ i ];

            }

        }
562830
function parseConfig(book) {
    var fs = book.getFS();
    var config = book.getConfig();

    return Promise.some(CONFIG_FILES, function(filename) {
        // Is this file ignored?
        if (book.isFileIgnored(filename)) {
            return;
        }

        // Try loading it
        return fs.loadAsObject(filename)
        .then(function(cfg) {
            return fs.statFile(filename)
            .then(function(file) {
                return {
                    file: file,
                    values: cfg
                };
            });
        })
        .fail(function(err) {
            if (err.code != 'MODULE_NOT_FOUND') throw(err);
            else return Promise(false);
        });
    })

    .then(function(result) {
        var values = result? result.values : {};
        values = validateConfig(values);

        // Set the file
        if (result.file) {
            config = config.setFile(result.file);
        }

        // Merge with old values
        config = config.mergeValues(values);

        return book.setConfig(config);
    });
}
174440
function(db) {

		/** Fetch external documents
		 * @param data {} 
		 * @param config {} 
		 * @param plv8 {} 
		 * @param ERROR {} 
		 * @param WARNING {} 
		 */
		function get_documents(data, config, plv8, ERROR, WARNING) {

			function get_document(id, fields) {
				fields = (fields || [{'query':'*'}]);

				var map = {};

				var obj = plv8.execute("SELECT "+fields.map(function(f, i) {
					var k;
					if(f.key) {
						k = 'p__' + i;
						map[k] = f;
						return f.query + ' AS ' + k;
					} else {
						return f.query;
					}
				}).join(', ')+" FROM documents WHERE id = $1 LIMIT 1", [id])[0];

				if(!obj) {
					return obj;
				}

				Object.keys(obj).forEach(function(key) {
					if(!map.hasOwnProperty(key)) {
						return;
					}

					var spec = map[key];
					if(!is_object(spec)) {
						return error('mapped resource missing');
					}
					if(!is_string(spec.key)) {
						return error('key missing');
					}
					var value = obj[key];
					delete obj[key];

					if(is_string(spec.datakey)) {
						if(!obj[spec.datakey]) {
							obj[spec.datakey] = {};
						}
						obj[spec.datakey][spec.key] = value;
					} else {
						obj[spec.key] = value;
					}
				});

				return obj;
			}

			function error(msg) {
				plv8.elog(ERROR, msg);
			}

			function warn(msg) {
				plv8.elog(WARNING, msg);
			}

			function is_object(a) {
				return a && (typeof a === 'object');
			}

			function is_array(a) {
				return a && (a instanceof Array);
			}

			function is_string(a) {
				return a && (typeof a === 'string');
			}

			function is_uuid(obj) {
				return /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/.test(obj);
			}

			/** Returns property from object
			 * @returns The value of property named `current` of object `last`, otherwise undefined.
			 */
			function get_property_step(last, current) {
				return is_object(last) ? last[current] : undefined;
			}

			/** Get value of property from provided object using a path.
			 * @param obj {object} The object from where to find the value.
			 * @param path {string} The path to the value in object.
			 * @returns {mixed} The value from the object at the end of path or `undefined` if any part is missing.
			 */
			function get_property(obj, path) {
				if(!is_object(obj)) { return error('get_property(obj, ...) not object: '+ obj); }
				if(!is_string(path)) { return error('get_property(..., path) not string: '+ path); }
				return path.split('.').reduce(get_property_step, obj);
			}

			/** Get PostgreSQL style property expression */
			function get_pg_prop(name) {

				if(name[0] === '$') {
					return name.substr(1);
				}

				var parts = name.split('.');

				if(parts.length === 1) {
					return "content->>'" + name + "'";
				}

				if(parts.length === 2) {
					return "content->'" + parts.join("'->>'") + "'";
				}

				return "content->'" + parts.slice(0, parts.length-1).join("'->'") + "'->>'" + parts[parts.length-1] + "'";
			}

			/** Execute query for document expressions
			 * @param parent {object} The parent document object
			 * @param prop {string} The name of the property where results are saved in the parent
			 * @param type_name {string} The name of the type of related documents
			 * @param type_prop {string} The property name in the related document for the UUID of parent
			 * @param fields {array} The fields in the related document that should be returned
			 */
			function expression_query(parent, prop, type_name, type_prop, fields) {

				fields = (fields || [{'query':'*'}]);

				var map = {};

				var query = "SELECT "+fields.map(function(f, i) {
					var k;
					if(f.key) {
						k = 'p__' + i;
						map[k] = f;
						return f.query + ' AS ' + k;
					} else {
						return f.query;
					}
				}).join(', ')+" FROM documents WHERE type = $1 AND "+get_pg_prop(type_prop)+" = $2";

				var rows = plv8.execute(query, [type_name, parent.id]);

				if(!is_array(rows)) {
					return rows;
				}

				var errors = [];

				rows = rows.map(function(obj) {
					Object.keys(obj).forEach(function(key) {
						if(!map.hasOwnProperty(key)) {
							return;
						}
						var spec = map[key];
						if(!is_object(spec)) {
							errors.push( error('mapped resource missing') );
							return;
						}
						if(!is_string(spec.key)) {
							errors.push( error('key missing') );
							return;
						}
						var value = obj[key];
						delete obj[key];

						if(is_string(spec.datakey)) {
							if(!obj[spec.datakey]) {
								obj[spec.datakey] = {};
							}
							obj[spec.datakey][spec.key] = value;
						} else {
							obj[spec.key] = value;
						}
					});
					return obj;
				});

				if(errors.length >= 1) {
					return errors.shift();
				}

				return rows;
			}

			/** Get document(s) by expression */
			function fetch_objects_by_expression(data, prop, fields, expression) {
				if(!is_object(data)) { return error('fetch_objects_by_expression(data, ..., ...) not object: '+ data); }
				if(!is_string(prop)) { return error('fetch_objects_by_expression(..., prop, ...) not string: '+ prop); }
				if(!is_string(expression)) { return warn('Expression was not string: {' + expression + '}, typeof ' + (typeof expression)); }

				prop = prop.trim();
				expression = expression.trim();

				var type_name, type_prop;
				var type_start = expression.indexOf('#');
				if(type_start >= 0) {
					type_name = expression.substr(0, type_start).trim();
					type_prop = expression.substr(type_start+1).trim();
				} else {
					type_name = expression;
				}

				if(!type_prop) {
					return error('No property name in expression: {'+ expression+'}');
				}

				var rows = expression_query(data, prop, type_name, type_prop, fields);
				if(!is_array(rows)) {
					return rows;
				}

				var warnings = [];

				if(!data.documents) {
					data.documents = {};
				}

				if(!data.documents.expressions) {
					data.documents.expressions = {};
				}

				if(!is_array(data.documents.expressions[prop])) {
					if(data.documents.expressions.hasOwnProperty(prop)) {
						data.documents.expressions[prop] = [data.documents.expressions[prop]];
					} else {
						data.documents.expressions[prop] = [];
					}
				}

				var id_list = data.documents.expressions[prop];

				rows.forEach(function(row) {
					var uuid = row.id;
					if(is_uuid(uuid)) {
						id_list.push(uuid);
						if(data.documents[uuid] === undefined) {
							data.documents[uuid] = row;
						//} else {
						//	warnings.push( warn('Document already fetched: ' + uuid) );
						}
					} else {
						warnings.push( warn('Document did not have UUID property: ' + JSON.stringify(row, null, 2) ) );
					}
				});

				if(warnings.length >= 1) {
					return warnings.shift();
				}
			}

			/** Get document by UUID */
			function fetch_object_by_uuid(data, prop, fields, uuid) {
				if(!is_object(data)) { return error('fetch_object_by_uuid(data, ..., ...) not object: '+ data); }
				if(!is_string(prop)) { return error('fetch_object_by_uuid(..., prop, ...) not string: '+ prop); }
				if(!is_uuid(uuid)) { return warn('Property ' + prop + ' was not uuid: ' + uuid); }
				if(data.documents[uuid] === undefined) {
					data.documents[uuid] = get_document(uuid, fields);
				} else {
					return warn('Document already fetched: ' + uuid);
				}
			}

			/* */
			function fetch_object(data, config) {
				var prop, fields;

				if(is_object(config)) {
					prop = config.prop;
					fields = config.fields;
				} else if(is_string(config)) {
					prop = config;
				}

				if(!is_string(prop)) {
					return error('property is not valid: ' + prop);
				}

				fields = fields ? fields : [{'query':'*'}];

				if(!is_array(fields)) {
					return error('fields are not valid: ' + fields);
				}

				var exp_start = prop.indexOf('{');
				var exp_end = prop.length-1;
				if( (exp_start >= 0) && (prop[exp_end] === '}') ) {
					return fetch_objects_by_expression(data, prop.substr(0, exp_start), fields, prop.substr(exp_start+1, exp_end-(exp_start+1)) );
				}

				var uuid = get_property(data, prop);

				if(is_array(uuid)) {
					// FIXME: This could be implemented with one query
					return uuid.forEach(fetch_object_by_uuid.bind(undefined, data, prop, fields));
				}

				return fetch_object_by_uuid(data, prop, fields, uuid);
			}

			// Check for bad input
			if(!is_object(data)) { return error("get_documents(data, ...) not object"); }
			if(!is_array(config)) { return error("get_documents(..., config) not array"); }

			// Populate documents from `config`
			data.documents = {};
			config.forEach( fetch_object.bind(undefined, data) );
			return data.documents;
		}

		return db.query('CREATE OR REPLACE FUNCTION get_documents(data json, config json) RETURNS json LANGUAGE plv8 VOLATILE AS ' + NoPg._escapeFunction(get_documents, ["data", "config", "plv8", "ERROR", "WARNING"]));
	}
906267
public function getFunctions($db = NULL): array
    {
        if (!$db) {
            $db = Configuration::getInstance()->get('db')['name'];
        }

        $res = [];
        foreach (q_assoc_iterator('SHOW FUNCTION STATUS WHERE `Db` = "' . $db . '"') as $v) {
            $res[] = $v['Name'];
        }

        return $res;
    }
425486
function openDatabase() {
    return new Promise((resolve, reject) => {
      var request = indexedDB.open(dbName, dbVersion);
      request.onerror = reject.bind(null, 'Error opening wasm cache database');
      request.onsuccess = () => { resolve(request.result) };
      request.onupgradeneeded = event => {
        var db = request.result;
        if (db.objectStoreNames.contains(storeName)) {
            console.log(`Clearing out version ${event.oldVersion} wasm cache`);
            db.deleteObjectStore(storeName);
        }
        console.log(`Creating version ${event.newVersion} wasm cache`);
        db.createObjectStore(storeName)
      };
    });
  }
53972
function(obj, callback, error) {
      var that = this
      objs = (this.isArray(obj) ? obj : [obj]).map(function(o) {
        if (!o.key) {
          o.key = that.uuid()
        }
        return o
      }),
        ins = "INSERT OR REPLACE INTO " + this.record + " (value, timestamp, id) VALUES (?,?,?)",
        win = function() {
          if (callback) {
            that.lambda(callback).call(that, that.isArray(obj) ? objs : objs[0])
          }
        }, error = error || function() {}, insvals = [],
        ts = now()

        try {
          for (var i = 0, l = objs.length; i < l; i++) {
            insvals[i] = [JSON.stringify(objs[i]), ts, objs[i].key];
          }
        } catch (e) {
          fail(e)
          throw e;
        }

      that.db.transaction(function(t) {
        for (var i = 0, l = objs.length; i < l; i++)
          t.executeSql(ins, insvals[i])
      }, function(e, i) {
        fail(e, i)
      }, win)

      return this
    }
658784
function getDatabase(database, options, callback) {
    getDatabaseConnector(database, options, returnDatabase)

    function returnDatabase(err, databaseConnector) {
        if (err) {
            return callback(err)
        }

        var db = databaseConnector.db(database)

        callback(null, db)
    }
}
938420
function DB() {
  this.requests = {}
  process.on('message', function(message) {
    if (message.type !== 'cache:response') {
      return
    }

    /** @type {{error: Error, response: string, uid: string, method: string}} */
    var data = message.data
    // The requests for this UID may not exist because there can be multiple
    // instances of Impromptu.
    if (!(this.requests[data.method] && this.requests[data.method][data.uid])) {
      return
    }

    var callbacks = this.requests[data.method][data.uid]
    for (var i = 0; i < callbacks.length; i++) {
      var callback = callbacks[i]
      callback(data.error, data.response)
    }

    delete this.requests[data.method][data.uid]
  }.bind(this))
}
866570
function _initStorage(options) {
    var self = this;
    var dbInfo = {
        db: null
    };

    if (options) {
        for (var i in options) {
            dbInfo[i] = options[i];
        }
    }

    // Get the current context of the database;
    var dbContext = dbContexts[dbInfo.name];

    // ...or create a new context.
    if (!dbContext) {
        dbContext = createDbContext();
        // Register the new context in the global container.
        dbContexts[dbInfo.name] = dbContext;
    }

    // Register itself as a running localForage in the current context.
    dbContext.forages.push(self);

    // Replace the default `ready()` function with the specialized one.
    if (!self._initReady) {
        self._initReady = self.ready;
        self.ready = _fullyReady;
    }

    // Create an array of initialization states of the related localForages.
    var initPromises = [];

    function ignoreErrors() {
        // Don't handle errors here,
        // just makes sure related localForages aren't pending.
        return Promise$1.resolve();
    }

    for (var j = 0; j < dbContext.forages.length; j++) {
        var forage = dbContext.forages[j];
        if (forage !== self) {
            // Don't wait for itself...
            initPromises.push(forage._initReady()["catch"](ignoreErrors));
        }
    }

    // Take a snapshot of the related localForages.
    var forages = dbContext.forages.slice(0);

    // Initialize the connection process only when
    // all the related localForages aren't pending.
    return Promise$1.all(initPromises).then(function () {
        dbInfo.db = dbContext.db;
        // Get the connection or open a new one without upgrade.
        return _getOriginalConnection(dbInfo);
    }).then(function (db) {
        dbInfo.db = db;
        if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {
            // Reopen the database for upgrading.
            return _getUpgradedConnection(dbInfo);
        }
        return db;
    }).then(function (db) {
        dbInfo.db = dbContext.db = db;
        self._dbInfo = dbInfo;
        // Share the final connection amongst related localForages.
        for (var k = 0; k < forages.length; k++) {
            var forage = forages[k];
            if (forage !== self) {
                // Self is already up-to-date.
                forage._dbInfo.db = dbInfo.db;
                forage._dbInfo.version = dbInfo.version;
            }
        }
    });
}
758663
function (db, id, operations, cb) {
			request.patch({
				url: host + 'databases/' + db + '/docs/' + id,
				headers: {
					'Content-Type': 'application/json; charset=utf-8'
				},
				body: JSON.stringify(operations)
			}, function (error, response, resBody) {
				if (!error && response.statusCode === 200) {
					var result = JSON.parse(resBody);
					cb(null, result);
				} else {
					cb(error || new Error(response.statusCode), null);
				}
			});
		}
1276035
function getDatabase(callback) {
    node.log(`Getting database:\n${dbName}\n`);
    var dbdef = {id : dbName};
        return new Promise((resolve, reject) => {
            client.readDatabase(databaseUrl, (err, result) => {
                if (err) {
                    if (err.code == HttpStatusCodes.NOTFOUND) {
                        client.createDatabase(dbdef, (err, created) => {
                            if (err) reject(err)
                            else resolve(created);
                        });
                    } else {
                        reject(err);
                    }
                } else {
                    resolve(result);
                }
            });
        });
    }