Adding file_group.effective_datetime to speed up video and archive browsing.
Some checks are pending
CodeQL / Analyze (push) Waiting to run

This commit is contained in:
Roland 2025-08-16 11:13:45 -06:00 • committed by lrnselfreliance
parent cff827383e
commit 338d961284
5 changed files with 89 additions and 16 deletions

View file

@ -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')

View file

@ -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')

View file

@ -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']

View file

@ -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',

View file

@ -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'