Create the index for storing profiles.

    This is idempotent; it can be called every time a database is opened to
    make sure it's ready to use and up-to-date.

    :param conn: A connection to an SQLite3 database.
967612
def schema_create(conn):
    
    conn.execute(dedent("""\
    CREATE TABLE IF NOT EXISTS profiles
      (id INTEGER PRIMARY KEY,
       name TEXT NOT NULL UNIQUE,
       data BLOB NOT NULL,
       selected BOOLEAN NOT NULL DEFAULT FALSE)
    """))
    # Partial indexes are only available in >=3.8.0 and expressions in indexes
    # are only available in >=3.9.0 (https://www.sqlite.org/partialindex.html
    # & https://www.sqlite.org/expridx.html). Don't bother with any kind of
    # index before that because it would complicate upgrades.
    if sqlite3.sqlite_version_info >= (3, 9, 0):
        # This index is for data integrity -- ensuring that only one profile
        # is the default ("selected") profile -- and speed a distant second.
        conn.execute(dedent("""\
        CREATE UNIQUE INDEX IF NOT EXISTS
          only_one_profile_selected ON profiles
          (selected IS NOT NULL) WHERE selected
        """))
767176
def add_connections(self, conns):
        
        rets = []
        for addr, kwargs in conns:
            r = self.add_connection(addr, **kwargs)
            rets.append(r)
        return rets
796514
def create_index(self,
                     table: str,
                     field: str,
                     nchars: int = None,
                     indexname: str = None,
                     unique: bool = False) -> Optional[int]:
        """"""
        limit = ""
        if nchars is not None:
            limit = "({})".format(nchars)
        if indexname is None:
            indexname = "_idx_{}".format(field)
        if self.index_exists(table, indexname):
            return None
        uniquestr = "UNIQUE" if unique else ""
        sql = (
            "CREATE {unique} INDEX {indexname} "
            "ON {table} ({field}{limit})".format(
                unique=uniquestr,
                indexname=indexname,
                table=table,
                field=field,
                limit=limit,
            )
        )
        return self.db_exec(sql)
1198674
def create_cache_database(self):
        

        conn = sqlite3.connect(self.database)
        conn.text_factory = str

        c = conn.cursor()
        c.execute("""CREATE TABLE items
                     (url text, metadata text, datetime text)""")
        c.execute("""CREATE TABLE documents
                     (url text, path text, datetime text)""")
        c.execute("""CREATE TABLE primary_texts
                     (item_url text, primary_text text, datetime text)""")
        conn.commit()
        conn.close()
758231
def _CreateIndexIfNotExists(self, index_name, mappings):
    
    try:
      if not self._client.indices.exists(index_name):
        self._client.indices.create(
            body={'mappings': mappings}, index=index_name)

    except elasticsearch.exceptions.ConnectionError as exception:
      raise RuntimeError(
          'Unable to create Elasticsearch index with error: {0!s}'.format(
              exception))
393237
def indices(db=None):
    '''
    
    '''
    cur = _connect(db)

    if not cur:
        return False

    cur.execute(
        "SELECT name FROM sqlite_master WHERE type='index' ORDER BY name;"
    )
    rows = cur.fetchall()
    return rows
1236797
def create_index(self, collection, index_name, **kwargs):
        """"""
        try:
            self.connection[collection].create_index(index_name, **kwargs)
        except Exception as exc:
            LOG.warn("Error tuning mongodb database: %s", exc)
848096
def _conn_key(self, instance, db_key, db_name=None):
        ''' 
        '''
        dsn, host, username, password, database, driver = self._get_access_info(instance, db_key, db_name)
        return '{}:{}:{}:{}:{}:{}'.format(dsn, host, username, password, database, driver)
1302049
def createIndices(self):
        

        sql = '''CREATE INDEX name_index
                 ON Expression (name)'''
        self._cursor.execute(sql)
        self._dbConn.commit()

        sql = '''CREATE INDEX expression_index
                 ON Expression (expression)'''
        self._cursor.execute(sql)
        self._dbConn.commit()
835608
def set_db_opts(self, dbname="mta4", credentials=True):
        
        from jcvi.utils.db import valid_dbconn, get_profile

        self.add_option("--db", default=dbname, dest="dbname",
                help="Specify name of database to query [default: %default]")
        self.add_option("--connector", default="Sybase", dest="dbconn",
                choices=valid_dbconn.keys(), help="Specify database connector [default: %default]")
        hostname, username, password = get_profile()
        if credentials:
            self.add_option("--hostname", default=hostname,
                    help="Specify hostname [default: %default]")
            self.add_option("--username", default=username,
                    help="Username to connect to database [default: %default]")
            self.add_option("--password", default=password,
                    help="Password to connect to database [default: %default]")
        self.add_option("--port", type="int",
                help="Specify port number [default: %default]")
1336356
def create_index(self, key, reindex=True, sparse=False):
        
        warnings.warn('Index support is currently very alpha and is not guaranteed')
        if isinstance(key, (list, tuple)):
            index_name = ','.join(key)
            index_columns = ', '.join('%s text' % f for f in key)
        else:
            index_name = key
            index_columns = '%s text' % key

        table_name = '[%s{%s}]' % (self.name, index_name)
        reindex = reindex or not self._object_exists('table', table_name)

        # Create a table store for the index data
        self.db.execute("""
            create table if not exists {table} (
                id integer primary key,
                {columns},
                foreign key(id) references {collection}(id) on delete cascade on update cascade
            )
        """.format(
            table=table_name,
            collection=self.name,
            columns=index_columns
        ))

        # Create the index
        self.db.execute("""
            create index if not exists [idx.{collection}{{index}}] on {table}({index})
        """.format(
            collection=self.name,
            index=index_name,
            table=table_name,
        ))

        if reindex:
            self.reindex(key)
1116873
def _prepare_proxy(self, conn):
        
        conn.set_tunnel(self._proxy_host, self.port, self.proxy_headers)
        conn.connect()
1172584
def get_conn(filename):
    """"""
    conn = sqlite3.connect(filename)
    conn.row_factory = _dict_factory
    return conn
1328548
def init_db(self):
        '''
        '''
        cache_path = os.path.join(Config.CACHE_DIR,
                                  self.app.profile['username'])
        if not os.path.exists(cache_path):
            os.makedirs(cache_path, exist_ok=True)
        db = os.path.join(cache_path, TASK_FILE)
        self.conn = sqlite3.connect(db)
        self.cursor = self.conn.cursor()
        sql = '''CREATE TABLE IF NOT EXISTS tasks (
        name CHAR NOT NULL,
        path CHAR NOT NULL,
        fsid CHAR NOT NULL,
        size INTEGER NOT NULL,
        currsize INTEGER NOT NULL,
        link CHAR,
        isdir INTEGER,
        savename CHAR NOT NULL,
        savedir CHAR NOT NULL,
        state INT NOT NULL,
        statename CHAR NOT NULL,
        humansize CHAR NOT NULL,
        percent INT NOT NULL,
        tooltip CHAR
        )
        '''
        self.cursor.execute(sql)
164686
def connect(self, *args, **kwargs):
        
        self.db = sqlite3.connect(*args, **kwargs)
        self.db.isolation_level = None
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()
1171073
def make_cursor(path, init_statements=(), _connectioncache={}):
    """"""
    connection = _connectioncache.get(path)
    if not connection:
        is_new = not os.path.exists(path) or not os.path.getsize(path)
        try: is_new and os.makedirs(os.path.dirname(path))
        except OSError: pass
        connection = sqlite3.connect(path, isolation_level=None,
            check_same_thread=False, detect_types=sqlite3.PARSE_DECLTYPES)
        for x in init_statements or (): connection.execute(x)
        try: is_new and ":memory:" not in path.lower() and os.chmod(path, 0707)
        except OSError: pass
        connection.row_factory = lambda cur, row: dict(sqlite3.Row(cur, row))
        _connectioncache[path] = connection
    return connection.cursor()