Upgrades the snapshots by adding the blockhash to it and to any pending transactions
973765
def _transform_snapshots_for_blockhash(storage: SQLiteStorage, cache: BlockHashCache) -> None:
    """"""

    snapshots = storage.get_snapshots()
    snapshot_records = [
        TransformSnapshotRecord(
            data=snapshot.data,
            identifier=snapshot.identifier,
            storage=storage,
            cache=cache,
        )
        for snapshot in snapshots
    ]

    pool_generator = Pool(len(snapshots)).imap(_do_transform_snapshot, snapshot_records)

    updated_snapshots_data = []
    for result in pool_generator:
        updated_snapshots_data.append(result)

    storage.update_snapshots(updated_snapshots_data)
485977
function increaseBlockRecursively(provider, count, total, callback) {
  // if the count hits the total, stop the recursion
  if (count >= total) {
    callback(null, true);
  } else {
    // else mine a block
    provider.sendAsync({
      method: 'evm_mine',
    }, (mineError) => {
      if (mineError) {
        callback(`while mining to increase block: ${JSON.stringify(mineError)}`, null);
      } else {
        increaseBlockRecursively(provider, count + 1, total, callback);
      }
    });
  }
}
412842
public function upgradeDatabase()
    {
        $db = $this->connection;
        $db->executeQuery("UPDATE FileImageThumbnailPaths SET thumbnailFormat = ? WHERE thumbnailFormat = '' AND (path LIKE '%.jpg' OR path LIKE '%.jpeg' OR path LIKE '%.pjpg' OR path LIKE '%.pjpeg')", [BitmapFormat::FORMAT_JPEG]);
        $db->executeQuery("UPDATE FileImageThumbnailPaths SET thumbnailFormat = ? WHERE thumbnailFormat = ''", [BitmapFormat::FORMAT_PNG]);
    }
957897
def load_expected_snapshots( snapshots_path ):
    
    # use snapshots?
    snapshots_path = os.path.expanduser(snapshots_path)
    expected_snapshots = {}

    # legacy chainstate?
    try:
        with open(snapshots_path, "r") as f:
            snapshots_json = f.read()
        
        snapshots_data = json.loads(snapshots_json)
        assert 'snapshots' in snapshots_data.keys(), "Not a valid snapshots file"

        # extract snapshots: map int to consensus hash
        for (block_id_str, consensus_hash) in snapshots_data['snapshots'].items():
            expected_snapshots[ int(block_id_str) ] = str(consensus_hash)
        
        log.debug("Loaded expected snapshots from legacy JSON {}; {} entries".format(snapshots_path, len(expected_snapshots)))
        return expected_snapshots
    
    except ValueError as ve:
        log.debug("Snapshots file {} is not JSON".format(snapshots_path))

    except Exception as e:
        if os.environ.get('BLOCKSTACK_DEBUG') == '1':
            log.exception(e)

        log.debug("Failed to read expected snapshots from '{}'".format(snapshots_path))
        return None

    try:
        # sqlite3 db?
        db_con = virtualchain.StateEngine.db_connect(snapshots_path)
        expected_snapshots = virtualchain.StateEngine.get_consensus_hashes(None, None, db_con=db_con, completeness_check=False)
        log.debug("Loaded expected snapshots from chainstate DB {}, {} entries".format(snapshots_path, len(expected_snapshots)))
        return expected_snapshots

    except:
        log.debug("{} does not appear to be a chainstate DB".format(snapshots_path))

    return None
379120
def sync_blockchain( working_dir, bt_opts, last_block, server_state, expected_snapshots={}, **virtualchain_args ):
    
    
    subdomain_index = server_state['subdomains']
    atlas_state = server_state['atlas']
    
    # make this usable even if we haven't explicitly configured virtualchain 
    impl = sys.modules[__name__]
    log.info("Synchronizing database {} up to block {}".format(working_dir, last_block))

    # NOTE: this is the only place where a read-write handle should be created,
    # since this is the only place where the db should be modified.
    new_db = BlockstackDB.borrow_readwrite_instance(working_dir, last_block, expected_snapshots=expected_snapshots)

    # propagate runtime state to virtualchain callbacks
    new_db.subdomain_index = subdomain_index
    new_db.atlas_state = atlas_state
    
    rc = virtualchain.sync_virtualchain(bt_opts, last_block, new_db, expected_snapshots=expected_snapshots, **virtualchain_args)
    
    BlockstackDB.release_readwrite_instance(new_db, last_block)

    return rc
