Setup data from database
975382
def _init_turrets(self):
        
        for turret in Turret.select():
            self.turrets.append(turret.to_dict())
943742
def populate_db(sql_path):
    """"""

    logger.info("Populating DB %s from %s", repr(DB["NAME"]), repr(sql_path))
    shell(
        'psql -U "{USER}" -h "{HOST}" -d "{NAME}" --file={sql_path}'.format(
            sql_path=sql_path, **DB
        )
    )
884451
def set_data(self, *args):
        """"""
        db = self.begining.get_data() or formats.DATE_DEFAULT
        df = self.end.get_data() or formats.DATE_DEFAULT
        jours = max((df - db).days + 1, 0)
        self.setText(str(jours) + (jours >= 2 and " jours" or " jour"))
192661
protected function connectToDb()
    {
        try {
            $this->db = new PDO("mysql:dbname=;" . $this->db_host, $this->db_user, $this->db_pass);
            $this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
        } catch (\Exception $e) {
            $this->log("Cannot connect to database.  Are the credentials correct?");
            $this->log(print_r($e), 1);
            exit;
        }
    }
1346154
def init_database(self):
        """"""
        with contextlib.closing(self.database.cursor()) as cursor:
            cursor.execute("""
              CREATE TABLE IF NOT EXISTS users(
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name VARCHAR(32)
              )
            """)
1306134
public void setupFields()
    {
        FieldInfo field = null;
        field = new FieldInfo(this, ID, Constants.DEFAULT_FIELD_LENGTH, null, null);
        field.setDataClass(Integer.class);
        field.setHidden(true);
        field = new FieldInfo(this, LAST_CHANGED, Constants.DEFAULT_FIELD_LENGTH, null, null);
        field.setDataClass(Date.class);
        field.setHidden(true);
        field = new FieldInfo(this, DELETED, 10, null, new Boolean(false));
        field.setDataClass(Boolean.class);
        field.setHidden(true);
        field = new FieldInfo(this, NAME, 30, null, null);
        field = new FieldInfo(this, DESCRIPTION, 30, null, null);
        field = new FieldInfo(this, VERSION, 20, null, null);
        field = new FieldInfo(this, START_ID, 10, null, null);
        field.setDataClass(Integer.class);
        field = new FieldInfo(this, END_ID, 10, null, null);
        field.setDataClass(Integer.class);
        field = new FieldInfo(this, BASE_DATABASE, 30, null, null);
        field = new FieldInfo(this, PROPERTIES, Constants.DEFAULT_FIELD_LENGTH, null, null);
    }
1165301
def setup(settings):
    
    connector = settings.get('db_connector')
    if connector == 'postgres':
        from playhouse.pool import PooledPostgresqlExtDatabase
        return PooledPostgresqlExtDatabase(settings['db_name'],
                           user=settings['db_user'],
                           password=settings['db_password'],
                           host=settings['db_host'],
                           port=settings.get('db_port'),
                           max_connections=settings.get('db_max_conn'),
                           stale_timeout=settings.get('db_stale_timeout'),
                           timeout=settings.get('db_timeout'),
                           register_hstore=False)
499189
def setup_database(eng, modules=None, models=None):
    
    if modules is not None:
        for modu in modules:
            for m in modu.__all__:
                getattr(modu, m).metadata.create_all(eng)
    if models is not None:
        for mod in models:
            mod.metadata.create_all(eng)
697201
public function dbInfo()
    {
        $view = $this->getView();
        $session = $this->getSessionInstance();
        $systemRequirements = getSystemReqCheck();
        $utilities = $this->getUtilitiesInstance();

        $eulaOptionValue = $utilities->getRequestVar("iEula", "post");
        $eulaOptionValue = (int)($eulaOptionValue ? $eulaOptionValue : $session->getSessionParam("eula"));
        if (!$eulaOptionValue) {
            $setup = $this->getSetupInstance();
            $setup->setNextStep($setup->getStep("STEP_WELCOME"));
            $view->setMessage($this->getLanguageInstance()->getText("ERROR_SETUP_CANCELLED"));

            throw new SetupControllerExitException("licenseerror.php");
        }

        $databaseConfigValues = $session->getSessionParam('aDB');
        $demodataPackageExists = $utilities->isDemodataPrepared();

        if (!isset($databaseConfigValues)) {
            // default values
            $databaseConfigValues['dbHost'] = "localhost";
            $databaseConfigValues['dbPort'] = "3306";
            $databaseConfigValues['dbUser'] = "";
            $databaseConfigValues['dbPwd'] = "";
            $databaseConfigValues['dbName'] = "";
            $databaseConfigValues['dbiDemoData'] = $demodataPackageExists ? 1 : 0;
        }

        $this->setViewOptions(
            'dbinfo.php',
            'STEP_3_TITLE',
            [
                "aDB" => $databaseConfigValues,
                "blMbStringOn" => $systemRequirements->getModuleInfo('mb_string'),
                "blUnicodeSupport" => $systemRequirements->getModuleInfo('unicode_support'),
                "demodataPackageExists" => $demodataPackageExists
            ]
        );
    }
