Initialize and return a Database instance
198912
def MonSQL(host=None, port=None, username=None, password=None, dbname=None, dbpath=None, dbtype=None):
	
	if dbtype is None:
		raise MonSQLException('Database type must be specified')

	if dbtype == DB_TYPES.MYSQL:
		return MySQLDatabase(host, port, username, password, dbname)
	elif dbtype == DB_TYPES.SQLITE3:
		return SQLite3Database(dbpath)
	elif dbtype == DB_TYPES.POSTGRESQL:
		return PostgreSQLDatabase(host, port, username, password, dbname)
	else:
		raise MonSQLException('Database type %s not supported' %dbtype)
1355379
def init_db(db_path):
    """"""
    logger.info("Creating database")
    with closing(connect_database(db_path)) as db:
        with open(SCHEMA, 'r') as f:
            db.cursor().executescript(f.read())
        db.commit()
    return
1245265
def from_db(cls, db, force=False):
        
        if force or db not in cls._cache:
            cls._cache[db] = cls._new_from_db(db)
        return cls._cache[db]
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;
        }
    }
718838
def _init_db(cls):
        
        # This list of import defines which SQLAlchemy classes will be
        # initialized when Meta.init() is called. If a sqlalchemy class is not
        # imported before the call to create_all(), it will not be created.
        import fonduer.candidates.models  # noqa
        import fonduer.features.models  # noqa
        import fonduer.learning.models  # noqa
        import fonduer.parser.models  # noqa
        import fonduer.supervision.models  # noqa
        import fonduer.utils.models  # noqa

        logger.info("Initializing the storage schema")
        Meta.Base.metadata.create_all(Meta.engine)
