File size: 55,908 Bytes
2fcdd6d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 | """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()
|