Create PostgreSQL function `get_documents(data json, type json)` which returns the contents for
the property `$documents` based on provided specification.
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"]));
	}
1127516
def params_to_mongo(query_params):
    
    if not query_params:
        return {}
    for key, value in query_params.items():
        if isinstance(value, list):
            query_params[key] = {'$in': value}
    return query_params
521874
public function queryDocument($collection, $sql, array $params = [], array $options = [])
    {
        $this->setOptions($options);
        $doc = new Document($this->client, $this->database, $collection);
        $doc->setHeaders($this->getHeaders());
        $rs = $doc->query($sql, $params);
        $this->checkResponse($rs);
        unset($rs['_curl_info']);

        return $rs;
    }
400368
async function fetchDatabaseSchemas (client, schemaNames, jsonSchemas, messages) {
  const currentDbStructure = await pgInfo({
    client: client,
    schemas: schemaNames
  })

  const expectedDbStructure = await relationize({
    source: {
      schemas: jsonSchemas
    }
  })

  return {
    currentDbStructure,
    expectedDbStructure
  }
}
521552
public function parse($path, $tables, $json)
    {
        $this->path     = $path;
        $parser         = new SwaggerParser();
        $this->document = $parser->parseFile($path);

        $this->tables = $tables;
        $this->json   = $json;

        $documentObject = new OpenAPISpec($this->document, $this->tables, $this->json);

        return $documentObject;
    }
246780
def get!(id, params = {})
      slug = escape_docid(id)
      url = CouchRest.paramify_url("#{path}/#{slug}", params)
      result = connection.get(url)
      return result unless result.is_a?(Hash)
      doc = if /^_design/ =~ result["_id"]
        Design.new(result)
      else
        Document.new(result)
      end
      doc.database = self
      doc
    end
938586
def _rows_from_json(values, schema):
    """"""
    from google.cloud.bigquery import Row

    field_to_index = _field_to_index_mapping(schema)
    return [Row(_row_tuple_from_json(r, schema), field_to_index) for r in values]
1034098
def from_dict(self, document):
        
        # Get object properties from Json document
        identifier = str(document['_id'])
        active = document['active']
        timestamp = datetime.datetime.strptime(document['timestamp'], '%Y-%m-%dT%H:%M:%S.%f')
        properties = document['properties']
        # The directory is not materilaized in database to allow moving the
        # base directory without having to update the database.
        directory = self.get_directory(identifier)
        # Cretae image handle
        return ImageHandle(identifier, properties, directory, timestamp=timestamp, is_active=active)
286126
function() {
				var doc = this;
				var stack = [];

				_.forEach(model.$oids, function(fkType, schemaPath) {
					if (fkType.type == 'subDocument') return; // Skip sub-documents (as they are stored against the parent anyway)

					stack = stack.concat(doc.getNodesBySchemaPath(schemaPath)
						.map(function(node) {
							node.fkType = fkType.type;
							return node;
						})
					);
				});
				return stack;
			}
