Retrieve data from an sqlite3 db (returns all rows, be careful!)

    CLI Example:

    .. code-block:: bash

        salt '*' sqlite3.fetch /root/test.db 'SELECT * FROM test;'
8856
def fetch(db=None, sql=None):
    '''
    
    '''
    cur = _connect(db)

    if not cur:
        return False

    cur.execute(sql)
    rows = cur.fetchall()
    return rows
635919
def get_all(cls):
        

        api = Client.instance().api

        data = api.database.get()

        database_names = data['result']
        databases = []

        for name in database_names:
            db = Database(name=name, api=api)
            databases.append(db)

        return databases
673658
def fetchall_with_fieldnames(self, sql: str, *args) \
            -> Tuple[Sequence[Sequence[Any]], Sequence[str]]:
        """"""
        self.ensure_db_open()
        cursor = self.db.cursor()
        self.db_exec_with_cursor(cursor, sql, *args)
        try:
            rows = cursor.fetchall()
            fieldnames = [i[0] for i in cursor.description]
            return rows, fieldnames
        except:  # nopep8
            log.exception("fetchall_with_fieldnames: SQL was: " + sql)
            raise
1089004
def fetch(self,
              minion_id,
              pillar,  # pylint: disable=W0613
              *args,
              **kwargs):
        '''
        
        '''
        db_name = self._db_name()
        log.info('Querying %s for information for %s', db_name, minion_id)
        #
        #    log.debug('ext_pillar %s args: %s', db_name, args)
        #    log.debug('ext_pillar %s kwargs: %s', db_name, kwargs)
        #
        # Most of the heavy lifting is in this class for ease of testing.
        qbuffer = self.extract_queries(args, kwargs)
        with self._get_cursor() as cursor:
            for root, details in qbuffer:
                # Run the query
                cursor.execute(details['query'], (minion_id,))

                # Extract the field names the db has returned and process them
                self.process_fields([row[0] for row in cursor.description], details['depth'])
                self.enter_root(root)
                self.as_list = details['as_list']
                if details['with_lists']:
                    self.with_lists = details['with_lists']
                else:
                    self.with_lists = []
                self.ignore_null = details['ignore_null']
                self.process_results(cursor.fetchall())

                log.debug('ext_pillar %s: Return data: %s', db_name, self)
        return self.result
406096
async def fetchrow(self, *args, timeout=None):
        
        data = await self.__bind_execute(args, 1, timeout)
        if not data:
            return None
        return data[0]
199339
def _query(_node_id, value=None, **kw):
    ""
    query_result = []
    try:
        query_result = db.execute(text(fetch_query_string('select_query_from_node.sql')), **kw).fetchall()
    except DatabaseError as err:
        current_app.logger.error("DatabaseError: %s, %s", err, kw)
        return value
    #current_app.logger.debug("queries kw: %s", kw)
    #current_app.logger.debug("queries value: %s", value)
    current_app.logger.debug("queries: %s", query_result)
    if query_result:
        values = []
        for query_name in [x['name'] for x in query_result]:
            if query_name:
                result = []
                try:
                    current_app.logger.debug("query_name: %s", query_name)
                    #current_app.logger.debug("kw: %s", kw)
                    # Query string can be insert or select here
                    #statement = text(fetch_query_string(query_name))
                    #params = [x.key for x in statement.params().get_children()]
                    #skw = {key: kw[key] for key in params}
                    #result = db.execute(statement, **skw)
                    result = db.execute(text(fetch_query_string(query_name)), **kw)
                    current_app.logger.debug("result query: %s", result.keys())
                except (DatabaseError, StatementError) as err:
                    current_app.logger.error("DatabaseError (%s) %s: %s", query_name, kw, err)
                if result and result.returns_rows:
                    result = result.fetchall()
                    #values.append(([[dict(zip(result.keys(), x)) for x in result]], result.keys()))
                    #values.append((result.fetchall(), result.keys()))
                    #current_app.logger.debug("fetchall: %s", values)
                    if len(result) == 0:
                        values.append(([], []))
                    else:
                        current_app.logger.debug("result: %s", result)
                        # There may be more results, but only interested in the
                        # first one. Use the older rowify method for now.
                        # TODO: use case for rowify?
                        values.append(rowify(result, [(x, None) for x in result[0].keys()]))
                        #current_app.logger.debug("fetchone: %s", values)
        value = values
    #current_app.logger.debug("value: %s", value)
    return value
1288919
def gen_fetchall(self, sql: str, *args) -> Iterator[Sequence[Any]]:
        """"""
        self.ensure_db_open()
        cursor = self.db.cursor()
        self.db_exec_with_cursor(cursor, sql, *args)
        try:
            row = cursor.fetchone()
            while row is not None:
                yield row
                row = cursor.fetchone()
        except:  # nopep8
            log.exception("gen_fetchall: SQL was: " + sql)
            raise
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
856327
def fetchall_as_dictlist(self, sql: str, *args) -> List[Dict[str, Any]]:
        """"""
        self.ensure_db_open()
        cursor = self.db.cursor()
        self.db_exec_with_cursor(cursor, sql, *args)
        try:
            rows = cursor.fetchall()
            fieldnames = [i[0] for i in cursor.description]
            dictlist = []
            for r in rows:
                dictlist.append(dict(zip(fieldnames, r)))
            return dictlist
        except:  # nopep8
            log.exception("fetchall_as_dictlist: SQL was: " + sql)
            raise
1355788
def retrieve_data(key = '')
      key = key.to_s unless key.is_a? String
      data_array = @db.execute 'SELECT value FROM data WHERE key = ?', key
      Marshal.load(data_array[0][0]) unless data_array[0].nil?
    end
612871
def query(self, sql: str, args: tuple = None):
        """"""

        with self._cursor() as cursor:
            log.debug('Running SQL: ' + str((sql, args)))
            cursor.execute(sql, args)
            return cursor.fetchall()
513832
def all(self, command, params=None):
        
        dr = self.query(command, params)
        return dr['rows']
932797
def query_fetch_all(self, query, values):
        
        self.cursor.execute(query, values)
        retval = self.cursor.fetchall()
        self.__close_db()
        return retval
84885
def info(self):
        
        t = self.query("SELECT * FROM sqlite_master WHERE type='table'", fmt='table')
        all_tables = t['name'].tolist()
        print('\nDatabase path: {} \nSQL path: {}\n'.format(self.dbpath, self.sqlpath))
        print('Database Inventory')
        print('==================')
        for table in ['sources'] + [t for t in all_tables if
                                    t not in ['sources', 'sqlite_sequence']]:
            x = self.query('select count() from {}'.format(table), fmt='array', fetch='one')
            if x is None: continue
            print('{}: {}'.format(table.upper(), x[0]))
982986
def data_sql(db, sql):
    
    if not db:
        if sql:
            print "ERR: -db option must be set if using -sql"
        return ""

    cmd = """
    library(RPostgreSQL)
    drv = dbDriver('PostgreSQL')
    con = dbConnect(drv, dbname='%(db_name)s')
    q = "%(query)s"
    data = dbGetQuery(con, q)
    """

    return GGData(cmd % {
        'db_name': db,
        'query': sql
    })
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)
393237
def indices(db=None):
    '''
    
    '''
    cur = _connect(db)

    if not cur:
        return False

    cur.execute(
        "SELECT name FROM sqlite_master WHERE type='index' ORDER BY name;"
    )
    rows = cur.fetchall()
    return rows