Generic SELECT query
@param self {object} The NoPg connection/transaction object
@param types {}
@param search_opts {}
@param traits {object}
977296
function do_select(self, types, search_opts, traits) {
	return nr_fcall("nopg:do_select", function() {
		return prepare_select_query(self, types, search_opts, traits).then(function(q) {
			var result = q.compile();

			// Unnecessary since do_query() does it too
			//if(NoPg.debug) {
			//	debug.log('query = ', result.query);
			//	debug.log('params = ', result.params);
			//}

			debug.assert(result).is('object');
			debug.assert(result.query).is('string');
			debug.assert(result.params).is('array');

			var builder;
			var type = result.documentType;

			if( (result.ObjType === NoPg.Document) &&
			  is.string(type) &&
			  self._documentBuilders &&
			  self._documentBuilders.hasOwnProperty(type) &&
			  is.func(self._documentBuilders[type]) ) {
				builder = self._documentBuilders[type];
			}
			debug.assert(builder).ignore(undefined).is('function');

			return do_query(self, result.query, result.params ).then(get_results(result.ObjType, {
				'fieldMap': result.fieldMap
			})).then(function(data) {
				if(!builder) {
					return data;
				}
				debug.log('data = ', data);
				return builder(data);
			});
		});
	});
}
1191143
public <T extends Type> T selectCandidate(T[] candidates, T actual, Environment environment) {
		//
		T candidate = null;
		for (int i = 0; i != candidates.length; ++i) {
			T next = candidates[i];
			if (subtypeOperator.isSubtype(next, actual, environment)) {
				if (candidate == null) {
					candidate = next;
				} else {
					candidate = selectCandidate(candidate, next, actual, environment);
				}
			}
		}
		//
		return candidate;
	}
1009037
function(db) {
		return db.query('SELECT name FROM types WHERE name IS NOT NULL').then(function(db) {
			var types = db.fetch();
			debug.assert(types).is('array');

			var queries = ARRAY(types).map(function step_builder(type) {
				if(type && type.name) {
					return NoPg.createTriggerQueriesForType(type.name);
				}
				return [];
			}).reduce(function(a, b) {
				return a.concat(b);
			}, []);

			return queries.map(function(q) {
				return db.query(q);
			}).reduce(_Q.when, _Q(db));
		});
	}
139148
public SearchResponse searchAll(String[] indices, String type) {
        return searchAll(indices, JMArrays.buildArray(type));
    }
644884
def select(clas,pool_or_cursor,**kwargs):
    ""
    columns = kwargs.pop('columns','*')
    # todo(awinter): write a test for whether eqexpr matters; figure out pg behavior and apply to pgmock
    query="select %s from %s"%(columns,clas.TABLE)
    if kwargs: query+=' where %s'%' and '.join('%s=%%s'%k for k in kwargs)
    return select_or_execute(pool_or_cursor,query,tuple(kwargs.values()))
1314335
function _parse_select_order(ObjType, document_type, order, q, traits) {

	debug.assert(ObjType).is('function');
	debug.assert(document_type).ignore(undefined).is('object');
	debug.assert(order).is('array');

	return ARRAY(order).map(function(o) {
		var key, type, rest;
		if(is.array(o)) {
			key = parse_operator_name(o[0]);
			type = parse_operator_type(o[0], 'text');
			rest = o.slice(1);
		} else {
			key = parse_operator_name(o);
			type = parse_operator_type(o, 'text');
			rest = [];
		}

		if(key === 'BIND') {
			return _parse_function_predicate(ObjType, q, undefined, rest, type, traits);
		}

		//debug.log('key = ', key);
		var parsed_key = _parse_predicate_key(ObjType, {'traits': traits, 'epoch':true}, key);
		//debug.log('parsed_key = ', parsed_key);
		var pgcast = parse_predicate_pgcast(ObjType, document_type, key);
		//debug.log('pgcast = ', pgcast);

		return new Predicate( [pgcast(parsed_key.getString())].concat(rest).join(' '), parsed_key.getParams(), parsed_key.getMetaObject() );
	}).valueOf();
}
853068
public QueryResults<Entity> newTypedQuery(String kind) {
    // [START newTypedQuery]
    String gqlQuery = "select * from " + kind;
    Query<Entity> query = Query.newGqlQueryBuilder(Query.ResultType.ENTITY, gqlQuery).build();
    QueryResults<Entity> results = datastore.run(query);
    // Use results
    // [END newTypedQuery]
    return results;
  }
