Initialize sqlite3 movies database.

    :param movies_data: Data about movies
    :type movies_data: tuple[tuple]

    :param database: Connection to sqlite database with movies data
    :type database: sqlite3.Connection
554002
def init_sqlite(movies_data, database):
    
    with database:
        database.execute('CREATE TABLE IF NOT EXISTS movies '
                         '(name text, year int, director text)')
        database.execute('DELETE FROM movies')
        database.executemany('INSERT INTO movies VALUES (?,?,?)', movies_data)
876163
def create():
    """"""
    if not all(map(os.path.isdir, ARGS.directory)):
        exit('Error: One or more of the specified directories does not exist.')
    with sqlite3.connect(ARGS.database) as connection:
        connection.text_factory = str
        cursor = connection.cursor()
        cursor.execute('DROP TABLE IF EXISTS Movies')
        cursor.execute('''CREATE TABLE Movies(name TEXT, path TEXT, size TEXT,
                          files BLOB)''')
        for dir in ARGS.directory:
            cursor.executemany('INSERT INTO Movies VALUES(?, ?, ?, ?)',
                               local_data(dir))
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)
348496
protected function initDatabase()
    {
        $dbConfig = (array) config("database");

        if (count($dbConfig) > 0) {
            $this->db = new Database($dbConfig);
            Model::$db = $this->db;
        }
    }
797371
def connect(
    database: Union[str, Path], *, loop: asyncio.AbstractEventLoop = None, **kwargs: Any
) -> Connection:
    """"""
    if loop is None:
        loop = asyncio.get_event_loop()

    def connector() -> sqlite3.Connection:
        if isinstance(database, str):
            loc = database
        elif isinstance(database, bytes):
            loc = database.decode("utf-8")
        else:
            loc = str(database)

        return sqlite3.connect(loc, **kwargs)

    return Connection(connector, loop)
164686
def connect(self, *args, **kwargs):
        
        self.db = sqlite3.connect(*args, **kwargs)
        self.db.isolation_level = None
1094698
def initdb(config):
    
    engine = sa.engine_from_config(config, 'sqlalchemy.')
    Session.configure(bind=engine)
132450
def connect_db(Repo, database=":memory:"):
        
        Repo.db = sqlite3.connect(database,
                                  detect_types=sqlite3.PARSE_DECLTYPES)
        return Repo.db
834854
def createDatabase(self, name, **dbArgs) :
        ""
        dbArgs['name'] = name
        payload = json.dumps(dbArgs, default=str)
        url = self.URL + "/database"
        r = self.session.post(url, data = payload)
        data = r.json()
        if r.status_code == 201 and not data["error"] :
            db = Database(self, name)
            self.databases[name] = db
            return self.databases[name]
        else :
            raise CreationError(data["errorMessage"], r.content)
1288275
public function initializeObject() {
		$databaseFilePath = $this->storageFolder . md5($this->getIndexName()) . '.db';
		$createDatabaseTables = FALSE;

		if (!is_file($databaseFilePath)) {
			if (!is_dir($this->storageFolder)) {
				mkdir($this->storageFolder, 0777, TRUE);
			}
			$createDatabaseTables = TRUE;
		}
		$this->connection = new \SQLite3($databaseFilePath);

		if ($createDatabaseTables) {
			$this->createIndexTables();
		} else {
			$this->loadAvailablePropertyFields();
		}
	}
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)
289235
def _create_db(self):
        
        log.debug("Creating sqlite database")
        self._conn = sqlite3.connect(self._db_filename)

        # create table structure
        self._conn.cursor().execute("""
        CREATE TABLE IF NOT EXISTS {}
        (
          ts REAL,
          arbitration_id INTEGER,
          extended INTEGER,
          remote INTEGER,
          error INTEGER,
          dlc INTEGER,
          data BLOB
        )
        """.format(self.table_name))
        self._conn.commit()

        self._insert_template = "INSERT INTO {} VALUES (?, ?, ?, ?, ?, ?, ?)".format(self.table_name)
137904
def create_default_database(reset: bool = False) -> GraphDatabaseInterface:
        
        import sqlalchemy
        from sqlalchemy.ext.declarative import declarative_base
        from sqlalchemy.orm import sessionmaker
        from sqlalchemy.pool import StaticPool

        Base = declarative_base()
        engine = sqlalchemy.create_engine("sqlite:///SpotifyArtistGraph.db", poolclass=StaticPool)
        Session = sessionmaker(bind=engine)

        dbi: GraphDatabaseInterface = create_graph_database_interface(
            sqlalchemy, Session(), Base, sqlalchemy.orm.relationship
        )

        if reset:
            Base.metadata.drop_all(engine)
        Base.metadata.create_all(engine)

        return dbi
