Generate argument pairs for queries like where(id=2)
177065
def _standard_items(self, restrictions):
        """"""
        standard_items = self._build_where(restrictions, for_in=False)
        names = ["{}.{} == ?".format(pair[0], pair[1])
                 for pair in standard_items]
        values = [item[2] for item in standard_items]
        return (names, values)
471847
function ( arg ) {
		var result;

		if ( !arg ) {
			return;
		}

		arg = string.trim( arg );

		if ( arg.indexOf( "," ) === -1 ) {
			result = utility.dom( arg );
		}
		else {
			result = [];

			array.each( string.explode( arg ), function ( query ) {
				var obj = utility.dom( query );

				if ( obj instanceof Array ) {
					result = result.concat( obj );
				}
				else if ( obj ) {
					result.push( obj );
				}
			});
		}

		return result;
	}
1147594
function orwhere($where)
    {
        $args = func_get_args();
        if (count($args) == 1)
        {
            $where = $args[0];
        }
        else
        {
            list($field, $expr, $value) = $args;
            $where = '`'.str_replace('`', '', $field).'`' . $this->db->quote($expr) . " '".$this->db->quote($value)."'";
        }

        if ($this->where == "")
        {
            $this->where = "where " . $where;
        }
        else
        {
            $this->where = $this->where . " or " . $where;
        }
    }
224853
function where(column, operator, value) {

    // Support "where true || where false"
    if (column === false || column === true) {
      return this.where(1, '=', column ? 1 : 0);
    }

    // Check if the column is a function, in which case it's
    // a where statement wrapped in parens.
    if (typeof column === 'function') {
      return this.whereWrapped(column);
    }

    // Allow a raw statement to be passed along to the query.
    if (column instanceof Raw && arguments.length === 1) {
      return this.whereRaw(column);
    }

    // Allows `where({id: 2})` syntax.
    if (typeof column === 'object' && !(column instanceof Raw)) {
      return this._objectWhere(column);
    }

    // Enable the where('key', value) syntax, only when there
    // are explicitly two arguments passed, so it's not possible to
    // do where('key', '!=') and have that turn into where key != null
    if (arguments.length === 2) {
      value = operator;
      operator = '=';

      // If the value is null, and it's a two argument query,
      // we assume we're going for a `whereNull`.
      if (value === null) {
        return this.whereNull(column);
      }
    }

    // lower case the operator for comparison purposes
    var checkOperator = ('' + operator).toLowerCase().trim();

    // If there are 3 arguments, check whether 'in' is one of them.
    if (arguments.length === 3) {
      if (checkOperator === 'in' || checkOperator === 'not in') {
        return this._not(checkOperator === 'not in').whereIn(arguments[0], arguments[2]);
      }
      if (checkOperator === 'between' || checkOperator === 'not between') {
        return this._not(checkOperator === 'not between').whereBetween(arguments[0], arguments[2]);
      }
    }

    // If the value is still null, check whether they're meaning
    // where value is null
    if (value === null) {

      // Check for .where(key, 'is', null) or .where(key, 'is not', 'null');
      if (checkOperator === 'is' || checkOperator === 'is not') {
        return this._not(checkOperator === 'is not').whereNull(column);
      }
    }

    // Push onto the where statement stack.
    this._statements.push({
      grouping: 'where',
      type: 'whereBasic',
      column: column,
      operator: operator,
      value: value,
      not: this._not(),
      bool: this._bool()
    });
    return this;
  }
851790
def _convert_params(sql, params):
    """"""
    args = [sql]
    if params is not None:
        if hasattr(params, 'keys'):  # test if params is a mapping
            args += [params]
        else:
            args += [list(params)]
    return args
99809
def in_query(expression):
    """"""
    def _in(index, expression=expression):
        """Return store key for documents that satisfy expression."""
        ev = expression() if callable(expression) else expression
        try:
            iter(ev)
        except TypeError:
            raise AttributeError('$in argument must be an iterable!')
        hashed_ev = [index.get_hash_for(v) for v in ev]
        store_keys = set()

        for value in hashed_ev:
            store_keys |= set(index.get_keys_for(value))

        return list(store_keys)

    return _in
761032
def _annotate_query(query, generate_dict):
    """"""
    annotate_key_list = []
    for field_name, annotate_dict in generate_dict.items():
        for annotate_name, annotate_func in annotate_dict["annotate_dict"].items():
            query = annotate_func(query)
            annotate_key_list.append(annotate_name)
    return query, annotate_key_list
602122
def get_mongo_query_from_arguments(self, reserved_attributes=[]):
        

        query = {}
        for arg in self.request.arguments:
            if arg not in reserved_attributes:
                if len(self.request.arguments.get(arg)) > 1:
                    query["$or"] = []
                    for val in self.request.arguments.get(arg):
                        query["$or"].append({arg: self.get_arg_value_as_type(val)})
                else:
                    query[arg] = self.get_arg_value_as_type(self.request.arguments.get(arg)[0])

        return query
870641
def _make_sql_params(self,kw):
        """"""
        return ['%s=?' %k for k in kw.keys() ]
        for k,v in kw.iteritems():
            vals.append('%s=?' %k)
        return vals
