forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBc9b707aAhmet Kaan Gümüş4 months ago189 commits

migration_sql.rs1066 lines, 67.6 KiBHistoryRawDownload
1//! The boot migration, as SurrealQL text.
2//!
3//! Split out of [`crate::constant`] purely for size: these three batches are
4//! ~700 lines of schema, and left in the constants file they buried the
5//! validation bounds that file exists to hold. Nothing else changed — they are
6//! still `pub const`, still the only migration text, and
7//! [`crate::database::migrate`] still reads [`MIGRATION_BATCHES`] and nothing
8//! else.
9//!
10//! Numbers stay in `constant.rs`: `tests/limits_completeness.rs` sweeps `src/`
11//! for stray bounds, and a bound hidden here would reach neither `GET /limits`
12//! nor the OpenAPI spec. Only SurrealQL strings live in this file.
13
14/// Repairs that must run *before* the DDL batch, because the DDL is what makes
15/// them impossible.
16///
17/// `MIGRATION` retires `exam_question.source_bank` with `REMOVE FIELD`, and
18/// once the column is gone SCHEMAFULL rejects every write to a row that still
19/// stores it ("Found field 'source_bank', but no such field exists") — an
20/// UNSET included. So the value has to go while its definition is still
21/// standing. Runs as its own query for the usual reason (see `MIGRATION`).
22///
23/// `chatbot_message.claimed_by` / `claimed_at` (retired 2026-07-30 with the
24/// chat claim queue) are the same story, one table over.
25///
26/// The table-exists guard is load-bearing: on a fresh database `MIGRATION` has
27/// not run yet, and an UPDATE against an undefined table is an error, not an
28/// empty result. On a database that has the table but never had the column the
29/// `WHERE` simply matches nothing.
30pub const PRE_REPAIR: &str = "
31 IF 'exam_question' IN object::keys((INFO FOR DB).tables) {
32 UPDATE exam_question UNSET source_bank WHERE source_bank != NONE
33 };
34 IF 'chatbot_message' IN object::keys((INFO FOR DB).tables) {
35 UPDATE chatbot_message UNSET claimed_by, claimed_at
36 WHERE claimed_by != NONE OR claimed_at != NONE
37 };
38";
39
40/// SCHEMAFULL schema: every column is typed, references use `record<..>`.
41/// Idempotent — safe to run on every boot: `IF NOT EXISTS` guards the
42/// definitions and `REMOVE ... IF EXISTS` retires schema (like the
43/// single-attempt unique index) exactly once. DDL only — data backfills live
44/// in `BACKFILL`, which runs as a *separate* query: statements inside one
45/// batch see the schema as it stood when the batch started, so an UPDATE next
46/// to a fresh `DEFINE FIELD audience.*` writes against the old field set and
47/// SCHEMAFULL silently strips the very keys being backfilled.
48pub const MIGRATION: &str = "
49 DEFINE TABLE IF NOT EXISTS user SCHEMAFULL;
50 DEFINE FIELD IF NOT EXISTS username ON user TYPE string;
51 DEFINE FIELD IF NOT EXISTS password_hash ON user TYPE string;
52 DEFINE FIELD IF NOT EXISTS role ON user TYPE string DEFAULT 'student';
53 DEFINE FIELD IF NOT EXISTS name ON user TYPE option<string>;
54 DEFINE FIELD IF NOT EXISTS surname ON user TYPE option<string>;
55 DEFINE FIELD IF NOT EXISTS email ON user TYPE option<string>;
56 DEFINE FIELD IF NOT EXISTS phone ON user TYPE option<string>;
57 DEFINE FIELD IF NOT EXISTS birth_date ON user TYPE option<string>;
58 DEFINE FIELD IF NOT EXISTS theme ON user TYPE option<string>;
59 DEFINE FIELD IF NOT EXISTS language ON user TYPE option<string>;
60 DEFINE FIELD IF NOT EXISTS palette_color ON user TYPE option<string>;
61 DEFINE FIELD IF NOT EXISTS chatbot_thread_count ON user TYPE option<int>;
62 DEFINE FIELD IF NOT EXISTS board_count ON user TYPE option<int>;
63 DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE;
64
65 DEFINE TABLE IF NOT EXISTS session SCHEMAFULL;
66 DEFINE FIELD IF NOT EXISTS user ON session TYPE record<user>;
67 DEFINE FIELD IF NOT EXISTS token ON session TYPE string;
68 DEFINE FIELD IF NOT EXISTS expires_at ON session TYPE int;
69 DEFINE INDEX IF NOT EXISTS session_token ON session FIELDS token UNIQUE;
70 DEFINE INDEX IF NOT EXISTS session_expires ON session FIELDS expires_at;
71
72 DEFINE TABLE IF NOT EXISTS note SCHEMAFULL;
73 DEFINE FIELD IF NOT EXISTS user ON note TYPE record<user>;
74 DEFINE FIELD IF NOT EXISTS title ON note TYPE string;
75 DEFINE FIELD IF NOT EXISTS content ON note TYPE string;
76 DEFINE FIELD IF NOT EXISTS file_count ON note TYPE option<int>;
77 DEFINE INDEX IF NOT EXISTS note_user ON note FIELDS user;
78
79 DEFINE TABLE IF NOT EXISTS message SCHEMAFULL;
80 DEFINE FIELD IF NOT EXISTS sender ON message TYPE record<user>;
81 DEFINE FIELD IF NOT EXISTS recipient ON message TYPE record<user>;
82 DEFINE FIELD IF NOT EXISTS subject ON message TYPE string;
83 DEFINE FIELD IF NOT EXISTS body ON message TYPE string;
84 DEFINE FIELD IF NOT EXISTS label ON message TYPE option<string>;
85 DEFINE FIELD IF NOT EXISTS sent_at ON message TYPE int;
86 DEFINE FIELD IF NOT EXISTS read ON message TYPE bool DEFAULT false;
87 DEFINE FIELD IF NOT EXISTS sender_folder ON message TYPE string DEFAULT 'sent';
88 DEFINE FIELD IF NOT EXISTS recipient_folder ON message TYPE string DEFAULT 'inbox';
89 -- Where each side's copy sat before it was filed into archive/trash, so a
90 -- restore lands where it came from. NONE while the copy is in its home
91 -- folder — and on rows filed before this field existed (2026-07-23), which
92 -- restore to the home folder just as they always did.
93 DEFINE FIELD IF NOT EXISTS sender_origin ON message TYPE option<string>;
94 DEFINE FIELD IF NOT EXISTS recipient_origin ON message TYPE option<string>;
95 DEFINE INDEX IF NOT EXISTS message_sender ON message FIELDS sender;
96 DEFINE INDEX IF NOT EXISTS message_recipient ON message FIELDS recipient;
97
98 -- Collaborative whiteboard (2026-07-31): one `board` is a room, one
99 -- `board_stroke` is one append-only mark. A clear NEVER deletes — it bumps
100 -- `epoch`, so the canvas empties while the whole history stays replayable.
101 -- `locked` is a plain bool, not an option: the open-board guard asks for
102 -- `locked = false`, which a NONE would never match. `locked_by`/`locked_at`/
103 -- `closed_at` are three top-level option columns rather than one nested
104 -- object, because SurrealDB 3 drops an object key valued NONE.
105 DEFINE TABLE IF NOT EXISTS board SCHEMAFULL;
106 DEFINE FIELD IF NOT EXISTS creator ON board TYPE record<user>;
107 DEFINE FIELD IF NOT EXISTS title ON board TYPE string;
108 DEFINE FIELD IF NOT EXISTS participants ON board TYPE array<record<user>>;
109 DEFINE FIELD IF NOT EXISTS locked ON board TYPE bool DEFAULT false;
110 DEFINE FIELD IF NOT EXISTS locked_by ON board TYPE option<record<user>>;
111 DEFINE FIELD IF NOT EXISTS locked_at ON board TYPE option<int>;
112 DEFINE FIELD IF NOT EXISTS epoch ON board TYPE int DEFAULT 0;
113 -- Resets to 0 on every clear (recoverable); never resets (stamps closed_at).
114 DEFINE FIELD IF NOT EXISTS epoch_stroke_count ON board TYPE option<int>;
115 DEFINE FIELD IF NOT EXISTS total_stroke_count ON board TYPE option<int>;
116 -- Stamped once, when the lifetime cap is hit: permanently read-only.
117 DEFINE FIELD IF NOT EXISTS closed_at ON board TYPE option<int>;
118 DEFINE FIELD IF NOT EXISTS created_at ON board TYPE int;
119 DEFINE INDEX IF NOT EXISTS board_creator ON board FIELDS creator;
120 -- Listing a user's boards asks `creator = $u OR participants CONTAINS $u`;
121 -- without this the CONTAINS half is a full scan. SurrealDB indexes an
122 -- array field per element, so it covers the membership test directly.
123 DEFINE INDEX IF NOT EXISTS board_participants ON board FIELDS participants;
124
125 DEFINE TABLE IF NOT EXISTS board_stroke SCHEMAFULL;
126 DEFINE FIELD IF NOT EXISTS board ON board_stroke TYPE record<board>;
127 DEFINE FIELD IF NOT EXISTS author ON board_stroke TYPE record<user>;
128 -- 'stroke' or 'clear'; `payload` is the opaque blob, absent on a clear
129 -- marker, and `count` is populated only on a clear marker — the final
130 -- stroke count of the epoch that marker closed.
131 DEFINE FIELD IF NOT EXISTS kind ON board_stroke TYPE string;
132 DEFINE FIELD IF NOT EXISTS payload ON board_stroke TYPE option<string>;
133 DEFINE FIELD IF NOT EXISTS count ON board_stroke TYPE option<int>;
134 DEFINE FIELD IF NOT EXISTS epoch ON board_stroke TYPE int;
135 DEFINE FIELD IF NOT EXISTS created_at ON board_stroke TYPE int;
136 -- Keeps a socket's join-replay scoped to the current epoch instead of
137 -- scanning the board's whole history.
138 DEFINE INDEX IF NOT EXISTS board_stroke_board_epoch ON board_stroke FIELDS board, epoch;
139 -- The clear markers ARE the epoch index, so listing them is a hot read.
140 DEFINE INDEX IF NOT EXISTS board_stroke_board_kind ON board_stroke FIELDS board, kind;
141
142 DEFINE TABLE IF NOT EXISTS note_file SCHEMAFULL;
143 DEFINE FIELD IF NOT EXISTS note ON note_file TYPE record<note>;
144 DEFINE FIELD IF NOT EXISTS name ON note_file TYPE string;
145 DEFINE FIELD IF NOT EXISTS content_type ON note_file TYPE string;
146 DEFINE FIELD IF NOT EXISTS size ON note_file TYPE int;
147 DEFINE INDEX IF NOT EXISTS note_file_note ON note_file FIELDS note;
148
149 -- Chatbot relay (2026-07-23): a `thread` groups the turns, one
150 -- `chatbot_message` is one turn. `user_id` rides on the message too so an
151 -- ownership check needs no join. An assistant turn is born `pending` and
152 -- is completed (or failed) by the task holding the AI-bridge stream —
153 -- hence the BACKFILL sweep, since that task dies with the process.
154 DEFINE TABLE IF NOT EXISTS chatbot_thread SCHEMAFULL;
155 DEFINE FIELD IF NOT EXISTS user_id ON chatbot_thread TYPE record<user> READONLY;
156 DEFINE FIELD IF NOT EXISTS title ON chatbot_thread TYPE option<string>;
157 DEFINE FIELD IF NOT EXISTS created_at ON chatbot_thread TYPE int READONLY;
158 DEFINE FIELD IF NOT EXISTS updated_at ON chatbot_thread TYPE int;
159 DEFINE INDEX IF NOT EXISTS chatbot_thread_user_updated ON chatbot_thread FIELDS user_id, updated_at;
160
161 DEFINE TABLE IF NOT EXISTS chatbot_message SCHEMAFULL;
162 DEFINE FIELD IF NOT EXISTS thread_id ON chatbot_message TYPE record<chatbot_thread> READONLY;
163 DEFINE FIELD IF NOT EXISTS user_id ON chatbot_message TYPE record<user> READONLY;
164 DEFINE FIELD IF NOT EXISTS role ON chatbot_message TYPE string READONLY;
165 DEFINE FIELD IF NOT EXISTS content ON chatbot_message TYPE string;
166 DEFINE FIELD IF NOT EXISTS status ON chatbot_message TYPE string;
167 DEFINE FIELD IF NOT EXISTS truncated ON chatbot_message TYPE bool DEFAULT false;
168 DEFINE FIELD IF NOT EXISTS error_code ON chatbot_message TYPE option<string>;
169 DEFINE FIELD IF NOT EXISTS created_at ON chatbot_message TYPE int READONLY;
170 DEFINE FIELD IF NOT EXISTS completed_at ON chatbot_message TYPE option<int>;
171 -- The chat claim queue is gone (2026-07-30): one process answers its own
172 -- turns, so nothing claims them. PRE_REPAIR clears the values first —
173 -- SCHEMAFULL rejects every write to a row still storing a column that no
174 -- longer exists.
175 REMOVE FIELD IF EXISTS claimed_by ON TABLE chatbot_message;
176 REMOVE FIELD IF EXISTS claimed_at ON TABLE chatbot_message;
177 DEFINE INDEX IF NOT EXISTS chatbot_message_thread_created ON chatbot_message FIELDS thread_id, created_at;
178 DEFINE INDEX IF NOT EXISTS chatbot_message_user ON chatbot_message FIELDS user_id;
179 -- The boot sweep asks for pending rows by age.
180 DEFINE INDEX IF NOT EXISTS chatbot_message_status_created ON chatbot_message FIELDS status, created_at;
181
182 -- The AI worker presence table is gone (2026-07-30): one process holds
183 -- every worker socket, so its in-process registry is the whole truth and
184 -- nothing needed publishing.
185 REMOVE TABLE IF EXISTS ai_worker;
186
187 -- The elected-boot lease is gone with it (2026-07-30): one process migrates,
188 -- so nothing takes the lock. SCHEMALESS and read by nobody, so unlike the
189 -- claim columns it needs no PRE_REPAIR — the table just goes.
190 REMOVE TABLE IF EXISTS migration_lock;
191
192 -- How much of a rate-limit budget one client has spent in one wall window
193 -- (2026-07-27). One row per tier+client+window, id-keyed so a restart of
194 -- the process lands back on the same record; `hits` is the durable total
195 -- the in-memory bucket folds its local admits into (see
196 -- `crate::rate_limit`), which is what carries a window across a restart.
197 -- Rows are swept by the same task once their window is past.
198 DEFINE TABLE IF NOT EXISTS rate_limit SCHEMAFULL;
199 DEFINE FIELD IF NOT EXISTS hits ON rate_limit TYPE int DEFAULT 0;
200 DEFINE FIELD IF NOT EXISTS window_start ON rate_limit TYPE int;
201
202 DEFINE TABLE IF NOT EXISTS event SCHEMAFULL;
203 DEFINE FIELD IF NOT EXISTS creator ON event TYPE record<user>;
204 DEFINE FIELD IF NOT EXISTS title ON event TYPE string;
205 DEFINE FIELD IF NOT EXISTS description ON event TYPE string;
206 DEFINE FIELD IF NOT EXISTS audience ON event TYPE object;
207 DEFINE FIELD IF NOT EXISTS audience.kind ON event TYPE string;
208 DEFINE FIELD IF NOT EXISTS audience.role ON event TYPE option<string>;
209 DEFINE FIELD IF NOT EXISTS audience.course ON event TYPE option<record<course>>;
210 DEFINE FIELD IF NOT EXISTS audience.capacity ON event TYPE option<int>;
211 -- Seats taken on the signup list, the stored capacity guard that closes
212 -- write-skew between concurrent request tasks (see `crate::domain::cap`).
213 -- Absent reads as zero, so no Rust struct needs it.
214 DEFINE FIELD IF NOT EXISTS registration_count ON event TYPE option<int>;
215 REMOVE FIELD IF EXISTS audience.users ON TABLE event;
216 DEFINE FIELD IF NOT EXISTS starts_at ON event TYPE option<int>;
217 DEFINE FIELD IF NOT EXISTS ends_at ON event TYPE option<int>;
218
219 DEFINE TABLE IF NOT EXISTS attendance SCHEMAFULL;
220 DEFINE FIELD IF NOT EXISTS event ON attendance TYPE record<event>;
221 DEFINE FIELD IF NOT EXISTS user ON attendance TYPE record<user>;
222 DEFINE FIELD IF NOT EXISTS status ON attendance TYPE string;
223 DEFINE FIELD IF NOT EXISTS marked_by ON attendance TYPE record<user>;
224 DEFINE INDEX IF NOT EXISTS attendance_event_user ON attendance FIELDS event, user UNIQUE;
225 DEFINE INDEX IF NOT EXISTS attendance_user ON attendance FIELDS user;
226
227 DEFINE TABLE IF NOT EXISTS registration SCHEMAFULL;
228 DEFINE FIELD IF NOT EXISTS event ON registration TYPE record<event>;
229 DEFINE FIELD IF NOT EXISTS user ON registration TYPE record<user>;
230 DEFINE FIELD IF NOT EXISTS registered_by ON registration TYPE record<user>;
231 DEFINE INDEX IF NOT EXISTS registration_event_user ON registration FIELDS event, user UNIQUE;
232 DEFINE INDEX IF NOT EXISTS registration_event ON registration FIELDS event;
233
234 DEFINE TABLE IF NOT EXISTS term SCHEMAFULL;
235 DEFINE FIELD IF NOT EXISTS name ON term TYPE string;
236 DEFINE FIELD IF NOT EXISTS starts_at ON term TYPE int;
237 DEFINE FIELD IF NOT EXISTS ends_at ON term TYPE int;
238 -- Courses still linking this term, the stored delete guard that closes
239 -- write-skew between concurrent request tasks (see `crate::domain::cap`).
240 -- Absent reads as zero, so no Rust struct needs it.
241 DEFINE FIELD IF NOT EXISTS course_count ON term TYPE option<int>;
242 -- Classes linking this term, the other half of the same guard. A column of
243 -- its own because `course_count` is seeded from the course rows alone.
244 DEFINE FIELD IF NOT EXISTS class_count ON term TYPE option<int>;
245
246 DEFINE TABLE IF NOT EXISTS course SCHEMAFULL;
247 DEFINE FIELD IF NOT EXISTS creator ON course TYPE record<user>;
248 DEFINE FIELD IF NOT EXISTS teachers ON course TYPE array<record<user>> DEFAULT [];
249 DEFINE FIELD IF NOT EXISTS teachers[*] ON course TYPE record<user>;
250 DEFINE FIELD IF NOT EXISTS title ON course TYPE string;
251 DEFINE FIELD IF NOT EXISTS description ON course TYPE string;
252 DEFINE FIELD IF NOT EXISTS kind ON course TYPE string DEFAULT 'course';
253 DEFINE FIELD IF NOT EXISTS term ON course TYPE option<record<term>>;
254 DEFINE FIELD IF NOT EXISTS capacity ON course TYPE option<int>;
255 DEFINE FIELD IF NOT EXISTS enrollment_count ON course TYPE option<int>;
256
257 DEFINE TABLE IF NOT EXISTS subject SCHEMAFULL;
258 DEFINE FIELD IF NOT EXISTS course ON subject TYPE record<course>;
259 DEFINE FIELD IF NOT EXISTS name ON subject TYPE string;
260 DEFINE FIELD IF NOT EXISTS description ON subject TYPE string;
261 -- How many exam questions and how many homework still point here. The
262 -- delete is conditioned on both reading zero, which is what makes the
263 -- guard hold against a question created by a concurrent request task.
264 DEFINE FIELD IF NOT EXISTS exam_question_count ON subject TYPE option<int>;
265 DEFINE FIELD IF NOT EXISTS homework_count ON subject TYPE option<int>;
266 DEFINE INDEX IF NOT EXISTS subject_course ON subject FIELDS course;
267
268 -- A class (şube) is a named set of students that bulk-manages real
269 -- `enrollment` rows: `class_member` is one student in it, `class_course` one
270 -- course it is attached to. Both counters gate the class delete.
271 DEFINE TABLE IF NOT EXISTS class_group SCHEMAFULL;
272 DEFINE FIELD IF NOT EXISTS name ON class_group TYPE string;
273 DEFINE FIELD IF NOT EXISTS grade ON class_group TYPE option<string>;
274 DEFINE FIELD IF NOT EXISTS term ON class_group TYPE option<record<term>>;
275 DEFINE FIELD IF NOT EXISTS creator ON class_group TYPE record<user>;
276 DEFINE FIELD IF NOT EXISTS class_member_count ON class_group TYPE option<int>;
277 DEFINE FIELD IF NOT EXISTS class_course_count ON class_group TYPE option<int>;
278
279 DEFINE TABLE IF NOT EXISTS class_member SCHEMAFULL;
280 DEFINE FIELD IF NOT EXISTS class ON class_member TYPE record<class_group>;
281 DEFINE FIELD IF NOT EXISTS user ON class_member TYPE record<user>;
282 DEFINE FIELD IF NOT EXISTS added_by ON class_member TYPE record<user>;
283 DEFINE INDEX IF NOT EXISTS class_member_class_user ON class_member FIELDS class, user UNIQUE;
284 DEFINE INDEX IF NOT EXISTS class_member_class ON class_member FIELDS class;
285 DEFINE INDEX IF NOT EXISTS class_member_user ON class_member FIELDS user;
286
287 DEFINE TABLE IF NOT EXISTS class_course SCHEMAFULL;
288 DEFINE FIELD IF NOT EXISTS class ON class_course TYPE record<class_group>;
289 DEFINE FIELD IF NOT EXISTS course ON class_course TYPE record<course>;
290 DEFINE FIELD IF NOT EXISTS attached_by ON class_course TYPE record<user>;
291 DEFINE INDEX IF NOT EXISTS class_course_class_course ON class_course FIELDS class, course UNIQUE;
292 DEFINE INDEX IF NOT EXISTS class_course_class ON class_course FIELDS class;
293 DEFINE INDEX IF NOT EXISTS class_course_course ON class_course FIELDS course;
294
295 DEFINE TABLE IF NOT EXISTS enrollment SCHEMAFULL;
296 DEFINE FIELD IF NOT EXISTS course ON enrollment TYPE record<course>;
297 DEFINE FIELD IF NOT EXISTS user ON enrollment TYPE record<user>;
298 DEFINE FIELD IF NOT EXISTS enrolled_by ON enrollment TYPE record<user>;
299 -- The class that pumped this row, absent when a human placed the student
300 -- directly. Absence is the meaning, so there is nothing to backfill: a class
301 -- sweep may only take back the rows it wrote.
302 DEFINE FIELD IF NOT EXISTS source ON enrollment TYPE option<record<class_group>>;
303 DEFINE INDEX IF NOT EXISTS enrollment_course_user ON enrollment FIELDS course, user UNIQUE;
304 DEFINE INDEX IF NOT EXISTS enrollment_user ON enrollment FIELDS user;
305
306 DEFINE TABLE IF NOT EXISTS parent_link SCHEMAFULL;
307 DEFINE FIELD IF NOT EXISTS parent ON parent_link TYPE record<user>;
308 DEFINE FIELD IF NOT EXISTS student ON parent_link TYPE record<user>;
309 DEFINE FIELD IF NOT EXISTS linked_by ON parent_link TYPE record<user>;
310 DEFINE INDEX IF NOT EXISTS parent_link_parent_student ON parent_link FIELDS parent, student UNIQUE;
311 DEFINE INDEX IF NOT EXISTS parent_link_parent ON parent_link FIELDS parent;
312 DEFINE INDEX IF NOT EXISTS parent_link_student ON parent_link FIELDS student;
313
314 DEFINE TABLE IF NOT EXISTS course_session SCHEMAFULL;
315 DEFINE FIELD IF NOT EXISTS course ON course_session TYPE record<course>;
316 DEFINE FIELD IF NOT EXISTS teacher ON course_session TYPE record<user>;
317 DEFINE FIELD IF NOT EXISTS topic ON course_session TYPE string;
318 DEFINE FIELD IF NOT EXISTS starts_at ON course_session TYPE int;
319 DEFINE FIELD IF NOT EXISTS ends_at ON course_session TYPE option<int>;
320 DEFINE INDEX IF NOT EXISTS course_session_course ON course_session FIELDS course;
321
322 DEFINE TABLE IF NOT EXISTS session_attendance SCHEMAFULL;
323 DEFINE FIELD IF NOT EXISTS session ON session_attendance TYPE record<course_session>;
324 DEFINE FIELD IF NOT EXISTS course ON session_attendance TYPE record<course>;
325 DEFINE FIELD IF NOT EXISTS user ON session_attendance TYPE record<user>;
326 DEFINE FIELD IF NOT EXISTS status ON session_attendance TYPE string;
327 DEFINE FIELD IF NOT EXISTS marked_by ON session_attendance TYPE record<user>;
328 DEFINE INDEX IF NOT EXISTS session_attendance_session_user ON session_attendance FIELDS session, user UNIQUE;
329 DEFINE INDEX IF NOT EXISTS session_attendance_session ON session_attendance FIELDS session;
330 DEFINE INDEX IF NOT EXISTS session_attendance_user ON session_attendance FIELDS user;
331 DEFINE INDEX IF NOT EXISTS session_attendance_course ON session_attendance FIELDS course;
332
333 DEFINE TABLE IF NOT EXISTS work_entry SCHEMAFULL;
334 DEFINE FIELD IF NOT EXISTS user ON work_entry TYPE record<user>;
335 DEFINE FIELD IF NOT EXISTS check_in ON work_entry TYPE int;
336 DEFINE FIELD IF NOT EXISTS check_out ON work_entry TYPE option<int>;
337 DEFINE INDEX IF NOT EXISTS work_entry_user ON work_entry FIELDS user;
338
339 DEFINE TABLE IF NOT EXISTS pomodoro_session SCHEMAFULL;
340 DEFINE FIELD IF NOT EXISTS user ON pomodoro_session TYPE record<user>;
341 DEFINE FIELD IF NOT EXISTS started_at ON pomodoro_session TYPE int;
342 DEFINE FIELD IF NOT EXISTS finished_at ON pomodoro_session TYPE option<int>;
343 DEFINE INDEX IF NOT EXISTS pomodoro_session_user ON pomodoro_session FIELDS user;
344
345 DEFINE TABLE IF NOT EXISTS exam SCHEMAFULL;
346 DEFINE FIELD IF NOT EXISTS creator ON exam TYPE record<user>;
347 DEFINE FIELD IF NOT EXISTS course ON exam TYPE record<course>;
348 DEFINE FIELD IF NOT EXISTS title ON exam TYPE string;
349 DEFINE FIELD IF NOT EXISTS description ON exam TYPE string;
350 DEFINE FIELD IF NOT EXISTS kind ON exam TYPE string;
351 DEFINE FIELD IF NOT EXISTS mode ON exam TYPE option<string>;
352 DEFINE FIELD IF NOT EXISTS starts_at ON exam TYPE option<int>;
353 DEFINE FIELD IF NOT EXISTS ends_at ON exam TYPE option<int>;
354 DEFINE FIELD IF NOT EXISTS duration_ms ON exam TYPE option<int>;
355 DEFINE FIELD IF NOT EXISTS max_attempts ON exam TYPE int DEFAULT 1;
356 DEFINE FIELD IF NOT EXISTS allow_rejoin ON exam TYPE bool DEFAULT true;
357 DEFINE FIELD IF NOT EXISTS allow_review ON exam TYPE bool DEFAULT false;
358 DEFINE FIELD IF NOT EXISTS draft ON exam TYPE bool DEFAULT false;
359 -- How many marks the exam carries (2026-07-27). A kind change is refused
360 -- against it, and the exam's own compare-and-set pins it, so a grade
361 -- landing mid-PATCH refuses that save instead of slipping past its gates.
362 DEFINE FIELD IF NOT EXISTS result_count ON exam TYPE option<int>;
363 DEFINE INDEX IF NOT EXISTS exam_course ON exam FIELDS course;
364
365 DEFINE TABLE IF NOT EXISTS exam_attempt SCHEMAFULL;
366 DEFINE FIELD IF NOT EXISTS exam ON exam_attempt TYPE record<exam>;
367 DEFINE FIELD IF NOT EXISTS user ON exam_attempt TYPE record<user>;
368 DEFINE FIELD IF NOT EXISTS seq ON exam_attempt TYPE int DEFAULT 1;
369 DEFINE FIELD IF NOT EXISTS started_at ON exam_attempt TYPE int;
370 DEFINE FIELD IF NOT EXISTS finished_at ON exam_attempt TYPE option<int>;
371 DEFINE FIELD IF NOT EXISTS left_at ON exam_attempt TYPE option<int>;
372 DEFINE INDEX IF NOT EXISTS exam_attempt_exam_user_seq ON exam_attempt FIELDS exam, user, seq UNIQUE;
373 DEFINE INDEX IF NOT EXISTS exam_attempt_exam ON exam_attempt FIELDS exam;
374
375 DEFINE TABLE IF NOT EXISTS exam_question SCHEMAFULL;
376 DEFINE FIELD IF NOT EXISTS exam ON exam_question TYPE record<exam>;
377 DEFINE FIELD IF NOT EXISTS text ON exam_question TYPE string;
378 DEFINE FIELD IF NOT EXISTS kind ON exam_question TYPE string;
379 DEFINE FIELD IF NOT EXISTS points ON exam_question TYPE int;
380 -- OVERWRITE, not IF NOT EXISTS: these columns changed type when choices
381 -- gained stable ids (`array<string>`/`int` -> `array<object>`/`string`),
382 -- and IF NOT EXISTS would leave an existing database on the old types.
383 DEFINE FIELD OVERWRITE choices ON exam_question TYPE option<array<object>>;
384 -- SCHEMAFULL rejects any nested key it wasn't told about, so the choice
385 -- object's own fields are declared too (same shape as `settings.exam_kinds`).
386 DEFINE FIELD OVERWRITE choices.*.id ON exam_question TYPE string;
387 DEFINE FIELD OVERWRITE choices.*.text ON exam_question TYPE string;
388 DEFINE FIELD OVERWRITE correct ON exam_question TYPE option<string>;
389 DEFINE FIELD IF NOT EXISTS subject ON exam_question TYPE record<subject>;
390 -- Provenance, one column per direction: `from_bank` is the template this
391 -- question was inserted from, `banked_as` the template most recently minted
392 -- by saving it into the bank. They replace the single `source_bank`, which
393 -- both directions wrote — so a question inserted from the bank read as
394 -- already-saved. OVERWRITE (not IF NOT EXISTS): the old column has to
395 -- actually go on an existing database, or SCHEMAFULL keeps accepting it
396 -- while the struct no longer writes it.
397 DEFINE FIELD OVERWRITE from_bank ON exam_question TYPE option<record<bank_question>>;
398 DEFINE FIELD OVERWRITE banked_as ON exam_question TYPE option<record<bank_question>>;
399 REMOVE FIELD IF EXISTS source_bank ON TABLE exam_question;
400 DEFINE INDEX IF NOT EXISTS exam_question_exam ON exam_question FIELDS exam;
401 DEFINE INDEX IF NOT EXISTS exam_question_subject ON exam_question FIELDS subject;
402
403 DEFINE TABLE IF NOT EXISTS question_image SCHEMAFULL;
404 DEFINE FIELD IF NOT EXISTS exam ON question_image TYPE record<exam>;
405 DEFINE FIELD IF NOT EXISTS question ON question_image TYPE record<exam_question>;
406 -- OVERWRITE: `slot` is now the choice's id, not its position.
407 DEFINE FIELD OVERWRITE slot ON question_image TYPE option<string>;
408 DEFINE FIELD IF NOT EXISTS file ON question_image TYPE string;
409 DEFINE FIELD IF NOT EXISTS content_type ON question_image TYPE string;
410 DEFINE FIELD IF NOT EXISTS size ON question_image TYPE int;
411 DEFINE INDEX IF NOT EXISTS question_image_exam ON question_image FIELDS exam;
412 DEFINE INDEX IF NOT EXISTS question_image_question ON question_image FIELDS question;
413
414 DEFINE TABLE IF NOT EXISTS bank_question SCHEMAFULL;
415 DEFINE FIELD IF NOT EXISTS owner ON bank_question TYPE record<user>;
416 -- OVERWRITE, not IF NOT EXISTS: the field started life as a required
417 -- `record<subject>` and has to actually change type on an existing database,
418 -- otherwise the subject-delete cascade (`SET subject = NONE`) is rejected.
419 DEFINE FIELD OVERWRITE subject ON bank_question TYPE option<record<subject>>;
420 DEFINE FIELD IF NOT EXISTS text ON bank_question TYPE string;
421 DEFINE FIELD IF NOT EXISTS kind ON bank_question TYPE string;
422 DEFINE FIELD IF NOT EXISTS points ON bank_question TYPE int;
423 -- OVERWRITE, not IF NOT EXISTS: these columns changed type when choices
424 -- gained stable ids (`array<string>`/`int` -> `array<object>`/`string`),
425 -- and IF NOT EXISTS would leave an existing database on the old types.
426 DEFINE FIELD OVERWRITE choices ON bank_question TYPE option<array<object>>;
427 -- SCHEMAFULL rejects any nested key it wasn't told about, so the choice
428 -- object's own fields are declared too (same shape as `settings.exam_kinds`).
429 DEFINE FIELD OVERWRITE choices.*.id ON bank_question TYPE string;
430 DEFINE FIELD OVERWRITE choices.*.text ON bank_question TYPE string;
431 DEFINE FIELD OVERWRITE correct ON bank_question TYPE option<string>;
432 DEFINE FIELD IF NOT EXISTS source_exam ON bank_question TYPE option<record<exam>>;
433 -- 'private' | 'school'. DEFAULT so a row that predates the field (or any
434 -- partial write) can never come out published: the answer key stays the
435 -- owner's until they publish it.
436 DEFINE FIELD IF NOT EXISTS visibility ON bank_question TYPE string DEFAULT 'private';
437 DEFINE FIELD IF NOT EXISTS created_at ON bank_question TYPE int READONLY;
438 DEFINE INDEX IF NOT EXISTS bank_question_owner ON bank_question FIELDS owner;
439 DEFINE INDEX IF NOT EXISTS bank_question_subject ON bank_question FIELDS subject;
440
441 DEFINE TABLE IF NOT EXISTS bank_question_image SCHEMAFULL;
442 DEFINE FIELD IF NOT EXISTS bank_question ON bank_question_image TYPE record<bank_question>;
443 -- OVERWRITE: `slot` is now the choice's id, not its position.
444 DEFINE FIELD OVERWRITE slot ON bank_question_image TYPE option<string>;
445 DEFINE FIELD IF NOT EXISTS file ON bank_question_image TYPE string;
446 DEFINE FIELD IF NOT EXISTS content_type ON bank_question_image TYPE string;
447 DEFINE FIELD IF NOT EXISTS size ON bank_question_image TYPE int;
448 DEFINE INDEX IF NOT EXISTS bank_question_image_question ON bank_question_image FIELDS bank_question;
449
450 DEFINE TABLE IF NOT EXISTS exam_answer SCHEMAFULL;
451 DEFINE FIELD IF NOT EXISTS exam ON exam_answer TYPE record<exam>;
452 DEFINE FIELD IF NOT EXISTS question ON exam_answer TYPE record<exam_question>;
453 DEFINE FIELD IF NOT EXISTS user ON exam_answer TYPE record<user>;
454 -- OVERWRITE: `selected` now names the picked option by id.
455 DEFINE FIELD OVERWRITE selected ON exam_answer TYPE option<string>;
456 DEFINE FIELD IF NOT EXISTS text ON exam_answer TYPE option<string>;
457 DEFINE FIELD IF NOT EXISTS updated_at ON exam_answer TYPE int;
458 -- `seq` numbers the sitting an answer belongs to (1, 2, …), mirroring
459 -- exam_attempt. It rides the record key too, so a retake's answer is a new
460 -- row, not an overwrite of the prior sitting.
461 DEFINE FIELD IF NOT EXISTS seq ON exam_answer TYPE int DEFAULT 1;
462 -- Retire the pre-history unique index: (question, user) is no longer unique
463 -- once a student re-sits; (question, user, seq) is.
464 REMOVE INDEX IF EXISTS exam_answer_question_user ON exam_answer;
465 DEFINE INDEX IF NOT EXISTS exam_answer_question_user_seq ON exam_answer FIELDS question, user, seq UNIQUE;
466 DEFINE INDEX IF NOT EXISTS exam_answer_exam_user ON exam_answer FIELDS exam, user;
467 DEFINE INDEX IF NOT EXISTS exam_answer_exam ON exam_answer FIELDS exam;
468
469 DEFINE TABLE IF NOT EXISTS answer_image SCHEMAFULL;
470 DEFINE FIELD IF NOT EXISTS exam ON answer_image TYPE record<exam>;
471 DEFINE FIELD IF NOT EXISTS question ON answer_image TYPE record<exam_question>;
472 DEFINE FIELD IF NOT EXISTS user ON answer_image TYPE record<user>;
473 DEFINE FIELD IF NOT EXISTS file ON answer_image TYPE string;
474 DEFINE FIELD IF NOT EXISTS content_type ON answer_image TYPE string;
475 DEFINE FIELD IF NOT EXISTS size ON answer_image TYPE int;
476 -- `seq` numbers the sitting this drawing belongs to; it rides the record
477 -- key so a retake's image never overwrites the prior sitting's.
478 DEFINE FIELD IF NOT EXISTS seq ON answer_image TYPE int DEFAULT 1;
479 DEFINE INDEX IF NOT EXISTS answer_image_exam ON answer_image FIELDS exam;
480 DEFINE INDEX IF NOT EXISTS answer_image_user ON answer_image FIELDS user;
481
482 DEFINE TABLE IF NOT EXISTS exam_result SCHEMAFULL;
483 DEFINE FIELD IF NOT EXISTS exam ON exam_result TYPE record<exam>;
484 DEFINE FIELD IF NOT EXISTS user ON exam_result TYPE record<user>;
485 DEFINE FIELD IF NOT EXISTS mark ON exam_result TYPE int;
486 DEFINE FIELD IF NOT EXISTS graded_by ON exam_result TYPE record<user>;
487 -- `seq` numbers the sitting a mark belongs to; a retake earns its own mark
488 -- row, and the latest seq is the student's standing.
489 DEFINE FIELD IF NOT EXISTS seq ON exam_result TYPE int DEFAULT 1;
490 REMOVE INDEX IF EXISTS exam_result_exam_user ON exam_result;
491 DEFINE INDEX IF NOT EXISTS exam_result_exam_user_seq ON exam_result FIELDS exam, user, seq UNIQUE;
492
493 DEFINE TABLE IF NOT EXISTS pool_question SCHEMAFULL;
494 DEFINE FIELD IF NOT EXISTS asker ON pool_question TYPE record<user>;
495 DEFINE FIELD IF NOT EXISTS title ON pool_question TYPE string;
496 DEFINE FIELD IF NOT EXISTS body ON pool_question TYPE string;
497 DEFINE FIELD IF NOT EXISTS status ON pool_question TYPE string DEFAULT 'pending';
498 DEFINE FIELD IF NOT EXISTS asked_at ON pool_question TYPE int;
499 DEFINE FIELD IF NOT EXISTS approved_by ON pool_question TYPE option<record<user>>;
500 DEFINE FIELD IF NOT EXISTS image_file ON pool_question TYPE option<string>;
501 DEFINE FIELD IF NOT EXISTS image_content_type ON pool_question TYPE option<string>;
502 DEFINE FIELD IF NOT EXISTS image_size ON pool_question TYPE option<int>;
503 DEFINE INDEX IF NOT EXISTS pool_question_status ON pool_question FIELDS status;
504 DEFINE INDEX IF NOT EXISTS pool_question_asker ON pool_question FIELDS asker;
505
506 DEFINE TABLE IF NOT EXISTS solution SCHEMAFULL;
507 DEFINE FIELD IF NOT EXISTS question ON solution TYPE record<pool_question>;
508 DEFINE FIELD IF NOT EXISTS author ON solution TYPE record<user>;
509 DEFINE FIELD IF NOT EXISTS body ON solution TYPE string;
510 DEFINE FIELD IF NOT EXISTS offered_at ON solution TYPE int;
511 DEFINE FIELD IF NOT EXISTS image_file ON solution TYPE option<string>;
512 DEFINE FIELD IF NOT EXISTS image_content_type ON solution TYPE option<string>;
513 DEFINE FIELD IF NOT EXISTS image_size ON solution TYPE option<int>;
514 DEFINE INDEX IF NOT EXISTS solution_question ON solution FIELDS question;
515
516 DEFINE TABLE IF NOT EXISTS settings SCHEMAFULL;
517 DEFINE FIELD IF NOT EXISTS exam_kinds ON settings TYPE array<object>;
518 DEFINE FIELD IF NOT EXISTS exam_kinds.*.name ON settings TYPE string;
519 DEFINE FIELD IF NOT EXISTS exam_kinds.*.weight ON settings TYPE int;
520 DEFINE FIELD IF NOT EXISTS attendance_statuses ON settings TYPE array<string>;
521 DEFINE FIELD IF NOT EXISTS grade_bands ON settings TYPE array<object>;
522 DEFINE FIELD IF NOT EXISTS grade_bands.*.min ON settings TYPE int;
523 DEFINE FIELD IF NOT EXISTS grade_bands.*.label ON settings TYPE string;
524 DEFINE FIELD IF NOT EXISTS max_file_bytes ON settings TYPE option<int>;
525 DEFINE FIELD IF NOT EXISTS chatbot_history_turns ON settings TYPE option<int>;
526 DEFINE FIELD IF NOT EXISTS max_chatbot_threads ON settings TYPE option<int>;
527 DEFINE FIELD IF NOT EXISTS max_chatbot_message_len ON settings TYPE option<int>;
528 -- Food program (2026-07-26). `meal_slots` mirrors the `exam_kinds` shape —
529 -- a named list a menu snapshots from — and `dietary_tags` mirrors
530 -- `attendance_statuses`. `meal_cancel_cutoff_minutes` is ONE knob for both
531 -- the booking and the cancel deadline; absent means no cutoff at all. All
532 -- three are `option<>`, exactly like `max_file_bytes`: NOT `DEFAULT []`.
533 -- `DEFAULT` fires on create only, and `PATCH /settings` writes the whole
534 -- row with `UPDATE ... CONTENT`, so a required-with-default field a writer
535 -- omits coerces to NONE and fails every settings write until the domain
536 -- struct carries it. `option<>` also means the existing singleton reads
537 -- fine, which is why the food program needs no BACKFILL anywhere.
538 DEFINE FIELD IF NOT EXISTS meal_slots ON settings TYPE option<array<object>>;
539 DEFINE FIELD IF NOT EXISTS meal_slots.*.name ON settings TYPE string;
540 -- Minutes past midnight UTC at which the slot is served (2026-07-26).
541 -- `option<int>` for the same reason the list itself is: slots written
542 -- before the field existed simply have no key, and read back as NONE ->
543 -- the booking cutoff falls back to midnight UTC, its old meaning. No
544 -- BACKFILL, and no DEFAULT — see the note above.
545 DEFINE FIELD IF NOT EXISTS meal_slots.*.serving_minute ON settings TYPE option<int>;
546 DEFINE FIELD IF NOT EXISTS dietary_tags ON settings TYPE option<array<string>>;
547 DEFINE FIELD IF NOT EXISTS meal_cancel_cutoff_minutes ON settings TYPE option<int>;
548
549 -- Homework (greenfield, 2026-07-22): a teacher assigns per course, students
550 -- submit files + optional text, a teacher grades a status + optional mark.
551 -- `course`/`created_by`/`created_at` are READONLY (a homework never moves
552 -- course, and stamps never rewrite); `subject` is NOT — it is re-taggable
553 -- via PATCH. `assigned` NONE/empty means the whole course. No BACKFILL: the
554 -- tables are new, so the whole migration stays additive and idempotent.
555 DEFINE TABLE IF NOT EXISTS homework SCHEMAFULL;
556 DEFINE FIELD IF NOT EXISTS course ON homework TYPE record<course> READONLY;
557 DEFINE FIELD IF NOT EXISTS subject ON homework TYPE record<subject>;
558 DEFINE FIELD IF NOT EXISTS title ON homework TYPE string;
559 DEFINE FIELD IF NOT EXISTS description ON homework TYPE option<string>;
560 DEFINE FIELD IF NOT EXISTS due_at ON homework TYPE int;
561 DEFINE FIELD IF NOT EXISTS assigned ON homework TYPE option<array<record<user>>>;
562 DEFINE FIELD IF NOT EXISTS assigned[*] ON homework TYPE record<user>;
563 DEFINE FIELD IF NOT EXISTS created_by ON homework TYPE record<user> READONLY;
564 DEFINE FIELD IF NOT EXISTS created_at ON homework TYPE int READONLY;
565 DEFINE INDEX IF NOT EXISTS homework_course ON homework FIELDS course;
566
567 DEFINE TABLE IF NOT EXISTS homework_submission SCHEMAFULL;
568 DEFINE FIELD IF NOT EXISTS homework ON homework_submission TYPE record<homework> READONLY;
569 DEFINE FIELD IF NOT EXISTS user ON homework_submission TYPE record<user> READONLY;
570 DEFINE FIELD IF NOT EXISTS text ON homework_submission TYPE option<string>;
571 DEFINE FIELD IF NOT EXISTS submitted_at ON homework_submission TYPE int READONLY;
572 DEFINE FIELD IF NOT EXISTS updated_at ON homework_submission TYPE int;
573 DEFINE FIELD IF NOT EXISTS file_count ON homework_submission TYPE option<int>;
574 -- The grade that froze this submission, absent while it is still open. The
575 -- freeze used to be a cross-table read (does a homework_result exist?)
576 -- followed by a write here, which no lock can hold across replicas; the
577 -- stamp turns every submission edit into a conditional single-record write
578 -- (`WHERE graded_by_result = NONE`), the one guard that survives. Set by
579 -- grading, cleared by un-grading, never by the student.
580 DEFINE FIELD IF NOT EXISTS graded_by_result ON homework_submission TYPE option<record<homework_result>>;
581 DEFINE INDEX IF NOT EXISTS homework_submission_homework ON homework_submission FIELDS homework;
582
583 DEFINE TABLE IF NOT EXISTS homework_file SCHEMAFULL;
584 DEFINE FIELD IF NOT EXISTS submission ON homework_file TYPE record<homework_submission> READONLY;
585 DEFINE FIELD IF NOT EXISTS name ON homework_file TYPE string;
586 DEFINE FIELD IF NOT EXISTS content_type ON homework_file TYPE string;
587 DEFINE FIELD IF NOT EXISTS size ON homework_file TYPE int;
588 DEFINE FIELD IF NOT EXISTS file ON homework_file TYPE string READONLY;
589 DEFINE FIELD IF NOT EXISTS created_at ON homework_file TYPE int READONLY;
590 DEFINE INDEX IF NOT EXISTS homework_file_submission ON homework_file FIELDS submission;
591
592 DEFINE TABLE IF NOT EXISTS homework_result SCHEMAFULL;
593 DEFINE FIELD IF NOT EXISTS homework ON homework_result TYPE record<homework> READONLY;
594 DEFINE FIELD IF NOT EXISTS user ON homework_result TYPE record<user> READONLY;
595 DEFINE FIELD IF NOT EXISTS status ON homework_result TYPE string;
596 DEFINE FIELD IF NOT EXISTS mark ON homework_result TYPE option<int>;
597 DEFINE FIELD IF NOT EXISTS graded_by ON homework_result TYPE record<user>;
598 DEFINE FIELD IF NOT EXISTS created_at ON homework_result TYPE int;
599 DEFINE INDEX IF NOT EXISTS homework_result_homework ON homework_result FIELDS homework;
600
601 -- Appointments (greenfield, 2026-07-23): a teacher publishes availability
602 -- slots, a student or parent books one. `series` groups the occurrences a
603 -- weekly repeat expanded into, so one cancel deletes one row and a series
604 -- delete finds the rest. A booking's live/dead state is the `status`
605 -- string; `occupied` is the cap-1 counter that says whether the slot is
606 -- taken (2026-07-27 — it used to be counted from the booking rows under a
607 -- process-local lock, which two replicas could each pass), decremented in
608 -- the same transaction as the reject/cancel that frees it.
609 -- The `proposed_*` fields carry a teacher's counter-proposal on the same
610 -- row until the requester accepts.
611 DEFINE TABLE IF NOT EXISTS appointment_slot SCHEMAFULL;
612 DEFINE FIELD IF NOT EXISTS teacher ON appointment_slot TYPE record<user>;
613 DEFINE FIELD IF NOT EXISTS starts_at ON appointment_slot TYPE int;
614 DEFINE FIELD IF NOT EXISTS ends_at ON appointment_slot TYPE int;
615 DEFINE FIELD IF NOT EXISTS occupied ON appointment_slot TYPE option<int>;
616 DEFINE FIELD IF NOT EXISTS note ON appointment_slot TYPE option<string>;
617 DEFINE FIELD IF NOT EXISTS series ON appointment_slot TYPE option<string>;
618 DEFINE FIELD IF NOT EXISTS created_at ON appointment_slot TYPE int;
619 DEFINE INDEX IF NOT EXISTS appointment_slot_teacher_starts ON appointment_slot FIELDS teacher, starts_at;
620 DEFINE INDEX IF NOT EXISTS appointment_slot_series ON appointment_slot FIELDS series;
621
622 DEFINE TABLE IF NOT EXISTS appointment SCHEMAFULL;
623 DEFINE FIELD IF NOT EXISTS slot ON appointment TYPE record<appointment_slot>;
624 DEFINE FIELD IF NOT EXISTS requester ON appointment TYPE record<user>;
625 DEFINE FIELD IF NOT EXISTS status ON appointment TYPE string DEFAULT 'pending';
626 DEFINE FIELD IF NOT EXISTS reason ON appointment TYPE string;
627 DEFINE FIELD IF NOT EXISTS proposed_starts_at ON appointment TYPE option<int>;
628 DEFINE FIELD IF NOT EXISTS proposed_ends_at ON appointment TYPE option<int>;
629 DEFINE FIELD IF NOT EXISTS proposed_by ON appointment TYPE option<record<user>>;
630 DEFINE FIELD IF NOT EXISTS decided_by ON appointment TYPE option<record<user>>;
631 DEFINE FIELD IF NOT EXISTS cancelled_by ON appointment TYPE option<record<user>>;
632 DEFINE FIELD IF NOT EXISTS cancel_reason ON appointment TYPE option<string>;
633 DEFINE FIELD IF NOT EXISTS reject_reason ON appointment TYPE option<string>;
634 DEFINE FIELD IF NOT EXISTS created_at ON appointment TYPE int;
635 DEFINE INDEX IF NOT EXISTS appointment_slot_ref ON appointment FIELDS slot;
636 DEFINE INDEX IF NOT EXISTS appointment_requester ON appointment FIELDS requester;
637 DEFINE INDEX IF NOT EXISTS appointment_status ON appointment FIELDS status;
638
639 -- Food program (greenfield, 2026-07-26): a published menu per day+slot,
640 -- dishes on it, a dietary profile per student, bookings against a menu's
641 -- capacity, who actually ate, and the money that moved. `date` is a
642 -- calendar day as `YYYY-MM-DD` text, not a timestamp: the unique index is
643 -- an equality test and a midnight-in-millis day is only unique for one
644 -- timezone. `slot` is snapshotted text, not a link, so retiring a slot in
645 -- settings never rewrites a past menu. Stamps stay `int` millis like the
646 -- rest of the schema. No BACKFILL: all six tables are new.
647 DEFINE TABLE IF NOT EXISTS menu SCHEMAFULL;
648 DEFINE FIELD IF NOT EXISTS date ON menu TYPE string READONLY;
649 DEFINE FIELD IF NOT EXISTS slot ON menu TYPE string READONLY;
650 DEFINE FIELD IF NOT EXISTS capacity ON menu TYPE option<int>;
651 -- `seats_booked` is the seat cap's counter (see `domain::cap`) and
652 -- `version` the menu's revision: a booking claims its seat only while the
653 -- menu still stands at the revision it read the price at, so a dish
654 -- re-priced mid-booking cannot be billed as the old price. Both absent
655 -- means zero, which is what `(x ?? 0)` reads on a row written before them.
656 DEFINE FIELD IF NOT EXISTS seats_booked ON menu TYPE option<int>;
657 DEFINE FIELD IF NOT EXISTS version ON menu TYPE option<int>;
658 DEFINE FIELD IF NOT EXISTS created_by ON menu TYPE record<user> READONLY;
659 DEFINE FIELD IF NOT EXISTS created_at ON menu TYPE int READONLY;
660 DEFINE INDEX IF NOT EXISTS menu_date_slot ON menu FIELDS date, slot UNIQUE;
661
662 DEFINE TABLE IF NOT EXISTS menu_dish SCHEMAFULL;
663 DEFINE FIELD IF NOT EXISTS menu ON menu_dish TYPE record<menu> READONLY;
664 DEFINE FIELD IF NOT EXISTS name ON menu_dish TYPE string;
665 DEFINE FIELD IF NOT EXISTS description ON menu_dish TYPE option<string>;
666 -- Money is minor units (kuruş) as an integer, everywhere. Never decimal.
667 DEFINE FIELD IF NOT EXISTS price_minor ON menu_dish TYPE int;
668 DEFINE FIELD IF NOT EXISTS tags ON menu_dish TYPE array<string> DEFAULT [];
669 DEFINE FIELD IF NOT EXISTS tags[*] ON menu_dish TYPE string;
670 DEFINE FIELD IF NOT EXISTS created_at ON menu_dish TYPE int READONLY;
671 DEFINE INDEX IF NOT EXISTS menu_dish_menu ON menu_dish FIELDS menu;
672
673 DEFINE TABLE IF NOT EXISTS dietary_profile SCHEMAFULL;
674 DEFINE FIELD IF NOT EXISTS student ON dietary_profile TYPE record<user> READONLY;
675 DEFINE FIELD IF NOT EXISTS tags ON dietary_profile TYPE array<string> DEFAULT [];
676 DEFINE FIELD IF NOT EXISTS tags[*] ON dietary_profile TYPE string;
677 DEFINE FIELD IF NOT EXISTS note ON dietary_profile TYPE option<string>;
678 DEFINE FIELD IF NOT EXISTS updated_by ON dietary_profile TYPE record<user>;
679 DEFINE FIELD IF NOT EXISTS updated_at ON dietary_profile TYPE int;
680 DEFINE INDEX IF NOT EXISTS dietary_profile_student ON dietary_profile FIELDS student UNIQUE;
681
682 -- A cancel flips `status` and stamps `cancelled_at`; the row stays so the
683 -- freed seat is still auditable against the ledger line it charged.
684 DEFINE TABLE IF NOT EXISTS meal_booking SCHEMAFULL;
685 DEFINE FIELD IF NOT EXISTS menu ON meal_booking TYPE record<menu> READONLY;
686 DEFINE FIELD IF NOT EXISTS student ON meal_booking TYPE record<user> READONLY;
687 DEFINE FIELD IF NOT EXISTS booked_by ON meal_booking TYPE record<user> READONLY;
688 DEFINE FIELD IF NOT EXISTS status ON meal_booking TYPE string DEFAULT 'booked';
689 -- How many times this seat has been taken, and what it cost when the
690 -- *current* attempt took it (NONE = the menu was free then). Together they
691 -- key the attempt's ledger lines, which is what makes billing idempotent
692 -- by identity rather than by scanning for an outstanding charge.
693 DEFINE FIELD IF NOT EXISTS attempt ON meal_booking TYPE int DEFAULT 1;
694 DEFINE FIELD IF NOT EXISTS price_minor ON meal_booking TYPE option<int>;
695 DEFINE FIELD IF NOT EXISTS cancelled_at ON meal_booking TYPE option<int>;
696 DEFINE FIELD IF NOT EXISTS created_at ON meal_booking TYPE int READONLY;
697 DEFINE INDEX IF NOT EXISTS meal_booking_menu ON meal_booking FIELDS menu;
698 DEFINE INDEX IF NOT EXISTS meal_booking_student ON meal_booking FIELDS student;
699
700 DEFINE TABLE IF NOT EXISTS meal_attendance SCHEMAFULL;
701 DEFINE FIELD IF NOT EXISTS menu ON meal_attendance TYPE record<menu> READONLY;
702 DEFINE FIELD IF NOT EXISTS student ON meal_attendance TYPE record<user> READONLY;
703 DEFINE FIELD IF NOT EXISTS status ON meal_attendance TYPE string;
704 DEFINE FIELD IF NOT EXISTS marked_by ON meal_attendance TYPE record<user>;
705 DEFINE FIELD IF NOT EXISTS marked_at ON meal_attendance TYPE int;
706 DEFINE INDEX IF NOT EXISTS meal_attendance_menu_student ON meal_attendance FIELDS menu, student UNIQUE;
707
708 -- APPEND-ONLY by design: a mistake is corrected with an opposing
709 -- `reversal` line, never by editing or deleting one. Hence every field is
710 -- READONLY. `source` is untyped on purpose — a charge points at the
711 -- booking that caused it, a reversal at the line it undoes.
712 DEFINE TABLE IF NOT EXISTS meal_ledger SCHEMAFULL;
713 DEFINE FIELD IF NOT EXISTS student ON meal_ledger TYPE record<user> READONLY;
714 DEFINE FIELD IF NOT EXISTS kind ON meal_ledger TYPE string READONLY;
715 DEFINE FIELD IF NOT EXISTS amount_minor ON meal_ledger TYPE int READONLY;
716 DEFINE FIELD IF NOT EXISTS source ON meal_ledger TYPE option<record> READONLY;
717 DEFINE FIELD IF NOT EXISTS method ON meal_ledger TYPE option<string> READONLY;
718 DEFINE FIELD IF NOT EXISTS note ON meal_ledger TYPE option<string> READONLY;
719 DEFINE FIELD IF NOT EXISTS recorded_by ON meal_ledger TYPE record<user> READONLY;
720 DEFINE FIELD IF NOT EXISTS created_at ON meal_ledger TYPE int READONLY;
721 DEFINE INDEX IF NOT EXISTS meal_ledger_student ON meal_ledger FIELDS student;
722
723 -- A school fee plan: a name and its installments, each an amount and the
724 -- day it falls due. The installments are embedded (SCHEMAFULL, so the
725 -- object's own fields are declared too, same shape as `settings.exam_kinds`)
726 -- because a charge line copies the amount it was assigned at — child rows
727 -- would buy nothing. Neither field inside the object is optional: a NONE
728 -- value would be dropped from the stored object entirely.
729 DEFINE TABLE IF NOT EXISTS fee_plan SCHEMAFULL;
730 DEFINE FIELD IF NOT EXISTS name ON fee_plan TYPE string;
731 DEFINE FIELD IF NOT EXISTS installments ON fee_plan TYPE array<object>;
732 DEFINE FIELD IF NOT EXISTS installments.*.amount_minor ON fee_plan TYPE int;
733 DEFINE FIELD IF NOT EXISTS installments.*.due_at ON fee_plan TYPE int;
734 DEFINE FIELD IF NOT EXISTS created_by ON fee_plan TYPE record<user> READONLY;
735 DEFINE FIELD IF NOT EXISTS created_at ON fee_plan TYPE int READONLY;
736 -- How many students are on the plan. The edit and delete guards read it,
737 -- an assignment's own transaction increments it, and nothing decrements it
738 -- (assignments are never removed). `option<int>` and no DEFAULT, like every
739 -- other counter: no Rust struct carries it, so the plan's create must not
740 -- be expected to state it.
741 DEFINE FIELD IF NOT EXISTS assignment_count ON fee_plan TYPE option<int>;
742
743 -- One plan on one student, keyed `<plan>_<student>`: assigning twice is the
744 -- same record id, so a replay writes nothing and an assignment cut short
745 -- half-way self-heals when it is repeated. Nothing here is ever edited.
746 DEFINE TABLE IF NOT EXISTS fee_plan_assignment SCHEMAFULL;
747 DEFINE FIELD IF NOT EXISTS plan ON fee_plan_assignment TYPE record<fee_plan> READONLY;
748 DEFINE FIELD IF NOT EXISTS student ON fee_plan_assignment TYPE record<user> READONLY;
749 DEFINE FIELD IF NOT EXISTS assigned_by ON fee_plan_assignment TYPE record<user> READONLY;
750 DEFINE FIELD IF NOT EXISTS created_at ON fee_plan_assignment TYPE int READONLY;
751 DEFINE INDEX IF NOT EXISTS fee_plan_assignment_plan ON fee_plan_assignment FIELDS plan;
752 DEFINE INDEX IF NOT EXISTS fee_plan_assignment_student ON fee_plan_assignment FIELDS student;
753
754 -- School fees, APPEND-ONLY by design exactly like `meal_ledger`: a mistake
755 -- is corrected with an opposing line, never by editing or deleting one,
756 -- hence every field is READONLY. `source` is untyped on purpose — a charge
757 -- points at the `fee_plan_assignment` that raised it, a credit at the charge
758 -- it pays, a refund at the credit it returns, a reversal at the line it
759 -- undoes. `due_at` is set on charges alone.
760 DEFINE TABLE IF NOT EXISTS payment_ledger SCHEMAFULL;
761 DEFINE FIELD IF NOT EXISTS student ON payment_ledger TYPE record<user> READONLY;
762 DEFINE FIELD IF NOT EXISTS kind ON payment_ledger TYPE string READONLY;
763 DEFINE FIELD IF NOT EXISTS amount_minor ON payment_ledger TYPE int READONLY;
764 DEFINE FIELD IF NOT EXISTS source ON payment_ledger TYPE option<record> READONLY;
765 DEFINE FIELD IF NOT EXISTS due_at ON payment_ledger TYPE option<int> READONLY;
766 DEFINE FIELD IF NOT EXISTS method ON payment_ledger TYPE option<string> READONLY;
767 DEFINE FIELD IF NOT EXISTS note ON payment_ledger TYPE option<string> READONLY;
768 DEFINE FIELD IF NOT EXISTS recorded_by ON payment_ledger TYPE record<user> READONLY;
769 DEFINE FIELD IF NOT EXISTS created_at ON payment_ledger TYPE int READONLY;
770 DEFINE INDEX IF NOT EXISTS payment_ledger_student ON payment_ledger FIELDS student;
771 DEFINE INDEX IF NOT EXISTS payment_ledger_source ON payment_ledger FIELDS source;
772
773 -- Reference counters, one row per *name* the settings offer, keyed by the
774 -- name itself (2026-07-27). They are how 'a kind nothing is graded under
775 -- may be removed' survives a second replica: the guard used to be a
776 -- count-then-write across two tables under a process-wide lock, and the
777 -- database serializes neither half of that. Both columns are `option<…>`
778 -- so an absent row reads as zero references, in service — the counter is
779 -- created by the first claim, never seeded per name.
780 DEFINE TABLE IF NOT EXISTS kind_ref SCHEMAFULL;
781 DEFINE FIELD IF NOT EXISTS count ON kind_ref TYPE option<int>;
782 DEFINE FIELD IF NOT EXISTS retired ON kind_ref TYPE option<bool>;
783
784 DEFINE TABLE IF NOT EXISTS slot_ref SCHEMAFULL;
785 DEFINE FIELD IF NOT EXISTS count ON slot_ref TYPE option<int>;
786 DEFINE FIELD IF NOT EXISTS retired ON slot_ref TYPE option<bool>;
787";
788
789/// Data backfills for rows written by older binaries. Runs *after* (and apart
790/// from) the DDL batch so every statement sees the freshly defined schema —
791/// see the `MIGRATION` doc for why sharing the batch corrupts the writes.
792/// Idempotent: each backfill's `WHERE` only matches unconverted rows.
793pub const BACKFILL: &str = "
794 UPDATE user SET role = 'student' WHERE role = NONE;
795
796 UPDATE course SET kind = 'course' WHERE kind = NONE;
797
798 -- Courses predate assignable teachers (2026-07-21): every existing course
799 -- was run by its creator alone, so it starts with nobody else assigned.
800 UPDATE course SET teachers = [] WHERE teachers = NONE;
801
802 -- Exams predate the draft flag (2026-07-19): everything already out there
803 -- was live for its course, so it stays published.
804 UPDATE exam SET draft = false WHERE draft = NONE;
805
806 -- Exams predate the review toggle (2026-07-24): default it closed (opt-in).
807 UPDATE exam SET allow_review = false WHERE allow_review = NONE;
808
809 UPDATE event SET audience = { kind: 'school' } WHERE audience = NONE OR audience = {};
810
811 -- Questions written before subjects existed (2026-07-17) are destroyed, not
812 -- backfilled: a subject is mandatory and there is nothing truthful to
813 -- assign. Their answers go first so no answer row outlives its question.
814 DELETE exam_answer WHERE question IN (SELECT VALUE id FROM exam_question WHERE subject = NONE);
815 DELETE exam_question WHERE subject = NONE;
816
817 -- The hand-picked `users` audience retired into `registration` (2026-07-16):
818 -- each listed user becomes a signup row credited to the event's creator, and
819 -- the event becomes an uncapped registration list. Runs once — converted
820 -- events no longer match the `kind = 'users'` filter. (`?? []`: an empty
821 -- statement-subquery evaluates to NONE, which FOR refuses to iterate.)
822 FOR $ev IN ((SELECT id, creator, audience FROM event WHERE audience.kind = 'users') ?? []) {
823 FOR $usr IN ($ev.audience.users ?? []) {
824 UPSERT type::record('registration', string::concat(record::id($ev.id), '_', record::id($usr))) CONTENT {
825 event: $ev.id,
826 user: $usr,
827 registered_by: $ev.creator,
828 };
829 };
830 UPDATE $ev.id SET audience = { kind: 'registration' };
831 };
832
833 -- Turns written before the clipped-answer flag existed (2026-07-23): the
834 -- clip was silent then, so nothing can be recovered — they read as whole,
835 -- which is what they were presented as all along.
836 UPDATE chatbot_message SET truncated = false WHERE truncated = NONE;
837
838 -- An assistant turn is answered by a task in this process, so a restart can
839 -- leave its row `pending` with nobody left to complete it. Only rows past
840 -- the stale horizon ($stale_ms, from `CHATBOT_PENDING_STALE_SECS`) are
841 -- certainly abandoned though: a young one may still be being answered on
842 -- the other side of the AI bridge, and a deploy must not shoot down a turn
843 -- dispatched seconds ago. Nothing is lost by waiting — a reader already
844 -- presents an over-age `pending` row as failed, and the next boot sweeps
845 -- for real whatever crossed the horizon in the meantime.
846 --
847 -- The claim half of this guard went with the claim queue (2026-07-30): it
848 -- only ever spared a row a *live peer* was answering, and there is no peer.
849 -- The rows selected are otherwise the same ones — an unclaimed row past the
850 -- horizon was always swept, and a claim of this process's own could not
851 -- outlive the process whose boot is running this.
852 UPDATE chatbot_message SET status = 'failed', error_code = 'interrupted',
853 completed_at = time::unix(time::now()) * 1000
854 WHERE status = 'pending' AND created_at < time::unix(time::now()) * 1000 - $stale_ms;
855
856 -- Promotion out of student now deletes the user's enrollments (2026-07-18);
857 -- this sweeps rows promoted before that fix. A deleted user reads as
858 -- `user.role = NONE`, which is also != 'student' — those rows go too.
859 DELETE enrollment WHERE user.role != 'student';
860
861 -- Choices gained stable ids (2026-07-24): `choices` held bare strings and
862 -- `correct`/`selected`/`slot` held the option's *position*. The DDL above
863 -- retypes those columns, which leaves every old-shaped row readable but
864 -- unwritable ('Expected `none | array<object>` but found `[..]`'), so this
865 -- conversion is repair, not cosmetics.
866 --
867 -- Ids are minted in array order, so the id at position i *is* the id for
868 -- old index i — that identity is what keeps a stored answer, and an option
869 -- picture, pointing at the option the student actually saw. Hence the
870 -- dependent rows are remapped inside the loop that mints `$new`, against
871 -- that same array: once the ids are stored the positions are still
872 -- recoverable, but nothing guarantees a later pass would look them up the
873 -- same way. `WHERE choices[0] != NONE AND type::is_string(choices[0])`
874 -- matches only unconverted rows, so a second boot re-mints nothing; an
875 -- empty or absent `choices` needs no conversion at all. A question-level
876 -- picture (`slot = NONE`) is not an index and is left alone.
877 --
878 -- Runs *before* every other backfill that writes these rows (the `seq`
879 -- stamps below): a write coerces the whole record, so touching a row for
880 -- any reason fails while its choices are still positional. For the same
881 -- reason the answer's remap stamps `seq` itself — the two legacy gaps sit
882 -- on the same row, and a write that fixes only one of them is rejected for
883 -- the other. `seq ?? 1` leaves an already-numbered sitting alone (DEFAULT
884 -- fills a CREATE, not an UPDATE of a row that predates the column).
885 FOR $q IN ((SELECT id, choices, correct FROM exam_question
886 WHERE choices[0] != NONE AND type::is_string(choices[0])) ?? []) {
887 LET $new = $q.choices.map(|$c| { id: rand::ulid(), text: $c });
888 UPDATE $q.id SET choices = $new,
889 correct = IF $q.correct = NONE { NONE } ELSE { $new[$q.correct].id };
890 FOR $img IN ((SELECT id, slot FROM question_image
891 WHERE question = $q.id AND type::is_int(slot)) ?? []) {
892 UPDATE $img.id SET slot = $new[$img.slot].id;
893 };
894 FOR $ans IN ((SELECT id, selected FROM exam_answer
895 WHERE question = $q.id AND type::is_int(selected)) ?? []) {
896 UPDATE $ans.id SET selected = $new[$ans.selected].id, seq = seq ?? 1;
897 };
898 };
899
900 FOR $q IN ((SELECT id, choices, correct FROM bank_question
901 WHERE choices[0] != NONE AND type::is_string(choices[0])) ?? []) {
902 LET $new = $q.choices.map(|$c| { id: rand::ulid(), text: $c });
903 UPDATE $q.id SET choices = $new,
904 correct = IF $q.correct = NONE { NONE } ELSE { $new[$q.correct].id };
905 FOR $img IN ((SELECT id, slot FROM bank_question_image
906 WHERE bank_question = $q.id AND type::is_int(slot)) ?? []) {
907 UPDATE $img.id SET slot = $new[$img.slot].id;
908 };
909 };
910
911 -- Per-attempt history (2026-07-24): answers, drawings, and marks written
912 -- before retakes stopped wiping belong to the student's first sitting.
913 -- They already use the bare (seq==1) record key, so only the denormalized
914 -- `seq` field needs stamping.
915 UPDATE exam_answer SET seq = 1 WHERE seq = NONE;
916 UPDATE answer_image SET seq = 1 WHERE seq = NONE;
917 UPDATE exam_result SET seq = 1 WHERE seq = NONE;
918
919 -- The homework freeze became cross-replica (2026-07-27): a grade that
920 -- predates the stamp column has to put it on the submission it already
921 -- froze, or that submission would read as open and be editable again.
922 -- Result and submission share the deterministic `{homework}_{user}` key, so
923 -- the owning row is addressed directly rather than searched for; an UPDATE
924 -- of a record that isn't there (graded absent work) is an empty no-op. The
925 -- `= NONE` guard keeps it one-time, for the same reason the counters below
926 -- are one-time — migrate() runs again on every boot against a volume the
927 -- live system has been writing to since.
928 FOR $r IN ((SELECT VALUE id FROM homework_result) ?? []) {
929 UPDATE type::record('homework_submission', record::id($r))
930 SET graded_by_result = $r WHERE graded_by_result = NONE;
931 };
932
933 -- Count caps became cross-replica (2026-07-27): the authority moved from a
934 -- process-wide mutex to a counter column on the parent row, so every parent
935 -- that predates the column is seeded from the children it actually has.
936 -- Runs LAST, after the sweeps above have deleted whatever they delete.
937 --
938 -- Deliberately one-time (`= NONE` guards every write): migrate() reruns on
939 -- every boot of an existing volume, and recounting a seeded counter would
940 -- overwrite what the live system has maintained since. An absent
941 -- counter reads as zero, so the group pass runs before the zero pass.
942 FOR $row IN ((SELECT course, count() AS n FROM enrollment GROUP BY course) ?? []) {
943 UPDATE $row.course SET enrollment_count = $row.n WHERE enrollment_count = NONE;
944 };
945 UPDATE course SET enrollment_count = 0 WHERE enrollment_count = NONE;
946
947 -- The one refcount among them: courses per term, not children per parent.
948 -- Same one-time `= NONE` guard, and `WHERE term != NONE` keeps the
949 -- unlinked courses out of the group (they would form a NONE bucket).
950 FOR $row IN ((SELECT term, count() AS n FROM course WHERE term != NONE GROUP BY term) ?? []) {
951 UPDATE $row.term SET course_count = $row.n WHERE course_count = NONE;
952 };
953 UPDATE term SET course_count = 0 WHERE course_count = NONE;
954
955 FOR $row IN ((SELECT event, count() AS n FROM registration GROUP BY event) ?? []) {
956 UPDATE $row.event SET registration_count = $row.n WHERE registration_count = NONE;
957 };
958 UPDATE event SET registration_count = 0 WHERE registration_count = NONE;
959
960 FOR $row IN ((SELECT note, count() AS n FROM note_file GROUP BY note) ?? []) {
961 UPDATE $row.note SET file_count = $row.n WHERE file_count = NONE;
962 };
963 UPDATE note SET file_count = 0 WHERE file_count = NONE;
964
965 FOR $row IN ((SELECT submission, count() AS n FROM homework_file GROUP BY submission) ?? []) {
966 UPDATE $row.submission SET file_count = $row.n WHERE file_count = NONE;
967 };
968 UPDATE homework_submission SET file_count = 0 WHERE file_count = NONE;
969
970 FOR $row IN ((SELECT user_id, count() AS n FROM chatbot_thread GROUP BY user_id) ?? []) {
971 UPDATE $row.user_id SET chatbot_thread_count = $row.n WHERE chatbot_thread_count = NONE;
972 };
973 UPDATE user SET chatbot_thread_count = 0 WHERE chatbot_thread_count = NONE;
974
975 -- The appointment slot's counter is the odd one out: it counts only the
976 -- bookings that are still *live*, because a rejected or cancelled one gave
977 -- the slot back long before this column existed.
978 FOR $row IN ((SELECT slot, count() AS n FROM appointment
979 WHERE status IN ['pending', 'approved'] GROUP BY slot) ?? []) {
980 UPDATE $row.slot SET occupied = $row.n WHERE occupied = NONE;
981 };
982 UPDATE appointment_slot SET occupied = 0 WHERE occupied = NONE;
983
984 -- A menu's seats, counted from the bookings still *held* — a cancelled one
985 -- gave its seat back before this column existed, exactly like the slot
986 -- above. `version` gets no pass at all: absent already reads as revision
987 -- zero everywhere it is compared, so writing it would be a no-op that
988 -- touches every menu row.
989 FOR $row IN ((SELECT menu, count() AS n FROM meal_booking
990 WHERE status = 'booked' GROUP BY menu) ?? []) {
991 UPDATE $row.menu SET seats_booked = $row.n WHERE seats_booked = NONE;
992 };
993 UPDATE menu SET seats_booked = 0 WHERE seats_booked = NONE;
994
995 -- A subject's two reference counters, seeded from what actually points at
996 -- it. This must run *after* the legacy sweep above destroys the questions
997 -- that predate subjects, or a subject would be seeded with rows that are
998 -- about to vanish and could then never be deleted. No zero pass, for the
999 -- same reason `version` gets none: absent already reads as zero in the
1000 -- delete's `(count ?? 0) = 0` guard, so writing it would touch every
1001 -- subject row to say what it already says.
1002 FOR $row IN ((SELECT subject, count() AS n FROM exam_question GROUP BY subject) ?? []) {
1003 UPDATE $row.subject SET exam_question_count = $row.n WHERE exam_question_count = NONE;
1004 };
1005
1006 FOR $row IN ((SELECT subject, count() AS n FROM homework GROUP BY subject) ?? []) {
1007 UPDATE $row.subject SET homework_count = $row.n WHERE homework_count = NONE;
1008 };
1009
1010 -- The settings guards became cross-replica the same way (2026-07-27): an
1011 -- exam kind counts the marks written under it, a meal slot the menus
1012 -- published for it, and a name is removable exactly while its counter reads
1013 -- zero. Rows written before the counters existed are counted once here.
1014 --
1015 -- Same `= NONE` guard and the same reason as the caps above: migrate()
1016 -- reruns on every boot of an existing volume, and recounting a seeded
1017 -- counter would overwrite what the live system has maintained since, handing
1018 -- back a reference that is still held. No zero pass either — an
1019 -- absent counter already reads as zero, and a name nobody ever used needs
1020 -- no row at all.
1021 --
1022 -- Marks predate the counter but so may their *kind*: an exam whose kind was
1023 -- removed from the list long ago is counted too, which only ever refuses a
1024 -- removal that already happened. `slot` is text on the menu, so its group
1025 -- needs no join; `kind` lives on the exam, one hop from the mark.
1026 FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result GROUP BY kind) ?? []) {
1027 UPSERT type::record('kind_ref', $row.kind) SET count = $row.n WHERE count = NONE;
1028 };
1029
1030 FOR $row IN ((SELECT slot, count() AS n FROM menu GROUP BY slot) ?? []) {
1031 UPSERT type::record('slot_ref', $row.slot) SET count = $row.n WHERE count = NONE;
1032 };
1033
1034 -- Same one-time seeding for the per-exam mark counter: an exam graded by an
1035 -- older binary must read as graded, or its kind could be changed under the
1036 -- marks it already carries.
1037 FOR $row IN ((SELECT exam, count() AS n FROM exam_result GROUP BY exam) ?? []) {
1038 UPDATE $row.exam SET result_count = $row.n WHERE result_count = NONE;
1039 };
1040
1041 -- The fee-plan guard became a refcount (2026-07-30): editing or deleting a
1042 -- plan is now refused by `(assignment_count ?? 0) = 0` on the plan row
1043 -- itself, instead of by a scan a concurrent assign could land behind.
1044 --
1045 -- This seeding is what keeps a *stale* volume safe: a plan written by an
1046 -- older binary carries no counter, an absent counter reads as zero, and a
1047 -- zero would make an already-assigned plan editable and deletable again —
1048 -- the exact thing the 409 exists to prevent. Boot seeds it from the
1049 -- assignment rows that actually exist, and `migrate` runs to completion
1050 -- before the router is bound, so no request is ever served against the
1051 -- unseeded shape. `= NONE` keeps it one-time, so a second boot recomputes
1052 -- nothing.
1053 --
1054 -- No zero pass, for the same reason the subject counters get none: a plan
1055 -- nobody is on has no assignment rows, and absent already reads as zero in
1056 -- the guard — writing it would touch every plan row to say what it says.
1057 FOR $row IN ((SELECT plan, count() AS n FROM fee_plan_assignment GROUP BY plan) ?? []) {
1058 UPDATE $row.plan SET assignment_count = $row.n WHERE assignment_count = NONE;
1059 };
1060";
1061
1062/// The migration batches, in the order a boot applies them — and the *only*
1063/// list of them. [`crate::database::migrate`] runs exactly these. They stay
1064/// three separate queries: statements in one batch see the schema as it stood
1065/// when the batch started (see `MIGRATION`).
1066pub const MIGRATION_BATCHES: [&str; 3] = [PRE_REPAIR, MIGRATION, BACKFILL];