Sets up the database schema and adds defaults.
    :param connection_string: Database URL. e.g: sqlite:///filename.db
                              This is usually taken from the config file.
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)
643292
protected static function initDB() {
        $dbConfig = static::getConfig('db', static::getServer());
        static::$db = new Connection($dbConfig['dsn'], $dbConfig['user'], $dbConfig['password'], $dbConfig['options']);
        static::$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        if (!empty($dbConfig['tablePrefix']))
            static::$db->setTablePrefix($dbConfig['tablePrefix']);
    }
403497
def create_db():
    
    from flask_appbuilder.models.sqla import Model

    engine = current_app.appbuilder.get_session.get_bind(mapper=None, clause=None)
    Model.metadata.create_all(engine)
    click.echo(click.style("DB objects created", fg="green"))
1233711
def initialize(self, name=None, dbname=None, base=None, generator=None,
                   case=None, namespaces=None):

        self.name = none_or(name, str)
        

        self.dbname = none_or(dbname, str)
        """
        The dbname of the site. : str | `None`
        """

        self.base = none_or(base, str)
        """
        TODO: ??? : str | `None`
        """

        self.generator = none_or(generator, str)
        """
        TODO: ??? : str | `None`
        """

        self.case = none_or(case, str)
        """
        TODO: ??? : str | `None`
        """

        self.namespaces = none_or(namespaces, list)
        """
        A list of :class:`mwtypes.Namespace` | `None`
        """
18885
def connect(cls, dbname):
        
        test_times_schema = """
        CREATE TABLE IF NOT EXISTS test_times (
          file text,
          module text,
          class text,
          func text,
          elapsed float
        )
        """
        
        setup_times_schema = """
        CREATE TABLE IF NOT EXISTS setup_times (
          file text,
          module text,
          class text,
          func text,
          elapsed float
        )
        """
        
        schemas = [test_times_schema,
                   setup_times_schema]
        
        db_file = '{}.db'.format(dbname)
                
        cls.connection = sqlite3.connect(db_file)
        for s in schemas:
            cls.connection.execute(s)
821342
def _database_create(self, engine, database):
        
        logger.info('Creating database "%s" in "%s"', database, engine)
        database_operation(engine, 'create', database)
        url = copy(engine.url)
        url.database = database
        return str(url)
266320
def default_database(ctx: click.Context, _param: Parameter, value: Optional[str]):
    """"""
    if value:
        return value

    if ctx.params["repository"]:
        return os.path.join(ctx.params["repository"], DB.DEFAULT_DB_FILE)

    raise click.BadParameter("Could not guess a database location")
44187
public static function useConnection($connection_name='', $db = null) {
        if(!$connection_name){
            $connection_name=Connection::class;
        }
        CoContext::getContext()->set(CoContext::CONNECTION_NAME, $connection_name);
        if ($db) {
            CoContext::getContext()->set(CoContext::CONNECTION_scheme, $db);
        }
    }
718858
def init_db_conn(
        connection_name, HOST=None, PORT=None, DB=None, PASSWORD=None):
    
    rpool = redis.ConnectionPool(
        host=HOST, port=PORT, db=DB, password=PASSWORD)
    r = redis.Redis(connection_pool=rpool)
    redis_pool.connections[connection_name] = RedisClient(r)
