Turn the low-level rows from the result of a standard query join
        into higher-level statements, yielded iteratively. Note this might lead to
        idle transaction errors?
549879
def _process_db_rows_iter(self, cursor):
        '''
        

        '''
        #Be aware of: http://packages.python.org/psycopg2/faq.html#problems-with-transactions-handling
        #The results will come back grouped by the raw relationship IDs, in order
        for relid, relgroup in groupby(cursor, itemgetter(0)):
            curr_rel = None
            attrs = None
            #Each relgroup are the DB rows corresponding to a single relationship,
            #With redundant origin/rel/target but the sequence of attributes
            for row in relgroup:
                (rawid, origin, rel, target, a_name, a_val) = row
                #self._logger.debug('Row: {0}'.format(repr(row)))
                if not curr_rel: curr_rel = (origin, rel, target)
                if a_name:
                    if not attrs:
                        attrs = {}
                        curr_rel = (origin, rel, target, attrs)
                    attrs[a_name] = a_val
            yield curr_rel
        cursor.close()
        self._conn.rollback() #Finish with the transaction
        return
202782
private Iteration<Statement, QueryEvaluationException> toStatementIteration(TupleQueryResult iter, final Resource subj, final URI pred, final Value obj) {
        return new ConvertingIteration<BindingSet, Statement, QueryEvaluationException>(iter) {
            @Override
            protected Statement convert(BindingSet b) throws QueryEvaluationException {
                Resource s = subj==null ? (Resource)b.getValue("s") : subj;
                URI p = pred==null ? (URI)b.getValue("p") : pred;
                Value o = obj==null ? b.getValue("o") : obj;
                URI ctx = (URI)b.getValue("ctx");
                if (ctx.stringValue().equals(DEFAULT_GRAPH_URI)) {
                    ctx = null;
                }
                return getValueFactory().createStatement(s, p, o, ctx);
            }
        };
    }
895491
def _setop(self, query):
        
        if isinstance(query.select, list):
            # RETURN BORING RESULT SET
            selects = FlatList()
            for s in listwrap(query.select):
                if isinstance(s.value, Mapping):
                    for k, v in s.value.items:
                        selects.append(sql_alias(v, quote_column(s.name + "." + k)))
                if isinstance(s.value, list):
                    for i, ss in enumerate(s.value):
                        selects.append(sql_alias(s.value, quote_column(s.name + "," + str(i))))
                else:
                    selects.append(sql_alias(s.value, quote_column(s.name)))

            sql = expand_template("""
                SELECT
                    {{selects}}
                FROM
                    {{table}}
                {{where}}
                {{sort}}
                {{limit}}
            """, {
                "selects": SQL(",\n".join(selects)),
                "table": self._subquery(query["from"])[0],
                "where": self._where2sql(query.where),
                "limit": self._limit2sql(query.limit),
                "sort": self._sort2sql(query.sort)
            })

            def post_process(sql):
                result = self.db.query(sql)
                for s in listwrap(query.select):
                    if isinstance(s.value, Mapping):
                        for r in result:
                            r[s.name] = {}
                            for k, v in s.value:
                                r[s.name][k] = r[s.name + "." + k]
                                r[s.name + "." + k] = None

                    if isinstance(s.value, list):
                        # REWRITE AS TUPLE
                        for r in result:
                            r[s.name] = tuple(r[s.name + "," + str(i)] for i, ss in enumerate(s.value))
                            for i, ss in enumerate(s.value):
                                r[s.name + "," + str(i)] = None

                expand_json(result)
                return result

            return sql, post_process  # RETURN BORING RESULT SET
        else:
            # RETURN LIST OF VALUES
            if query.select.value == ".":
                select = "*"
            else:
                name = query.select.name
                select = sql_alias(query.select.value, quote_column(name))

            sql = expand_template("""
                SELECT
                    {{selects}}
                FROM
                    {{table}}
                {{where}}
                {{sort}}
                {{limit}}
            """, {
                "selects": SQL(select),
                "table": self._subquery(query["from"])[0],
                "where": self._where2sql(query.where),
                "limit": self._limit2sql(query.limit),
                "sort": self._sort2sql(query.sort)
            })

            if query.select.value == ".":
                def post(sql):
                    result = self.db.query(sql)
                    expand_json(result)
                    return result

                return sql, post
            else:
                return sql, lambda sql: [r[name] for r in self.db.query(sql)]
