Iterate over all of the chains in the database.

    Args:
        cur (:class:`sqlite3.Cursor`):
            An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement.

    Yields:
        list: The chain.
348295
def iter_chain(cur):
    
    select = "SELECT nodes FROM chain"
    for nodes, in cur.execute(select):
        yield json.loads(nodes)
217918
async def execute_fetchall(
        self, sql: str, parameters: Iterable[Any] = None
    ) -> Iterable[sqlite3.Row]:
        """"""
        if parameters is None:
            parameters = []
        return await self._execute(self._execute_fetchall, sql, parameters)
885898
function C(dbCursor) {
        var chain = dbCursor;

        _.each(['sort', 'skip', 'limit', 'projection'], function(fName) {
            this[fName] = function() {
                chain = chain[fName].apply(chain, arguments);
                return this;
            }
        }.bind(this));

        this.exec = function(){
            return convertToPromise(chain, 'exec', [], function(data) {
                if(_.isArray(data)) return dbCallbacks.find(data);
                if(_.isObject(data)) return dbCallbacks.findOne(data);
                return data;
            });
        };
    }
1327758
def each
      (1..ROWS).each do |r|
        (1..COLS).each do |c|
          yield(r, c, self[r, c])
        end
      end
    end
678628
def iterate_subchain(self, chain):
        
        for mw in chain:
            try:
                yield mw
            except Exception as err:
                yield chain.throw(err)
394339
function(chain) {
    // Some attempt is made to prevent the cursor from jumping
    // randomly when an undo or redo happens. It still behaves a bit
    // strange sometimes.
    var cursor = select.cursorPos(this.container, false), self = this;

    // Remove all nodes in the DOM tree between from and to (null for
    // start/end of container).
    function removeRange(from, to) {
      var pos = from ? from.nextSibling : self.container.firstChild;
      while (pos != to) {
        var temp = pos.nextSibling;
        removeElement(pos);
        pos = temp;
      }
    }

    var start = chain[0].from, end = chain[chain.length - 1].to;
    // Clear the space where this change has to be made.
    removeRange(start, end);

    // Insert the content specified by the chain into the DOM tree.
    for (var i = 0; i < chain.length; i++) {
      var line = chain[i];
      // The start and end of the space are already correct, but BR
      // tags inside it have to be put back.
      if (i > 0)
        self.container.insertBefore(line.from, end);

      // Add the text.
      var node = makePartSpan(fixSpaces(line.text), this.container.ownerDocument);
      self.container.insertBefore(node, end);
      // See if the cursor was on this line. Put it back, adjusting
      // for changed line length, if it was.
      if (cursor && cursor.node == line.from) {
        var cursordiff = 0;
        var prev = this.after(line.from);
        if (prev && i == chain.length - 1) {
          // Only adjust if the cursor is after the unchanged part of
          // the line.
          for (var match = 0; match < cursor.offset &&
               line.text.charAt(match) == prev.text.charAt(match); match++);
          if (cursor.offset > match)
            cursordiff = line.text.length - prev.text.length;
        }
        select.setCursorPos(this.container, {node: line.from, offset: Math.max(0, cursor.offset + cursordiff)});
      }
      // Cursor was in removed line, this is last new line.
      else if (cursor && (i == chain.length - 1) && cursor.node && cursor.node.parentNode != this.container) {
        select.setCursorPos(this.container, {node: line.from, offset: line.text.length});
      }
    }

    // Anchor the chain in the DOM tree.
    this.linkChain(chain);
    return start;
  }