517522
function createDatabase (name) {
  var deferred = q.defer();

  // Make sure the database location exists
  ready.then(function () {
    // Check if database exists
    fs.exists(globalConfig.db.location + name + '.db.json', function (exists) {
      if(exists) return deferred.resolve();

      // If database is non-existent, simply write an empty object as placeholder
      fs.writeFile(globalConfig.db.location + name + '.db.json', '{}', function (err) {
        if(err) return deferred.reject('Database couldn\'t create table');

        return deferred.resolve();
      });
    });
  }, function () {
    deferred.reject('Database couldn\'t instantiate');
  });

  return deferred.promise;
}
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)
              )
            """)
828851
protected function onInit()
    {
        $host = Util::get($this->params, "host", "");//host\instanceName
        $username = Util::get($this->params, "username", "");
        $password = Util::get($this->params, "password", "");
        $dbname = Util::get($this->params, "dbname", "");
        $returnDatesAsStrings = Util::get($this->params, "returnDatesAsStrings", true);
        $charset = Util::get($this->params, "charset", 'utf-8');
        $connectionInfo = array(
            "Database"=>$dbname,
            "UID"=>$username,
            "PWD"=>$password, 
            "ReturnDatesAsStrings" => $returnDatesAsStrings, 
            "CharacterSet" => $charset
        );

        $key = md5($host.$username.$password.$dbname);
        if (isset(SQLSRVDataSource::$connections[$key])) {
            $this->connection = SQLSRVDataSource::$connections[$key];
        } else {
            $conn = sqlsrv_connect($host, $connectionInfo);
            if ($conn) {
                $this->connection = $conn;
            } else {
                throw new \Exception(
                    "Connection could not be established: "
                    .print_r(sqlsrv_errors(), true)
                );
            }    
            SQLSRVDataSource::$connections[$key] = $this->connection;
        }
    }
358831
function db_init() {
        if ($this->is_configured() === false) {
            throw new moodle_exception('auth_dbcantconnect', 'auth_db');
        }

        // Connect to the external database (forcing new connection).
        $authdb = ADONewConnection($this->config->type);
        if (!empty($this->config->debugauthdb)) {
            $authdb->debug = true;
            ob_start(); //Start output buffer to allow later use of the page headers.
        }
        $authdb->Connect($this->config->host, $this->config->user, $this->config->pass, $this->config->name, true);
        $authdb->SetFetchMode(ADODB_FETCH_ASSOC);
        if (!empty($this->config->setupsql)) {
            $authdb->Execute($this->config->setupsql);
        }

        return $authdb;
    }
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']);
    }
522555
def init(self, db=RDB_DB, host=RDB_HOST, port=RDB_PORT):
        """"""
        self.RDB_HOST = host
        self.RDB_PORT = port
        self.RDB_DB = db

        from .connection import RethinkDB
        self.rdb = RethinkDB()
        self.rdb.init()
779434
def db(self):
        

        # Initialize the database handle; we're running in a separate
        # process, so we need to get_database() ourself
        if not self._db:
            self._db = self.config.get_database()

        return self._db
617120
def _initialize(self, con):
        """"""
        if self.initialized:
            return

        SQLite3Database()._initialize(con)  # ASE db initialization

        cur = con.execute(
            'SELECT COUNT(*) FROM sqlite_master WHERE name="reaction"')

        if cur.fetchone()[0] == 0:  # no reaction table
            for init_command in init_commands:
                con.execute(init_command)  # Create tables
            con.commit()

        self.initialized = True
216083
def init_db(uri, base, **kwargs):
    
    engine = create_engine(uri, **kwargs)
    base.metadata.create_all(engine)
    return engine
1359077
def db(self):
        

        # Initialize the database handle from the middleware's copy of
        # it
        if not self._db:
            self._db = self.middleware.db

        return self._db
613090
def _setup_db(cls):
        
        uri = cls._app.config.get("DB_URL")
        if uri:
            db.connect__(uri, cls._app)
813276
def init_from_database(self, conn, database, table_name):
        
        info = conn.query('SHOW TABLE STATUS FROM `{database}` WHERE name="{table_name}"'.format(
            table_name=table_name, database=database), as_dict=True).fetchone()
        if info is None:
            if table_name == '~log':
                logger.warning('Could not create the ~log table')
                return
            else:
                raise DataJointError('The table `{database}`.`{table_name}` is not defined.'.format(
                    table_name=table_name, database=database))
        self.table_info = {k.lower(): v for k, v in info.items()}

        cur = conn.query(
            'SHOW FULL COLUMNS FROM `{table_name}` IN `{database}`'.format(
                table_name=table_name, database=database), as_dict=True)

        attributes = cur.fetchall()

        rename_map = {
            'Field': 'name',
            'Type': 'type',
            'Null': 'nullable',
            'Default': 'default',
            'Key': 'in_key',
            'Comment': 'comment'}

        fields_to_drop = ('Privileges', 'Collation')

        # rename and drop attributes
        attributes = [{rename_map[k] if k in rename_map else k: v
                       for k, v in x.items() if k not in fields_to_drop}
                      for x in attributes]

        numeric_types = {
            ('float', False): np.float64,
            ('float', True): np.float64,
            ('double', False): np.float64,
            ('double', True): np.float64,
            ('tinyint', False): np.int64,
            ('tinyint', True): np.int64,
            ('smallint', False): np.int64,
            ('smallint', True): np.int64,
            ('mediumint', False): np.int64,
            ('mediumint', True): np.int64,
            ('int', False): np.int64,
            ('int', True): np.int64,
            ('bigint', False): np.int64,
            ('bigint', True): np.uint64}

        sql_literals = ['CURRENT_TIMESTAMP']

        # additional attribute properties
        for attr in attributes:
            # process external attributes
            split_comment = attr['comment'].split(':')
            attr['is_external'] = len(split_comment) >= 3 and split_comment[1].startswith('external')
            if attr['is_external']:
                attr['comment'] = ':'.join(split_comment[2:])
                attr['type'] = split_comment[1]

            attr['nullable'] = (attr['nullable'] == 'YES')
            attr['in_key'] = (attr['in_key'] == 'PRI')
            attr['autoincrement'] = bool(re.search(r'auto_increment', attr['Extra'], flags=re.IGNORECASE))
            attr['type'] = re.sub(r'int\(\d+\)', 'int', attr['type'], count=1)   # strip size off integers
            attr['numeric'] = bool(re.match(r'(tiny|small|medium|big)?int|decimal|double|float', attr['type']))
            attr['string'] = bool(re.match(r'(var)?char|enum|date|year|time|timestamp', attr['type']))
            attr['is_blob'] = attr['is_external'] or bool(re.match(r'(tiny|medium|long)?blob', attr['type']))
            attr['database'] = database

            if attr['string'] and attr['default'] is not None and attr['default'] not in sql_literals:
                attr['default'] = '"%s"' % attr['default']

            if attr['nullable']:   # nullable fields always default to null
                attr['default'] = 'null'

            attr['sql_expression'] = None
            if not (attr['numeric'] or attr['string'] or attr['is_blob']):
                raise DataJointError('Unsupported field type {field} in `{database}`.`{table_name}`'.format(
                    field=attr['type'], database=database, table_name=table_name))
            attr.pop('Extra')

            # fill out dtype. All floats and non-nullable integers are turned into specific dtypes
            attr['dtype'] = object
            if attr['numeric']:
                is_integer = bool(re.match(r'(tiny|small|medium|big)?int', attr['type']))
                is_float = bool(re.match(r'(double|float)', attr['type']))
                if is_integer and not attr['nullable'] or is_float:
                    is_unsigned = bool(re.match('\sunsigned', attr['type'], flags=re.IGNORECASE))
                    t = attr['type']
                    t = re.sub(r'\(.*\)', '', t)    # remove parentheses
                    t = re.sub(r' unsigned$', '', t)   # remove unsigned
                    assert (t, is_unsigned) in numeric_types, 'dtype not found for type %s' % t
                    attr['dtype'] = numeric_types[(t, is_unsigned)]
        self.attributes = OrderedDict([(q['name'], Attribute(**q)) for q in attributes])

        # Read and tabulate secondary indexes
        keys = defaultdict(dict)
        for item in conn.query('SHOW KEYS FROM `{db}`.`{tab}`'.format(db=database, tab=table_name), as_dict=True):
            if item['Key_name'] != 'PRIMARY':
                keys[item['Key_name']][item['Seq_in_index']] = dict(
                    column=item['Column_name'],
                    unique=(item['Non_unique'] == 0),
                    nullable=item['Null'].lower() == 'yes')
        self.indexes = {
            tuple(item[k]['column'] for k in sorted(item.keys())):
                dict(unique=item[1]['unique'],
                     nullable=any(v['nullable'] for v in item.values()))
            for item in keys.values()}