Creates and opens a database session
778177
def get_session(db_path: str):
    
    # cfg = Config()
    # db_path = cfg.get(ConfigKeys.asset_allocation_database_path)

    # connection
    con_str = "sqlite:///" + db_path
    # Display all SQLite info with echo.
    engine = create_engine(con_str, echo=False)

    # create metadata (?)
    Base.metadata.create_all(engine)

    # create session
    Session = sessionmaker(bind=engine)
    session = Session()

    return session
1345062
def _MakeConnection(self, database=""):
    """"""
    first_attempt_time = time.time()
    wait_time = config.CONFIG["Mysql.max_connect_wait"]
    while wait_time == 0 or time.time() - first_attempt_time < wait_time:
      try:
        connection_args = dict(
            user=config.CONFIG["Mysql.database_username"],
            db=database,
            charset="utf8",
            passwd=config.CONFIG["Mysql.database_password"],
            autocommit=True,
            cursorclass=cursors.DictCursor,
            host=config.CONFIG["Mysql.host"],
            port=config.CONFIG["Mysql.port"])

        key_path = config.CONFIG["Mysql.client_key_path"]
        if key_path:
          cert_path = config.CONFIG["Mysql.client_cert_path"]
          ca_cert_path = config.CONFIG["Mysql.ca_cert_path"]
          logging.debug("Client key file configured, trying to use SSL.")

          connection_args["ssl"] = {
              "key": key_path,
              "cert": cert_path,
              "ca": ca_cert_path,
          }

        return MySQLdb.connect(**connection_args)

      except MySQLdb.OperationalError as e:
        # This is a fatal error, we just raise the top level exception here.
        if "Access denied" in str(e):
          raise Error(str(e))

        if "Can't connect" in str(e):
          logging.warning("Datastore connection retrying after failed with %s.",
                          str(e))
          time.sleep(.5)
          continue
        raise

    raise IOError("Unable to connect to Mysql database.")
332901
private void openDatabase() {
        m_client = new Client(m_config.host, m_config.port, m_config.getTLSParams());
        m_client.setCredentials(m_config.getCredentials());
    }
292999
def _get_session(self):
        
        if self._session is None:
            session = self._session = self._database.session()
            session.create()
        return self._session
639711
static final ZooRollingSession open(String dbName) {
        if (!ZooHelper.dbExists(dbName)) {
            // create database
            // By default, all database files will be created in %USER_HOME%/zoodb
            ZooHelper.createDb(dbName);
        }
		return new ZooRollingSession(dbName);
	}
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)
918707
def database_create(self, database, **params):
        
        binds = {}
        dbname = database
        for key, engine in self.keys_engines():
            if hasattr(database, '__call__'):
                dbname = database(engine)
            assert dbname, "Cannot create a database, no db name given"
            key = key if key else 'default'
            binds[key] = self._database_create(engine, dbname)
        return self.copy(binds)
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)
550394
def db(self):
        
        if self.database is NotImplemented:
            self.database = Session

        return self.database
161892
def create_db(name, **client_args):
    '''
    
    '''
    if db_exists(name, **client_args):
        log.info('DB \'%s\' already exists', name)
        return False

    client = _client(**client_args)
    client.create_database(name)

    return True
550998
def init_db_conn(connection_name, connection_string, scopefunc=None):
    
    engine = create_engine(connection_string)
    session = scoped_session(sessionmaker(), scopefunc=scopefunc)
    session.configure(bind=engine)
    pool.connections[connection_name] = Connection(engine, session)
278101
def create_db(name, owner=None, encoding=u'UTF-8', template='template1',
              **kwargs):
    """"""

    flags = u''
    if encoding:
        flags = u'-E %s' % encoding
    if owner:
        flags = u'%s -O %s' % (flags, owner)
    if template and template != 'template1':
        flags = u'%s --template=%s' % (flags, template)
    sudo('createdb %s %s' % (flags, name), user='postgres', **kwargs)
1175677
def magic_session(db_session=None, url=None):
    

    if db_session is not None:
        yield db_session
    else:
        session = get_session(url, expire_on_commit=False)
        try:
            try:
                yield session
            finally:
                session.commit()
        finally:
            session.close()
256154
def create_db(url=None):
    
    if url is None:
        url = os.environ.get("DATABASE_URL")
    parsed_url = urlparse(url)
    db_name = parsed_url.path
    db_name = db_name.strip("/")
    db = connect("postgresql://" + parsed_url.netloc)
    # check that db does not exist
    q = """SELECT 1 as exists
           FROM pg_database
           WHERE datname = '{db_name}'""".format(
        db_name=db_name
    )
    if not db.query(q).fetchone():
        # CREATE DATABASE must be run outside of a transaction
        # https://stackoverflow.com/questions/6506578/how-to-create-a-new-database-using-sqlalchemy
        conn = db.engine.connect()
        conn.execute("commit")
        conn.execute("CREATE DATABASE " + db_name)
        conn.close()
633656
public void open() {
        if(sqlSession == null) {
            if (executorType == null) {
                executorType = ExecutorType.SIMPLE;
            }

            sqlSession = sqlSessionFactory.openSession(executorType, autoCommit);

            if (log.isDebugEnabled()) {
                ToStringBuilder tsb = new ToStringBuilder(String.format("%s %s@%x",
                        (arbitrarilyClosed ? "Reopened" : "Opened"),
                        sqlSession.getClass().getSimpleName(),
                        sqlSession.hashCode()));
                tsb.append("executorType", executorType);
                tsb.append("autoCommit", autoCommit);
                log.debug(tsb.toString());
            }

            arbitrarilyClosed = false;
        }
    }
1088485
def get_session(db_url):
        # type: (str) -> Session
        
        engine = create_engine(db_url, poolclass=NullPool, echo=False)
        Session = sessionmaker(bind=engine)
        Base.metadata.create_all(engine)
        return Session()
1011096
def create_database_mysql(database: str,
                          user: str,
                          password: str,
                          server: str = "localhost",
                          port: int = 3306,
                          charset: str = "utf8",
                          collate: str = "utf8_general_ci",
                          use_unicode: bool = True) -> bool:
    """"""
    con = mysql.connect(
        host=server,
        port=port,
        user=user,
        passwd=password,
        charset=charset,
        use_unicode=use_unicode
    )
    sql = ("CREATE DATABASE IF NOT EXISTS {} DEFAULT CHARACTER SET {} "
           "DEFAULT COLLATE {}").format(
        database,
        charset,
        collate
    )
    cursor = con.cursor()
    debug_sql(sql)
    cursor.execute(sql)
    log.info("Created database {}", database)
    return True