1142827
def ls():
    """"""
    if not os.path.exists(ARGS.database):
        exit('Error: The database does not exist; you must create it first.')
    with sqlite3.connect(ARGS.database) as connection:
        connection.text_factory = str
        cursor = connection.cursor()
        if ARGS.pattern:
            if not ARGS.strict:
                ARGS.pattern = '%{0}%'.format(ARGS.pattern)
            cursor.execute('SELECT * FROM Movies WHERE Name LIKE (?)',
                           [ARGS.pattern])
        else:
            cursor.execute('SELECT * FROM Movies')
        movies = sorted([row for row in cursor])
    if ARGS.name:
        print '\n'.join([movie[0] for movie in movies])
    elif ARGS.location:
        print '\n'.join([movie[1] for movie in movies])
    elif ARGS.size:
        print '\n'.join([prefix_size(int(movie[2])) for movie in movies])
    elif ARGS.files:
        for movie in movies:
            print ', '.join(movie[3].split('##'))
    else:
        for i, movie in enumerate(movies):
            print 'Name:\t\t{0}'.format(movie[0])
            print 'Location:\t{0}'.format(movie[1])
            print 'Size:\t\t{0}'.format(prefix_size(int(movie[2])))
            print 'Files:\t\t{0}'.format(', '.join(movie[3].split('##')))
            if not i == len(movies) - 1:
                print
105151
def _initDatabase(self):
        
        queries = []

        if len(self.application.config["viper.mysql"]["init"]["scripts"]) > 0:
            for scriptFilePath in self.application.config["viper.mysql"]["init"]["scripts"]:
                sqlFile = open(scriptFilePath, "r")
                queriesInFile = self.extractFromSQLFile(sqlFile)
                sqlFile.close()

                queries.extend(queriesInFile)

        def failCallback(error):
            errorMessage = str(error)
            if isinstance(error, Failure):
                errorMessage = error.getErrorMessage()

            self.log.error(
                "[Viper.MySQL] _initDatabase() database error: {errorMessage}",
                errorMessage=errorMessage
            )

        def runCallback(transaction, queries):
            try:
                for query in queries:
                    transaction.execute(query)
            except Exception as e:
                failCallback(e)
                return

        interaction = self.runInteraction(runCallback, queries)
        interaction.addErrback(failCallback)
446651
@Override
  public void initialize() {
    if(databaseConnection == null) {
      return; // Supposedly we initialized already.
    }
    if(LOG.isDebugging()) {
      LOG.debugFine("Loading data from database connection.");
    }
    MultipleObjectsBundle bundle = databaseConnection.loadData();
    // Run at most once.
    databaseConnection = null;

    // Find DBIDs for bundle
    {
      DBIDs bids = bundle.getDBIDs();
      if(bids instanceof ArrayStaticDBIDs) {
        this.ids = (ArrayStaticDBIDs) bids;
      }
      else if(bids == null) {
        this.ids = DBIDUtil.generateStaticDBIDRange(bundle.dataLength());
      }
      else {
        this.ids = (ArrayStaticDBIDs) DBIDUtil.makeUnmodifiable(DBIDUtil.ensureArray(bids));
      }
    }
    // Replace id representation (it would be nicer if we would not need
    // DBIDView at all)
    this.idrep = new DBIDView(this.ids);
    relations.add(this.idrep);
    getHierarchy().add(this, idrep);

    DBIDArrayIter it = this.ids.iter();

    int numrel = bundle.metaLength();
    for(int i = 0; i < numrel; i++) {
      SimpleTypeInformation<?> meta = bundle.meta(i);
      @SuppressWarnings("unchecked")
      SimpleTypeInformation<Object> ometa = (SimpleTypeInformation<Object>) meta;
      WritableDataStore<Object> store = DataStoreUtil.makeStorage(ids, DataStoreFactory.HINT_DB, ometa.getRestrictionClass());
      for(it.seek(0); it.valid(); it.advance()) {
        store.put(it, bundle.data(it.getOffset(), i));
      }
      Relation<?> relation = new MaterializedRelation<>(ometa, ids, null, store);
      relations.add(relation);
      getHierarchy().add(this, relation);

      // Try to add indexes where appropriate
      for(IndexFactory<?> factory : indexFactories) {
        if(factory.getInputTypeRestriction().isAssignableFromType(ometa)) {
          @SuppressWarnings("unchecked")
          final IndexFactory<Object> ofact = (IndexFactory<Object>) factory;
          @SuppressWarnings("unchecked")
          final Relation<Object> orep = (Relation<Object>) relation;
          final Index index = ofact.instantiate(orep);
          Duration duration = LOG.isStatistics() ? LOG.newDuration(index.getClass().getName() + ".construction").begin() : null;
          index.initialize();
          if(duration != null) {
            LOG.statistics(duration.end());
          }
          getHierarchy().add(relation, index);
        }
      }
    }

    // fire insertion event
    eventManager.fireObjectsInserted(ids);
  }
146711
def init(**kwargs):
    

    # TODO: Iterate through all engines in name set.
    database = kwargs.pop('database', False)
    if database and not database_exists(engine['default'].url):
        create_database(engine['default'].url, encoding='utf8')
        clear_cache()

    expression = lambda target, table: table.create(target)
    test = lambda target, table: table.exists(target)
    op(expression, test=test, primary='init', secondary='create', **kwargs)