Create PostgreSQL function `get_documents(data json, type json)` which returns the contents for
the property `$documents` based on provided specification.
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"]));
	}
638248
function _get_result(Type) {
	return function(rows) {
		if(!rows) { throw new TypeError("failed to parse result"); }
		var doc = rows.shift();
		if(!doc) { return; }

		if(doc instanceof Type) {
			return doc;
		}

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

			if(key === 'documents') {
				obj['$'+key] = {};
				ARRAY(Object.keys(doc[key])).forEach(function(k) {
					if(is.uuid(k)) {
						obj['$'+key][k] = _get_result(NoPg.Document)([doc[key][k]]);
					} else {
						obj['$'+key][k] = doc[key][k];
					}
				});
				return;
			}

			obj['$'+key] = doc[key];
		});

		_parse_object_expressions(obj);

		return new Type(obj);
	};
}
467215
function getDocs(src, target, diffs, state) {
  diffs = pouchdbUtils.clone(diffs); // we do not need to modify this

  var resultDocs = [],
      ok = true;

  function getAllDocs() {

    var bulkGetOpts = createBulkGetOpts(diffs);

    if (!bulkGetOpts.docs.length) { // optimization: skip empty requests
      return;
    }

    return src.bulkGet(bulkGetOpts).then(function (bulkGetResponse) {
      /* istanbul ignore if */
      if (state.cancelled) {
        throw new Error('cancelled');
      }
      return Promise.all(bulkGetResponse.results.map(function (bulkGetInfo) {
        return Promise.all(bulkGetInfo.docs.map(function (doc) {
          var remoteDoc = doc.ok;

          if (doc.error) {
            // when AUTO_COMPACTION is set, docs can be returned which look
            // like this: {"missing":"1-7c3ac256b693c462af8442f992b83696"}
            ok = false;
          }

          if (!remoteDoc || !remoteDoc._attachments) {
            return remoteDoc;
          }

          return getDocAttachmentsFromTargetOrSource(target, src, remoteDoc)
                   .then(function (attachments) {
                           var filenames = Object.keys(remoteDoc._attachments);
                           attachments
                             .forEach(function (attachment, i) {
                                        var att = remoteDoc._attachments[filenames[i]];
                                        delete att.stub;
                                        delete att.length;
                                        att.data = attachment;
                                      });

                                      return remoteDoc;
                                    });
        }));
      }))

      .then(function (results) {
        resultDocs = resultDocs.concat(pouchdbUtils.flatten(results).filter(Boolean));
      });
    });
  }

  function hasAttachments(doc) {
    return doc._attachments && Object.keys(doc._attachments).length > 0;
  }

  function hasConflicts(doc) {
    return doc._conflicts && doc._conflicts.length > 0;
  }

  function fetchRevisionOneDocs(ids) {
    // Optimization: fetch gen-1 docs and attachments in
    // a single request using _all_docs
    return src.allDocs({
      keys: ids,
      include_docs: true,
      conflicts: true
    }).then(function (res) {
      if (state.cancelled) {
        throw new Error('cancelled');
      }
      res.rows.forEach(function (row) {
        if (row.deleted || !row.doc || !isGenOne(row.value.rev) ||
            hasAttachments(row.doc) || hasConflicts(row.doc)) {
          // if any of these conditions apply, we need to fetch using get()
          return;
        }

        // strip _conflicts array to appease CSG (#5793)
        /* istanbul ignore if */
        if (row.doc._conflicts) {
          delete row.doc._conflicts;
        }

        // the doc we got back from allDocs() is sufficient
        resultDocs.push(row.doc);
        delete diffs[row.id];
      });
    });
  }

  function getRevisionOneDocs() {
    // filter out the generation 1 docs and get them
    // leaving the non-generation one docs to be got otherwise
    var ids = Object.keys(diffs).filter(function (id) {
      var missing = diffs[id].missing;
      return missing.length === 1 && isGenOne(missing[0]);
    });
    if (ids.length > 0) {
      return fetchRevisionOneDocs(ids);
    }
  }

  function returnResult() {
    return { ok:ok, docs:resultDocs };
  }

  return Promise.resolve()
    .then(getRevisionOneDocs)
    .then(getAllDocs)
    .then(returnResult);
}
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;
    }