996593
private org.hibernate.Query query(String hql, Class<?>... type)
  {
    org.hibernate.Query q = session.createQuery(hql);
    for(int i = 0; i < positionedParameters.length; i++) {
      q.setParameter(i, positionedParameters[i]);
    }
    for(Map.Entry<String, Object> entry : namedParameters.entrySet()) {
      Object value = entry.getValue();
      if(Types.isArray(value)) {
        Object[] parameter = (Object[])value;
        if(parameter.length == 0) {
          throw new HibernateException(String.format("Invalid named parameter |%s|. Empty array.", entry.getKey()));
        }
        q.setParameterList(entry.getKey(), parameter);
      }
      else if(Types.isCollection(value)) {
        Collection<?> parameter = (Collection<?>)value;
        if(parameter.isEmpty()) {
          throw new HibernateException(String.format("Invalid named parameter |%s|. Empty list.", entry.getKey()));
        }
        q.setParameterList(entry.getKey(), parameter);
      }
      else {
        q.setParameter(entry.getKey(), value);
      }
    }
    if(offset > 0) {
      q.setFirstResult(offset);
    }
    if(rowsCount > 0) {
      q.setMaxResults(rowsCount);
    }

    if(type.length > 0) {
      q.setResultTransformer(Transformers.aliasToBean(type[0]));
    }
    return q;
  }
324020
@InterfaceAudience.Private
    public List<QueryRow> query(QueryOptions options) throws CouchbaseLiteException {
        if (options == null)
            options = new QueryOptions();
        if (groupOrReduce(options))
            return viewStore.reducedQuery(options);
        else
            return viewStore.regularQuery(options);
    }
