improved handling of empty DB; "tables,py" now contains verbatim code from sqlacodegen, eliminating the need for code reformatting

This commit is contained in:
eclipse 2025-07-17 09:45:23 +02:00
parent a607b8c4f3
commit 93198254f6
2 changed files with 49 additions and 40 deletions

View File

@ -5,14 +5,21 @@ db = SQLAlchemy()
def init_db(app):
db.init_app(app)
with app.app_context():
print(f"number of db tables is {len(db.metadata.tables)}")
# populate an empty DB with fresh tables
#TODO: maybe add tables to metadata in any case since tables won't get overwritten
# check if database is empty and if so, populate it with fresh tables
#TODO: does it make sense to try and create all tables by default? Existing tables wouldn't be overwritten but what about DB constraints ?
if not len(db.metadata.tables):
from the_works.tables import add_tables
add_tables(db.metadata)
db.metadata.create_all(db.engine)
print(f"and now number of db tables is {len(db.metadata.tables)}")
# import table classes from code that was generated via `sqlacodegen --generator tables sqlite:///the_works.sqlite > ./the_works/tables.py` in project root
import the_works.tables
# filter the objects just imported for those of type sqlalchemy.Table
from sqlalchemy import Table
table_list = list(filter(lambda t: type(t) == Table, vars(the_works.tables).values()))
# Table objects imported from sqlacodegen code are associated with a random MetaData() object, so we have to re-associate them with the DB's metadata
table_list = list(map(lambda t: t.to_metadata(db.metadata), table_list))
# create tables in DB )
db.metadata.create_all(db.engine)
# generate declarative table objects by reflecting the DB
db.reflect()

View File

@ -1,8 +1,10 @@
# File content is based on the output of `sqlacodegen --generator tables sqlite:///path/to/the_works.sqlite`
# file created via `sqlacodegen --generator tables sqlite:///path/to/the_works.sqlite > tables.py`
from sqlalchemy import Column, ForeignKey, Integer, LargeBinary, MetaData, Table, Text
def add_tables(metadata):
metadata = MetaData()
t_Genre = Table(
'Genre', metadata,
Column('ID', Integer, primary_key=True),