Execute queries against SQLCipher, merge and return as a dict
15344
def ext_pillar(minion_id,
               pillar,
               *args,
               **kwargs):
    '''
    
    '''
    return SQLCipherExtPillar().fetch(minion_id, pillar, *args, **kwargs)
1157474
def fetch_all(self, sql, *args, **kwargs):
        
        with self.locked() as conn:
            return conn.query(sql, *args, **kwargs).fetch_all()
854801
def query(self, sql, param=None, stream=False, row_tuples=False):
        
        if not self.cursor:  # ALLOW NON-TRANSACTIONAL READS
            Log.error("must perform all queries inside a transaction")
        self._execute_backlog()

        try:
            if param:
                sql = expand_template(sql, quote_param(param))
            sql = self.preamble + outdent(sql)
            self.debug and Log.note("Execute SQL:\n{{sql}}", sql=indent(sql))

            self.cursor.execute(sql)
            if row_tuples:
                if stream:
                    result = self.cursor
                else:
                    result = wrap(list(self.cursor))
            else:
                columns = [utf8_to_unicode(d[0]) for d in coalesce(self.cursor.description, [])]
                if stream:
                    result = (wrap({c: utf8_to_unicode(v) for c, v in zip(columns, row)}) for row in self.cursor)
                else:
                    result = wrap([{c: utf8_to_unicode(v) for c, v in zip(columns, row)} for row in self.cursor])

            return result
        except Exception as e:
            e = Except.wrap(e)
            if "InterfaceError" in e:
                Log.error("Did you close the db connection?", e)
            Log.error("Problem executing SQL:\n{{sql|indent}}", sql=sql, cause=e, stack_depth=1)
421112
def query(query, args_or_dbname, params = {})
      query = transmute_data(query)
      args = args_or_dbname.is_a?(String) ? [db_alias(args_or_dbname)] : args_or_dbname
      args = transmute_data(args)
      get root_url("api/query"), params.merge(:q => query, :args => args)
    end
1062419
def query_by_sql(self, sql):
        
        # https://www.elastic.co/guide/en/elasticsearch/reference/current/sql-rest.html
        # https://www.elastic.co/guide/en/elasticsearch/reference/current/sql-syntax-select.html
        body = {'query': sql}

        resp = self._es.transport.perform_request('POST', '/_xpack/sql', params={'format': 'json'}, body=body)

        # build key-value dictionary for each row to match results returned by query_by_string
        columns = [column['name'] for column in resp.get('columns')]

        return [dict(zip(columns, row)) for row in resp.get('rows')]
1065391
def union(self, query, all=False):
        
        self.unions.append({
            'query': query,
            'all': all
        })

        return self.merge_bindings(query)
1254569
def sql(self, sql, *params):
        """"""
        self.ops.append(self.migrator.sql(sql, *params))
