Execute queries against MySQL, merge and return as a dict
423451
def ext_pillar(minion_id,
               pillar,
               *args,
               **kwargs):
    '''
    
    '''
    return MySQLExtPillar().fetch(minion_id, pillar, *args, **kwargs)
667650
function execute() {
		try {

			// we need to bind in order
			if (empty($this->refactored_stmt)) {
				$index = [];

				$this->refactored_stmt = $this->query;

				# 
				# We need to sort by length to avoid replacing keys that are
				# prefixes of other keys, thereby invaliding the bigger keys
				#

				$keylengths = [];
				foreach (\array_keys($this->params) as $key) {
					$keylengths[$key] = strlen($key);
				}

				\asort($keylengths, SORT_NUMERIC);

				$keys = \array_keys(\array_reverse($keylengths, true));

				foreach ($keys as $key) {
					$position = \strpos($this->query, $key);
					if ($position == false) {
						throw new Panic("Tried to bind parameter $key but it's not present in statement.");
					}

					$this->refactored_stmt = \str_replace($key, '?', $this->refactored_stmt);

					$index[$key] = $position;
				}

				\asort($index, SORT_NUMERIC);

				$this->stmt = \mysqli_prepare($this->dbh, $this->refactored_stmt);

				if ( ! $this->stmt) {
					throw new Panic('Failed to prepare statement');
				}

				$bindings = '';
				$args = [ $this->stmt, null ];
				foreach (array_keys($index) as $key) {
					$bindings .= $this->params[$key][1];
					$args[] = & $this->params[$key][0];
				}

				$args[1] = $bindings;

				if ( ! empty($args[1])) {
					\call_user_func_array('mysqli_stmt_bind_param', $args);
				}
			}
			
			if ( ! \mysqli_stmt_execute($this->stmt)) {
				throw new Panic('Failed to execute statement');
			}

			#
			# to avoid complications with statements not getting closed before
			# new ones are executed we fetch the result set imediatly
			#

			$this->resultset = [];
			$result = \mysqli_stmt_get_result($this->stmt);
			while ($data = mysqli_fetch_assoc($result)) {
				$this->resultset[] = $data;
			}
		}
		catch (\Exception $exception) {
			$message = $exception->getMessage();
			$message .= "\n".$this->formatQuery($this->query);
			throw new Panic($message, 500, $exception);
		}

		return $this;
	}
716239
def batch(self, queries):
        
        with self.connection() as cur:
            for sql, vars in queries:

                if self.debug:
                    print(cur.mogrify(query, vars))
                cur.execute(sql, vars)
1269673
def execute(self, sql, parameters=None, bulk_parameters=None):
        
        if self.connection._closed:
            raise ProgrammingError("Connection closed")

        if self._closed:
            raise ProgrammingError("Cursor closed")

        self._result = self.connection.client.sql(sql, parameters,
                                                  bulk_parameters)
        if "rows" in self._result:
            self.rows = iter(self._result["rows"])
735439
def json2sql(raw_json=None, **definition):  # pylint: disable=too-many-branches
    
    if raw_json and definition:
        raise InputError("Cannot process dict and kwargs input at the same time")

    definition = load_input(raw_json or definition)
    if not isinstance(definition, dict):
        raise UnknownStatementError("Unknown statement parsed: %s (type: %s)"
                                    % (definition, type(definition)))

    try:
        statement = definition.pop('statement', None)
        if statement is None:
            raise NoStatementError("No statement provided")

        statement = statement.lower()

        if statement == 'delete':
            return delete2sql(definition)
        elif statement == 'insert':
            return insert2sql(definition)
        elif statement == 'select':
            return select2sql(definition)
        elif statement == 'update':
            return update2sql(definition)
        elif statement == 'replace':
            return replace2sql(definition)
        else:
            raise UnknownStatementError("Unknown statement provided '%s' in definition %s"
                                        % (statement, definition))
    except Exception as exc:  # pylint: disable=broad-except
        if isinstance(exc, Json2SqlError):
            raise

        raise Json2SqlInternalError("Internal json2sql error: %s" % str(exc)) from exc

    # Just to make Pylint happy :)
    raise Json2SqlInternalError("Unreachable state reached")
