|
2 | 2 |
|
3 | 3 | import structlog |
4 | 4 | from sqlalchemy import Dialect, Engine, String, TypeDecorator, create_engine, text |
5 | | -from sqlalchemy.orm import DeclarativeBase |
| 5 | +from sqlalchemy.orm import DeclarativeBase, sessionmaker |
6 | 6 |
|
7 | 7 | logger = structlog.getLogger(__name__) |
8 | 8 |
|
@@ -37,10 +37,19 @@ def make_tables(engine: Engine) -> None: |
37 | 37 | # tag IDs < 1000 are reserved |
38 | 38 | # create tag and delete it to bump the autoincrement sequence |
39 | 39 | # TODO - find a better way |
40 | | - with engine.connect() as conn: |
41 | | - conn.execute(text("INSERT INTO tags (id, name, color) VALUES (999, 'temp', 1)")) |
42 | | - conn.execute(text("DELETE FROM tags WHERE id = 999")) |
43 | | - conn.commit() |
| 40 | + # is this the better way? |
| 41 | + Session = sessionmaker(bind=engine) # noqa: N806 |
| 42 | + session = Session() |
| 43 | + result = session.execute(text("SELECT SEQ FROM sqlite_sequence WHERE name='tags'")) |
| 44 | + autoincrement_val = result.fetchone() |
| 45 | + if autoincrement_val: |
| 46 | + # fetchone returns a tuple even when there is only one value |
| 47 | + autoincrement_val = autoincrement_val[0] |
| 48 | + if not autoincrement_val or autoincrement_val < 1000: |
| 49 | + with engine.connect() as conn: |
| 50 | + conn.execute(text("INSERT INTO tags (id, name, color) VALUES (999, 'temp', 1)")) |
| 51 | + conn.execute(text("DELETE FROM tags WHERE id = 999")) |
| 52 | + conn.commit() |
44 | 53 |
|
45 | 54 |
|
46 | 55 | def drop_tables(engine: Engine) -> None: |
|
0 commit comments