mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-12-01 20:36:21 -05:00
Postgres -> SQLite hard cutover: the database moves into the media directory.
The database now lives at <media>/config/wrolpi.db so a library (files, configs, AND database) travels with the drive between WROLPi systems. Core: - wrolpi/db.py: lazy SQLite engine factory (WAL, busy_timeout=30s, foreign_keys=ON); get_db_curs yields a plain sqlite3.Cursor; native sqlite3 paramstyle everywhere (no compatibility shims); global sqlite3 adapters keep raw-SQL datetime formats identical to the ORM's. - wrolpi/fts.py: FTS5 external-content search replacing tsvector/GIN. Injection-proof websearch->FTS5 translator, bm25(10,4,2,1) reproducing A/B/C/D weighting, fast(abc)/deep column filtering, snippet headlines. Stemming contract pinned by dedicated tests (watch/watches/watched/ watching are interchangeable). - wrolpi/schema_ddl.py: SQLite triggers shared verbatim by the alembic baseline and test DBs; fixes the channel video_count DELETE/UPDATE bugs and a latent total_size bug (it used the video id as channel id). - wrolpi/db_bootstrap.py: startup auto-create/migrate; refuses databases written by a newer WROLPi (db_version_mismatch); SQLite 3.40 floor; network-filesystem refusal; never creates/migrates/trusts a database beneath an unmounted production media directory (shadow-DB guard). - Alembic: 85 Postgres-era migrations squashed into one baseline; revision ids are dates (2026_07_10_1350) so filenames self-sort and alembic_version says when a schema was created; render_as_batch=True. - All raw Postgres SQL rewritten (ANY->json_each IN, array_agg @> -> HAVING COUNT(DISTINCT), unnest->executemany/UPDATE..FROM, generate_series histograms->strftime GROUP BY, DISTINCT ON-> row_number(), writable CTEs->two statements, jsonb_*->json_*, explicit NULLS FIRST/LAST, LIMIT-before-OFFSET). Simple statements converted to SQLAlchemy instead (flag upsert, download retry/summary/tag checks, channel-by-tag estimate, Directory delete). - Config imports count skipped entries; background dumps are blocked after a lossy import so partial imports can never overwrite YAML configs (they are the sole source of truth for rebuilds now). - Search tolerates explicit JSON nulls for limit/offset (Postgres treated OFFSET NULL as 0; SQLite errors). - file_group.id/doc_section.id render as INTEGER PRIMARY KEY on SQLite (BIGINT is not a rowid alias; FTS5 content_rowid requires it). Ops teardown: docker-compose db service, CI postgres sidecars, initialize_api_db.sh, controller postgresql service, psycopg2-binary all removed. upgrade.sh stops/disables postgresql (data is NOT deleted; `systemctl enable --now postgresql` restores it); systemd units no longer Want postgresql.service. Existing-user upgrade: first boot creates+migrates the DB, configs import (tags recreate their FileGroups from disk), a refresh rebuilds the library index. QA'd on the 10.0.0.8 RPi: rebuild matched the Postgres baseline exactly; survived an uncontrolled hard reboot with clean integrity checks. Accepted behavior changes: FTS5 has no stopwords; bm25 length normalization shifts some rank orders; fast-path d_headline is un-highlighted; all-negative queries match nothing. Deferred: Debian/trixie package lists (incl. sqlite3 CLI), Cypress re-baseline, VACUUM INTO snapshots, exFAT/NTFS warning, auto-kicked rebuild refresh with progress UX. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
parent
7da89d883e
commit
d9303a0ea8
150 changed files with 2749 additions and 6833 deletions
|
|
@ -20,6 +20,7 @@ from sqlalchemy.orm import Session
|
|||
|
||||
from modules.archive.models import Archive
|
||||
from wrolpi import dates
|
||||
from wrolpi import fts
|
||||
from wrolpi.cmd import READABILITY_BIN, run_command
|
||||
from wrolpi.collections import Collection
|
||||
from wrolpi.common import get_media_directory, get_relative_to_media_directory, logger, extract_domain, \
|
||||
|
|
@ -120,6 +121,7 @@ class DomainsConfig(ConfigFile):
|
|||
name = collection_data.get('name')
|
||||
if not name:
|
||||
logger.error(f'Domain collection at index {idx} has no name, skipping')
|
||||
self.import_skipped += 1
|
||||
continue
|
||||
|
||||
# Validate domain name format before batching
|
||||
|
|
@ -128,6 +130,7 @@ class DomainsConfig(ConfigFile):
|
|||
f"Domain collection at index {idx} has invalid name '{name}' "
|
||||
f"(must contain at least one '.' and not start/end with '.'), skipping"
|
||||
)
|
||||
self.import_skipped += 1
|
||||
continue
|
||||
|
||||
# Ensure kind is 'domain'
|
||||
|
|
@ -140,6 +143,7 @@ class DomainsConfig(ConfigFile):
|
|||
valid_data_list.append(collection_data)
|
||||
except Exception as e:
|
||||
logger.error(f'Failed to validate domain collection at index {idx}', exc_info=e)
|
||||
self.import_skipped += 1
|
||||
continue
|
||||
|
||||
# Batch create/update collections
|
||||
|
|
@ -1344,10 +1348,10 @@ def get_domain(domain_id: int) -> dict:
|
|||
# Get archive statistics for this domain
|
||||
with get_db_curs() as curs:
|
||||
stmt = '''
|
||||
SELECT COUNT(a.id) AS url_count, SUM(fg.size)::BIGINT AS size
|
||||
SELECT COUNT(a.id) AS url_count, SUM(fg.size) AS size
|
||||
FROM archive a
|
||||
LEFT JOIN file_group fg on fg.id = a.file_group_id
|
||||
WHERE a.collection_id = %(domain_id)s
|
||||
WHERE a.collection_id = :domain_id
|
||||
'''
|
||||
curs.execute(stmt, {'domain_id': domain_id})
|
||||
stats = dict(curs.fetchone())
|
||||
|
|
@ -1377,20 +1381,6 @@ ARCHIVE_ORDERS = {
|
|||
'viewed': 'fg.viewed ASC',
|
||||
'-viewed': 'fg.viewed DESC',
|
||||
}
|
||||
ORDER_GROUP_BYS = {
|
||||
'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',
|
||||
'-download_datetime': 'fg.download_datetime',
|
||||
'rank': 'fg.published_datetime, fg.download_datetime',
|
||||
'-rank': 'fg.published_datetime, fg.download_datetime',
|
||||
'size': 'fg.size, fg.published_datetime, fg.primary_path',
|
||||
'-size': 'fg.size, fg.published_datetime, fg.primary_path',
|
||||
'viewed': 'fg.viewed',
|
||||
'-viewed': 'fg.viewed',
|
||||
}
|
||||
NO_NULL_ORDERS = {
|
||||
'viewed': 'fg.viewed IS NOT NULL',
|
||||
'-viewed': 'fg.viewed IS NOT NULL',
|
||||
|
|
@ -1404,26 +1394,40 @@ 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.effective_datetime, a.file_group_id'
|
||||
|
||||
params = dict(search_str=search_str, offset=int(offset), limit=int(limit))
|
||||
# Explicit JSON nulls bypass the schema defaults; SQLite rejects LIMIT/OFFSET NULL.
|
||||
params = dict(search_str=search_str, offset=int(offset) if offset else 0, limit=int(limit) if limit else 20)
|
||||
order_by = ARCHIVE_ORDERS['-published_datetime']
|
||||
|
||||
select_columns = ''
|
||||
if search_str:
|
||||
# A search_str was provided by the user, modify the query to filter by it.
|
||||
# `textsearch` includes d_text (page contents); `textsearch_abc` is much smaller and faster.
|
||||
ts_col = 'textsearch' if deep else 'textsearch_abc'
|
||||
select_columns = f'ts_rank(fg.{ts_col}, websearch_to_tsquery(%(search_str)s)) AS rank,' \
|
||||
' COUNT(*) OVER() AS total'
|
||||
wheres.append(f'fg.{ts_col} @@ websearch_to_tsquery(%(search_str)s)')
|
||||
params['search_str'] = search_str
|
||||
group_by = f'{group_by}, rank'
|
||||
fts_join = ''
|
||||
headline_columns = ''
|
||||
# The fast (deep=False) search only matches the a/b/c FTS columns; deep also matches d
|
||||
# (page contents). `file_group_search` returns None when the search string is unusable, in
|
||||
# which case we behave as if no search was requested.
|
||||
file_group_search = fts.file_group_search(search_str, deep=deep) if search_str else None
|
||||
if file_group_search:
|
||||
# A search_str was provided by the user, modify the query to filter by it. The rank and
|
||||
# snippets come from a subquery because FTS5 auxiliary functions (snippet) cannot appear
|
||||
# in a query that also uses window functions (COUNT(*) OVER()).
|
||||
headline_selects = fts.file_group_headline_selects() if headline else ''
|
||||
fts_join = f'''JOIN (
|
||||
SELECT fts.rowid AS id, {file_group_search.rank_select}{headline_selects}
|
||||
FROM file_group_fts fts
|
||||
WHERE {file_group_search.where}
|
||||
) fts ON fts.id = fg.id'''
|
||||
select_columns = 'fts.ts_rank AS ts_rank' # positive, higher is better.
|
||||
params.update(file_group_search.params)
|
||||
if headline:
|
||||
# b/c/d headlines come from the FTS index. `title` is not an FTS column; select it
|
||||
# plainly and highlight it in Python below.
|
||||
headline_columns = ''',
|
||||
fts.b_headline, fts.c_headline, fts.d_headline,
|
||||
fg.title AS title_headline'''
|
||||
|
||||
if order:
|
||||
try:
|
||||
order_by = ARCHIVE_ORDERS[order]
|
||||
group_by = f'{group_by}, {ORDER_GROUP_BYS[order]}'
|
||||
except KeyError:
|
||||
raise InvalidOrderBy(f'Invalid order byy {order}')
|
||||
if order in NO_NULL_ORDERS:
|
||||
|
|
@ -1431,41 +1435,40 @@ def search_archives(search_str: str, domain: str, limit: int, offset: int, order
|
|||
|
||||
wheres, params = tag_append_sub_select_where(wheres, params, tag_names)
|
||||
|
||||
if search_str and headline:
|
||||
headline = ''',
|
||||
ts_headline(fg.title, websearch_to_tsquery(%(search_str)s)) AS "title_headline",
|
||||
ts_headline(fg.b_text, websearch_to_tsquery(%(search_str)s)) AS "b_headline",
|
||||
ts_headline(fg.c_text, websearch_to_tsquery(%(search_str)s)) AS "c_headline",
|
||||
ts_headline(fg.d_text, websearch_to_tsquery(%(search_str)s)) AS "d_headline"'''
|
||||
group_by = f'{group_by}, title_headline, b_headline, c_headline, d_headline'
|
||||
else:
|
||||
headline = ''
|
||||
|
||||
if domain:
|
||||
params['domain'] = domain
|
||||
# Use LIMIT 1 to handle potential duplicate domain collections with the same name
|
||||
wheres.append(
|
||||
"a.collection_id = (select id from collection where collection.name = %(domain)s and collection.kind = 'domain' LIMIT 1)")
|
||||
"a.collection_id = (select id from collection where collection.name = :domain and collection.kind = 'domain' LIMIT 1)")
|
||||
|
||||
select_columns = f", {select_columns}" if select_columns else ""
|
||||
select_columns = f"{select_columns}," if select_columns else ""
|
||||
wheres = '\n AND '.join(wheres)
|
||||
where = f'WHERE\n{wheres}' if wheres else ''
|
||||
stmt = f'''
|
||||
SELECT
|
||||
a.file_group_id AS id, -- always get `file_group.id` for `handle_file_group_search_results`
|
||||
COUNT(*) OVER() AS total
|
||||
{select_columns}
|
||||
{headline}
|
||||
COUNT(*) OVER() AS total
|
||||
{headline_columns}
|
||||
FROM archive a
|
||||
LEFT JOIN file_group fg ON fg.id = a.file_group_id
|
||||
{fts_join}
|
||||
{where}
|
||||
GROUP BY {group_by}
|
||||
ORDER BY {order_by}
|
||||
OFFSET %(offset)s LIMIT %(limit)s
|
||||
LIMIT :limit OFFSET :offset
|
||||
'''.strip()
|
||||
logger.debug(stmt, params)
|
||||
logger.debug(f'{stmt} {params}')
|
||||
|
||||
results, total = handle_file_group_search_results(stmt, params)
|
||||
|
||||
if file_group_search and headline and results:
|
||||
# Highlight the plain titles like the FTS snippets above (Postgres used ts_headline).
|
||||
titles = [i.get('title_headline') for i in results]
|
||||
highlighted = fts.headline_texts(titles, search_str)
|
||||
for result, title, (title_headline, _) in zip(results, titles, highlighted):
|
||||
if title is not None:
|
||||
result['title_headline'] = title_headline
|
||||
|
||||
return results, total
|
||||
|
||||
|
||||
|
|
@ -1617,39 +1620,41 @@ async def get_statistics():
|
|||
curs.execute('''
|
||||
SELECT
|
||||
-- total archives
|
||||
COUNT(a.id) AS "archives",
|
||||
COUNT(a.id) AS "archives",
|
||||
-- total archives downloaded over the past week/month/year
|
||||
COUNT(a.id) FILTER (WHERE fg.download_datetime >= current_date - interval '1 week') AS "week",
|
||||
COUNT(a.id) FILTER (WHERE fg.download_datetime >= datetime('now', '-7 days')) AS "week",
|
||||
COUNT(a.id)
|
||||
FILTER (WHERE fg.download_datetime >= current_date - interval '1 month') AS "month",
|
||||
COUNT(a.id) FILTER (WHERE fg.download_datetime >= current_date - interval '1 year') AS "year",
|
||||
FILTER (WHERE fg.download_datetime >= datetime('now', '-1 month')) AS "month",
|
||||
COUNT(a.id) FILTER (WHERE fg.download_datetime >= datetime('now', '-1 year')) AS "year",
|
||||
-- sum of all archive file sizes
|
||||
COALESCE(SUM(fg.size), 0)::BIGINT AS "sum_size",
|
||||
COALESCE(SUM(fg.size), 0) AS "sum_size",
|
||||
-- largest archive
|
||||
COALESCE(MAX(fg.size), 0) AS "max_size"
|
||||
COALESCE(MAX(fg.size), 0) AS "max_size"
|
||||
FROM archive a
|
||||
LEFT JOIN file_group fg on a.file_group_id = fg.id
|
||||
''')
|
||||
archive_stats = dict(curs.fetchone())
|
||||
|
||||
# Get the total archives downloaded every month for the past two years.
|
||||
# Get the total archives downloaded every month for the past two years (excluding the
|
||||
# current month, like the old generate_series query).
|
||||
curs.execute('''
|
||||
SELECT DATE_TRUNC('month', months.a),
|
||||
COUNT(archive.id)::BIGINT,
|
||||
SUM(size)::BIGINT AS "size"
|
||||
FROM generate_series(
|
||||
date_trunc('month', current_date) - interval '2 years',
|
||||
date_trunc('month', current_date) - interval '1 month',
|
||||
'1 month'::interval) AS months(a),
|
||||
archive
|
||||
SELECT strftime('%Y-%m-01 00:00:00', fg.download_datetime) AS "date_trunc",
|
||||
COUNT(archive.id) AS "count",
|
||||
SUM(fg.size) AS "size"
|
||||
FROM archive
|
||||
LEFT JOIN file_group fg on archive.file_group_id = fg.id
|
||||
WHERE fg.download_datetime >= date_trunc('month', months.a)
|
||||
AND fg.download_datetime < date_trunc('month', months.a) + interval '1 month'
|
||||
AND fg.download_datetime IS NOT NULL
|
||||
WHERE fg.download_datetime IS NOT NULL
|
||||
AND fg.download_datetime >= datetime('now', 'start of month', '-24 months')
|
||||
AND fg.download_datetime < datetime('now', 'start of month')
|
||||
GROUP BY 1
|
||||
ORDER BY 1
|
||||
''')
|
||||
monthly_archives = [dict(i) for i in curs.fetchall()]
|
||||
monthly_archives = []
|
||||
for row in curs.fetchall():
|
||||
row = dict(row)
|
||||
# Convert the month strings back to datetimes so the JSON response shape is unchanged.
|
||||
row['date_trunc'] = datetime.strptime(row['date_trunc'], '%Y-%m-%d %H:%M:%S')
|
||||
monthly_archives.append(row)
|
||||
|
||||
historical_stats = dict(monthly_archives=monthly_archives)
|
||||
historical_stats['average_count'] = (sum(i['count'] for i in monthly_archives) // len(monthly_archives)) \
|
||||
|
|
|
|||
|
|
@ -75,9 +75,9 @@ async def test_archives_search(test_session, archive_directory, archive_factory,
|
|||
data = {'search_str': 'baz', 'domain': 'example.org', 'deep': True}
|
||||
await check_results(async_client, data, [3, ])
|
||||
|
||||
# 1's title contains "my", this is ignored by Postgres.
|
||||
# 1's title contains "my". Postgres ignored this stopword; FTS5 has no stopwords, so it matches.
|
||||
data = {'search_str': 'my', 'deep': True}
|
||||
await check_results(async_client, data, [])
|
||||
await check_results(async_client, data, [1, ])
|
||||
|
||||
# 3's title contains "third", found by the default (fast) search and the deep search.
|
||||
data = {'search_str': 'third'}
|
||||
|
|
|
|||
|
|
@ -1053,8 +1053,9 @@ def test_collection_unique_name_kind_constraint(test_directory, test_session, ar
|
|||
with pytest.raises(IntegrityError) as exc_info:
|
||||
test_session.commit()
|
||||
|
||||
# Verify it's the unique constraint violation
|
||||
assert 'uq_collection_name_kind' in str(exc_info.value)
|
||||
# Verify it's the unique constraint violation. SQLite reports the columns, not the
|
||||
# constraint name (Postgres reported 'uq_collection_name_kind').
|
||||
assert 'collection.name, collection.kind' in str(exc_info.value)
|
||||
test_session.rollback()
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -4,9 +4,10 @@ import pathlib
|
|||
import re
|
||||
from typing import List, Optional
|
||||
|
||||
from sqlalchemy import asc, desc, func, nullslast, text
|
||||
from sqlalchemy import asc, desc, func, nullslast, text, column, bindparam, Integer, Float
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from wrolpi import fts
|
||||
from wrolpi.collections.models import Collection
|
||||
from wrolpi.collections.types import collection_type_registry
|
||||
from wrolpi.db import get_db_session
|
||||
|
|
@ -351,14 +352,21 @@ def _search_docs(search_str=None, author=None, subject=None, language=None, mime
|
|||
from .models import Doc
|
||||
from wrolpi.files.models import FileGroup
|
||||
|
||||
# `textsearch` includes d_text (document contents); `textsearch_abc` is much smaller and faster.
|
||||
ts_col = FileGroup.textsearch if deep else FileGroup.textsearch_abc
|
||||
# Deep search matches all FTS columns (including d_text, the document contents); the default matches only
|
||||
# the much smaller a/b/c columns.
|
||||
match = fts.translate_websearch(search_str, None if deep else fts.ABC_COLUMNS) if search_str else None
|
||||
|
||||
with get_db_session() as session:
|
||||
query = session.query(FileGroup).join(Doc, Doc.file_group_id == FileGroup.id)
|
||||
|
||||
if search_str:
|
||||
query = query.filter(ts_col.op('@@')(func.websearch_to_tsquery(search_str)))
|
||||
fts_sq = None
|
||||
if match is not None:
|
||||
fts_sq = text('SELECT rowid AS id, -rank AS ts_rank'
|
||||
' FROM file_group_fts WHERE file_group_fts MATCH :fts_match') \
|
||||
.bindparams(fts_match=match) \
|
||||
.columns(column('id', Integer), column('ts_rank', Float)) \
|
||||
.alias('fts')
|
||||
query = query.join(fts_sq, fts_sq.c.id == FileGroup.id)
|
||||
|
||||
if author:
|
||||
query = query.filter(FileGroup.b_text.ilike(f'%{author}%'))
|
||||
|
|
@ -383,9 +391,9 @@ def _search_docs(search_str=None, author=None, subject=None, language=None, mime
|
|||
total = query.count()
|
||||
|
||||
# Ordering.
|
||||
if order_by == 'rank' and search_str:
|
||||
if order_by == 'rank' and fts_sq is not None:
|
||||
query = query.order_by(
|
||||
desc(func.ts_rank(ts_col, func.websearch_to_tsquery(search_str))),
|
||||
desc(fts_sq.c.ts_rank),
|
||||
desc(FileGroup.id),
|
||||
)
|
||||
elif order_by == 'published_datetime':
|
||||
|
|
@ -416,26 +424,35 @@ def _fetch_section_hints(session, file_group_ids, search_str):
|
|||
|
||||
Returns a mapping of file_group_id -> {kind, ordinal, label, snippet}.
|
||||
"""
|
||||
from .models import Doc, DocSection
|
||||
|
||||
if not file_group_ids:
|
||||
return {}
|
||||
|
||||
match = fts.translate_websearch(search_str)
|
||||
if match is None:
|
||||
return {}
|
||||
|
||||
# FTS5 auxiliary functions (snippet, rank) must be evaluated in the innermost SELECT that scans the
|
||||
# FTS table; the window function must live in a separate outer layer.
|
||||
sql = text('''
|
||||
SELECT DISTINCT ON (d.file_group_id)
|
||||
d.file_group_id AS fg_id,
|
||||
ds.kind AS kind,
|
||||
ds.ordinal AS ordinal,
|
||||
ds.label AS label,
|
||||
ts_headline('english', ds.content, q,
|
||||
'MaxWords=20,MinWords=5,ShortWord=3,StartSel=[[WROLPI_HL]],StopSel=[[/WROLPI_HL]]') AS snippet
|
||||
FROM doc_section ds
|
||||
JOIN doc d ON d.id = ds.doc_id,
|
||||
websearch_to_tsquery('english', :q) q
|
||||
WHERE d.file_group_id = ANY(:ids) AND ds.tsv @@ q
|
||||
ORDER BY d.file_group_id, ts_rank(ds.tsv, q) DESC, ds.ordinal ASC
|
||||
''')
|
||||
rows = session.execute(sql, {'q': search_str, 'ids': list(file_group_ids)}).fetchall()
|
||||
SELECT fg_id, kind, ordinal, label, snippet FROM (
|
||||
SELECT fg_id, kind, ordinal, label, snippet,
|
||||
row_number() OVER (PARTITION BY fg_id
|
||||
ORDER BY fts_rank ASC, ordinal ASC) AS rn
|
||||
FROM (
|
||||
SELECT d.file_group_id AS fg_id,
|
||||
ds.kind AS kind,
|
||||
ds.ordinal AS ordinal,
|
||||
ds.label AS label,
|
||||
snippet(doc_section_fts, 0, '[[WROLPI_HL]]', '[[/WROLPI_HL]]', '…', 20) AS snippet,
|
||||
doc_section_fts.rank AS fts_rank
|
||||
FROM doc_section_fts
|
||||
JOIN doc_section ds ON ds.id = doc_section_fts.rowid
|
||||
JOIN doc d ON d.id = ds.doc_id
|
||||
WHERE doc_section_fts MATCH :q AND d.file_group_id IN :ids
|
||||
)
|
||||
) WHERE rn = 1
|
||||
''').bindparams(bindparam('ids', expanding=True))
|
||||
rows = session.execute(sql, {'q': match, 'ids': list(file_group_ids)}).fetchall()
|
||||
hints = {}
|
||||
for row in rows:
|
||||
hints[row['fg_id']] = {
|
||||
|
|
|
|||
|
|
@ -1,10 +1,10 @@
|
|||
import pathlib
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import Column, Integer, BigInteger, ForeignKey, String, Text, Index, Computed, or_
|
||||
from sqlalchemy.orm import relationship, Session, deferred
|
||||
from sqlalchemy import Column, Integer, BigInteger, ForeignKey, String, Text, Index, or_
|
||||
from sqlalchemy.orm import relationship, Session
|
||||
|
||||
from wrolpi.common import ModelHelper, Base, tsvector
|
||||
from wrolpi.common import ModelHelper, Base
|
||||
from wrolpi.db import get_db_session
|
||||
from wrolpi.files.models import FileGroup
|
||||
|
||||
|
|
@ -139,23 +139,23 @@ class DocSection(ModelHelper, Base):
|
|||
|
||||
For EPUB files, one row per spine item with `ordinal` as the 0-based spine index.
|
||||
For PDF files, one row per page with `ordinal` as the 1-based page number.
|
||||
Each row maintains its own tsvector for per-section full-text search, which lets us
|
||||
deep-link from a search result into a specific chapter or page.
|
||||
Each row is indexed by the `doc_section_fts` FTS5 table for per-section full-text search,
|
||||
which lets us deep-link from a search result into a specific chapter or page.
|
||||
"""
|
||||
__tablename__ = 'doc_section'
|
||||
__table_args__ = (
|
||||
Index('doc_section_doc_id_idx', 'doc_id', 'ordinal'),
|
||||
Index('doc_section_tsv_idx', 'tsv', postgresql_using='gin'),
|
||||
)
|
||||
|
||||
id = Column(BigInteger, primary_key=True)
|
||||
# SQLite requires exactly "INTEGER PRIMARY KEY" for the rowid alias (FTS5 content_rowid).
|
||||
id = Column(BigInteger().with_variant(Integer, 'sqlite'), primary_key=True)
|
||||
doc_id = Column(Integer, ForeignKey('doc.id', ondelete='CASCADE'), nullable=False)
|
||||
kind = Column(String, nullable=False)
|
||||
ordinal = Column(Integer, nullable=False)
|
||||
label = Column(String)
|
||||
# Full-text search over `content` is provided by the external-content FTS5 table
|
||||
# `doc_section_fts` (see `wrolpi.fts`).
|
||||
content = Column(Text)
|
||||
tsv = deferred(Column(tsvector, Computed(
|
||||
"to_tsvector('english'::regconfig, COALESCE(content, ''))")))
|
||||
|
||||
doc = relationship('Doc', back_populates='sections')
|
||||
|
||||
|
|
|
|||
|
|
@ -70,8 +70,8 @@ def _legacy_inventories_from_db() -> list:
|
|||
inventories = []
|
||||
try:
|
||||
with get_db_curs() as curs:
|
||||
curs.execute("SELECT to_regclass('public.inventory')")
|
||||
if curs.fetchone()[0] is None:
|
||||
curs.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='inventory'")
|
||||
if curs.fetchone() is None:
|
||||
return []
|
||||
curs.execute('SELECT id, name, created_at, viewed_at FROM inventory WHERE deleted_at IS NULL')
|
||||
rows = curs.fetchall()
|
||||
|
|
@ -79,7 +79,7 @@ def _legacy_inventories_from_db() -> list:
|
|||
inv = dict(id=row[0], name=row[1], created_at=row[2], viewed_at=row[3], items=[])
|
||||
curs.execute(
|
||||
'SELECT brand, name, item_size, unit, count, category, subcategory, expiration_date '
|
||||
'FROM item WHERE inventory_id = %s AND deleted_at IS NULL', (row[0],))
|
||||
'FROM item WHERE inventory_id = ? AND deleted_at IS NULL', (row[0],))
|
||||
for item in curs.fetchall():
|
||||
inv['items'].append(dict(
|
||||
brand=item[0], name=item[1], item_size=item[2], unit=item[3], count=item[4],
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import asyncio
|
||||
import json
|
||||
from typing import Callable, List, Tuple
|
||||
|
||||
from sqlalchemy import or_
|
||||
|
|
@ -82,19 +83,23 @@ def video_cleanup():
|
|||
with get_db_curs(commit=True) as curs:
|
||||
# Delete all Videos if the FileModel no longer contains a video or audio file.
|
||||
curs.execute('''
|
||||
WITH deleted AS
|
||||
(UPDATE file_group SET model = null
|
||||
WHERE model = 'video'
|
||||
AND mimetype NOT LIKE 'video/%%'
|
||||
AND mimetype NOT LIKE 'audio/%%'
|
||||
RETURNING id)
|
||||
DELETE
|
||||
FROM video
|
||||
WHERE file_group_id = ANY (select id from deleted)
|
||||
UPDATE file_group
|
||||
SET model = NULL
|
||||
WHERE model = 'video'
|
||||
AND mimetype NOT LIKE 'video/%'
|
||||
AND mimetype NOT LIKE 'audio/%'
|
||||
RETURNING id
|
||||
''')
|
||||
deleted_ids = [i['id'] for i in curs.fetchall()]
|
||||
if deleted_ids:
|
||||
curs.execute('''
|
||||
DELETE
|
||||
FROM video
|
||||
WHERE file_group_id IN (SELECT value FROM json_each(:ids))
|
||||
''', dict(ids=json.dumps(deleted_ids)))
|
||||
# Claim all Videos in a Channel's directory for that Channel. But, only if they have not yet been claimed.
|
||||
curs.execute('''
|
||||
UPDATE video v
|
||||
UPDATE video AS v
|
||||
SET channel_id = c.id
|
||||
FROM channel c
|
||||
INNER JOIN collection col ON col.id = c.collection_id
|
||||
|
|
@ -123,13 +128,13 @@ def claim_videos_for_channels(channel_ids: List[int]):
|
|||
logger.info(f'Claiming Videos for {len(channel_ids)} channel(s)')
|
||||
with get_db_curs(commit=True) as curs:
|
||||
curs.execute('''
|
||||
UPDATE video v
|
||||
UPDATE video AS v
|
||||
SET channel_id = c.id
|
||||
FROM channel c
|
||||
INNER JOIN collection col ON col.id = c.collection_id
|
||||
LEFT JOIN file_group fg ON fg.directory = col.directory
|
||||
OR fg.directory LIKE col.directory || '/%%'
|
||||
OR fg.directory LIKE col.directory || '/%'
|
||||
WHERE v.channel_id IS NULL
|
||||
AND fg.id = v.file_group_id
|
||||
AND c.id = ANY (%s)
|
||||
''', (list(channel_ids),))
|
||||
AND c.id IN (SELECT value FROM json_each(:channel_ids))
|
||||
''', dict(channel_ids=json.dumps(list(channel_ids))))
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import pathlib
|
|||
from pathlib import Path
|
||||
from typing import List, Union
|
||||
|
||||
from sqlalchemy import or_, func, desc, asc
|
||||
from sqlalchemy import or_, func, desc
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from wrolpi import flags
|
||||
|
|
@ -203,6 +203,9 @@ async def search_channels_by_name(session: Session, name: str, limit: int = 5,
|
|||
order_by_video_count: bool = False) -> List[Channel]:
|
||||
name = name or ''
|
||||
name_no_spaces = ''.join(name.split(' '))
|
||||
# SQLite sorts by byte value; emulate the old locale-aware (en_US.UTF-8) ordering: compare
|
||||
# names case-insensitively and without spaces, ties broken with lowercase names first.
|
||||
name_order = (func.lower(func.replace(Collection.name, ' ', '')).asc(), Collection.name.desc())
|
||||
if order_by_video_count:
|
||||
stmt = session.query(Channel, func.count(Video.id).label('video_count')) \
|
||||
.join(Collection) \
|
||||
|
|
@ -212,7 +215,7 @@ async def search_channels_by_name(session: Session, name: str, limit: int = 5,
|
|||
)) \
|
||||
.outerjoin(Video, Video.channel_id == Channel.id) \
|
||||
.group_by(Channel.id, Collection.id, Collection.name) \
|
||||
.order_by(desc('video_count'), asc(Collection.name)) \
|
||||
.order_by(desc('video_count'), *name_order) \
|
||||
.limit(limit)
|
||||
channels = [i[0] for i in stmt]
|
||||
else:
|
||||
|
|
@ -222,7 +225,7 @@ async def search_channels_by_name(session: Session, name: str, limit: int = 5,
|
|||
Collection.name.ilike(f'%{name}%'),
|
||||
Collection.name.ilike(f'%{name_no_spaces}%'),
|
||||
)) \
|
||||
.order_by(asc(Collection.name)) \
|
||||
.order_by(*name_order) \
|
||||
.limit(limit)
|
||||
channels = stmt.all()
|
||||
return channels
|
||||
|
|
|
|||
|
|
@ -364,15 +364,14 @@ async def update_view_counts_and_censored(channel_id: int):
|
|||
with get_db_curs(commit=True) as curs:
|
||||
# Update the view_count for each video.
|
||||
stmt = '''
|
||||
WITH source AS (select * from json_to_recordset(%s::json) as (id text, view_count bigint))
|
||||
UPDATE video
|
||||
SET view_count = s.view_count
|
||||
FROM source as s
|
||||
WHERE source_id = s.id
|
||||
AND channel_id = %s
|
||||
RETURNING video.id AS updated_ids \
|
||||
SET view_count = CAST(json_extract(s.value, '$.view_count') AS INTEGER)
|
||||
FROM json_each(:view_counts) AS s
|
||||
WHERE video.source_id = json_extract(s.value, '$.id')
|
||||
AND video.channel_id = :channel_id
|
||||
RETURNING video.id \
|
||||
'''
|
||||
curs.execute(stmt, (view_counts_str, channel_id))
|
||||
curs.execute(stmt, {'view_counts': view_counts_str, 'channel_id': channel_id})
|
||||
count = len(curs.fetchall())
|
||||
logger.info(f'Updated {count} view counts in DB for {channel_name}.')
|
||||
|
||||
|
|
@ -380,13 +379,13 @@ async def update_view_counts_and_censored(channel_id: int):
|
|||
with get_db_curs(commit=True) as curs:
|
||||
# Set FileGroup.censored if the video is no longer on the Channel.
|
||||
stmt = '''
|
||||
UPDATE file_group fg
|
||||
SET censored = NOT (v.source_id = ANY (%(source_ids)s))
|
||||
UPDATE file_group AS fg
|
||||
SET censored = (v.source_id NOT IN (SELECT value FROM json_each(:source_ids)))
|
||||
FROM video v
|
||||
WHERE v.file_group_id = fg.id
|
||||
AND v.channel_id = %(channel_id)s
|
||||
RETURNING fg.id, fg.censored \
|
||||
AND v.channel_id = :channel_id
|
||||
RETURNING id, censored \
|
||||
'''
|
||||
curs.execute(stmt, {'channel_id': channel_id, 'source_ids': source_ids})
|
||||
curs.execute(stmt, {'channel_id': channel_id, 'source_ids': json.dumps(source_ids)})
|
||||
censored = len([i for i in curs.fetchall() if i['censored']])
|
||||
logger.info(f'Set {censored} censored videos for {channel_name}.')
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import contextlib
|
||||
import dataclasses
|
||||
import html
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
|
|
@ -988,13 +989,13 @@ async def get_statistics():
|
|||
-- total videos
|
||||
COUNT(v.id) AS "videos",
|
||||
-- total videos downloaded over the past week/month/year
|
||||
COUNT(v.id) FILTER (WHERE published_datetime >= current_date - interval '1 week') AS "week",
|
||||
COUNT(v.id) FILTER (WHERE published_datetime >= current_date - interval '1 month') AS "month",
|
||||
COUNT(v.id) FILTER (WHERE published_datetime >= current_date - interval '1 year') AS "year",
|
||||
COUNT(v.id) FILTER (WHERE published_datetime >= datetime('now', '-7 days')) AS "week",
|
||||
COUNT(v.id) FILTER (WHERE published_datetime >= datetime('now', '-1 month')) AS "month",
|
||||
COUNT(v.id) FILTER (WHERE published_datetime >= datetime('now', '-1 year')) AS "year",
|
||||
-- sum of all video lengths in seconds
|
||||
COALESCE(SUM(fg.length), 0) AS "sum_duration",
|
||||
COALESCE(SUM(fg.length), 0) AS "sum_duration",
|
||||
-- sum of all video file sizes
|
||||
COALESCE(SUM(fg.size), 0)::BIGINT AS "sum_size",
|
||||
COALESCE(SUM(fg.size), 0) AS "sum_size",
|
||||
-- largest video
|
||||
COALESCE(MAX(fg.size), 0) AS "max_size",
|
||||
-- Videos may or may not have comments.
|
||||
|
|
@ -1010,23 +1011,24 @@ async def get_statistics():
|
|||
video_stats = dict(curs.fetchone())
|
||||
|
||||
# Get the total videos downloaded every month for the past two years.
|
||||
# (Not parameterized, so `%` needs no escaping.) Like the old Postgres query, months
|
||||
# without any videos are absent from the results.
|
||||
curs.execute('''
|
||||
SELECT DATE_TRUNC('month', months.a),
|
||||
COUNT(video.id)::BIGINT,
|
||||
SUM(size)::BIGINT AS "size"
|
||||
FROM generate_series(
|
||||
date_trunc('month', current_date) - interval '2 years',
|
||||
date_trunc('month', current_date) - interval '1 month',
|
||||
'1 month'::interval) AS months(a),
|
||||
video
|
||||
SELECT strftime('%Y-%m-01 00:00:00', fg.published_datetime) AS "month",
|
||||
COUNT(video.id) AS "count",
|
||||
SUM(fg.size) AS "size"
|
||||
FROM video
|
||||
LEFT JOIN file_group fg on video.file_group_id = fg.id
|
||||
WHERE published_datetime >= date_trunc('month', months.a)
|
||||
AND published_datetime < date_trunc('month', months.a) + interval '1 month'
|
||||
AND published_datetime IS NOT NULL
|
||||
WHERE fg.published_datetime IS NOT NULL
|
||||
AND fg.published_datetime >= datetime('now', 'start of month', '-24 months')
|
||||
AND fg.published_datetime < datetime('now', 'start of month')
|
||||
GROUP BY 1
|
||||
ORDER BY 1
|
||||
''')
|
||||
monthly_videos = [dict(i) for i in curs.fetchall()]
|
||||
for monthly_video in monthly_videos:
|
||||
# The frontend expects a datetime, not the TEXT that SQLite stores.
|
||||
monthly_video['month'] = datetime.fromisoformat(monthly_video['month'])
|
||||
|
||||
historical_stats = dict(monthly_videos=monthly_videos)
|
||||
historical_stats['average_count'] = (sum(i['count'] for i in monthly_videos) // len(monthly_videos)) \
|
||||
|
|
@ -1039,7 +1041,7 @@ async def get_statistics():
|
|||
COUNT(c.id) FILTER ( WHERE col.tag_id IS NOT NULL ) AS "tagged_channels"
|
||||
FROM channel c
|
||||
LEFT JOIN collection col on col.id = c.collection_id
|
||||
LEFT JOIN public.tag t on t.id = col.tag_id
|
||||
LEFT JOIN tag t on t.id = col.tag_id
|
||||
''')
|
||||
channel_stats = dict(curs.fetchone())
|
||||
ret = dict(statistics=dict(
|
||||
|
|
@ -1153,16 +1155,21 @@ def find_orphaned_video_files(directory: pathlib.Path) -> Generator[pathlib.Path
|
|||
|
||||
# Query returns directory and files - files may contain relative or absolute paths
|
||||
# Use indexed directory column for efficient lookup
|
||||
# (Not parameterized, so `%` needs no escaping.)
|
||||
curs.execute(f'''
|
||||
SELECT directory, files
|
||||
FROM file_group
|
||||
WHERE
|
||||
mimetype NOT LIKE 'video%%'
|
||||
AND (directory = '{directory_str}' OR directory LIKE '{directory_str}/%%')
|
||||
mimetype NOT LIKE 'video%'
|
||||
AND (directory = '{directory_str}' OR directory LIKE '{directory_str}/%')
|
||||
''')
|
||||
for row in curs.fetchall():
|
||||
fg_directory = pathlib.Path(row[0]) if row[0] else None
|
||||
for file_info in row[1]:
|
||||
files = row[1]
|
||||
if isinstance(files, str):
|
||||
# Raw cursor reads return the JSON column as TEXT.
|
||||
files = json.loads(files)
|
||||
for file_info in files:
|
||||
path = pathlib.Path(file_info['path'])
|
||||
if not path.is_absolute() and fg_directory:
|
||||
# Resolve relative path using directory
|
||||
|
|
|
|||
|
|
@ -2,8 +2,7 @@ import json
|
|||
import pathlib
|
||||
from typing import Optional, Dict, List
|
||||
|
||||
from sqlalchemy import Column, Integer, String, Boolean, Date, ForeignKey, BigInteger, Index, text
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from sqlalchemy import Column, Integer, String, Boolean, Date, ForeignKey, BigInteger, Index, text, JSON
|
||||
from sqlalchemy.orm import relationship, Session, deferred
|
||||
from sqlalchemy.orm.collections import InstrumentedList
|
||||
|
||||
|
|
@ -30,12 +29,14 @@ class Video(ModelHelper, Base):
|
|||
Index('video_channel_id_idx', 'channel_id'),
|
||||
Index('video_source_id_idx', 'source_id'),
|
||||
Index('video_view_count_idx', 'view_count'),
|
||||
# Do not reuse ids of deleted Videos (like Postgres sequences).
|
||||
{'sqlite_autoincrement': True},
|
||||
)
|
||||
id = Column(Integer, primary_key=True)
|
||||
|
||||
source_id = Column(String) # The id from yt-dlp
|
||||
view_count = Column(BigInteger) # The view count from the ChannelDownloader (or from initial download)
|
||||
ffprobe_json = deferred(Column(JSONB)) # Data that is fetched once from ffprobe (ffmpeg)
|
||||
ffprobe_json = deferred(Column(JSON)) # Data that is fetched once from ffprobe (ffmpeg)
|
||||
have_comments = Column(Boolean, default=False) # see `get_missing_videos_comments`
|
||||
comments_failed = Column(Boolean, default=False) # see `get_missing_videos_comments`
|
||||
|
||||
|
|
@ -164,19 +165,19 @@ class Video(ModelHelper, Base):
|
|||
ROW_NUMBER() OVER (ORDER BY published_datetime ASC) AS row_number
|
||||
FROM file_group fg
|
||||
LEFT OUTER JOIN video v on fg.id = v.file_group_id
|
||||
WHERE v.channel_id = %(channel_id)s
|
||||
WHERE v.channel_id = :channel_id
|
||||
AND fg.published_datetime IS NOT NULL)
|
||||
SELECT v_id
|
||||
FROM numbered_videos
|
||||
WHERE row_number IN (SELECT row_number + i
|
||||
FROM numbered_videos
|
||||
CROSS JOIN (SELECT -1 AS i UNION ALL SELECT 0 UNION ALL SELECT 1) n
|
||||
WHERE fg_id = %(fg_id)s) \
|
||||
WHERE fg_id = :fg_id) \
|
||||
'''
|
||||
else:
|
||||
# No videos near this Video with upload dates, recommend the files next to this Video.
|
||||
# Only recommend videos in the same Channel (or similarly without a Channel).
|
||||
channel_where = 'WHERE v.channel_id = %(channel_id)s' if self.channel_id \
|
||||
channel_where = 'WHERE v.channel_id = :channel_id' if self.channel_id \
|
||||
else 'WHERE v.channel_id IS NULL'
|
||||
stmt = f'''
|
||||
WITH numbered_videos AS (
|
||||
|
|
@ -192,7 +193,7 @@ class Video(ModelHelper, Base):
|
|||
SELECT row_number+i
|
||||
FROM numbered_videos
|
||||
CROSS JOIN (SELECT -1 AS i UNION ALL SELECT 0 UNION ALL SELECT 1) n
|
||||
WHERE fg_id = %(fg_id)s
|
||||
WHERE fg_id = :fg_id
|
||||
)
|
||||
'''
|
||||
logger.debug(stmt)
|
||||
|
|
@ -584,7 +585,8 @@ class Channel(ModelHelper, Base):
|
|||
Index('channel_source_id', 'source_id'),
|
||||
Index('channel_total_size_idx', 'total_size'),
|
||||
Index('channel_video_count_idx', 'video_count'),
|
||||
Index('channel_url_key', 'url', unique=True, postgresql_where=text('url IS NOT NULL')),
|
||||
Index('channel_url_key', 'url', unique=True, postgresql_where=text('url IS NOT NULL'),
|
||||
sqlite_where=text('url IS NOT NULL')),
|
||||
)
|
||||
id = Column(Integer, primary_key=True)
|
||||
# name and directory are stored in Collection, accessed via properties
|
||||
|
|
@ -600,7 +602,7 @@ class Channel(ModelHelper, Base):
|
|||
total_size = Column(BigInteger, default=0, nullable=False) # update_channel_size
|
||||
minimum_frequency = Column(Integer) # update_channel_minimum_frequency
|
||||
|
||||
info_json = deferred(Column(JSONB))
|
||||
info_json = deferred(Column(JSON))
|
||||
info_date = Column(Date)
|
||||
|
||||
videos: InstrumentedList = relationship('Video', primaryjoin='Channel.id==Video.channel_id')
|
||||
|
|
@ -961,10 +963,10 @@ class Channel(ModelHelper, Base):
|
|||
(SELECT COUNT(DISTINCT tf.file_group_id)
|
||||
FROM tag_file tf
|
||||
INNER JOIN video v ON v.file_group_id = tf.file_group_id
|
||||
WHERE v.channel_id = %(id)s) AS "video_tags"
|
||||
WHERE v.channel_id = :id) AS "video_tags"
|
||||
FROM video
|
||||
LEFT JOIN file_group fg on fg.id = video.file_group_id
|
||||
WHERE channel_id = %(id)s \
|
||||
WHERE channel_id = :id \
|
||||
'''
|
||||
curs.execute(stmt, dict(id=self.id))
|
||||
return dict(curs.fetchone())
|
||||
|
|
@ -976,15 +978,15 @@ class Channel(ModelHelper, Base):
|
|||
with get_db_curs() as curs:
|
||||
stmt = '''
|
||||
SELECT COUNT(fg.id) AS "video_file_groups",
|
||||
COUNT(fg.id) FILTER ( WHERE v.channel_id = %(id)s ) AS "assigned_to_channel",
|
||||
COUNT(fg.id) FILTER ( WHERE v.channel_id = :id ) AS "assigned_to_channel",
|
||||
COUNT(fg.id) FILTER ( WHERE v.channel_id IS NOT NULL
|
||||
AND v.channel_id != %(id)s ) AS "assigned_to_other_channels",
|
||||
AND v.channel_id != :id ) AS "assigned_to_other_channels",
|
||||
COUNT(fg.id) FILTER ( WHERE v.id IS NULL
|
||||
OR v.channel_id IS NULL ) AS "unassigned"
|
||||
FROM file_group fg
|
||||
LEFT JOIN video v ON v.file_group_id = fg.id
|
||||
WHERE (fg.directory = %(directory)s OR fg.directory LIKE %(directory)s || '/%%')
|
||||
AND (fg.mimetype LIKE 'video/%%' OR fg.mimetype LIKE 'audio/%%') \
|
||||
WHERE (fg.directory = :directory OR fg.directory LIKE :directory || '/%')
|
||||
AND (fg.mimetype LIKE 'video/%' OR fg.mimetype LIKE 'audio/%') \
|
||||
'''
|
||||
curs.execute(stmt, dict(id=self.id, directory=str(self.directory)))
|
||||
return dict(curs.fetchone())
|
||||
|
|
|
|||
|
|
@ -74,11 +74,11 @@ async def test_refresh_videos(async_client, test_session, test_directory, simple
|
|||
video_file = test_directory / 'foo.mp4'
|
||||
with get_db_curs(commit=True) as curs:
|
||||
stmt = "INSERT INTO file_group (mimetype, directory, primary_path, indexed, files, model)" \
|
||||
" values ('video/mp4', %(directory)s, %(primary_path)s, true, %(files)s, 'video') RETURNING id"
|
||||
" values ('video/mp4', :directory, :primary_path, true, :files, 'video') RETURNING id"
|
||||
params = {'directory': str(test_directory), 'primary_path': str(video_file), 'files': '[]'}
|
||||
curs.execute(stmt, params)
|
||||
video4_id = curs.fetchall()[0][0]
|
||||
stmt = "INSERT INTO video (file_group_id) values (%(video_id)s)"
|
||||
stmt = "INSERT INTO video (file_group_id) values (:video_id)"
|
||||
curs.execute(stmt, {'video_id': str(video4_id)})
|
||||
|
||||
await async_client.post('/api/files/refresh')
|
||||
|
|
@ -198,8 +198,10 @@ async def test_search_videos_file(test_session, test_directory, video_with_searc
|
|||
# Captions are d_text, so a deep search is required to match them.
|
||||
# Repeated runs should return the same result
|
||||
for _ in range(2):
|
||||
# Only videos with a b are returned, ordered by the amount of b's
|
||||
await assert_video_search(search_str='b', deep=True, assert_ids=[1, 2, 3, 4])
|
||||
# Only videos with a b are returned, ordered by their rank. (FTS5's bm25 normalizes by
|
||||
# document length, so the short 'b b' caption outranks longer captions with more b's;
|
||||
# Postgres' ts_rank ordered by raw frequency.)
|
||||
await assert_video_search(search_str='b', deep=True, assert_ids=[3, 1, 2, 4])
|
||||
|
||||
# The default (fast) search does not match captions.
|
||||
await assert_video_search(search_str='b', assert_ids=[])
|
||||
|
|
@ -220,11 +222,11 @@ async def test_search_videos_file(test_session, test_directory, video_with_searc
|
|||
# only video 1 has e and d
|
||||
await assert_video_search(search_str='e d', deep=True, assert_ids=[1, ])
|
||||
|
||||
# video 1 and 4 have b and e, but 1 has more
|
||||
await assert_video_search(search_str='b e', deep=True, assert_ids=[1, 4])
|
||||
# Videos 1 and 4 have b and e; 4's caption is shorter so bm25 ranks it higher.
|
||||
await assert_video_search(search_str='b e', deep=True, assert_ids=[4, 1])
|
||||
|
||||
# Check totals are correct even with a limit
|
||||
await assert_video_search(search_str='b', deep=True, limit=2, assert_ids=[1, 2], assert_total=4)
|
||||
await assert_video_search(search_str='b', deep=True, limit=2, assert_ids=[3, 1], assert_total=4)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ from sqlalchemy import or_
|
|||
from sqlalchemy.orm import Session
|
||||
|
||||
from modules.videos.models import Video, Channel
|
||||
from wrolpi import fts
|
||||
from wrolpi.common import logger, limit_concurrent, wrol_mode_check
|
||||
from wrolpi.dates import now
|
||||
from wrolpi.db import get_db_session
|
||||
|
|
@ -58,8 +59,8 @@ VIDEO_ORDERS = {
|
|||
'-size': 'fg.size DESC, LOWER(fg.primary_path) DESC',
|
||||
'length': 'fg.length ASC, LOWER(fg.primary_path) ASC',
|
||||
'-length': 'fg.length DESC, LOWER(fg.primary_path) DESC',
|
||||
'size_to_duration': 'CASE WHEN fg.length > 0 THEN fg.size::float / fg.length ELSE fg.size END ASC, LOWER(fg.primary_path) ASC',
|
||||
'-size_to_duration': 'CASE WHEN fg.length > 0 THEN fg.size::float / fg.length ELSE fg.size END DESC, LOWER(fg.primary_path) DESC',
|
||||
'size_to_duration': 'CASE WHEN fg.length > 0 THEN CAST(fg.size AS REAL) / fg.length ELSE fg.size END ASC, LOWER(fg.primary_path) ASC',
|
||||
'-size_to_duration': 'CASE WHEN fg.length > 0 THEN CAST(fg.size AS REAL) / fg.length ELSE fg.size END DESC, LOWER(fg.primary_path) DESC',
|
||||
'viewed': 'fg.viewed ASC',
|
||||
'-viewed': 'fg.viewed DESC',
|
||||
'view_count': 'v.view_count ASC',
|
||||
|
|
@ -97,41 +98,42 @@ def search_videos(
|
|||
) -> Tuple[List[dict], int]:
|
||||
tag_names = tag_names or []
|
||||
# Search videos and audio-only files.
|
||||
wheres = ["(fg.mimetype LIKE 'video/%%' OR fg.mimetype LIKE 'audio/%%')"]
|
||||
wheres = ["(fg.mimetype LIKE 'video/%' OR fg.mimetype LIKE 'audio/%')"]
|
||||
if censored:
|
||||
# Only return videos which are no longer available for download.
|
||||
wheres.append('fg.censored = TRUE')
|
||||
joins = list()
|
||||
join_video = False
|
||||
|
||||
params = dict(search_str=search_str, offset=offset or 0)
|
||||
# Explicit JSON nulls bypass the schema defaults; SQLite rejects LIMIT/OFFSET NULL.
|
||||
limit = int(limit) if limit else 20
|
||||
params = dict(search_str=search_str, offset=int(offset) if offset else 0)
|
||||
if channel_id:
|
||||
wheres.append('v.channel_id = %(channel_id)s')
|
||||
wheres.append('v.channel_id = :channel_id')
|
||||
joins.append('LEFT JOIN channel c ON c.id = v.channel_id')
|
||||
join_video = True
|
||||
params['channel_id'] = channel_id
|
||||
|
||||
if search_str:
|
||||
# `deep` searches d_text (captions) as well; the default abc search is much smaller and faster.
|
||||
# The subquery join is required: snippet() cannot coexist with COUNT(*) OVER() in one SELECT.
|
||||
fts_search = fts.file_group_search_join(search_str, deep=deep, headlines=bool(headline)) \
|
||||
if search_str else None
|
||||
if fts_search:
|
||||
# A search_str was provided by the user, modify the query to filter by it.
|
||||
# `textsearch` includes d_text (captions); `textsearch_abc` is much smaller and faster.
|
||||
ts_col = 'textsearch' if deep else 'textsearch_abc'
|
||||
select_columns = f'fg.id, ts_rank(fg.{ts_col}, websearch_to_tsquery(%(search_str)s)), COUNT(*) OVER() AS total'
|
||||
wheres.append(f'fg.{ts_col} @@ websearch_to_tsquery(%(search_str)s)')
|
||||
params['search_str'] = search_str
|
||||
select_columns = f'fg.id, {fts_search.rank_select}, COUNT(*) OVER() AS total'
|
||||
joins.append(fts_search.join)
|
||||
params.update(fts_search.params)
|
||||
else:
|
||||
# No search_str provided. Get id and total only.
|
||||
# No (usable) search_str provided. Get id and total only.
|
||||
select_columns = 'fg.id, COUNT(*) OVER() AS total'
|
||||
|
||||
wheres, params = tag_append_sub_select_where(wheres, params, tag_names)
|
||||
|
||||
if search_str and headline:
|
||||
headline = ''',
|
||||
ts_headline(fg.title, websearch_to_tsquery(%(search_str)s)) AS "title_headline",
|
||||
ts_headline(fg.b_text, websearch_to_tsquery(%(search_str)s)) AS "b_headline",
|
||||
ts_headline(fg.c_text, websearch_to_tsquery(%(search_str)s)) AS "c_headline",
|
||||
ts_headline(fg.d_text, websearch_to_tsquery(%(search_str)s)) AS "d_headline"'''
|
||||
if fts_search and headline:
|
||||
# The title headline is computed in Python by `handle_file_group_search_results`.
|
||||
headline_selects = ', fts.b_headline, fts.c_headline, fts.d_headline'
|
||||
else:
|
||||
headline = ''
|
||||
headline_selects = ''
|
||||
|
||||
# Convert the user-friendly order by into a real order by, restrict what can be interpolated by using the
|
||||
# whitelist.
|
||||
|
|
@ -155,14 +157,14 @@ def search_videos(
|
|||
stmt = f'''
|
||||
SELECT
|
||||
{select_columns}
|
||||
{headline}
|
||||
{headline_selects}
|
||||
FROM file_group fg
|
||||
{join}
|
||||
{where}
|
||||
ORDER BY {order_by}
|
||||
OFFSET %(offset)s LIMIT {int(limit)}
|
||||
LIMIT {int(limit)} OFFSET :offset
|
||||
'''.strip()
|
||||
logger.debug(stmt, params)
|
||||
logger.debug(f'{stmt} {params}')
|
||||
|
||||
results, total = handle_file_group_search_results(stmt, params)
|
||||
return results, total
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import asyncio
|
||||
import functools
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
from datetime import datetime
|
||||
|
|
@ -132,7 +133,7 @@ def get_all_entries_tags():
|
|||
},
|
||||
"""
|
||||
stmt = '''
|
||||
SELECT tz.zim_id, tz.zim_entry, array_agg(t.name)::TEXT[]
|
||||
SELECT tz.zim_id, tz.zim_entry, json_group_array(t.name)
|
||||
FROM tag t
|
||||
LEFT JOIN tag_zim tz on t.id = tz.tag_id
|
||||
GROUP BY 1, 2 \
|
||||
|
|
@ -143,6 +144,7 @@ def get_all_entries_tags():
|
|||
for zim_id, zim_entry, tag_names in curs.fetchall():
|
||||
if not zim_id:
|
||||
continue
|
||||
tag_names = json.loads(tag_names)
|
||||
try:
|
||||
entries[zim_id][zim_entry] = tag_names
|
||||
except KeyError:
|
||||
|
|
@ -195,8 +197,7 @@ def headline_zim(session: Session, search_str: str, zim_id: int, tag_names: List
|
|||
|
||||
entries_tag_names = get_entries_tags([i.path for i in entries], zim_id)
|
||||
|
||||
# Always get headlines even if there is no search_str. This is because Postgres will return the start of each
|
||||
# article.
|
||||
# Always get headlines even if there is no search_str. Non-matches get the leading text of each article.
|
||||
headlines = extract_headlines(articles, search_str)
|
||||
|
||||
search = list()
|
||||
|
|
|
|||
|
|
@ -251,14 +251,16 @@ class Zim(Base, ModelHelper):
|
|||
def _entries_with_tags_process(limit: int, offset: int, params: dict, session: Session, tags_sub_select: str):
|
||||
with get_db_curs() as curs:
|
||||
curs.execute(tags_sub_select, params)
|
||||
zim_ids_entries: List[Tuple[int, int]] = list(curs.fetchall())
|
||||
# sqlite3.Row is not a tuple; convert for the `tuple_(...).in_()` below.
|
||||
zim_ids_entries: List[Tuple[int, str]] = [tuple(row) for row in curs.fetchall()]
|
||||
|
||||
# GROUP BY dedupes entries with multiple Tags (SQLite has no DISTINCT ON).
|
||||
tag_zim_entries = session.query(TagZimEntry, Zim) \
|
||||
.join(Zim, Zim.id == TagZimEntry.zim_id) \
|
||||
.filter(tuple_(TagZimEntry.zim_id, TagZimEntry.zim_entry).in_(zim_ids_entries)) \
|
||||
.group_by(TagZimEntry.zim_id, TagZimEntry.zim_entry) \
|
||||
.order_by(TagZimEntry.zim_id, TagZimEntry.zim_entry) \
|
||||
.offset(offset).limit(limit) \
|
||||
.distinct(TagZimEntry.zim_id, TagZimEntry.zim_entry)
|
||||
.offset(offset).limit(limit)
|
||||
|
||||
entries = list()
|
||||
for tag_zim_entry, zim in tag_zim_entries:
|
||||
|
|
|
|||
|
|
@ -17,27 +17,27 @@ async def test_zim_search(async_client, test_session, test_zim, tag_factory, ass
|
|||
test_zim.tag_entry(test_session, tag1.name, 'two')
|
||||
test_session.commit()
|
||||
|
||||
# Test searching with only `search_str`.
|
||||
# Test searching with only `search_str`. (Ranks/headlines come from FTS5 `headline_texts`.)
|
||||
await assert_zim_search('one', 1, {
|
||||
'path': test_zim.path,
|
||||
'search': [
|
||||
# Entry "One" contains a 'one' in the title, and the text.
|
||||
{'path': 'one', 'headline': 'This is the first item', 'rank': 0.06079271},
|
||||
{'path': 'one', 'headline': 'This is the first item', 'rank': 1e-06},
|
||||
# Home only contains one 'one'.
|
||||
{'path': 'home', 'rank': 0.06079271, 'headline': 'file for testing.\n<b>One</b>', },
|
||||
{'path': 'home', 'rank': 8.8e-07, 'headline': '…an example ZIM file for testing.\n<b>One</b>\nTwo', },
|
||||
],
|
||||
'estimate': 2,
|
||||
})
|
||||
await assert_zim_search('two', 1, {
|
||||
'path': test_zim.path,
|
||||
'search': [{'path': 'two', 'headline': 'This is the second item', 'rank': 0.06079271},
|
||||
{'path': 'home', 'headline': 'testing.\nOne\n<b>Two</b>', 'rank': 0.06079271}],
|
||||
'search': [{'path': 'two', 'headline': 'This is the second item', 'rank': 1e-06},
|
||||
{'path': 'home', 'headline': '…One\n<b>Two</b>', 'rank': 8.8e-07}],
|
||||
'estimate': 2,
|
||||
})
|
||||
await assert_zim_search('item', 1, {
|
||||
'path': test_zim.path,
|
||||
'search': [{'path': 'one', 'headline': 'first <b>item</b>', 'rank': 0.06079271},
|
||||
{'path': 'two', 'headline': 'second <b>item</b>', 'rank': 0.06079271}],
|
||||
'search': [{'path': 'one', 'headline': 'This is the first <b>item</b>', 'rank': 1e-06},
|
||||
{'path': 'two', 'headline': 'This is the second <b>item</b>', 'rank': 1e-06}],
|
||||
'estimate': 2,
|
||||
})
|
||||
|
||||
|
|
@ -45,21 +45,21 @@ async def test_zim_search(async_client, test_session, test_zim, tag_factory, ass
|
|||
await assert_zim_search('one', 1, tag_names=[tag2.name, ], expected={
|
||||
'search': [
|
||||
# Only entry "One" is tagged with Tag 2.
|
||||
{'path': 'one', 'headline': 'This is the first item', 'rank': 0.06079271},
|
||||
{'path': 'one', 'headline': 'This is the first item', 'rank': 1e-06},
|
||||
],
|
||||
'estimate': 1,
|
||||
})
|
||||
await assert_zim_search('one', 1, tag_names=[tag1.name, tag2.name], expected={
|
||||
'search': [
|
||||
# Only "One" is tagged with Tag 1 and contains "one".
|
||||
{'path': 'one', 'headline': 'This is the first item', 'rank': 0.06079271},
|
||||
{'path': 'one', 'headline': 'This is the first item', 'rank': 1e-06},
|
||||
],
|
||||
'estimate': 1,
|
||||
})
|
||||
await assert_zim_search('two', 1, tag_names=[tag1.name, ], expected={
|
||||
'search': [
|
||||
# Only "Two" was tagged with Tag 1 and contains "two".
|
||||
{'path': 'two', 'headline': 'This is the second item', 'rank': 0.06079271},
|
||||
{'path': 'two', 'headline': 'This is the second item', 'rank': 1e-06},
|
||||
],
|
||||
'estimate': 1,
|
||||
})
|
||||
|
|
|
|||
|
|
@ -172,8 +172,8 @@ async def test_zim_tags_config(async_client, test_session, test_directory, test_
|
|||
assert [(i.tag.name, i.zim.path, i.zim_entry) for i in tag_zim_entries] \
|
||||
== [('Tag2', test_zim.path, 'one'), ('Tag1', test_zim.path, 'two')]
|
||||
|
||||
# Tags were recreated.
|
||||
assert {i[0] for i in test_session.query(tags.Tag.id)} == {3, 4}
|
||||
# Tags were recreated. (SQLite reuses row ids after DELETE, so assert by name rather than by id.)
|
||||
assert {i.name for i in test_session.query(tags.Tag)} == {'Tag1', 'Tag2'}
|
||||
|
||||
|
||||
def test_zim_all_entries(test_session, test_zim):
|
||||
|
|
@ -376,7 +376,8 @@ async def test_zim_subscription_download_import(async_client, test_session):
|
|||
for _ in range(1): # Import twice.
|
||||
# Importing the config restores the Download and ZimSubscription.
|
||||
await import_downloads_config()
|
||||
recurring, once = test_session.query(Download).order_by(Download.frequency)
|
||||
# NULLS LAST because SQLite sorts NULLs first (Postgres sorted them last).
|
||||
recurring, once = test_session.query(Download).order_by(Download.frequency.nullslast())
|
||||
assert once.url == 'https://download.kiwix.org/zim/wikibooks/wikibooks_en_all_maxi_2021-03.zim'
|
||||
assert test_session.query(Download).count() == 2
|
||||
assert recurring.url == 'https://download.kiwix.org/zim/wikisource/wikisource_en_all_maxi_'
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue