init database with demo data
964929
@PostConstruct
    public void initDatabase() {
        MongoDBInit.LOGGER.info("initializing MongoDB");
        String dbName = System.getProperty("mongodb.name");
        if (dbName == null) {
            throw new RuntimeException("Missing database name; Set system property 'mongodb.name'");
        }
        MongoDatabase db = this.mongo.getDatabase(dbName);

        try {
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resolver.getResources("classpath*:mongodb/*.ndjson");
            MongoDBInit.LOGGER.info("Scanning for collection data");
            for (Resource res : resources) {
                String filename = res.getFilename();
                String collection = filename.substring(0, filename.length() - 7);
                MongoDBInit.LOGGER.info("Found collection file: {}", collection);
                MongoCollection<DBObject> dbCollection = db.getCollection(collection, DBObject.class);
                try (Scanner scan = new Scanner(res.getInputStream(), "UTF-8")) {
                    int lines = 0;
                    while (scan.hasNextLine()) {
                        String json = scan.nextLine();
                        Object parse = JSON.parse(json);
                        if (parse instanceof DBObject) {
                            DBObject dbObject = (DBObject) parse;
                            dbCollection.insertOne(dbObject);
                        } else {
                            MongoDBInit.LOGGER.error("Invalid object found: {}", parse);
                            throw new RuntimeException("Invalid object");
                        }
                        lines++;
                    }
                    MongoDBInit.LOGGER.info("Imported {} objects into collection {}", lines, collection);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("Error importing objects", e);
        }
    }
1260525
def initialize(self):
        """"""
        self.Base.metadata.create_all(self.session.bind)
        logger.debug("initialized sqlalchemy orm tables")
597605
public void init(BaseDatabase database, Record record)
    {
        super.init(database, record);
        
        m_databaseFake = m_database;
        m_database = this.getSharedTable().getDatabase();  // Return the correct database
    }
651130
def init_db():
    
    with current_app.app_context():
        for filename in CHILL_CREATE_TABLE_FILES:
            db.execute(text(fetch_query_string(filename)))
647264
@Override
    public void initialize() {
        String adminUsername = "admin";
        String adminPassword = "123456";

        User param = new User();
        param.setUserName(adminUsername);
        User admin = baseDao.getUnique(User.class, param);
        if (admin != null) {
            LoggerHelper.info("database has been initialized.");
            return;
        }
        LoggerHelper.info("begin init database.");
        admin = new User();
        admin.setUserName(adminUsername);
        admin.setUserPassword(HashHelper.getHashedPassword(adminPassword, adminUsername));
        admin.setPasswordSalt(adminUsername);

        Role role = new Role();
        role.setRoleName("ROLE_ADMIN");
        role.setRoleDescription("Administrator");
        baseDao.save(role);

        admin.setRoleList(Arrays.asList(role));
        baseDao.save(admin);

        LoggerHelper.info("init database successfully.");
    }
104572
public void init(BaseDatabase database, Record record)
    {
        super.init(database, record);
        if (((QueryRecord)record).getBaseRecord() != null)
            m_tableNext = ((QueryRecord)record).getBaseRecord().getTable();   // Pass most commands thru to the main record's table
    }
886129
public void init(BaseDatabase database, Record record)
    {
        super.init(database, record);
        m_iRow = -1;        // resultSet row 0 = First row.
        m_iEOFRow = Integer.MAX_VALUE;  // Last valid row.
        m_iLastOrder = -1;
    }
1283700
function init()
    {
        $this->_a['table'] = 'cms_contents';
        $this->_a['cols'] = array(
            // Identifier
            'id' => array(
                'type' => 'Pluf_DB_Field_Sequence',
                'is_null' => false,
                'editable' => false
            ),
            // Fields
            'name' => array(
                'type' => 'Pluf_DB_Field_Varchar',
                'is_null' => false,
                'size' => 64,
                'unique' => true,
                'editable' => true
            ),
            'title' => array(
                'type' => 'Pluf_DB_Field_Varchar',
                'is_null' => true,
                'size' => 250,
                'default' => '',
                'editable' => true
            ),
            'description' => array(
                'type' => 'Pluf_DB_Field_Varchar',
                'is_null' => true,
                'size' => 2048,
                'default' => 'auto created content',
                'editable' => true
            ),
            'mime_type' => array(
                'type' => 'Pluf_DB_Field_Varchar',
                'is_null' => true,
                'size' => 64,
                'default' => 'application/octet-stream',
                'editable' => true
            ),
            'media_type' => array(
                'type' => 'Pluf_DB_Field_Varchar',
                'is_null' => true,
                'size' => 64,
                'default' => 'application/octet-stream',
                'verbose' => 'Media type',
                'help_text' => 'This types allow you to category contents',
                'editable' => true
            ),
            'file_path' => array(
                'type' => 'Pluf_DB_Field_Varchar',
                'is_null' => false,
                'size' => 250,
                'verbose' => 'File path',
                'help_text' => 'Content file path',
                'editable' => false,
                'readable' => false
            ),
            'file_name' => array(
                'type' => 'Pluf_DB_Field_Varchar',
                'is_null' => false,
                'size' => 250,
                'default' => 'unknown',
                'verbose' => 'file name',
                'help_text' => 'Content file name',
                'editable' => false
            ),
            'file_size' => array(
                'type' => 'Pluf_DB_Field_Integer',
                'is_null' => false,
                'default' => 'no title',
                'verbose' => 'file size',
                'help_text' => 'content file size',
                'editable' => false
            ),
            'downloads' => array(
                'type' => 'Pluf_DB_Field_Integer',
                'is_null' => false,
                'default' => 0,
                'help_text' => 'content downloads number',
                'editable' => false
            ),
            'status' => array(
                'type' => 'Pluf_DB_Field_Varchar',
                'is_null' => true,
                'size' => 64,
                'default' => 'published',
                'editable' => false
            ),
            'password' => array(
                'type' => 'Pluf_DB_Field_Password',
                'is_null' => true,
                'size' => 150,
                'help_text' => __('Format: [algo]:[salt]:[hash]'),
                'editable' => false,
                'readable' => false
            ),
            'comment_status' => array(
                'type' => 'Pluf_DB_Field_Varchar',
                'is_null' => true,
                'size' => 64,
                'default' => NULL,
                'editable' => false
            ),
            'comment_count' => array(
                'type' => 'Pluf_DB_Field_Integer',
                'is_null' => false,
                'default' => 0,
                'help_text' => 'number of comments on the content',
                'editable' => false
            ),
            'creation_dtime' => array(
                'type' => 'Pluf_DB_Field_Datetime',
                'blank' => true,
                'verbose' => 'creation',
                'help_text' => 'content creation time',
                'editable' => false
            ),
            'modif_dtime' => array(
                'type' => 'Pluf_DB_Field_Datetime',
                'blank' => true,
                'verbose' => 'modification',
                'help_text' => 'content modification time',
                'editable' => false
            ),
            /*
             * Foreign keys
             */
            'author_id' => array(
                'type' => 'Pluf_DB_Field_Foreignkey',
                'model' => 'User_Account',
                'is_null' => false,
                'name' => 'author',
                'relate_name' => 'cms_contents',
                'graphql_name' => 'author',
                'editable' => false
            ),
            'parent_id' => array(
                'type' => 'Pluf_DB_Field_Foreignkey',
                'model' => 'CMS_Content',
                'is_null' => true,
                'name' => 'parent',
                'graphql_name' => 'parent',
                'relate_name' => 'children',
                'editable' => true,
                'readable' => true
            ),
        );

        $this->_a['idx'] = array(
            // @Note: hadi - 1396-10: when define an attribute as 'unique => true', pluf automatically
            // create an unique index for it (for example 'name' field here).
            'content_mime_filter_idx' => array(
                'col' => 'mime_type',
                'type' => 'normal', // normal, unique, fulltext, spatial
                'index_type' => '', // hash, btree
                'index_option' => '',
                'algorithm_option' => '',
                'lock_option' => ''
            )
        );
    }
1213952
def init_db(self, app, entry_point_group='invenio_db.models', **kwargs):
        """"""
        # Setup SQLAlchemy
        app.config.setdefault(
            'SQLALCHEMY_DATABASE_URI',
            'sqlite:///' + os.path.join(app.instance_path, app.name + '.db')
        )
        app.config.setdefault('SQLALCHEMY_ECHO', False)

        # 
        database = kwargs.get('db', db)
        database.init_app(app)

        # Initialize versioning support.
        self.init_versioning(app, database, kwargs.get('versioning_manager'))

        # Initialize model bases
        if entry_point_group:
            for base_entry in pkg_resources.iter_entry_points(
                    entry_point_group):
                base_entry.load()

        # All models should be loaded by now.
        sa.orm.configure_mappers()
        # Ensure that versioning classes have been built.
        if app.config['DB_VERSIONING']:
            manager = self.versioning_manager
            if manager.pending_classes:
                if not versioning_models_registered(manager, database.Model):
                    manager.builder.configure_versioned_classes()
            elif 'transaction' not in database.metadata.tables:
                manager.declarative_base = database.Model
                manager.create_transaction_model()
                manager.plugins.after_build_tx_class(manager)
1189223
def init_db(self):
        
        # get the database url from the configuration
        db_url = self.config.get('database_url', 'sqlite:///nautilus.db')
        # configure the nautilus database to the url
        nautilus.database.init_db(db_url)
956259
def init_db(drop_all=False, bind=engine):
    """"""
    try:
        if drop_all:
            Base.metadata.drop_all(bind=bind)
        Base.metadata.create_all(bind=bind)
    except OperationalError as err:
        msg = 'password authentication failed for user "dallinger"'
        if msg in err.message:
            sys.stderr.write(db_user_warning)
        raise

    return session
146711
def init(**kwargs):
    

    # TODO: Iterate through all engines in name set.
    database = kwargs.pop('database', False)
    if database and not database_exists(engine['default'].url):
        create_database(engine['default'].url, encoding='utf8')
        clear_cache()

    expression = lambda target, table: table.create(target)
    test = lambda target, table: table.exists(target)
    op(expression, test=test, primary='init', secondary='create', **kwargs)
798731
def init_db(self):
        

        # database file
        db_path = self.get_data_file("data.sqlite")

        # comect and create cursor
        self.db = sqlite3.connect(db_path)
        self.cursor = self.db.cursor()

        # prep tables
        self.db_exec('''
            CREATE TABLE IF NOT EXISTS shortcuts (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL,
                path TEXT NOT NULL,
                command TEXT NOT NULL
            )
            ''')
1110656
public function init()
    {

        // initialize the prepared statements
        $this->productMediaGalleryValueStmt =
            $this->getConnection()->prepare($this->loadStatement(SqlStatementKeys::PRODUCT_MEDIA_GALLERY_VALUE));
    }
1338497
function initDB () {
  return db.listDatabases()
    .then(response => {
      if (response.data.indexOf(dbName) !== -1) {
        // database already exists
        return Promise.resolve('ok')
      } else {
        // create new database
        return db.createDatabase(dbName).then(() => 'ok')
      }
    })
}
987442
private function installShopData($database, $demoDataRequired = 0)
    {
        $baseSqlDir = $this->getUtilitiesInstance()->getSqlDirectory(EditionSelector::COMMUNITY);

        try {
            // If demo data files are provided.
            if ($demoDataRequired && $this->getUtilitiesInstance()->isDemodataPrepared()) {
                $this->getUtilitiesInstance()->executeExternalDatabaseMigrationCommand();

                // Install demo data.
                $database->queryFile($this->getUtilitiesInstance()->getActiveEditionDemodataPackageSqlFilePath());
                // Copy demo data files.
                $this->getUtilitiesInstance()->executeExternalDemodataAssetsInstallCommand();
            } else {
                $database->queryFile("$baseSqlDir/initial_data.sql");

                $this->getUtilitiesInstance()->executeExternalDatabaseMigrationCommand();
            }
        } catch (Exception $exception) {
            $commandException = new CommandExecutionFailedException('Migration', $exception->getCode(), $exception);
            $commandException->setCommandOutput([$exception->getMessage()]);

            $this->handleCommandExecutionFailedException($commandException);

            throw new SetupControllerExitException();
        }
    }
498675
def initDatabase(self, db_file):
        
        try:
            self.__f = io.open(db_file, "rb")
        except IOError, e:
            print "[Error]: ", e
            sys.exit()