wrolpi/wrolpi/schema_ddl.py
lrnselfreliance 20be5dfc27
collections: channel and domain listings read trigger-maintained summary columns (#739)
* collections: channel listing reads trigger columns and batch-loads tag/downloads

Listing channel collections summed FileGroup sizes through a video join, which reads a
random page of the file_group table per video, and lazy-loaded every collection's tag
and downloads one query at a time. On a large library with a cold disk cache the
listing took over two minutes, past the browser's 60 s timeout, so the Channels page
showed an error.

channel.video_count and channel.total_size are already maintained by triggers
(wrolpi/schema_ddl.py), so read those. Tag and downloads are selectin-loaded, so the
query count no longer grows with the number of collections.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* collections: domain listing reads trigger-maintained summary columns

Domain Collections summed file_group.size through an archive join on every listing,
one random page read per archive (about 9 s from a cold disk cache on a large
library). New triggers keep collection.item_count and collection.total_size current
for Domain Collections, as the channel triggers already do for Channels, and the
listing reads those columns. A migration installs the triggers and backfills
existing Domain Collections.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-27 11:36:08 -06:00

188 lines
8.3 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]:
conn.execute(statement)