How to create index for a SQLite3 database using SQLAlchemy?

2024/10/6 9:49:56

I have multiple SQLite3 databases for which the models are not available.

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?

Answer

I can come up with two ways to add that index through SQLAlchemy:

  • if you do not reflect, execute the SQL statement directly
  • if you reflect you table/model, add an index to it

Firstly, let's create the table to work on.

import sqlite3con = 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.

import sqlalchemy as saengine = 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):

import sqlalchemy as sametadata_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):

import sqlalchemy as sa
from sqlalchemy import ormBase = 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)
https://en.xdnf.cn/q/119977.html

Related Q&A

Implementing ast.literal_eval on a numpy array

With the following expression, you can convert a string to a python dict.>>> import ast >>> a = ast.literal_eval("{muffin : lolz, foo : kitty}") >>> a {muffin: lolz…

Best way to make argument parser accept absolute number and percentage?

I am trying to write a Nagios style check to use with Nagios. I have working script that takes in something like -w 15 -c 10 and interprets that as "Warning at 15%, Critical at 10%". But I ju…

Python calculating prime numbers

I have to define a function called is_prime that takes a number x as input, then for each number n from 2 to x - 1, test if x is evenly divisible by n. If it is, return False. If none of them are, then…

Why am I getting a column does not exist error when it does exist? I am modifying the Flask tutorial

I have a column named ticker_symbol, but I am getting a error when I run the error that there is no such column. Here is my auth.py code so far. It is similar to the Flask tutorial code. I get my get_d…

Update Key Value In Python In JSON File

How do I change a value in a json file with python? I want to search and find "class": "DepictionScreenshotsView" and replace it with "class": ""JSON File:{&quo…

Getting UnboundLocalError: local variable age referenced before assignment error

Ive written a simple script with TKinter and SQLAlchemy, where an sqlite .db is created, saving Employee information such as name, age, address, etc, etc.I realized that if a user puts a string in the …

Cannot run python script [duplicate]

This question already has answers here:What does "SyntaxError: Missing parentheses in call to print" mean in Python?(11 answers)Closed 9 years ago.I am trying to run this python script:https…

I want to read multiple audio files with librosa and then save it into an empty list

Here id my code . when I append into the array the array remain empty . Please help me where is the mistake. Or tell me some other way also to do thisA = [] # load more files with librosa pathAudio = …

How to db.execute in postgresql using the LIKE operator with variables within flask [duplicate]

This question already has an answer here:CS50: LIKE operator, variable substitution with % expansion(1 answer)Closed 4 years ago.Im trying to get my db.execute to work but encounter a syntax error when…

C, Perl, and Python similar loops different results

I wrote scripts to calculate pi in python, perl and c. They all use the same algorithm (trapezoidal reimann sum of a circle with n subintervals) and the python and perl programs always get the same re…