From 75c05f6e25d8aa6e0f9b64a83a8c0511ea90fa68 Mon Sep 17 00:00:00 2001 From: Roland Date: Sun, 17 Aug 2025 11:00:38 -0600 Subject: [PATCH] Adding db trigger for file_group.effective_datetime. --- ...48f6e_file_group_effective_date_trigger.py | 47 +++++++++++++++++++ wrolpi/files/models.py | 3 +- 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 alembic/versions/4f03b9548f6e_file_group_effective_date_trigger.py diff --git a/alembic/versions/4f03b9548f6e_file_group_effective_date_trigger.py b/alembic/versions/4f03b9548f6e_file_group_effective_date_trigger.py new file mode 100644 index 00000000..61945eaa --- /dev/null +++ b/alembic/versions/4f03b9548f6e_file_group_effective_date_trigger.py @@ -0,0 +1,47 @@ +"""file_group.effective_date trigger + +Revision ID: 4f03b9548f6e +Revises: 54c19aa847da +Create Date: 2025-08-17 10:49:35.754548 + +""" +import os +from alembic import op +from sqlalchemy.orm import Session + +# revision identifiers, used by Alembic. +revision = '4f03b9548f6e' +down_revision = '54c19aa847da' +branch_labels = None +depends_on = None + + +def upgrade(): + # Create trigger function + op.execute(""" + CREATE OR REPLACE FUNCTION update_effective_datetime() + RETURNS TRIGGER AS + $$ + BEGIN + NEW.effective_datetime = COALESCE(NEW.published_datetime, NEW.download_datetime); + RETURN NEW; + END; + $$ LANGUAGE plpgsql; + """) + + # Create trigger + op.execute(""" + CREATE TRIGGER file_group_effective_datetime_trigger + BEFORE INSERT OR UPDATE OF published_datetime, download_datetime + ON file_group + FOR EACH ROW + EXECUTE FUNCTION update_effective_datetime(); + """) + + +def downgrade(): + # Drop trigger + op.execute("DROP TRIGGER IF EXISTS file_group_effective_datetime_trigger ON file_group") + + # Drop trigger function + op.execute("DROP FUNCTION IF EXISTS update_effective_datetime") diff --git a/wrolpi/files/models.py b/wrolpi/files/models.py index f2149beb..489793c4 100644 --- a/wrolpi/files/models.py +++ b/wrolpi/files/models.py @@ -87,7 +87,8 @@ class FileGroup(ModelHelper, Base): url = Column(String) # the location where this file can be downloaded. viewed = Column(TZDateTime) # the most recent time a User viewed this file. - # See `update_effective_datetime` + # Columns updated by triggers. + # `file_group_effective_datetime_trigger` and `update_effective_datetime` event handler effective_datetime = Column(TZDateTime) # Equivalent to COALESCE(published_datetime, download_datetime) tag_files: Iterable[TagFile] = relationship('TagFile', cascade='all')