" initialize the database for search
        " param: dbFile
498675
def initDatabase(self, db_file):
        
        try:
            self.__f = io.open(db_file, "rb")
        except IOError, e:
            print "[Error]: ", e
            sys.exit()
1333900
void open() {

        initParams();

        int state = properties.getDBModified();

        switch (state) {

            case HsqlDatabaseProperties.FILES_MODIFIED :
                deleteNewAndOldFiles();
                restoreBackup();
                processScript();
                processDataFile();
                processLog();
                close(false);

                if (cache != null) {
                    cache.open(filesReadOnly);
                }

                reopenAllTextCaches();
                break;

            case HsqlDatabaseProperties.FILES_NEW :
                try {
                    deleteBackup();
                    backupData();
                    renameNewBackup();
                    renameNewScript();
                    deleteLog();
                    properties.setDBModified(
                        HsqlDatabaseProperties.FILES_NOT_MODIFIED);
                } catch (IOException e) {
                    database.logger.appLog.logContext(e, null);
                }

            // continue as non-modified files
            // $FALL-THROUGH$
            case HsqlDatabaseProperties.FILES_NOT_MODIFIED :

                /**
                 * if startup is after a SHUTDOWN SCRIPT and there are CACHED
                 * or TEXT tables, perform a checkpoint so that the .script
                 * file no longer contains CACHED or TEXT table rows.
                 */
                processScript();

                if (isAnyCacheModified()) {
                    properties.setDBModified(
                        HsqlDatabaseProperties.FILES_MODIFIED);
                    close(false);

                    if (cache != null) {
                        cache.open(filesReadOnly);
                    }

                    reopenAllTextCaches();
                }
                break;
        }

        openLog();

        if (!filesReadOnly) {
            properties.setDBModified(HsqlDatabaseProperties.FILES_MODIFIED);
        }
    }
105151
def _initDatabase(self):
        
        queries = []

        if len(self.application.config["viper.mysql"]["init"]["scripts"]) > 0:
            for scriptFilePath in self.application.config["viper.mysql"]["init"]["scripts"]:
                sqlFile = open(scriptFilePath, "r")
                queriesInFile = self.extractFromSQLFile(sqlFile)
                sqlFile.close()

                queries.extend(queriesInFile)

        def failCallback(error):
            errorMessage = str(error)
            if isinstance(error, Failure):
                errorMessage = error.getErrorMessage()

            self.log.error(
                "[Viper.MySQL] _initDatabase() database error: {errorMessage}",
                errorMessage=errorMessage
            )

        def runCallback(transaction, queries):
            try:
                for query in queries:
                    transaction.execute(query)
            except Exception as e:
                failCallback(e)
                return

        interaction = self.runInteraction(runCallback, queries)
        interaction.addErrback(failCallback)