1012595
def execute_sql(self, statement):
        
        path = '/archive/{}/sql'.format(self._instance)
        req = archive_pb2.ExecuteSqlRequest()
        req.statement = statement

        response = self._client.post_proto(path=path,
                                           data=req.SerializeToString())
        message = archive_pb2.ExecuteSqlResponse()
        message.ParseFromString(response.content)
        if message.HasField('result'):
            return message.result
        return None
988046
def _process_db_rows_iter(self, cursor):
        '''
        

        '''
        #Be aware of: http://packages.python.org/psycopg2/faq.html#problems-with-transactions-handling
        #The results will come back grouped by the raw relationship IDs, in order
        for relid, relgroup in groupby(cursor, itemgetter(0)):
            rel = None
            attrs = None
            #Each relgroup are the DB rows corresponding to a single relationship,
            #With redundant subject/predicate/object but the sequence of attributes
            for row in relgroup:
                (rawid, subj, pred, obj, a_name, a_val) = row
                #self._logger.debug('Row: {0}'.format(repr(row)))
                if not rel: rel = (subj, pred, obj)
                if a_name:
                    if not attrs:
                        attrs = {}
                        rel = (subj, pred, obj, attrs)
                    attrs[a_name] = a_val
            yield rel
        cursor.close()
        self._conn.rollback() #Finish with the transaction
        return
378397
def _split_queries(cls, sql):
        ""

        sql_s = dbt.compat.to_string(sql)
        sql_buf = StringIO(sql_s)
        split_query = snowflake.connector.util_text.split_statements(sql_buf)
        return [part[0] for part in split_query]
233694
def iterateRecords( dbid, fieldNames, query = nil, qid = nil, qname = nil, clist = nil, slist = nil, fmt = "structured", options = nil )
      if block_given?   
         queryResults = getAllValuesForFields(dbid,fieldNames,query,qid,qname,clist,slist,fmt,options)
         if queryResults
            numRecords = 0
            numRecords = queryResults[fieldNames[0]].length if queryResults[fieldNames[0]]
            (0..(numRecords-1)).each{|recNum|
               recordHash = {}
               fieldNames.each{|fieldName|
                  recordHash[fieldName]=queryResults[fieldName][recNum]
               }
               yield recordHash
            }
         end
      else
         raise "'iterateRecords' must be called with a block."
      end
   end
1318369
def runQuery(statDict, query):
  """"""
  parts = [x.strip() for x in OPERATOR.split(query)]
  assert len(parts) in (1, 3)
  queryKey = parts[0]

  result = {}
  for key, value in six.iteritems(statDict):
    if key == queryKey:
      if len(parts) == 3:
        op = OPERATORS[parts[1]]
        try:
          queryValue = type(value)(parts[2]) if value else parts[2]
        except (TypeError, ValueError):
          continue
        if not op(value, queryValue):
          continue
      result[key] = value
    elif isinstance(value, scales.StatContainer) or isinstance(value, dict):
      child = runQuery(value, query)
      if child:
        result[key] = child
  return result