3144
function fromJson(collection, collectionPath, next) {

  var docsBulk = [];
  var docs = fs.readdirSync(collectionPath);
  var last = ~~docs.length, counter = 0;
  if (last === 0) {
    return next(null);
  }

  docs.forEach(function(docName) {

    var doc, data;
    try {
      data = fs.readFileSync(collectionPath + docName);
    } catch (err) {
      return last === ++counter ? next(null) : null;
    }
    try {
      doc = JSON.parse(data);
    } catch (err) {
      return last === ++counter ? next(err) : error(err);
    }

    docsBulk.push({
      insertOne: {
        document: doc
      }
    });

    return last === ++counter ? collection.bulkWrite(docsBulk, next) : null;
  });
}
1351430
function generateReplicationId(src, target, opts) {
  var docIds = opts.doc_ids ? opts.doc_ids.sort(pouchdbCollate.collate) : '';
  var filterFun = opts.filter ? opts.filter.toString() : '';
  var queryParams = '';
  var filterViewName =  '';
  var selector = '';

  // possibility for checkpoints to be lost here as behaviour of
  // JSON.stringify is not stable (see #6226)
  /* istanbul ignore if */
  if (opts.selector) {
    selector = JSON.stringify(opts.selector);
  }

  if (opts.filter && opts.query_params) {
    queryParams = JSON.stringify(sortObjectPropertiesByKey(opts.query_params));
  }

  if (opts.filter && opts.filter === '_view') {
    filterViewName = opts.view.toString();
  }

  return Promise.all([src.id(), target.id()]).then(function (res) {
    var queryData = res[0] + res[1] + filterFun + filterViewName +
      queryParams + docIds + selector;
    return new Promise(function (resolve) {
      pouchdbMd5.binaryMd5(queryData, resolve);
    });
  }).then(function (md5sum) {
    // can't use straight-up md5 alphabet, because
    // the char '/' is interpreted as being for attachments,
    // and + is also not url-safe
    md5sum = md5sum.replace(/\//g, '.').replace(/\+/g, '_');
    return '_local/' + md5sum;
  });
}
700980
function() {
      var documents = [];
      // search localstorage for saved documents
      for ( var i = 0, max = localStorage.length; i < max; i++) {
        var key = localStorage.key(i);
        // value is a document if key confirms to prefix
        if (key.indexOf(prefix) == 0) {
          var doc = getDocumentByKey(key);
          if (doc) {
            documents.push(doc);
          }
        }
      }
      return documents;
    }
767486
function applyGetters (self, json, type, options) {
  var schema = self.schema
    , paths = Object.keys(schema[type])
    , i = paths.length
    , path;


  while (i--) {
    path = paths[i];
    json[path] = clone(self.get(path), options);
  }

  return json;
}
153728
def read_contents(self):
        ''''''
        cur = self.conn.cursor()
        cur.execute('''select nspname,
                              description
                        from pg_catalog.pg_namespace s
                        left join pg_catalog.pg_description d
                            on (d.objoid = s.oid)
                        where s.nspname not like 'pg\_%' and
                        s.nspname <> 'information_schema'
                        order by s.nspname''')
        schemas = cur.fetchall()
        cur.close()
        from pgdocgen.ddlobject.schema import Schema
        for (schema, comment) in [(x[0], x[1]) for x in schemas]:
            schema_obj = Schema(schema, comment, self.conn)
            self.contents.append(copy.deepcopy(schema_obj))
        self.conn.close()
135512
def mongoqs_to_json(qs, fields=None):
    

    l = list(qs.as_pymongo())

    for element in l:
        element.pop('_cls')

    # use DjangoJSONEncoder for transform date data type to datetime
    json_qs = json.dumps(l, indent=2, ensure_ascii=False, cls=DjangoJSONEncoder)
    return json_qs
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();
	};
}
416540
def document_from_string(self, schema, request_string):
        # type: (GraphQLSchema, str) -> GraphQLDocument
        """"""
        key = self.get_key_for_schema_and_document_string(schema, request_string)
        if key not in self.cache_map:
            # We return from the fallback
            self.cache_map[key] = self.fallback_backend.document_from_string(
                schema, request_string
            )
            # We ensure the main backend response is in the queue
            self.get_worker().queue(self.queue_backend, key, schema, request_string)

        return self.cache_map[key]
351898
function generateQuery (fields, options, not) {
  let $and = []
  const $or = []
  const result = {}

  for (const key in options)
    switch (key) {
    case 'and':
    case 'or':
      const query = {}
      query[`$${key}`] = mapValues(options[key], value => {
        return generateQuery(fields, value)
      })
      return query
    case 'not':
      return generateQuery(fields, options[key], true)
    case 'range':
      $and.push(generateRangeQuery(fields, options.range))
      break
    case 'match':
      if ('or' in options.match)
        for (const key in options.match.or) {
          const q = {}
          q[key] = options.match.or[key]
          $or.push(q)
        }
      else $and.push(mapValues(options.match, value =>
        Array.isArray(value) ? { $in: value } : value))
      break
    case 'exists':
      $and.push(mapValues(options.exists, (value, key) => {
        if (!(key in fields)) return void 0

        if (fields[key].isArray)
          return value ? { $ne: [] } : []

        return value ? { $ne: null } : null
      }))
      break
    default:
    }

  if (not)
    $and = $and.map(applyNotOperator)

  if ($and.length) result.$and = $and
  if ($or.length) result.$or = $or

  return result
}
238619
public function generate_json($result=NULL, $match_array_type=FALSE) {
		// JSON data can optionally be passed to this function
		// either as a database result object or an array, or a user supplied array
		if (!is_null($result)) {
			if (is_object($result)) {
				$json_result=$result->result_array();
			} elseif (is_array($result)) {
				$json_result=$result;
			} else {
				return $this->_prep_args($result);
			}
		} else {
			return 'null';
		}
		return $this->_create_json($json_result, $match_array_type);
	}
612003
function getStats(results, done) {
  const databases = results.databases;

  const keys = ['document_count', 'storage_size', 'index_count', 'index_size'];
  const stats = {};
  keys.map(function(k) {
    stats[k] = 0;
  });
  databases.map(function(db) {
    keys.map(function(k) {
      stats[k] += db[k];
    });
  });
  done(null, stats);
}
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
702727
function couchdb (json) {
  return {
    prepareEndpoint (endpointOptions, sourceOptions) {
      return prepareEndpoint(json, endpointOptions, sourceOptions)
    },

    async send (request) {
      return send(json, request)
    },

    async serialize (data, request) {
      const serializedData = await serializeData(data, request, json)
      return json.serialize(serializedData, request)
    },

    async normalize (data, request) {
      const normalizedData = await json.normalize(data, request)
      return normalizeData(normalizedData)
    }
  }
}