Skip to content

Instantly share code, notes, and snippets.

@michaelwooley
Created January 26, 2023 01:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaelwooley/9bee3847cb20dd19241e133839d743f7 to your computer and use it in GitHub Desktop.
Save michaelwooley/9bee3847cb20dd19241e133839d743f7 to your computer and use it in GitHub Desktop.
Simple insert statement autogen for sqlalchemy
SELECT
m.name,
(
'INSERT INTO ' || m.name || '(' || GROUP_CONCAT (p.name, ', ') || ')VALUES(' || GROUP_CONCAT (
(
CASE
WHEN p.pk
AND m.sql LIKE "%AUTOINCREMENT%" THEN 'NULL'
ELSE ':' || p.name
END
),
', '
) || ');'
) AS stmt
FROM
sqlite_master m
LEFT OUTER JOIN pragma_table_info ((m.name)) p ON m.name <> p.name
WHERE
m.type = 'table'
AND m.name NOT LIKE "sqlite_%"
GROUP BY
m.name;
from sqlalchemy import create_engine
SELECT_INSERT_STATEMENTS = '''SELECT m.name, ( 'INSERT INTO ' || m.name || '(' || GROUP_CONCAT (p.name, ', ') || ')VALUES(' || GROUP_CONCAT ( ( CASE WHEN p.pk AND m.sql LIKE "%AUTOINCREMENT%" THEN 'NULL' ELSE ':' || p.name END ), ', ' ) || ');' ) AS stmt FROM sqlite_master m LEFT OUTER JOIN pragma_table_info ((m.name)) p ON m.name <> p.name WHERE m.type = 'table' AND m.name NOT LIKE "sqlite_%" GROUP BY m.name;'''
# GOOD Example file: https://github.com/codecrafters-io/sample-sqlite-databases/blob/master/sample.db
DB_FILEPATH = ... # "~/Downloads/sample.db"
engine = create_engine(DB_FILEPATH, echo=False)
with engine.begin() as conn:
insert_statements = {el['name']: el['insert'] for el in conn.execute(select_insert_statements).mappings().all()}
print(insert_statements)
# {
# "apples": "INSERT INTO apples(id, name, color) VALUES(NULL, :name, :color);",
# "oranges": "INSERT INTO oranges(id, name, description) VALUES(NULL, :name, :description);"
# }
with engine.begin() as conn:
conn.execute(
insert_statements["apple"],
[
{"name": "a", "color": "red"},
{"name": "b", "color": "green"},
],
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment