wrolpi/wrolpi/schema_ddl.py
lrnselfreliance dab333124e
Upgrade to SQLAlchemy 2.0 (synchronous) (#803)
SQLAlchemy 1.3 has been end-of-life since 2021, and alembic was held at 1.10
because newer releases need SQLAlchemy 2.  This is a mechanical port; the code
stays synchronous.

- SQLAlchemy[asyncio]==2.0.54, alembic==1.20.0.
- Model annotations use Mapped[...] (2.0 rejects bare annotations on mapped
  attributes); declarative_base moves to sqlalchemy.orm.
- Plain SQL strings go through text() or exec_driver_sql; schema_ddl.execute_sql
  accepts a SQLAlchemy Connection or a raw sqlite3 connection, so rebuild_fts
  works from the baseline migration again.
- Session.get replaces Query.get; session.in_transaction() replaces
  session.transaction; cache_ok on MediaPathType and FancyJSON.
- The tag-directory sync query joins through TagFile's relationships instead of
  the legacy two-entity outerjoin.
- Section-hint rows use attribute access (2.0 rows are tuples).
- Migrations run on an AUTOCOMMIT connection, matching 1.3, where each
  statement committed on its own.  2.0 autobegins, so the unique-stem
  migration's read snapshot could not become a writer after its helpers wrote
  on another connection ("database is locked").  The begin listener emits no
  BEGIN for AUTOCOMMIT connections.
- Newer alembic compares column types: WrolpiKV now describes the TEXT table
  its migration created.
- The test database installs its DDL inside engine.begin(); 2.0 connections
  no longer autocommit, so the FTS tables were rolled back.
- Dependabot now holds SQLAlchemy at 2.0 instead of 1.3.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 15:08:40 -06:00

205 lines
8.9 KiB
Python

"""Raw SQLite DDL shared by the Alembic baseline and the test database.
SQLAlchemy models (`Base.metadata`) define the tables; this module holds everything the models
cannot express: triggers and the FTS5 full-text-search tables (see `wrolpi.fts`).
`install_raw_ddl` is executed by BOTH:
* the Alembic baseline migration (production databases), and
* `wrolpi.conftest.test_db` (test databases, after `Base.metadata.create_all`),
so tests exercise exactly the schema production runs.
All statements are idempotent (IF NOT EXISTS).
"""
# Triggers maintaining the summary columns `channel.video_count`, `channel.total_size`,
# `channel.minimum_frequency`, `collection.item_count`/`collection.total_size` (domains) and
# `file_group.effective_datetime`.
#
# These are re-authored from the old PL/pgSQL triggers (see git history of alembic/versions/).
# The old triggers had known bugs which are fixed here:
# * video_count used NEW.channel_id on DELETE (always NULL in Postgres), so counts never
# decremented, and did not fire on UPDATE OF channel_id (re-parenting).
# * total_size used NEW.id (a video/file_group id) as the channel id.
TRIGGER_DDL = [
# channel.video_count + channel.total_size follow the videos in the channel.
'''
CREATE TRIGGER IF NOT EXISTS video_insert_channel_summary
AFTER INSERT ON video WHEN new.channel_id IS NOT NULL
BEGIN
UPDATE channel SET
video_count = (SELECT COUNT(*) FROM video WHERE channel_id = channel.id),
total_size = (SELECT COALESCE(SUM(fg.size), 0) FROM video v
LEFT JOIN file_group fg ON v.file_group_id = fg.id
WHERE v.channel_id = channel.id)
WHERE id = new.channel_id;
END
''',
'''
CREATE TRIGGER IF NOT EXISTS video_delete_channel_summary
AFTER DELETE ON video WHEN old.channel_id IS NOT NULL
BEGIN
UPDATE channel SET
video_count = (SELECT COUNT(*) FROM video WHERE channel_id = channel.id),
total_size = (SELECT COALESCE(SUM(fg.size), 0) FROM video v
LEFT JOIN file_group fg ON v.file_group_id = fg.id
WHERE v.channel_id = channel.id)
WHERE id = old.channel_id;
END
''',
# Re-parenting a video (or changing its FileGroup) updates both affected channels.
'''
CREATE TRIGGER IF NOT EXISTS video_update_channel_summary
AFTER UPDATE OF channel_id, file_group_id ON video
BEGIN
UPDATE channel SET
video_count = (SELECT COUNT(*) FROM video WHERE channel_id = channel.id),
total_size = (SELECT COALESCE(SUM(fg.size), 0) FROM video v
LEFT JOIN file_group fg ON v.file_group_id = fg.id
WHERE v.channel_id = channel.id)
WHERE id IN (old.channel_id, new.channel_id);
END
''',
# A FileGroup's size changed; update the Channel of the Video which owns it (if any).
'''
CREATE TRIGGER IF NOT EXISTS file_group_size_channel_summary
AFTER UPDATE OF size ON file_group WHEN old.size IS NOT new.size
BEGIN
UPDATE channel SET
total_size = (SELECT COALESCE(SUM(fg.size), 0) FROM video v
LEFT JOIN file_group fg ON v.file_group_id = fg.id
WHERE v.channel_id = channel.id)
WHERE id = (SELECT channel_id FROM video WHERE file_group_id = new.id);
END
''',
# collection.item_count + collection.total_size follow the Archives of a Domain Collection.
# (Channels keep their summary on the channel table; generic Collections count collection_item.)
'''
CREATE TRIGGER IF NOT EXISTS archive_insert_collection_summary
AFTER INSERT ON archive WHEN new.collection_id IS NOT NULL
BEGIN
UPDATE collection SET
item_count = (SELECT COUNT(*) FROM archive WHERE collection_id = collection.id),
total_size = (SELECT COALESCE(SUM(fg.size), 0) FROM archive a
LEFT JOIN file_group fg ON a.file_group_id = fg.id
WHERE a.collection_id = collection.id)
WHERE id = new.collection_id;
END
''',
'''
CREATE TRIGGER IF NOT EXISTS archive_delete_collection_summary
AFTER DELETE ON archive WHEN old.collection_id IS NOT NULL
BEGIN
UPDATE collection SET
item_count = (SELECT COUNT(*) FROM archive WHERE collection_id = collection.id),
total_size = (SELECT COALESCE(SUM(fg.size), 0) FROM archive a
LEFT JOIN file_group fg ON a.file_group_id = fg.id
WHERE a.collection_id = collection.id)
WHERE id = old.collection_id;
END
''',
'''
CREATE TRIGGER IF NOT EXISTS archive_update_collection_summary
AFTER UPDATE OF collection_id, file_group_id ON archive
BEGIN
UPDATE collection SET
item_count = (SELECT COUNT(*) FROM archive WHERE collection_id = collection.id),
total_size = (SELECT COALESCE(SUM(fg.size), 0) FROM archive a
LEFT JOIN file_group fg ON a.file_group_id = fg.id
WHERE a.collection_id = collection.id)
WHERE id IN (old.collection_id, new.collection_id);
END
''',
'''
CREATE TRIGGER IF NOT EXISTS file_group_size_collection_summary
AFTER UPDATE OF size ON file_group WHEN old.size IS NOT new.size
BEGIN
UPDATE collection SET
total_size = (SELECT COALESCE(SUM(fg.size), 0) FROM archive a
LEFT JOIN file_group fg ON a.file_group_id = fg.id
WHERE a.collection_id = collection.id)
WHERE id = (SELECT collection_id FROM archive WHERE file_group_id = new.id);
END
''',
# channel.minimum_frequency follows the Downloads of the Channel's Collection.
'''
CREATE TRIGGER IF NOT EXISTS download_insert_minimum_frequency
AFTER INSERT ON download WHEN new.collection_id IS NOT NULL
BEGIN
UPDATE channel SET
minimum_frequency = (SELECT MIN(frequency) FROM download
WHERE collection_id = channel.collection_id)
WHERE collection_id = new.collection_id;
END
''',
'''
CREATE TRIGGER IF NOT EXISTS download_update_minimum_frequency
AFTER UPDATE OF frequency, collection_id ON download
BEGIN
UPDATE channel SET
minimum_frequency = (SELECT MIN(frequency) FROM download
WHERE collection_id = channel.collection_id)
WHERE collection_id IN (old.collection_id, new.collection_id);
END
''',
'''
CREATE TRIGGER IF NOT EXISTS download_delete_minimum_frequency
AFTER DELETE ON download WHEN old.collection_id IS NOT NULL
BEGIN
UPDATE channel SET
minimum_frequency = (SELECT MIN(frequency) FROM download
WHERE collection_id = channel.collection_id)
WHERE collection_id = old.collection_id;
END
''',
# file_group.effective_datetime = COALESCE(published_datetime, download_datetime).
# Also maintained by an ORM event (wrolpi.files.models.update_effective_datetime); these
# triggers cover raw-SQL writers. The WHEN clause avoids rewriting rows the ORM already set.
'''
CREATE TRIGGER IF NOT EXISTS file_group_effective_datetime_insert
AFTER INSERT ON file_group
WHEN new.effective_datetime IS NOT COALESCE(new.published_datetime, new.download_datetime)
BEGIN
UPDATE file_group
SET effective_datetime = COALESCE(new.published_datetime, new.download_datetime)
WHERE id = new.id;
END
''',
'''
CREATE TRIGGER IF NOT EXISTS file_group_effective_datetime_update
AFTER UPDATE OF published_datetime, download_datetime ON file_group
WHEN new.effective_datetime IS NOT COALESCE(new.published_datetime, new.download_datetime)
BEGIN
UPDATE file_group
SET effective_datetime = COALESCE(new.published_datetime, new.download_datetime)
WHERE id = new.id;
END
''',
]
def install_raw_ddl(conn):
"""Install all raw DDL (triggers + FTS5) on a SQLite database.
`conn` may be a SQLAlchemy Connection (e.g. `op.get_bind()` in Alembic) or a raw
`sqlite3.Connection`. Idempotent."""
from wrolpi import fts
for statement in [*TRIGGER_DDL, *fts.FTS_DDL]:
execute_sql(conn, statement)
# DDL for tables created after the baseline migration (which also calls this function).
if _table_exists(conn, 'repository'):
for statement in fts.REPOSITORY_FTS_DDL:
execute_sql(conn, statement)
def execute_sql(conn, statement: str):
"""Execute a plain SQL string on a SQLAlchemy Connection or a raw `sqlite3.Connection`."""
if hasattr(conn, 'exec_driver_sql'):
return conn.exec_driver_sql(statement)
return conn.execute(statement)
def _table_exists(conn, name: str) -> bool:
sql = f"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = '{name}'"
return execute_sql(conn, sql).fetchone() is not None