---------------------------------------------------------------------- Helper for the incrementing/decrementing queries.
971667
function _counter(column, amount, symbol) {
    var amt = parseInt(amount, 10);
    if (isNaN(amt)) {
      amt = 1;
    }
    this._method = 'counter';
    this._single.counter = {
      column: column,
      amount: amt,
      symbol: symbol || '+'
    };
    return this;
  }
1224420
private static function addQueries() {
        self::$debugbar->addCollector(new MessagesCollector('queries'));
        self::$queries = ORM::get_query_log();
        if (self::$queries) {
            foreach (self::$queries as $query) {
                self::$debugbar['queries']->info($query);
            }
        }
    }
187645
function Mql(query, values){
  var self = this;
  if(dynamicMatch){
    var mql = dynamicMatch.call(window, query);
    this.matches = mql.matches;
    this.media = mql.media;
    // TODO: is there a time it makes sense to remove this listener?
    mql.addListener(update);
  } else {
    this.matches = staticMatch(query, values);
    this.media = query;
  }

  this.addListener = addListener;
  this.removeListener = removeListener;
  this.dispose = dispose;

  function addListener(listener){
    if(mql){
      mql.addListener(listener);
    }
  }

  function removeListener(listener){
    if(mql){
      mql.removeListener(listener);
    }
  }

  // update ourselves!
  function update(evt){
    self.matches = evt.matches;
    self.media = evt.media;
  }

  function dispose(){
    mql.removeListener(update);
  }
}
944109
@Override
  public String buildQuery() {
    validateQuery();

    StringBuilder stringBuilder = new StringBuilder();
    if (!Strings.isNullOrEmpty(select)) {
      stringBuilder = stringBuilder.append(SELECT).append(" ").append(select).append(" ");
    }
    if (!Strings.isNullOrEmpty(from)) {
      stringBuilder = stringBuilder.append(FROM).append(" ").append(from).append(" ");
    }
    if (!Strings.isNullOrEmpty(where)) {
      stringBuilder = stringBuilder.append(WHERE).append(" ").append(where).append(" ");
    }
    if (!Strings.isNullOrEmpty(orderBy)) {
      stringBuilder = stringBuilder.append(ORDER_BY).append(" ").append(orderBy).append(" ");
    }
    if (limit != null) {
      stringBuilder = stringBuilder.append(LIMIT).append(" ").append(limit).append(" ");
    }
    if (offset != null) {
      stringBuilder = stringBuilder.append(OFFSET).append(" ").append(offset).append(" ");
    }
    return stringBuilder.toString().trim();
  }
978515
@Override
  public void next() {
    if (!hasNext()) {
      throw new IllegalDataException("No more data");
    }
    for (final ITimeSyncedIterator sub : queries.values()) {
      sub.next(timestamp);
    }
    timestamp = nextTimestamp();
  }
1138693
function next ()
  {
    ++$this->idx;
    if ($this->idx == count($this->data))
    {
      $this->offset += $this->limit;
      $this->idx = 0;
      $sql = "select * from $this->tableName limit $this->limit offset $this->offset";
      if ($this->asColumn)
        $this->data = $this->mysql->queryColumn($sql);
      else
        $this->data = $this->mysql->queryData($sql, null, $this->resultType);
      assert(count($this->data) <= $this->limit);
    }      
  }
1238044
final public void selectQuery() throws ParseException {
    select();
    from();
    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
    case WHERE:
      where();
      break;
    default:
      jj_la1[0] = jj_gen;
      ;
    }
    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
    case ORDER_BY:
      sort();
      break;
    default:
      jj_la1[1] = jj_gen;
      ;
    }
    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
    case LIMIT:
      limit();
      break;
    default:
      jj_la1[2] = jj_gen;
      ;
    }
    jj_consume_token(0);
  }
665959
function(query) {
    var qparts = getQueryParts(goog.string.trim(query));

    // if it's trivial, avoid iteration and zipping costs
    if (qparts.length == 1) {
      // We optimize this case here to prevent dispatch further down the
      // chain, potentially slowing things down. We could more elegantly
      // handle this in filterDown(), but it's slower for simple things
      // that need to be fast (e.g., '#someId').
      var tef = getElementsFunc(qparts[0]);
      return function(root) {
        var r = tef(root, []);
        if (r) { r.nozip = true; }
        return r;
      }
    }

    // otherwise, break it up and return a runner that iterates over the parts
    // recursively
    return function(root) {
      return filterDown(root, qparts);
    }
  }
509489
function(start, end, query) {
				//console.log("deep.store.Collection.range : ", start, end, query);
				var res = null;
				var total = 0;
				query = query || "";
				return deep.when(this.get(query))
					.done(function(res) {
						total = res.length;
						if (typeof start === 'string')
							start = parseInt(start);
						if (typeof end === 'string')
							end = parseInt(end);
						start = Math.min(start, total);
						res = res.slice(start, end + 1);
						end = start + res.length - 1;
						query += "&limit(" + (res.length) + "," + start + ")";
						return ranger.createRangeObject(start, end, total, res.length, deep.utils.copy(res), query);
					});
			}
1307098
function BasicQuery(query) {
	assign(this, query);
	if (!this.filter) {
		this.filter = set.UNIVERSAL;
	}
	if (!this.page) {
		this.page = new RecordRange();
	}
	if (!this.sort) {
		this.sort = "id";
	}
	if (typeof this.sort === "string") {
		this.sort = new DefaultSort(this.sort);
	}
}
1352706
def _restore_auto_increment(self, table):
        """"""
        query, seq_table, seq_column, seq_name = self._get_auto_increment_info(table)
        if query:
            queries = [query, "select nextval('{}')".format(seq_name)]
            return self._run_queries(queries)
1320466
@Override
    public Cursor onQuery(T helper, SQLiteDatabase db, MatcherPattern target, QueryParameters parameter) {
        Cursor result = null;

        SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
        builder.setTables(target.getTableInfo().getName());
        builder.setProjectionMap(target.getTableInfo().getProjectionMap());

        // where
        switch (target.getMimeTypeVnd().getSubType()) {

            case ITEM:
                // Add item selection criteria (using StringBuilder via appendWhere)
                // URI parameter type not set at this level of the class hierarchy, but it is
                // assumed to be numeric so value not escaped.
                builder.appendWhere(target.getTableInfo().getIdColumnInfo().getColumnName());
                builder.appendWhere("=");
                builder.appendWhere(parameter.getUri().getPathSegments().get(1));
                break;

            case DIRECTORY:
            default:
                break;
        }

        // orderBy
        String orderBy = getSortOrderStringForQuery(target, parameter);

        result = builder.query(db, parameter.getProjection(), parameter.getSelection(), parameter.getSelectionArgs(),
            null, null, orderBy);
        return result;
    }
266927
def select(self, fields=['rowid', '*'], offset=None, limit=None):
        ''' 
        '''
        # base SQL
        SQL = 'SELECT %s FROM %s' % (','.join(fields), self._table)
        
        # selectors
        if self._selectors:
            SQL = ' '.join([SQL, 'WHERE', self._selectors]).strip()
        
        # modifiers
        if self._modifiers:
            SQL = ' '.join([SQL, self._modifiers])

        # limit
        if limit is not None and isinstance(limit, int):
            SQL = ' '.join((SQL, 'LIMIT %s' % limit))

        # offset
        if (limit is not None) and (offset is not None) and isinstance(offset, int):
            SQL = ' '.join((SQL, 'OFFSET %s' % offset))

        return ''.join((SQL, ';'))
1034251
function(query) {
	//	console.log(query);
	// Loop over all sources
	// Todo: make this loop smaller and more graspable
	for (var k = 0, klen = query.sources.length; k < klen; k++) {
		var source = query.sources[k];
		delete source.ix;
		// If there is indexation rule
		//console.log('preIndex', source);
		//console.log(source);
		if (k > 0 && source.optimization == 'ix' && source.onleftfn && source.onrightfn) {
			// If there is no table.indices - create it
			if (source.databaseid && alasql.databases[source.databaseid].tables[source.tableid]) {
				if (!alasql.databases[source.databaseid].tables[source.tableid].indices)
					query.database.tables[source.tableid].indices = {};
				// Check if index already exists
				var ixx =
					alasql.databases[source.databaseid].tables[source.tableid].indices[
						hash(source.onrightfns + '`' + source.srcwherefns)
					];
				if (!alasql.databases[source.databaseid].tables[source.tableid].dirty && ixx) {
					source.ix = ixx;
				}
			}

			if (!source.ix) {
				source.ix = {};
				// Walking over source data
				var scope = {};
				var i = 0;
				var ilen = source.data.length;
				var dataw;
				//				while(source.getfn i<ilen) {

				while (
					(dataw = source.data[i]) ||
					(source.getfn && (dataw = source.getfn(i))) ||
					i < ilen
				) {
					if (source.getfn && !source.dontcache) source.data[i] = dataw;
					//					scope[tableid] = dataw;

					//				for(var i=0, ilen=source.data.length; i<ilen; i++) {
					// Prepare scope for indexation
					scope[source.alias || source.tableid] = dataw;

					// Check if it apply to where function
					if (source.srcwherefn(scope, query.params, alasql)) {
						// Create index entry for each address
						var addr = source.onrightfn(scope, query.params, alasql);
						var group = source.ix[addr];
						if (!group) {
							group = source.ix[addr] = [];
						}
						group.push(dataw);
					}
					i++;
				}

				if (
					source.databaseid &&
					alasql.databases[source.databaseid].tables[source.tableid]
				) {
					// Save index to original table
					alasql.databases[source.databaseid].tables[source.tableid].indices[
						hash(source.onrightfns + '`' + source.srcwherefns)
					] =
						source.ix;
				}
			}
			//console.log(38,274,source.ix);

			// Optimization for WHERE column = expression
		} else if (source.wxleftfn) {
			if (!alasql.databases[source.databaseid].engineid) {
				// Check if index exists
				ixx =
					alasql.databases[source.databaseid].tables[source.tableid].indices[
						hash(source.wxleftfns + '`')
					];
			}
			if (!alasql.databases[source.databaseid].tables[source.tableid].dirty && ixx) {
				// Use old index if exists
				source.ix = ixx;
				// Reduce data (apply filter)
				source.data = source.ix[source.wxrightfn(null, query.params, alasql)];
			} else {
				// Create new index
				source.ix = {};
				// Prepare scope
				scope = {};
				// Walking on each source line
				i = 0;
				ilen = source.data.length;
				dataw;
				//				while(source.getfn i<ilen) {

				while (
					(dataw = source.data[i]) ||
					(source.getfn && (dataw = source.getfn(i))) ||
					i < ilen
				) {
					if (source.getfn && !source.dontcache) source.data[i] = dataw;
					//					for(var i=0, ilen=source.data.length; i<ilen; i++) {
					scope[source.alias || source.tableid] = source.data[i];
					// Create index entry
					addr = source.wxleftfn(scope, query.params, alasql);
					group = source.ix[addr];
					if (!group) {
						group = source.ix[addr] = [];
					}
					group.push(source.data[i]);
					i++;
				}
				//					query.database.tables[source.tableid].indices[hash(source.wxleftfns+'`'+source.onwherefns)] = source.ix;
				if (!alasql.databases[source.databaseid].engineid) {
					alasql.databases[source.databaseid].tables[source.tableid].indices[
						hash(source.wxleftfns + '`')
					] =
						source.ix;
				}
			}
			// Apply where filter to reduces rows
			if (source.srcwherefns) {
				if (source.data) {
					scope = {};
					source.data = source.data.filter(function(r) {
						scope[source.alias] = r;
						return source.srcwherefn(scope, query.params, alasql);
					});
				} else {
					source.data = [];
				}
			}
			//			}
			// If there is no any optimization than apply srcwhere filter
		} else if (source.srcwherefns && !source.dontcache) {
			if (source.data) {
				var scope = {};
				// TODO!!!!! Data as Function

				source.data = source.data.filter(function(r) {
					scope[source.alias] = r;
					//					console.log(288,source);
					return source.srcwherefn(scope, query.params, alasql);
				});

				scope = {};
				i = 0;
				ilen = source.data.length;
				//var dataw;
				var res = [];
				//				while(source.getfn i<ilen) {

				while (
					(dataw = source.data[i]) ||
					(source.getfn && (dataw = source.getfn(i))) ||
					i < ilen
				) {
					if (source.getfn && !source.dontcache) source.data[i] = dataw;
					scope[source.alias] = dataw;
					if (source.srcwherefn(scope, query.params, alasql)) res.push(dataw);
					i++;
				}
				source.data = res;
			} else {
				source.data = [];
			}
		}
		// Change this to another place (this is a wrong)
		if (source.databaseid && alasql.databases[source.databaseid].tables[source.tableid]) {
			//query.database.tables[source.tableid].dirty = false;
		} else {
			// this is a subquery?
		}
	}
}
658128
function(query) {
    //  summary:
    //    state machine for query tokenization
    //  description:
    //    instead of using a brittle and slow regex-based CSS parser,
    //    dojo.query implements an AST-style query representation. This
    //    representation is only generated once per query. For example,
    //    the same query run multiple times or under different root nodes
    //    does not re-parse the selector expression but instead uses the
    //    cached data structure. The state machine implemented here
    //    terminates on the last " " (space) character and returns an
    //    ordered array of query component structures (or "parts"). Each
    //    part represents an operator or a simple CSS filtering
    //    expression. The structure for parts is documented in the code
    //    below.


    // NOTE:
    //    this code is designed to run fast and compress well. Sacrifices
    //    to readability and maintainability have been made.
    if (specials.indexOf(query.slice(-1)) >= 0) {
      // If we end with a ">", "+", or "~", that means we're implicitly
      // searching all children, so make it explicit.
      query += ' * '
    } else {
      // if you have not provided a terminator, one will be provided for
      // you...
      query += ' ';
    }

    var ts = function(/*Integer*/ s, /*Integer*/ e) {
      // trim and slice.

      // take an index to start a string slice from and an end position
      // and return a trimmed copy of that sub-string
      return goog.string.trim(query.slice(s, e));
    };

    // The overall data graph of the full query, as represented by queryPart
    // objects.
    var queryParts = [];


    // state keeping vars
    var inBrackets = -1,
        inParens = -1,
        inMatchFor = -1,
        inPseudo = -1,
        inClass = -1,
        inId = -1,
        inTag = -1,
        lc = '',
        cc = '',
        pStart;

    // iteration vars
    var x = 0, // index in the query
        ql = query.length,
        currentPart = null, // data structure representing the entire clause
        cp = null; // the current pseudo or attr matcher

    // several temporary variables are assigned to this structure during a
    // potential sub-expression match:
    //    attr:
    //      a string representing the current full attribute match in a
    //      bracket expression
    //    type:
    //      if there's an operator in a bracket expression, this is
    //      used to keep track of it
    //    value:
    //      the internals of parenthetical expression for a pseudo. for
    //      :nth-child(2n+1), value might be '2n+1'

    var endTag = function() {
      // called when the tokenizer hits the end of a particular tag name.
      // Re-sets state variables for tag matching and sets up the matcher
      // to handle the next type of token (tag or operator).
      if (inTag >= 0) {
        var tv = (inTag == x) ? null : ts(inTag, x);
        if (specials.indexOf(tv) < 0) {
          currentPart.tag = tv;
        } else {
          currentPart.oper = tv;
        }
        inTag = -1;
      }
    };

    var endId = function() {
      // Called when the tokenizer might be at the end of an ID portion of a
      // match.
      if (inId >= 0) {
        currentPart.id = ts(inId, x).replace(/\\/g, '');
        inId = -1;
      }
    };

    var endClass = function() {
      // Called when the tokenizer might be at the end of a class name
      // match. CSS allows for multiple classes, so we augment the
      // current item with another class in its list.
      if (inClass >= 0) {
        currentPart.classes.push(ts(inClass + 1, x).replace(/\\/g, ''));
        inClass = -1;
      }
    };

    var endAll = function() {
      // at the end of a simple fragment, so wall off the matches
      endId(); endTag(); endClass();
    };

    var endPart = function() {
      endAll();
      if (inPseudo >= 0) {
        currentPart.pseudos.push({ name: ts(inPseudo + 1, x) });
      }
      // Hint to the selector engine to tell it whether or not it
      // needs to do any iteration. Many simple selectors don't, and
      // we can avoid significant construction-time work by advising
      // the system to skip them.
      currentPart.loops = currentPart.pseudos.length ||
                          currentPart.attrs.length ||
                          currentPart.classes.length;

      // save the full expression as a string
      currentPart.oquery = currentPart.query = ts(pStart, x);


      // otag/tag are hints to suggest to the system whether or not
      // it's an operator or a tag. We save a copy of otag since the
      // tag name is cast to upper-case in regular HTML matches. The
      // system has a global switch to figure out if the current
      // expression needs to be case sensitive or not and it will use
      // otag or tag accordingly
      currentPart.otag = currentPart.tag = (currentPart.oper) ?
                                                     null :
                                                     (currentPart.tag || '*');

      if (currentPart.tag) {
        // if we're in a case-insensitive HTML doc, we likely want
        // the toUpperCase when matching on element.tagName. If we
        // do it here, we can skip the string op per node
        // comparison
        currentPart.tag = currentPart.tag.toUpperCase();
      }

      // add the part to the list
      if (queryParts.length && (queryParts[queryParts.length - 1].oper)) {
        // operators are always infix, so we remove them from the
        // list and attach them to the next match. The evaluator is
        // responsible for sorting out how to handle them.
        currentPart.infixOper = queryParts.pop();
        currentPart.query = currentPart.infixOper.query + ' ' +
            currentPart.query;
      }
      queryParts.push(currentPart);

      currentPart = null;
    }

    // iterate over the query, character by character, building up a
    // list of query part objects
    for (; lc = cc, cc = query.charAt(x), x < ql; x++) {
      //    cc: the current character in the match
      //    lc: the last character (if any)

      // someone is trying to escape something, so don't try to match any
      // fragments. We assume we're inside a literal.
      if (lc == '\\') {
        continue;
      }
      if (!currentPart) { // a part was just ended or none has yet been created
        // NOTE: I hate all this alloc, but it's shorter than writing tons of
        // if's
        pStart = x;
        //  rules describe full CSS sub-expressions, like:
        //    #someId
        //    .className:first-child
        //  but not:
        //    thinger > div.howdy[type=thinger]
        //  the individual components of the previous query would be
        //  split into 3 parts that would be represented a structure
        //  like:
        //    [
        //      {
        //        query: 'thinger',
        //        tag: 'thinger',
        //      },
        //      {
        //        query: 'div.howdy[type=thinger]',
        //        classes: ['howdy'],
        //        infixOper: {
        //          query: '>',
        //          oper: '>',
        //        }
        //      },
        //    ]
        currentPart = {
          query: null, // the full text of the part's rule
          pseudos: [], // CSS supports multiple pseudo-class matches in a single
              // rule
          attrs: [],  // CSS supports multi-attribute match, so we need an array
          classes: [], // class matches may be additive,
              // e.g.: .thinger.blah.howdy
          tag: null,  // only one tag...
          oper: null, // ...or operator per component. Note that these wind up
              // being exclusive.
          id: null,   // the id component of a rule
          getTag: function() {
            return (caseSensitive) ? this.otag : this.tag;
          }
        };

        // if we don't have a part, we assume we're going to start at
        // the beginning of a match, which should be a tag name. This
        // might fault a little later on, but we detect that and this
        // iteration will still be fine.
        inTag = x;
      }

      if (inBrackets >= 0) {
        // look for a the close first
        if (cc == ']') { // if we're in a [...] clause and we end, do assignment
          if (!cp.attr) {
            // no attribute match was previously begun, so we
            // assume this is an attribute existence match in the
            // form of [someAttributeName]
            cp.attr = ts(inBrackets + 1, x);
          } else {
            // we had an attribute already, so we know that we're
            // matching some sort of value, as in [attrName=howdy]
            cp.matchFor = ts((inMatchFor || inBrackets + 1), x);
          }
          var cmf = cp.matchFor;
          if (cmf) {
            // try to strip quotes from the matchFor value. We want
            // [attrName=howdy] to match the same
            //  as [attrName = 'howdy' ]
            if ((cmf.charAt(0) == '"') || (cmf.charAt(0) == "'")) {
              cp.matchFor = cmf.slice(1, -1);
            }
          }
          // end the attribute by adding it to the list of attributes.
          currentPart.attrs.push(cp);
          cp = null; // necessary?
          inBrackets = inMatchFor = -1;
        } else if (cc == '=') {
          // if the last char was an operator prefix, make sure we
          // record it along with the '=' operator.
          var addToCc = ('|~^$*'.indexOf(lc) >= 0) ? lc : '';
          cp.type = addToCc + cc;
          cp.attr = ts(inBrackets + 1, x - addToCc.length);
          inMatchFor = x + 1;
        }
        // now look for other clause parts
      } else if (inParens >= 0) {
        // if we're in a parenthetical expression, we need to figure
        // out if it's attached to a pseudo-selector rule like
        // :nth-child(1)
        if (cc == ')') {
          if (inPseudo >= 0) {
            cp.value = ts(inParens + 1, x);
          }
          inPseudo = inParens = -1;
        }
      } else if (cc == '#') {
        // start of an ID match
        endAll();
        inId = x + 1;
      } else if (cc == '.') {
        // start of a class match
        endAll();
        inClass = x;
      } else if (cc == ':') {
        // start of a pseudo-selector match
        endAll();
        inPseudo = x;
      } else if (cc == '[') {
        // start of an attribute match.
        endAll();
        inBrackets = x;
        // provide a new structure for the attribute match to fill-in
        cp = {
          /*=====
          attr: null, type: null, matchFor: null
          =====*/
        };
      } else if (cc == '(') {
        // we really only care if we've entered a parenthetical
        // expression if we're already inside a pseudo-selector match
        if (inPseudo >= 0) {
          // provide a new structure for the pseudo match to fill-in
          cp = {
            name: ts(inPseudo + 1, x),
            value: null
          }
          currentPart.pseudos.push(cp);
        }
        inParens = x;
      } else if (
        (cc == ' ') &&
        // if it's a space char and the last char is too, consume the
        // current one without doing more work
        (lc != cc)
      ) {
        endPart();
      }
    }
    return queryParts;
  }
1006181
public void updateQuery(QueryControllerQuery query) {
		int position = getElementPosition(query.getID());
		queries.set(position, query);
	}
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
}