dojinvoice_db.db

SQLite storage for DLsite voice works.

The schema separates three kinds of data by how expensive they are to obtain and how often they change:

  • work — metadata. summary_fetched_at marks the cheap ajax-sourced columns, detail_fetched_at the ones that cost one request per work. A NULL detail_fetched_at is the resume marker: those works are picked up by the next run.
  • work_stat (+ work_stat_history) — price/sales/rating figures, which keep changing and can be refreshed in batches of 100 works per request.
  • work_creator / work_genre / work_file_format / work_event / work_sample_image — the multi-valued detail fields.

fetch_error remembers works that failed so repeated runs do not keep re-requesting them, and crawl_state holds bookkeeping between runs.

  1"""SQLite storage for DLsite voice works.
  2
  3The schema separates three kinds of data by how expensive they are to obtain
  4and how often they change:
  5
  6* ``work`` — metadata. ``summary_fetched_at`` marks the cheap ajax-sourced
  7  columns, ``detail_fetched_at`` the ones that cost one request per work.
  8  A NULL ``detail_fetched_at`` is the resume marker: those works are picked up
  9  by the next run.
 10* ``work_stat`` (+ ``work_stat_history``) — price/sales/rating figures, which
 11  keep changing and can be refreshed in batches of 100 works per request.
 12* ``work_creator`` / ``work_genre`` / ``work_file_format`` / ``work_event`` /
 13  ``work_sample_image`` — the multi-valued detail fields.
 14
 15``fetch_error`` remembers works that failed so repeated runs do not keep
 16re-requesting them, and ``crawl_state`` holds bookkeeping between runs.
 17"""
 18
 19from __future__ import annotations
 20
 21import sqlite3
 22from datetime import datetime
 23from pathlib import Path
 24from typing import TYPE_CHECKING, Any, Self
 25
 26from dlsite_async import AgeCategory, BookType, Work, WorkType
 27
 28from .models import parse_file_size
 29
 30if TYPE_CHECKING:
 31    from collections.abc import Sequence
 32    from types import TracebackType
 33
 34    from .models import WorkStats
 35
 36SCHEMA_VERSION = 1
 37
 38MAX_ERROR_ATTEMPTS = 3
 39"""Works that failed this many times are skipped unless ``--retry-errors``."""
 40
 41CREATOR_ROLES = ("voice_actor", "scenario", "illustration", "music", "author", "writer")
 42"""``Work`` list attributes stored as ``work_creator`` rows."""
 43
 44_SCHEMA = """
 45create table work (
 46    product_id         text primary key,
 47    site_id            text,
 48    maker_id           text,
 49    work_name          text not null,
 50    work_name_masked   text,
 51    age_category       integer,
 52    work_type          text,
 53    book_type          text,
 54    work_image         text,
 55    regist_date        text,
 56    announce_date      text,
 57    modified_date      text,
 58    series             text,
 59    circle             text,
 60    brand              text,
 61    publisher          text,
 62    label              text,
 63    description        text,
 64    file_size          text,
 65    file_size_bytes    integer,
 66    page_count         integer,
 67    work_url           text,
 68    first_seen_at      text not null,
 69    summary_fetched_at text,
 70    detail_fetched_at  text
 71);
 72create index work_regist_date_idx on work (regist_date desc);
 73create index work_maker_idx on work (maker_id);
 74create index work_type_idx on work (work_type);
 75create index work_detail_pending_idx on work (detail_fetched_at);
 76
 77create table work_stat (
 78    product_id        text primary key references work (product_id) on delete cascade,
 79    price             integer,
 80    price_without_tax integer,
 81    official_price    integer,
 82    discount_rate     integer,
 83    dl_count          integer,
 84    wishlist_count    integer,
 85    rate_average      real,
 86    rate_count        integer,
 87    review_count      integer,
 88    is_sale           integer,
 89    is_discount       integer,
 90    fetched_at        text not null
 91);
 92
 93create table work_stat_history (
 94    product_id     text not null references work (product_id) on delete cascade,
 95    fetched_at     text not null,
 96    price          integer,
 97    dl_count       integer,
 98    wishlist_count integer,
 99    rate_average   real,
100    rate_count     integer,
101    review_count   integer
102);
103create index work_stat_history_idx on work_stat_history (product_id, fetched_at);
104
105create table work_creator (
106    product_id text not null references work (product_id) on delete cascade,
107    role       text not null,
108    name       text not null,
109    primary key (product_id, role, name)
110);
111create index work_creator_name_idx on work_creator (name);
112
113create table work_genre (
114    product_id text not null references work (product_id) on delete cascade,
115    genre      text not null,
116    primary key (product_id, genre)
117);
118create index work_genre_idx on work_genre (genre);
119
120create table work_file_format (
121    product_id  text not null references work (product_id) on delete cascade,
122    file_format text not null,
123    primary key (product_id, file_format)
124);
125
126create table work_event (
127    product_id text not null references work (product_id) on delete cascade,
128    event      text not null,
129    primary key (product_id, event)
130);
131
132create table work_sample_image (
133    product_id text not null references work (product_id) on delete cascade,
134    idx        integer not null,
135    url        text not null,
136    primary key (product_id, idx)
137);
138
139create table fetch_error (
140    product_id      text primary key,
141    attempts        integer not null default 0,
142    last_error      text,
143    last_attempt_at text
144);
145
146create table crawl_state (
147    key   text primary key,
148    value text
149);
150
151create view work_full as
152select
153    w.*,
154    s.price,
155    s.dl_count,
156    s.wishlist_count,
157    s.rate_average,
158    s.rate_count,
159    s.review_count,
160    (select group_concat(c.name, ', ') from work_creator c
161      where c.product_id = w.product_id and c.role = 'voice_actor') as voice_actors,
162    (select group_concat(c.name, ', ') from work_creator c
163      where c.product_id = w.product_id and c.role = 'scenario') as scenarios,
164    (select group_concat(c.name, ', ') from work_creator c
165      where c.product_id = w.product_id and c.role = 'illustration') as illustrations,
166    (select group_concat(g.genre, ', ') from work_genre g
167      where g.product_id = w.product_id) as genres
168from work w
169left join work_stat s on s.product_id = w.product_id;
170"""
171
172_SUMMARY_COLUMNS = (
173    "site_id",
174    "maker_id",
175    "work_name",
176    "work_name_masked",
177    "age_category",
178    "work_type",
179    "book_type",
180    "work_image",
181    "regist_date",
182    "series",
183    "work_url",
184)
185
186_DETAIL_COLUMNS = (
187    "circle",
188    "brand",
189    "publisher",
190    "label",
191    "description",
192    "file_size",
193    "file_size_bytes",
194    "page_count",
195    "announce_date",
196    "modified_date",
197)
198
199_STAT_COLUMNS = (
200    "price",
201    "price_without_tax",
202    "official_price",
203    "discount_rate",
204    "dl_count",
205    "wishlist_count",
206    "rate_average",
207    "rate_count",
208    "review_count",
209    "is_sale",
210    "is_discount",
211)
212
213_HISTORY_COLUMNS = ("price", "dl_count", "wishlist_count", "rate_average", "rate_count", "review_count")
214
215
216class SchemaVersionError(RuntimeError):
217    """The database file was written by an incompatible version."""
218
219
220def to_iso(value: datetime | None) -> str | None:
221    """Render a datetime the way it is stored (``YYYY-MM-DD HH:MM:SS``)."""
222    if value is None:
223        return None
224    return value.isoformat(sep=" ", timespec="seconds")
225
226
227def from_iso(value: str | None) -> datetime | None:
228    """Parse a datetime stored by :func:`to_iso`."""
229    if not value:
230        return None
231    try:
232        return datetime.fromisoformat(value)
233    except ValueError:  # pragma: no cover - defensive
234        return None
235
236
237def _enum(enum_cls: Any, value: Any) -> Any:  # noqa: ANN401 - generic enum helper
238    if value is None:
239        return None
240    try:
241        return enum_cls(value)
242    except ValueError:  # pragma: no cover - defensive
243        return None
244
245
246def work_url(work: Work) -> str:
247    """Return the public work page URL for ``work``."""
248    return f"https://www.dlsite.com/{work.site_id or 'maniax'}/work/=/product_id/{work.product_id}.html"
249
250
251def _summary_values(work: Work) -> dict[str, Any]:
252    return {
253        "site_id": work.site_id,
254        "maker_id": work.maker_id,
255        "work_name": work.work_name,
256        "work_name_masked": work.work_name_masked,
257        "age_category": int(work.age_category) if work.age_category is not None else None,
258        "work_type": work.work_type.value if work.work_type else None,
259        "book_type": work.book_type.value if work.book_type else None,
260        "work_image": work.work_image,
261        "regist_date": to_iso(work.regist_date),
262        "series": work.series,
263        "work_url": work_url(work),
264    }
265
266
267def _detail_values(work: Work) -> dict[str, Any]:
268    return {
269        "circle": work.circle,
270        "brand": work.brand,
271        "publisher": work.publisher,
272        "label": work.label,
273        "description": work.description,
274        "file_size": work.file_size,
275        "file_size_bytes": parse_file_size(work.file_size),
276        "page_count": work.page_count,
277        "announce_date": to_iso(work.announce_date),
278        "modified_date": to_iso(work.modified_date),
279    }
280
281
282class WorkDatabase:
283    """SQLite database of DLsite voice works.
284
285    Args:
286        path: Database file path. ``:memory:`` is accepted for tests.
287    """
288
289    def __init__(self, path: str | Path) -> None:
290        self.path = str(path)
291        if self.path != ":memory:":
292            Path(self.path).parent.mkdir(parents=True, exist_ok=True)
293        self.conn = sqlite3.connect(self.path)
294        self.conn.row_factory = sqlite3.Row
295        self.conn.execute("pragma journal_mode = wal")
296        self.conn.execute("pragma foreign_keys = on")
297        try:
298            self._migrate()
299        except Exception:
300            self.conn.close()
301            raise
302
303    def __enter__(self) -> Self:
304        """Enter the database context."""
305        return self
306
307    def __exit__(
308        self,
309        exc_type: type[BaseException] | None,
310        exc: BaseException | None,
311        tb: TracebackType | None,
312    ) -> None:
313        """Close the database."""
314        self.close()
315
316    def close(self) -> None:
317        """Close the underlying connection."""
318        self.conn.close()
319
320    def _migrate(self) -> None:
321        version = int(self.conn.execute("pragma user_version").fetchone()[0])
322        if version == 0:
323            with self.conn:
324                self.conn.executescript(_SCHEMA)
325                self.conn.execute(f"pragma user_version = {SCHEMA_VERSION}")
326        elif version > SCHEMA_VERSION:
327            msg = f"{self.path} was created by a newer dojinvoice-db (schema v{version} > v{SCHEMA_VERSION})"
328            raise SchemaVersionError(msg)
329
330    # -- writes ---------------------------------------------------------
331
332    def upsert_work(self, work: Work, *, detail: bool, now: datetime | None = None) -> None:
333        """Insert or update ``work``.
334
335        Args:
336            work: The work to store.
337            detail: Whether ``work`` carries the work-page fields. When false,
338                only the cheap ajax-sourced columns are touched, so existing
339                detail columns are never overwritten with NULLs.
340            now: Timestamp recorded as the fetch time (defaults to now).
341        """
342        stamp = to_iso(now or datetime.now().astimezone())
343        values = _summary_values(work)
344        columns = list(_SUMMARY_COLUMNS)
345        if detail:
346            values |= _detail_values(work)
347            columns += [*_DETAIL_COLUMNS, "detail_fetched_at"]
348            values["detail_fetched_at"] = stamp
349        else:
350            columns.append("summary_fetched_at")
351            values["summary_fetched_at"] = stamp
352        values["product_id"] = work.product_id
353        values["first_seen_at"] = stamp
354        insert_columns = ["product_id", "first_seen_at", *columns]
355        placeholders = ",".join("?" * len(insert_columns))
356        updates = ",".join(f"{c} = excluded.{c}" for c in columns)
357        with self.conn:
358            self.conn.execute(
359                f"insert into work ({','.join(insert_columns)}) values ({placeholders}) "  # noqa: S608
360                f"on conflict (product_id) do update set {updates}",
361                [values[c] for c in insert_columns],
362            )
363            if detail:
364                self._replace_children(work)
365
366    def _replace_children(self, work: Work) -> None:
367        pid = work.product_id
368        creators = [(pid, role, name) for role in CREATOR_ROLES for name in getattr(work, role, None) or []]
369        self.conn.execute("delete from work_creator where product_id = ?", (pid,))
370        self.conn.executemany("insert or ignore into work_creator values (?,?,?)", creators)
371
372        for table, column, items in (
373            ("work_genre", "genre", work.genre),
374            ("work_file_format", "file_format", work.file_format),
375            ("work_event", "event", work.event),
376        ):
377            self.conn.execute(f"delete from {table} where product_id = ?", (pid,))  # noqa: S608
378            self.conn.executemany(
379                f"insert or ignore into {table} (product_id, {column}) values (?,?)",  # noqa: S608
380                [(pid, item) for item in items or []],
381            )
382
383        self.conn.execute("delete from work_sample_image where product_id = ?", (pid,))
384        self.conn.executemany(
385            "insert or ignore into work_sample_image values (?,?,?)",
386            [(pid, i, url) for i, url in enumerate(work.sample_images or [])],
387        )
388
389    def upsert_stats(self, stats: WorkStats, *, now: datetime | None = None) -> bool:
390        """Store ``stats``, appending to the history only when figures changed.
391
392        Returns:
393            Whether a history row was appended.
394        """
395        stamp = to_iso(now or datetime.now().astimezone())
396        values = {c: getattr(stats, c) for c in _STAT_COLUMNS}
397        previous = self.conn.execute(
398            f"select {','.join(_HISTORY_COLUMNS)} from work_stat where product_id = ?",  # noqa: S608
399            (stats.product_id,),
400        ).fetchone()
401        changed = previous is None or any(previous[c] != values[c] for c in _HISTORY_COLUMNS)
402        columns = ["product_id", *_STAT_COLUMNS, "fetched_at"]
403        placeholders = ",".join("?" * len(columns))
404        updates = ",".join(f"{c} = excluded.{c}" for c in (*_STAT_COLUMNS, "fetched_at"))
405        with self.conn:
406            self.conn.execute(
407                f"insert into work_stat ({','.join(columns)}) values ({placeholders}) "  # noqa: S608
408                f"on conflict (product_id) do update set {updates}",
409                [stats.product_id, *(values[c] for c in _STAT_COLUMNS), stamp],
410            )
411            if changed:
412                self.conn.execute(
413                    f"insert into work_stat_history "  # noqa: S608
414                    f"(product_id, fetched_at, {','.join(_HISTORY_COLUMNS)}) "
415                    f"values ({','.join('?' * (len(_HISTORY_COLUMNS) + 2))})",
416                    [stats.product_id, stamp, *(values[c] for c in _HISTORY_COLUMNS)],
417                )
418        return changed
419
420    def record_error(self, product_id: str, message: str, *, now: datetime | None = None) -> None:
421        """Record a failed fetch so later runs can skip or retry it."""
422        stamp = to_iso(now or datetime.now().astimezone())
423        with self.conn:
424            self.conn.execute(
425                "insert into fetch_error (product_id, attempts, last_error, last_attempt_at) "
426                "values (?, 1, ?, ?) "
427                "on conflict (product_id) do update set "
428                "attempts = attempts + 1, last_error = excluded.last_error, "
429                "last_attempt_at = excluded.last_attempt_at",
430                (product_id, message[:500], stamp),
431            )
432
433    def clear_error(self, product_id: str) -> None:
434        """Forget a previously recorded fetch failure."""
435        with self.conn:
436            self.conn.execute("delete from fetch_error where product_id = ?", (product_id,))
437
438    def set_state(self, key: str, value: str) -> None:
439        """Store a bookkeeping value."""
440        with self.conn:
441            self.conn.execute(
442                "insert into crawl_state (key, value) values (?,?) "
443                "on conflict (key) do update set value = excluded.value",
444                (key, value),
445            )
446
447    def get_state(self, key: str) -> str | None:
448        """Read a bookkeeping value."""
449        row = self.conn.execute("select value from crawl_state where key = ?", (key,)).fetchone()
450        return None if row is None else row["value"]
451
452    # -- reads ----------------------------------------------------------
453
454    def known_product_ids(self) -> set[str]:
455        """Return every product ID already stored."""
456        return {row[0] for row in self.conn.execute("select product_id from work")}
457
458    def count_works(self) -> int:
459        """Return the number of stored works."""
460        return int(self.conn.execute("select count(*) from work").fetchone()[0])
461
462    def pending_detail_ids(
463        self,
464        *,
465        limit: int | None = None,
466        stale_before: datetime | None = None,
467        retry_errors: bool = False,
468        now: datetime | None = None,
469    ) -> list[str]:
470        """Return works whose work-page detail should be fetched.
471
472        A work is pending when its detail was never fetched, when it was
473        fetched before ``stale_before``, or when it was fetched while the work
474        was still an announcement and has since been released -- announced
475        works are not re-fetched every run, only once after release.
476        """
477        conditions = [
478            "w.detail_fetched_at is null",
479            (
480                "(w.regist_date is not null and w.detail_fetched_at is not null"
481                " and w.regist_date > w.detail_fetched_at and w.regist_date <= ?)"
482            ),
483        ]
484        params: list[Any] = [to_iso(now or datetime.now().astimezone())]
485        if stale_before is not None:
486            conditions.append("w.detail_fetched_at < ?")
487            params.append(to_iso(stale_before))
488        sql = f"select w.product_id from work w where ({' or '.join(conditions)})"  # noqa: S608
489        if not retry_errors:
490            sql += " and not exists (select 1 from fetch_error e where e.product_id = w.product_id and e.attempts >= ?)"
491            params.append(MAX_ERROR_ATTEMPTS)
492        sql += " order by w.regist_date desc"
493        if limit is not None:
494            sql += " limit ?"
495            params.append(limit)
496        return [row[0] for row in self.conn.execute(sql, params)]
497
498    def stale_stat_ids(self, *, stale_before: datetime | None = None, limit: int | None = None) -> list[str]:
499        """Return works whose stats are missing or older than ``stale_before``.
500
501        Ordered oldest-first so an interrupted refresh resumes where it left off.
502        """
503        sql = "select w.product_id from work w left join work_stat s on s.product_id = w.product_id"
504        params: list[Any] = []
505        if stale_before is not None:
506            sql += " where s.fetched_at is null or s.fetched_at < ?"
507            params.append(to_iso(stale_before))
508        sql += " order by s.fetched_at is not null, s.fetched_at"
509        if limit is not None:
510            sql += " limit ?"
511            params.append(limit)
512        return [row[0] for row in self.conn.execute(sql, params)]
513
514    def load_work(self, product_id: str) -> Work | None:
515        """Rebuild a :class:`~dlsite_async.Work` from the stored summary columns.
516
517        Used to fetch a work's detail page on a later run without re-requesting
518        the ajax info that produced the row in the first place.
519        """
520        row = self.conn.execute("select * from work where product_id = ?", (product_id,)).fetchone()
521        if row is None:
522            return None
523        return Work(
524            product_id=row["product_id"],
525            site_id=row["site_id"] or "maniax",
526            maker_id=row["maker_id"],
527            work_name=row["work_name"],
528            age_category=_enum(AgeCategory, row["age_category"]),
529            work_name_masked=row["work_name_masked"],
530            work_type=_enum(WorkType, row["work_type"]),
531            book_type=_enum(BookType, row["book_type"]),
532            work_image=row["work_image"],
533            regist_date=from_iso(row["regist_date"]),
534            title_name_masked=row["series"],
535        )
536
537    def get_work(self, product_id: str) -> dict[str, Any] | None:
538        """Return one work with its stats and multi-valued fields, or ``None``."""
539        row = self.conn.execute("select * from work where product_id = ?", (product_id,)).fetchone()
540        if row is None:
541            return None
542        result = dict(row)
543        stat = self.conn.execute("select * from work_stat where product_id = ?", (product_id,)).fetchone()
544        result["stats"] = dict(stat) if stat else None
545        creators: dict[str, list[str]] = {}
546        for crow in self.conn.execute(
547            "select role, name from work_creator where product_id = ? order by role, rowid",
548            (product_id,),
549        ):
550            creators.setdefault(crow["role"], []).append(crow["name"])
551        result["creators"] = creators
552        for key, table, column in (
553            ("genres", "work_genre", "genre"),
554            ("file_formats", "work_file_format", "file_format"),
555            ("events", "work_event", "event"),
556        ):
557            result[key] = [
558                r[0]
559                for r in self.conn.execute(
560                    f"select {column} from {table} where product_id = ? order by rowid",  # noqa: S608
561                    (product_id,),
562                )
563            ]
564        result["sample_images"] = [
565            r[0]
566            for r in self.conn.execute(
567                "select url from work_sample_image where product_id = ? order by idx",
568                (product_id,),
569            )
570        ]
571        return result
572
573    def summary(self) -> dict[str, Any]:
574        """Return aggregate counts for the ``stats`` command."""
575        row = self.conn.execute(
576            "select count(*) as works,"
577            " sum(detail_fetched_at is not null) as detailed,"
578            " min(regist_date) as oldest,"
579            " max(regist_date) as newest"
580            " from work",
581        ).fetchone()
582        return {
583            "works": row["works"],
584            "detailed": row["detailed"] or 0,
585            "pending_detail": row["works"] - (row["detailed"] or 0),
586            "oldest_release": row["oldest"],
587            "newest_release": row["newest"],
588            "circles": self.conn.execute("select count(distinct maker_id) from work").fetchone()[0],
589            "voice_actors": self.conn.execute(
590                "select count(distinct name) from work_creator where role = 'voice_actor'",
591            ).fetchone()[0],
592            "genres": self.conn.execute("select count(distinct genre) from work_genre").fetchone()[0],
593            "errors": self.conn.execute("select count(*) from fetch_error").fetchone()[0],
594            "last_crawl": self.get_state("last_crawl_at"),
595        }
596
597    def top_rows(self, sql: str, params: Sequence[Any] = ()) -> list[dict[str, Any]]:
598        """Run a read-only query and return the rows as dicts."""
599        return [dict(row) for row in self.conn.execute(sql, params)]
SCHEMA_VERSION = 1
MAX_ERROR_ATTEMPTS = 3

Works that failed this many times are skipped unless --retry-errors.

CREATOR_ROLES = ('voice_actor', 'scenario', 'illustration', 'music', 'author', 'writer')

Work list attributes stored as work_creator rows.

class SchemaVersionError(builtins.RuntimeError):
217class SchemaVersionError(RuntimeError):
218    """The database file was written by an incompatible version."""

The database file was written by an incompatible version.

def to_iso(value: datetime.datetime | None) -> str | None:
221def to_iso(value: datetime | None) -> str | None:
222    """Render a datetime the way it is stored (``YYYY-MM-DD HH:MM:SS``)."""
223    if value is None:
224        return None
225    return value.isoformat(sep=" ", timespec="seconds")

Render a datetime the way it is stored (YYYY-MM-DD HH:MM:SS).

def from_iso(value: str | None) -> datetime.datetime | None:
228def from_iso(value: str | None) -> datetime | None:
229    """Parse a datetime stored by :func:`to_iso`."""
230    if not value:
231        return None
232    try:
233        return datetime.fromisoformat(value)
234    except ValueError:  # pragma: no cover - defensive
235        return None

Parse a datetime stored by to_iso().

def work_url(work: dlsite_async.work.Work) -> str:
247def work_url(work: Work) -> str:
248    """Return the public work page URL for ``work``."""
249    return f"https://www.dlsite.com/{work.site_id or 'maniax'}/work/=/product_id/{work.product_id}.html"

