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