244613
public function refreshBlockOutputCache()
    {
        $db = Loader::db();
        $cID = $this->getBlockCollectionID();
        $bID = $this->getBlockID();
        $c = $this->getBlockCollectionObject();
        $v = [$c->getCollectionID(), $c->getVersionID(), $this->getAreaHandle(), $bID];
        $db->Execute(
            'update CollectionVersionBlocksOutputCache set btCachedBlockOutputExpires = 0 where cID = ? and cvID = ? and arHandle = ? and bID = ?',
            $v
            );
    }
738422
def upgrade_v16_to_v17(storage: SQLiteStorage, old_version: int, current_version: int, **kwargs):
    
    if old_version == SOURCE_VERSION:
        _transform_snapshots(storage)

    return TARGET_VERSION
1283436
def update_blocknumbers(blk)
      loop do
        if blk.number > 0
          @db.put_temporarily block_by_number_key(blk.number), blk.full_hash
        else
          @db.put block_by_number_key(blk.number), blk.full_hash
        end
        @db.commit_refcount_changes blk.number

        break if blk.number == 0

        blk = blk.get_parent()
        break if has_block_by_number(blk.number) && get_block_by_number(blk.number) == blk.full_hash
      end
    end
105230
protected function updateHash()
    {
        $hash = $this->getClassName() . '_' . $this->getObjectId();
        $base64Hash = base64_encode($hash);

        $this->hash = $base64Hash;
    }
1080782
def upgrade():
    """"""
    op.create_table(
        'records_buckets',
        sa.Column(
            'record_id',
            sqlalchemy_utils.types.uuid.UUIDType(),
            nullable=False),
        sa.Column(
            'bucket_id',
            sqlalchemy_utils.types.uuid.UUIDType(),
            nullable=False),
        sa.ForeignKeyConstraint(['bucket_id'], [u'files_bucket.id'], ),
        sa.ForeignKeyConstraint(['record_id'], [u'records_metadata.id'], ),
        sa.PrimaryKeyConstraint('record_id', 'bucket_id')
    )
1000102
private void installSnapshot() {
    state.checkThread();

    // If the last stored snapshot has not yet been installed and its index matches the last applied state
    // machine index, install the snapshot. This requires that the state machine see all indexes sequentially
    // even for entries that have been compacted from the log.
    Snapshot currentSnapshot = state.getSnapshotStore().currentSnapshot();
    if (currentSnapshot != null && currentSnapshot.index() > log.compactor().snapshotIndex() && currentSnapshot.index() == lastApplied && stateMachine instanceof Snapshottable) {

      // Install the snapshot in the state machine thread. Multiple threads can access snapshots, so we
      // synchronize on the snapshot object. In practice, this probably isn't even necessary and could prove
      // to be an expensive operation. Snapshots can be read concurrently with separate SnapshotReaders since
      // memory snapshots are copied to the reader and file snapshots open a separate FileBuffer for each reader.
      LOGGER.info("{} - Installing snapshot {}", state.getCluster().member().address(), currentSnapshot.index());
      executor.executor().execute(() -> {
        synchronized (currentSnapshot) {
          try (SnapshotReader reader = currentSnapshot.reader()) {
            ((Snapshottable) stateMachine).install(reader);
          }
        }
      });

      // Once a snapshot has been applied, snapshot dependent entries can be cleaned from the log.
      log.compactor().snapshotIndex(currentSnapshot.index());
    }
  }
594093
def commit(self):
        """"""
        if (not self._add_cache and
                not self._remove_cache and
                not self._undefined_cache):
            return

        for store_key, hash_values in self._add_cache.items():
            for hash_value in hash_values:
                super(TransactionalIndex, self).add_hashed_value(
                    hash_value, store_key)
        for store_key in self._remove_cache:
            super(TransactionalIndex, self).remove_key(store_key)
        for store_key in self._undefined_cache:
            super(TransactionalIndex, self).add_undefined(store_key)
        if not self.ephemeral:
            self.save_to_store()

        self._init_cache()
        self._in_transaction = True
50344
def begin(self):
        
        if not self._multi_use:
            raise ValueError("Cannot call 'begin' on single-use snapshots")

        if self._transaction_id is not None:
            raise ValueError("Read-only transaction already begun")

        if self._read_request_count > 0:
            raise ValueError("Read-only transaction already pending")

        database = self._session._database
        api = database.spanner_api
        metadata = _metadata_with_prefix(database.name)
        txn_selector = self._make_txn_selector()
        response = api.begin_transaction(
            self._session.name, txn_selector.begin, metadata=metadata
        )
        self._transaction_id = response.id
        return self._transaction_id
