forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBe2d0e43Ahmet Kaan Gümüş2 months ago397 commits

migration_sql.rs1518 lines, 97.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 display_name ON user TYPE option<string>;
62 DEFINE FIELD IF NOT EXISTS bio ON user TYPE option<string>;
63 DEFINE FIELD IF NOT EXISTS avatar_file ON user TYPE option<string>;
64 DEFINE FIELD IF NOT EXISTS avatar_content_type ON user TYPE option<string>;
65 DEFINE FIELD IF NOT EXISTS avatar_size ON user TYPE option<int>;
66 DEFINE FIELD IF NOT EXISTS chatbot_thread_count ON user TYPE option<int>;
67 DEFINE FIELD IF NOT EXISTS board_count ON user TYPE option<int>;
68 -- Lifetime badge counters (2026-08-04). Not caps and never released: each
69 -- counts something the student *did*, so a badge earned off one stands even
70 -- if the counter later drops. `option<int>` and absent reads as zero, so a
71 -- row written before them needs no repair to be *readable* — but it does
72 -- need one to be *right*, which is what the BACKFILL seeding is for.
73 DEFINE FIELD IF NOT EXISTS homework_submitted_total ON user TYPE option<int>;
74 DEFINE FIELD IF NOT EXISTS homework_on_time_total ON user TYPE option<int>;
75 DEFINE FIELD IF NOT EXISTS exam_sat_total ON user TYPE option<int>;
76 DEFINE FIELD IF NOT EXISTS pomodoro_finished_total ON user TYPE option<int>;
77 DEFINE FIELD IF NOT EXISTS pomodoro_focus_ms_total ON user TYPE option<int>;
78 -- Pass 3 (2026-08-04): the staff-side counters, two more student ones, and
79 -- the study streak. `study_streak_longest` is the badge counter; the other
80 -- two streak columns are bookkeeping the write site needs to compute it and
81 -- are read by nothing else. Definitions only — the seeding of the
82 -- row-derivable ones is a BACKFILL under its own migration mark, never in
83 -- this batch (same-batch DDL + backfill reads a stale schema).
84 DEFINE FIELD IF NOT EXISTS marks_given_total ON user TYPE option<int>;
85 DEFINE FIELD IF NOT EXISTS lessons_held_total ON user TYPE option<int>;
86 DEFINE FIELD IF NOT EXISTS pool_approved_total ON user TYPE option<int>;
87 DEFINE FIELD IF NOT EXISTS pool_published_total ON user TYPE option<int>;
88 DEFINE FIELD IF NOT EXISTS lessons_attended_total ON user TYPE option<int>;
89 DEFINE FIELD IF NOT EXISTS high_mark_total ON user TYPE option<int>;
90 DEFINE FIELD IF NOT EXISTS study_streak_longest ON user TYPE option<int>;
91 DEFINE FIELD IF NOT EXISTS study_streak_current ON user TYPE option<int>;
92 DEFINE FIELD IF NOT EXISTS study_streak_last_day ON user TYPE option<int>;
93 -- The counted-stint quota (2026-08-05): which UTC day the student last had
94 -- a pomodoro stint counted on, and how many counted that day. Bookkeeping
95 -- for the daily cap, read by nothing else; absent reads as no day yet,
96 -- which is what makes the first finish after this deploy open a fresh
97 -- bucket with no backfill.
98 DEFINE FIELD IF NOT EXISTS pomodoro_counted_day ON user TYPE option<int>;
99 DEFINE FIELD IF NOT EXISTS pomodoro_counted_today ON user TYPE option<int>;
100 DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE;
101
102 DEFINE TABLE IF NOT EXISTS session SCHEMAFULL;
103 DEFINE FIELD IF NOT EXISTS user ON session TYPE record<user>;
104 DEFINE FIELD IF NOT EXISTS token ON session TYPE string;
105 DEFINE FIELD IF NOT EXISTS expires_at ON session TYPE int;
106 DEFINE INDEX IF NOT EXISTS session_token ON session FIELDS token UNIQUE;
107 DEFINE INDEX IF NOT EXISTS session_expires ON session FIELDS expires_at;
108
109 DEFINE TABLE IF NOT EXISTS note SCHEMAFULL;
110 DEFINE FIELD IF NOT EXISTS user ON note TYPE record<user>;
111 DEFINE FIELD IF NOT EXISTS title ON note TYPE string;
112 DEFINE FIELD IF NOT EXISTS content ON note TYPE string;
113 DEFINE FIELD IF NOT EXISTS file_count ON note TYPE option<int>;
114 DEFINE INDEX IF NOT EXISTS note_user ON note FIELDS user;
115
116 DEFINE TABLE IF NOT EXISTS message SCHEMAFULL;
117 DEFINE FIELD IF NOT EXISTS sender ON message TYPE record<user>;
118 DEFINE FIELD IF NOT EXISTS recipient ON message TYPE record<user>;
119 DEFINE FIELD IF NOT EXISTS subject ON message TYPE string;
120 DEFINE FIELD IF NOT EXISTS body ON message TYPE string;
121 DEFINE FIELD IF NOT EXISTS label ON message TYPE option<string>;
122 DEFINE FIELD IF NOT EXISTS sent_at ON message TYPE int;
123 DEFINE FIELD IF NOT EXISTS read ON message TYPE bool DEFAULT false;
124 DEFINE FIELD IF NOT EXISTS sender_folder ON message TYPE string DEFAULT 'sent';
125 DEFINE FIELD IF NOT EXISTS recipient_folder ON message TYPE string DEFAULT 'inbox';
126 -- Where each side's copy sat before it was filed into archive/trash, so a
127 -- restore lands where it came from. NONE while the copy is in its home
128 -- folder — and on rows filed before this field existed (2026-07-23), which
129 -- restore to the home folder just as they always did.
130 DEFINE FIELD IF NOT EXISTS sender_origin ON message TYPE option<string>;
131 DEFINE FIELD IF NOT EXISTS recipient_origin ON message TYPE option<string>;
132 DEFINE INDEX IF NOT EXISTS message_sender ON message FIELDS sender;
133 DEFINE INDEX IF NOT EXISTS message_recipient ON message FIELDS recipient;
134
135 -- Collaborative whiteboard (2026-07-31): one `board` is a room, one
136 -- `board_stroke` is one append-only mark. A clear NEVER deletes — it bumps
137 -- `epoch`, so the canvas empties while the whole history stays replayable.
138 -- `locked` is a plain bool, not an option: the open-board guard asks for
139 -- `locked = false`, which a NONE would never match. `locked_by`/`locked_at`/
140 -- `closed_at` are three top-level option columns rather than one nested
141 -- object, because SurrealDB 3 drops an object key valued NONE.
142 DEFINE TABLE IF NOT EXISTS board SCHEMAFULL;
143 DEFINE FIELD IF NOT EXISTS creator ON board TYPE record<user>;
144 DEFINE FIELD IF NOT EXISTS title ON board TYPE string;
145 DEFINE FIELD IF NOT EXISTS participants ON board TYPE array<record<user>>;
146 DEFINE FIELD IF NOT EXISTS locked ON board TYPE bool DEFAULT false;
147 DEFINE FIELD IF NOT EXISTS locked_by ON board TYPE option<record<user>>;
148 DEFINE FIELD IF NOT EXISTS locked_at ON board TYPE option<int>;
149 DEFINE FIELD IF NOT EXISTS epoch ON board TYPE int DEFAULT 0;
150 -- Resets to 0 on every clear (recoverable); never resets (stamps closed_at).
151 DEFINE FIELD IF NOT EXISTS epoch_stroke_count ON board TYPE option<int>;
152 DEFINE FIELD IF NOT EXISTS total_stroke_count ON board TYPE option<int>;
153 -- Stamped once, when the lifetime cap is hit: permanently read-only.
154 DEFINE FIELD IF NOT EXISTS closed_at ON board TYPE option<int>;
155 DEFINE FIELD IF NOT EXISTS created_at ON board TYPE int;
156 DEFINE INDEX IF NOT EXISTS board_creator ON board FIELDS creator;
157 -- Listing a user's boards asks `creator = $u OR participants CONTAINS $u`;
158 -- without this the CONTAINS half is a full scan. SurrealDB indexes an
159 -- array field per element, so it covers the membership test directly.
160 DEFINE INDEX IF NOT EXISTS board_participants ON board FIELDS participants;
161
162 DEFINE TABLE IF NOT EXISTS board_stroke SCHEMAFULL;
163 DEFINE FIELD IF NOT EXISTS board ON board_stroke TYPE record<board>;
164 DEFINE FIELD IF NOT EXISTS author ON board_stroke TYPE record<user>;
165 -- 'stroke' or 'clear'; `payload` is the opaque blob, absent on a clear
166 -- marker, and `count` is populated only on a clear marker — the final
167 -- stroke count of the epoch that marker closed.
168 DEFINE FIELD IF NOT EXISTS kind ON board_stroke TYPE string;
169 DEFINE FIELD IF NOT EXISTS payload ON board_stroke TYPE option<string>;
170 DEFINE FIELD IF NOT EXISTS count ON board_stroke TYPE option<int>;
171 DEFINE FIELD IF NOT EXISTS epoch ON board_stroke TYPE int;
172 DEFINE FIELD IF NOT EXISTS created_at ON board_stroke TYPE int;
173 -- Keeps a socket's join-replay scoped to the current epoch instead of
174 -- scanning the board's whole history.
175 DEFINE INDEX IF NOT EXISTS board_stroke_board_epoch ON board_stroke FIELDS board, epoch;
176 -- The clear markers ARE the epoch index, so listing them is a hot read.
177 DEFINE INDEX IF NOT EXISTS board_stroke_board_kind ON board_stroke FIELDS board, kind;
178
179 DEFINE TABLE IF NOT EXISTS note_file SCHEMAFULL;
180 DEFINE FIELD IF NOT EXISTS note ON note_file TYPE record<note>;
181 DEFINE FIELD IF NOT EXISTS name ON note_file TYPE string;
182 DEFINE FIELD IF NOT EXISTS content_type ON note_file TYPE string;
183 DEFINE FIELD IF NOT EXISTS size ON note_file TYPE int;
184 DEFINE INDEX IF NOT EXISTS note_file_note ON note_file FIELDS note;
185
186 DEFINE TABLE IF NOT EXISTS course_note SCHEMAFULL;
187 DEFINE FIELD IF NOT EXISTS course ON course_note TYPE record<course>;
188 DEFINE FIELD IF NOT EXISTS author ON course_note TYPE record<user>;
189 DEFINE FIELD IF NOT EXISTS title ON course_note TYPE string;
190 DEFINE FIELD IF NOT EXISTS content ON course_note TYPE string;
191 DEFINE FIELD IF NOT EXISTS file_count ON course_note TYPE option<int>;
192 DEFINE INDEX IF NOT EXISTS course_note_course ON course_note FIELDS course;
193
194 DEFINE TABLE IF NOT EXISTS course_note_file SCHEMAFULL;
195 DEFINE FIELD IF NOT EXISTS course_note ON course_note_file TYPE record<course_note>;
196 DEFINE FIELD IF NOT EXISTS name ON course_note_file TYPE string;
197 DEFINE FIELD IF NOT EXISTS content_type ON course_note_file TYPE string;
198 DEFINE FIELD IF NOT EXISTS size ON course_note_file TYPE int;
199 DEFINE INDEX IF NOT EXISTS course_note_file_note ON course_note_file FIELDS course_note;
200
201 -- What an AI service produced for a course note (rag.index, 2026-09-05).
202 -- Derived and disposable: the note is the source of truth, so the rows
203 -- cascade from the note AND from any attachment they were built from.
204 -- `payload` is FLEXIBLE because its shape belongs to the service, not to
205 -- this schema — SCHEMAFULL would otherwise strip every key inside it.
206 DEFINE TABLE IF NOT EXISTS rag_output SCHEMAFULL;
207 DEFINE FIELD IF NOT EXISTS course_note ON rag_output TYPE record<course_note>;
208 DEFINE FIELD IF NOT EXISTS course ON rag_output TYPE record<course>;
209 DEFINE FIELD IF NOT EXISTS sources ON rag_output TYPE array<record<course_note_file>>;
210 DEFINE FIELD IF NOT EXISTS payload ON rag_output TYPE object FLEXIBLE;
211 DEFINE FIELD IF NOT EXISTS generated_at ON rag_output TYPE int;
212 DEFINE INDEX IF NOT EXISTS rag_output_note ON rag_output FIELDS course_note;
213 -- Retire the course index: nothing queries rag_output by course.
214 REMOVE INDEX IF EXISTS rag_output_course ON rag_output;
215 -- Indexed per element, so the source cascade's `sources CONTAINS $file`
216 -- is a lookup rather than a table scan.
217 DEFINE INDEX IF NOT EXISTS rag_output_source ON rag_output FIELDS sources;
218
219 -- Chatbot relay (2026-07-23): a `thread` groups the turns, one
220 -- `chatbot_message` is one turn. `user_id` rides on the message too so an
221 -- ownership check needs no join. An assistant turn is born `pending` and
222 -- is completed (or failed) by the task holding the AI-bridge stream —
223 -- hence the BACKFILL sweep, since that task dies with the process.
224 DEFINE TABLE IF NOT EXISTS chatbot_thread SCHEMAFULL;
225 DEFINE FIELD IF NOT EXISTS user_id ON chatbot_thread TYPE record<user> READONLY;
226 DEFINE FIELD IF NOT EXISTS title ON chatbot_thread TYPE option<string>;
227 DEFINE FIELD IF NOT EXISTS created_at ON chatbot_thread TYPE int READONLY;
228 DEFINE FIELD IF NOT EXISTS updated_at ON chatbot_thread TYPE int;
229 DEFINE INDEX IF NOT EXISTS chatbot_thread_user_updated ON chatbot_thread FIELDS user_id, updated_at;
230
231 DEFINE TABLE IF NOT EXISTS chatbot_message SCHEMAFULL;
232 DEFINE FIELD IF NOT EXISTS thread_id ON chatbot_message TYPE record<chatbot_thread> READONLY;
233 DEFINE FIELD IF NOT EXISTS user_id ON chatbot_message TYPE record<user> READONLY;
234 DEFINE FIELD IF NOT EXISTS role ON chatbot_message TYPE string READONLY;
235 DEFINE FIELD IF NOT EXISTS content ON chatbot_message TYPE string;
236 DEFINE FIELD IF NOT EXISTS status ON chatbot_message TYPE string;
237 DEFINE FIELD IF NOT EXISTS truncated ON chatbot_message TYPE bool DEFAULT false;
238 DEFINE FIELD IF NOT EXISTS error_code ON chatbot_message TYPE option<string>;
239 DEFINE FIELD IF NOT EXISTS created_at ON chatbot_message TYPE int READONLY;
240 DEFINE FIELD IF NOT EXISTS completed_at ON chatbot_message TYPE option<int>;
241 -- The chat claim queue is gone (2026-07-30): one process answers its own
242 -- turns, so nothing claims them. PRE_REPAIR clears the values first —
243 -- SCHEMAFULL rejects every write to a row still storing a column that no
244 -- longer exists.
245 REMOVE FIELD IF EXISTS claimed_by ON TABLE chatbot_message;
246 REMOVE FIELD IF EXISTS claimed_at ON TABLE chatbot_message;
247 DEFINE INDEX IF NOT EXISTS chatbot_message_thread_created ON chatbot_message FIELDS thread_id, created_at;
248 DEFINE INDEX IF NOT EXISTS chatbot_message_user ON chatbot_message FIELDS user_id;
249 -- The boot sweep asks for pending rows by age.
250 DEFINE INDEX IF NOT EXISTS chatbot_message_status_created ON chatbot_message FIELDS status, created_at;
251
252 -- The AI worker presence table is gone (2026-07-30): one process holds
253 -- every worker socket, so its in-process registry is the whole truth and
254 -- nothing needed publishing.
255 REMOVE TABLE IF EXISTS ai_worker;
256
257 -- The elected-boot lease is gone with it (2026-07-30): one process migrates,
258 -- so nothing takes the lock. SCHEMALESS and read by nobody, so unlike the
259 -- claim columns it needs no PRE_REPAIR — the table just goes.
260 REMOVE TABLE IF EXISTS migration_lock;
261
262 -- How much of a rate-limit budget one client has spent in one wall window
263 -- (2026-07-27). One row per tier+client+window, id-keyed so a restart of
264 -- the process lands back on the same record; `hits` is the durable total
265 -- the in-memory bucket folds its local admits into (see
266 -- `crate::rate_limit`), which is what carries a window across a restart.
267 -- Rows are swept by the same task once their window is past.
268 DEFINE TABLE IF NOT EXISTS rate_limit SCHEMAFULL;
269 DEFINE FIELD IF NOT EXISTS hits ON rate_limit TYPE int DEFAULT 0;
270 DEFINE FIELD IF NOT EXISTS window_start ON rate_limit TYPE int;
271
272 DEFINE TABLE IF NOT EXISTS event SCHEMAFULL;
273 DEFINE FIELD IF NOT EXISTS creator ON event TYPE record<user>;
274 DEFINE FIELD IF NOT EXISTS title ON event TYPE string;
275 DEFINE FIELD IF NOT EXISTS description ON event TYPE string;
276 DEFINE FIELD IF NOT EXISTS audience ON event TYPE object;
277 DEFINE FIELD IF NOT EXISTS audience.kind ON event TYPE string;
278 DEFINE FIELD IF NOT EXISTS audience.role ON event TYPE option<string>;
279 DEFINE FIELD IF NOT EXISTS audience.course ON event TYPE option<record<course>>;
280 DEFINE FIELD IF NOT EXISTS audience.class ON event TYPE option<record<class_group>>;
281 DEFINE FIELD IF NOT EXISTS audience.capacity ON event TYPE option<int>;
282 -- Seats taken on the signup list, the stored capacity guard that closes
283 -- write-skew between concurrent request tasks (see `crate::db::cap`).
284 -- Absent reads as zero, so no Rust struct needs it.
285 DEFINE FIELD IF NOT EXISTS registration_count ON event TYPE option<int>;
286 REMOVE FIELD IF EXISTS audience.users ON TABLE event;
287 DEFINE FIELD IF NOT EXISTS starts_at ON event TYPE option<int>;
288 DEFINE FIELD IF NOT EXISTS ends_at ON event TYPE option<int>;
289
290 DEFINE TABLE IF NOT EXISTS attendance SCHEMAFULL;
291 DEFINE FIELD IF NOT EXISTS event ON attendance TYPE record<event>;
292 DEFINE FIELD IF NOT EXISTS user ON attendance TYPE record<user>;
293 DEFINE FIELD IF NOT EXISTS status ON attendance TYPE string;
294 DEFINE FIELD IF NOT EXISTS marked_by ON attendance TYPE record<user>;
295 DEFINE INDEX IF NOT EXISTS attendance_event_user ON attendance FIELDS event, user UNIQUE;
296 DEFINE INDEX IF NOT EXISTS attendance_user ON attendance FIELDS user;
297
298 DEFINE TABLE IF NOT EXISTS registration SCHEMAFULL;
299 DEFINE FIELD IF NOT EXISTS event ON registration TYPE record<event>;
300 DEFINE FIELD IF NOT EXISTS user ON registration TYPE record<user>;
301 DEFINE FIELD IF NOT EXISTS registered_by ON registration TYPE record<user>;
302 DEFINE INDEX IF NOT EXISTS registration_event_user ON registration FIELDS event, user UNIQUE;
303 DEFINE INDEX IF NOT EXISTS registration_event ON registration FIELDS event;
304
305 DEFINE TABLE IF NOT EXISTS term SCHEMAFULL;
306 DEFINE FIELD IF NOT EXISTS name ON term TYPE string;
307 DEFINE FIELD IF NOT EXISTS starts_at ON term TYPE int;
308 DEFINE FIELD IF NOT EXISTS ends_at ON term TYPE int;
309 -- When the term was archived; absent = open. `option<int>` and no
310 -- BACKFILL: every term that exists predates archiving and is open, which
311 -- is exactly what an absent stamp already means.
312 DEFINE FIELD IF NOT EXISTS archived_at ON term TYPE option<int>;
313 -- Courses still linking this term, the stored delete guard that closes
314 -- write-skew between concurrent request tasks (see `crate::db::cap`).
315 -- Absent reads as zero, so no Rust struct needs it.
316 DEFINE FIELD IF NOT EXISTS course_count ON term TYPE option<int>;
317 -- Classes linking this term, the other half of the same guard. A column of
318 -- its own because `course_count` is seeded from the course rows alone.
319 DEFINE FIELD IF NOT EXISTS class_count ON term TYPE option<int>;
320
321 DEFINE TABLE IF NOT EXISTS course SCHEMAFULL;
322 DEFINE FIELD IF NOT EXISTS creator ON course TYPE record<user>;
323 DEFINE FIELD IF NOT EXISTS teachers ON course TYPE array<record<user>> DEFAULT [];
324 DEFINE FIELD IF NOT EXISTS teachers[*] ON course TYPE record<user>;
325 DEFINE FIELD IF NOT EXISTS title ON course TYPE string;
326 DEFINE FIELD IF NOT EXISTS description ON course TYPE string;
327 DEFINE FIELD IF NOT EXISTS kind ON course TYPE string DEFAULT 'course';
328 DEFINE FIELD IF NOT EXISTS term ON course TYPE option<record<term>>;
329 DEFINE FIELD IF NOT EXISTS capacity ON course TYPE option<int>;
330 DEFINE FIELD IF NOT EXISTS enrollment_count ON course TYPE option<int>;
331
332 DEFINE TABLE IF NOT EXISTS subject SCHEMAFULL;
333 DEFINE FIELD IF NOT EXISTS course ON subject TYPE record<course>;
334 DEFINE FIELD IF NOT EXISTS name ON subject TYPE string;
335 DEFINE FIELD IF NOT EXISTS description ON subject TYPE string;
336 -- How many exam questions and how many homework still point here. The
337 -- delete is conditioned on both reading zero, which is what makes the
338 -- guard hold against a question created by a concurrent request task.
339 DEFINE FIELD IF NOT EXISTS exam_question_count ON subject TYPE option<int>;
340 DEFINE FIELD IF NOT EXISTS homework_count ON subject TYPE option<int>;
341 DEFINE INDEX IF NOT EXISTS subject_course ON subject FIELDS course;
342
343 -- A class section (şube) is a named set of students that bulk-manages real
344 -- `enrollment` rows: `class_member` is one student in it, `class_course` one
345 -- course it is attached to. Both counters gate the class delete.
346 DEFINE TABLE IF NOT EXISTS class_group SCHEMAFULL;
347 DEFINE FIELD IF NOT EXISTS name ON class_group TYPE string;
348 DEFINE FIELD IF NOT EXISTS grade ON class_group TYPE option<string>;
349 DEFINE FIELD IF NOT EXISTS term ON class_group TYPE option<record<term>>;
350 DEFINE FIELD IF NOT EXISTS creator ON class_group TYPE record<user>;
351 DEFINE FIELD IF NOT EXISTS teacher ON class_group TYPE option<record<user>>;
352 DEFINE FIELD IF NOT EXISTS class_member_count ON class_group TYPE option<int>;
353 DEFINE FIELD IF NOT EXISTS class_course_count ON class_group TYPE option<int>;
354 -- Every class at one grade is what a blueprint pumps, so the grade label is
355 -- that read's whole `WHERE`.
356 DEFINE INDEX IF NOT EXISTS class_group_grade ON class_group FIELDS grade;
357
358 -- A grade's course template: the courses every class section at that grade
359 -- carries. The grade label *is* the record key, so a second blueprint for
360 -- one grade cannot exist and no find-then-insert has to race for it (the shape
361 -- `menu` uses for its date+slot). It holds no term — the class names its
362 -- own — and `courses` carries no DEFAULT: a defaulted array on a SCHEMAFULL
363 -- row is what broke every settings PATCH.
364 DEFINE TABLE IF NOT EXISTS class_blueprint SCHEMAFULL;
365 DEFINE FIELD IF NOT EXISTS grade ON class_blueprint TYPE string;
366 DEFINE FIELD IF NOT EXISTS courses ON class_blueprint TYPE array<record<course>>;
367 DEFINE FIELD IF NOT EXISTS creator ON class_blueprint TYPE record<user>;
368
369 DEFINE TABLE IF NOT EXISTS class_member SCHEMAFULL;
370 DEFINE FIELD IF NOT EXISTS class ON class_member TYPE record<class_group>;
371 DEFINE FIELD IF NOT EXISTS user ON class_member TYPE record<user>;
372 DEFINE FIELD IF NOT EXISTS added_by ON class_member TYPE record<user>;
373 -- When the student was put in. Both link tables key on the *pair*
374 -- (`<class>_<user>`), so ordering a roster by its record id sorts it by the
375 -- member's account ULID — an arbitrary order the routes nevertheless
376 -- documented as newest-first. `option<int>` and no BACKFILL: rows written
377 -- before this column are of unknown age, and an absent stamp is NONE, which
378 -- SurrealDB sorts *last* under DESC — already the honest place for them, so
379 -- there is no number to invent.
380 DEFINE FIELD IF NOT EXISTS added_at ON class_member TYPE option<int>;
381 DEFINE INDEX IF NOT EXISTS class_member_class_user ON class_member FIELDS class, user UNIQUE;
382 DEFINE INDEX IF NOT EXISTS class_member_class ON class_member FIELDS class;
383 DEFINE INDEX IF NOT EXISTS class_member_user ON class_member FIELDS user;
384
385 DEFINE TABLE IF NOT EXISTS class_course SCHEMAFULL;
386 DEFINE FIELD IF NOT EXISTS class ON class_course TYPE record<class_group>;
387 DEFINE FIELD IF NOT EXISTS course ON class_course TYPE record<course>;
388 DEFINE FIELD IF NOT EXISTS attached_by ON class_course TYPE record<user>;
389 -- The mirror of `class_member.added_at`, for the same reason: without it
390 -- the course list is ordered by the *course's* ULID.
391 DEFINE FIELD IF NOT EXISTS attached_at ON class_course TYPE option<int>;
392 -- The blueprint that attached this course, absent when a human attached it
393 -- by hand — the same shape, and the same meaning, as `enrollment.source`
394 -- one table down. The line is not optional bookkeeping: `class_course` is
395 -- SCHEMAFULL with a definition per key, so an undefined column is silently
396 -- stripped on write and a blueprint could never take back what it placed.
397 -- Absence *is* the meaning, so there is nothing to backfill: a row written
398 -- before this column reads back as hand-attached, and `source = $blueprint`
399 -- is false for an absent key, which is what keeps a hand-attached course
400 -- unreachable by every blueprint sweep.
401 DEFINE FIELD IF NOT EXISTS source ON class_course TYPE option<record<class_blueprint>>;
402 DEFINE INDEX IF NOT EXISTS class_course_class_course ON class_course FIELDS class, course UNIQUE;
403 DEFINE INDEX IF NOT EXISTS class_course_class ON class_course FIELDS class;
404 DEFINE INDEX IF NOT EXISTS class_course_course ON class_course FIELDS course;
405
406 DEFINE TABLE IF NOT EXISTS enrollment SCHEMAFULL;
407 DEFINE FIELD IF NOT EXISTS course ON enrollment TYPE record<course>;
408 DEFINE FIELD IF NOT EXISTS user ON enrollment TYPE record<user>;
409 DEFINE FIELD IF NOT EXISTS enrolled_by ON enrollment TYPE record<user>;
410 -- The class that pumped this row, absent when a human placed the student
411 -- directly. Absence is the meaning, so there is nothing to backfill: a class
412 -- sweep may only take back the rows it wrote.
413 DEFINE FIELD IF NOT EXISTS source ON enrollment TYPE option<record<class_group>>;
414 DEFINE INDEX IF NOT EXISTS enrollment_course_user ON enrollment FIELDS course, user UNIQUE;
415 DEFINE INDEX IF NOT EXISTS enrollment_user ON enrollment FIELDS user;
416
417 DEFINE TABLE IF NOT EXISTS parent_link SCHEMAFULL;
418 DEFINE FIELD IF NOT EXISTS parent ON parent_link TYPE record<user>;
419 DEFINE FIELD IF NOT EXISTS student ON parent_link TYPE record<user>;
420 DEFINE FIELD IF NOT EXISTS linked_by ON parent_link TYPE record<user>;
421 DEFINE INDEX IF NOT EXISTS parent_link_parent_student ON parent_link FIELDS parent, student UNIQUE;
422 DEFINE INDEX IF NOT EXISTS parent_link_parent ON parent_link FIELDS parent;
423 DEFINE INDEX IF NOT EXISTS parent_link_student ON parent_link FIELDS student;
424
425 DEFINE TABLE IF NOT EXISTS course_session SCHEMAFULL;
426 DEFINE FIELD IF NOT EXISTS course ON course_session TYPE record<course>;
427 DEFINE FIELD IF NOT EXISTS teacher ON course_session TYPE record<user>;
428 DEFINE FIELD IF NOT EXISTS topic ON course_session TYPE string;
429 DEFINE FIELD IF NOT EXISTS starts_at ON course_session TYPE int;
430 DEFINE FIELD IF NOT EXISTS ends_at ON course_session TYPE option<int>;
431 -- The once-per-session guard behind `lessons_held_total` (2026-08-04):
432 -- stamped by the first roll call taken for the lesson, read by nothing but
433 -- that guard. Definition only, and deliberately no backfill — a session
434 -- that predates it carries no stamp, so the next roll call taken on it
435 -- credits its teacher once, which is the rule this column encodes anyway.
436 DEFINE FIELD IF NOT EXISTS held_counted_at ON course_session TYPE option<int>;
437 DEFINE INDEX IF NOT EXISTS course_session_course ON course_session FIELDS course;
438
439 DEFINE TABLE IF NOT EXISTS session_attendance SCHEMAFULL;
440 DEFINE FIELD IF NOT EXISTS session ON session_attendance TYPE record<course_session>;
441 DEFINE FIELD IF NOT EXISTS course ON session_attendance TYPE record<course>;
442 DEFINE FIELD IF NOT EXISTS user ON session_attendance TYPE record<user>;
443 DEFINE FIELD IF NOT EXISTS status ON session_attendance TYPE string;
444 DEFINE FIELD IF NOT EXISTS marked_by ON session_attendance TYPE record<user>;
445 DEFINE INDEX IF NOT EXISTS session_attendance_session_user ON session_attendance FIELDS session, user UNIQUE;
446 DEFINE INDEX IF NOT EXISTS session_attendance_session ON session_attendance FIELDS session;
447 DEFINE INDEX IF NOT EXISTS session_attendance_user ON session_attendance FIELDS user;
448 DEFINE INDEX IF NOT EXISTS session_attendance_course ON session_attendance FIELDS course;
449
450 DEFINE TABLE IF NOT EXISTS work_entry SCHEMAFULL;
451 DEFINE FIELD IF NOT EXISTS user ON work_entry TYPE record<user>;
452 DEFINE FIELD IF NOT EXISTS check_in ON work_entry TYPE int;
453 DEFINE FIELD IF NOT EXISTS check_out ON work_entry TYPE option<int>;
454 DEFINE INDEX IF NOT EXISTS work_entry_user ON work_entry FIELDS user;
455
456 DEFINE TABLE IF NOT EXISTS pomodoro_session SCHEMAFULL;
457 DEFINE FIELD IF NOT EXISTS user ON pomodoro_session TYPE record<user>;
458 DEFINE FIELD IF NOT EXISTS started_at ON pomodoro_session TYPE int;
459 DEFINE FIELD IF NOT EXISTS finished_at ON pomodoro_session TYPE option<int>;
460 -- The verdict `finish` reached for this stint, stamped at close so a later
461 -- reader never re-derives it against thresholds that have since moved.
462 -- `option<bool>`: a running stint has no verdict yet, and a stint closed
463 -- before the rule existed carries none and cannot honestly be given one.
464 DEFINE FIELD IF NOT EXISTS counted ON pomodoro_session TYPE option<bool>;
465 DEFINE INDEX IF NOT EXISTS pomodoro_session_user ON pomodoro_session FIELDS user;
466
467 DEFINE TABLE IF NOT EXISTS exam SCHEMAFULL;
468 DEFINE FIELD IF NOT EXISTS creator ON exam TYPE record<user>;
469 DEFINE FIELD IF NOT EXISTS course ON exam TYPE record<course>;
470 DEFINE FIELD IF NOT EXISTS title ON exam TYPE string;
471 DEFINE FIELD IF NOT EXISTS description ON exam TYPE string;
472 DEFINE FIELD IF NOT EXISTS kind ON exam TYPE string;
473 DEFINE FIELD IF NOT EXISTS mode ON exam TYPE option<string>;
474 DEFINE FIELD IF NOT EXISTS starts_at ON exam TYPE option<int>;
475 DEFINE FIELD IF NOT EXISTS ends_at ON exam TYPE option<int>;
476 DEFINE FIELD IF NOT EXISTS duration_ms ON exam TYPE option<int>;
477 DEFINE FIELD IF NOT EXISTS max_attempts ON exam TYPE int DEFAULT 1;
478 DEFINE FIELD IF NOT EXISTS allow_rejoin ON exam TYPE bool DEFAULT true;
479 DEFINE FIELD IF NOT EXISTS allow_review ON exam TYPE bool DEFAULT false;
480 DEFINE FIELD IF NOT EXISTS draft ON exam TYPE bool DEFAULT false;
481 -- How many marks the exam carries (2026-07-27). A kind change is refused
482 -- against it, and the exam's own compare-and-set pins it, so a grade
483 -- landing mid-PATCH refuses that save instead of slipping past its gates.
484 DEFINE FIELD IF NOT EXISTS result_count ON exam TYPE option<int>;
485 DEFINE INDEX IF NOT EXISTS exam_course ON exam FIELDS course;
486
487 DEFINE TABLE IF NOT EXISTS exam_attempt SCHEMAFULL;
488 DEFINE FIELD IF NOT EXISTS exam ON exam_attempt TYPE record<exam>;
489 DEFINE FIELD IF NOT EXISTS user ON exam_attempt TYPE record<user>;
490 DEFINE FIELD IF NOT EXISTS seq ON exam_attempt TYPE int DEFAULT 1;
491 DEFINE FIELD IF NOT EXISTS started_at ON exam_attempt TYPE int;
492 DEFINE FIELD IF NOT EXISTS finished_at ON exam_attempt TYPE option<int>;
493 DEFINE FIELD IF NOT EXISTS left_at ON exam_attempt TYPE option<int>;
494 DEFINE INDEX IF NOT EXISTS exam_attempt_exam_user_seq ON exam_attempt FIELDS exam, user, seq UNIQUE;
495 DEFINE INDEX IF NOT EXISTS exam_attempt_exam ON exam_attempt FIELDS exam;
496
497 DEFINE TABLE IF NOT EXISTS exam_question SCHEMAFULL;
498 DEFINE FIELD IF NOT EXISTS exam ON exam_question TYPE record<exam>;
499 DEFINE FIELD IF NOT EXISTS text ON exam_question TYPE string;
500 DEFINE FIELD IF NOT EXISTS kind ON exam_question TYPE string;
501 DEFINE FIELD IF NOT EXISTS points ON exam_question TYPE int;
502 -- OVERWRITE, not IF NOT EXISTS: these columns changed type when choices
503 -- gained stable ids (`array<string>`/`int` -> `array<object>`/`string`),
504 -- and IF NOT EXISTS would leave an existing database on the old types.
505 DEFINE FIELD OVERWRITE choices ON exam_question TYPE option<array<object>>;
506 -- SCHEMAFULL rejects any nested key it wasn't told about, so the choice
507 -- object's own fields are declared too (same shape as `settings.exam_kinds`).
508 DEFINE FIELD OVERWRITE choices.*.id ON exam_question TYPE string;
509 DEFINE FIELD OVERWRITE choices.*.text ON exam_question TYPE string;
510 DEFINE FIELD OVERWRITE correct ON exam_question TYPE option<string>;
511 DEFINE FIELD IF NOT EXISTS subject ON exam_question TYPE record<subject>;
512 -- Provenance, one column per direction: `from_bank` is the template this
513 -- question was inserted from, `banked_as` the template most recently minted
514 -- by saving it into the bank. They replace the single `source_bank`, which
515 -- both directions wrote — so a question inserted from the bank read as
516 -- already-saved. OVERWRITE (not IF NOT EXISTS): the old column has to
517 -- actually go on an existing database, or SCHEMAFULL keeps accepting it
518 -- while the struct no longer writes it.
519 DEFINE FIELD OVERWRITE from_bank ON exam_question TYPE option<record<bank_question>>;
520 DEFINE FIELD OVERWRITE banked_as ON exam_question TYPE option<record<bank_question>>;
521 REMOVE FIELD IF EXISTS source_bank ON TABLE exam_question;
522 DEFINE INDEX IF NOT EXISTS exam_question_exam ON exam_question FIELDS exam;
523 DEFINE INDEX IF NOT EXISTS exam_question_subject ON exam_question FIELDS subject;
524
525 DEFINE TABLE IF NOT EXISTS question_image SCHEMAFULL;
526 DEFINE FIELD IF NOT EXISTS exam ON question_image TYPE record<exam>;
527 DEFINE FIELD IF NOT EXISTS question ON question_image TYPE record<exam_question>;
528 -- OVERWRITE: `slot` is now the choice's id, not its position.
529 DEFINE FIELD OVERWRITE slot ON question_image TYPE option<string>;
530 DEFINE FIELD IF NOT EXISTS file ON question_image TYPE string;
531 DEFINE FIELD IF NOT EXISTS content_type ON question_image TYPE string;
532 DEFINE FIELD IF NOT EXISTS size ON question_image TYPE int;
533 DEFINE INDEX IF NOT EXISTS question_image_exam ON question_image FIELDS exam;
534 DEFINE INDEX IF NOT EXISTS question_image_question ON question_image FIELDS question;
535
536 DEFINE TABLE IF NOT EXISTS bank_question SCHEMAFULL;
537 DEFINE FIELD IF NOT EXISTS owner ON bank_question TYPE record<user>;
538 -- OVERWRITE, not IF NOT EXISTS: the field started life as a required
539 -- `record<subject>` and has to actually change type on an existing database,
540 -- otherwise the subject-delete cascade (`SET subject = NONE`) is rejected.
541 DEFINE FIELD OVERWRITE subject ON bank_question TYPE option<record<subject>>;
542 DEFINE FIELD IF NOT EXISTS text ON bank_question TYPE string;
543 DEFINE FIELD IF NOT EXISTS kind ON bank_question TYPE string;
544 DEFINE FIELD IF NOT EXISTS points ON bank_question TYPE int;
545 -- OVERWRITE, not IF NOT EXISTS: these columns changed type when choices
546 -- gained stable ids (`array<string>`/`int` -> `array<object>`/`string`),
547 -- and IF NOT EXISTS would leave an existing database on the old types.
548 DEFINE FIELD OVERWRITE choices ON bank_question TYPE option<array<object>>;
549 -- SCHEMAFULL rejects any nested key it wasn't told about, so the choice
550 -- object's own fields are declared too (same shape as `settings.exam_kinds`).
551 DEFINE FIELD OVERWRITE choices.*.id ON bank_question TYPE string;
552 DEFINE FIELD OVERWRITE choices.*.text ON bank_question TYPE string;
553 DEFINE FIELD OVERWRITE correct ON bank_question TYPE option<string>;
554 DEFINE FIELD IF NOT EXISTS source_exam ON bank_question TYPE option<record<exam>>;
555 -- 'private' | 'school'. DEFAULT so a row that predates the field (or any
556 -- partial write) can never come out published: the answer key stays the
557 -- owner's until they publish it.
558 DEFINE FIELD IF NOT EXISTS visibility ON bank_question TYPE string DEFAULT 'private';
559 DEFINE FIELD IF NOT EXISTS created_at ON bank_question TYPE int READONLY;
560 DEFINE INDEX IF NOT EXISTS bank_question_owner ON bank_question FIELDS owner;
561 DEFINE INDEX IF NOT EXISTS bank_question_subject ON bank_question FIELDS subject;
562
563 DEFINE TABLE IF NOT EXISTS bank_question_image SCHEMAFULL;
564 DEFINE FIELD IF NOT EXISTS bank_question ON bank_question_image TYPE record<bank_question>;
565 -- OVERWRITE: `slot` is now the choice's id, not its position.
566 DEFINE FIELD OVERWRITE slot ON bank_question_image TYPE option<string>;
567 DEFINE FIELD IF NOT EXISTS file ON bank_question_image TYPE string;
568 DEFINE FIELD IF NOT EXISTS content_type ON bank_question_image TYPE string;
569 DEFINE FIELD IF NOT EXISTS size ON bank_question_image TYPE int;
570 DEFINE INDEX IF NOT EXISTS bank_question_image_question ON bank_question_image FIELDS bank_question;
571
572 DEFINE TABLE IF NOT EXISTS exam_answer SCHEMAFULL;
573 DEFINE FIELD IF NOT EXISTS exam ON exam_answer TYPE record<exam>;
574 DEFINE FIELD IF NOT EXISTS question ON exam_answer TYPE record<exam_question>;
575 DEFINE FIELD IF NOT EXISTS user ON exam_answer TYPE record<user>;
576 -- OVERWRITE: `selected` now names the picked option by id.
577 DEFINE FIELD OVERWRITE selected ON exam_answer TYPE option<string>;
578 DEFINE FIELD IF NOT EXISTS text ON exam_answer TYPE option<string>;
579 DEFINE FIELD IF NOT EXISTS updated_at ON exam_answer TYPE int;
580 -- `seq` numbers the sitting an answer belongs to (1, 2, …), mirroring
581 -- exam_attempt. It rides the record key too, so a retake's answer is a new
582 -- row, not an overwrite of the prior sitting.
583 DEFINE FIELD IF NOT EXISTS seq ON exam_answer TYPE int DEFAULT 1;
584 -- Retire the pre-history unique index: (question, user) is no longer unique
585 -- once a student re-sits; (question, user, seq) is.
586 REMOVE INDEX IF EXISTS exam_answer_question_user ON exam_answer;
587 DEFINE INDEX IF NOT EXISTS exam_answer_question_user_seq ON exam_answer FIELDS question, user, seq UNIQUE;
588 DEFINE INDEX IF NOT EXISTS exam_answer_exam_user ON exam_answer FIELDS exam, user;
589 DEFINE INDEX IF NOT EXISTS exam_answer_exam ON exam_answer FIELDS exam;
590
591 DEFINE TABLE IF NOT EXISTS answer_image SCHEMAFULL;
592 DEFINE FIELD IF NOT EXISTS exam ON answer_image TYPE record<exam>;
593 DEFINE FIELD IF NOT EXISTS question ON answer_image TYPE record<exam_question>;
594 DEFINE FIELD IF NOT EXISTS user ON answer_image TYPE record<user>;
595 DEFINE FIELD IF NOT EXISTS file ON answer_image TYPE string;
596 DEFINE FIELD IF NOT EXISTS content_type ON answer_image TYPE string;
597 DEFINE FIELD IF NOT EXISTS size ON answer_image TYPE int;
598 -- `seq` numbers the sitting this drawing belongs to; it rides the record
599 -- key so a retake's image never overwrites the prior sitting's.
600 DEFINE FIELD IF NOT EXISTS seq ON answer_image TYPE int DEFAULT 1;
601 DEFINE INDEX IF NOT EXISTS answer_image_exam ON answer_image FIELDS exam;
602 DEFINE INDEX IF NOT EXISTS answer_image_user ON answer_image FIELDS user;
603
604 DEFINE TABLE IF NOT EXISTS exam_result SCHEMAFULL;
605 DEFINE FIELD IF NOT EXISTS exam ON exam_result TYPE record<exam>;
606 DEFINE FIELD IF NOT EXISTS user ON exam_result TYPE record<user>;
607 DEFINE FIELD IF NOT EXISTS mark ON exam_result TYPE int;
608 DEFINE FIELD IF NOT EXISTS graded_by ON exam_result TYPE record<user>;
609 -- `seq` numbers the sitting a mark belongs to; a retake earns its own mark
610 -- row, and the latest seq is the student's standing.
611 DEFINE FIELD IF NOT EXISTS seq ON exam_result TYPE int DEFAULT 1;
612 REMOVE INDEX IF EXISTS exam_result_exam_user ON exam_result;
613 DEFINE INDEX IF NOT EXISTS exam_result_exam_user_seq ON exam_result FIELDS exam, user, seq UNIQUE;
614
615 DEFINE TABLE IF NOT EXISTS pool_question SCHEMAFULL;
616 DEFINE FIELD IF NOT EXISTS asker ON pool_question TYPE record<user>;
617 DEFINE FIELD IF NOT EXISTS title ON pool_question TYPE string;
618 DEFINE FIELD IF NOT EXISTS body ON pool_question TYPE string;
619 DEFINE FIELD IF NOT EXISTS status ON pool_question TYPE string DEFAULT 'pending';
620 DEFINE FIELD IF NOT EXISTS asked_at ON pool_question TYPE int;
621 DEFINE FIELD IF NOT EXISTS approved_by ON pool_question TYPE option<record<user>>;
622 DEFINE FIELD IF NOT EXISTS image_file ON pool_question TYPE option<string>;
623 DEFINE FIELD IF NOT EXISTS image_content_type ON pool_question TYPE option<string>;
624 DEFINE FIELD IF NOT EXISTS image_size ON pool_question TYPE option<int>;
625 DEFINE INDEX IF NOT EXISTS pool_question_status ON pool_question FIELDS status;
626 DEFINE INDEX IF NOT EXISTS pool_question_asker ON pool_question FIELDS asker;
627
628 DEFINE TABLE IF NOT EXISTS solution SCHEMAFULL;
629 DEFINE FIELD IF NOT EXISTS question ON solution TYPE record<pool_question>;
630 DEFINE FIELD IF NOT EXISTS author ON solution TYPE record<user>;
631 DEFINE FIELD IF NOT EXISTS body ON solution TYPE string;
632 DEFINE FIELD IF NOT EXISTS offered_at ON solution TYPE int;
633 DEFINE FIELD IF NOT EXISTS image_file ON solution TYPE option<string>;
634 DEFINE FIELD IF NOT EXISTS image_content_type ON solution TYPE option<string>;
635 DEFINE FIELD IF NOT EXISTS image_size ON solution TYPE option<int>;
636 DEFINE INDEX IF NOT EXISTS solution_question ON solution FIELDS question;
637
638 DEFINE TABLE IF NOT EXISTS settings SCHEMAFULL;
639 DEFINE FIELD IF NOT EXISTS exam_kinds ON settings TYPE array<object>;
640 DEFINE FIELD IF NOT EXISTS exam_kinds.*.name ON settings TYPE string;
641 DEFINE FIELD IF NOT EXISTS exam_kinds.*.weight ON settings TYPE int;
642 DEFINE FIELD IF NOT EXISTS attendance_statuses ON settings TYPE array<string>;
643 DEFINE FIELD IF NOT EXISTS grade_bands ON settings TYPE array<object>;
644 DEFINE FIELD IF NOT EXISTS grade_bands.*.min ON settings TYPE int;
645 DEFINE FIELD IF NOT EXISTS grade_bands.*.label ON settings TYPE string;
646 DEFINE FIELD IF NOT EXISTS max_file_bytes ON settings TYPE option<int>;
647 DEFINE FIELD IF NOT EXISTS chatbot_history_turns ON settings TYPE option<int>;
648 DEFINE FIELD IF NOT EXISTS max_chatbot_threads ON settings TYPE option<int>;
649 DEFINE FIELD IF NOT EXISTS max_chatbot_message_len ON settings TYPE option<int>;
650 -- Food program (2026-07-26). `meal_slots` mirrors the `exam_kinds` shape —
651 -- a named list a menu snapshots from — and `dietary_tags` mirrors
652 -- `attendance_statuses`. `meal_cancel_cutoff_minutes` is ONE knob for both
653 -- the booking and the cancel deadline; absent means no cutoff at all. All
654 -- three are `option<>`, exactly like `max_file_bytes`: NOT `DEFAULT []`.
655 -- `DEFAULT` fires on create only, and `PATCH /settings` writes the whole
656 -- row with `UPDATE ... CONTENT`, so a required-with-default field a writer
657 -- omits coerces to NONE and fails every settings write until the domain
658 -- struct carries it. `option<>` also means the existing singleton reads
659 -- fine, which is why the food program needs no BACKFILL anywhere.
660 DEFINE FIELD IF NOT EXISTS meal_slots ON settings TYPE option<array<object>>;
661 DEFINE FIELD IF NOT EXISTS meal_slots.*.name ON settings TYPE string;
662 -- Minutes past midnight UTC at which the slot is served (2026-07-26).
663 -- `option<int>` for the same reason the list itself is: slots written
664 -- before the field existed simply have no key, and read back as NONE ->
665 -- the booking cutoff falls back to midnight UTC, its old meaning. No
666 -- BACKFILL, and no DEFAULT — see the note above.
667 DEFINE FIELD IF NOT EXISTS meal_slots.*.serving_minute ON settings TYPE option<int>;
668 DEFINE FIELD IF NOT EXISTS dietary_tags ON settings TYPE option<array<string>>;
669 DEFINE FIELD IF NOT EXISTS meal_cancel_cutoff_minutes ON settings TYPE option<int>;
670
671 -- Homework (greenfield, 2026-07-22): a teacher assigns per course, students
672 -- submit files + optional text, a teacher grades a status + optional mark.
673 -- `course`/`created_by`/`created_at` are READONLY (a homework never moves
674 -- course, and stamps never rewrite); `subject` is NOT — it is re-taggable
675 -- via PATCH. `assigned` NONE/empty means the whole course. No BACKFILL: the
676 -- tables are new, so the whole migration stays additive and idempotent.
677 DEFINE TABLE IF NOT EXISTS homework SCHEMAFULL;
678 DEFINE FIELD IF NOT EXISTS course ON homework TYPE record<course> READONLY;
679 DEFINE FIELD IF NOT EXISTS subject ON homework TYPE record<subject>;
680 DEFINE FIELD IF NOT EXISTS title ON homework TYPE string;
681 DEFINE FIELD IF NOT EXISTS description ON homework TYPE option<string>;
682 DEFINE FIELD IF NOT EXISTS due_at ON homework TYPE int;
683 DEFINE FIELD IF NOT EXISTS assigned ON homework TYPE option<array<record<user>>>;
684 DEFINE FIELD IF NOT EXISTS assigned[*] ON homework TYPE record<user>;
685 DEFINE FIELD IF NOT EXISTS created_by ON homework TYPE record<user> READONLY;
686 DEFINE FIELD IF NOT EXISTS created_at ON homework TYPE int READONLY;
687 DEFINE INDEX IF NOT EXISTS homework_course ON homework FIELDS course;
688
689 DEFINE TABLE IF NOT EXISTS homework_submission SCHEMAFULL;
690 DEFINE FIELD IF NOT EXISTS homework ON homework_submission TYPE record<homework> READONLY;
691 DEFINE FIELD IF NOT EXISTS user ON homework_submission TYPE record<user> READONLY;
692 DEFINE FIELD IF NOT EXISTS text ON homework_submission TYPE option<string>;
693 DEFINE FIELD IF NOT EXISTS submitted_at ON homework_submission TYPE int READONLY;
694 DEFINE FIELD IF NOT EXISTS updated_at ON homework_submission TYPE int;
695 DEFINE FIELD IF NOT EXISTS file_count ON homework_submission TYPE option<int>;
696 -- The on-time verdict the badge counter was actually credited with, stamped
697 -- at the first hand-in and never re-judged. `due_at` is mutable (a teacher
698 -- moves a deadline with `PATCH /homework/{id}`), so re-deriving the verdict
699 -- at withdrawal read a *different* deadline than the credit did and gave
700 -- back the wrong thing in both directions — extend the deadline after a late
701 -- hand-in and the withdrawal debited an on-time credit that was never given;
702 -- pull it back after a punctual one and it debited nothing, leaving on_time
703 -- above submitted. `option<>` because every row predating 2026-08-04 has no
704 -- stored verdict and cannot be given one for a credit that already happened:
705 -- those fall back to the old comparison (see
706 -- [`crate::db::homework_submission::delete`]).
707 DEFINE FIELD IF NOT EXISTS counted_on_time ON homework_submission TYPE option<bool>;
708 -- The grade that froze this submission, absent while it is still open. The
709 -- freeze used to be a cross-table read (does a homework_result exist?)
710 -- followed by a write here, which no lock can hold across replicas; the
711 -- stamp turns every submission edit into a conditional single-record write
712 -- (`WHERE graded_by_result = NONE`), the one guard that survives. Set by
713 -- grading, cleared by un-grading, never by the student.
714 DEFINE FIELD IF NOT EXISTS graded_by_result ON homework_submission TYPE option<record<homework_result>>;
715 DEFINE INDEX IF NOT EXISTS homework_submission_homework ON homework_submission FIELDS homework;
716
717 DEFINE TABLE IF NOT EXISTS homework_file SCHEMAFULL;
718 DEFINE FIELD IF NOT EXISTS submission ON homework_file TYPE record<homework_submission> READONLY;
719 DEFINE FIELD IF NOT EXISTS name ON homework_file TYPE string;
720 DEFINE FIELD IF NOT EXISTS content_type ON homework_file TYPE string;
721 DEFINE FIELD IF NOT EXISTS size ON homework_file TYPE int;
722 DEFINE FIELD IF NOT EXISTS file ON homework_file TYPE string READONLY;
723 DEFINE FIELD IF NOT EXISTS created_at ON homework_file TYPE int READONLY;
724 DEFINE INDEX IF NOT EXISTS homework_file_submission ON homework_file FIELDS submission;
725
726 DEFINE TABLE IF NOT EXISTS homework_result SCHEMAFULL;
727 DEFINE FIELD IF NOT EXISTS homework ON homework_result TYPE record<homework> READONLY;
728 DEFINE FIELD IF NOT EXISTS user ON homework_result TYPE record<user> READONLY;
729 DEFINE FIELD IF NOT EXISTS status ON homework_result TYPE string;
730 DEFINE FIELD IF NOT EXISTS mark ON homework_result TYPE option<int>;
731 DEFINE FIELD IF NOT EXISTS graded_by ON homework_result TYPE record<user>;
732 DEFINE FIELD IF NOT EXISTS created_at ON homework_result TYPE int;
733 DEFINE INDEX IF NOT EXISTS homework_result_homework ON homework_result FIELDS homework;
734
735 -- Appointments (greenfield, 2026-07-23): a teacher publishes availability
736 -- slots, a student or parent books one. `series` groups the occurrences a
737 -- weekly repeat expanded into, so one cancel deletes one row and a series
738 -- delete finds the rest. A booking's live/dead state is the `status`
739 -- string; `occupied` is the cap-1 counter that says whether the slot is
740 -- taken (2026-07-27 — it used to be counted from the booking rows under a
741 -- process-local lock, which two replicas could each pass), decremented in
742 -- the same transaction as the reject/cancel that frees it.
743 -- The `proposed_*` fields carry a teacher's counter-proposal on the same
744 -- row until the requester accepts.
745 DEFINE TABLE IF NOT EXISTS appointment_slot SCHEMAFULL;
746 DEFINE FIELD IF NOT EXISTS teacher ON appointment_slot TYPE record<user>;
747 DEFINE FIELD IF NOT EXISTS starts_at ON appointment_slot TYPE int;
748 DEFINE FIELD IF NOT EXISTS ends_at ON appointment_slot TYPE int;
749 DEFINE FIELD IF NOT EXISTS occupied ON appointment_slot TYPE option<int>;
750 DEFINE FIELD IF NOT EXISTS note ON appointment_slot TYPE option<string>;
751 DEFINE FIELD IF NOT EXISTS series ON appointment_slot TYPE option<string>;
752 DEFINE FIELD IF NOT EXISTS created_at ON appointment_slot TYPE int;
753 DEFINE INDEX IF NOT EXISTS appointment_slot_teacher_starts ON appointment_slot FIELDS teacher, starts_at;
754 DEFINE INDEX IF NOT EXISTS appointment_slot_series ON appointment_slot FIELDS series;
755
756 DEFINE TABLE IF NOT EXISTS appointment SCHEMAFULL;
757 DEFINE FIELD IF NOT EXISTS slot ON appointment TYPE record<appointment_slot>;
758 DEFINE FIELD IF NOT EXISTS requester ON appointment TYPE record<user>;
759 DEFINE FIELD IF NOT EXISTS status ON appointment TYPE string DEFAULT 'pending';
760 DEFINE FIELD IF NOT EXISTS reason ON appointment TYPE string;
761 DEFINE FIELD IF NOT EXISTS proposed_starts_at ON appointment TYPE option<int>;
762 DEFINE FIELD IF NOT EXISTS proposed_ends_at ON appointment TYPE option<int>;
763 DEFINE FIELD IF NOT EXISTS proposed_by ON appointment TYPE option<record<user>>;
764 DEFINE FIELD IF NOT EXISTS decided_by ON appointment TYPE option<record<user>>;
765 DEFINE FIELD IF NOT EXISTS cancelled_by ON appointment TYPE option<record<user>>;
766 DEFINE FIELD IF NOT EXISTS cancel_reason ON appointment TYPE option<string>;
767 DEFINE FIELD IF NOT EXISTS reject_reason ON appointment TYPE option<string>;
768 DEFINE FIELD IF NOT EXISTS created_at ON appointment TYPE int;
769 DEFINE INDEX IF NOT EXISTS appointment_slot_ref ON appointment FIELDS slot;
770 DEFINE INDEX IF NOT EXISTS appointment_requester ON appointment FIELDS requester;
771 DEFINE INDEX IF NOT EXISTS appointment_status ON appointment FIELDS status;
772
773 -- Food program (greenfield, 2026-07-26): a published menu per day+slot,
774 -- dishes on it, a dietary profile per student, bookings against a menu's
775 -- capacity, who actually ate, and the money that moved. `date` is a
776 -- calendar day as `YYYY-MM-DD` text, not a timestamp: the unique index is
777 -- an equality test and a midnight-in-millis day is only unique for one
778 -- timezone. `slot` is snapshotted text, not a link, so retiring a slot in
779 -- settings never rewrites a past menu. Stamps stay `int` millis like the
780 -- rest of the schema. No BACKFILL: all six tables are new.
781 DEFINE TABLE IF NOT EXISTS menu SCHEMAFULL;
782 DEFINE FIELD IF NOT EXISTS date ON menu TYPE string READONLY;
783 DEFINE FIELD IF NOT EXISTS slot ON menu TYPE string READONLY;
784 DEFINE FIELD IF NOT EXISTS capacity ON menu TYPE option<int>;
785 -- `seats_booked` is the seat cap's counter (see `db::cap`) and
786 -- `version` the menu's revision: a booking claims its seat only while the
787 -- menu still stands at the revision it read the price at, so a dish
788 -- re-priced mid-booking cannot be billed as the old price. Both absent
789 -- means zero, which is what `(x ?? 0)` reads on a row written before them.
790 DEFINE FIELD IF NOT EXISTS seats_booked ON menu TYPE option<int>;
791 DEFINE FIELD IF NOT EXISTS version ON menu TYPE option<int>;
792 DEFINE FIELD IF NOT EXISTS created_by ON menu TYPE record<user> READONLY;
793 DEFINE FIELD IF NOT EXISTS created_at ON menu TYPE int READONLY;
794 DEFINE INDEX IF NOT EXISTS menu_date_slot ON menu FIELDS date, slot UNIQUE;
795
796 DEFINE TABLE IF NOT EXISTS menu_dish SCHEMAFULL;
797 DEFINE FIELD IF NOT EXISTS menu ON menu_dish TYPE record<menu> READONLY;
798 DEFINE FIELD IF NOT EXISTS name ON menu_dish TYPE string;
799 DEFINE FIELD IF NOT EXISTS description ON menu_dish TYPE option<string>;
800 -- Money is minor units (kuruş) as an integer, everywhere. Never decimal.
801 DEFINE FIELD IF NOT EXISTS price_minor ON menu_dish TYPE int;
802 DEFINE FIELD IF NOT EXISTS tags ON menu_dish TYPE array<string> DEFAULT [];
803 DEFINE FIELD IF NOT EXISTS tags[*] ON menu_dish TYPE string;
804 DEFINE FIELD IF NOT EXISTS created_at ON menu_dish TYPE int READONLY;
805 DEFINE INDEX IF NOT EXISTS menu_dish_menu ON menu_dish FIELDS menu;
806
807 DEFINE TABLE IF NOT EXISTS dietary_profile SCHEMAFULL;
808 DEFINE FIELD IF NOT EXISTS student ON dietary_profile TYPE record<user> READONLY;
809 DEFINE FIELD IF NOT EXISTS tags ON dietary_profile TYPE array<string> DEFAULT [];
810 DEFINE FIELD IF NOT EXISTS tags[*] ON dietary_profile TYPE string;
811 DEFINE FIELD IF NOT EXISTS note ON dietary_profile TYPE option<string>;
812 DEFINE FIELD IF NOT EXISTS updated_by ON dietary_profile TYPE record<user>;
813 DEFINE FIELD IF NOT EXISTS updated_at ON dietary_profile TYPE int;
814 DEFINE INDEX IF NOT EXISTS dietary_profile_student ON dietary_profile FIELDS student UNIQUE;
815
816 -- A cancel flips `status` and stamps `cancelled_at`; the row stays so the
817 -- freed seat is still auditable against the ledger line it charged.
818 DEFINE TABLE IF NOT EXISTS meal_booking SCHEMAFULL;
819 DEFINE FIELD IF NOT EXISTS menu ON meal_booking TYPE record<menu> READONLY;
820 DEFINE FIELD IF NOT EXISTS student ON meal_booking TYPE record<user> READONLY;
821 DEFINE FIELD IF NOT EXISTS booked_by ON meal_booking TYPE record<user> READONLY;
822 DEFINE FIELD IF NOT EXISTS status ON meal_booking TYPE string DEFAULT 'booked';
823 -- How many times this seat has been taken, and what it cost when the
824 -- *current* attempt took it (NONE = the menu was free then). Together they
825 -- key the attempt's ledger lines, which is what makes billing idempotent
826 -- by identity rather than by scanning for an outstanding charge.
827 DEFINE FIELD IF NOT EXISTS attempt ON meal_booking TYPE int DEFAULT 1;
828 DEFINE FIELD IF NOT EXISTS price_minor ON meal_booking TYPE option<int>;
829 DEFINE FIELD IF NOT EXISTS cancelled_at ON meal_booking TYPE option<int>;
830 DEFINE FIELD IF NOT EXISTS created_at ON meal_booking TYPE int READONLY;
831 DEFINE INDEX IF NOT EXISTS meal_booking_menu ON meal_booking FIELDS menu;
832 DEFINE INDEX IF NOT EXISTS meal_booking_student ON meal_booking FIELDS student;
833
834 DEFINE TABLE IF NOT EXISTS meal_attendance SCHEMAFULL;
835 DEFINE FIELD IF NOT EXISTS menu ON meal_attendance TYPE record<menu> READONLY;
836 DEFINE FIELD IF NOT EXISTS student ON meal_attendance TYPE record<user> READONLY;
837 DEFINE FIELD IF NOT EXISTS status ON meal_attendance TYPE string;
838 DEFINE FIELD IF NOT EXISTS marked_by ON meal_attendance TYPE record<user>;
839 DEFINE FIELD IF NOT EXISTS marked_at ON meal_attendance TYPE int;
840 DEFINE INDEX IF NOT EXISTS meal_attendance_menu_student ON meal_attendance FIELDS menu, student UNIQUE;
841
842 -- APPEND-ONLY by design: a mistake is corrected with an opposing
843 -- `reversal` line, never by editing or deleting one. Hence every field is
844 -- READONLY. `source` is untyped on purpose — a charge points at the
845 -- booking that caused it, a reversal at the line it undoes.
846 DEFINE TABLE IF NOT EXISTS meal_ledger SCHEMAFULL;
847 DEFINE FIELD IF NOT EXISTS student ON meal_ledger TYPE record<user> READONLY;
848 DEFINE FIELD IF NOT EXISTS kind ON meal_ledger TYPE string READONLY;
849 DEFINE FIELD IF NOT EXISTS amount_minor ON meal_ledger TYPE int READONLY;
850 DEFINE FIELD IF NOT EXISTS source ON meal_ledger TYPE option<record> READONLY;
851 DEFINE FIELD IF NOT EXISTS method ON meal_ledger TYPE option<string> READONLY;
852 DEFINE FIELD IF NOT EXISTS note ON meal_ledger TYPE option<string> READONLY;
853 DEFINE FIELD IF NOT EXISTS recorded_by ON meal_ledger TYPE record<user> READONLY;
854 DEFINE FIELD IF NOT EXISTS created_at ON meal_ledger TYPE int READONLY;
855 DEFINE INDEX IF NOT EXISTS meal_ledger_student ON meal_ledger FIELDS student;
856
857 -- A school fee plan: a name and its installments, each an amount and the
858 -- day it falls due. The installments are embedded (SCHEMAFULL, so the
859 -- object's own fields are declared too, same shape as `settings.exam_kinds`)
860 -- because a charge line copies the amount it was assigned at — child rows
861 -- would buy nothing. Neither field inside the object is optional: a NONE
862 -- value would be dropped from the stored object entirely.
863 DEFINE TABLE IF NOT EXISTS fee_plan SCHEMAFULL;
864 DEFINE FIELD IF NOT EXISTS name ON fee_plan TYPE string;
865 DEFINE FIELD IF NOT EXISTS installments ON fee_plan TYPE array<object>;
866 DEFINE FIELD IF NOT EXISTS installments.*.amount_minor ON fee_plan TYPE int;
867 DEFINE FIELD IF NOT EXISTS installments.*.due_at ON fee_plan TYPE int;
868 DEFINE FIELD IF NOT EXISTS created_by ON fee_plan TYPE record<user> READONLY;
869 DEFINE FIELD IF NOT EXISTS created_at ON fee_plan TYPE int READONLY;
870 -- How many students are on the plan. The edit and delete guards read it,
871 -- an assignment's own transaction increments it, and nothing decrements it
872 -- (assignments are never removed). `option<int>` and no DEFAULT, like every
873 -- other counter: no Rust struct carries it, so the plan's create must not
874 -- be expected to state it.
875 DEFINE FIELD IF NOT EXISTS assignment_count ON fee_plan TYPE option<int>;
876
877 -- One plan on one student, keyed `<plan>_<student>`: assigning twice is the
878 -- same record id, so a replay writes nothing and an assignment cut short
879 -- half-way self-heals when it is repeated. Nothing here is ever edited.
880 DEFINE TABLE IF NOT EXISTS fee_plan_assignment SCHEMAFULL;
881 DEFINE FIELD IF NOT EXISTS plan ON fee_plan_assignment TYPE record<fee_plan> READONLY;
882 DEFINE FIELD IF NOT EXISTS student ON fee_plan_assignment TYPE record<user> READONLY;
883 DEFINE FIELD IF NOT EXISTS assigned_by ON fee_plan_assignment TYPE record<user> READONLY;
884 DEFINE FIELD IF NOT EXISTS created_at ON fee_plan_assignment TYPE int READONLY;
885 DEFINE INDEX IF NOT EXISTS fee_plan_assignment_plan ON fee_plan_assignment FIELDS plan;
886 DEFINE INDEX IF NOT EXISTS fee_plan_assignment_student ON fee_plan_assignment FIELDS student;
887
888 -- School fees, APPEND-ONLY by design exactly like `meal_ledger`: a mistake
889 -- is corrected with an opposing line, never by editing or deleting one,
890 -- hence every field is READONLY. `source` is untyped on purpose — a charge
891 -- points at the `fee_plan_assignment` that raised it, a credit at the charge
892 -- it pays, a refund at the credit it returns, a reversal at the line it
893 -- undoes. `due_at` is set on charges alone.
894 DEFINE TABLE IF NOT EXISTS payment_ledger SCHEMAFULL;
895 DEFINE FIELD IF NOT EXISTS student ON payment_ledger TYPE record<user> READONLY;
896 DEFINE FIELD IF NOT EXISTS kind ON payment_ledger TYPE string READONLY;
897 DEFINE FIELD IF NOT EXISTS amount_minor ON payment_ledger TYPE int READONLY;
898 DEFINE FIELD IF NOT EXISTS source ON payment_ledger TYPE option<record> READONLY;
899 DEFINE FIELD IF NOT EXISTS due_at ON payment_ledger TYPE option<int> READONLY;
900 DEFINE FIELD IF NOT EXISTS method ON payment_ledger TYPE option<string> READONLY;
901 DEFINE FIELD IF NOT EXISTS note ON payment_ledger TYPE option<string> READONLY;
902 DEFINE FIELD IF NOT EXISTS recorded_by ON payment_ledger TYPE record<user> READONLY;
903 DEFINE FIELD IF NOT EXISTS created_at ON payment_ledger TYPE int READONLY;
904 DEFINE INDEX IF NOT EXISTS payment_ledger_student ON payment_ledger FIELDS student;
905 DEFINE INDEX IF NOT EXISTS payment_ledger_source ON payment_ledger FIELDS source;
906
907 -- One row per badge a user has earned, keyed `{user}_{badge}` so the award
908 -- is written by an UPSERT that can never double (domain::badge). `earned_at`
909 -- is `option<int>` because that is what makes the stamp write-once: the
910 -- UPSERT carries `WHERE earned_at = NONE`, so a re-sync of a badge already
911 -- held leaves the original date standing. Awards are permanent — nothing
912 -- deletes a row here — so the table needs no repair and no BACKFILL.
913 DEFINE TABLE IF NOT EXISTS badge_award SCHEMAFULL;
914 DEFINE FIELD IF NOT EXISTS user ON badge_award TYPE record<user>;
915 DEFINE FIELD IF NOT EXISTS badge ON badge_award TYPE string;
916 DEFINE FIELD IF NOT EXISTS earned_at ON badge_award TYPE option<int>;
917 -- A plain field index, never `FIELDS user[*]`: the per-element form is used
918 -- by the planner and then returns zero rows (see the `course.teachers` note).
919 DEFINE INDEX IF NOT EXISTS badge_award_user ON badge_award FIELDS user;
920
921 -- Reference counters, one row per *name* the settings offer, keyed by the
922 -- name itself (2026-07-27). They are how 'a kind nothing is graded under
923 -- may be removed' survives a second replica: the guard used to be a
924 -- count-then-write across two tables under a process-wide lock, and the
925 -- database serializes neither half of that. Both columns are `option<…>`
926 -- so an absent row reads as zero references, in service — the counter is
927 -- created by the first claim, never seeded per name.
928 DEFINE TABLE IF NOT EXISTS kind_ref SCHEMAFULL;
929 DEFINE FIELD IF NOT EXISTS count ON kind_ref TYPE option<int>;
930 DEFINE FIELD IF NOT EXISTS retired ON kind_ref TYPE option<bool>;
931
932 DEFINE TABLE IF NOT EXISTS slot_ref SCHEMAFULL;
933 DEFINE FIELD IF NOT EXISTS count ON slot_ref TYPE option<int>;
934 DEFINE FIELD IF NOT EXISTS retired ON slot_ref TYPE option<bool>;
935
936 -- One row per backfill that is genuinely *one-time*, keyed by the backfill's
937 -- own name (2026-08-02). Most of `BACKFILL` is a `WHERE` that matches no row
938 -- once it has converged, so re-running it is free — but a repair whose cost
939 -- is the *scan* rather than the write pays that cost on every boot forever,
940 -- and the board-roster sweep's scan is one full `user` pass per board. A
941 -- marker row is the smallest thing that can say 'this one is finished': the
942 -- boot loop carries no lock and no fingerprint any more (2026-07-30), so
943 -- there is nowhere else for that fact to live. A database that never ran the
944 -- repair holds no row and runs it; the row is written by the same query.
945 --
946 -- `fingerprint` is *which* text ran (2026-08-05), and it is what makes a
947 -- marked block correctable. Saying only 'this ran' meant an edit to a block
948 -- that was already marked could never reach a volume that had booted once:
949 -- the `exam_sat_total` correction below shipped inside one and would have
950 -- been dead on arrival on every existing database. The gate compares the
951 -- stored number against the hash of the text *this* binary would run
952 -- (`database::marked_blocks`), so an edited block runs once more and
953 -- re-stamps, and an unedited one still costs a single record read.
954 -- `option<int>`: a mark written before this column existed carries none,
955 -- which matches no fingerprint and so re-runs its block exactly once.
956 DEFINE TABLE IF NOT EXISTS migration_mark SCHEMAFULL;
957 DEFINE FIELD IF NOT EXISTS done_at ON migration_mark TYPE int;
958 DEFINE FIELD IF NOT EXISTS fingerprint ON migration_mark TYPE option<int>;
959";
960
961/// Data backfills for rows written by older binaries. Runs *after* (and apart
962/// from) the DDL batch so every statement sees the freshly defined schema —
963/// see the `MIGRATION` doc for why sharing the batch corrupts the writes.
964/// Idempotent: each backfill's `WHERE` only matches unconverted rows.
965pub const BACKFILL: &str = "
966 UPDATE user SET role = 'student' WHERE role = NONE;
967
968 UPDATE course SET kind = 'course' WHERE kind = NONE;
969
970 -- Courses predate assignable teachers (2026-07-21): every existing course
971 -- was run by its creator alone, so it starts with nobody else assigned.
972 UPDATE course SET teachers = [] WHERE teachers = NONE;
973
974 -- Exams predate the draft flag (2026-07-19): everything already out there
975 -- was live for its course, so it stays published.
976 UPDATE exam SET draft = false WHERE draft = NONE;
977
978 -- Exams predate the review toggle (2026-07-24): default it closed (opt-in).
979 UPDATE exam SET allow_review = false WHERE allow_review = NONE;
980
981 UPDATE event SET audience = { kind: 'school' } WHERE audience = NONE OR audience = {};
982
983 -- Questions written before subjects existed (2026-07-17) are destroyed, not
984 -- backfilled: a subject is mandatory and there is nothing truthful to
985 -- assign. Their answers go first so no answer row outlives its question.
986 DELETE exam_answer WHERE question IN (SELECT VALUE id FROM exam_question WHERE subject = NONE);
987 DELETE exam_question WHERE subject = NONE;
988
989 -- The hand-picked `users` audience retired into `registration` (2026-07-16):
990 -- each listed user becomes a signup row credited to the event's creator, and
991 -- the event becomes an uncapped registration list. Runs once — converted
992 -- events no longer match the `kind = 'users'` filter. (`?? []`: an empty
993 -- statement-subquery evaluates to NONE, which FOR refuses to iterate.)
994 FOR $ev IN ((SELECT id, creator, audience FROM event WHERE audience.kind = 'users') ?? []) {
995 FOR $usr IN ($ev.audience.users ?? []) {
996 UPSERT type::record('registration', string::concat(record::id($ev.id), '_', record::id($usr))) CONTENT {
997 event: $ev.id,
998 user: $usr,
999 registered_by: $ev.creator,
1000 };
1001 };
1002 UPDATE $ev.id SET audience = { kind: 'registration' };
1003 };
1004
1005 -- Turns written before the clipped-answer flag existed (2026-07-23): the
1006 -- clip was silent then, so nothing can be recovered — they read as whole,
1007 -- which is what they were presented as all along.
1008 UPDATE chatbot_message SET truncated = false WHERE truncated = NONE;
1009
1010 -- An assistant turn is answered by a task in this process, so a restart can
1011 -- leave its row `pending` with nobody left to complete it. Only rows past
1012 -- the stale horizon ($stale_ms, from `CHATBOT_PENDING_STALE_SECS`) are
1013 -- certainly abandoned though: a young one may still be being answered on
1014 -- the other side of the AI bridge, and a deploy must not shoot down a turn
1015 -- dispatched seconds ago. Nothing is lost by waiting — a reader already
1016 -- presents an over-age `pending` row as failed, and the next boot sweeps
1017 -- for real whatever crossed the horizon in the meantime.
1018 --
1019 -- The claim half of this guard went with the claim queue (2026-07-30): it
1020 -- only ever spared a row a *live peer* was answering, and there is no peer.
1021 -- The rows selected are otherwise the same ones — an unclaimed row past the
1022 -- horizon was always swept, and a claim of this process's own could not
1023 -- outlive the process whose boot is running this.
1024 UPDATE chatbot_message SET status = 'failed', error_code = 'interrupted',
1025 completed_at = time::unix(time::now()) * 1000
1026 WHERE status = 'pending' AND created_at < time::unix(time::now()) * 1000 - $stale_ms;
1027
1028 -- The seats the sweep below spent every past boot *not* giving back: until
1029 -- today it deleted those rows without touching the course's counter, so
1030 -- every course it ever swept carries a phantom seat — one that denies a real
1031 -- student a place, and that `Course::delete` refuses to let anyone past,
1032 -- forever (its guard is `(enrollment_count ?? 0) = 0` on the course row).
1033 -- This recomputes the counter for every course whose stored number disagrees
1034 -- with the enrollment rows it actually has.
1035 --
1036 -- Counting the rows cannot read *low*. The counter has exactly one meaning —
1037 -- the live enrollment rows of this course — and every writer moves it with
1038 -- the row in one transaction (`db::enrollment`'s `enroll`/`remove`, `set_role`'s
1039 -- demotion sweep, the class pump's attach and detach); `Course::delete` takes
1040 -- the rows *and* the course together, so no cascade leaves counted rows
1041 -- behind. That is what separates it from the lifetime tallies below, which
1042 -- are seeded once precisely because their rows do die under them. The claims
1043 -- that borrow this column as a collision device (`cap::touch_and_create`,
1044 -- `Axis::pivot_claim`) bump and restore it inside their own transaction, so
1045 -- no other reader ever sees the raised value — and `migrate` runs to
1046 -- completion before the router is bound, one process per volume, so there is
1047 -- no concurrent writer to see it from anyway.
1048 --
1049 -- Neither `= NONE`-guarded nor marked, for the board-stroke repair's reason:
1050 -- this is not an opinion the live system maintains, it is the course's row
1051 -- count, so recomputing converges instead of overwriting and the `!=` guard
1052 -- writes nothing on the next boot. It runs *before* the sweep, so the two
1053 -- own separate halves of the same invariant — this one clears the drift the
1054 -- volume arrived with, the sweep's own decrement leaves none behind — and it
1055 -- does not fight the `= NONE` seeding further down either: a pre-counter
1056 -- course with rows gets the same number here that the seeding would have
1057 -- given it, and one with no rows stays absent for the zero pass to fill.
1058 --
1059 -- Per course rather than `GROUP BY course`, because the case that matters
1060 -- most forms no group: a course whose last enrollment the sweep took away has
1061 -- zero rows and a counter above zero, and a grouped pass would never visit
1062 -- it. `array::len` over ids rather than `count()`, because an aggregate over
1063 -- an indexed field (`enrollment` is indexed on `course`) can come back as
1064 -- `{ count: n }` from the server — a shape the in-memory engine never
1065 -- produces and `option<int>` would refuse.
1066 FOR $c IN ((SELECT VALUE id FROM course) ?? []) {
1067 LET $live = array::len((SELECT VALUE id FROM enrollment WHERE course = $c));
1068 UPDATE $c SET enrollment_count = $live WHERE (enrollment_count ?? 0) != $live;
1069 };
1070
1071 -- Promotion out of student now deletes the user's enrollments (2026-07-18);
1072 -- this sweeps rows promoted before that fix. A deleted user reads as
1073 -- `user.role = NONE`, which is also != 'student' — those rows go too.
1074 --
1075 -- The course's seat goes back with the row, per course, exactly the way
1076 -- `User::set_role`'s own demotion sweep releases it: the counter is the
1077 -- roster's authority, so a swept row that kept its seat denies a real
1078 -- student a place *and* makes the course undeletable for good
1079 -- (`Course::delete` refuses on `(enrollment_count ?? 0) = 0`). Several rows
1080 -- of one course each take their own turn through the loop, so the counter
1081 -- comes down by exactly as many rows as went.
1082 LET $swept = (DELETE enrollment WHERE user.role != 'student' RETURN BEFORE);
1083 FOR $row IN ($swept ?? []) {
1084 UPDATE $row.course SET enrollment_count =
1085 math::max([(enrollment_count ?? 0) - 1, 0]);
1086 };
1087
1088 -- Choices gained stable ids (2026-07-24): `choices` held bare strings and
1089 -- `correct`/`selected`/`slot` held the option's *position*. The DDL above
1090 -- retypes those columns, which leaves every old-shaped row readable but
1091 -- unwritable ('Expected `none | array<object>` but found `[..]`'), so this
1092 -- conversion is repair, not cosmetics.
1093 --
1094 -- Ids are minted in array order, so the id at position i *is* the id for
1095 -- old index i — that identity is what keeps a stored answer, and an option
1096 -- picture, pointing at the option the student actually saw. Hence the
1097 -- dependent rows are remapped inside the loop that mints `$new`, against
1098 -- that same array: once the ids are stored the positions are still
1099 -- recoverable, but nothing guarantees a later pass would look them up the
1100 -- same way. `WHERE choices[0] != NONE AND type::is_string(choices[0])`
1101 -- matches only unconverted rows, so a second boot re-mints nothing; an
1102 -- empty or absent `choices` needs no conversion at all. A question-level
1103 -- picture (`slot = NONE`) is not an index and is left alone.
1104 --
1105 -- Runs *before* every other backfill that writes these rows (the `seq`
1106 -- stamps below): a write coerces the whole record, so touching a row for
1107 -- any reason fails while its choices are still positional. For the same
1108 -- reason the answer's remap stamps `seq` itself — the two legacy gaps sit
1109 -- on the same row, and a write that fixes only one of them is rejected for
1110 -- the other. `seq ?? 1` leaves an already-numbered sitting alone (DEFAULT
1111 -- fills a CREATE, not an UPDATE of a row that predates the column).
1112 FOR $q IN ((SELECT id, choices, correct FROM exam_question
1113 WHERE choices[0] != NONE AND type::is_string(choices[0])) ?? []) {
1114 LET $new = $q.choices.map(|$c| { id: rand::ulid(), text: $c });
1115 UPDATE $q.id SET choices = $new,
1116 correct = IF $q.correct = NONE { NONE } ELSE { $new[$q.correct].id };
1117 FOR $img IN ((SELECT id, slot FROM question_image
1118 WHERE question = $q.id AND type::is_int(slot)) ?? []) {
1119 UPDATE $img.id SET slot = $new[$img.slot].id;
1120 };
1121 FOR $ans IN ((SELECT id, selected FROM exam_answer
1122 WHERE question = $q.id AND type::is_int(selected)) ?? []) {
1123 UPDATE $ans.id SET selected = $new[$ans.selected].id, seq = seq ?? 1;
1124 };
1125 };
1126
1127 FOR $q IN ((SELECT id, choices, correct FROM bank_question
1128 WHERE choices[0] != NONE AND type::is_string(choices[0])) ?? []) {
1129 LET $new = $q.choices.map(|$c| { id: rand::ulid(), text: $c });
1130 UPDATE $q.id SET choices = $new,
1131 correct = IF $q.correct = NONE { NONE } ELSE { $new[$q.correct].id };
1132 FOR $img IN ((SELECT id, slot FROM bank_question_image
1133 WHERE bank_question = $q.id AND type::is_int(slot)) ?? []) {
1134 UPDATE $img.id SET slot = $new[$img.slot].id;
1135 };
1136 };
1137
1138 -- Per-attempt history (2026-07-24): sittings, answers, drawings, and marks
1139 -- written before retakes stopped wiping belong to the student's first
1140 -- sitting. They already use the bare (seq==1) record key, so only the
1141 -- denormalized `seq` field needs stamping.
1142 --
1143 -- `exam_attempt` was left out of this list when the other three were added
1144 -- and that is not a decision, it is a gap: `DEFAULT 1` fills a CREATE, never
1145 -- a row stored before the column was defined, and 3.2.3 does not synthesize
1146 -- it on read either — such a row comes back with no `seq` key at all, which
1147 -- makes `ExamAttempt` (a non-`option` `i64`) fail to deserialize *and* makes
1148 -- every later write to the row fail coercion, so finishing or leaving that
1149 -- sitting 500s forever. Ungated like its siblings and for the same reason:
1150 -- the cost here is the write, not a scan, and `WHERE seq = NONE` matches
1151 -- nothing the moment it has converged.
1152 UPDATE exam_attempt SET seq = 1 WHERE seq = NONE;
1153 UPDATE exam_answer SET seq = 1 WHERE seq = NONE;
1154 UPDATE answer_image SET seq = 1 WHERE seq = NONE;
1155 UPDATE exam_result SET seq = 1 WHERE seq = NONE;
1156
1157 -- The homework freeze became cross-replica (2026-07-27): a grade that
1158 -- predates the stamp column has to put it on the submission it already
1159 -- froze, or that submission would read as open and be editable again.
1160 -- Result and submission share the deterministic `{homework}_{user}` key, so
1161 -- the owning row is addressed directly rather than searched for; an UPDATE
1162 -- of a record that isn't there (graded absent work) is an empty no-op. The
1163 -- `= NONE` guard keeps it one-time, for the same reason the counters below
1164 -- are one-time — migrate() runs again on every boot against a volume the
1165 -- live system has been writing to since.
1166 FOR $r IN ((SELECT VALUE id FROM homework_result) ?? []) {
1167 UPDATE type::record('homework_submission', record::id($r))
1168 SET graded_by_result = $r WHERE graded_by_result = NONE;
1169 };
1170
1171 -- Count caps became cross-replica (2026-07-27): the authority moved from a
1172 -- process-wide mutex to a counter column on the parent row, so every parent
1173 -- that predates the column is seeded from the children it actually has.
1174 -- Runs LAST, after the sweeps above have deleted whatever they delete.
1175 --
1176 -- Deliberately one-time (`= NONE` guards every write): migrate() reruns on
1177 -- every boot of an existing volume, and recounting a seeded counter would
1178 -- overwrite what the live system has maintained since. An absent
1179 -- counter reads as zero, so the group pass runs before the zero pass.
1180 FOR $row IN ((SELECT course, count() AS n FROM enrollment GROUP BY course) ?? []) {
1181 UPDATE $row.course SET enrollment_count = $row.n WHERE enrollment_count = NONE;
1182 };
1183 UPDATE course SET enrollment_count = 0 WHERE enrollment_count = NONE;
1184
1185 -- The one refcount among them: courses per term, not children per parent.
1186 -- Same one-time `= NONE` guard, and `WHERE term != NONE` keeps the
1187 -- unlinked courses out of the group (they would form a NONE bucket).
1188 FOR $row IN ((SELECT term, count() AS n FROM course WHERE term != NONE GROUP BY term) ?? []) {
1189 UPDATE $row.term SET course_count = $row.n WHERE course_count = NONE;
1190 };
1191 UPDATE term SET course_count = 0 WHERE course_count = NONE;
1192
1193 FOR $row IN ((SELECT event, count() AS n FROM registration GROUP BY event) ?? []) {
1194 UPDATE $row.event SET registration_count = $row.n WHERE registration_count = NONE;
1195 };
1196 UPDATE event SET registration_count = 0 WHERE registration_count = NONE;
1197
1198 FOR $row IN ((SELECT note, count() AS n FROM note_file GROUP BY note) ?? []) {
1199 UPDATE $row.note SET file_count = $row.n WHERE file_count = NONE;
1200 };
1201 UPDATE note SET file_count = 0 WHERE file_count = NONE;
1202
1203 FOR $row IN ((SELECT submission, count() AS n FROM homework_file GROUP BY submission) ?? []) {
1204 UPDATE $row.submission SET file_count = $row.n WHERE file_count = NONE;
1205 };
1206 UPDATE homework_submission SET file_count = 0 WHERE file_count = NONE;
1207
1208 FOR $row IN ((SELECT user_id, count() AS n FROM chatbot_thread GROUP BY user_id) ?? []) {
1209 UPDATE $row.user_id SET chatbot_thread_count = $row.n WHERE chatbot_thread_count = NONE;
1210 };
1211 UPDATE user SET chatbot_thread_count = 0 WHERE chatbot_thread_count = NONE;
1212
1213 -- The appointment slot's counter is the odd one out: it counts only the
1214 -- bookings that are still *live*, because a rejected or cancelled one gave
1215 -- the slot back long before this column existed.
1216 FOR $row IN ((SELECT slot, count() AS n FROM appointment
1217 WHERE status IN ['pending', 'approved'] GROUP BY slot) ?? []) {
1218 UPDATE $row.slot SET occupied = $row.n WHERE occupied = NONE;
1219 };
1220 UPDATE appointment_slot SET occupied = 0 WHERE occupied = NONE;
1221
1222 -- A menu's seats, counted from the bookings still *held* — a cancelled one
1223 -- gave its seat back before this column existed, exactly like the slot
1224 -- above. `version` gets no pass at all: absent already reads as revision
1225 -- zero everywhere it is compared, so writing it would be a no-op that
1226 -- touches every menu row.
1227 FOR $row IN ((SELECT menu, count() AS n FROM meal_booking
1228 WHERE status = 'booked' GROUP BY menu) ?? []) {
1229 UPDATE $row.menu SET seats_booked = $row.n WHERE seats_booked = NONE;
1230 };
1231 UPDATE menu SET seats_booked = 0 WHERE seats_booked = NONE;
1232
1233 -- A subject's two reference counters, seeded from what actually points at
1234 -- it. This must run *after* the legacy sweep above destroys the questions
1235 -- that predate subjects, or a subject would be seeded with rows that are
1236 -- about to vanish and could then never be deleted. No zero pass, for the
1237 -- same reason `version` gets none: absent already reads as zero in the
1238 -- delete's `(count ?? 0) = 0` guard, so writing it would touch every
1239 -- subject row to say what it already says.
1240 FOR $row IN ((SELECT subject, count() AS n FROM exam_question GROUP BY subject) ?? []) {
1241 UPDATE $row.subject SET exam_question_count = $row.n WHERE exam_question_count = NONE;
1242 };
1243
1244 FOR $row IN ((SELECT subject, count() AS n FROM homework GROUP BY subject) ?? []) {
1245 UPDATE $row.subject SET homework_count = $row.n WHERE homework_count = NONE;
1246 };
1247
1248 -- The settings guards became cross-replica the same way (2026-07-27): an
1249 -- exam kind counts the marks written under it, a meal slot the menus
1250 -- published for it, and a name is removable exactly while its counter reads
1251 -- zero. Rows written before the counters existed are counted once here.
1252 --
1253 -- Same `= NONE` guard and the same reason as the caps above: migrate()
1254 -- reruns on every boot of an existing volume, and recounting a seeded
1255 -- counter would overwrite what the live system has maintained since, handing
1256 -- back a reference that is still held. No zero pass either — an
1257 -- absent counter already reads as zero, and a name nobody ever used needs
1258 -- no row at all.
1259 --
1260 -- Marks predate the counter but so may their *kind*: an exam whose kind was
1261 -- removed from the list long ago is counted too, which only ever refuses a
1262 -- removal that already happened. `slot` is text on the menu, so its group
1263 -- needs no join; `kind` lives on the exam, one hop from the mark.
1264 FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result GROUP BY kind) ?? []) {
1265 UPSERT type::record('kind_ref', $row.kind) SET count = $row.n WHERE count = NONE;
1266 };
1267
1268 FOR $row IN ((SELECT slot, count() AS n FROM menu GROUP BY slot) ?? []) {
1269 UPSERT type::record('slot_ref', $row.slot) SET count = $row.n WHERE count = NONE;
1270 };
1271
1272 -- Same one-time seeding for the per-exam mark counter: an exam graded by an
1273 -- older binary must read as graded, or its kind could be changed under the
1274 -- marks it already carries.
1275 FOR $row IN ((SELECT exam, count() AS n FROM exam_result GROUP BY exam) ?? []) {
1276 UPDATE $row.exam SET result_count = $row.n WHERE result_count = NONE;
1277 };
1278
1279 -- The fee-plan guard became a refcount (2026-07-30): editing or deleting a
1280 -- plan is now refused by `(assignment_count ?? 0) = 0` on the plan row
1281 -- itself, instead of by a scan a concurrent assign could land behind.
1282 --
1283 -- This seeding is what keeps a *stale* volume safe: a plan written by an
1284 -- older binary carries no counter, an absent counter reads as zero, and a
1285 -- zero would make an already-assigned plan editable and deletable again —
1286 -- the exact thing the 409 exists to prevent. Boot seeds it from the
1287 -- assignment rows that actually exist, and `migrate` runs to completion
1288 -- before the router is bound, so no request is ever served against the
1289 -- unseeded shape. `= NONE` keeps it one-time, so a second boot recomputes
1290 -- nothing.
1291 --
1292 -- No zero pass, for the same reason the subject counters get none: a plan
1293 -- nobody is on has no assignment rows, and absent already reads as zero in
1294 -- the guard — writing it would touch every plan row to say what it says.
1295 FOR $row IN ((SELECT plan, count() AS n FROM fee_plan_assignment GROUP BY plan) ?? []) {
1296 UPDATE $row.plan SET assignment_count = $row.n WHERE assignment_count = NONE;
1297 };
1298
1299 -- The clear marker began paying the board's lifetime counter (2026-08-02):
1300 -- it is a real `board_stroke` row, so a marker that charged nothing left
1301 -- `total_stroke_count` counting marks *drawn* instead of rows *stored*, and
1302 -- every board an older binary cleared is short exactly one per past clear.
1303 --
1304 -- The only repair here that is NOT `= NONE`-guarded, and the one counter
1305 -- that may be: it is not an opinion the live system maintains, it is the
1306 -- board's row count — every stroke and every marker charges 1, and a stroke
1307 -- row is only ever deleted with the board itself (domain::board_stroke).
1308 -- So recomputing converges instead of overwriting, and `!= $row.n` writes
1309 -- nothing on the next boot, when every counter already equals its count.
1310 -- No zero pass: a board nobody drew on forms no group, and an absent
1311 -- counter already reads as zero through the `?? 0` every reader applies.
1312 FOR $row IN ((SELECT board, count() AS n FROM board_stroke GROUP BY board) ?? []) {
1313 UPDATE $row.board SET total_stroke_count = $row.n WHERE total_stroke_count != $row.n;
1314 };
1315
1316 -- Board rosters became self-repairing (2026-08-02). `set_role` sweeps a
1317 -- demoted user off every board *going forward*, but a volume written before
1318 -- that sweep still holds rosters naming parents — and ids of users who have
1319 -- since been deleted outright, which no sweep ever covered.
1320 --
1321 -- It is not a cosmetic staleness: the roster is served back on every read
1322 -- and `resolve_participants` refuses an id that no longer resolves to a
1323 -- student-or-above, so the creator's next read-modify-write roster PATCH
1324 -- echoes the stale id and takes a 400 — the board's invite list is frozen
1325 -- until the row is repaired.
1326 --
1327 -- `parent` is the only role below `student` (domain::role), so `!= 'parent'`
1328 -- is the same cut `Role::at_least(Student)` makes; a missing user matches no
1329 -- row and so falls out of `$keep` for free. A board whose whole roster is
1330 -- stale ends with `participants = []` — the creator alone on it, which is
1331 -- the same shape a board created without invites carries. Not `= NONE`
1332 -- guarded and it need not be: `$keep` is derived from the rows that exist,
1333 -- so it converges, and `WHERE participants != $keep` writes nothing on the
1334 -- next boot. `$keep` comes back deduped and in record-id order, so a
1335 -- repaired row can be *reordered* relative to what it stored, never
1336 -- duplicated — and the roster is a set to every reader.
1337 --
1338 -- Marked one-time (`migration_mark`), unlike every backfill above it. Those
1339 -- converge to a `WHERE` that matches nothing, so their second run is a cheap
1340 -- index probe; this one's cost is the *scan* — a `board` table scan whose
1341 -- body runs a full `user` scan per row, measured at 773ms for 300 boards
1342 -- over 2000 users on a boot with nothing left to write. That is paid on
1343 -- every restart forever, and it buys nothing: `set_role` sweeps rosters
1344 -- going forward and a deleted user is swept with its row, so no new stale id
1345 -- is ever created. The mark is written *after* the loop and in the same
1346 -- statement batch, so a boot killed mid-repair writes no mark and the next
1347 -- one redoes the whole sweep — which is free, because the sweep is
1348 -- idempotent. `UPSERT`, not `CREATE`: re-marking must never be an error.
1349 --
1350 -- Editing this block is therefore safe at any time: the fingerprint gate
1351 -- re-runs it once and the sweep converges on whatever it finds, exactly as
1352 -- a boot killed mid-repair would. The mark buys the scan back, not
1353 -- correctness.
1354 IF array::len((SELECT VALUE id FROM migration_mark:board_roster
1355 WHERE fingerprint = $fp_board_roster)) = 0 {
1356 FOR $row IN ((SELECT id, participants FROM board WHERE array::len(participants ?? []) > 0) ?? []) {
1357 LET $keep = (SELECT VALUE id FROM user WHERE id IN $row.participants AND role != 'parent');
1358 UPDATE $row.id SET participants = $keep WHERE participants != $keep;
1359 };
1360 UPSERT migration_mark:board_roster SET done_at = time::unix(time::now()) * 1000,
1361 fingerprint = $fp_board_roster;
1362 };
1363
1364 -- The badge counters, seeded from the history that already exists
1365 -- (2026-08-04). Badges are earned off stored lifetime totals, and every
1366 -- account on an existing volume predates the columns — so starting them all
1367 -- at zero would not merely lose a number, it would mis-award every student
1368 -- permanently: someone who really handed in 40 homeworks would owe 10 *more*
1369 -- than a new account does to reach the same badge. The counts below are the
1370 -- rows that exist, so the seed says exactly what the student did.
1371 --
1372 -- Marked one-time, like the board-roster sweep above and unlike every other
1373 -- backfill in this file — but for the opposite reason. Those recompute a
1374 -- number the live system does not own; these columns are maintained by the
1375 -- request path from here on (a submission increments as it lands), so a
1376 -- second recount would not converge, it would *overwrite* everything earned
1377 -- since boot. The mark is the only thing that makes that safe.
1378 --
1379 -- The reset is inside the mark and comes first, so the whole block is
1380 -- recompute-from-scratch: a boot killed mid-seed writes no mark and the next
1381 -- one redoes it from a clean slate, and an operator who clears the mark to
1382 -- force a re-seed gets the counts as they stand rather than a stale high
1383 -- water mark. It is the one place a *zero pass* is right: it writes over
1384 -- whatever a half-finished pass left, and it runs exactly once per volume.
1385 --
1386 -- Every counter here has to *mean* what the request path means, or a
1387 -- pre-existing student diverges from a new one forever. So the on-time cut
1388 -- is `submitted_at <= due_at`, the stamp both live sites use: the create
1389 -- credits on the first hand-in and the delete debits by `submitted_at`, so
1390 -- judging the seed by `updated_at` would let a withdrawal decrement a
1391 -- submission the seed never credited and drive the counter *below* the
1392 -- truth — and `touch()` moves `updated_at` on every file add or delete, so
1393 -- merely attaching a file after the deadline would have done it. A dangling
1394 -- `homework` link still falls out of the pass rather than counting as on
1395 -- time (the traversal yields no value, so the comparison fails).
1396 --
1397 -- The focus sum floors *per row*, like the live close does
1398 -- (`math::max([started_at, done])`), not per user: a legacy stint written
1399 -- with a backwards clock is negative, and flooring the total instead would
1400 -- let one such row swallow the real stints beside it. `math::max` *around*
1401 -- the aggregate is the spelling that is rejected ('nested aggregate
1402 -- functions are not supported'); inside it, per row, is fine.
1403 --
1404 -- Two counters the seed cannot make whole, for the same reason:
1405 -- `exam_sat_total` (deleting an exam or a course deletes its `exam_attempt`
1406 -- rows) and `homework_submitted_total` (deleting a homework cascades its
1407 -- `homework_submission` rows away). Neither delete decrements — deliberate,
1408 -- a lifetime 'did it' tally must not shrink because a teacher tidied up — so
1409 -- the live count stands where the request path left it while a re-seed of
1410 -- the same volume would read *lower*: the rows do not exist to be counted.
1411 -- Do not 'repair' this by making the live path decrement; that breaks the
1412 -- tally for everyone to patch history for a few.
1413 --
1414 -- `counted_on_time` is stamped here too, for every row the pass looks at and
1415 -- by the very same cut, so a submission that predates this seed debits at
1416 -- withdrawal exactly what the seed credited it. Absolute like every SET
1417 -- below, so it converges on a forced re-seed.
1418 --
1419 -- corner-cut: editing this block re-runs it (the fingerprint gate), and unlike
1420 -- the board sweep above this one is only *mostly* re-runnable. Every SET is
1421 -- absolute, so a re-run converges on the rows that exist — but two of the
1422 -- counters are lifetime tallies the request path never decrements while the
1423 -- rows behind them can be deleted (`exam_sat_total`,
1424 -- `homework_submitted_total`, see the paragraph above). On a volume where a
1425 -- teacher has deleted an exam or a homework since the last seed, a re-run
1426 -- reads *lower* than the live count and the student's tally walks backwards
1427 -- — badges already awarded are permanent, so nothing is revoked, but the
1428 -- next one moves further away. Correcting this block is a deliberate trade,
1429 -- not a free edit. The upgrade path, if it ever needs to be free: keep the
1430 -- deleted rows' contribution on the row (a `*_retired` column the delete
1431 -- bumps) so the recount can add it back.
1432 IF array::len((SELECT VALUE id FROM migration_mark:profile_counters
1433 WHERE fingerprint = $fp_profile_counters)) = 0 {
1434 UPDATE user SET homework_submitted_total = 0, homework_on_time_total = 0,
1435 exam_sat_total = 0, pomodoro_finished_total = 0, pomodoro_focus_ms_total = 0;
1436 FOR $row IN ((SELECT user, count() AS n FROM homework_submission GROUP BY user) ?? []) {
1437 UPDATE $row.user SET homework_submitted_total = $row.n;
1438 };
1439 FOR $row IN ((SELECT user, count() AS n FROM homework_submission
1440 WHERE submitted_at <= homework.due_at GROUP BY user) ?? []) {
1441 UPDATE $row.user SET homework_on_time_total = $row.n;
1442 };
1443 UPDATE homework_submission SET counted_on_time = submitted_at <= homework.due_at;
1444 -- `(seq ?? 1) = 1` is one row per (exam, student) pair, so this counts
1445 -- *exams sat* — what the request path credits (a retake writes a higher
1446 -- seq and moves nothing). Counting every row instead would seed a
1447 -- pre-existing student above a new one for the same work, and above
1448 -- what the live path would ever give them again.
1449 FOR $row IN ((SELECT user, count() AS n FROM exam_attempt
1450 WHERE (seq ?? 1) = 1 GROUP BY user) ?? []) {
1451 UPDATE $row.user SET exam_sat_total = $row.n;
1452 };
1453 FOR $row IN ((SELECT user, count() AS sessions,
1454 math::sum(math::max([finished_at - started_at, 0])) AS focus_ms
1455 FROM pomodoro_session WHERE finished_at != NONE GROUP BY user) ?? []) {
1456 UPDATE $row.user SET pomodoro_finished_total = $row.sessions,
1457 pomodoro_focus_ms_total = $row.focus_ms;
1458 };
1459 UPSERT migration_mark:profile_counters SET done_at = time::unix(time::now()) * 1000,
1460 fingerprint = $fp_profile_counters;
1461 };
1462";
1463
1464/// The **control** database's schema — the one database per deployment that
1465/// knows which schools exist and who may create them. Everything else lives in
1466/// a school database, whose schema is [`MIGRATION_BATCHES`] and is applied
1467/// per school by [`crate::tenant::Tenants::create`].
1468///
1469/// The `rate_limit` copy is deliberate: the shared per-IP window
1470/// (`crate::rate_limit::RateLimiter::share`) is billed against the control
1471/// handle, because the limiter runs in front of the router — before any cookie
1472/// has named a school. One budget per deployment is also the honest one for an
1473/// unauthenticated brute-forcer, who has not picked a school yet either.
1474pub const CONTROL_MIGRATION: &str = "
1475 DEFINE TABLE IF NOT EXISTS school SCHEMAFULL;
1476 DEFINE FIELD IF NOT EXISTS slug ON school TYPE string;
1477 DEFINE FIELD IF NOT EXISTS name ON school TYPE string;
1478 DEFINE FIELD IF NOT EXISTS status ON school TYPE string;
1479 DEFINE FIELD IF NOT EXISTS created_at ON school TYPE int;
1480 -- Which product modules this school has bought (see `crate::module`). The
1481 -- names are bound from `Module::ALL`, never spelled here, so a new module
1482 -- cannot be forgotten in this string.
1483 DEFINE FIELD IF NOT EXISTS modules ON school TYPE array<string> DEFAULT [];
1484 -- Only `NONE` — a row written before the field existed, which predates the
1485 -- idea of buying modules and so had all of them. An empty array is a
1486 -- deliberate \"nothing enabled\" and must never be re-widened by a boot.
1487 UPDATE school SET modules = $all_modules WHERE modules = NONE;
1488 -- Redundant with the `school:<slug>` id, and kept anyway: the id is the
1489 -- fast path, the index is what makes a second row on the same slug
1490 -- impossible if a future write ever mints an id some other way.
1491 DEFINE INDEX IF NOT EXISTS school_slug ON school FIELDS slug UNIQUE;
1492
1493 DEFINE TABLE IF NOT EXISTS builder SCHEMAFULL;
1494 DEFINE FIELD IF NOT EXISTS username ON builder TYPE string;
1495 DEFINE FIELD IF NOT EXISTS password_hash ON builder TYPE string;
1496 DEFINE INDEX IF NOT EXISTS builder_username ON builder FIELDS username UNIQUE;
1497
1498 DEFINE TABLE IF NOT EXISTS builder_session SCHEMAFULL;
1499 DEFINE FIELD IF NOT EXISTS builder ON builder_session TYPE record<builder>;
1500 DEFINE FIELD IF NOT EXISTS token ON builder_session TYPE string;
1501 DEFINE FIELD IF NOT EXISTS created_at ON builder_session TYPE int;
1502 DEFINE FIELD IF NOT EXISTS expires_at ON builder_session TYPE int;
1503 DEFINE INDEX IF NOT EXISTS builder_session_token ON builder_session FIELDS token UNIQUE;
1504 DEFINE INDEX IF NOT EXISTS builder_session_expires ON builder_session FIELDS expires_at;
1505
1506 -- Verbatim from `MIGRATION`; see the note above this constant.
1507 DEFINE TABLE IF NOT EXISTS rate_limit SCHEMAFULL;
1508 DEFINE FIELD IF NOT EXISTS hits ON rate_limit TYPE int DEFAULT 0;
1509 DEFINE FIELD IF NOT EXISTS window_start ON rate_limit TYPE int;
1510";
1511
1512pub const CONTROL_MIGRATION_BATCHES: [&str; 1] = [CONTROL_MIGRATION];
1513
1514/// The migration batches, in the order a boot applies them — and the *only*
1515/// list of them. [`crate::database::migrate`] runs exactly these. They stay
1516/// three separate queries: statements in one batch see the schema as it stood
1517/// when the batch started (see `MIGRATION`).
1518pub const MIGRATION_BATCHES: [&str; 3] = [PRE_REPAIR, MIGRATION, BACKFILL];