1283876
public synchronized void initialize() throws DatabaseException {
        //this only needs to be called once.
        if (connectionString != null) {
            return;
        }
        Connection conn = null;
        try {
            //load the driver if necessary
            final String driverName = settings.getString(Settings.KEYS.DB_DRIVER_NAME, "");
            final String driverPath = settings.getString(Settings.KEYS.DB_DRIVER_PATH, "");
            LOGGER.debug("Loading driver '{}'", driverName);
            try {
                if (!driverPath.isEmpty()) {
                    LOGGER.debug("Loading driver from: {}", driverPath);
                    driver = DriverLoader.load(driverName, driverPath);
                } else {
                    driver = DriverLoader.load(driverName);
                }
            } catch (DriverLoadException ex) {
                LOGGER.debug("Unable to load database driver", ex);
                throw new DatabaseException("Unable to load database driver", ex);
            }
            userName = settings.getString(Settings.KEYS.DB_USER, "dcuser");
            //yes, yes - hard-coded password - only if there isn't one in the properties file.
            password = settings.getString(Settings.KEYS.DB_PASSWORD, "DC-Pass1337!");
            try {
                connectionString = settings.getConnectionString(
                        Settings.KEYS.DB_CONNECTION_STRING,
                        Settings.KEYS.DB_FILE_NAME);
            } catch (IOException ex) {
                LOGGER.debug("Unable to retrieve the database connection string", ex);
                throw new DatabaseException("Unable to retrieve the database connection string", ex);
            }

            boolean shouldCreateSchema = false;
            try {
                if (connectionString.startsWith("jdbc:h2:file:")) { //H2
                    shouldCreateSchema = !h2DataFileExists();
                    LOGGER.debug("Need to create DB Structure: {}", shouldCreateSchema);
                }
            } catch (IOException ioex) {
                LOGGER.debug("Unable to verify database exists", ioex);
                throw new DatabaseException("Unable to verify database exists", ioex);
            }
            LOGGER.debug("Loading database connection");
            LOGGER.debug("Connection String: {}", connectionString);
            LOGGER.debug("Database User: {}", userName);

            try {
                if (connectionString.toLowerCase().contains("integrated security=true")
                        || connectionString.toLowerCase().contains("trusted_connection=true")) {
                    conn = DriverManager.getConnection(connectionString);
                } else {
                    conn = DriverManager.getConnection(connectionString, userName, password);
                }
            } catch (SQLException ex) {
                if (ex.getMessage().contains("java.net.UnknownHostException") && connectionString.contains("AUTO_SERVER=TRUE;")) {
                    connectionString = connectionString.replace("AUTO_SERVER=TRUE;", "");
                    try {
                        conn = DriverManager.getConnection(connectionString, userName, password);
                        settings.setString(Settings.KEYS.DB_CONNECTION_STRING, connectionString);
                        LOGGER.debug("Unable to start the database in server mode; reverting to single user mode");
                    } catch (SQLException sqlex) {
                        LOGGER.debug("Unable to connect to the database", ex);
                        throw new DatabaseException("Unable to connect to the database", ex);
                    }
                } else {
                    LOGGER.debug("Unable to connect to the database", ex);
                    throw new DatabaseException("Unable to connect to the database", ex);
                }
            }
            if (shouldCreateSchema) {
                try {
                    createTables(conn);
                } catch (DatabaseException dex) {
                    LOGGER.debug("", dex);
                    throw new DatabaseException("Unable to create the database structure", dex);
                }
            }
            try {
                ensureSchemaVersion(conn);
            } catch (DatabaseException dex) {
                LOGGER.debug("", dex);
                throw new DatabaseException("Database schema does not match this version of dependency-check", dex);
            }
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    LOGGER.debug("An error occurred closing the connection", ex);
                }
            }
        }
    }
321808
def _init_compiled(cls, dialect, connection, dbapi_connection,
                       compiled, parameters):
        """"""

        self = cls.__new__(cls)
        self.root_connection = connection
        self._dbapi_connection = dbapi_connection
        self.dialect = connection.dialect

        self.compiled = compiled

        # this should be caught in the engine before
        # we get here
        assert compiled.can_execute

        self.execution_options = compiled.execution_options.union(
            connection._execution_options)

        self.result_column_struct = (
            compiled._result_columns, compiled._ordered_columns,
            compiled._textual_ordered_columns)

        self.unicode_statement = util.text_type(compiled)
        if not dialect.supports_unicode_statements:
            self.statement = self.unicode_statement.encode(
                self.dialect.encoding)
        else:
            self.statement = self.unicode_statement

        self.isinsert = compiled.isinsert
        self.isupdate = compiled.isupdate
        self.isdelete = compiled.isdelete
        self.is_text = compiled.isplaintext

        if not parameters:
            self.compiled_parameters = [compiled.construct_params()]
        else:
            self.compiled_parameters = \
                [compiled.construct_params(m, _group_number=grp) for
                 grp, m in enumerate(parameters)]

            self.executemany = len(parameters) > 1

        self.cursor = self.create_cursor()

        if self.isinsert or self.isupdate or self.isdelete:
            self.is_crud = True
            self._is_explicit_returning = bool(compiled.statement._returning)
            self._is_implicit_returning = bool(
                compiled.returning and not compiled.statement._returning)

        if self.compiled.insert_prefetch or self.compiled.update_prefetch:
            if self.executemany:
                self._process_executemany_defaults()
            else:
                self._process_executesingle_defaults()

        processors = compiled._bind_processors

        # Convert the dictionary of bind parameter values
        # into a dict or list to be sent to the DBAPI's
        # execute() or executemany() method.
        parameters = []
        if dialect.positional:
            for compiled_params in self.compiled_parameters:
                param = []
                for key in self.compiled.positiontup:
                    if key in processors:
                        param.append(processors[key](compiled_params[key]))
                    else:
                        param.append(compiled_params[key])
                parameters.append(dialect.execute_sequence_format(param))
        else:
            encode = not dialect.supports_unicode_statements
            for compiled_params in self.compiled_parameters:

                if encode:
                    param = dict(
                        (
                            dialect._encoder(key)[0],
                            processors[key](compiled_params[key])
                            if key in processors
                            else compiled_params[key]
                        )
                        for key in compiled_params
                    )
                else:
                    param = dict(
                        (
                            key,
                            processors[key](compiled_params[key])
                            if key in processors
                            else compiled_params[key]
                        )
                        for key in compiled_params
                    )

                parameters.append(param)
        self.parameters = dialect.execute_sequence_format(parameters)

        self.statement = compiled
        return self