Return the public work page URL for work.

class WorkDatabase:
283class WorkDatabase:
284    """SQLite database of DLsite voice works.
285
286    Args:
287        path: Database file path. ``:memory:`` is accepted for tests.
288    """
289
290    def __init__(self, path: str | Path) -> None:
291        self.path = str(path)
292        if self.path != ":memory:":
293            Path(self.path).parent.mkdir(parents=True, exist_ok=True)
294        self.conn = sqlite3.connect(self.path)
295        self.conn.row_factory = sqlite3.Row
296        self.conn.execute("pragma journal_mode = wal")
297        self.conn.execute("pragma foreign_keys = on")
298        try:
299            self._migrate()
300        except Exception:
301            self.conn.close()
302            raise
303
304    def __enter__(self) -> Self:
305        """Enter the database context."""
306        return self
307
308    def __exit__(
309        self,
310        exc_type: type[BaseException] | None,
311        exc: BaseException | None,
312        tb: TracebackType | None,
313    ) -> None:
314        """Close the database."""
315        self.close()
316
317    def close(self) -> None:
318        """Close the underlying connection."""
319        self.conn.close()
320
321    def _migrate(self) -> None:
322        version = int(self.conn.execute("pragma user_version").fetchone()[0])
323        if version == 0:
324            with self.conn:
325                self.conn.executescript(_SCHEMA)
326                self.conn.execute(f"pragma user_version = {SCHEMA_VERSION}")
327        elif version > SCHEMA_VERSION:
328            msg = f"{self.path} was created by a newer dojinvoice-db (schema v{version} > v{SCHEMA_VERSION})"
329            raise SchemaVersionError(msg)
330
331    # -- writes ---------------------------------------------------------
332
333    def upsert_work(self, work: Work, *, detail: bool, now: datetime | None = None) -> None:
334        """Insert or update ``work``.
335
336        Args:
337            work: The work to store.
338            detail: Whether ``work`` carries the work-page fields. When false,
339                only the cheap ajax-sourced columns are touched, so existing
340                detail columns are never overwritten with NULLs.
341            now: Timestamp recorded as the fetch time (defaults to now).
342        """
343        stamp = to_iso(now or datetime.now().astimezone())
344        values = _summary_values(work)
345        columns = list(_SUMMARY_COLUMNS)
346        if detail:
347            values |= _detail_values(work)
348            columns += [*_DETAIL_COLUMNS, "detail_fetched_at"]
349            values["detail_fetched_at"] = stamp
350        else:
351            columns.append("summary_fetched_at")
352            values["summary_fetched_at"] = stamp
353        values["product_id"] = work.product_id
354        values["first_seen_at"] = stamp
355        insert_columns = ["product_id", "first_seen_at", *columns]
356        placeholders = ",".join("?" * len(insert_columns))
357        updates = ",".join(f"{c} = excluded.{c}" for c in columns)
358        with self.conn:
359            self.conn.execute(
360                f"insert into work ({','.join(insert_columns)}) values ({placeholders}) "  # noqa: S608
361                f"on conflict (product_id) do update set {updates}",
362                [values[c] for c in insert_columns],
363            )
364            if detail:
365                self._replace_children(work)
366
367    def _replace_children(self, work: Work) -> None:
368        pid = work.product_id
369        creators = [(pid, role, name) for role in CREATOR_ROLES for name in getattr(work, role, None) or []]
370        self.conn.execute("delete from work_creator where product_id = ?", (pid,))
371        self.conn.executemany("insert or ignore into work_creator values (?,?,?)", creators)
372
373        for table, column, items in (
374            ("work_genre", "genre", work.genre),
375            ("work_file_format", "file_format", work.file_format),
376            ("work_event", "event", work.event),
377        ):
378            self.conn.execute(f"delete from {table} where product_id = ?", (pid,))  # noqa: S608
379            self.conn.executemany(
380                f"insert or ignore into {table} (product_id, {column}) values (?,?)",  # noqa: S608
381                [(pid, item) for item in items or []],
382            )
383
384        self.conn.execute("delete from work_sample_image where product_id = ?", (pid,))
385        self.conn.executemany(
386            "insert or ignore into work_sample_image values (?,?,?)",
387            [(pid, i, url) for i, url in enumerate(work.sample_images or [])],
388        )
389
390    def upsert_stats(self, stats: WorkStats, *, now: datetime | None = None) -> bool:
391        """Store ``stats``, appending to the history only when figures changed.
392
393        Returns:
394            Whether a history row was appended.
395        """
396        stamp = to_iso(now or datetime.now().astimezone())
397        values = {c: getattr(stats, c) for c in _STAT_COLUMNS}
398        previous = self.conn.execute(
399            f"select {','.join(_HISTORY_COLUMNS)} from work_stat where product_id = ?",  # noqa: S608
400            (stats.product_id,),
401        ).fetchone()
402        changed = previous is None or any(previous[c] != values[c] for c in _HISTORY_COLUMNS)
403        columns = ["product_id", *_STAT_COLUMNS, "fetched_at"]
404        placeholders = ",".join("?" * len(columns))
405        updates = ",".join(f"{c} = excluded.{c}" for c in (*_STAT_COLUMNS, "fetched_at"))
406        with self.conn:
407            self.conn.execute(
408                f"insert into work_stat ({','.join(columns)}) values ({placeholders}) "  # noqa: S608
409                f"on conflict (product_id) do update set {updates}",
410                [stats.product_id, *(values[c] for c in _STAT_COLUMNS), stamp],
411            )
412            if changed:
413                self.conn.execute(
414                    f"insert into work_stat_history "  # noqa: S608
415                    f"(product_id, fetched_at, {','.join(_HISTORY_COLUMNS)}) "
416                    f"values ({','.join('?' * (len(_HISTORY_COLUMNS) + 2))})",
417                    [stats.product_id, stamp, *(values[c] for c in _HISTORY_COLUMNS)],
418                )
419        return changed
420
421    def record_error(self, product_id: str, message: str, *, now: datetime | None = None) -> None:
422        """Record a failed fetch so later runs can skip or retry it."""
423        stamp = to_iso(now or datetime.now().astimezone())
424        with self.conn:
425            self.conn.execute(
426                "insert into fetch_error (product_id, attempts, last_error, last_attempt_at) "
427                "values (?, 1, ?, ?) "
428                "on conflict (product_id) do update set "
429                "attempts = attempts + 1, last_error = excluded.last_error, "
430                "last_attempt_at = excluded.last_attempt_at",
431                (product_id, message[:500], stamp),
432            )
433
434    def clear_error(self, product_id: str) -> None:
435        """Forget a previously recorded fetch failure."""
436        with self.conn:
437            self.conn.execute("delete from fetch_error where product_id = ?", (product_id,))
438
439    def set_state(self, key: str, value: str) -> None:
440        """Store a bookkeeping value."""
441        with self.conn:
442            self.conn.execute(
443                "insert into crawl_state (key, value) values (?,?) "
444                "on conflict (key) do update set value = excluded.value",
445                (key, value),
446            )
447
448    def get_state(self, key: str) -> str | None:
449        """Read a bookkeeping value."""
450        row = self.conn.execute("select value from crawl_state where key = ?", (key,)).fetchone()
451        return None if row is None else row["value"]
452
453    # -- reads ----------------------------------------------------------
454
455    def known_product_ids(self) -> set[str]:
456        """Return every product ID already stored."""
457        return {row[0] for row in self.conn.execute("select product_id from work")}
458
459    def count_works(self) -> int:
460        """Return the number of stored works."""
461        return int(self.conn.execute("select count(*) from work").fetchone()[0])
462
463    def pending_detail_ids(
464        self,
465        *,
466        limit: int | None = None,
467        stale_before: datetime | None = None,
468        retry_errors: bool = False,
469        now: datetime | None = None,
470    ) -> list[str]:
471        """Return works whose work-page detail should be fetched.
472
473        A work is pending when its detail was never fetched, when it was
474        fetched before ``stale_before``, or when it was fetched while the work
475        was still an announcement and has since been released -- announced
476        works are not re-fetched every run, only once after release.
477        """
478        conditions = [
479            "w.detail_fetched_at is null",
480            (
481                "(w.regist_date is not null and w.detail_fetched_at is not null"
482                " and w.regist_date > w.detail_fetched_at and w.regist_date <= ?)"
483            ),
484        ]
485        params: list[Any] = [to_iso(now or datetime.now().astimezone())]
486        if stale_before is not None:
487            conditions.append("w.detail_fetched_at < ?")
488            params.append(to_iso(stale_before))
489        sql = f"select w.product_id from work w where ({' or '.join(conditions)})"  # noqa: S608
490        if not retry_errors:
491            sql += " and not exists (select 1 from fetch_error e where e.product_id = w.product_id and e.attempts >= ?)"
492            params.append(MAX_ERROR_ATTEMPTS)
493        sql += " order by w.regist_date desc"
494        if limit is not None:
495            sql += " limit ?"
496            params.append(limit)
497        return [row[0] for row in self.conn.execute(sql, params)]
498
499    def stale_stat_ids(self, *, stale_before: datetime | None = None, limit: int | None = None) -> list[str]:
500        """Return works whose stats are missing or older than ``stale_before``.
501
502        Ordered oldest-first so an interrupted refresh resumes where it left off.
503        """
504        sql = "select w.product_id from work w left join work_stat s on s.product_id = w.product_id"
505        params: list[Any] = []
506        if stale_before is not None:
507            sql += " where s.fetched_at is null or s.fetched_at < ?"
508            params.append(to_iso(stale_before))
509        sql += " order by s.fetched_at is not null, s.fetched_at"
510        if limit is not None:
511            sql += " limit ?"
512            params.append(limit)
513        return [row[0] for row in self.conn.execute(sql, params)]
514
515    def load_work(self, product_id: str) -> Work | None:
516        """Rebuild a :class:`~dlsite_async.Work` from the stored summary columns.
517
518        Used to fetch a work's detail page on a later run without re-requesting
519        the ajax info that produced the row in the first place.
520        """
521        row = self.conn.execute("select * from work where product_id = ?", (product_id,)).fetchone()
522        if row is None:
523            return None
524        return Work(
525            product_id=row["product_id"],
526            site_id=row["site_id"] or "maniax",
527            maker_id=row["maker_id"],
528            work_name=row["work_name"],
529            age_category=_enum(AgeCategory, row["age_category"]),
530            work_name_masked=row["work_name_masked"],
531            work_type=_enum(WorkType, row["work_type"]),
532            book_type=_enum(BookType, row["book_type"]),
533            work_image=row["work_image"],
534            regist_date=from_iso(row["regist_date"]),
535            title_name_masked=row["series"],
536        )
537
538    def get_work(self, product_id: str) -> dict[str, Any] | None:
539        """Return one work with its stats and multi-valued fields, or ``None``."""
540        row = self.conn.execute("select * from work where product_id = ?", (product_id,)).fetchone()
541        if row is None:
542            return None
543        result = dict(row)
544        stat = self.conn.execute("select * from work_stat where product_id = ?", (product_id,)).fetchone()
545        result["stats"] = dict(stat) if stat else None
546        creators: dict[str, list[str]] = {}
547        for crow in self.conn.execute(
548            "select role, name from work_creator where product_id = ? order by role, rowid",
549            (product_id,),
550        ):
551            creators.setdefault(crow["role"], []).append(crow["name"])
552        result["creators"] = creators
553        for key, table, column in (
554            ("genres", "work_genre", "genre"),
555            ("file_formats", "work_file_format", "file_format"),
556            ("events", "work_event", "event"),
557        ):
558            result[key] = [
559                r[0]
560                for r in self.conn.execute(
561                    f"select {column} from {table} where product_id = ? order by rowid",  # noqa: S608
562                    (product_id,),
563                )
564            ]
565        result["sample_images"] = [
566            r[0]
567            for r in self.conn.execute(
568                "select url from work_sample_image where product_id = ? order by idx",
569                (product_id,),
570            )
571        ]
572        return result
573
574    def summary(self) -> dict[str, Any]:
575        """Return aggregate counts for the ``stats`` command."""
576        row = self.conn.execute(
577            "select count(*) as works,"
578            " sum(detail_fetched_at is not null) as detailed,"
579            " min(regist_date) as oldest,"
580            " max(regist_date) as newest"
581            " from work",
582        ).fetchone()
583        return {
584            "works": row["works"],
585            "detailed": row["detailed"] or 0,
586            "pending_detail": row["works"] - (row["detailed"] or 0),
587            "oldest_release": row["oldest"],
588            "newest_release": row["newest"],
589            "circles": self.conn.execute("select count(distinct maker_id) from work").fetchone()[0],
590            "voice_actors": self.conn.execute(
591                "select count(distinct name) from work_creator where role = 'voice_actor'",
592            ).fetchone()[0],
593            "genres": self.conn.execute("select count(distinct genre) from work_genre").fetchone()[0],
594            "errors": self.conn.execute("select count(*) from fetch_error").fetchone()[0],
595            "last_crawl": self.get_state("last_crawl_at"),
596        }
597
598    def top_rows(self, sql: str, params: Sequence[Any] = ()) -> list[dict[str, Any]]:
599        """Run a read-only query and return the rows as dicts."""
600        return [dict(row) for row in self.conn.execute(sql, params)]

SQLite database of DLsite voice works.

Arguments:
  • path: Database file path. :memory: is accepted for tests.
WorkDatabase(path: str | pathlib.Path)
290    def __init__(self, path: str | Path) -> None:
291        self.path = str(path)
292        if self.path != ":memory:":
293            Path(self.path).parent.mkdir(parents=True, exist_ok=True)
294        self.conn = sqlite3.connect(self.path)
295        self.conn.row_factory = sqlite3.Row
296        self.conn.execute("pragma journal_mode = wal")
297        self.conn.execute("pragma foreign_keys = on")
298        try:
299            self._migrate()
300        except Exception:
301            self.conn.close()
302            raise
path
conn
def close(self) -> None:
317    def close(self) -> None:
318        """Close the underlying connection."""
319        self.conn.close()

Close the underlying connection.

def upsert_work( self, work: dlsite_async.work.Work, *, detail: bool, now: datetime.datetime | None = None) -> None:
333    def upsert_work(self, work: Work, *, detail: bool, now: datetime | None = None) -> None:
334        """Insert or update ``work``.
335
336        Args:
337            work: The work to store.
338            detail: Whether ``work`` carries the work-page fields. When false,
339                only the cheap ajax-sourced columns are touched, so existing
340                detail columns are never overwritten with NULLs.
341            now: Timestamp recorded as the fetch time (defaults to now).
342        """
343        stamp = to_iso(now or datetime.now().astimezone())
344        values = _summary_values(work)
345        columns = list(_SUMMARY_COLUMNS)
346        if detail:
347            values |= _detail_values(work)
348            columns += [*_DETAIL_COLUMNS, "detail_fetched_at"]
349            values["detail_fetched_at"] = stamp
350        else:
351            columns.append("summary_fetched_at")
352            values["summary_fetched_at"] = stamp
353        values["product_id"] = work.product_id
354        values["first_seen_at"] = stamp
355        insert_columns = ["product_id", "first_seen_at", *columns]
356        placeholders = ",".join("?" * len(insert_columns))
357        updates = ",".join(f"{c} = excluded.{c}" for c in columns)
358        with self.conn:
359            self.conn.execute(
360                f"insert into work ({','.join(insert_columns)}) values ({placeholders}) "  # noqa: S608
361                f"on conflict (product_id) do update set {updates}",
362                [values[c] for c in insert_columns],
363            )
364            if detail:
365                self._replace_children(work)

