Execute an ASQL file and return the result of the first SELECT statement.

        :param asql:
        :param logger:
        :return:
499647
def query(self, asql, logger=None):
        
        import sqlparse
        from ambry.mprlib.exceptions import BadSQLError
        from ambry.bundle.asql_parser import process_sql
        from ambry.orm.exc import NotFoundError

        if not logger:
            logger = self._library.logger

        rec = process_sql(asql, self._library)

        for drop in reversed(rec.drop):

            if drop:
                connection = self._backend._get_connection()
                cursor = self._backend.query(connection, drop, fetch=False)
                cursor.close()

        for vid in rec.materialize:
            logger.debug('Materialize {}'.format(vid))
            self.materialize(vid, logger=logger)

        for vid in rec.install:
            logger.debug('Install {}'.format(vid))

            self.install(vid, logger=logger)


        for statement in rec.statements:

            statement = statement.strip()

            logger.debug("Process statement: {}".format(statement[:60]))

            if statement.lower().startswith('create'):
                logger.debug('    Create {}'.format(statement))
                connection = self._backend._get_connection()
                cursor = self._backend.query(connection, statement, fetch=False)

                cursor.close()

            elif statement.lower().startswith('select'):
                logger.debug('Run query {}'.format(statement))
                connection = self._backend._get_connection()
                return self._backend.query(connection, statement, fetch=False)

        for table_or_vid, columns in rec.indexes:

            logger.debug('Index {}'.format(table_or_vid))

            try:
                self.index(table_or_vid, columns)
            except NotFoundError as e:
                # Comon when the index table in's a VID, so no partition can be found.

                logger.debug('Failed to index {}; {}'.format(vid, e))
            except Exception as e:
                logger.error('Failed to index {}; {}'.format(vid, e))

        # A fake cursor that can be closed and iterated
        class closable_iterable(object):
            def close(self):
                pass

            def __iter__(self):
                pass

        return closable_iterable()
1068330
def select(self,sql):
    
    if not self.curs:
      raise LIGOLwDBError, "Database connection not initalized"
    if len(self.table) != 0:
      raise LIGOLwDBError, 'attempt to fill non-empty table from database'
    ligolw = ''
    self.table = {}
    sqltypes = {
      -2 : 'ilwd:char_u',
      1 : 'lstring',
      3 : 'real_8',
      4  : 'int_4s',
      5 : 'int_2s',
      7 : 'real_4',
      8 : 'real_8',
      12 : 'lstring',
      93 : 'lstring', 
      }
    try:
      tab = re.compile(r'[Ff][Rr][Oo][Mm]\s+([A-Za-z0-0_]+)([,\s]+|$)').search(sql).group(1)
    except AttributeError:
      raise LIGOLwDBError, 'could not find table name in query ' + str(sql)
    self.table[tab] = {
      'pos' : 0,
      'column' : {},
      'stream' : (), 
      'query' : sql
      }
    try:
      self.curs.execute(sql)
    except DB2.Error, e:
      raise LIGOLwDBError, e[2]
    desc = self.curs.description
    for col,typ,disp,intsz,prec,sca,nul in desc:
      try:
        self.table[tab]['column'][col] = sqltypes[typ]
      except KeyError:
        raise LIGOLwDBError, 'unknown type returned by database ' + str(typ)
      self.table[tab].setdefault('orderedcol',[]).append(col)

    try:
      self.table[tab]['stream'] = self.curs.fetchall()
    except DB2.Error, e:
      raise LIGOLwDBError, e[2]

    return len(self.table[tab]['stream'])
1036746
def as_sql(self, qn, connection):
        
        engine = connection.settings_dict['ENGINE'].rsplit('.', -1)[-1]
        if engine.startswith('postgres'):
            XOR_OPERATOR = '#'
        elif engine.startswith('sqlite'):
            raise NotImplementedError
        else:
            XOR_OPERATOR = '^'

        if self.bit:
            return ("%s.%s | %d" % (qn(self.table_alias), qn(self.column), self.bit.mask),
                    [])
        return ("%s.%s %s %d" % (qn(self.table_alias), qn(self.column), XOR_OPERATOR, self.bit.mask),
                [])
1267393
public void logFirstSelectQueryForCurrentThread() {
		String firstSelectQuery = getSelectQueriesForCurrentThread()
			.stream()
			.findFirst()
			.map(CircularQueueCaptureQueriesListener::formatQueryAsSql)
			.orElse("NONE FOUND");
		ourLog.info("First select Query:\n{}", firstSelectQuery);
	}
158787
def execute(self, conn, logical_file_name, block_name, block_id, transaction=False):
        
        binds = {}
        sql = ''

        if logical_file_name:
            if isinstance(logical_file_name, basestring):
                wheresql = "WHERE F.LOGICAL_FILE_NAME = :logical_file_name"
                binds = {"logical_file_name": logical_file_name}
                sql = "{sql} {wheresql}".format(sql=self.sql, wheresql=wheresql)
            elif isinstance(logical_file_name, list):
                wheresql = "WHERE F.LOGICAL_FILE_NAME in (SELECT TOKEN FROM TOKEN_GENERATOR)"
                lfn_generator, binds = create_token_generator(logical_file_name)
                sql = "{lfn_generator} {sql} {wheresql}".format(lfn_generator=lfn_generator, sql=self.sql,
                                                                wheresql=wheresql)
        elif block_name:
            joins = "JOIN {owner}BLOCKS B on B.BLOCK_ID = F.BLOCK_ID".format(owner=self.owner)
            wheresql = "WHERE B.BLOCK_NAME = :block_name"
            binds = {"block_name": block_name}
            sql = "{sql} {joins} {wheresql}".format(sql=self.sql, joins=joins, wheresql=wheresql)
        elif block_id:
            wheresql = "WHERE F.BLOCK_ID = :block_id"
            binds = {"block_id": block_id}
            sql = "{sql} {wheresql}".format(sql=self.sql, wheresql=wheresql)
        else:
            dbsExceptionHandler('dbsException-invalid-input', "Logical_file_names is required for listChild dao.", self.logger.exception)

        cursors = self.dbi.processData(sql, binds, conn, transaction=transaction, returnCursor=True)
        result = []
        for c in cursors:
            result.extend(self.formatCursor(c, size=100))
        return result
409726
def query_one(self, sql, params=None):
        
        r = self.engine.execute(sql, params)
        return r.fetchone()
72631
def query(self, sql):
        '''
        
        '''
        try:
            self.connect()
            with self.con.cursor() as cursor:
                cursor.execute(sql)
                self.con.commit()
                res = cursor.fetchall()
                return res
        except Exception as e:
            print(e)
            return -1
        finally:
            self.close()
150240
def execute(self, query_string, params=None):
    
    cr = self.connection.cursor()
    logger.info("SQL: %s (%s)", query_string, params)
    self.last_query = (query_string, params)
    t0 = time.time()
    cr.execute(query_string, params or self.core.empty_params)
    ms = (time.time() - t0) * 1000
    logger.info("RUNTIME: %.2f ms", ms)
    self._update_cursor_stats(cr)
    return cr
1249775
def execute_sql(self, sql, commit=False):
        """"""
        logger.info("Running sqlite query: \"%s\"", sql)
        self.connection.execute(sql)
        if commit:
            self.connection.commit()
1249456
def execute(self, conn, transaction=False):
        
        sql = self.sql
        binds = {}
        
	cursors = self.dbi.processData(sql, binds, conn, transaction, returnCursor=True)
        result = []
        for c in cursors:
            result.extend(self.formatCursor(c, size=100))
        return result
1336868
def execute(self, conn, app="", release_version="", pset_hash="", output_label="", 
                global_tag='', transaction = False):
        
	sql = self.sql
        binds = {}
	setAnd=False
	if not app == "":
		sql += " A.APP_NAME=:app_name"
        	binds["app_name"]=app
		setAnd=True
	if not release_version == "":
		if setAnd : sql += " AND "
		sql += " R.RELEASE_VERSION=:release_version"
		binds["release_version"]=release_version
		setAnd=True
	if not pset_hash == "":
		if setAnd : sql += " AND "
		sql += " P.PSET_HASH=:pset_hash"
		binds["pset_hash"]=pset_hash
		setAnd=True
	if not output_label == "":
		if setAnd : sql += " AND "
		sql += " O.OUTPUT_MODULE_LABEL=:output_module_label"
		binds["output_module_label"]=output_label
                setAnd=True
        if not global_tag == "":
                if setAnd : sql += " AND "
                sql += " O.GLOBAL_TAG=:global_tag"
                binds["global_tag"]=global_tag
	if app == release_version == pset_hash  == global_tag == "":
            dbsExceptionHandler('dbsException-invalid-input', "%s Either app_name, release_version, pset_hash or global_tag must be provided", self.logger.exception)	

        result = self.dbi.processData(sql, binds, conn, transaction)
        plist = self.formatDict(result)
	if len(plist) < 1: return -1
        return plist[0]["output_mod_config_id"]
370603
def execute(self, fetchcommand, sql, params=None):
		

		cur = self.conn.cursor()
		if params:
			if not type(params).__name__ == 'tuple':
				raise ValueError('the params argument needs to be a tuple')
				return None
			cur.execute(sql, params)
		else:
			cur.execute(sql)

		self.conn.commit()

		if not fetchcommand or fetchcommand == 'none':
			return

		if fetchcommand == 'last' or fetchcommand == 'lastid':
			lastdata = cur.fetchall()
			self.conn.commit()
			return lastdata

		m = insertion_pattern.match(sql)
		"""
		 TODO: This is a BUG - need to also check tail of query for RETURNING
		"""
		if m:
			""" lastid = cursor.fetchone()['lastval'] """
			lastdata = cur.fetchone()
			self.conn.commit()
			return lastdata

		if fetchcommand == 'fetchone' or fetchcommand == 'one':
			return cur.fetchone()
		elif fetchcommand == 'fetchall' or fetchcommand == 'all':
			return cur.fetchall()
		else:
			msg = "expecting <fetchcommand> argument to be either 'fetchone'|'one'|'fetchall|all'"
			raise ValueError(msg)
95485
def _run_select(self):
        
        return self._connection.select(
            self.to_sql(), self.get_bindings(), not self._use_write_connection
        )
1337542
def _sql(self, sql: str, params=()):
        
        statement = SingleSqlStatement(sql)
        return self.statement(statement).execute_for_params(params).cursor
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)
1097966
def _query(self, sql, *args):
      
      if not self._con:
          logger.debug(("Open MBTiles file '%s'") % self.filename)
          self._con = sqlite3.connect(self.filename)
          self._cur = self._con.cursor()
      sql = ' '.join(sql.split())
      logger.debug(("Execute query '%s' %s") % (sql, args))
      try:
          self._cur.execute(sql, *args)
      except (sqlite3.OperationalError, sqlite3.DatabaseError) as e:
          raise InvalidFormatError(("%s while reading %s") % (e, self.filename))
      return self._cur
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