1328548
def init_db(self):
        '''
        '''
        cache_path = os.path.join(Config.CACHE_DIR,
                                  self.app.profile['username'])
        if not os.path.exists(cache_path):
            os.makedirs(cache_path, exist_ok=True)
        db = os.path.join(cache_path, TASK_FILE)
        self.conn = sqlite3.connect(db)
        self.cursor = self.conn.cursor()
        sql = '''CREATE TABLE IF NOT EXISTS tasks (
        name CHAR NOT NULL,
        path CHAR NOT NULL,
        fsid CHAR NOT NULL,
        size INTEGER NOT NULL,
        currsize INTEGER NOT NULL,
        link CHAR,
        isdir INTEGER,
        savename CHAR NOT NULL,
        savedir CHAR NOT NULL,
        state INT NOT NULL,
        statename CHAR NOT NULL,
        humansize CHAR NOT NULL,
        percent INT NOT NULL,
        tooltip CHAR
        )
        '''
        self.cursor.execute(sql)
357875
def init_db(self):
    '''
    '''

    # The user can provide a custom string
    if self.database is None:
        self.logger.error("You must provide a database url, exiting.")
        sys.exit(1)

    self.engine = create_engine(self.database, convert_unicode=True)
    self.session = scoped_session(sessionmaker(autocommit=False,
                                               autoflush=False,
                                               bind=self.engine))

    # Database Setup
    Base.query = self.session.query_property()

    # import all modules here that might define models so that
    # they will be registered properly on the metadata.  Otherwise
    # you will have to import them first before calling init_db()
    import expfactory.database.models
    self.Base = Base
    self.Base.metadata.create_all(bind=self.engine)
884981
def _run_init_queries(self):
        '''
        
        '''
        for obj in (Package, PackageCfgFile, PayloadFile, IgnoredDir, AllowedDir):
            self._db.create_table_from_object(obj())
1019779
public void init(BaseDatabase database, Record record)
    {
        super.init(database, record);

        m_gridList = new DataRecordList();      
        m_iEndOfFileIndex = UNKNOWN_POSITION; // Actual end of file (-1 means don't know)

        m_gridBuffer = new DataRecordBuffer();
        m_gridNew = new DataRecordBuffer();
        m_iPhysicalFilePosition = UNKNOWN_POSITION;
        m_iLogicalFilePosition = UNKNOWN_POSITION;

        if (((record.getOpenMode() & DBConstants.OPEN_READ_ONLY) != DBConstants.OPEN_READ_ONLY)
            && (record.getCounterField() != null))
                record.setOpenMode(record.getOpenMode() | DBConstants.OPEN_REFRESH_AND_LOCK_ON_CHANGE_STRATEGY);  // Must have for GridTable to re-read.
    }
959807
def init_db():
    
    db.drop_all()
    db.create_all()

    # Create sample Post
    title = "de Finibus Bonorum et Malorum - Part I"
    text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor \
                incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud \
                exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure \
                dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. \
                Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt \
                mollit anim id est laborum."

    post = Post(title=title, text=text)
    db.session.add(post)
    db.session.commit()
774038
def initialize_schema(connection):
  
  cursor = connection.cursor()
  cursor.execute("PRAGMA application_id={}".format(_TENSORBOARD_APPLICATION_ID))
  cursor.execute("PRAGMA user_version={}".format(_TENSORBOARD_USER_VERSION))
  with connection:
    for statement in _SCHEMA_STATEMENTS:
      lines = statement.strip('\n').split('\n')
      message = lines[0] + ('...' if len(lines) > 1 else '')
      logger.debug('Running DB init statement: %s', message)
      cursor.execute(statement)
966881
def open(self, new=False):
        '''
        
        '''
        self._db.new() if new else self._db.open()  # pylint: disable=W0106
        self._run_init_queries()