418304
function do_delete(self, ObjType, obj) {
	return nr_fcall("nopg:do_delete", function() {
		if(!(obj && obj.$id)) { throw new TypeError("opts.$id invalid: " + util.inspect(obj) ); }
		var query, params;
		query = "DELETE FROM " + (ObjType.meta.table) + " WHERE id = $1";
		params = [obj.$id];
		return do_query(self, query, params);
	});
}
417932
function parse_search_traits(traits) {
	traits = traits || {};

	// Initialize fields as all fields
	if(!traits.fields) {
		traits.fields = ['$*'];
	}

	// If fields was not an array (but is not negative -- check previous if clause), lets make it that.
	if(!is.array(traits.fields)) {
		traits.fields = [traits.fields];
	}

	debug.assert(traits.fields).is('array');

	// Order by $created by default
	if(!traits.order) {
		// FIXME: Check if `$created` exists in the ObjType!
		traits.order = ['$created'];
	}

	// Enable group by
	if(traits.hasOwnProperty('group')) {
		traits.group = [].concat(traits.group);
	}

	if(!is.array(traits.order)) {
		traits.order = [traits.order];
	}

	debug.assert(traits.order).is('array');

	if(traits.limit) {
		if(!traits.order) {
			debug.warn('Limit without ordering will yeald unpredictable results!');
		}

		if((''+traits.limit).toLowerCase() === 'all') {
			traits.limit = 'ALL';
		} else {
			traits.limit = '' + parseInt(traits.limit, 10);
		}
	}

	if(traits.offset) {
		traits.offset = parseInt(traits.offset, 10);
	}

	if(traits.hasOwnProperty('prepareOnly')) {
		traits.prepareOnly = traits.prepareOnly === true;
	}

	if(traits.hasOwnProperty('typeAwareness')) {
		traits.typeAwareness = traits.typeAwareness === true;
	} else {
		traits.typeAwareness = NoPg.defaults.enableTypeAwareness === true;
	}

	// Append '$documents' to fields if traits.documents is specified and it is missing from there
	if((traits.documents || traits.typeAwareness) && (traits.fields.indexOf('$documents') === -1) ) {
		traits.fields = traits.fields.concat(['$documents']);
	}

	if(traits.hasOwnProperty('count')) {
		traits.count = traits.count === true;
		traits.fields = ['count'];
		delete traits.order;
	}

	return traits;
}
1151321
function QueryLogic(Type, options){
    Type = Type || {};
    var passedHydrator = options && options.toQuery;
    var passedSerializer = options && options.toParams;
    var schema;
    if(Type[schemaSymbol]) {
        schema = Type[schemaSymbol]();
    } else {
        schema = Type;
    }

    // check that the basics are here

    var id = schema.identity && schema.identity[0];
    if(!id) {
        //console.warn("can-query given a type without an identity schema.  Using `id` as the identity id.");
        schema.identity = ["id"];
    }

    var converter = makeBasicQueryConvert(schema),
        hydrate,
        serialize;

    if(passedHydrator) {
        hydrate = function(query){
            return converter.hydrate(passedHydrator(query));
        };
    } else {
        hydrate = converter.hydrate;
    }

    if(passedSerializer) {
        serialize = function(query){
            return passedSerializer(converter.serializer.serialize(query));
        };
    } else {
        serialize = converter.serializer.serialize;
    }
    this.hydrate = hydrate;
    this.serialize = serialize;
    this.schema = schema;

}
845654
@Description("apoc.index.relationships('TYPE','prop:value*') YIELD rel - lucene query on relationship index with the given type name")
    @Procedure(mode = Mode.READ)
    public Stream<WeightedRelationshipResult> relationships(@Name("type") String type, @Name("query") String query) throws Exception {
        if (!db.index().existsForRelationships(type)) return Stream.empty();
        return toWeightedRelationshipResult(db.index().forRelationships(type).query(query,null,null));
    }
697829
def where_entry_type(query, entry_type):
    
    if isinstance(entry_type, (list, set, tuple)):
        return orm.select(e for e in query if e.entry_type in entry_type)
    return orm.select(e for e in query if e.entry_type == entry_type)
400682
def es_query_proto(path, selects, wheres, schema):
    
    output = None
    last_where = MATCH_ALL
    for p in reversed(sorted( wheres.keys() | set(selects.keys()))):
        where = wheres.get(p)
        select = selects.get(p)

        if where:
            where = AndOp(where).partial_eval().to_esfilter(schema)
            if output:
                where = es_or([es_and([output, where]), where])
        else:
            if output:
                if last_where is MATCH_ALL:
                    where = es_or([output, MATCH_ALL])
                else:
                    where = output
            else:
                where = MATCH_ALL

        if p == ".":
            output = set_default(
                {
                    "from": 0,
                    "size": 0,
                    "sort": [],
                    "query": where
                },
                select.to_es()
            )
        else:
            output = {"nested": {
                "path": p,
                "inner_hits": set_default({"size": 100000}, select.to_es()) if select else None,
                "query": where
            }}

        last_where = where
    return output
735273
public Transactions getTransactions(final TransactionState state, final TransactionType type, final QueryParams params) {
        if (state != null) params.put("state", state.getType());
        if (type != null) params.put("type", type.getType());

        return doGET(Transactions.TRANSACTIONS_RESOURCE, Transactions.class, params);
    }
1124077
function (type) {
            var sql = [("" + type).toUpperCase()];
            try {
                this._static[sql + "_CLAUSE_METHODS"].forEach(function (m) {
                    if (m.match("With")) {
                        this[m](sql);
                    } else {
                        var sqlRet = this[m]();
                        if (sqlRet) {
                            sql.push(sqlRet);
                        }
                    }
                }, this);
            } catch (e) {
                throw e;
            }
            return sql.join("");
        }