mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-28 19:06:19 -05:00
db: request-path library functions use the request's connection
Library functions an API request reaches now take the request's Session (first argument) instead of opening their own session or cursor, so a request needs one SQLite connection. Raw SQL runs through the new `wrolpi.db.session_curs(session)`, a cursor on the Session's connection; `RequestDB.curs()` uses it. - Search: files, videos, archives, flasher, and docs search share the request connection for the total, the page of ids, and the page's models (3 connections -> 1). - Zim search, including tag-filtered search and estimates (2 -> 1). - Channel detail (`Channel.get_statistics` reads on the Channel's own Session) and the channel list. - Video detail, edit, description, captions, comments and transcode. `get_video_for_app` and `update_video` no longer commit; their handlers use `request.ctx.db.write()`, so editing a Video and reading it back is one transaction. - Tags (list, overlaps, recent), file statistics and estimates, other estimates, bulk tag preview, the download list, retry, kill and the status summary, and docs/videos/archive statistics. Not converted: file operations that refresh files inside the request (delete, rename, upload, channel and collection tag/move) commit page by page in code shared with the file worker; the cached zim entry lookup; config import. The connection-count tests now assert one connection for every endpoint they cover (no xfails left), and cover the videos and archive statistics endpoints, which had no API test. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
a2bef48c6c
commit
24c5796fc6
34 changed files with 545 additions and 422 deletions
|
|
@ -20,8 +20,8 @@ logger = logger.getChild(__name__)
|
|||
|
||||
@docs_bp.get('/statistics')
|
||||
@openapi.response(HTTPStatus.OK, schema.DocStatisticsResponse)
|
||||
async def statistics(_: Request):
|
||||
ret = get_statistics()
|
||||
async def statistics(request: Request):
|
||||
ret = get_statistics(request.ctx.session)
|
||||
return json_response(ret, HTTPStatus.OK)
|
||||
|
||||
|
||||
|
|
@ -44,11 +44,12 @@ doc_limit_limiter = api_param_limiter(100)
|
|||
)
|
||||
@openapi.response(HTTPStatus.OK, schema.DocSearchResponse)
|
||||
@validate(schema.DocSearchRequest)
|
||||
async def search_docs(_: Request, body: schema.DocSearchRequest):
|
||||
async def search_docs(request: Request, body: schema.DocSearchRequest):
|
||||
limit = doc_limit_limiter(body.limit)
|
||||
offset = body.offset or 0
|
||||
file_groups, total = await asyncio.to_thread(
|
||||
_search_docs,
|
||||
request.ctx.session,
|
||||
search_str=body.search_str,
|
||||
author=body.author,
|
||||
subject=body.subject,
|
||||
|
|
|
|||
|
|
@ -10,7 +10,6 @@ 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
|
||||
from wrolpi.errors import ValidationError
|
||||
from wrolpi.files.lib import split_path_stem_and_suffix, get_mimetype, cached_search_total, \
|
||||
search_filter_cache_key
|
||||
|
|
@ -293,24 +292,23 @@ def discover_calibre_cover(ebook_path: pathlib.Path):
|
|||
return cover
|
||||
|
||||
|
||||
def get_statistics() -> dict:
|
||||
def get_statistics(session: Session) -> dict:
|
||||
"""Get doc statistics."""
|
||||
from .models import Doc
|
||||
from wrolpi.files.models import FileGroup
|
||||
|
||||
with get_db_session() as session:
|
||||
total = session.query(func.count(Doc.id)).scalar() or 0
|
||||
total_size = session.query(func.sum(Doc.size)).scalar() or 0
|
||||
total = session.query(func.count(Doc.id)).scalar() or 0
|
||||
total_size = session.query(func.sum(Doc.size)).scalar() or 0
|
||||
|
||||
epub_count = session.query(func.count(Doc.id)).join(FileGroup).filter(
|
||||
FileGroup.mimetype.startswith('application/epub')).scalar() or 0
|
||||
pdf_count = session.query(func.count(Doc.id)).join(FileGroup).filter(
|
||||
FileGroup.mimetype == 'application/pdf').scalar() or 0
|
||||
epub_count = session.query(func.count(Doc.id)).join(FileGroup).filter(
|
||||
FileGroup.mimetype.startswith('application/epub')).scalar() or 0
|
||||
pdf_count = session.query(func.count(Doc.id)).join(FileGroup).filter(
|
||||
FileGroup.mimetype == 'application/pdf').scalar() or 0
|
||||
|
||||
author_count = session.query(func.count(Collection.id)).filter(
|
||||
Collection.kind == 'author').scalar() or 0
|
||||
subject_count = session.query(func.count(Collection.id)).filter(
|
||||
Collection.kind == 'subject').scalar() or 0
|
||||
author_count = session.query(func.count(Collection.id)).filter(
|
||||
Collection.kind == 'author').scalar() or 0
|
||||
subject_count = session.query(func.count(Collection.id)).filter(
|
||||
Collection.kind == 'subject').scalar() or 0
|
||||
|
||||
return dict(statistics=dict(
|
||||
doc_count=total,
|
||||
|
|
@ -368,7 +366,7 @@ def _doc_browse_sql(order_by: str) -> Optional[str]:
|
|||
ORDER BY {order} LIMIT :limit OFFSET :offset'''
|
||||
|
||||
|
||||
def _search_docs(search_str=None, author=None, subject=None, language=None, mimetype=None,
|
||||
def _search_docs(session: Session, search_str=None, author=None, subject=None, language=None, mimetype=None,
|
||||
limit=20, offset=0, order_by='published_datetime', tag_names=None, deep=False):
|
||||
from .models import Doc
|
||||
from wrolpi.files.models import FileGroup
|
||||
|
|
@ -377,86 +375,85 @@ def _search_docs(search_str=None, author=None, subject=None, language=None, mime
|
|||
# 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)
|
||||
query = session.query(FileGroup).join(Doc, Doc.file_group_id == FileGroup.id)
|
||||
|
||||
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)
|
||||
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}%'))
|
||||
if author:
|
||||
query = query.filter(FileGroup.b_text.ilike(f'%{author}%'))
|
||||
|
||||
if subject:
|
||||
query = query.filter(Doc.subject.ilike(f'%{subject}%'))
|
||||
if subject:
|
||||
query = query.filter(Doc.subject.ilike(f'%{subject}%'))
|
||||
|
||||
if language:
|
||||
query = query.filter(Doc.language == language)
|
||||
if language:
|
||||
query = query.filter(Doc.language == language)
|
||||
|
||||
if mimetype:
|
||||
query = query.filter(FileGroup.mimetype.startswith(mimetype))
|
||||
if mimetype:
|
||||
query = query.filter(FileGroup.mimetype.startswith(mimetype))
|
||||
|
||||
if tag_names:
|
||||
from wrolpi.tags import Tag, TagFile
|
||||
tagged_fg_ids = session.query(TagFile.file_group_id) \
|
||||
.join(Tag, Tag.id == TagFile.tag_id) \
|
||||
.filter(Tag.name.in_(tag_names)) \
|
||||
.subquery()
|
||||
query = query.filter(FileGroup.id.in_(tagged_fg_ids))
|
||||
if tag_names:
|
||||
from wrolpi.tags import Tag, TagFile
|
||||
tagged_fg_ids = session.query(TagFile.file_group_id) \
|
||||
.join(Tag, Tag.id == TagFile.tag_id) \
|
||||
.filter(Tag.name.in_(tag_names)) \
|
||||
.subquery()
|
||||
query = query.filter(FileGroup.id.in_(tagged_fg_ids))
|
||||
|
||||
unfiltered = not (search_str or author or subject or language or mimetype or tag_names)
|
||||
if unfiltered:
|
||||
total = cached_search_total(
|
||||
search_filter_cache_key('docs'),
|
||||
lambda: session.query(func.count(Doc.id)).scalar() or 0,
|
||||
)
|
||||
else:
|
||||
cache_key = search_filter_cache_key(
|
||||
'docs', search_str=search_str, author=author, subject=subject,
|
||||
language=language, mimetype=mimetype, tag_names=tag_names, deep=deep,
|
||||
)
|
||||
# Count before ORDER BY / LIMIT; cache by filters not page.
|
||||
total = cached_search_total(cache_key, lambda q=query: q.count())
|
||||
unfiltered = not (search_str or author or subject or language or mimetype or tag_names)
|
||||
if unfiltered:
|
||||
total = cached_search_total(
|
||||
search_filter_cache_key('docs'),
|
||||
lambda: session.query(func.count(Doc.id)).scalar() or 0,
|
||||
)
|
||||
else:
|
||||
cache_key = search_filter_cache_key(
|
||||
'docs', search_str=search_str, author=author, subject=subject,
|
||||
language=language, mimetype=mimetype, tag_names=tag_names, deep=deep,
|
||||
)
|
||||
# Count before ORDER BY / LIMIT; cache by filters not page.
|
||||
total = cached_search_total(cache_key, lambda q=query: q.count())
|
||||
|
||||
# Ordering.
|
||||
if order_by == 'rank' and fts_sq is not None:
|
||||
query = query.order_by(
|
||||
desc(fts_sq.c.ts_rank),
|
||||
desc(FileGroup.id),
|
||||
)
|
||||
elif order_by == 'published_datetime':
|
||||
query = query.order_by(nullslast(desc(FileGroup.published_datetime)), desc(FileGroup.id))
|
||||
elif order_by == 'size':
|
||||
query = query.order_by(nullslast(desc(Doc.size)))
|
||||
elif order_by == 'title':
|
||||
query = query.order_by(nullslast(asc(FileGroup.a_text)))
|
||||
else:
|
||||
query = query.order_by(desc(FileGroup.id))
|
||||
# Ordering.
|
||||
if order_by == 'rank' and fts_sq is not None:
|
||||
query = query.order_by(
|
||||
desc(fts_sq.c.ts_rank),
|
||||
desc(FileGroup.id),
|
||||
)
|
||||
elif order_by == 'published_datetime':
|
||||
query = query.order_by(nullslast(desc(FileGroup.published_datetime)), desc(FileGroup.id))
|
||||
elif order_by == 'size':
|
||||
query = query.order_by(nullslast(desc(Doc.size)))
|
||||
elif order_by == 'title':
|
||||
query = query.order_by(nullslast(asc(FileGroup.a_text)))
|
||||
else:
|
||||
query = query.order_by(desc(FileGroup.id))
|
||||
|
||||
# `size` sorts on a doc column and `title` has no file_group index, so neither may fall back to `id`.
|
||||
browse_sql = None
|
||||
if unfiltered and order_by not in ('size', 'title'):
|
||||
browse_sql = _doc_browse_sql(order_by if order_by in DOC_BROWSE_ORDERS else 'id')
|
||||
if browse_sql:
|
||||
fg_ids = [i for i, in session.execute(text(browse_sql), dict(limit=limit, offset=offset)).fetchall()]
|
||||
by_id = {fg.id: fg for fg in session.query(FileGroup).filter(FileGroup.id.in_(fg_ids))} if fg_ids else {}
|
||||
file_groups = [by_id[i] for i in fg_ids]
|
||||
else:
|
||||
file_groups = query.offset(offset).limit(limit).all()
|
||||
fg_ids = [fg.id for fg in file_groups]
|
||||
results = [fg.__json__() for fg in file_groups]
|
||||
# `size` sorts on a doc column and `title` has no file_group index, so neither may fall back to `id`.
|
||||
browse_sql = None
|
||||
if unfiltered and order_by not in ('size', 'title'):
|
||||
browse_sql = _doc_browse_sql(order_by if order_by in DOC_BROWSE_ORDERS else 'id')
|
||||
if browse_sql:
|
||||
fg_ids = [i for i, in session.execute(text(browse_sql), dict(limit=limit, offset=offset)).fetchall()]
|
||||
by_id = {fg.id: fg for fg in session.query(FileGroup).filter(FileGroup.id.in_(fg_ids))} if fg_ids else {}
|
||||
file_groups = [by_id[i] for i in fg_ids]
|
||||
else:
|
||||
file_groups = query.offset(offset).limit(limit).all()
|
||||
fg_ids = [fg.id for fg in file_groups]
|
||||
results = [fg.__json__() for fg in file_groups]
|
||||
|
||||
if search_str and fg_ids:
|
||||
hints = _fetch_section_hints(session, fg_ids, search_str)
|
||||
for r in results:
|
||||
hint = hints.get(r['id'])
|
||||
if hint:
|
||||
r['section_hint'] = hint
|
||||
if search_str and fg_ids:
|
||||
hints = _fetch_section_hints(session, fg_ids, search_str)
|
||||
for r in results:
|
||||
hint = hints.get(r['id'])
|
||||
if hint:
|
||||
r['section_hint'] = hint
|
||||
|
||||
return results, total
|
||||
|
||||
|
|
|
|||
|
|
@ -293,10 +293,10 @@ async def test_search_docs_attaches_section_hint_epub(test_session, test_directo
|
|||
])
|
||||
|
||||
# "mullen" is only in the document body (d_text), so a deep search is required to match it.
|
||||
results, total = _search_docs(search_str='mullen', mimetype='application/epub')
|
||||
results, total = _search_docs(test_session, search_str='mullen', mimetype='application/epub')
|
||||
assert total == 0, 'Document contents are not searched unless deep=True'
|
||||
|
||||
results, total = _search_docs(search_str='mullen', mimetype='application/epub', deep=True)
|
||||
results, total = _search_docs(test_session, search_str='mullen', mimetype='application/epub', deep=True)
|
||||
assert total == 1
|
||||
assert results[0]['id'] == fg.id
|
||||
hint = results[0]['section_hint']
|
||||
|
|
@ -318,7 +318,7 @@ async def test_search_docs_attaches_section_hint_pdf(test_session, test_director
|
|||
(3, 'Page 3', 'here is where mullen shows up'),
|
||||
])
|
||||
|
||||
results, total = _search_docs(search_str='mullen', mimetype='application/pdf', deep=True)
|
||||
results, total = _search_docs(test_session, search_str='mullen', mimetype='application/pdf', deep=True)
|
||||
assert total == 1
|
||||
assert results[0]['id'] == fg.id
|
||||
hint = results[0]['section_hint']
|
||||
|
|
@ -334,7 +334,7 @@ async def test_search_docs_no_hint_when_no_query(test_session, test_directory):
|
|||
'gamma.pdf', 'application/pdf', [
|
||||
(1, 'Page 1', 'whatever'),
|
||||
])
|
||||
results, _ = _search_docs(mimetype='application/pdf')
|
||||
results, _ = _search_docs(test_session, mimetype='application/pdf')
|
||||
assert results and results[0]['id'] == fg.id
|
||||
assert 'section_hint' not in results[0]
|
||||
|
||||
|
|
@ -360,15 +360,15 @@ async def test_search_docs_browse_walks_file_group_date_index(test_session, test
|
|||
assert 'TEMP B-TREE' not in plan, plan
|
||||
|
||||
# Newest first, NULL published dates last, same as the filtered ORM path.
|
||||
results, total = _search_docs()
|
||||
results, total = _search_docs(test_session, )
|
||||
assert total == 3
|
||||
assert [i['id'] for i in results] == [docs[2].file_group_id, docs[1].file_group_id, docs[0].file_group_id]
|
||||
|
||||
# Paging still works on the fast path.
|
||||
results, total = _search_docs(limit=1, offset=1)
|
||||
results, total = _search_docs(test_session, limit=1, offset=1)
|
||||
assert total == 3
|
||||
assert [i['id'] for i in results] == [docs[1].file_group_id]
|
||||
|
||||
# Filtered searches are unaffected.
|
||||
results, total = _search_docs(mimetype='application/pdf')
|
||||
results, total = _search_docs(test_session, mimetype='application/pdf')
|
||||
assert total == 3
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue