/*
Compile Query
763766
public function compileFrom()
    {
        $fromQuery = '';

        foreach ($this->query->getQueryFrom() as $key => $value) {
            if ($key == 0) {
                $fromQuery = "$value";
            } else {
                $fromQuery .= ",$value";
            }
        }

        $this->queryString = "{$this->queryString} FROM $fromQuery";
    }
1058732
function  doQuery(option, inQuery, cb)  {
	var  expr = option.expr,
		 tables = toTableArrays(expr.table),
		 mainTable = tables[0].alias || tables[0].name;
	//console.log('table names are:\n%s', JSON.stringify(tables, null, 4));

	getQueryTableSchema(tables, function(err, tableSchema) {
		if (err)
			return cb(err);

		//console.log('table schema:\n%s', JSON.stringify(tableSchema, null, 4));
		// now we can move on to analyze the query
		// first, we need to collect filter columns...
		var  noColumnSpecified = !(expr.columns || option.raw),
			 whereCol = [];
		if (expr.filters)
			collectFilterColumns(mainTable, expr.filters, whereCol);

		var  colInfo = scanColumns(tableSchema, mainTable, expr.columns, whereCol),
			 isSqlCol = colInfo.nc.length === 0,
			 isSqlFilter = matchSQLFilter(tableSchema, whereCol);
		//console.log('colInfo is:\n%s', JSON.stringify(colInfo, null, 4));
		//console.log('whereCol is:\n%s', JSON.stringify(whereCol, null, 4));

		if (isSqlCol && isSqlFilter)  {
			// all query column are 'inertia', go ahead to do SQL query
			//console.log('doing standard SQL query');
			//option.debug = true;
			soar.execute( option, inQuery, function(err, result) {
				if (noColumnSpecified && result)  {
					// user does not specify what columns to be returned.
					// return all columns and json_columns are extracted/added
					if (tableSchema[mainTable].columns.indexOf('_c_json') >= 0)
						mergeJsonColumns(option.op === 'query'  ?  [result] : result);
				}
				//console.log('query result is:\n%s', JSON.stringify(result, null, 4));
				cb(err, result);
			});
		}
		else  {
			// there are variable columns, we have to reconstruct the query terms to make them SQL only
			var  schema = tableSchema[mainTable],
				 sqlExpr = cloneObj(expr),
				 sqlCmd = {op: 'list', expr: sqlExpr};
				 
			sqlExpr.columns = colInfo.cc;
			//sqlCmd.range = sqlCmd.range || soar.range(1, _queryLimit);

			if (!isSqlFilter)
				sqlExpr.filters = buildSqlFilter(expr.filters, schema.columns);
			//console.log('The adjusted SQL expression is\n%s', JSON.stringify(sqlCmd, null, 2));

			// now we're ready to perform SQL query
			var  listQuery = sqlExpr.filters  ?  inQuery : null;
			
			var  pgIdx = 1,
				 hasMore = true,
				 listSum = [];
			async.whilst(
				function()  {return  hasMore;},
				function(cb)  {
					sqlCmd.range = soar.range(pgIdx++, _queryPageSize);
					//sqlCmd.debug = true;
					soar.execute( sqlCmd, listQuery, function(err, result, count) {
						if (err)  {
							console.log( err.stack );
							return cb(err);
						}
						
						hasMore = result.length === _queryPageSize;
		
						//console.log('result of adjusted SQL:\n%s', JSON.stringify(result, null, 2));
						if (!isSqlCol)
							// add back specified non-sql properties
							mergeSelectedJsonColumns(colInfo, result);
						else
							// user does not specify what columns to be returned.
							// return all columns and json_columns are extracted/added
							mergeJsonColumns(result);
						//console.log('result before final filtering\n%s', JSON.stringify(result, null, 2));
		
						if (!isSqlFilter)  {
							// ok, let's run a JSON-FP program to get the final result
							var  rdQuery = {},
								 reducedF = reduceFilter(mainTable, expr.filters, schema.columns, colInfo.nc, inQuery, rdQuery);
							//console.log('filter is\n%s', JSON.stringify(reducedF, null, 2));
							//console.log('query value is\n%s', JSON.stringify(rdQuery, null, 2));
							result = jsonQ.filter( result, reducedF, rdQuery );
						}
						//console.log('result after final filtering\n%s', JSON.stringify(result, null, 2));
		
						if (colInfo.more.length)  {
							// remove auto-added columns
							var  rmc = colInfo.more;
							result.forEach(function(data) {
								for (var i in rmc)
									delete  data[rmc[i]];
							});
						}
		
						// not using listSum = listSum.concat(result) for potential performance gains
						for (var i in result)
							listSum.push( result[i] );
							
						//console.log('current size: %d, accumulated size: %d, total size: %d, hasMore: %s', result.length, listSum.length, count, hasMore);
						cb();
					});
				},
				function(err)  {
					cb(err, listSum);
				}
			);
		}
	});
}
246233
def compile_delete(self, query):
        
        table = self.wrap_table(query.from__)

        if isinstance(query.wheres, list):
            wheres = self._compile_wheres(query)
        else:
            wheres = ""

        if query.joins:
            joins = " %s" % self._compile_joins(query, query.joins)

            sql = "DELETE %s FROM %s%s %s" % (table, table, joins, wheres)
        else:
            sql = "DELETE FROM %s %s" % (table, wheres)

        sql = sql.strip()

        if query.orders:
            sql += " %s" % self._compile_orders(query, query.orders)

        if query.limit_:
            sql += " %s" % self._compile_limit(query, query.limit_)

        return sql
540915
public <T>
    Query<T> build(
                    final Query<T> query,
                    final QueryParams params
                    )
    {
//        query.disableValidation();

        for (String  key : params.keys()) {
            Handler  handler = _getHandler( key );
            String  field = _getField( key );
            String  value = params.get( key );

            if (CommonQueryParams.Key.ORDER.equalsIgnoreCase( key )) {
                value = _convertOrderingFields( value );
            }

            handler.build( query, field, value );
        }

        return query;
    }
175669
def compile(self):
        
        # Can't tell if this is a hack or not. Revisit later
        self.context.set_query(self)

        # If any subqueries, translate them and add to beginning of query as
        # part of the WITH section
        with_frag = self.format_subqueries()

        # SELECT
        select_frag = self.format_select_set()

        # FROM, JOIN, UNION
        from_frag = self.format_table_set()

        # WHERE
        where_frag = self.format_where()

        # GROUP BY and HAVING
        groupby_frag = self.format_group_by()

        # ORDER BY
        order_frag = self.format_order_by()

        # LIMIT
        limit_frag = self.format_limit()

        # Glue together the query fragments and return
        query = '\n'.join(
            filter(
                None,
                [
                    with_frag,
                    select_frag,
                    from_frag,
                    where_frag,
                    groupby_frag,
                    order_frag,
                    limit_frag,
                ],
            )
        )
        return query
414417
public function compileUpdate(Builder $query, $values)
    {
        // Each one of the columns in the update statements needs to be wrapped in the
        // keyword identifiers, also a place-holder needs to be created for each of
        // the values in the list of bindings so we can make the sets statements.

        foreach ($values as $key => $value)
        {
            // Update bindings are differentiated with an _update postfix to make sure the don't clash
            // with query bindings.
            $columns[] = $this->wrap($key) . ' = ' . $this->parameter(array('column' => $key .'_update'));
        }

        $columns = implode(', ', $columns);

        // Of course, update queries may also be constrained by where clauses so we'll
        // need to compile the where clauses and attach it to the query so only the
        // intended records are updated by the Cypher statements we generate to run.
        $where = $this->compileWheres($query);

        // We always need the MATCH clause in our Cypher which
        // is the responsibility of compiling the From component.
        $match = $this->compileComponents($query, array('from'));
        $match = $match['from'];

        // When updating we need to return the count of the affected nodes
        // so we trick the Columns compiler into returning that for us.
        $return = $this->compileColumns($query, array('count('. $query->modelAsNode() .')'));

        return "$match $where SET $columns $return";
    }
513661
function (query, params, stringifier) {
    if (!query || !query.length || !params) {
      return query;
    }
    if (!stringifier) {
      stringifier = function (a) {return a.toString()};
    }
    var parts = [];
    var isLiteral = false;
    var lastIndex = 0;
    var paramsCounter = 0;
    for (var i = 0; i < query.length; i++) {
      var char = query.charAt(i);
      if (char === "'" && query.charAt(i-1) !== '\\') {
        //opening or closing quotes in a literal value of the query
        isLiteral = !isLiteral;
      }
      if (!isLiteral && char === '?') {
        //is a placeholder
        parts.push(query.substring(lastIndex, i));
        parts.push(stringifier(params[paramsCounter++]));
        lastIndex = i+1;
      }
    }
    parts.push(query.substring(lastIndex));
    return parts.join('');
  }
1036410
public void compile(Session session) {

        if (!database.schemaManager.schemaExists(compileTimeSchema.name)) {
            compileTimeSchema = session.getSchemaHsqlName(null);
        }

        session.setSchema(compileTimeSchema.name);

        ParserDQL p = new ParserDQL(session, new Scanner(statement));

        p.read();

        viewSubQuery    = p.XreadViewSubquery(this);
        queryExpression = viewSubQuery.queryExpression;

        if (getColumnCount() == 0) {
            if (columnNames == null) {
                columnNames =
                    viewSubQuery.queryExpression.getResultColumnNames();
            }

            if (columnNames.length
                    != viewSubQuery.queryExpression.getColumnCount()) {
                throw Error.error(ErrorCode.X_42593, tableName.statementName);
            }

            TableUtil.setColumnsInSchemaTable(
                this, columnNames, queryExpression.getColumnTypes());
        }

        //
        viewSubqueries = p.compileContext.getSubqueries();

        for (int i = 0; i < viewSubqueries.length; i++) {
            if (viewSubqueries[i].parentView == null) {
                viewSubqueries[i].parentView = this;
            }
        }

        //
        viewSubQuery.getTable().view       = this;
        viewSubQuery.getTable().columnList = columnList;
        schemaObjectNames = p.compileContext.getSchemaObjectNames();
        baseTable                          = queryExpression.getBaseTable();

        if (baseTable == null) {
            return;
        }

        switch (check) {

            case SchemaObject.ViewCheckModes.CHECK_NONE :
                break;

            case SchemaObject.ViewCheckModes.CHECK_LOCAL :
                checkExpression = queryExpression.getCheckCondition();
                break;

            case SchemaObject.ViewCheckModes.CHECK_CASCADE :
                break;

            default :
                throw Error.runtimeError(ErrorCode.U_S0500, "View");
        }
    }
120321
function QueryCompiler(client, builder) {
  this.client = client;
  this.method = builder._method || 'select';
  this.options = builder._options || {};
  this.single = builder._single;
  var grouped = this.grouped = {};
  builder._statements.forEach(function (item) {
    if (!item.grouping) {
      return;
    }
    var val = item.grouping;
    if (!(val in grouped)) {
      grouped[val] = [];
    }
    grouped[val].push(item);
  });
  this.formatter = new Formatter(client);
}
455868
@Override
    public MongodbQueryResult build(String query) throws IOException, ParserNotFoundException {
        DBObject result = (DBObject) super.parse(query);
        return new MongodbQueryResult(query, result);
    }
330451
protected function compileWheresToArray($query)
    {
        return collect($query->wheres)->map(function ($where) use ($query) {
            return $where['boolean'].' '.$this->{"where{$where['type']}"}($query, $where);
        })->all();
    }
458560
function runQuery(query, connection, user) {
  const driver = drivers[connection.driver];

  const queryResult = {
    id: uuid.v4(),
    cacheKey: null,
    startTime: new Date(),
    stopTime: null,
    queryRunTime: null,
    fields: [],
    incomplete: false,
    meta: {},
    rows: []
  };

  return driver.runQuery(query, connection).then(results => {
    const { rows, incomplete } = results;
    if (!Array.isArray(rows)) {
      throw new Error(`${connection.driver}.runQuery() must return rows array`);
    }

    queryResult.incomplete = incomplete || false;
    queryResult.rows = rows;
    queryResult.stopTime = new Date();
    queryResult.queryRunTime = queryResult.stopTime - queryResult.startTime;
    queryResult.meta = getMeta(rows);
    queryResult.fields = Object.keys(queryResult.meta);

    if (debug) {
      const connectionName = connection.name;
      const rowCount = rows.length;
      const { startTime, stopTime, queryRunTime } = queryResult;

      console.log(
        JSON.stringify({
          userId: user && user._id,
          userEmail: user && user.email,
          connectionName,
          startTime,
          stopTime,
          queryRunTime,
          rowCount,
          query
        })
      );
    }

    return queryResult;
  });
}
777392
def compile_query(query: dict) -> PyQuery:
    

    def _pair_to_dict(pair):
        if isinstance(pair, dict):
            return pair
        return {pair[0]: pair[1]}

    def _reduce(pair):
        try:
            return {'and': (_pair_to_dict(pair[0]), _pair_to_dict(pair[1]))}
        except (KeyError, IndexError):
            return _pair_to_dict(pair)

    def _get_first_pair(d: dict):
        return list(query.items())[0]

    if len(query) < 2:
        return compile_single_item(*_get_first_pair(query))
    try:
        reduced = reduce(lambda x, y: _reduce((x, y)), query.items())
    except KeyError:
        print(query)
        reduced = query
        raise
    return compile_single_item(*_get_first_pair(reduced))
532382
function $query(ctx, query, values, qrm, config) {

    const special = qrm instanceof SpecialQuery && qrm;
    const $p = config.promise;

    if (special && special.isStream) {
        return npm.stream.call(this, ctx, query, values, config);
    }

    const opt = ctx.options,
        capSQL = opt.capSQL;

    let error, isFunc,
        pgFormatting = opt.pgFormatting,
        params = pgFormatting ? values : undefined;

    if (typeof query === 'function') {
        try {
            query = npm.formatting.resolveFunc(query, values);
        } catch (e) {
            error = e;
            params = values;
            query = npm.util.inspect(query);
        }
    }

    if (!error && !query) {
        error = new TypeError(npm.text.invalidQuery);
    }

    if (!error && typeof query === 'object') {
        if (query instanceof npm.QueryFile) {
            query.prepare();
            if (query.error) {
                error = query.error;
                query = query.file;
            } else {
                query = query[npm.QueryFile.$query];
            }
        } else {
            if ('funcName' in query) {
                isFunc = true;
                query = query.funcName; // query is a function name;
            } else {
                if (query instanceof ExternalQuery) {
                    pgFormatting = true;
                } else {
                    if ('name' in query) {
                        query = new PreparedStatement(query);
                        pgFormatting = true;
                    } else {
                        if ('text' in query) {
                            query = new ParameterizedQuery(query);
                            pgFormatting = true;
                        }
                    }
                }
                if (query instanceof ExternalQuery && !npm.utils.isNull(values)) {
                    query.values = values;
                }
            }
        }
    }

    if (!error) {
        if (!pgFormatting && !npm.utils.isText(query)) {
            error = new TypeError(isFunc ? npm.text.invalidFunction : npm.text.invalidQuery);
        }
        if (query instanceof ExternalQuery) {
            const qp = query.parse();
            if (qp instanceof Error) {
                error = qp;
            } else {
                query = qp;
            }
        }
    }

    if (!error && !special) {
        if (npm.utils.isNull(qrm)) {
            qrm = npm.result.any; // default query result;
        } else {
            if (qrm !== parseInt(qrm) || (qrm & badMask) === badMask || qrm < 1 || qrm > 6) {
                error = new TypeError(npm.text.invalidMask);
            }
        }
    }

    if (!error && (!pgFormatting || isFunc)) {
        try {
            // use 'pg-promise' implementation of values formatting;
            if (isFunc) {
                params = undefined;
                query = npm.formatting.formatFunction(query, values, capSQL);
            } else {
                query = npm.formatting.formatQuery(query, values);
            }
        } catch (e) {
            if (isFunc) {
                const prefix = capSQL ? 'SELECT * FROM' : 'select * from';
                query = prefix + ' ' + query + '(...)';
            } else {
                params = values;
            }
            error = e instanceof Error ? e : new npm.utils.InternalError(e);
        }
    }

    return $p((resolve, reject) => {

        if (notifyReject()) {
            return;
        }
        error = npm.events.query(opt, getContext());
        if (notifyReject()) {
            return;
        }
        try {
            const start = Date.now();
            ctx.db.client.query(query, params, (err, result) => {
                let data, multiResult, lastResult = result;
                if (err) {
                    error = err;
                } else {
                    multiResult = Array.isArray(result);
                    if (multiResult) {
                        lastResult = result[result.length - 1];
                        for (let i = 0; i < result.length; i++) {
                            const r = result[i];
                            error = npm.events.receive(opt, r.rows, r, getContext());
                            if (error) {
                                break;
                            }
                        }
                    } else {
                        result.duration = Date.now() - start;
                        error = npm.events.receive(opt, result.rows, result, getContext());
                    }
                }
                if (!error) {
                    data = lastResult;
                    if (special) {
                        if (special.isMultiResult) {
                            data = multiResult ? result : [result]; // method .multiResult() called
                        }
                    } else {
                        data = data.rows;
                        const len = data.length;
                        if (len) {
                            if (len > 1 && qrm & npm.result.one) {
                                // one row was expected, but returned multiple;
                                error = new QueryResultError(qrec.multiple, lastResult, query, params);
                            } else {
                                if (!(qrm & (npm.result.one | npm.result.many))) {
                                    // no data should have been returned;
                                    error = new QueryResultError(qrec.notEmpty, lastResult, query, params);
                                } else {
                                    if (!(qrm & npm.result.many)) {
                                        data = data[0];
                                    }
                                }
                            }
                        } else {
                            // no data returned;
                            if (qrm & npm.result.none) {
                                if (qrm & npm.result.one) {
                                    data = null;
                                } else {
                                    data = qrm & npm.result.many ? data : null;
                                }
                            } else {
                                error = new QueryResultError(qrec.noData, lastResult, query, params);
                            }
                        }
                    }
                }

                if (!notifyReject()) {
                    resolve(data);
                }
            });
        } catch (e) {
            // this can only happen as a result of an internal failure within node-postgres,
            // like during a sudden loss of communications, which is impossible to reproduce
            // automatically, so removing it from the test coverage:
            // istanbul ignore next
            error = e;
        }

        function getContext() {
            let client;
            if (ctx.db) {
                client = ctx.db.client;
            } else {
                error = new Error(npm.text.looseQuery);
            }
            return {
                client, query, params,
                dc: ctx.dc,
                ctx: ctx.ctx
            };
        }

        notifyReject();

        function notifyReject() {
            const context = getContext();
            if (error) {
                if (error instanceof InternalError) {
                    error = error.error;
                }
                npm.events.error(opt, error, context);
                reject(error);
                return true;
            }
        }
    });
}
724631
public function compile_delete( &$query )
	{
		$build = 'delete from '.$this->escape_table( $query );

		$build .= $this->compile_where( $query );
		$build .= $this->compile_limit( $query );

		// cut the last comma away
		return $build;
	}
1304606
function runQuery(query, connection) {
  const { maxRows } = connection;
  const limit = maxRows < CRATE_LIMIT ? maxRows : CRATE_LIMIT;

  if (connection.port) {
    crate.connect(connection.host, connection.port);
  } else {
    crate.connect(connection.host);
  }

  return crate
    .execute(query)
    .then(res => {
      const results = {
        rows: res.json,
        incomplete: false
      };

      if (results.rows.length >= limit) {
        results.incomplete = true;
        results.rows = results.rows.slice(0, limit);
      }

      return results;
    })
    .catch(err => {
      throw new Error(err.message);
    });
}
1095320
public function compileUpdate(Builder $query, $values)
    {
        [$table, $alias] = $this->parseUpdateTable($query->from);

        // Each one of the columns in the update statements needs to be wrapped in the
        // keyword identifiers, also a place-holder needs to be created for each of
        // the values in the list of bindings so we can make the sets statements.
        $columns = collect($values)->map(function ($value, $key) {
            return $this->wrap($key).' = '.$this->parameter($value);
        })->implode(', ');

        // If the query has any "join" clauses, we will setup the joins on the builder
        // and compile them so we can attach them to this update, as update queries
        // can get join statements to attach to other tables when they're needed.
        $joins = '';

        if (isset($query->joins)) {
            $joins = ' '.$this->compileJoins($query, $query->joins);
        }

        // Of course, update queries may also be constrained by where clauses so we'll
        // need to compile the where clauses and attach it to the query so only the
        // intended records are updated by the SQL statements we generate to run.
        $where = $this->compileWheres($query);

        if (! empty($joins)) {
            return trim("update {$alias} set {$columns} from {$table}{$joins} {$where}");
        }

        return trim("update {$table}{$joins} set $columns $where");
    }