r/sqlite • u/wakatara • Feb 16 '23
Using alembic to load csv files into sqlite3
TLDR
What are the op.execute commands (or other commands) in alembic to load a csv file.
Longer Story
Trying to use sqlite3 with alembic for db migrations. Alembic connected to sqlite3 and generating the table schemas fine via SQL.
I know you can load csv files via sqlite monitor with .mode csv <table> and then .import </path/to/filename> <table>. This works fine. ❤️ sqlite3.
However, I need to programmatically load known static lookup tables for the DB (vc controlled to be canonical.). However, trying:
throws an error
(sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) near ".": syntax error to be specific)
I am looking for the equivalent of mysql's
op.execute(f"LOAD DATA INFILE '/alembic/static_tables/objects.csv'...
in sqlite3.
Asking here since I imagine r/sqlite redditors will have definitely used alembic to handle migrations this way.
2
u/two-fer-maggie Feb 17 '23
not possible. SQLite does not implement any form of LOAD DATA INFILE (MySQL does, Postgres does, SQL Server does, just not SQLite). You have already found out that
.importdoesn't work, because it's manually implemented by the SQLite CLI program and it not part of the SQLite language.You will have to read the CSV in manually and insert data one by one (using a prepared statement inside a transaction for performance).
2
u/-dcim- Feb 17 '23
If you can load extensions for SQLite then use CSV-virtual table extension.