rebuildDatabase()
543580
function parse( source, errBuf ) {
	commons.resolveRelatives( source );
	return {
		meta: source,
		database: rebuildDatabase( source, errBuf )
	};
}
33741
def init(context, reset, force):
    """"""
    existing_tables = context.obj['store'].engine.table_names()
    if force or reset:
        if existing_tables and not force:
            message = f"Delete existing tables? [{', '.join(existing_tables)}]"
            click.confirm(click.style(message, fg='yellow'), abort=True)
        context.obj['store'].drop_all()
    elif existing_tables:
        click.echo(click.style("Database already exists, use '--reset'", fg='red'))
        context.abort()

    context.obj['store'].setup()
    message = f"Success! New tables: {', '.join(context.obj['store'].engine.table_names())}"
    click.echo(click.style(message, fg='green'))
208591
public function upgradeDatabase()
    {
        $em = $this->getPackageEntityManager();
        if ($em !== null) {
            $this->destroyProxyClasses($em);
            $this->installEntitiesDatabase();
        }
        static::installDB($this->getPackagePath() . '/' . FILENAME_PACKAGE_DB);
    }
1352753
public void updateDatabase(String updateScript, Map<String, String> replacers) {

        StringReader reader = new StringReader(updateScript);
        executeSql(reader, replacers, true);
    }
782470
public function digipolisDatabaseRestore($database = 'default', $opts = [
      'file-system-config|fsconf' => null,
      'database-config|dbconf' => null,
      'compression|c' => 'gzip',
      'source|s' => null,
      'source-type|stype' => 'local',
    ])
    {
        if (is_callable([$this, 'readProperties'])) {
            $this->readProperties();
        }
        $source = $opts['source']
            ? $opts['source']
            : realpath(getcwd()) . '/project.tar.gz';
        if (!$opts['file-system-config']) {
            $opts['file-system-config'] = [
                $opts['source-type'] => [
                    'type' => ucfirst($opts['source-type']),
                    'root' => realpath(dirname($source)),
                ],
            ];
            $source = basename($source);
        }
        return $this->createDbTask('taskDatabaseRestore', $database, $opts)
            ->source($source, $opts['source-type'])
            ->run();
    }
1119147
void reopen() {

        boolean isNew;

        setState(DATABASE_OPENING);

        try {
            databaseProperties = new HsqlDatabaseProperties(this);
            isNew = !DatabaseURL.isFileBasedDatabaseType(databaseType)
                    || !databaseProperties.checkFileExists();

            if (isNew && urlProperties.isPropertyTrue(
                    HsqlDatabaseProperties.url_ifexists)) {
                throw Error.error(ErrorCode.DATABASE_NOT_EXISTS, sName);
            }

            databaseProperties.load();
            databaseProperties.setURLProperties(urlProperties);
            compiledStatementManager.reset();

            nameManager    = new HsqlNameManager(this);
            granteeManager = new GranteeManager(this);
            userManager    = new UserManager(this);
            schemaManager  = new SchemaManager(this);
            persistentStoreCollection =
                new PersistentStoreCollectionDatabase();
            bReferentialIntegrity = true;
            sessionManager        = new SessionManager(this);
            txManager             = new TransactionManager(this);
            collation             = collation.getDefaultInstance();
            dbInfo = DatabaseInformation.newDatabaseInformation(this);

            databaseProperties.setDatabaseVariables();

            String version = databaseProperties.getProperty(
                HsqlDatabaseProperties.db_version);

            if (version.substring(0, 3).equals("1.7")) {
                schemaManager.createPublicSchema();
            }

            if (DatabaseURL.isFileBasedDatabaseType(databaseType)) {
                logger.openLog(this);
            }

            if (version.substring(0, 3).equals("1.7")
                    || version.substring(0, 5).equals("1.8.0")) {
                HsqlName name = schemaManager.findSchemaHsqlName(
                    SqlInvariants.PUBLIC_SCHEMA);

                if (name != null) {
                    schemaManager.setDefaultSchemaHsqlName(name);
                }
            }

            if (isNew) {
                String tableType = urlProperties.getProperty(
                    HsqlDatabaseProperties.hsqldb_default_table_type,
                    "MEMORY");

                if ("CACHED".equalsIgnoreCase(tableType)) {
                    schemaManager.setDefaultTableType(TableBase.CACHED_TABLE);
                }

                HsqlName name = nameManager.newHsqlName("SA", false,
                    SchemaObject.GRANTEE);

                userManager.createUser(name, "");

                Session session = sessionManager.getSysSession();

                granteeManager.grant(name.name,
                                     SqlInvariants.DBA_ADMIN_ROLE_NAME,
                                     granteeManager.getDBARole());
                logger.writeToLog(session,
                                  "CREATE USER SA PASSWORD \'\' ADMIN");
                schemaManager.createPublicSchema();
                logger.writeToLog(session,
                                  "CREATE SCHEMA PUBLIC AUTHORIZATION DBA");
                logger.writeToLog(
                    session, "SET DATABASE DEFAULT INITIAL SCHEMA PUBLIC");

                if (schemaManager.getDefaultTableType()
                        == Table.CACHED_TABLE) {
                    logger.writeToLog(
                        session, "SET DATABASE DEFAULT TABLE TYPE CACHED");
                }

                logger.synchLogForce();
            }

            dbInfo.setWithContent(true);
        } catch (Throwable e) {
            logger.closeLog(Database.CLOSEMODE_IMMEDIATELY);
            logger.releaseLock();
            setState(DATABASE_SHUTDOWN);
            clearStructures();
            DatabaseManager.removeDatabase(this);

            if (!(e instanceof HsqlException)) {
                e = Error.error(ErrorCode.GENERAL_ERROR, e.toString());
            }

            throw (HsqlException) e;
        }

        setState(DATABASE_ONLINE);
    }