Insert or update work.

Arguments:
  • work: The work to store.
  • detail: Whether work carries the work-page fields. When false, only the cheap ajax-sourced columns are touched, so existing detail columns are never overwritten with NULLs.
  • now: Timestamp recorded as the fetch time (defaults to now).
def upsert_stats( self, stats: dojinvoice_db.models.WorkStats, *, now: datetime.datetime | None = None) -> bool:
390    def upsert_stats(self, stats: WorkStats, *, now: datetime | None = None) -> bool:
391        """Store ``stats``, appending to the history only when figures changed.
392
393        Returns:
394            Whether a history row was appended.
395        """
396        stamp = to_iso(now or datetime.now().astimezone())
397        values = {c: getattr(stats, c) for c in _STAT_COLUMNS}
398        previous = self.conn.execute(
399            f"select {','.join(_HISTORY_COLUMNS)} from work_stat where product_id = ?",  # noqa: S608
400            (stats.product_id,),
401        ).fetchone()
402        changed = previous is None or any(previous[c] != values[c] for c in _HISTORY_COLUMNS)
403        columns = ["product_id", *_STAT_COLUMNS, "fetched_at"]
404        placeholders = ",".join("?" * len(columns))
405        updates = ",".join(f"{c} = excluded.{c}" for c in (*_STAT_COLUMNS, "fetched_at"))
406        with self.conn:
407            self.conn.execute(
408                f"insert into work_stat ({','.join(columns)}) values ({placeholders}) "  # noqa: S608
409                f"on conflict (product_id) do update set {updates}",
410                [stats.product_id, *(values[c] for c in _STAT_COLUMNS), stamp],
411            )
412            if changed:
413                self.conn.execute(
414                    f"insert into work_stat_history "  # noqa: S608
415                    f"(product_id, fetched_at, {','.join(_HISTORY_COLUMNS)}) "
416                    f"values ({','.join('?' * (len(_HISTORY_COLUMNS) + 2))})",
417                    [stats.product_id, stamp, *(values[c] for c in _HISTORY_COLUMNS)],
418                )
419        return changed