555244
static function init()
    {
        if (SettingsDatabase::NEED_CONNECT) {
            $connection_string = 'mysql:host=' . SettingsDatabase::HOST . ';port=' . SettingsDatabase::PORT . ';dbname=' . SettingsDatabase::DBNAME;

            ORM::configure('connection_string', $connection_string);
            ORM::configure('username', SettingsDatabase::USERNAME);
            ORM::configure('password', SettingsDatabase::PASSWORD);
            ORM::configure('logging', SettingsDatabase::LOGGING);
            ORM::configure('driver_options', [
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
            ]);
        }
    }
1088422
def _createDatabase( self ):
        """"""

        # create experiment metadata table
        command = """
                  CREATE TABLE {tn} (
                  {k}             INT PRIMARY KEY NOT NULL,
                  START_TIME      INT             NOT NULL,
                  END_TIME        INT             NOT NULL,
                  ELAPSED_TIME    INT             NOT NULL,
                  SETUP_TIME      INT             NOT NULL,
                  EXPERIMENT_TIME INT             NOT NULL,
                  TEARDOWN_TIME   INT             NOT NULL,
                  STATUS          BOOLEAN         NOT NULL)
                  """
        self._connection.execute(command.format(tn = self.EXPERIMENT_METADATA_TABLE,
                                                k = self.EXPERIMENT_ID))
        
        # commit the changes
        self.commit()
1329207
protected static function _setupDb($connection_name = self::DEFAULT_CONNECTION)
        {
            if (!Arrays::exists($connection_name, self::$_db) || !is_object(self::$_db[$connection_name])) {
                self::_setupDbConfig($connection_name);

                $db = new PDO(
                    self::$_config[$connection_name]['connection_string'],
                    self::$_config[$connection_name]['username'],
                    self::$_config[$connection_name]['password'],
                    self::$_config[$connection_name]['driver_options']
                );

                $db->setAttribute(PDO::ATTR_ERRMODE, self::$_config[$connection_name]['error_mode']);

                self::set_db($db, $connection_name);
            }
        }
357107
def setup_db(connection_string):
    
    global DB_Session, engine
    new_database = False
    if connection_string == 'sqlite://' or not database_exists(connection_string):
        new_database = True
    engine = create_engine(connection_string, connect_args={'timeout': 20})
    entities.Base.metadata.create_all(engine)
    DB_Session = sessionmaker(bind=engine)
    db_path = os.path.dirname(__file__)

    if new_database:
        # bootstrapping the db with classifications types.
        json_file = open(os.path.join(db_path, 'bootstrap.json'))
        data = json.load(json_file)
        session = get_session()
        session.execute('PRAGMA user_version = {0}'.format(beeswarm.server.db.DATABASE_VERSION))
        for entry in data['classifications']:
            c = session.query(Classification).filter(Classification.type == entry['type']).first()
            if not c:
                classification = Classification(type=entry['type'], description_short=entry['description_short'],
                                                description_long=entry['description_long'])
                session.add(classification)
            else:
                c.description_short = entry['description_short']
                c.description_long = entry['description_long']
        for username in data['bait_users']:
            u = session.query(BaitUser).filter(BaitUser.username == username).first()
            if not u:
                logger.debug('Creating default BaitUser: {}'.format(username))
                password = data['bait_users'][username]
                bait_user = BaitUser(username=username, password=password)
                session.add(bait_user)
        session.commit()
    else:
        result = engine.execute("PRAGMA user_version;")
        version = result.fetchone()[0]
        result.close()
        logger.info('Database is at version {0}.'.format(version))
        if version != beeswarm.server.db.DATABASE_VERSION:
            logger.error('Incompatible database version detected. This version of Beeswarm is compatible with '
                         'database version {0}, but {1} was found. Please delete the database, restart the Beeswarm '
                         'server and reconnect the drones.'.format(beeswarm.server.db.DATABASE_VERSION,
                                                                   version))
            sys.exit(1)