469349
def marvcli_restore(file):
    """"""
    data = json.load(file)
    site = create_app().site
    site.restore_database(**data)
1243145
def _rebuild_table(self, new_name, old_name, new_columns, old_columns): 
        
        '''  '''
    
    # verbosity
        print('Rebuilding %s table in %s database' % (self.table_name, self.database_name), end='', flush=True)
        
        from sqlalchemy import Table, MetaData
        metadata_object = MetaData()
    
    # construct old table
        old_table_args = [ old_name, metadata_object ]
        old_column_args = self._construct_columns(old_columns)
        old_table_args.extend(old_column_args)
        old_table = Table(*old_table_args)
    
    # construct new table
        new_table_args = [ new_name, metadata_object ]
        new_column_args = self._construct_columns(new_columns)
        new_table_args.extend(new_column_args)
        new_table = Table(*new_table_args)
    
    # determine differences between tables
        add_columns, remove_columns, rename_columns, retype_columns, resize_columns = self._compare_columns(new_columns, old_columns)
        
    # rename table and recreate table if it doesn't already exist
        table_list = self.engine.table_names()
        if not old_name in table_list:
            self.engine.execute('ALTER TABLE %s RENAME TO %s' % (new_name, old_name))
            new_table.create(self.engine)
     
    # wait for renamed table to be responsive
                
    # migrate records from old to new
        list_statement = old_table.select()
        count = 0
        for record in self.session.execute(list_statement).fetchall():
            create_kwargs = self._construct_inserts(record, new_columns, rename_columns, retype_columns, resize_columns)
            insert_statement = new_table.insert().values(**create_kwargs)
            self.session.execute(insert_statement)
            delete_statement = old_table.delete(old_table.c.id==record.id)
            self.session.execute(delete_statement)
            if not count % 10:
                print('.', end='', flush=True)
            count += 1
        
    # drop old table
        record_list = self.session.execute(list_statement).first()
        if not record_list:
            self.session.close()
            old_table.drop(self.engine)
            self.session = self.engine.connect()
    
    # handle verbosity   
        print(' done.')
        
        return True
822686
def refresh_db(root=None, **kwargs):
    '''
    
    '''
    # Remove rtag file to keep multiple refreshes from happening in pkg states
    salt.utils.pkg.clear_rtag(__opts__)
    cmd = ['pacman', '-Sy']

    if root is not None:
        cmd.extend(('-r', root))

    ret = {}
    call = __salt__['cmd.run_all'](cmd,
                                   output_loglevel='trace',
                                   env={'LANG': 'C'},
                                   python_shell=False)
    if call['retcode'] != 0:
        comment = ''
        if 'stderr' in call:
            comment += ': ' + call['stderr']
        raise CommandExecutionError(
            'Error refreshing package database' + comment
        )
    else:
        out = call['stdout']

    for line in salt.utils.itertools.split(out, '\n'):
        if line.strip().startswith('::'):
            continue
        if not line:
            continue
        key = line.strip().split()[0]
        if 'is up to date' in line:
            ret[key] = False
        elif 'downloading' in line:
            key = line.strip().split()[1].split('.')[0]
            ret[key] = True
    return ret