8856
def fetch(db=None, sql=None):
    '''
    
    '''
    cur = _connect(db)

    if not cur:
        return False

    cur.execute(sql)
    rows = cur.fetchall()
    return rows
430301
def dmql(query):
        """"""
        if isinstance(query, dict):
            raise ValueError("You supplied a dictionary to the dmql_query parameter, but a string is required."
                                " Did you mean to pass this to the search_filter parameter? ")

        # automatically surround the given query with parentheses if it doesn't have them already
        if len(query) > 0 and query != "*" and query[0] != '(' and query[-1] != ')':
            query = '({})'.format(query)
        return query
1254646
def returner(ret):
    '''
    
    '''
    try:
        with _get_serv(ret, commit=True) as cur:
            sql = '''INSERT INTO salt_returns
                    (fun, jid, return, id, success, full_ret, alter_time)
                    VALUES (%s, %s, %s, %s, %s, %s, to_timestamp(%s))'''

            cur.execute(sql, (ret['fun'], ret['jid'],
                              psycopg2.extras.Json(ret['return']),
                              ret['id'],
                              ret.get('success', False),
                              psycopg2.extras.Json(ret),
                              time.time()))
    except salt.exceptions.SaltMasterError:
        log.critical('Could not store return with pgjsonb returner. PostgreSQL server unavailable.')
987762
def script(self, sql_script, split_algo='sql_split', prep_statements=True, dump_fails=True):
        """"""
        return Execute(sql_script, split_algo, prep_statements, dump_fails, self)
733409
def compile_select(self, query):
        
        sql = super(MySQLQueryGrammar, self).compile_select(query)

        if query.unions:
            sql = "(%s) %s" % (sql, self._compile_unions(query))

        return sql
64281
def execute_sql(self, query):
        
        c = self.con.cursor()
        c.execute(query)
        result = c.fetchall()
        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)
1101490
async def execute(self, sql: str, parameters: Iterable[Any] = None) -> None:
        """"""
        if parameters is None:
            parameters = []
        await self._execute(self._cursor.execute, sql, parameters)
1102500
def __do_query_into_hash(conn, sql_str):
    '''
    

    '''
    mod = sys._getframe().f_code.co_name
    log.debug('%s<--(%s)', mod, sql_str)

    rtn_results = []

    try:
        cursor = conn.cursor()
    except MySQLdb.MySQLError:
        log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
        cursor.close()
        log.debug('%s-->', mod)
        return rtn_results

    try:
        _execute(cursor, sql_str)
    except MySQLdb.MySQLError:
        log.error('%s: try to execute : SQL->%s', mod, sql_str)
        cursor.close()
        log.debug('%s-->', mod)
        return rtn_results

    qrs = cursor.fetchall()

    for row_data in qrs:
        col_cnt = 0
        row = {}
        for col_data in cursor.description:
            col_name = col_data[0]
            row[col_name] = row_data[col_cnt]
            col_cnt += 1

        rtn_results.append(row)

    cursor.close()
    log.debug('%s-->', mod)
    return rtn_results
1096441
def execute(self, sql, *args, **kwargs):
    '''
    
    '''
    try:
      self.cursor.execute(sql, *args)
    except self.sqlite3.InterfaceError, msg:
      raise self.sqlite3.InterfaceError(unicode(msg) + '\nTry converting types or pickling.')
    rows = self.cursor.fetchall()

    self.__commit_if_necessary(kwargs)

    if None == self.cursor.description:
      return None
    else:
      colnames = [d[0].decode('utf-8') for d in self.cursor.description]
      rawdata = [OrderedDict(zip(colnames,row)) for row in rows]
      return rawdata
692270
def execute(self, sql):
        """"""
        cursor = self.connection.cursor()
        try:
            cursor.execute(sql)
        finally:
            cursor.close()
533698
def execute(self, fetchall=False, fetchone=False, use_labels=True):
        
        query = self.get_query(use_labels=use_labels)
        if fetchall:
            return flask.g.db_conn.execute(query).fetchall()
        elif fetchone:
            return flask.g.db_conn.execute(query).fetchone()