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