500850
public void setupDB() throws Exception {

        if (m_bean.isInitialized()) {
            System.out.println("Setup-Bean initialized successfully.");
            CmsSetupDb db = new CmsSetupDb(m_bean.getWebAppRfsPath());
            try {
                // try to connect as the runtime user
                db.setConnection(
                    m_bean.getDbDriver(),
                    m_bean.getDbWorkConStr(),
                    m_bean.getDbConStrParams(),
                    m_bean.getDbWorkUser(),
                    m_bean.getDbWorkPwd(),
                    false);
                if (!db.noErrors()) {
                    // try to connect as the setup user
                    db.closeConnection();
                    db.clearErrors();
                    db.setConnection(
                        m_bean.getDbDriver(),
                        m_bean.getDbCreateConStr(),
                        m_bean.getDbConStrParams(),
                        m_bean.getDbCreateUser(),
                        m_bean.getDbCreatePwd());
                }
                if (!db.noErrors() || !m_bean.validateJdbc()) {
                    throw new Exception("DB Connection test faild.");
                }
            } finally {
                db.clearErrors();
                db.closeConnection();
            }
        }

        System.out.println("DB connection tested successfully.");

        CmsSetupDb db = null;
        boolean dbExists = false;
        if (m_bean.isInitialized()) {
            if (m_props.isCreateDb() || m_props.isCreateTables()) {
                db = new CmsSetupDb(m_bean.getWebAppRfsPath());
                // check if database exists
                if (m_bean.getDatabase().startsWith("oracle")
                    || m_bean.getDatabase().startsWith("db2")
                    || m_bean.getDatabase().startsWith("as400")) {
                    db.setConnection(
                        m_bean.getDbDriver(),
                        m_bean.getDbWorkConStr(),
                        m_bean.getDbConStrParams(),
                        m_bean.getDbWorkUser(),
                        m_bean.getDbWorkPwd());
                } else {
                    db.setConnection(
                        m_bean.getDbDriver(),
                        m_bean.getDbWorkConStr(),
                        m_bean.getDbConStrParams(),
                        m_bean.getDbCreateUser(),
                        m_bean.getDbCreatePwd(),
                        false);
                    dbExists = db.noErrors();
                    if (dbExists) {
                        db.closeConnection();
                    } else {
                        db.clearErrors();
                    }
                }
                if (!dbExists || m_props.isDropDb()) {
                    db.closeConnection();
                    if (!m_bean.getDatabase().startsWith("db2") && !m_bean.getDatabase().startsWith("as400")) {
                        db.setConnection(
                            m_bean.getDbDriver(),
                            m_bean.getDbCreateConStr(),
                            m_bean.getDbConStrParams(),
                            m_bean.getDbCreateUser(),
                            m_bean.getDbCreatePwd());
                    }
                }
            }
        }
        if (!m_props.isCreateDb() && !m_props.isCreateTables() && !dbExists) {
            throw new Exception("You have not created the Alkacon OpenCms database.");
        }
        if (dbExists && m_props.isCreateTables() && !m_props.isDropDb() && (db != null)) {
            throw new Exception("You have selected to not drop existing DBs, but a DB with the given name exists.");
        }
        if (dbExists && m_props.isCreateDb() && m_props.isDropDb() && (db != null)) {
            // drop the DB
            db.closeConnection();
            db.setConnection(
                m_bean.getDbDriver(),
                m_bean.getDbWorkConStr(),
                m_bean.getDbConStrParams(),
                m_bean.getDbCreateUser(),
                m_bean.getDbCreatePwd());
            db.dropDatabase(m_bean.getDatabase(), m_bean.getReplacer());
            if (!db.noErrors()) {
                for (String error : db.getErrors()) {
                    System.err.println(error + "\n");
                    System.err.println(HR + "\n");
                }
                db.clearErrors();
                throw new Exception("Error ocurred while dropping the DB!");
            }
            System.out.println("Database dropped successfully.");
        }

        if (m_props.isCreateDb() && (db != null)) {
            // Create Database
            db.createDatabase(m_bean.getDatabase(), m_bean.getReplacer());
            if (!db.noErrors()) {
                for (String error : db.getErrors()) {
                    System.err.println(error + "\n");
                    System.err.println(HR + "\n");
                }
                db.clearErrors();
                throw new Exception("Error ocurred while creating the DB!");
            }
            db.closeConnection();
            System.out.println("Database created successfully.");
        }

        if (m_props.isCreateTables() && (db != null)) {
            db.setConnection(
                m_bean.getDbDriver(),
                m_bean.getDbWorkConStr(),
                m_bean.getDbConStrParams(),
                m_bean.getDbWorkUser(),
                m_bean.getDbWorkPwd());
            //Drop Tables (intentionally quiet)
            db.dropTables(m_bean.getDatabase());
            db.clearErrors();
            db.closeConnection();
            // reopen the connection in order to display errors
            db.setConnection(
                m_bean.getDbDriver(),
                m_bean.getDbWorkConStr(),
                m_bean.getDbConStrParams(),
                m_bean.getDbWorkUser(),
                m_bean.getDbWorkPwd());
            //Create Tables
            db.createTables(m_bean.getDatabase(), m_bean.getReplacer());
            if (!db.noErrors()) {
                for (String error : db.getErrors()) {
                    System.err.println(error + "\n");
                    System.err.println(HR + "\n");
                }
                db.clearErrors();
                throw new Exception("Error ocurred while creating tables.");
            }
            db.closeConnection();
            System.out.println("Tables created successfully.");
        }
        if (db != null) {
            db.closeConnection();
        }
        System.out.println("Database setup was successful.");
    }
143584
def set_up(self, reset=False):
        
        if reset:
            self.tear_down()

        logger.info("Creating database")
        # create the tables
        BASE.metadata.create_all(self.engine)
        return self
812112
def set_database(self, db):
        '''
        
        '''
        # This can not be imported globally due to circular import
        from .database import Database
        assert isinstance(db, Database), "database must be database.Database instance"
        self._database = db
68044
def _load_data(self, data, from_db=False):
        
        self._data = data[:]
        self.setattrs(
            values=[],
            node_stack=[],
            node_dict={},
        )
        self._from_db = from_db