570726
def get_snapshots(working_dir, start_block=None, end_block=None):
    

    # make this usable even if we haven't explicitly configured virtualchain 
    impl = sys.modules[__name__]
    return BlockstackDB.get_consensus_hashes(impl, working_dir, start_block_height=start_block, end_block_height=end_block)
1125963
private void upgradeLockIfNeeded()
    {
        // using clone to avoid ConcurentModificationException
        Iterator iter = ((List) mvOrderOfIds.clone()).iterator();
        TransactionImpl tx = getTransaction();
        ObjectEnvelope mod;
        while(iter.hasNext())
        {
            mod = (ObjectEnvelope) mhtObjectEnvelopes.get(iter.next());
            // ignore transient objects
            if(!mod.getModificationState().isTransient())
            {
                /*
                now we check if all modified objects has a write lock. On insert of new
                objects we don't need a write lock.
                */
                if(!mod.needsInsert())
                {
                    if((mod.needsDelete() || mod.needsUpdate()
                            || mod.hasChanged(tx.getBroker())))
                    {
                        needsCommit = true;
                        // mark object dirty
                        mod.setModificationState(mod.getModificationState().markDirty());
                        ClassDescriptor cld = mod.getClassDescriptor();
                        // if the object isn't already locked, we will do it now
                        if(!mod.isWriteLocked())
                        {
                            tx.doSingleLock(cld, mod.getObject(), mod.getIdentity(), Transaction.WRITE);
                        }
                    }
                }
                else
                {
                    needsCommit = true;
                }
            }
        }
    }
445450
def update
      @trackers.each_value {|tracker| tracker.update}
      results = all
      (results.each {|r| yield r}) if block_given?
      results
    end
179830
def upgrade():
    """"""
    op.execute('COMMIT')  # See https://bitbucket.org/zzzeek/alembic/issue/123
    ctx = op.get_context()
    metadata = ctx.opts['target_metadata']
    metadata.naming_convention = NAMING_CONVENTION
    metadata.bind = ctx.connection.engine
    insp = Inspector.from_engine(ctx.connection.engine)

    for table_name in insp.get_table_names():
        if table_name not in metadata.tables:
            continue

        table = metadata.tables[table_name]

        ixs = {}
        uqs = {}
        fks = {}

        for ix in insp.get_indexes(table_name):
            ixs[tuple(ix['column_names'])] = ix
        for uq in insp.get_unique_constraints(table_name):
            uqs[tuple(uq['column_names'])] = uq
        for fk in insp.get_foreign_keys(table_name):
            fks[(tuple(fk['constrained_columns']), fk['referred_table'])] = fk

        with op.batch_alter_table(
                table_name, naming_convention=NAMING_CONVENTION) as batch_op:
            for c in list(table.constraints) + list(table.indexes):
                key = None
                if isinstance(c, sa.schema.ForeignKeyConstraint):
                    key = (tuple(c.column_keys), c.referred_table.name)
                    fk = fks.get(key)
                    if fk and c.name != fk['name']:
                        batch_op.drop_constraint(
                            fk['name'], type_='foreignkey')
                        batch_op.create_foreign_key(
                            op.f(c.name), fk['referred_table'],
                            fk['constrained_columns'],
                            fk['referred_columns'],
                            **fk['options']
                        )
                elif isinstance(c, sa.schema.UniqueConstraint):
                    key = tuple(c.columns.keys())
                    uq = uqs.get(key)
                    if uq and c.name != uq['name']:
                        batch_op.drop_constraint(uq['name'], type_='unique')
                        batch_op.create_unique_constraint(
                            op.f(c.name), uq['column_names'])
                elif isinstance(c, sa.schema.CheckConstraint):
                    util.warn('Update {0.table.name} CHECK {0.name} '
                              'manually'.format(c))
                elif isinstance(c, sa.schema.Index):
                    key = tuple(c.columns.keys())
                    ix = ixs.get(key)
                    if ix and c.name != ix['name']:
                        batch_op.drop_index(ix['name'])
                        batch_op.create_index(
                            op.f(c.name), ix['column_names'],
                            unique=ix['unique'],
                        )
                elif isinstance(c, sa.schema.PrimaryKeyConstraint) or \
                        c.name == '_unnamed_':
                    # NOTE we don't care about primary keys since they have
                    # specific syntax.
                    pass
                else:
                    raise RuntimeError('Missing {0!r}'.format(c))