1031553
function iterate(iterator, callback) {
	        var self = this;

	        var promise = self.ready().then(function () {
	            var dbInfo = self._dbInfo;
	            var keyPrefix = dbInfo.keyPrefix;
	            var keyPrefixLength = keyPrefix.length;
	            var length = localStorage.length;

	            // We use a dedicated iterator instead of the `i` variable below
	            // so other keys we fetch in localStorage aren't counted in
	            // the `iterationNumber` argument passed to the `iterate()`
	            // callback.
	            //
	            // See: github.com/mozilla/localForage/pull/435#discussion_r38061530
	            var iterationNumber = 1;

	            for (var i = 0; i < length; i++) {
	                var key = localStorage.key(i);
	                if (key.indexOf(keyPrefix) !== 0) {
	                    continue;
	                }
	                var value = localStorage.getItem(key);

	                // If a result was found, parse it from the serialized
	                // string into a JS object. If result isn't truthy, the
	                // key is likely undefined and we'll pass it straight
	                // to the iterator.
	                if (value) {
	                    value = dbInfo.serializer.deserialize(value);
	                }

	                value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);

	                if (value !== void 0) {
	                    return value;
	                }
	            }
	        });

	        executeCallback(promise, callback);
	        return promise;
	    }
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
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'])
803797
def _get_cursor(self):
        '''
        
        '''
        _options = self._get_options()
        conn = sqlcipher.connect(_options.get('database'),
                                 timeout=float(_options.get('timeout')))
        conn.execute('pragma key="{0}"'.format(_options.get('pass')))
        cursor = conn.cursor()
        try:
            yield cursor
        except sqlcipher.Error as err:
            log.exception('Error in ext_pillar SQLCipher: %s', err.args)
        finally:
            conn.close()
16931
def db_chainstate_get_block(cls, cur, block_height):
        
        query = 'SELECT * FROM chainstate WHERE block_id = ? ORDER BY vtxindex;'
        args = (block_height,)

        rows = cls.db_query_execute(cur, query, args, verbose=False)
        ret = []

        for r in rows:
            rowdata = {
                'txid': str(r['txid']),
                'block_id': r['block_id'],
                'txindex': r['txindex'],
                'vtxindex': r['vtxindex'],
                'opcode': str(r['opcode']),
                'data_hex': str(r['data_hex']),
                'senders': simplejson.loads(r['senders']),
                'tx_hex': str(r['tx_hex']),
                'tx_merkle_path': str(r['tx_merkle_path']),
                'fee': r['fee']
            }

            ret.append(rowdata)

        return ret
50241
def _iter(self):
        
        keys = self.keys()
        while keys:
            key = keys[0]
            yield key
            keys = keys[1:]
916930
def iterintervals(self, n=2):
        
        # tee the original iterator into n identical iterators
        streams = tee(iter(self), n)

        # advance the "cursor" on each iterator by an increasing
        # offset, e.g. if n=3:
        #
        #                   [a, b, c, d, e, f, ..., w, x, y, z]
        #  first cursor -->  *
        # second cursor -->     *
        #  third cursor -->        *
        for stream_index, stream in enumerate(streams):
            for i in range(stream_index):
                next(stream)

        # now, zip the offset streams back together to yield tuples,
        # in the n=3 example it would yield:
        # (a, b, c), (b, c, d), ..., (w, x, y), (x, y, z)
        for intervals in zip(*streams):
            yield intervals
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)
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
1091158
def cursor(self,*args,**kwargs):
        
        d_out("Handle.cursor: Creating cursor..")
        if not self.open:
            raise Exception("Connection isn't open.")

        if 'cursor_factory' not in kwargs or kwargs['cursor_factory'] == None:
            kwargs["cursor_factory"] = Cursor
        callback = kwargs.pop('callback', None)
        cur = self.conn.cursor(*args,**kwargs)
        if callback:
            d_out('Handle.cursor() setting callback attrib {0}'.format(callback))
            cur.callback = callback
        return cur
1361716
def db_create(cls, impl, working_dir):
        

        global VIRTUALCHAIN_DB_SCRIPT
       
        log.debug("Setup chain state in {}".format(working_dir))

        path = config.get_snapshots_filename(impl, working_dir)
        if os.path.exists( path ):
            raise Exception("Database {} already exists")

        lines = [l + ";" for l in VIRTUALCHAIN_DB_SCRIPT.split(";")]
        con = sqlite3.connect(path, isolation_level=None, timeout=2**30)

        for line in lines:
            con.execute(line)

        con.row_factory = StateEngine.db_row_factory
        return con