1301434
function exec(query, config, done) {
  if(!query || (typeof query != 'string')){
    throw new Error('Node-SQL: query was not in the correct format.');
    return;
  }
  if(!config || (typeof config != 'object')){
    throw new Error('Node-SQL: config was not in the correct format.');
    return;
  }
  if(!done || (typeof done != 'function')){
    done = function(a, b){};
  }
  var connection = new Connection(config);
  connection.on('connect', function(err) {
    if(err){
      done(err, null);
      return;
    }
    var request = new Request(query, function(_err) {
      if (_err) {
        done(_err, null);
        return;
      }
      connection.close();
    });
    var result = [];
    request.on('row', function(columns) {
      var row = {};
      columns.forEach(function(column) {
        row[column.metadata.colName] = column.value;
      });
      result.push(row);
    });
    request.on('doneProc', function(rowCount, more, returnStatus) {
      if(returnStatus == 0) done(null, result);
    });
    connection.execSql(request);
  });
}
1060113
def execute(self, sql, parameters = None, cursorClass = DictCursor, quiet = False, locked = False, do_commit = True):
		""""""
		i = 0
		errcode = 0
		caughte = None
		cursor = None
		if sql.find(";") != -1 or sql.find("\\G") != -1:
			# Catches some injections
			raise Exception("The SQL command '%s' contains a semi-colon or \\G. This is a potential SQL injection." % sql)
		while i < self.numTries:
			i += 1
			try:
				assert(not(self.connection) or not(self.connection.open))
				self._get_connection(cursorClass)
				cursor = self.connection.cursor()
				if locked:
					cursor.execute(self.lockstring)
					self.locked = True
				if parameters:
					errcode = cursor.execute(sql, parameters)
				else:
					errcode = cursor.execute(sql)
				self.lastrowid = int(cursor.lastrowid)
				if do_commit and self.isInnoDB:
					self.connection.commit()
				results = cursor.fetchall()
				if locked:
					cursor.execute(self.unlockstring)
					self.locked = False
				cursor.close()
				self._close_connection()
				return results
			except MySQLdb.OperationalError, e:
				if cursor:
					if self.locked:
						cursor.execute(self.unlockstring)
						self.locked = False
					cursor.close()
				self._close_connection()
				caughte = str(e)
				errcode = e[0]
				continue
			except Exception, e:
				if cursor:
					if self.locked:
						cursor.execute(self.unlockstring)
						self.locked = False
					cursor.close()
				self._close_connection()
				caughte = str(e)
				traceback.print_exc()
				break
			sleep(0.2)
		
		if not quiet:
			sys.stderr.write("\nSQL execution error in query %s at %s:" % (sql, datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
			sys.stderr.write("\nErrorcode/Error: %d - '%s'.\n" % (errcode, str(caughte)))
			sys.stderr.flush()
		raise MySQLdb.OperationalError(caughte)
681337
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'entities' in _dict:
            args['entities'] = [
                QueryEntitiesEntity._from_dict(x)
                for x in (_dict.get('entities'))
            ]
        return cls(**args)
147821
def executeSQL(self, sql, args=()):
        
        sql = self._execSQL(sql, args)
        result = self.cursor.lastRowID()
        if self.executedThisTransaction is not None:
            self.executedThisTransaction.append((result, sql, args))
        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)
972407
def execute_sql(self, *args, **kwargs):
        
        assert self._allow_sync, (
            "Error, sync query is not allowed! Call the `.set_allow_sync()` "
            "or use the `.allow_sync()` context manager.")
        if self._allow_sync in (logging.ERROR, logging.WARNING):
            logging.log(self._allow_sync,
                        "Error, sync query is not allowed: %s %s" %
                        (str(args), str(kwargs)))
        return super().execute_sql(*args, **kwargs)
94163
def execute_query(self, query, session):
		'''  '''
		self.auto_ensure_indexes(query.type)

		kwargs = dict()
		if query._get_fields():
			if PYMONGO_3: # pragma: nocover
				kwargs['projection'] = query._fields_expression()
			else: # pragma: nocover
				kwargs['fields'] = query._fields_expression()

		collection = self.db[query.type.get_collection_name()]
		
		if query._search:
			index_fields = query._createIndex
			if index_fields:
				# create new index
				if type(index_fields) is list:
					index_list = []
					for field in index_fields:
						index_list.append ((field, pymongo.TEXT))
					collection.create_index(index_list, name='search_index', default_language='english')
				else:
					raise InvalidConfigException()
			cursor = collection.find(query.query, {'__index_score': {'$meta': "textScore"}}, **kwargs)
			cursor.sort([('__index_score', {'$meta': 'textScore'})])
		elif query._rawquery:
			if query._query_type=='aggregate':
				cursor = collection.aggregate(query.query, cursor={}, **kwargs)
			elif query._query_type=='map_reduce':
				cursor = collection.map_reduce( query._mapreduce_mapper, query._mapreduce_reducer, query._mapreduce_key, query=query._mapreduce_query)
		else:
			cursor = collection.find(query.query, **kwargs)

		if query._sort:
			cursor.sort(query._sort)
		elif query.type.config_default_sort:
			cursor.sort(query.type.config_default_sort)
		if query.hints:
			cursor.hint(query.hints)
		if query._get_limit() is not None:
			cursor.limit(query._get_limit())
		if query._get_skip() is not None:
			cursor.skip(query._get_skip())
		return QueryResult(session, cursor, query.type, raw_output=query._raw_output, fields=query._get_fields())
183325
def exec_query(sql, name = 'SQL', binds = [])
      # NOTE: we allow to execute SQL as requested returning a results.
      # e.g. this allows to use SQLServer's EXEC with a result set ...
      sql = to_sql(sql, binds) if sql.respond_to?(:to_sql)

      sql = repair_special_columns(sql)
      if prepared_statements?
        log(sql, name, binds) { @connection.execute_query(sql, binds) }
      else
        log(sql, name) { @connection.execute_query(sql) }
      end
    end
791485
def _executing(self, sql, params=[]):
        
        with self.connection() as connection:
            for row in connection.execute(sql, params):
                yield row
                if not self._db:
                    return
797674
def ExecuteQuery(self, query, args=None):
    """"""

    def Action(connection):
      connection.cursor.execute(query, args)
      rowcount = connection.cursor.rowcount
      results = connection.cursor.fetchall()
      return results, rowcount

    return self._RetryWrapper(Action)