1366724
protected function useConfiguredDatabase()
    {
        try {
            $this->getDbConnection()->exec('USE `' . $this->getDbName() . '`');
        } catch (Exception $e) {
            throw new Exception("Could not connect to database " . $this->getDbName());
        }
    }
213298
@Override
  public final void restoreDatabase(final String pDbName) throws Exception {
    String encPath = this.backupDir + File.separator + pDbName + ".sqlten";
    File dbBkFile = new File(encPath);
    if (dbBkFile.exists()) {
      this.cryptoHelper.decryptFile(encPath,
        this.databaseDir + File.separator + pDbName + ".sqlite");
    }
  }
1215545
def DeleteDatabase(self, database_link, options=None):
        
        if options is None:
            options = {}

        path = base.GetPathFromLink(database_link)
        database_id = base.GetResourceIdOrFullNameFromLink(database_link)
        return self.DeleteResource(path,
                                   'dbs',
                                   database_id,
                                   None,
                                   options)
1299801
def api_rebuild():
    """"""
    if db is None:
        return '{"error": "single-user mode"}'
    build_job = q.fetch_job('build')
    orphans_job = q.fetch_job('orphans')

    if not build_job and not orphans_job:
        build_job = q.enqueue_call(func=coil.tasks.build,
                                   args=(app.config['REDIS_URL'],
                                         app.config['NIKOLA_ROOT'],
                                         ''),
                                   job_id='build')
        orphans_job = q.enqueue_call(func=coil.tasks.orphans,
                                     args=(app.config['REDIS_URL'],
                                           app.config['NIKOLA_ROOT']),
                                     job_id='orphans', depends_on=build_job)

    d = json.dumps({'build': build_job.meta, 'orphans': orphans_job.meta})

    if ('status' in build_job.meta and
            build_job.meta['status'] is not None and
            'status' in orphans_job.meta and
            orphans_job.meta['status'] is not None):
        rq.cancel_job('build', db)
        rq.cancel_job('orphans', db)
        db.set('site:needs_rebuild', '0')
        site.coil_needs_rebuild = '1'

    return d
167072
public function bootDatabaseRepositoryTrait()
    {
        $this->table      = property_exists($this, 'table') ? $this->table : null;
        $this->keys       = property_exists($this, 'keys') ? $this->keys : null;
        $this->record     = property_exists($this, 'record') ? $this->record : null;
        $this->dataMapper = property_exists($this, 'dataMapper') ? $this->dataMapper : null;
    }
152911
def rebuildtable(cls):
        """"""
        cls._closure_model.objects.all().delete()
        cls._closure_model.objects.bulk_create([cls._closure_model(
            parent_id=x['pk'],
            child_id=x['pk'],
            depth=0
        ) for x in cls.objects.values("pk")])
        for node in cls.objects.all():
            node._closure_createlink()
524240
public void resetData() {
    try (DbSession dbSession = dbClient.openSession(false);
      Connection connection = dbSession.getConnection()) {

      truncateAnalysisTables(connection);
      deleteManualRules(connection);
      truncateInternalProperties(null, null, connection);
      truncateUsers(null, null, connection);
      truncateOrganizations(null, null, connection);
    } catch (SQLException e) {
      throw new IllegalStateException("Fail to reset data", e);
    }

    clearIndex(IssueIndexDefinition.DESCRIPTOR);
    clearIndex(ViewIndexDefinition.DESCRIPTOR);
    clearIndex(ProjectMeasuresIndexDefinition.DESCRIPTOR);
    clearIndex(ComponentIndexDefinition.DESCRIPTOR);
  }
542462
function destroyDatabase(name, cb) {
  if(name === user_dbname)
    throw new Error('We never ever delete that database.')
  nano().db.destroy(name, function(err) {
    if(err && err.status_code !== 404) return cb(err)
    cb(null, err ? false : true)
  })
}