Download tasks/imdb/tests/oracle-runtime/clone/backend/db.py from TIGER-Lab/WebsiteBench: direct link, hf CLI and curl.
- Browser
- Download file 55.9 kB
-
https://huggingface.co/datasets/TIGER-Lab/WebsiteBench/resolve/main/tasks/imdb/tests/oracle-runtime/clone/backend/db.py
- Command line
-
hf download hf://datasets/TIGER-Lab/WebsiteBench/tasks/imdb/tests/oracle-runtime/clone/backend/db.py
-
curl -L -o db.py https://huggingface.co/datasets/TIGER-Lab/WebsiteBench/resolve/main/tasks/imdb/tests/oracle-runtime/clone/backend/db.py
55.9 kB
| """SQLite persistence layer for the IMDb offline clone persistent backend. | |
| Owns the durable, server-side state: frozen titles, people and credits, | |
| the home carousel capture rows, the two synthetic fixture accounts, | |
| watchlist entries, ratings, and custom lists. | |
| Contract highlights: | |
| - WAL journal mode, foreign keys ON, busy timeout for reload robustness. | |
| - Ordered migrations tracked in schema_migrations (legacy -> head safe). | |
| - Seeded rows are dated facts frozen at the 2026-07-25 capture; local | |
| mutations never touch the seeded aggregate columns. | |
| - The database file lives under WEBSITEBENCH_DATA_DIR (with the historical | |
| compatibility alias still accepted; default | |
| materials/imdb/data), always outside the candidate clone/ tree. | |
| Aggregate-rating policy (applied generically to every title): the displayed | |
| IMDb aggregate and its source vote count are immutable dated seeds. A local | |
| user rating is stored and displayed separately and never modifies or | |
| impersonates the IMDb aggregate. | |
| Optimistic concurrency note: titles are immutable in this fixture and | |
| watchlist reordering is not a captured source behavior, so there is no | |
| user-editable versioned resource; stale-version conflict handling is | |
| honestly N/A rather than simulated. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import sqlite3 | |
| from collections.abc import Iterable | |
| from . import ASSETS_BASE, CATALOG_ASSETS_BASE, FROZEN_CLOCK, SITE_ID, db_path | |
| from .catalog import ( | |
| PERSON_CREDITS, | |
| complete_catalog_titles, | |
| extra_people, | |
| extra_titles, | |
| ) | |
| FOREIGN_LIST_ID = "ls-510448718" | |
| # --------------------------------------------------------------------------- | |
| # Frozen seed data (dated facts captured 2026-07-25; never mutated locally) | |
| # --------------------------------------------------------------------------- | |
| SEED_ACCOUNTS = ( | |
| ("alex", "ur-alex-green", "Alex Green"), | |
| ("jordan", "ur-jordan-lee", "Jordan Lee"), | |
| ) | |
| SEED_TITLES = ( | |
| { | |
| "id": "tt0468569", | |
| "title": "The Dark Knight", | |
| "year": "2008", | |
| "cert": "PG-13", | |
| "runtime": "2h 32m", | |
| "imdb_rating": "9.1", | |
| "votes": "3.2M", | |
| "metascore": "85", | |
| "popularity": "31", | |
| "watchlist_count": "4.2M", | |
| "top_rank": "Top rated movie #3", | |
| "plot": ( | |
| "When a menace known as the Joker wreaks havoc and chaos on the " | |
| "people of Gotham, Batman, James Gordon and Harvey Dent must " | |
| "work together to put an end to the madness." | |
| ), | |
| "director": "Christopher Nolan", | |
| "writers": "Jonathan Nolan, Christopher Nolan, David S. Goyer", | |
| "stars": "Christian Bale, Heath Ledger, Aaron Eckhart", | |
| "genres": [ | |
| "DC", "Action Epic", "Epic", "Psychological Drama", | |
| "Psychological Thriller", "Superhero", "Crime", "Thriller", | |
| ], | |
| "poster": f"{ASSETS_BASE}/title-dark-knight/poster-tt0468569-main-380x562.jpg", | |
| "card": f"{ASSETS_BASE}/watchlist-page/poster-tt0468569-280x414.jpg", | |
| }, | |
| { | |
| "id": "tt0816692", | |
| "title": "Interstellar", | |
| "year": "2014", | |
| "cert": "PG-13", | |
| "runtime": "2h 49m", | |
| "imdb_rating": "8.7", | |
| "votes": "2.6M", | |
| "metascore": "74", | |
| "popularity": "15", | |
| "watchlist_count": "4.4M", | |
| "top_rank": "Top rated movie #17", | |
| "plot": ( | |
| "In a dystopian future where Earth has become near-uninhabitable, " | |
| "a team of astronauts embark on a mission to find a new home for " | |
| "humanity." | |
| ), | |
| "director": "Christopher Nolan", | |
| "writers": "Jonathan Nolan, Christopher Nolan", | |
| "stars": "Matthew McConaughey, Anne Hathaway, Jessica Chastain", | |
| "genres": [ | |
| "Adventure Epic", "Epic", "Psychological Drama", "Quest", | |
| "Sci-Fi Epic", "Space Sci-Fi", "Time Travel", "Adventure", | |
| "Drama", "Sci-Fi", | |
| ], | |
| "poster": f"{ASSETS_BASE}/title-interstellar/poster-tt0816692-main-380x562.jpg", | |
| "card": f"{ASSETS_BASE}/watchlist-page/poster-tt0816692-280x414.jpg", | |
| }, | |
| { | |
| "id": "tt0110912", | |
| "title": "Pulp Fiction", | |
| "year": "1994", | |
| "cert": "R", | |
| "runtime": "2h 34m", | |
| "imdb_rating": "8.8", | |
| "votes": "2.5M", | |
| "metascore": "95", | |
| "popularity": "130", | |
| "watchlist_count": "4.0M", | |
| "top_rank": "Top rated movie #9", | |
| "plot": ( | |
| "The lives of two mob hitmen, a boxer, a gangster and his wife, " | |
| "and a pair of diner bandits intertwine in four tales of " | |
| "violence and redemption." | |
| ), | |
| "director": "Quentin Tarantino", | |
| "writers": "Quentin Tarantino, Roger Avary", | |
| "stars": "John Travolta, Uma Thurman, Samuel L. Jackson", | |
| "genres": ["Dark Comedy", "Drug Crime", "Gangster", "Crime", "Drama"], | |
| "poster": f"{ASSETS_BASE}/title-pulp-fiction/poster-tt0110912-main-380x562.jpg", | |
| "card": f"{ASSETS_BASE}/watchlist-page/poster-tt0110912-280x414.jpg", | |
| }, | |
| ) + extra_titles(ASSETS_BASE) | |
| # ``SEED_TITLES`` retains the historical 36-title focus identity. The | |
| # actionable directory is its exact union with the unchanged Top 250 and | |
| # Popular 81 catalog contracts (302 additional IDs, 338 total). | |
| ALL_TITLES = complete_catalog_titles(SEED_TITLES) | |
| SEED_HOME_CAROUSEL = ( | |
| # (kind, position, image, heading, caption, duration) | |
| ( | |
| "hero", 1, f"{ASSETS_BASE}/home/home-hero-1-760x428.jpg", | |
| "\u201cLanterns\u201d", | |
| "Watch the Official Trailer From Comic-Con", "2:57", | |
| ), | |
| ( | |
| "hero", 2, f"{ASSETS_BASE}/home/home-hero-2-760x428.jpg", | |
| "\u201cThe Lord of the Rings: The Rings of Power\u201d Season 3", | |
| "Watch the Comic-Con Teaser", "1:38", | |
| ), | |
| ( | |
| "hero", 3, f"{ASSETS_BASE}/home/home-hero-3-760x428.jpg", | |
| "Get Into 'The Odyssey' Craziness With Christopher Nolan " | |
| "and the Cast", | |
| "Watch Our Interview", "9:23", | |
| ), | |
| ( | |
| "hero", 4, f"{ASSETS_BASE}/home/home-hero-4-760x428.jpg", | |
| "Eddie Marsan Is 'Clayface'", | |
| "Watch the Trailer", "2:29", | |
| ), | |
| ("fanpick", 1, f"{ASSETS_BASE}/home/home-fanpick-1-280x414.jpg", "", "", ""), | |
| ("fanpick", 2, f"{ASSETS_BASE}/home/home-fanpick-2-280x414.jpg", "", "", ""), | |
| ("fanpick", 3, f"{ASSETS_BASE}/home/home-fanpick-3-280x414.jpg", "", "", ""), | |
| ("fanpick", 4, f"{ASSETS_BASE}/home/home-fanpick-4-280x414.jpg", "", "", ""), | |
| ) | |
| SEED_FIXTURE_LISTS = ( | |
| # Jordan pre-owns a private list so foreign-owner 403 paths are testable. | |
| (FOREIGN_LIST_ID, "jordan", "Jordan's Noir Classics", "Titles", "Private"), | |
| ) | |
| # Exact seeded aggregate ballots behind the captured one-decimal displays. | |
| # (title_id, seed_vote_count, seed_rating_avg). Realistic multi-million | |
| # counts mean a single local vote shifts the display negligibly but | |
| # deterministically -- the generic rule for every title row. | |
| SEED_TITLE_AGGREGATES = ( | |
| ("tt0468569", 3_248_112, 9.1), | |
| ("tt0816692", 2_637_845, 8.7), | |
| ("tt0110912", 2_524_930, 8.8), | |
| ) + tuple( | |
| (title["id"], title["seed_vote_count"], title["seed_rating_avg"]) | |
| for title in SEED_TITLES[3:] | |
| ) | |
| ALL_TITLE_AGGREGATES = SEED_TITLE_AGGREGATES + tuple( | |
| (title["id"], title["seed_vote_count"], title["seed_rating_avg"]) | |
| for title in ALL_TITLES | |
| if title["id"] not in {item[0] for item in SEED_TITLE_AGGREGATES} | |
| and title.get("seed_vote_count") is not None | |
| and title.get("seed_rating_avg") is not None | |
| ) | |
| SEED_PEOPLE = ( | |
| # (id, name, roles, known_for, thumb, match_terms) | |
| ( | |
| "nm0000384", | |
| "Danny Elfman", | |
| "Music Department, Composer, Actor", | |
| "The Nightmare Before Christmas (1993)", | |
| f"{CATALOG_ASSETS_BASE}/catalog-people/nm0000384.svg", | |
| ["dark knight"], | |
| ), | |
| ) + extra_people(ASSETS_BASE) | |
| SEED_SEARCH_CATALOG = ( | |
| # (rank, display_title, local_title_id, year, runtime, cert, metascore, | |
| # rating, votes, thumb, match_terms) | |
| # Ratings/votes for locally captured titles are computed live from the | |
| # aggregate ballots; the static columns hold the frozen capture values | |
| # for rows whose full title pages were not captured. | |
| ( | |
| 10, "The Dark Knight", "tt0468569", "2008", "2h 32m", "PG-13", | |
| "85", "9.1", "3.2M", | |
| f"{ASSETS_BASE}/find-search/search-thumb-tt0468569-180x266.jpg", | |
| [], | |
| ), | |
| ( | |
| 20, "The Dark Knight Rises", None, "2012", "2h 44m", "PG-13", | |
| "78", "8.4", "2M", | |
| f"{ASSETS_BASE}/find-search/search-thumb-dark-knight-rises-180x266.jpg", | |
| [], | |
| ), | |
| ( | |
| 30, "Citizen Vigilante", None, "2026", "1h 29m", "Not Rated", | |
| None, "5.9", "33K", | |
| f"{ASSETS_BASE}/find-search/search-thumb-result-3-180x266.jpg", | |
| ["dark knight"], | |
| ), | |
| ( | |
| 40, "Batman: The Dark Knight Returns, Part 2", None, "2013", | |
| "1h 16m", "PG-13", None, "8.3", "62K", | |
| f"{ASSETS_BASE}/find-search/search-thumb-result-4-180x266.jpg", | |
| [], | |
| ), | |
| ( | |
| 50, "Batman: The Dark Knight Returns, Part 1", None, "2012", | |
| "1h 16m", "PG-13", None, "7.9", "68K", | |
| f"{ASSETS_BASE}/find-search/search-thumb-result-5-180x266.jpg", | |
| [], | |
| ), | |
| ( | |
| 60, "Interstellar", "tt0816692", "2014", "2h 49m", "PG-13", | |
| "74", "8.7", "2.6M", | |
| f"{ASSETS_BASE}/watchlist-page/poster-tt0816692-280x414.jpg", | |
| [], | |
| ), | |
| ( | |
| 70, "Pulp Fiction", "tt0110912", "1994", "2h 34m", "R", | |
| "95", "8.8", "2.5M", | |
| f"{ASSETS_BASE}/watchlist-page/poster-tt0110912-280x414.jpg", | |
| [], | |
| ), | |
| ) | |
| SEED_HOME_TITLE_RAILS = ( | |
| # (rail, position, title_id) | |
| ("fan-favorites", 1, "tt0816692"), | |
| ("fan-favorites", 2, "tt0110912"), | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Migrations (ordered; tracked in schema_migrations) | |
| # --------------------------------------------------------------------------- | |
| MIGRATIONS: tuple[tuple[str, str], ...] = ( | |
| ( | |
| "0001-initial-schema", | |
| """ | |
| CREATE TABLE accounts ( | |
| key TEXT PRIMARY KEY, | |
| public_id TEXT NOT NULL UNIQUE, | |
| display_name TEXT NOT NULL | |
| ); | |
| CREATE TABLE titles ( | |
| id TEXT PRIMARY KEY, | |
| title TEXT NOT NULL, | |
| year TEXT NOT NULL, | |
| cert TEXT NOT NULL, | |
| runtime TEXT NOT NULL, | |
| imdb_rating TEXT NOT NULL, | |
| votes TEXT NOT NULL, | |
| metascore TEXT NOT NULL, | |
| popularity TEXT NOT NULL, | |
| watchlist_count TEXT NOT NULL, | |
| top_rank TEXT NOT NULL, | |
| plot TEXT NOT NULL, | |
| director TEXT NOT NULL, | |
| writers TEXT NOT NULL, | |
| stars TEXT NOT NULL, | |
| genres_json TEXT NOT NULL, | |
| poster TEXT NOT NULL, | |
| card TEXT NOT NULL | |
| ); | |
| CREATE TABLE home_carousel ( | |
| kind TEXT NOT NULL, | |
| position INTEGER NOT NULL, | |
| image TEXT NOT NULL, | |
| heading TEXT NOT NULL, | |
| caption TEXT NOT NULL, | |
| duration TEXT NOT NULL, | |
| PRIMARY KEY (kind, position) | |
| ); | |
| CREATE TABLE watchlist_entries ( | |
| account_key TEXT NOT NULL REFERENCES accounts(key), | |
| title_id TEXT NOT NULL REFERENCES titles(id), | |
| PRIMARY KEY (account_key, title_id) | |
| ); | |
| CREATE TABLE ratings ( | |
| account_key TEXT NOT NULL REFERENCES accounts(key), | |
| title_id TEXT NOT NULL REFERENCES titles(id), | |
| value INTEGER NOT NULL CHECK (value BETWEEN 1 AND 10), | |
| PRIMARY KEY (account_key, title_id) | |
| ); | |
| CREATE TABLE lists ( | |
| id TEXT PRIMARY KEY, | |
| owner_key TEXT NOT NULL REFERENCES accounts(key), | |
| name TEXT NOT NULL, | |
| list_type TEXT NOT NULL, | |
| privacy TEXT NOT NULL | |
| ); | |
| CREATE TABLE list_members ( | |
| list_id TEXT NOT NULL REFERENCES lists(id) ON DELETE CASCADE, | |
| title_id TEXT NOT NULL REFERENCES titles(id), | |
| PRIMARY KEY (list_id, title_id) | |
| ); | |
| """, | |
| ), | |
| ( | |
| "0002-frozen-clock-audit-columns", | |
| f""" | |
| ALTER TABLE watchlist_entries | |
| ADD COLUMN added_at TEXT NOT NULL DEFAULT '{FROZEN_CLOCK}'; | |
| ALTER TABLE ratings | |
| ADD COLUMN updated_at TEXT NOT NULL DEFAULT '{FROZEN_CLOCK}'; | |
| ALTER TABLE lists | |
| ADD COLUMN created_at TEXT NOT NULL DEFAULT '{FROZEN_CLOCK}'; | |
| """, | |
| ), | |
| ( | |
| "0003-catalog-aggregates-people-search", | |
| """ | |
| CREATE TABLE title_aggregates ( | |
| title_id TEXT PRIMARY KEY REFERENCES titles(id), | |
| seed_vote_count INTEGER NOT NULL CHECK (seed_vote_count > 0), | |
| seed_rating_avg REAL NOT NULL | |
| CHECK (seed_rating_avg BETWEEN 1.0 AND 10.0) | |
| ); | |
| CREATE TABLE people ( | |
| id TEXT PRIMARY KEY, | |
| name TEXT NOT NULL, | |
| roles TEXT NOT NULL, | |
| known_for TEXT NOT NULL, | |
| thumb TEXT NOT NULL, | |
| match_terms_json TEXT NOT NULL | |
| ); | |
| CREATE TABLE search_catalog ( | |
| rank INTEGER PRIMARY KEY, | |
| display_title TEXT NOT NULL, | |
| local_title_id TEXT REFERENCES titles(id), | |
| year TEXT NOT NULL, | |
| runtime TEXT NOT NULL, | |
| cert TEXT NOT NULL, | |
| metascore TEXT, | |
| rating TEXT NOT NULL, | |
| votes TEXT NOT NULL, | |
| thumb TEXT NOT NULL, | |
| match_terms_json TEXT NOT NULL | |
| ); | |
| CREATE TABLE home_title_rails ( | |
| rail TEXT NOT NULL, | |
| position INTEGER NOT NULL, | |
| title_id TEXT NOT NULL REFERENCES titles(id), | |
| PRIMARY KEY (rail, position) | |
| ); | |
| """, | |
| ), | |
| ) | |
| HEAD_VERSION = MIGRATIONS[-1][0] | |
| # WebsiteBench owns this additive site schema through the runtime-declared | |
| # migration hook. The historical three-version migration ledger remains | |
| # intact for tasks 901–905 compatibility; new entities have their own current | |
| # site migration identity. | |
| SITE_SCHEMA_VERSION = "0001-directory-reviews-lists" | |
| SITE_SCHEMA_SQL = """ | |
| CREATE TABLE IF NOT EXISTS websitebench_imdb_migrations ( | |
| version TEXT PRIMARY KEY, | |
| applied_at TEXT NOT NULL | |
| ); | |
| CREATE TABLE IF NOT EXISTS title_details ( | |
| title_id TEXT PRIMARY KEY REFERENCES titles(id) ON DELETE CASCADE, | |
| title_type TEXT NOT NULL CHECK (title_type IN ('movie','series','episode')), | |
| series_id TEXT REFERENCES titles(id), | |
| season_number INTEGER, | |
| episode_number INTEGER, | |
| asset_group TEXT NOT NULL, | |
| catalog_credit TEXT NOT NULL DEFAULT '' | |
| ); | |
| CREATE TABLE IF NOT EXISTS credits ( | |
| title_id TEXT NOT NULL REFERENCES titles(id) ON DELETE CASCADE, | |
| person_id TEXT NOT NULL REFERENCES people(id) ON DELETE CASCADE, | |
| category TEXT NOT NULL, | |
| character_name TEXT NOT NULL DEFAULT '', | |
| position INTEGER NOT NULL DEFAULT 0, | |
| PRIMARY KEY (title_id, person_id, category, character_name) | |
| ); | |
| CREATE TABLE IF NOT EXISTS media ( | |
| id TEXT PRIMARY KEY, | |
| title_id TEXT NOT NULL REFERENCES titles(id) ON DELETE CASCADE, | |
| media_type TEXT NOT NULL CHECK (media_type IN ('image','video')), | |
| local_path TEXT NOT NULL, | |
| caption TEXT NOT NULL, | |
| position INTEGER NOT NULL, | |
| UNIQUE (title_id, media_type, position) | |
| ); | |
| CREATE TABLE IF NOT EXISTS reviews ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| account_key TEXT NOT NULL REFERENCES accounts(key) ON DELETE CASCADE, | |
| title_id TEXT NOT NULL REFERENCES titles(id) ON DELETE CASCADE, | |
| summary TEXT NOT NULL, | |
| body TEXT NOT NULL, | |
| spoiler INTEGER NOT NULL DEFAULT 0 CHECK (spoiler IN (0,1)), | |
| created_at TEXT NOT NULL, | |
| updated_at TEXT NOT NULL, | |
| UNIQUE (account_key, title_id) | |
| ); | |
| CREATE TABLE IF NOT EXISTS list_profiles ( | |
| list_id TEXT PRIMARY KEY REFERENCES lists(id) ON DELETE CASCADE, | |
| description TEXT NOT NULL DEFAULT '', | |
| updated_at TEXT NOT NULL | |
| ); | |
| CREATE INDEX IF NOT EXISTS reviews_title_idx | |
| ON reviews(title_id, updated_at DESC, id DESC); | |
| CREATE INDEX IF NOT EXISTS credits_person_idx | |
| ON credits(person_id, position, title_id); | |
| CREATE UNIQUE INDEX IF NOT EXISTS lists_owner_name_ci | |
| ON lists(owner_key, name COLLATE NOCASE); | |
| """ | |
| def connect() -> sqlite3.Connection: | |
| """Open the fixture database with WAL and foreign keys enabled.""" | |
| path = db_path() | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| conn = sqlite3.connect(path, timeout=10, isolation_level=None) | |
| conn.row_factory = sqlite3.Row | |
| conn.execute("PRAGMA journal_mode=WAL") | |
| conn.execute("PRAGMA foreign_keys=ON") | |
| conn.execute("PRAGMA busy_timeout=10000") | |
| return conn | |
| def applied_versions(conn: sqlite3.Connection) -> list[str]: | |
| conn.execute( | |
| """ | |
| CREATE TABLE IF NOT EXISTS schema_migrations ( | |
| version TEXT PRIMARY KEY, | |
| applied_at TEXT NOT NULL | |
| ) | |
| """ | |
| ) | |
| rows = conn.execute( | |
| "SELECT version FROM schema_migrations ORDER BY version" | |
| ).fetchall() | |
| return [row["version"] for row in rows] | |
| def apply_migrations( | |
| conn: sqlite3.Connection, upto: str | None = None | |
| ) -> list[str]: | |
| """Apply pending migrations in order; return newly applied versions. | |
| Each migration runs atomically: statements are executed one by one | |
| inside an explicit transaction (sqlite3.executescript would issue an | |
| implicit COMMIT, breaking atomicity), and the version row is recorded | |
| in the same transaction. | |
| """ | |
| done = set(applied_versions(conn)) | |
| applied: list[str] = [] | |
| for version, script in MIGRATIONS: | |
| if version not in done: | |
| nested = conn.in_transaction | |
| if nested: | |
| conn.execute("SAVEPOINT imdb_schema_migration") | |
| else: | |
| conn.execute("BEGIN") | |
| try: | |
| for statement in script.split(";"): | |
| if statement.strip(): | |
| conn.execute(statement) | |
| conn.execute( | |
| "INSERT INTO schema_migrations (version, applied_at) " | |
| "VALUES (?, ?)", | |
| (version, FROZEN_CLOCK), | |
| ) | |
| conn.execute( | |
| "RELEASE SAVEPOINT imdb_schema_migration" | |
| if nested else "COMMIT" | |
| ) | |
| except sqlite3.Error: | |
| if nested: | |
| conn.execute("ROLLBACK TO SAVEPOINT imdb_schema_migration") | |
| conn.execute("RELEASE SAVEPOINT imdb_schema_migration") | |
| else: | |
| conn.execute("ROLLBACK") | |
| raise | |
| applied.append(version) | |
| if upto is not None and version == upto: | |
| break | |
| migration_count = int( | |
| conn.execute("SELECT COUNT(*) FROM schema_migrations").fetchone()[0] | |
| ) | |
| conn.execute(f"PRAGMA user_version = {migration_count}") | |
| return applied | |
| def apply_site_backend_migrations(conn: sqlite3.Connection) -> None: | |
| """Runtime-declared, idempotent IMDb business migration hook.""" | |
| apply_migrations(conn) | |
| conn.executescript(SITE_SCHEMA_SQL) if not conn.in_transaction else _execute_sql( | |
| conn, SITE_SCHEMA_SQL | |
| ) | |
| _ensure_site_schema_columns(conn) | |
| conn.execute( | |
| "INSERT OR IGNORE INTO websitebench_imdb_migrations(version, applied_at) " | |
| "VALUES (?, ?)", | |
| (SITE_SCHEMA_VERSION, FROZEN_CLOCK), | |
| ) | |
| seed_fixtures(conn) | |
| def seed_site_backend(conn: sqlite3.Connection) -> None: | |
| """Runtime-declared seed hook for a newly bound site database.""" | |
| seed_fixtures(conn) | |
| def _ensure_site_schema_columns(conn: sqlite3.Connection) -> None: | |
| """Apply additive columns to databases created by earlier site revisions.""" | |
| columns = { | |
| row["name"] for row in conn.execute("PRAGMA table_info(title_details)") | |
| } | |
| if "catalog_credit" not in columns: | |
| conn.execute( | |
| "ALTER TABLE title_details " | |
| "ADD COLUMN catalog_credit TEXT NOT NULL DEFAULT ''" | |
| ) | |
| def _execute_sql(conn: sqlite3.Connection, script: str) -> None: | |
| """Execute a simple schema script without stealing an outer transaction.""" | |
| for statement in script.split(";"): | |
| if statement.strip(): | |
| conn.execute(statement) | |
| def seed_fixtures(conn: sqlite3.Connection) -> None: | |
| """Reconcile immutable catalog seeds without overwriting user state.""" | |
| nested = conn.in_transaction | |
| if nested: | |
| conn.execute("SAVEPOINT imdb_seed") | |
| else: | |
| conn.execute("BEGIN") | |
| try: | |
| for key, public_id, display_name in SEED_ACCOUNTS: | |
| conn.execute( | |
| "INSERT OR IGNORE INTO accounts " | |
| "(key, public_id, display_name) VALUES (?, ?, ?)", | |
| (key, public_id, display_name), | |
| ) | |
| for title in ALL_TITLES: | |
| conn.execute( | |
| """ | |
| INSERT INTO titles ( | |
| id, title, year, cert, runtime, imdb_rating, votes, | |
| metascore, popularity, watchlist_count, top_rank, plot, | |
| director, writers, stars, genres_json, poster, card | |
| ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) | |
| ON CONFLICT(id) DO UPDATE SET | |
| title=excluded.title, year=excluded.year, cert=excluded.cert, | |
| runtime=excluded.runtime, imdb_rating=excluded.imdb_rating, | |
| votes=excluded.votes, metascore=excluded.metascore, | |
| popularity=excluded.popularity, | |
| watchlist_count=excluded.watchlist_count, | |
| top_rank=excluded.top_rank, plot=excluded.plot, | |
| director=excluded.director, writers=excluded.writers, | |
| stars=excluded.stars, genres_json=excluded.genres_json, | |
| poster=excluded.poster, card=excluded.card | |
| """, | |
| ( | |
| title["id"], title["title"], title["year"], title["cert"], | |
| title["runtime"], title["imdb_rating"], title["votes"], | |
| title["metascore"], title["popularity"], | |
| title["watchlist_count"], title["top_rank"], | |
| title["plot"], title["director"], title["writers"], | |
| title["stars"], json.dumps(title["genres"]), | |
| title["poster"], title["card"], | |
| ), | |
| ) | |
| for kind, position, image, heading, caption, duration in ( | |
| SEED_HOME_CAROUSEL | |
| ): | |
| conn.execute( | |
| "INSERT OR IGNORE INTO home_carousel " | |
| "(kind, position, image, heading, caption, duration) " | |
| "VALUES (?, ?, ?, ?, ?, ?)", | |
| (kind, position, image, heading, caption, duration), | |
| ) | |
| for list_id, owner_key, name, list_type, privacy in SEED_FIXTURE_LISTS: | |
| conn.execute( | |
| "INSERT OR IGNORE INTO lists " | |
| "(id, owner_key, name, list_type, privacy, created_at) " | |
| "VALUES (?, ?, ?, ?, ?, ?)", | |
| (list_id, owner_key, name, list_type, privacy, FROZEN_CLOCK), | |
| ) | |
| for title_id, seed_votes, seed_avg in ALL_TITLE_AGGREGATES: | |
| conn.execute( | |
| "INSERT INTO title_aggregates " | |
| "(title_id, seed_vote_count, seed_rating_avg) " | |
| "VALUES (?, ?, ?) ON CONFLICT(title_id) DO UPDATE SET " | |
| "seed_vote_count=excluded.seed_vote_count, " | |
| "seed_rating_avg=excluded.seed_rating_avg", | |
| (title_id, seed_votes, seed_avg), | |
| ) | |
| # Credits and people are immutable directory rows. Reconcile them on | |
| # every seed so an upgraded persistent database converges to the same | |
| # exact 20-person catalog without touching any user-owned entity. | |
| conn.execute("DELETE FROM credits") | |
| person_ids = [person[0] for person in SEED_PEOPLE] | |
| placeholders = ",".join("?" for _ in person_ids) | |
| conn.execute( | |
| f"DELETE FROM people WHERE id NOT IN ({placeholders})", person_ids | |
| ) | |
| for person_id, name, roles, known_for, thumb, terms in SEED_PEOPLE: | |
| conn.execute( | |
| "INSERT INTO people " | |
| "(id, name, roles, known_for, thumb, match_terms_json) " | |
| "VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET " | |
| "name=excluded.name, roles=excluded.roles, " | |
| "known_for=excluded.known_for, thumb=excluded.thumb, " | |
| "match_terms_json=excluded.match_terms_json", | |
| (person_id, name, roles, known_for, thumb, json.dumps(terms)), | |
| ) | |
| for index, title in enumerate(ALL_TITLES[3:], start=1): | |
| conn.execute( | |
| "INSERT INTO search_catalog (" | |
| "rank, display_title, local_title_id, year, runtime, cert, " | |
| "metascore, rating, votes, thumb, match_terms_json" | |
| ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " | |
| "ON CONFLICT(rank) DO UPDATE SET " | |
| "display_title=excluded.display_title, " | |
| "local_title_id=excluded.local_title_id, year=excluded.year, " | |
| "runtime=excluded.runtime, cert=excluded.cert, " | |
| "metascore=excluded.metascore, rating=excluded.rating, " | |
| "votes=excluded.votes, thumb=excluded.thumb, " | |
| "match_terms_json=excluded.match_terms_json", | |
| ( | |
| 1000 + index, | |
| title["title"], | |
| title["id"], | |
| title["year"], | |
| title["runtime"], | |
| title["cert"], | |
| title["metascore"], | |
| title["imdb_rating"], | |
| ( | |
| _format_count(int(title["seed_vote_count"])) | |
| if title.get("seed_vote_count") is not None | |
| else "No ratings" | |
| ), | |
| title["card"], | |
| json.dumps([title["director"], *title["genres"]]), | |
| ), | |
| ) | |
| for ( | |
| rank, display_title, local_title_id, year, runtime, cert, | |
| metascore, rating, votes, thumb, terms, | |
| ) in SEED_SEARCH_CATALOG: | |
| conn.execute( | |
| """ | |
| INSERT INTO search_catalog ( | |
| rank, display_title, local_title_id, year, runtime, | |
| cert, metascore, rating, votes, thumb, match_terms_json | |
| ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) | |
| ON CONFLICT(rank) DO UPDATE SET | |
| display_title=excluded.display_title, | |
| local_title_id=excluded.local_title_id, year=excluded.year, | |
| runtime=excluded.runtime, cert=excluded.cert, | |
| metascore=excluded.metascore, rating=excluded.rating, | |
| votes=excluded.votes, thumb=excluded.thumb, | |
| match_terms_json=excluded.match_terms_json | |
| """, | |
| ( | |
| rank, display_title, local_title_id, year, runtime, | |
| cert, metascore, rating, votes, thumb, json.dumps(terms), | |
| ), | |
| ) | |
| for rail, position, title_id in SEED_HOME_TITLE_RAILS: | |
| conn.execute( | |
| "INSERT OR IGNORE INTO home_title_rails " | |
| "(rail, position, title_id) VALUES (?, ?, ?)", | |
| (rail, position, title_id), | |
| ) | |
| detail_defaults = { | |
| "tt0468569": "title-dark-knight", | |
| "tt0816692": "title-interstellar", | |
| "tt0110912": "title-pulp-fiction", | |
| } | |
| for title in ALL_TITLES: | |
| title_type = title.get("title_type", "movie") | |
| conn.execute( | |
| "INSERT INTO title_details (" | |
| "title_id, title_type, series_id, season_number, " | |
| "episode_number, asset_group, catalog_credit) " | |
| "VALUES (?, ?, ?, ?, ?, ?, ?) " | |
| "ON CONFLICT(title_id) DO UPDATE SET " | |
| "title_type=excluded.title_type, series_id=excluded.series_id, " | |
| "season_number=excluded.season_number, " | |
| "episode_number=excluded.episode_number, " | |
| "asset_group=excluded.asset_group, " | |
| "catalog_credit=excluded.catalog_credit", | |
| ( | |
| title["id"], | |
| title_type, | |
| title.get("series_id"), | |
| title.get("season_number"), | |
| title.get("episode_number"), | |
| title.get("asset_group") or detail_defaults[title["id"]], | |
| title.get("catalog_credit", ""), | |
| ), | |
| ) | |
| conn.execute( | |
| "INSERT INTO media (" | |
| "id, title_id, media_type, local_path, caption, position" | |
| ") VALUES (?, ?, 'image', ?, ?, 1) " | |
| "ON CONFLICT(id) DO UPDATE SET " | |
| "local_path=excluded.local_path, caption=excluded.caption, " | |
| "position=excluded.position", | |
| ( | |
| f"media-{title['id']}-poster", | |
| title["id"], | |
| title["poster"], | |
| f"{title['title']} poster", | |
| ), | |
| ) | |
| for position, (title_id, person_id, category, character) in enumerate( | |
| PERSON_CREDITS, start=1 | |
| ): | |
| conn.execute( | |
| "INSERT OR IGNORE INTO credits (" | |
| "title_id, person_id, category, character_name, position" | |
| ") VALUES (?, ?, ?, ?, ?)", | |
| (title_id, person_id, category, character, position), | |
| ) | |
| for list_id, *_ in SEED_FIXTURE_LISTS: | |
| conn.execute( | |
| "INSERT OR IGNORE INTO list_profiles " | |
| "(list_id, description, updated_at) VALUES (?, '', ?)", | |
| (list_id, FROZEN_CLOCK), | |
| ) | |
| conn.execute("RELEASE SAVEPOINT imdb_seed" if nested else "COMMIT") | |
| except sqlite3.Error: | |
| if nested: | |
| conn.execute("ROLLBACK TO SAVEPOINT imdb_seed") | |
| conn.execute("RELEASE SAVEPOINT imdb_seed") | |
| elif conn.in_transaction: | |
| conn.execute("ROLLBACK") | |
| raise | |
| def ensure_database() -> None: | |
| """Create/migrate/seed the database. Safe to call on every startup.""" | |
| conn = connect() | |
| try: | |
| # Historical direct-db test helpers predate the runtime seam. Bind the | |
| # same site identity before they create business tables so the next | |
| # canonical SiteBackend.open() still fails closed for foreign data. | |
| conn.execute( | |
| "CREATE TABLE IF NOT EXISTS websitebench_site_binding (" | |
| "singleton INTEGER PRIMARY KEY CHECK (singleton=1), " | |
| "site_id TEXT NOT NULL UNIQUE, bound_at TEXT NOT NULL)" | |
| ) | |
| conn.execute( | |
| "INSERT OR IGNORE INTO websitebench_site_binding" | |
| "(singleton,site_id,bound_at) VALUES (1,?,?)", | |
| (SITE_ID, FROZEN_CLOCK), | |
| ) | |
| apply_migrations(conn) | |
| _execute_sql(conn, SITE_SCHEMA_SQL) | |
| _ensure_site_schema_columns(conn) | |
| conn.execute( | |
| "INSERT OR IGNORE INTO websitebench_imdb_migrations" | |
| "(version, applied_at) VALUES (?, ?)", | |
| (SITE_SCHEMA_VERSION, FROZEN_CLOCK), | |
| ) | |
| seed_fixtures(conn) | |
| finally: | |
| conn.close() | |
| def reset_database() -> dict[str, int]: | |
| """Wipe all site-local auth and business state, then re-seed fixtures.""" | |
| ensure_database() | |
| conn = connect() | |
| try: | |
| conn.execute("BEGIN IMMEDIATE") | |
| removed = { | |
| "watchlist_entries": conn.execute( | |
| "DELETE FROM watchlist_entries" | |
| ).rowcount, | |
| "ratings": conn.execute("DELETE FROM ratings").rowcount, | |
| "list_members": conn.execute("DELETE FROM list_members").rowcount, | |
| "lists": conn.execute("DELETE FROM lists").rowcount, | |
| "reviews": conn.execute("DELETE FROM reviews").rowcount, | |
| } | |
| # Fixture reset is a reproducibility boundary, not merely a row wipe. | |
| # Review edit/delete routes carry the local integer id, so reset the | |
| # SQLite allocator as well and keep replay ids deterministic. | |
| conn.execute("DELETE FROM sqlite_sequence WHERE name = 'reviews'") | |
| auth_tables = ( | |
| "local_auth_mail_outbox", | |
| "local_auth_password_reset_flows", | |
| "local_auth_registration_flows", | |
| "local_auth_mail_rate_limits", | |
| "local_auth_sessions", | |
| "local_auth_accounts", | |
| ) | |
| existing = { | |
| row["name"] | |
| for row in conn.execute( | |
| "SELECT name FROM sqlite_master WHERE type='table'" | |
| ).fetchall() | |
| } | |
| for table in auth_tables: | |
| if table in existing: | |
| removed[table] = conn.execute(f"DELETE FROM {table}").rowcount | |
| conn.execute("COMMIT") | |
| seed_fixtures(conn) | |
| return removed | |
| finally: | |
| conn.close() | |
| # --------------------------------------------------------------------------- | |
| # Read helpers | |
| # --------------------------------------------------------------------------- | |
| def _format_count(count: int) -> str: | |
| """Format an exact ballot count the way the source site abbreviates it.""" | |
| if count >= 1_000_000: | |
| text = f"{count / 1_000_000:.1f}" | |
| if text.endswith(".0"): | |
| text = text[:-2] | |
| return f"{text}M" | |
| if count >= 10_000: | |
| return f"{count // 1_000}K" | |
| if count >= 1_000: | |
| text = f"{count / 1_000:.1f}" | |
| if text.endswith(".0"): | |
| text = text[:-2] | |
| return f"{text}K" | |
| return str(count) | |
| def title_aggregate(conn: sqlite3.Connection, title_id: str) -> dict | None: | |
| """Return the immutable captured aggregate plus separate local counts. | |
| A local rating is user-owned benchmark state and never changes or | |
| impersonates an IMDb aggregate. ``vote_count`` remains a historical | |
| diagnostic count for tasks 901–905; UI fields ``rating`` and ``votes`` | |
| are derived exclusively from the frozen source seed. | |
| """ | |
| seed = conn.execute( | |
| "SELECT seed_vote_count, seed_rating_avg FROM title_aggregates " | |
| "WHERE title_id = ?", | |
| (title_id,), | |
| ).fetchone() | |
| if seed is None: | |
| return None | |
| user = conn.execute( | |
| "SELECT COUNT(*) AS n " | |
| "FROM ratings WHERE title_id = ?", | |
| (title_id,), | |
| ).fetchone() | |
| source_vote_count = int(seed["seed_vote_count"]) | |
| local_vote_count = int(user["n"]) | |
| return { | |
| "rating": f"{float(seed['seed_rating_avg']):.1f}", | |
| "votes": _format_count(source_vote_count), | |
| "source_vote_count": source_vote_count, | |
| "local_vote_count": local_vote_count, | |
| "vote_count": source_vote_count + local_vote_count, | |
| } | |
| def _title_dict( | |
| row: sqlite3.Row, conn: sqlite3.Connection | None = None | |
| ) -> dict: | |
| data = dict(row) | |
| data["genres"] = json.loads(data.pop("genres_json")) | |
| if conn is not None: | |
| aggregate = title_aggregate(conn, data["id"]) | |
| if aggregate is not None: | |
| data["imdb_rating"] = aggregate["rating"] | |
| data["votes"] = aggregate["votes"] | |
| detail = conn.execute( | |
| "SELECT title_type, series_id, season_number, episode_number, " | |
| "asset_group, catalog_credit FROM title_details WHERE title_id = ?", | |
| (data["id"],), | |
| ).fetchone() | |
| if detail is not None: | |
| data.update(dict(detail)) | |
| if data.get("series_id"): | |
| series = conn.execute( | |
| "SELECT title FROM titles WHERE id=?", (data["series_id"],) | |
| ).fetchone() | |
| data["series_title"] = series["title"] if series else None | |
| return data | |
| def account_by_key(conn: sqlite3.Connection, key: str) -> dict | None: | |
| row = conn.execute( | |
| "SELECT key, public_id, display_name FROM accounts WHERE key = ?", | |
| (key,), | |
| ).fetchone() | |
| if row is None: | |
| return None | |
| return {"key": row["key"], "id": row["public_id"], "name": row["display_name"]} | |
| def create_registered_account( | |
| conn: sqlite3.Connection, registration: dict[str, str] | |
| ) -> str: | |
| """Create the business subject inside the auth registration transaction.""" | |
| suffix = registration["account_id"].removeprefix("account_")[:24] | |
| key = f"member-{suffix}" | |
| conn.execute( | |
| "INSERT INTO accounts(key, public_id, display_name) VALUES (?, ?, ?)", | |
| (key, f"ur-{suffix}", registration["display_name"]), | |
| ) | |
| return key | |
| def all_accounts(conn: sqlite3.Connection) -> dict[str, dict]: | |
| rows = conn.execute( | |
| "SELECT key, public_id, display_name FROM accounts ORDER BY key" | |
| ).fetchall() | |
| return { | |
| row["key"]: {"id": row["public_id"], "name": row["display_name"]} | |
| for row in rows | |
| } | |
| def get_title(conn: sqlite3.Connection, title_id: str) -> dict | None: | |
| row = conn.execute( | |
| "SELECT * FROM titles WHERE id = ?", (title_id,) | |
| ).fetchone() | |
| return _title_dict(row, conn) if row else None | |
| def title_ids(conn: sqlite3.Connection) -> set[str]: | |
| return { | |
| row["id"] for row in conn.execute("SELECT id FROM titles").fetchall() | |
| } | |
| def home_carousel(conn: sqlite3.Connection, kind: str) -> list[dict]: | |
| rows = conn.execute( | |
| "SELECT image, heading, caption, duration FROM home_carousel " | |
| "WHERE kind = ? ORDER BY position", | |
| (kind,), | |
| ).fetchall() | |
| return [dict(row) for row in rows] | |
| def home_rail_titles(conn: sqlite3.Connection, rail: str) -> list[dict]: | |
| rows = conn.execute( | |
| """ | |
| SELECT titles.* FROM home_title_rails | |
| JOIN titles ON titles.id = home_title_rails.title_id | |
| WHERE home_title_rails.rail = ? | |
| ORDER BY home_title_rails.position | |
| """, | |
| (rail,), | |
| ).fetchall() | |
| return [_title_dict(row, conn) for row in rows] | |
| def all_titles( | |
| conn: sqlite3.Connection, *, title_type: str | None = None | |
| ) -> list[dict]: | |
| """Return the fixed local directory in title order.""" | |
| if title_type is None: | |
| rows = conn.execute("SELECT * FROM titles ORDER BY title COLLATE NOCASE").fetchall() | |
| else: | |
| rows = conn.execute( | |
| "SELECT titles.* FROM titles JOIN title_details " | |
| "ON title_details.title_id=titles.id " | |
| "WHERE title_details.title_type=? ORDER BY titles.title COLLATE NOCASE", | |
| (title_type,), | |
| ).fetchall() | |
| return [_title_dict(row, conn) for row in rows] | |
| def chart_titles(conn: sqlite3.Connection, chart: str) -> list[dict]: | |
| order = ( | |
| "title_aggregates.seed_rating_avg DESC, " | |
| "title_aggregates.seed_vote_count DESC" | |
| if chart == "top" | |
| else "CAST(titles.popularity AS INTEGER), titles.title COLLATE NOCASE" | |
| ) | |
| rows = conn.execute( | |
| "SELECT titles.* FROM titles JOIN title_details " | |
| "ON title_details.title_id=titles.id JOIN title_aggregates " | |
| "ON title_aggregates.title_id=titles.id " | |
| "WHERE title_details.title_type='movie' ORDER BY " + order | |
| ).fetchall() | |
| return [_title_dict(row, conn) for row in rows] | |
| def get_person(conn: sqlite3.Connection, person_id: str) -> dict | None: | |
| row = conn.execute("SELECT * FROM people WHERE id=?", (person_id,)).fetchone() | |
| if row is None: | |
| return None | |
| result = dict(row) | |
| result["match_terms"] = json.loads(result.pop("match_terms_json")) | |
| result["credits"] = credits_for_person(conn, person_id) | |
| return result | |
| def all_people(conn: sqlite3.Connection) -> list[dict]: | |
| """Return the complete fixed people directory in display-name order.""" | |
| rows = conn.execute( | |
| "SELECT id FROM people ORDER BY name COLLATE NOCASE, id" | |
| ).fetchall() | |
| return [get_person(conn, row["id"]) for row in rows] | |
| def credits_for_person(conn: sqlite3.Connection, person_id: str) -> list[dict]: | |
| rows = conn.execute( | |
| "SELECT credits.category, credits.character_name, titles.* " | |
| "FROM credits JOIN titles ON titles.id=credits.title_id " | |
| "WHERE credits.person_id=? ORDER BY credits.position, titles.year DESC", | |
| (person_id,), | |
| ).fetchall() | |
| results: list[dict] = [] | |
| for row in rows: | |
| item = dict(row) | |
| category = item.pop("category") | |
| character = item.pop("character_name") | |
| title = item | |
| title["genres"] = json.loads(title.pop("genres_json")) | |
| title["category"] = category | |
| title["character_name"] = character | |
| results.append(title) | |
| return results | |
| def credits_for_title(conn: sqlite3.Connection, title_id: str) -> list[dict]: | |
| rows = conn.execute( | |
| "SELECT people.id, people.name, people.roles, people.known_for, " | |
| "people.thumb, credits.category, credits.character_name " | |
| "FROM credits JOIN people ON people.id=credits.person_id " | |
| "WHERE credits.title_id=? ORDER BY credits.position, people.name", | |
| (title_id,), | |
| ).fetchall() | |
| return [dict(row) for row in rows] | |
| def media_for_title(conn: sqlite3.Connection, title_id: str) -> list[dict]: | |
| rows = conn.execute( | |
| "SELECT id, media_type, local_path, caption, position FROM media " | |
| "WHERE title_id=? ORDER BY position, id", | |
| (title_id,), | |
| ).fetchall() | |
| return [dict(row) for row in rows] | |
| # --------------------------------------------------------------------------- | |
| # Search (DB-backed; matches against titles and captured search catalog) | |
| # --------------------------------------------------------------------------- | |
| def _matches(query_folded: str, candidates: Iterable[str]) -> bool: | |
| # A one-character title such as ``M`` must not match every query that | |
| # happens to contain that character. Search is query-within-field; aliases | |
| # are already represented as their own candidate fields. | |
| return any(term and query_folded in term for term in candidates) | |
| def search_titles(conn: sqlite3.Connection, query: str) -> list[dict]: | |
| """Return search rows whose title (or captured match term) fits query.""" | |
| folded = query.casefold().strip() | |
| if not folded: | |
| return [] | |
| results: list[dict] = [] | |
| for row in conn.execute( | |
| "SELECT * FROM search_catalog ORDER BY rank" | |
| ).fetchall(): | |
| terms = [row["display_title"].casefold()] | |
| terms.extend( | |
| term.casefold() | |
| for term in json.loads(row["match_terms_json"]) | |
| ) | |
| if not _matches(folded, terms): | |
| continue | |
| rating = row["rating"] | |
| votes = row["votes"] | |
| if row["local_title_id"]: | |
| aggregate = title_aggregate(conn, row["local_title_id"]) | |
| if aggregate is not None: | |
| rating = aggregate["rating"] | |
| votes = aggregate["votes"] | |
| results.append( | |
| { | |
| "title": row["display_title"], | |
| "local_id": row["local_title_id"], | |
| "year": row["year"], | |
| "runtime": row["runtime"], | |
| "cert": row["cert"], | |
| "metascore": row["metascore"], | |
| "rating": rating, | |
| "votes": votes, | |
| "thumb": row["thumb"], | |
| } | |
| ) | |
| return results | |
| def search_people(conn: sqlite3.Connection, query: str) -> list[dict]: | |
| folded = query.casefold().strip() | |
| if not folded: | |
| return [] | |
| results: list[dict] = [] | |
| for row in conn.execute("SELECT * FROM people ORDER BY id").fetchall(): | |
| terms = [row["name"].casefold()] | |
| terms.extend( | |
| term.casefold() | |
| for term in json.loads(row["match_terms_json"]) | |
| ) | |
| if not _matches(folded, terms): | |
| continue | |
| results.append( | |
| { | |
| "id": row["id"], | |
| "name": row["name"], | |
| "roles": row["roles"], | |
| "known_for": row["known_for"], | |
| "thumb": row["thumb"], | |
| } | |
| ) | |
| return results | |
| # --------------------------------------------------------------------------- | |
| # Watchlist (server-owned; idempotent per (account, title)) | |
| # --------------------------------------------------------------------------- | |
| def watchlist_title_ids(conn: sqlite3.Connection, account_key: str) -> list[str]: | |
| rows = conn.execute( | |
| "SELECT title_id FROM watchlist_entries WHERE account_key = ? " | |
| "ORDER BY rowid", | |
| (account_key,), | |
| ).fetchall() | |
| return [row["title_id"] for row in rows] | |
| def watchlist_titles(conn: sqlite3.Connection, account_key: str) -> list[dict]: | |
| rows = conn.execute( | |
| """ | |
| SELECT titles.* FROM watchlist_entries | |
| JOIN titles ON titles.id = watchlist_entries.title_id | |
| WHERE watchlist_entries.account_key = ? | |
| ORDER BY watchlist_entries.rowid | |
| """, | |
| (account_key,), | |
| ).fetchall() | |
| return [_title_dict(row, conn) for row in rows] | |
| def watchlist_add( | |
| conn: sqlite3.Connection, account_key: str, title_id: str | |
| ) -> str: | |
| """Idempotent add; returns 'added' or 'exists'.""" | |
| cursor = conn.execute( | |
| "INSERT OR IGNORE INTO watchlist_entries " | |
| "(account_key, title_id, added_at) VALUES (?, ?, ?)", | |
| (account_key, title_id, FROZEN_CLOCK), | |
| ) | |
| return "added" if cursor.rowcount else "exists" | |
| def watchlist_remove( | |
| conn: sqlite3.Connection, account_key: str, title_id: str | |
| ) -> bool: | |
| cursor = conn.execute( | |
| "DELETE FROM watchlist_entries WHERE account_key = ? AND title_id = ?", | |
| (account_key, title_id), | |
| ) | |
| return bool(cursor.rowcount) | |
| # --------------------------------------------------------------------------- | |
| # Ratings (1-10 integer; single row per account+title; deletable) | |
| # --------------------------------------------------------------------------- | |
| def get_rating( | |
| conn: sqlite3.Connection, account_key: str, title_id: str | |
| ) -> int | None: | |
| row = conn.execute( | |
| "SELECT value FROM ratings WHERE account_key = ? AND title_id = ?", | |
| (account_key, title_id), | |
| ).fetchone() | |
| return row["value"] if row else None | |
| def ratings_for_account( | |
| conn: sqlite3.Connection, account_key: str | |
| ) -> dict[str, int]: | |
| rows = conn.execute( | |
| "SELECT title_id, value FROM ratings WHERE account_key = ?", | |
| (account_key,), | |
| ).fetchall() | |
| return {row["title_id"]: row["value"] for row in rows} | |
| def set_rating( | |
| conn: sqlite3.Connection, account_key: str, title_id: str, value: int | |
| ) -> None: | |
| if not isinstance(value, int) or not 1 <= value <= 10: | |
| raise ValueError("rating must be an integer between 1 and 10") | |
| conn.execute( | |
| """ | |
| INSERT INTO ratings (account_key, title_id, value, updated_at) | |
| VALUES (?, ?, ?, ?) | |
| ON CONFLICT (account_key, title_id) | |
| DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at | |
| """, | |
| (account_key, title_id, value, FROZEN_CLOCK), | |
| ) | |
| def delete_rating( | |
| conn: sqlite3.Connection, account_key: str, title_id: str | |
| ) -> bool: | |
| cursor = conn.execute( | |
| "DELETE FROM ratings WHERE account_key = ? AND title_id = ?", | |
| (account_key, title_id), | |
| ) | |
| return bool(cursor.rowcount) | |
| # --------------------------------------------------------------------------- | |
| # Custom lists (server-owned; membership idempotent; owner-scoped) | |
| # --------------------------------------------------------------------------- | |
| def _list_dict(conn: sqlite3.Connection, row: sqlite3.Row) -> dict: | |
| members = [ | |
| member["title_id"] | |
| for member in conn.execute( | |
| "SELECT title_id FROM list_members WHERE list_id = ? " | |
| "ORDER BY rowid", | |
| (row["id"],), | |
| ).fetchall() | |
| ] | |
| profile = conn.execute( | |
| "SELECT description, updated_at FROM list_profiles WHERE list_id=?", | |
| (row["id"],), | |
| ).fetchone() | |
| return { | |
| "id": row["id"], | |
| "owner_key": row["owner_key"], | |
| "name": row["name"], | |
| "list_type": row["list_type"], | |
| "privacy": row["privacy"], | |
| "description": profile["description"] if profile else "", | |
| "updated_at": profile["updated_at"] if profile else row["created_at"], | |
| "members": members, | |
| } | |
| def get_list(conn: sqlite3.Connection, list_id: str) -> dict | None: | |
| row = conn.execute( | |
| "SELECT * FROM lists WHERE id = ?", (list_id,) | |
| ).fetchone() | |
| return _list_dict(conn, row) if row else None | |
| def lists_for_account( | |
| conn: sqlite3.Connection, account_key: str | |
| ) -> list[dict]: | |
| rows = conn.execute( | |
| "SELECT * FROM lists WHERE owner_key = ? ORDER BY rowid", | |
| (account_key,), | |
| ).fetchall() | |
| return [_list_dict(conn, row) for row in rows] | |
| def find_list_by_name( | |
| conn: sqlite3.Connection, account_key: str, name: str | |
| ) -> dict | None: | |
| row = conn.execute( | |
| "SELECT * FROM lists WHERE owner_key = ? AND name = ? COLLATE NOCASE", | |
| (account_key, name), | |
| ).fetchone() | |
| return _list_dict(conn, row) if row else None | |
| def _existing_list_ids(conn: sqlite3.Connection) -> set[str]: | |
| return { | |
| row["id"] for row in conn.execute("SELECT id FROM lists").fetchall() | |
| } | |
| def next_list_id(conn: sqlite3.Connection) -> str: | |
| taken = _existing_list_ids(conn) | |
| sequence = 1 | |
| while True: | |
| candidate = f"ls-5000009{sequence:02d}" | |
| if candidate not in taken: | |
| return candidate | |
| sequence += 1 | |
| def create_list( | |
| conn: sqlite3.Connection, | |
| account_key: str, | |
| name: str, | |
| list_type: str, | |
| privacy: str, | |
| description: str = "", | |
| ) -> dict: | |
| list_id = next_list_id(conn) | |
| conn.execute( | |
| "INSERT INTO lists (id, owner_key, name, list_type, privacy, " | |
| "created_at) VALUES (?, ?, ?, ?, ?, ?)", | |
| (list_id, account_key, name, list_type, privacy, FROZEN_CLOCK), | |
| ) | |
| conn.execute( | |
| "INSERT INTO list_profiles(list_id, description, updated_at) " | |
| "VALUES (?, ?, ?)", | |
| (list_id, description, FROZEN_CLOCK), | |
| ) | |
| return { | |
| "id": list_id, | |
| "owner_key": account_key, | |
| "name": name, | |
| "list_type": list_type, | |
| "privacy": privacy, | |
| "description": description, | |
| "updated_at": FROZEN_CLOCK, | |
| "members": [], | |
| } | |
| def list_add_member( | |
| conn: sqlite3.Connection, list_id: str, title_id: str | |
| ) -> str: | |
| """Idempotent membership add; returns 'added' or 'exists'.""" | |
| cursor = conn.execute( | |
| "INSERT OR IGNORE INTO list_members (list_id, title_id) " | |
| "VALUES (?, ?)", | |
| (list_id, title_id), | |
| ) | |
| return "added" if cursor.rowcount else "exists" | |
| def list_member_titles( | |
| conn: sqlite3.Connection, list_id: str | |
| ) -> list[dict]: | |
| rows = conn.execute( | |
| """ | |
| SELECT titles.* FROM list_members | |
| JOIN titles ON titles.id = list_members.title_id | |
| WHERE list_members.list_id = ? | |
| ORDER BY list_members.rowid | |
| """, | |
| (list_id,), | |
| ).fetchall() | |
| return [_title_dict(row, conn) for row in rows] | |
| def update_list( | |
| conn: sqlite3.Connection, | |
| list_id: str, | |
| *, | |
| name: str, | |
| description: str, | |
| privacy: str, | |
| ) -> dict: | |
| conn.execute( | |
| "UPDATE lists SET name=?, privacy=? WHERE id=?", | |
| (name, privacy, list_id), | |
| ) | |
| conn.execute( | |
| "INSERT INTO list_profiles(list_id, description, updated_at) " | |
| "VALUES (?, ?, ?) ON CONFLICT(list_id) DO UPDATE SET " | |
| "description=excluded.description, updated_at=excluded.updated_at", | |
| (list_id, description, FROZEN_CLOCK), | |
| ) | |
| updated = get_list(conn, list_id) | |
| if updated is None: | |
| raise LookupError(list_id) | |
| return updated | |
| def delete_list(conn: sqlite3.Connection, list_id: str) -> bool: | |
| return bool(conn.execute("DELETE FROM lists WHERE id=?", (list_id,)).rowcount) | |
| def list_remove_member( | |
| conn: sqlite3.Connection, list_id: str, title_id: str | |
| ) -> bool: | |
| return bool( | |
| conn.execute( | |
| "DELETE FROM list_members WHERE list_id=? AND title_id=?", | |
| (list_id, title_id), | |
| ).rowcount | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Reviews (one editable local review per account and title) | |
| # --------------------------------------------------------------------------- | |
| def reviews_for_title(conn: sqlite3.Connection, title_id: str) -> list[dict]: | |
| rows = conn.execute( | |
| "SELECT reviews.*, accounts.display_name FROM reviews JOIN accounts " | |
| "ON accounts.key=reviews.account_key WHERE reviews.title_id=? " | |
| "ORDER BY reviews.updated_at DESC, reviews.id DESC", | |
| (title_id,), | |
| ).fetchall() | |
| return [dict(row) for row in rows] | |
| def get_review(conn: sqlite3.Connection, review_id: int) -> dict | None: | |
| row = conn.execute( | |
| "SELECT reviews.*, accounts.display_name FROM reviews JOIN accounts " | |
| "ON accounts.key=reviews.account_key WHERE reviews.id=?", | |
| (review_id,), | |
| ).fetchone() | |
| return dict(row) if row else None | |
| def review_for_account( | |
| conn: sqlite3.Connection, account_key: str, title_id: str | |
| ) -> dict | None: | |
| row = conn.execute( | |
| "SELECT * FROM reviews WHERE account_key=? AND title_id=?", | |
| (account_key, title_id), | |
| ).fetchone() | |
| return dict(row) if row else None | |
| def create_review( | |
| conn: sqlite3.Connection, | |
| account_key: str, | |
| title_id: str, | |
| *, | |
| summary: str, | |
| body: str, | |
| spoiler: bool, | |
| ) -> dict: | |
| cursor = conn.execute( | |
| "INSERT INTO reviews(account_key,title_id,summary,body,spoiler,created_at,updated_at) " | |
| "VALUES (?,?,?,?,?,?,?)", | |
| (account_key, title_id, summary, body, int(spoiler), FROZEN_CLOCK, FROZEN_CLOCK), | |
| ) | |
| result = get_review(conn, int(cursor.lastrowid)) | |
| if result is None: | |
| raise RuntimeError("review insert was not readable") | |
| return result | |
| def update_review( | |
| conn: sqlite3.Connection, | |
| review_id: int, | |
| *, | |
| summary: str, | |
| body: str, | |
| spoiler: bool, | |
| ) -> dict: | |
| conn.execute( | |
| "UPDATE reviews SET summary=?, body=?, spoiler=?, updated_at=? WHERE id=?", | |
| (summary, body, int(spoiler), FROZEN_CLOCK, review_id), | |
| ) | |
| result = get_review(conn, review_id) | |
| if result is None: | |
| raise LookupError(review_id) | |
| return result | |
| def delete_review(conn: sqlite3.Connection, review_id: int) -> bool: | |
| return bool(conn.execute("DELETE FROM reviews WHERE id=?", (review_id,)).rowcount) | |
| # --------------------------------------------------------------------------- | |
| # Introspection helpers (tests + health) | |
| # --------------------------------------------------------------------------- | |
| def journal_mode(conn: sqlite3.Connection) -> str: | |
| return conn.execute("PRAGMA journal_mode").fetchone()[0] | |
| def store_snapshot(account_keys: Iterable[str] = ("alex", "jordan")) -> dict: | |
| """Legacy-shaped snapshot of all account state (test compatibility).""" | |
| ensure_database() | |
| conn = connect() | |
| try: | |
| accounts: dict[str, dict] = {} | |
| for key in account_keys: | |
| accounts[key] = { | |
| "watchlist": watchlist_title_ids(conn, key), | |
| "ratings": ratings_for_account(conn, key), | |
| "lists": { | |
| item["id"]: item for item in lists_for_account(conn, key) | |
| }, | |
| } | |
| return {"accounts": accounts} | |
| finally: | |
| conn.close() | |