From 338d9612849075a494f44791e19e55291f1d1cd5 Mon Sep 17 00:00:00 2001 From: Roland Date: Sat, 16 Aug 2025 11:13:45 -0600 Subject: [PATCH] Adding file_group.effective_datetime to speed up video and archive browsing. --- ...8973fda20f_lower_filegroup_primary_path.py | 26 +++++++++++++ ...e9754d1a63_filegroup_effective_datetime.py | 37 +++++++++++++++++++ modules/archive/lib.py | 25 +++++++------ modules/videos/video/lib.py | 6 +-- wrolpi/files/models.py | 11 +++++- 5 files changed, 89 insertions(+), 16 deletions(-) create mode 100644 alembic/versions/158973fda20f_lower_filegroup_primary_path.py create mode 100644 alembic/versions/69e9754d1a63_filegroup_effective_datetime.py diff --git a/alembic/versions/158973fda20f_lower_filegroup_primary_path.py b/alembic/versions/158973fda20f_lower_filegroup_primary_path.py new file mode 100644 index 00000000..850d12bc --- /dev/null +++ b/alembic/versions/158973fda20f_lower_filegroup_primary_path.py @@ -0,0 +1,26 @@ +"""Lower FileGroup.primary_path + +Revision ID: 158973fda20f +Revises: 69e9754d1a63 +Create Date: 2025-08-16 10:54:58.874094 + +""" +import os +from alembic import op +from sqlalchemy.orm import Session + +# revision identifiers, used by Alembic. +revision = '158973fda20f' +down_revision = '69e9754d1a63' +branch_labels = None +depends_on = None + +DOCKERIZED = True if os.environ.get('DOCKER', '').lower().startswith('t') else False + + +def upgrade(): + op.execute('CREATE INDEX file_group_primary_path_lower_idx ON file_group (LOWER(primary_path))') + + +def downgrade(): + op.execute('DROP INDEX IF EXISTS file_group_primary_path_lower_idx') diff --git a/alembic/versions/69e9754d1a63_filegroup_effective_datetime.py b/alembic/versions/69e9754d1a63_filegroup_effective_datetime.py new file mode 100644 index 00000000..d4bd15ca --- /dev/null +++ b/alembic/versions/69e9754d1a63_filegroup_effective_datetime.py @@ -0,0 +1,37 @@ +"""FileGroup.effective_datetime + +Revision ID: 69e9754d1a63 +Revises: f7229a67e333 +Create Date: 2025-08-16 10:28:42.661108 + +""" +import os +from alembic import op +from sqlalchemy.orm import Session + +# revision identifiers, used by Alembic. +revision = '69e9754d1a63' +down_revision = 'f7229a67e333' +branch_labels = None +depends_on = None + +DOCKERIZED = True if os.environ.get('DOCKER', '').lower().startswith('t') else False + + +def upgrade(): + op.execute('ALTER TABLE file_group ADD COLUMN IF NOT EXISTS effective_datetime TIMESTAMPTZ') + + # Populating effective_datetime for existing rows + op.execute(""" + UPDATE file_group + SET effective_datetime = COALESCE(published_datetime, download_datetime) + WHERE published_datetime IS NOT NULL + OR download_datetime IS NOT NULL; + """) + + op.execute('CREATE INDEX IF NOT EXISTS file_group_effective_datetime_idx ON file_group(effective_datetime)') + + +def downgrade(): + op.execute('DROP INDEX IF EXISTS file_group_effective_datetime_idx') + op.execute('ALTER TABLE file_group DROP COLUMN IF EXISTS effective_datetime') diff --git a/modules/archive/lib.py b/modules/archive/lib.py index 7a2198f9..681fabaa 100644 --- a/modules/archive/lib.py +++ b/modules/archive/lib.py @@ -429,21 +429,22 @@ def is_singlefile_file(path: pathlib.Path) -> bool: def get_domains(): with get_db_curs() as curs: stmt = ''' - SELECT domains.domain AS domain, COUNT(a.id) AS url_count, SUM(fg.size)::BIGINT AS size - FROM domains - LEFT JOIN archive a on domains.id = a.domain_id - LEFT JOIN file_group fg on fg.id = a.file_group_id - GROUP BY domains.domain - ORDER BY domains.domain - ''' + SELECT domains.domain AS domain, COUNT(a.id) AS url_count, SUM(fg.size)::BIGINT AS size + FROM domains + LEFT JOIN archive a on domains.id = a.domain_id + LEFT JOIN file_group fg on fg.id = a.file_group_id + GROUP BY domains.domain + ORDER BY domains.domain \ + ''' curs.execute(stmt) domains = [dict(i) for i in curs.fetchall()] return domains ARCHIVE_ORDERS = { - 'published_datetime': (date := 'COALESCE(fg.published_datetime, fg.download_datetime) ASC NULLS LAST'), - '-published_datetime': (_date := 'COALESCE(fg.published_datetime, fg.download_datetime) DESC NULLS LAST'), + # Sometimes we don't have a published_datetime. This is equivalent to COALESCE(fg.published_datetime, fg.download_datetime) + 'published_datetime': (date := 'fg.effective_datetime ASC NULLS LAST'), + '-published_datetime': (_date := 'fg.effective_datetime DESC NULLS LAST'), 'published_modified_datetime': f'fg.published_modified_datetime ASC NULLS LAST, {date}', '-published_modified_datetime': f'fg.published_modified_datetime DESC NULLS LAST, {_date}', 'download_datetime': 'fg.download_datetime ASC NULLS LAST', @@ -456,8 +457,8 @@ ARCHIVE_ORDERS = { '-viewed': 'fg.viewed DESC', } ORDER_GROUP_BYS = { - 'published_datetime': 'fg.published_datetime, fg.download_datetime', - '-published_datetime': 'fg.published_datetime, fg.download_datetime', + 'published_datetime': 'fg.effective_datetime', + '-published_datetime': 'fg.effective_datetime', 'published_modified_datetime': 'fg.published_modified_datetime, fg.published_datetime, fg.download_datetime', '-published_modified_datetime': 'fg.published_modified_datetime, fg.published_datetime, fg.download_datetime', 'download_datetime': 'fg.download_datetime', @@ -482,7 +483,7 @@ def search_archives(search_str: str, domain: str, limit: int, offset: int, order -> Tuple[List[dict], int]: # Always filter FileGroups to Archives. wheres = [] - group_by = 'fg.published_datetime, fg.download_datetime, a.file_group_id' + group_by = 'fg.effective_datetime, a.file_group_id' params = dict(search_str=search_str, offset=int(offset), limit=int(limit)) order_by = ARCHIVE_ORDERS['-published_datetime'] diff --git a/modules/videos/video/lib.py b/modules/videos/video/lib.py index 5080031a..01ce3073 100644 --- a/modules/videos/video/lib.py +++ b/modules/videos/video/lib.py @@ -47,9 +47,9 @@ def get_video(video_id: int) -> Video: VIDEO_ORDERS = { - 'published_datetime': 'COALESCE(fg.published_datetime, fg.download_datetime) ASC, LOWER(fg.primary_path) ASC', - '-published_datetime': 'COALESCE(fg.published_datetime, fg.download_datetime) DESC NULLS LAST,' - ' LOWER(fg.primary_path) ASC', + # Sometimes we don't have a published_datetime. This is equivalent to COALESCE(fg.published_datetime, fg.download_datetime) + 'published_datetime': 'fg.effective_datetime ASC, LOWER(fg.primary_path) ASC', + '-published_datetime': 'fg.effective_datetime DESC NULLS LAST, LOWER(fg.primary_path) ASC', 'rank': '2 DESC, LOWER(fg.primary_path) DESC', '-rank': '2 ASC, LOWER(fg.primary_path) ASC', 'size': 'fg.size ASC, LOWER(fg.primary_path) ASC', diff --git a/wrolpi/files/models.py b/wrolpi/files/models.py index 79120097..f2149beb 100644 --- a/wrolpi/files/models.py +++ b/wrolpi/files/models.py @@ -6,7 +6,7 @@ from datetime import datetime from functools import singledispatchmethod from typing import List, Type, Optional, Iterable -from sqlalchemy import Column, String, Computed, BigInteger, Boolean +from sqlalchemy import Column, String, Computed, BigInteger, Boolean, event from sqlalchemy import types from sqlalchemy.orm import deferred, relationship, Session @@ -87,6 +87,9 @@ 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` + effective_datetime = Column(TZDateTime) # Equivalent to COALESCE(published_datetime, download_datetime) + tag_files: Iterable[TagFile] = relationship('TagFile', cascade='all') a_text = deferred(Column(String)) @@ -540,6 +543,12 @@ class FileGroup(ModelHelper, Base): raise +@event.listens_for(FileGroup, 'before_insert') +@event.listens_for(FileGroup, 'before_update') +def update_effective_datetime(mapper, connection, target): + target.effective_datetime = target.published_datetime or target.download_datetime + + class Directory(ModelHelper, Base): """A representation of a file directory in the media directory.""" __tablename__ = 'directory'