简体   繁体   English

如何使用 SQLAlchemy 为 SQLite3 数据库创建索引?

[英]How to create index for a SQLite3 database using SQLAlchemy?

I have multiple SQLite3 databases for which the models are not available.我有多个模型不可用的 SQLite3 数据库。

def index_db(name, tempdb):
    print(f'{name.ljust(padding)} Indexing file: {tempdb}')

    if tempdb.endswith('primary.sqlite'):
        conn = sqlite3.connect(tempdb)
        conn.execute('CREATE INDEX packageSource ON packages (rpm_sourcerpm)')
        conn.commit()
        conn.close()

How can I perform the same operation using SQLAlchemy?如何使用 SQLAlchemy 执行相同的操作?

I can come up with two ways to add that index through SQLAlchemy:我可以想出两种方法来通过 SQLAlchemy 添加该索引:

  • if you do not reflect, execute the SQL statement directly如果不反映,直接执行SQL语句
  • if you reflect you table/model, add an index to it如果您反映您的表/模型,请为其添加索引

Firstly, let's create the table to work on.首先,让我们创建要处理的表。

import sqlite3

con = sqlite3.connect("/tmp/73526761.db")
con.execute("CREATE TABLE t73526761 (id INT PRIMARY KEY, name VARCHAR)")
con.commit()
con.close()

Then, without reflecting, you can execute your raw SQL with the following.然后,无需反射,您可以使用以下代码执行原始 SQL。

import sqlalchemy as sa

engine = sa.create_engine("sqlite:////tmp/73526761.db", future=True)

with engine.begin() as con:
    con.execute(sa.text("CREATE INDEX t73526761_name_idx ON t73526761 (name)"))
    con.commit()

Or if you reflect the table only (SQLAlchemy core):或者,如果您仅反映表(SQLAlchemy 核心):

import sqlalchemy as sa

metadata_obj = sa.MetaData()

engine = sa.create_engine("sqlite:////tmp/73526761.db", future=True)

t73526761 = sa.Table("t73526761", metadata_obj, autoload_with=engine)

t73526761_name_idx = sa.Index("t73526761_name_idx", t73526761.c.name)

t73526761_name_idx.create(bind=engine) # emits CREATE INDEX t73526761_name_idx ON t73526761 (name)

Or if you reflect the model (SQLAlchemy orm):或者,如果您反映 model(SQLAlchemy orm):

import sqlalchemy as sa
from sqlalchemy import orm

Base = orm.declarative_base()

engine = sa.create_engine("sqlite:////tmp/73526761.db", future=True)


class K73526761(Base):
    __table__ = sa.Table("t73526761", Base.metadata, autoload_with=engine)


t73526761_name_idx = sa.Index("t73526761_name_idx", K73526761.name)

t73526761_name_idx.create(bind=engine) # emits CREATE INDEX t73526761_name_idx ON t73526761 (name)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM