Get a loaded database session
550394
def db(self):
        
        if self.database is NotImplemented:
            self.database = Session

        return self.database
737297
def get_db(directory, engine=None):
    
    if engine is None:
        engine = create_engine('sqlite://')
    tables.metadata.create_all(engine)
    Session = sessionmaker(bind=engine)
    db = Session()
    if directory is not None:
        load_from_directory(db, directory)
    return db
1273219
def load_session
      unless logged_in?
        session[Shibbolite.pid] = request.env[Shibbolite.pid.to_s]
        current_user.update(get_attributes) if registered_user?
      end
    end
355926
def get_session(url):
    
    engine = create_engine(url)
    db_session = scoped_session(sessionmaker(engine))
    Base.metadata.create_all(engine)
    return db_session
635932
def db(self, connection_string=None):
        """"""

        connection_string = connection_string or self.settings["db"]

        if not hasattr(self, "_db_conns"):
            self._db_conns = {}
        if not connection_string in self._db_conns:
            self._db_conns[connection_string] = oz.sqlalchemy.session(connection_string=connection_string)

        return self._db_conns[connection_string]
101365
private static function getFromSession()
    {
        if (empty($_SESSION['current_user'])) {
            // No user in session, create one.
            $entityClassName = static::ENTITIES_CLASS_NAME;
            $user = new $entityClassName(array(
                'source' => 'cookie',
            ));
            self::setCurrent($user);
        } else {
            Logger::get()->debug('Found user in session.');
            // Regenerate session ID every SESSION_DURATION minutes.
            if (time() > ($_SESSION['timestamp'] +  + self::SESSION_DURATION)) {
                Logger::get()->debug('Regenerated session ID.');
                session_regenerate_id();
            }
        }

        return $_SESSION['current_user'];
    }
718670
def async_aldb_loaded_callback(self):
        """"""
        if self.aldb_load_lock.locked():
            self.aldb_load_lock.release()
        _LOGGING.info('ALDB Loaded')
1036357
public Session getSysSessionForScript(Database db) {

        Session session = new Session(db, db.getUserManager().getSysUser(),
                                      false, false, false, 0, 0);

        session.isProcessingScript = true;

        return session;
    }
1300735
def get(cls, external_id, local_user_id, provider_name, db_session=None):
        
        db_session = get_db_session(db_session)
        return db_session.query(cls.model).get(
            [external_id, local_user_id, provider_name]
        )
1094698
def initdb(config):
    
    engine = sa.engine_from_config(config, 'sqlalchemy.')
    Session.configure(bind=engine)
814990
def session(connection_string=None):
    """"""
    global _session_makers
    connection_string = connection_string or oz.settings["db"]

    if not connection_string in _session_makers:
        _session_makers[connection_string] = sessionmaker(bind=engine(connection_string=connection_string))

    return _session_makers[connection_string]()
1197832
static function getInstance($databaseNameOrResource = '*LOCAL', $userOrI5NamingFlag = '', $password = '', $extensionPrefix = '', $isPersistent = false, $forceNew = false)
    {
        // if we're forcing a new instance, close db conn first if exists.
        if ($forceNew && self::hasInstance() && isset(self::$instance->conn))
        {
            self::$instance->disconnect();
        }

        // if we're forcing a new instance, or an instance hasn't been created yet, create one
        if ($forceNew || self::$instance == NULL) {
            $toolkitService = __CLASS__;
            self::$instance = new $toolkitService($databaseNameOrResource, $userOrI5NamingFlag, $password, $extensionPrefix, $isPersistent);
        }

        if (self::$instance) {
            // instance exists
            return self::$instance;
        } else {
            // some problem
            return false;
        }
    }
664675
def _perform_database_action(action, *args):
    
    session = _get_session()
    getattr(session, action)(*args)
    session.commit()
326426
def reload(self) :
        

        r = self.session.get(self.databasesURL)

        data = r.json()
        if r.status_code == 200 and not data["error"] :
            self.databases = {}
            for dbName in data["result"] :
                if dbName not in self.databases :
                    self.databases[dbName] = DBHandle(self, dbName)
        else :
            raise ConnectionError(data["errorMessage"], self.databasesURL, r.status_code, r.content)
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)
618461
def get_engine_from_session(dbsession: Session) -> Engine:
    
    engine = dbsession.bind
    assert isinstance(engine, Engine)
    return engine
1300812
def session(self):
        """"""
        from sqlalchemy.orm import sessionmaker
        from sqlalchemy.event import listen

        if not self.Session:
            self.Session = sessionmaker(bind=self.engine)

        if not self._session:
            self._session = self.Session()
            # set the search path

            if self._schema:
                def after_begin(session, transaction, connection):
                    # import traceback
                    # print traceback.print_stack()
                    session.execute('SET search_path TO {}'.format(self._schema))

                listen(self._session, 'after_begin', after_begin)

        return self._session