1205316
function stringYAML2JSON (doc, compact = false) {
  if (!doc || typeof doc !== 'string') {
    throw new TypeError('Argument must be a string or object, and not empty: ' + doc)
  }

  let obj = yaml.safeLoad(doc)

  if (!obj || typeof obj !== 'object') {
    throw new TypeError('Argument must be in yaml format: ' + doc)
  }

  return JSON.stringify(obj, undefined, compact ? undefined : 2)
}
665326
function get_results(Type, opts) {
	opts = opts || {};

	var field_map;
	if(is.func(opts.fieldMap)) {
		field_map = opts.fieldMap;
	} else if(is.obj(opts.fieldMap)) {
		field_map = function(k) {
			return opts.fieldMap[k];
		};
	}

	/** Parse field */
	function parse_field(obj, key, value) {
		debug.assert(obj).is('object');
		//debug.log('obj = ', obj);
		//debug.log('key = ', key);
		//debug.log('value = ', value);

		/* Parse full top level field */
		function parse_field_top(obj, key, value) {
			if( is.array(obj['$'+key]) ) {
				obj['$'+key] = obj['$'+key].concat(value);
			} else if( is.obj(obj['$'+key]) ) {
				obj['$'+key] = merge(obj['$'+key], value);
			} else {
				obj['$'+key] = value;
			}
		}

		/* Parse property in top level field based on a key as an array `[datakey, property_name]` */
		function parse_field_property(obj, key, value) {
			//debug.log('key = ', key);
			var a = key[0];
			var b = key[1];
			//debug.log('key_a = ', a);
			//debug.log('key_b = ', b);

			if(!is.obj(obj['$'+a])) {
				obj['$'+a] = {};
			}

			obj['$'+a][b] = value;
		}

		/* Parse property in top level field based on key in PostgreSQL JSON format */
		function parse_field_property_pg(obj, key, value) {
			//debug.log('key = ', key);
			/*jslint regexp: false*/
			var matches = /^([a-z][a-z0-9\_]*)\-\>\>'([^\']+)'$/.exec(key);
			/*jslint regexp: true*/
			var a = matches[1];
			var b = matches[2];
			return parse_field_property_pg(obj, [a,b], value);
		}

		//
		var new_key;
		if( is.func(field_map) && (new_key = field_map(key)) ) {
			if( (new_key) && (new_key !== key) ) {
				return parse_field(obj, new_key, value);
			}
		}

		if( is.array(key) ) {
			parse_field_property(obj, key, value);
		} else if( is.string(key) && (/^[a-z][a-z0-9\_]*$/.test(key)) ) {
			parse_field_top(obj, key, value);
		/*jslint regexp: false*/
		} else if ( is.string(key) && (/^([a-z][a-z0-9\_]*)\-\>\>'([^\']+)'$/.test(key)) ) {
		/*jslint regexp: true*/
			parse_field_property_pg(obj, key, value);
		} else {
			//debug.log('key = ', key);
			throw new TypeError("Unknown field name: " + key);
		}
	}

	/* Returns a function which will go through rows and convert them to NoPg format */
	return function(rows) {
		return ARRAY(rows).map(function(row, i) {
			if(!row) { throw new TypeError("failed to parse result #" + i + " from database!"); }
			//debug.log('input in row = ', row);

			//debug.log('row = ', row);

			if(row instanceof Type) {
				return row;
			}

			var obj = {};
			ARRAY(Object.keys(row)).forEach(function(key) {

				if(key === 'documents') {
					obj['$'+key] = {};
					ARRAY(Object.keys(row[key])).forEach(function(uuid) {
						if(!is.uuid(uuid)) {
							obj['$'+key][uuid] = row[key][uuid];
							return;
						}
						var sub_doc = row[key][uuid];
						var sub_obj = {};
						ARRAY(Object.keys(sub_doc)).forEach(function(k) {
							parse_field(sub_obj, k, sub_doc[k]);
						});
						obj['$'+key][uuid] = new NoPg.Document(sub_obj);
					});
					return;
				}

				parse_field(obj, key, row[key]);
			});

			_parse_object_expressions(obj);

			//debug.log('result in obj = ', obj);
			return new Type(obj);
		}).valueOf();
	};
}
761816
def json_response_schema( expected_object_schema ):
    
    schema = {
        'type': 'object',
        'properties': {
            'status': {
                'type': 'boolean',
            },
            'indexing': {
                'type': 'boolean',
            },
            'lastblock': {
                'anyOf': [
                    {
                        'type': 'integer',
                        'minimum': 0,
                    },
                    {
                        'type': 'null',
                    },
                ],
            },
        },
        'required': [
            'status',
            'indexing',
            'lastblock'
        ],
    }

    # fold in the given object schema
    schema['properties'].update( expected_object_schema['properties'] )
    schema['required'] = list(set( schema['required'] + expected_object_schema['required'] ))

    return schema
167974
def document(self, result):
        
        self._add_meta(result)
        walker = JsonWalker(JsonWalker.value_json, JsonWalker.dict_expand)
        r = walker.walk(result)
        return r
260866
def as_json(*args)
      document = { COLLECTION => collection, ID => id }
      document.merge!(DATABASE => database) if database
      document
    end
431721
function(db) {

		function get_documents(data, config, plv8, ERROR, WARNING) {

			function get_document(id) {
				return plv8.execute("SELECT * FROM documents WHERE id = $1 LIMIT 1", [id])[0];
			}

			function get_type(id) {
				return plv8.execute("SELECT * FROM types WHERE id = $1 LIMIT 1", [id])[0];
			}

			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);
			}

			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 document by UUID */
			function fetch_object_by_uuid(data, prop, 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);
				} else {
					return warn('Document already fetched: ' + uuid);
				}
			}

			/* */
			function fetch_object(data, prop) {
				var uuid = get_property(data, prop);
				if(is_array(uuid)) {
					return uuid.forEach(fetch_object_by_uuid.bind(undefined, data, prop));
				}
				return fetch_object_by_uuid(data, prop, 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"); }

			//var types_id = data.types_id;
			//if(!is_uuid(types_id)) { return error("data.types_id not valid UUID: " + types_id); }

			// Get document type
			//var type = get_type(types_id);
			//if(!is_object(type)) { return error("type not valid object: " + type); }

			//var relations = type.relations || {};
			//if(!is_object(relations)) { return error("type.relations not valid object: " + relations); }

			// 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"]));
	}
391670
protected function getJsonDocumentList()
    {
        if (!isset($this->config['library'])) {
            return json_encode(static::$apiResponseBody, JSON_PRETTY_PRINT);
        }

        if (!count($this->config['library'])) {
            return json_encode(static::$apiResponseBody, JSON_PRETTY_PRINT);
        }

        foreach (array_keys($this->config['library']) as $document) {
            static::$apiResponseBody['data'][] = [
                'document' => $document,
                'link' => Router::url([
                    'plugin' => 'Alt3/Swagger',
                    'controller' => 'Docs',
                    'action' => 'index',
                    $document
                ], true)
            ];
        }

        return json_encode(static::$apiResponseBody, JSON_PRETTY_PRINT + JSON_UNESCAPED_SLASHES);
    }
558301
def document(schema):
    """"""
    teleport_schema = from_val(schema)
    return json.dumps(teleport_schema, sort_keys=True, indent=2)