返回 last30days-skill
test_store_migrations.py
根目录 / tests / test_store_migrations.py
1 """Migrations publish schema changes and their version marker together."""
2
3 import sqlite3
4 import threading
5 from concurrent.futures import ThreadPoolExecutor
6
7 import pytest
8
9 import store
10
11
12 @pytest.fixture
13 def legacy_store(tmp_path, monkeypatch, request):
14 path = tmp_path / "research.db"
15 version = getattr(request, "param", 3)
16 monkeypatch.setattr(store, "_db_override", path)
17 with monkeypatch.context() as legacy:
18 legacy.setattr(store, "MIGRATIONS", {
19 key: value for key, value in store.MIGRATIONS.items() if key <= version
20 })
21 store.init_db()
22 return path, version
23
24
25 @pytest.mark.parametrize("legacy_store", [3, 4], indirect=True)
26 def test_failed_version_write_rolls_back_schema_and_retry_succeeds(legacy_store):
27 _, previous_version = legacy_store
28 conn = store._connect()
29
30 def deny_version_write(action, table, *unused):
31 return sqlite3.SQLITE_DENY if action == sqlite3.SQLITE_INSERT and table == "schema_version" else sqlite3.SQLITE_OK
32
33 conn.set_authorizer(deny_version_write)
34 try:
35 with pytest.raises(sqlite3.DatabaseError, match="authorized"):
36 store._run_migrations(conn)
37 finally:
38 conn.close()
39
40 conn = store._connect()
41 try:
42 assert conn.execute("SELECT MAX(version) FROM schema_version").fetchone()[0] == previous_version
43 columns = {row[1] for row in conn.execute("PRAGMA table_info(research_runs)")}
44 assert ("cost_unknown" in columns) == (previous_version == 4)
45 assert conn.execute("PRAGMA table_info(removed_run_usage)").fetchall() == []
46 finally:
47 conn.close()
48 store.init_db()
49 conn = store._connect()
50 try:
51 assert conn.execute("SELECT MAX(version) FROM schema_version").fetchone()[0] == 5
52 assert "cost_unknown" in {row[1] for row in conn.execute("PRAGMA table_info(research_runs)")}
53 assert {row[1] for row in conn.execute("PRAGMA table_info(removed_run_usage)")} == {
54 "run_id", "run_day", "token_cost", "cost_unknown",
55 }
56 finally:
57 conn.close()
58
59
60 def test_concurrent_initialization_applies_each_version_once(legacy_store):
61 path, _ = legacy_store
62 barrier = threading.Barrier(8)
63
64 def initialize(_):
65 barrier.wait(timeout=5)
66 return store.init_db()
67
68 with ThreadPoolExecutor(max_workers=8) as executor:
69 assert list(executor.map(initialize, range(8))) == [path] * 8
70 conn = store._connect()
71 try:
72 assert [row[0] for row in conn.execute("SELECT version FROM schema_version ORDER BY version")] == [1, 2, 3, 4, 5]
73 finally:
74 conn.close()
75
76
77 def test_current_schema_check_succeeds_while_another_connection_holds_writer(legacy_store):
78 store.init_db()
79 writer = store._connect()
80 reader = store._connect()
81 try:
82 writer.execute("BEGIN IMMEDIATE")
83 writer.execute("INSERT INTO settings (key, value) VALUES ('held-writer', 'uncommitted')")
84 reader.execute("PRAGMA busy_timeout=1")
85
86 store._run_migrations(reader)
87
88 assert not reader.in_transaction
89 assert reader.execute("SELECT MAX(version) FROM schema_version").fetchone()[0] == 5
90 assert reader.execute("SELECT value FROM settings WHERE key = 'held-writer'").fetchone() is None
91 finally:
92 writer.rollback()
93 writer.close()
94 reader.close()
95
96
97 def test_pending_migration_after_committed_default_seeding(legacy_store):
98 conn = store._connect()
99 try:
100 conn.execute("DELETE FROM settings WHERE key = 'daily_budget'")
101 conn.execute("INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)", ("daily_budget", "9.25"))
102 conn.commit()
103
104 store._run_migrations(conn)
105
106 assert conn.execute("SELECT MAX(version) FROM schema_version").fetchone()[0] == 5
107 assert conn.execute("SELECT value FROM settings WHERE key = 'daily_budget'").fetchone()[0] == "9.25"
108 assert "cost_unknown" in {row[1] for row in conn.execute("PRAGMA table_info(research_runs)")}
109 finally:
110 conn.close()
111
112
113 def test_migration_retains_trigger_body_and_quoted_semicolons(legacy_store, monkeypatch):
114 monkeypatch.setattr(store, "MIGRATIONS", {
115 **store.MIGRATIONS,
116 6: """
117 CREATE TABLE migration_probe (value TEXT);
118 CREATE TRIGGER migration_probe_insert AFTER INSERT ON migration_probe BEGIN
119 INSERT INTO settings(key, value) VALUES ('trigger-one', 'value;one');
120 INSERT INTO settings(key, value) VALUES ('trigger-two', new.value);
121 END;
122 INSERT INTO migration_probe VALUES ('value;two');
123 """,
124 })
125 store.init_db()
126 assert store.get_setting("trigger-one") == "value;one"
127 assert store.get_setting("trigger-two") == "value;two"
128
129
130 @pytest.mark.parametrize("legacy_store", [4], indirect=True)
131 def test_version_four_upgrade_keeps_existing_usage_after_topic_removal(legacy_store):
132 conn = store._connect()
133 try:
134 assert conn.execute("SELECT MAX(version) FROM schema_version").fetchone()[0] == 4
135 topic_id = conn.execute("INSERT INTO topics (name) VALUES ('Legacy topic')").lastrowid
136 conn.executemany(
137 """INSERT INTO research_runs (topic_id, run_date, token_cost, cost_unknown)
138 VALUES (?, '2026-01-01 12:00:00', ?, ?)""",
139 [(topic_id, 1.25, 0), (topic_id, 0.25, 1)],
140 )
141 conn.commit()
142 finally:
143 conn.close()
144
145 store.init_db()
146 assert store.get_daily_usage("2026-01-01") == (1.50, 1)
147 assert store.remove_topic("Legacy topic")
148 assert store.get_latest_completed_runs(topic_id) == []
149 assert store.get_daily_usage("2026-01-01") == (1.50, 1)
150
150 lines PYTHON