992315
def configure_connection
      #if encoding = config[:encoding]
        # The client_encoding setting is set by the driver and should not be altered.
        # If the driver detects a change it will abort the connection.
        # see http://jdbc.postgresql.org/documentation/91/connect.html
        # self.set_client_encoding(encoding)
      #end
      self.client_min_messages = config[:min_messages] || 'warning'
      self.schema_search_path = config[:schema_search_path] || config[:schema_order]

      # Use standard-conforming strings if available so we don't have to do the E'...' dance.
      set_standard_conforming_strings

      # If using Active Record's time zone support configure the connection to return
      # TIMESTAMP WITH ZONE types in UTC.
      # (SET TIME ZONE does not use an equals sign like other SET variables)
      if ActiveRecord::Base.default_timezone == :utc
        execute("SET time zone 'UTC'", 'SCHEMA')
      elsif tz = local_tz
        execute("SET time zone '#{tz}'", 'SCHEMA')
      end unless redshift?

      # SET statements from :variables config hash
      # http://www.postgresql.org/docs/8.3/static/sql-set.html
      (config[:variables] || {}).map do |k, v|
        if v == ':default' || v == :default
          # Sets the value to the global or compile default
          execute("SET SESSION #{k} TO DEFAULT", 'SCHEMA')
        elsif ! v.nil?
          execute("SET SESSION #{k} TO #{quote(v)}", 'SCHEMA')
        end
      end
    end
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)
932710
def _dbsetup(self):
        
        self._dbconn = sqlite3.connect(self._db_file)
        # Create table for multiplicons
        sql = '''CREATE TABLE multiplicons
                 (id, genome_x, list_x, parent, genome_y, list_y, level,
                  number_of_anchorpoints, profile_length, begin_x, end_x,
                  begin_y, end_y, is_redundant)'''
        self._dbconn.execute(sql)
        # Create table for multiplicons ('order' appears to be reserved)
        sql = '''CREATE TABLE segments
                 (id, multiplicon, genome, list, first, last, ord)'''
        self._dbconn.execute(sql)
        self._dbconn.commit()
397792
def connect_db(database_name=":memory:"):
    
    db = repo.Repo.connect_db(database_name)
    base.Repo.db = db
    query.Repo.db = db
1269658
public function setConnection()
	{
		$connection = Config::get('core::database.default');

		if ($connection !== 'default')
		{
			$wardrobeConfig = Config::get('core::database.connections.'.$connection);
		}
		else
		{
			$connection = Config::get('database.default');
			$wardrobeConfig = Config::get('database.connections.'.$connection);
		}

		Config::set('database.connections.wardrobe', $wardrobeConfig);
	}
395287
private static function createConnection()
    {
        // Validate if configuration has enough details.
        $driver = Configuration::get('database_driver');

        // Make DSN and options
        $dsn = "";
        $options = Configuration::get('database-options');
        $options = !is_array($options) ? array() : $options;

        $user = null;
        $password = null;

        if ($driver === 'pdo_sqlite') {
            // We will ignore this for now, as it's not tested with SQLite yet!
            // @codeCoverageIgnoreStart
            $path = Configuration::get('database_path');

            if (! $path || ! file_exists($path)) {
                throw new \Exception("SQLite Database File doesn't exists or not configured! '".$path."'");
            }

            $dsn = "sqlite:" . $path;
            // @codeCoverageIgnoreEnd
        }else if ($driver === 'pdo_mysql') {
            $host = Configuration::get('database_host');
            $database = Configuration::get('database_db');
            $user = Configuration::get('database_user');
            $password = Configuration::get('database_password');

            $port = Configuration::get('database_port');
            $port = !is_int($port) ? 3306 : $port;

            $encoding = Configuration::get('database_encoding');
            $encoding = $encoding == null ? 'utf8' : $encoding;

            if (is_null($host) || is_null($database) || is_null($user) || is_null($password)) {
                throw new \Exception("Please configure the ORM first. We can't get a connection now!");
            }

            $dsn = "mysql:host=" . $host . ";port=" . $port . ";dbname=" . $database . ";charset=" . $encoding;
        }else{
            throw new \Exception("Please configure the ORM first. We can't get a connection now! No driver given!");
        }

        // Make connection
        self::$connection = new \PDO($dsn, $user, $password, $options);
    }
1288179
public static MongoDatabase getOrInitDefaultDatabase(String connectionString, String database) {
        if (DEFAULT_DATABASE == null) {
            synchronized (LOCK) {
                if (DEFAULT_DATABASE == null) {
                    if (!StringUtil.isEmpty(connectionString)) {
                        DEFAULT_CLIENT = MongoClients.create(connectionString);
                        CodecRegistry pojoCodecRegistry = fromRegistries(
                                /*fromCodecs(new StringCodecExt()),*/
                                MongoClientSettings.getDefaultCodecRegistry(),
                                fromProviders(PojoCodecProvider.builder().automatic(true).build()));
                        DEFAULT_DATABASE = DEFAULT_CLIENT.getDatabase(database).withCodecRegistry(pojoCodecRegistry);
                    } else {
                        throw new RuntimeException("No datasource configuration found for mongodb.");
                    }
                }
            }
        }
        return DEFAULT_DATABASE;
    }
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