355802
public void init(DatabaseOwner databaseOwner, String strDbName, int iDatabaseType, Map<String, Object> properties)
    {
        m_databaseOwner = databaseOwner;
        m_strDbName = strDbName;
        m_iDatabaseType = iDatabaseType;
        m_vTableList = new Vector<BaseTable>();
        m_iMasterSlave = RecordOwner.MASTER | RecordOwner.SLAVE;
        m_bAutosequenceSupport = true;
        if (m_properties == null)
            m_properties = new Hashtable<String,Object>();
        if (properties != null)
        	m_properties.putAll(properties);

        m_databaseOwner.addDatabase(this);
    }
124794
def init_db(dbURL, pwd_salt_size=None, pwd_rounds=None):
    '''
    '''
    if not dbURL:
        dbURL = 'sqlite:///:memory:'
    logging.getLogger(__name__).debug("Initializing database: {}".format(dict(url=dbURL,
                                                                              pwd_salt_size=pwd_salt_size,
                                                                              pwd_rounds=pwd_rounds)))
    try:
        db = init_proxy(dbURL)
        global pwdCryptCtx
        pwdCryptCtx = gen_crypt_context(salt_size=pwd_salt_size, rounds=pwd_rounds)
        create_tables(db)
        return db
    except Exception as e:
        e.args = (e.args[0] + ' [users database]',)
        raise
362039
def initdb():
    

    print("Syncing up database...")
    cwd_to_sys_path()
    if db and hasattr(db, "Model"):
        db.create_all()
        for m in db.Model.__subclasses__():
            if hasattr(m, "initialize__"):
                print("Sync up model: %s ..." % m.__name__)
                getattr(m, "initialize__")()

    print("Done")
446651
@Override
  public void initialize() {
    if(databaseConnection == null) {
      return; // Supposedly we initialized already.
    }
    if(LOG.isDebugging()) {
      LOG.debugFine("Loading data from database connection.");
    }
    MultipleObjectsBundle bundle = databaseConnection.loadData();
    // Run at most once.
    databaseConnection = null;

    // Find DBIDs for bundle
    {
      DBIDs bids = bundle.getDBIDs();
      if(bids instanceof ArrayStaticDBIDs) {
        this.ids = (ArrayStaticDBIDs) bids;
      }
      else if(bids == null) {
        this.ids = DBIDUtil.generateStaticDBIDRange(bundle.dataLength());
      }
      else {
        this.ids = (ArrayStaticDBIDs) DBIDUtil.makeUnmodifiable(DBIDUtil.ensureArray(bids));
      }
    }
    // Replace id representation (it would be nicer if we would not need
    // DBIDView at all)
    this.idrep = new DBIDView(this.ids);
    relations.add(this.idrep);
    getHierarchy().add(this, idrep);

    DBIDArrayIter it = this.ids.iter();

    int numrel = bundle.metaLength();
    for(int i = 0; i < numrel; i++) {
      SimpleTypeInformation<?> meta = bundle.meta(i);
      @SuppressWarnings("unchecked")
      SimpleTypeInformation<Object> ometa = (SimpleTypeInformation<Object>) meta;
      WritableDataStore<Object> store = DataStoreUtil.makeStorage(ids, DataStoreFactory.HINT_DB, ometa.getRestrictionClass());
      for(it.seek(0); it.valid(); it.advance()) {
        store.put(it, bundle.data(it.getOffset(), i));
      }
      Relation<?> relation = new MaterializedRelation<>(ometa, ids, null, store);
      relations.add(relation);
      getHierarchy().add(this, relation);

      // Try to add indexes where appropriate
      for(IndexFactory<?> factory : indexFactories) {
        if(factory.getInputTypeRestriction().isAssignableFromType(ometa)) {
          @SuppressWarnings("unchecked")
          final IndexFactory<Object> ofact = (IndexFactory<Object>) factory;
          @SuppressWarnings("unchecked")
          final Relation<Object> orep = (Relation<Object>) relation;
          final Index index = ofact.instantiate(orep);
          Duration duration = LOG.isStatistics() ? LOG.newDuration(index.getClass().getName() + ".construction").begin() : null;
          index.initialize();
          if(duration != null) {
            LOG.statistics(duration.end());
          }
          getHierarchy().add(relation, index);
        }
      }
    }

    // fire insertion event
    eventManager.fireObjectsInserted(ids);
  }
584977
def init_db(self):
    '''
    '''
    self.session = None

    if not os.path.exists(self.data_base):
        mkdir_p(self.data_base)

    self.database = "%s/%s" %(self.data_base, self.study_id)
    if not os.path.exists(self.database):
        mkdir_p(self.database)