Store stats, appending to the history only when figures changed.

Returns:

Whether a history row was appended.

def record_error( self, product_id: str, message: str, *, now: datetime.datetime | None = None) -> None:
421    def record_error(self, product_id: str, message: str, *, now: datetime | None = None) -> None:
422        """Record a failed fetch so later runs can skip or retry it."""
423        stamp = to_iso(now or datetime.now().astimezone())
424        with self.conn:
425            self.conn.execute(
426                "insert into fetch_error (product_id, attempts, last_error, last_attempt_at) "
427                "values (?, 1, ?, ?) "
428                "on conflict (product_id) do update set "
429                "attempts = attempts + 1, last_error = excluded.last_error, "
430                "last_attempt_at = excluded.last_attempt_at",
431                (product_id, message[:500], stamp),
432            )

Record a failed fetch so later runs can skip or retry it.

def clear_error(self, product_id: str) -> None:
434    def clear_error(self, product_id: str) -> None:
435        """Forget a previously recorded fetch failure."""
436        with self.conn:
437            self.conn.execute("delete from fetch_error where product_id = ?", (product_id,))

Forget a previously recorded fetch failure.

def set_state(self, key: str, value: str) -> None:
439    def set_state(self, key: str, value: str) -> None:
440        """Store a bookkeeping value."""
441        with self.conn:
442            self.conn.execute(
443                "insert into crawl_state (key, value) values (?,?) "
444                "on conflict (key) do update set value = excluded.value",
445                (key, value),
446            )