511560
def as_sql(self, with_limits=True, with_col_aliases=False, subquery=False):  # pylint:disable=arguments-differ
        # the argument `subquery` is only for old Django 1.10
        # pylint:disable=too-many-locals,too-many-branches,too-many-statements
        
        # After executing the query, we must get rid of any joins the query
        # setup created. So, take note of alias counts before the query ran.
        # However we do not want to get rid of stuff done in pre_sql_setup(),
        # as the pre_sql_setup will modify query state in a way that forbids
        # another run of it.
        if with_limits and self.query.low_mark == self.query.high_mark:
            return '', ()
        self.subquery = subquery
        refcounts_before = self.query.alias_refcount.copy()
        soql_trans = self.query_topology()
        try:
            extra_select, order_by, group_by = self.pre_sql_setup()
            if with_limits and self.query.low_mark == self.query.high_mark:
                return '', ()
            distinct_fields = self.get_distinct()

            # This must come after 'select', 'ordering', and 'distinct' -- see
            # docstring of get_from_clause() for details.
            from_, f_params = self.get_from_clause()

            where, w_params = self.compile(self.where) if self.where is not None else ("", [])
            having, h_params = self.compile(self.having) if self.having is not None else ("", [])
            params = []
            result = ['SELECT']

            if self.query.distinct:
                result.append(self.connection.ops.distinct_sql(distinct_fields))

            out_cols = []
            col_idx = 1
            for _, (s_sql, s_params), alias in self.select + extra_select:
                if alias:
                    # fixed by removing 'AS'
                    s_sql = '%s %s' % (s_sql, self.connection.ops.quote_name(alias))
                elif with_col_aliases and not isinstance(with_col_aliases, salesforce.backend.base.DatabaseWrapper):
                    s_sql = '%s AS %s' % (s_sql, 'Col%d' % col_idx)
                    col_idx += 1
                if soql_trans and re.match(r'^\w+\.\w+$', s_sql):
                    tab_name, col_name = s_sql.split('.')
                    s_sql = '%s.%s' % (soql_trans[tab_name], col_name)
                params.extend(s_params)
                out_cols.append(s_sql)

            result.append(', '.join(out_cols))

            result.append('FROM')
            result.extend(from_)
            params.extend(f_params)

            if where:
                result.append('WHERE %s' % where)
                params.extend(w_params)

            grouping = []
            for g_sql, g_params in group_by:
                grouping.append(g_sql)
                params.extend(g_params)
            if grouping:
                if distinct_fields:
                    raise NotSupportedError(
                        "annotate() + distinct(fields) is not implemented.")
                if not order_by:
                    order_by = self.connection.ops.force_no_ordering()
                result.append('GROUP BY %s' % ', '.join(grouping))

            if having:
                result.append('HAVING %s' % having)
                params.extend(h_params)

            if order_by:
                ordering = []
                for _, (o_sql, o_params, _) in order_by:
                    ordering.append(o_sql)
                    params.extend(o_params)
                result.append('ORDER BY %s' % ', '.join(ordering))

            if with_limits:
                if self.query.high_mark is not None:
                    result.append('LIMIT %d' % (self.query.high_mark - self.query.low_mark))
                if self.query.low_mark:
                    if self.query.high_mark is None:
                        val = self.connection.ops.no_limit_value()
                        if val:
                            result.append('LIMIT %d' % val)
                    result.append('OFFSET %d' % self.query.low_mark)

            if self.query.select_for_update and self.connection.features.has_select_for_update:
                if self.connection.get_autocommit():
                    raise TransactionManagementError(
                        "select_for_update cannot be used outside of a transaction."
                    )

                # If we've been asked for a NOWAIT query but the backend does
                # not support it, raise a DatabaseError otherwise we could get
                # an unexpected deadlock.
                nowait = self.query.select_for_update_nowait
                if nowait and not self.connection.features.has_select_for_update_nowait:
                    raise DatabaseError('NOWAIT is not supported on this database backend.')
                result.append(self.connection.ops.for_update_sql(nowait=nowait))

            return ' '.join(result), tuple(params)
        finally:
            # Finally do cleanup - get rid of the joins we created above.
            self.query.reset_refcounts(refcounts_before)
220995
def get_from_clause(self):
        
        result = super(MultilingualSQLCompiler, self).get_from_clause()

        if not self.query.include_translation_data:
            return result

        from_ = result[0]
        for join in self.query.extra_join.values():
            from_.append(join)
        return (from_, result[1])
35795
function interpretStatements(statements, resultVars) {
    var /** @type {?} */ stmtsWithReturn = statements.concat([new ReturnStatement(literalArr(resultVars.map(function (resultVar) { return variable(resultVar); })))]);
    var /** @type {?} */ ctx = new _ExecutionContext(null, null, null, new Map());
    var /** @type {?} */ visitor = new StatementInterpreter();
    var /** @type {?} */ result = visitor.visitAllStatements(stmtsWithReturn, ctx);
    return result != null ? result.value : null;
}
1338431
def _expanded_sql(self, sampling=None):
    

    # use lists to preserve the order of subqueries, bigquery will not like listing subqueries
    # out of order if they depend on each other. for example. the following will be rejected:
    # WITH q2 as (SELECT * FROM q1),
    #      q1 as (SELECT * FROM mytable),
    # SELECT * FROM q2
    # so when we're getting the dependencies, use recursion into a list to maintain the order
    udfs = []
    subqueries = []
    expanded_sql = ''

    def _recurse_subqueries(query):
      """Recursively scan subqueries and add their pieces to global scope udfs and subqueries
      """
      if query._subqueries:
        for subquery in query._subqueries:
          _recurse_subqueries(subquery[1])
        subqueries.extend([s for s in query._subqueries if s not in subqueries])
      if query._udfs:
        # query._udfs is a list of (name, UDF) tuples; we just want the UDF.
        udfs.extend([u[1] for u in query._udfs if u[1] not in udfs])

    _recurse_subqueries(self)

    if udfs:
      expanded_sql += '\n'.join([udf._expanded_sql() for udf in udfs])
      expanded_sql += '\n'

    def _indent_query(subquery):
      return '  ' + subquery._sql.replace('\n', '\n  ')

    if subqueries:
      expanded_sql += 'WITH ' + \
                      '\n),\n'.join(['%s AS (\n%s' % (sq[0], _indent_query(sq[1]))
                                     for sq in subqueries])
      expanded_sql += '\n)\n\n'

    expanded_sql += sampling(self._sql) if sampling else self._sql

    return expanded_sql
1174544
def queryMulti(self, queries):
		
		self.lastError = None
		self.affectedRows = 0
		self.rowcount = None
		self.record = None
		cursor = None
		
		try:
			try:
				self._GetConnection()
				#Execute query and store results
				cursor = self.conn.getCursor()
				for query in queries:
					self.conn.query = query
					if query.__class__ == [].__class__:
						self.affectedRows += cursor.execute(query[0], query[1])
					else:
						self.affectedRows += cursor.execute(query)
				self.conn.updateCheckTime()
			except Exception, e:
				self.lastError = e
		finally:
			if cursor is not None:
				cursor.close()
			self._ReturnConnection()
			if self.lastError is not None:
				raise self.lastError
			else:
				return self.affectedRows
11473
function columnsToSQL(columns, tables) {
  if (!columns) return
  const baseTable = Array.isArray(tables) && tables[0]
  let isDual = false
  if (baseTable && baseTable.type === 'dual') isDual = true
  return columns
    .map(column => {
      const { expr } = column
      if (isDual) expr.isDual = isDual
      let str = exprToSQL(expr)
      if (column.as !== null) {
        str = `${str} AS `
        if (column.as.match(/^[a-z_][0-9a-z_]*$/i)) str = `${str}${identifierToSql(column.as)}`

        else str = `${str}\`${column.as}\``
      }

      return str
    })
    .join(', ')
}
822583
def _set_join(self, query=None):
        
        if not query:
            query = self._query

        base_table = self._related.get_table()

        key = '%s.%s' % (base_table, self._related.get_key_name())

        query.join(self._table, key, '=', self.get_other_key())

        return self
248479
def from_resource_deeper(
        cls, resource_id=None, limit_depth=1000000, db_session=None, *args, **kwargs
    ):
        
        tablename = cls.model.__table__.name
        raw_q = """
            WITH RECURSIVE subtree AS (
                    SELECT res.*, 1 AS depth, LPAD(res.ordering::CHARACTER VARYING, 7, '0') AS sorting,
                    res.resource_id::CHARACTER VARYING AS path
                    FROM {tablename} AS res WHERE res.resource_id = :resource_id
                  UNION ALL
                    SELECT res_u.*, depth+1 AS depth,
                    (st.sorting::CHARACTER VARYING || '/' || LPAD(res_u.ordering::CHARACTER VARYING, 7, '0') ) AS sorting,
                    (st.path::CHARACTER VARYING || '/' || res_u.resource_id::CHARACTER VARYING ) AS path
                    FROM {tablename} res_u, subtree st
                    WHERE res_u.parent_id = st.resource_id
            )
            SELECT * FROM subtree WHERE depth<=:depth ORDER BY sorting;
        """.format(
            tablename=tablename
        )  # noqa
        db_session = get_db_session(db_session)
        text_obj = sa.text(raw_q)
        query = db_session.query(cls.model, "depth", "sorting", "path")
        query = query.from_statement(text_obj)
        query = query.params(resource_id=resource_id, depth=limit_depth)
        return query
590655
def _join(self, rows):
    '''
    
    '''
    rval = {}
    for row in rows:
      if row:
        for value,count in row.items():
          rval[ value ] = count + rval.get(value,0)
    return rval