1245244
def _build_query(self, table, tree, visitor):
        
        kwargs = {}
        index = None
        if tree.using:
            index_name = kwargs["index"] = tree.using[1]
            index = table.get_index(index_name)
        if tree.where:
            constraints = ConstraintExpression.from_where(tree.where)
            possible_hash = constraints.possible_hash_fields()
            possible_range = constraints.possible_range_fields()
            if index is None:
                # See if we can find an index to query on
                indexes = table.get_matching_indexes(possible_hash, possible_range)
                if not indexes:
                    action = "scan"
                    kwargs["filter"] = constraints.build(visitor)
                    kwargs["expr_values"] = visitor.expression_values
                    kwargs["alias"] = visitor.attribute_names
                elif len(indexes) == 1:
                    index = indexes[0]
                    action = "query"
                    add_query_kwargs(kwargs, visitor, constraints, index)
                else:
                    names = ", ".join([index.name for index in indexes])
                    raise SyntaxError(
                        "No index specified with USING <index>, "
                        "but multiple possibilities for query: "
                        "%s" % names
                    )
            else:
                if index.hash_key in possible_hash:
                    action = "query"
                    add_query_kwargs(kwargs, visitor, constraints, index)
                else:
                    action = "scan"
                    if not index.scannable:
                        raise SyntaxError("Cannot scan local index %r" % index_name)
                    kwargs["filter"] = constraints.build(visitor)
                    kwargs["expr_values"] = visitor.expression_values
                    kwargs["alias"] = visitor.attribute_names
        else:
            action = "scan"
        return [action, kwargs, index]
328774
function selectByIdWhereSql () {
    // get id column
    var idColumn = this.model.columnName('id')
    // every where statement will begin with the alias and column name
    var columnSql = `${this.alias}.${this.quoteName(idColumn)}`
    // sql for where query
    var sql
    // if ids are array build in query
    if (Array.isArray(this.args.where.id)) {
        var i = 0
        // get placeholder for each in value
        var placeholders = _.map(this.args.where.id, id => {
            // get param name
            var paramName = `id${i}`
            // increment param counter
            i++
            // set value for param placeholder
            this.params[paramName] = id
            // create placeholder
            return this.unhexId(`:${paramName}`)
        })
        // return where sql
        sql = `WHERE ${columnSql} IN(${placeholders.join(', ')})`
    }
    // otherwise build equals query
    else {
        // set value for param placeholder
        this.params.id = this.args.where.id
        // get place holder
        var placeholder = this.unhexId(':id')
        // return where sql
        sql = `WHERE ${columnSql} = ${placeholder}`
    }
    // and deleted check if d column exists and set in args
    if (defined(this.model.columns.d) && typeof this.args.where.isDeleted === 'boolean') {
        sql += ` AND ${this.alias}.d = ${this.args.where.isDeleted ? 1 : 0}`
    }

    return sql
}
432323
function runQuery(client, queryString, args, callback) {
  if (activeBackend === 'mysql') {
    queryString = queryString.replace(/\$\d+/, '?');
  }

  client.query(queryString, args, function (err, result) {
    if (err) {
      callback(err, null);
      return;
    }
    if (activeBackend === 'mysql') {
      callback(err, result);
    }
    else if (activeBackend === 'pgsql') {
      var rows = [];
      if (result.rows) {
        rows = result.rows;
      }
      callback(err, rows);
    }
  });
}
759812
def _query_gen(self):
        """"""
        return urlencode(self.__query__, safe=self.safe, querydelimiter=self.__querydelimiter__)
939839
def _slice_where_conditions(self, wheres, offset, length):
        
        where_group = self.get_query().for_nested_where()
        where_group.wheres = wheres[offset : (offset + length)]

        return {"type": "nested", "query": where_group, "boolean": "and"}
91403
def parse_args():
  """"""
  parser = ArgumentParser(description="ModelBase builder")
  subparsers = parser.add_subparsers()

  sql_parser = subparsers.add_parser(
    "get-query",
    description="Usage: e.g. psql -c \"copy ($(python3 lib/generate_models.py get-query)) to " +
                "stdout with csv header\" DB_NAME postgres")
  sql_parser.set_defaults(func=print_sql_query)

  gen_parser = subparsers.add_parser("generate")
  gen_parser.add_argument("filename", nargs="?", help="Read this file for input, or STDIN if not " \
                                                      "given")
  gen_parser.add_argument("-i", "--indent", default="  ")
  gen_parser.add_argument("-c", "--created-at-col-name", default="created_at")
  gen_parser.add_argument("-u", "--updated-at-col-name", default="updated_at")
  gen_parser.set_defaults(func=generate_models)

  args = parser.parse_args()

  if hasattr(args, "func"):
    return args
  else:
    arg_parser.print_help()
    sys.exit(1)
691898
def query(self, *args, **kwargs):
        
        clone = self._clone()
        queries = []
        from pyes.query import Query

        if args:
            for f in args:
                if isinstance(f, Query):
                    queries.append(f)
                else:
                    raise TypeError('Only Query objects can be passed as argument')

        for field, value in kwargs.items():
            if value == [None]:
                value = ["$$$$"]
            queries.append(self._build_inner_query(field, value))

        clone._queries.extend(queries)
        return clone
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
}