Store a bookkeeping value.

def get_state(self, key: str) -> str | None:
448    def get_state(self, key: str) -> str | None:
449        """Read a bookkeeping value."""
450        row = self.conn.execute("select value from crawl_state where key = ?", (key,)).fetchone()
451        return None if row is None else row["value"]

Read a bookkeeping value.

def known_product_ids(self) -> set[str]:
455    def known_product_ids(self) -> set[str]:
456        """Return every product ID already stored."""
457        return {row[0] for row in self.conn.execute("select product_id from work")}

Return every product ID already stored.

def count_works(self) -> int:
459    def count_works(self) -> int:
460        """Return the number of stored works."""
461        return int(self.conn.execute("select count(*) from work").fetchone()[0])

Return the number of stored works.

def pending_detail_ids( self, *, limit: int | None = None, stale_before: datetime.datetime | None = None, retry_errors: bool = False, now: datetime.datetime | None = None) -> list[str]:
463    def pending_detail_ids(
464        self,
465        *,
466        limit: int | None = None,
467        stale_before: datetime | None = None,
468        retry_errors: bool = False,
469        now: datetime | None = None,
470    ) -> list[str]:
471        """Return works whose work-page detail should be fetched.
472
473        A work is pending when its detail was never fetched, when it was
474        fetched before ``stale_before``, or when it was fetched while the work
475        was still an announcement and has since been released -- announced
476        works are not re-fetched every run, only once after release.
477        """
478        conditions = [
479            "w.detail_fetched_at is null",
480            (
481                "(w.regist_date is not null and w.detail_fetched_at is not null"
482                " and w.regist_date > w.detail_fetched_at and w.regist_date <= ?)"
483            ),
484        ]
485        params: list[Any] = [to_iso(now or datetime.now().astimezone())]
486        if stale_before is not None:
487            conditions.append("w.detail_fetched_at < ?")
488            params.append(to_iso(stale_before))
489        sql = f"select w.product_id from work w where ({' or '.join(conditions)})"  # noqa: S608
490        if not retry_errors:
491            sql += " and not exists (select 1 from fetch_error e where e.product_id = w.product_id and e.attempts >= ?)"
492            params.append(MAX_ERROR_ATTEMPTS)
493        sql += " order by w.regist_date desc"
494        if limit is not None:
495            sql += " limit ?"
496            params.append(limit)
497        return [row[0] for row in self.conn.execute(sql, params)]

Return works whose work-page detail should be fetched.

A work is pending when its detail was never fetched, when it was fetched before stale_before, or when it was fetched while the work was still an announcement and has since been released -- announced works are not re-fetched every run, only once after release.

def stale_stat_ids( self, *, stale_before: datetime.datetime | None = None, limit: int | None = None) -> list[str]:
499    def stale_stat_ids(self, *, stale_before: datetime | None = None, limit: int | None = None) -> list[str]:
500        """Return works whose stats are missing or older than ``stale_before``.
501
502        Ordered oldest-first so an interrupted refresh resumes where it left off.
503        """
504        sql = "select w.product_id from work w left join work_stat s on s.product_id = w.product_id"
505        params: list[Any] = []
506        if stale_before is not None:
507            sql += " where s.fetched_at is null or s.fetched_at < ?"
508            params.append(to_iso(stale_before))
509        sql += " order by s.fetched_at is not null, s.fetched_at"
510        if limit is not None:
511            sql += " limit ?"
512            params.append(limit)
513        return [row[0] for row in self.conn.execute(sql, params)]

Return works whose stats are missing or older than stale_before.

Ordered oldest-first so an interrupted refresh resumes where it left off.

def load_work(self, product_id: str) -> dlsite_async.work.Work | None:
515    def load_work(self, product_id: str) -> Work | None:
516        """Rebuild a :class:`~dlsite_async.Work` from the stored summary columns.
517
518        Used to fetch a work's detail page on a later run without re-requesting
519        the ajax info that produced the row in the first place.
520        """
521        row = self.conn.execute("select * from work where product_id = ?", (product_id,)).fetchone()
522        if row is None:
523            return None
524        return Work(
525            product_id=row["product_id"],
526            site_id=row["site_id"] or "maniax",
527            maker_id=row["maker_id"],
528            work_name=row["work_name"],
529            age_category=_enum(AgeCategory, row["age_category"]),
530            work_name_masked=row["work_name_masked"],
531            work_type=_enum(WorkType, row["work_type"]),
532            book_type=_enum(BookType, row["book_type"]),
533            work_image=row["work_image"],
534            regist_date=from_iso(row["regist_date"]),
535            title_name_masked=row["series"],
536        )

Rebuild a ~dlsite_async.Work from the stored summary columns.

Used to fetch a work's detail page on a later run without re-requesting the ajax info that produced the row in the first place.

def get_work(self, product_id: str) -> dict[str, Any] | None:
538    def get_work(self, product_id: str) -> dict[str, Any] | None:
539        """Return one work with its stats and multi-valued fields, or ``None``."""
540        row = self.conn.execute("select * from work where product_id = ?", (product_id,)).fetchone()
541        if row is None:
542            return None
543        result = dict(row)
544        stat = self.conn.execute("select * from work_stat where product_id = ?", (product_id,)).fetchone()
545        result["stats"] = dict(stat) if stat else None
546        creators: dict[str, list[str]] = {}
547        for crow in self.conn.execute(
548            "select role, name from work_creator where product_id = ? order by role, rowid",
549            (product_id,),
550        ):
551            creators.setdefault(crow["role"], []).append(crow["name"])
552        result["creators"] = creators
553        for key, table, column in (
554            ("genres", "work_genre", "genre"),
555            ("file_formats", "work_file_format", "file_format"),
556            ("events", "work_event", "event"),
557        ):
558            result[key] = [
559                r[0]
560                for r in self.conn.execute(
561                    f"select {column} from {table} where product_id = ? order by rowid",  # noqa: S608
562                    (product_id,),
563                )
564            ]
565        result["sample_images"] = [
566            r[0]
567            for r in self.conn.execute(
568                "select url from work_sample_image where product_id = ? order by idx",
569                (product_id,),
570            )
571        ]
572        return result

Return one work with its stats and multi-valued fields, or None.

def summary(self) -> dict[str, typing.Any]:
574    def summary(self) -> dict[str, Any]:
575        """Return aggregate counts for the ``stats`` command."""
576        row = self.conn.execute(
577            "select count(*) as works,"
578            " sum(detail_fetched_at is not null) as detailed,"
579            " min(regist_date) as oldest,"
580            " max(regist_date) as newest"
581            " from work",
582        ).fetchone()
583        return {
584            "works": row["works"],
585            "detailed": row["detailed"] or 0,
586            "pending_detail": row["works"] - (row["detailed"] or 0),
587            "oldest_release": row["oldest"],
588            "newest_release": row["newest"],
589            "circles": self.conn.execute("select count(distinct maker_id) from work").fetchone()[0],
590            "voice_actors": self.conn.execute(
591                "select count(distinct name) from work_creator where role = 'voice_actor'",
592            ).fetchone()[0],
593            "genres": self.conn.execute("select count(distinct genre) from work_genre").fetchone()[0],
594            "errors": self.conn.execute("select count(*) from fetch_error").fetchone()[0],
595            "last_crawl": self.get_state("last_crawl_at"),
596        }

Return aggregate counts for the stats command.

def top_rows( self, sql: str, params: Sequence[typing.Any] = ()) -> list[dict[str, typing.Any]]:
598    def top_rows(self, sql: str, params: Sequence[Any] = ()) -> list[dict[str, Any]]:
599        """Run a read-only query and return the rows as dicts."""
600        return [dict(row) for row in self.conn.execute(sql, params)]

Run a read-only query and return the rows as dicts.