diff --git a/.sqlx/query-00a2401b3c5acee26088b2f978927c983a73f8e8ff47ca6208a429958aec8a73.json b/.sqlx/query-00a2401b3c5acee26088b2f978927c983a73f8e8ff47ca6208a429958aec8a73.json new file mode 100644 index 0000000..be818b0 --- /dev/null +++ b/.sqlx/query-00a2401b3c5acee26088b2f978927c983a73f8e8ff47ca6208a429958aec8a73.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE class_course\n SET enrollment_count = GREATEST(enrollment_count - 1, 0)\n WHERE id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "00a2401b3c5acee26088b2f978927c983a73f8e8ff47ca6208a429958aec8a73" +} diff --git a/.sqlx/query-df95611307c9d494f12fef5d18258482330944d43abde0416a9c9ad368e68927.json b/.sqlx/query-01b0ff298ce9661c87b0fd82d01eca7b6f2912a98fe0b580ce237ab3754fde84.json similarity index 73% rename from .sqlx/query-df95611307c9d494f12fef5d18258482330944d43abde0416a9c9ad368e68927.json rename to .sqlx/query-01b0ff298ce9661c87b0fd82d01eca7b6f2912a98fe0b580ce237ab3754fde84.json index 0613051..78fe724 100644 --- a/.sqlx/query-df95611307c9d494f12fef5d18258482330944d43abde0416a9c9ad368e68927.json +++ b/.sqlx/query-01b0ff298ce9661c87b0fd82d01eca7b6f2912a98fe0b580ce237ab3754fde84.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: ExamId\", creator AS \"creator: UserId\", course AS \"course: CourseId\",\n title AS \"title: ExamTitle\", description AS \"description: ExamDescription\",\n kind AS \"kind: ExamKind\", mode AS \"mode: ExamMode\",\n starts_at AS \"starts_at: Timestamp\",\n ends_at AS \"ends_at: Timestamp\",\n duration_ms AS \"duration_ms: ExamDuration\",\n max_attempts AS \"max_attempts: ExamAttemptLimit\",\n allow_rejoin, allow_review, draft\n FROM exam WHERE id = $1", + "query": "SELECT DISTINCT ON (e.id)\n e.id AS \"id: ExamId\", e.creator AS \"creator: UserId\",\n e.class_course AS \"class_course: ClassCourseId\",\n e.term AS \"term: TermId\", e.title AS \"title: ExamTitle\",\n e.description AS \"description: ExamDescription\",\n e.kind AS \"kind: ExamKind\", e.mode AS \"mode: ExamMode\",\n e.starts_at AS \"starts_at: Timestamp\",\n e.ends_at AS \"ends_at: Timestamp\",\n e.duration_ms AS \"duration_ms: ExamDuration\",\n e.max_attempts AS \"max_attempts: ExamAttemptLimit\",\n e.allow_rejoin, e.allow_review, e.draft\n FROM exam e\n JOIN exam_audience a ON a.exam = e.id\n WHERE a.class_course = $1\n ORDER BY e.id DESC", "describe": { "columns": [ { @@ -27,17 +27,28 @@ }, { "ordinal": 2, - "name": "course: CourseId", + "name": "class_course: ClassCourseId", "type_info": "Uuid", "origin": { "Table": { "table": "exam", - "name": "course" + "name": "class_course" } } }, { "ordinal": 3, + "name": "term: TermId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "exam", + "name": "term" + } + } + }, + { + "ordinal": 4, "name": "title: ExamTitle", "type_info": "Text", "origin": { @@ -48,7 +59,7 @@ } }, { - "ordinal": 4, + "ordinal": 5, "name": "description: ExamDescription", "type_info": "Text", "origin": { @@ -59,7 +70,7 @@ } }, { - "ordinal": 5, + "ordinal": 6, "name": "kind: ExamKind", "type_info": "Text", "origin": { @@ -70,7 +81,7 @@ } }, { - "ordinal": 6, + "ordinal": 7, "name": "mode: ExamMode", "type_info": "Text", "origin": { @@ -81,7 +92,7 @@ } }, { - "ordinal": 7, + "ordinal": 8, "name": "starts_at: Timestamp", "type_info": "Int8", "origin": { @@ -92,7 +103,7 @@ } }, { - "ordinal": 8, + "ordinal": 9, "name": "ends_at: Timestamp", "type_info": "Int8", "origin": { @@ -103,7 +114,7 @@ } }, { - "ordinal": 9, + "ordinal": 10, "name": "duration_ms: ExamDuration", "type_info": "Int8", "origin": { @@ -114,7 +125,7 @@ } }, { - "ordinal": 10, + "ordinal": 11, "name": "max_attempts: ExamAttemptLimit", "type_info": "Int8", "origin": { @@ -125,7 +136,7 @@ } }, { - "ordinal": 11, + "ordinal": 12, "name": "allow_rejoin", "type_info": "Bool", "origin": { @@ -136,7 +147,7 @@ } }, { - "ordinal": 12, + "ordinal": 13, "name": "allow_review", "type_info": "Bool", "origin": { @@ -147,7 +158,7 @@ } }, { - "ordinal": 13, + "ordinal": 14, "name": "draft", "type_info": "Bool", "origin": { @@ -170,6 +181,7 @@ false, false, false, + false, true, true, true, @@ -180,5 +192,5 @@ false ] }, - "hash": "df95611307c9d494f12fef5d18258482330944d43abde0416a9c9ad368e68927" + "hash": "01b0ff298ce9661c87b0fd82d01eca7b6f2912a98fe0b580ce237ab3754fde84" } diff --git a/.sqlx/query-7eb71ec5abefdb8a1a70959e9f639cd4bc24913d0c44ee7739961329086d629d.json b/.sqlx/query-03f5c694634477fdaa10fc15662f1a31b6f132f5998e41991e758e76bd521bab.json similarity index 57% rename from .sqlx/query-7eb71ec5abefdb8a1a70959e9f639cd4bc24913d0c44ee7739961329086d629d.json rename to .sqlx/query-03f5c694634477fdaa10fc15662f1a31b6f132f5998e41991e758e76bd521bab.json index e4a1ad1..4d70fb2 100644 --- a/.sqlx/query-7eb71ec5abefdb8a1a70959e9f639cd4bc24913d0c44ee7739961329086d629d.json +++ b/.sqlx/query-03f5c694634477fdaa10fc15662f1a31b6f132f5998e41991e758e76bd521bab.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT 1 AS \"one\" FROM course WHERE id = $1", + "query": "UPDATE class_course SET enrollment_count = enrollment_count + 1\n WHERE id = $1\n RETURNING 1 AS \"one\"", "describe": { "columns": [ { @@ -19,5 +19,5 @@ null ] }, - "hash": "7eb71ec5abefdb8a1a70959e9f639cd4bc24913d0c44ee7739961329086d629d" + "hash": "03f5c694634477fdaa10fc15662f1a31b6f132f5998e41991e758e76bd521bab" } diff --git a/.sqlx/query-6098baf8e32ee3c6eb3bd37515b930c0ce298bc70225c495d101fd61ea326466.json b/.sqlx/query-0571110cc25b54c354dd07addbc04cfc921361ef0adfda6c4bf7fd7b2030acd5.json similarity index 75% rename from .sqlx/query-6098baf8e32ee3c6eb3bd37515b930c0ce298bc70225c495d101fd61ea326466.json rename to .sqlx/query-0571110cc25b54c354dd07addbc04cfc921361ef0adfda6c4bf7fd7b2030acd5.json index 4d17f76..f65a11f 100644 --- a/.sqlx/query-6098baf8e32ee3c6eb3bd37515b930c0ce298bc70225c495d101fd61ea326466.json +++ b/.sqlx/query-0571110cc25b54c354dd07addbc04cfc921361ef0adfda6c4bf7fd7b2030acd5.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT session AS \"session: CourseSessionId\", app_user AS \"user: UserId\",\n course AS \"course: CourseId\", status AS \"status: AttendanceStatus\",\n marked_by AS \"marked_by: UserId\"\n FROM session_attendance\n WHERE session = $1 AND app_user = $2\n FOR UPDATE", + "query": "SELECT session AS \"session: CourseSessionId\", app_user AS \"user: UserId\",\n class_course AS \"class_course: ClassCourseId\",\n status AS \"status: AttendanceStatus\",\n marked_by AS \"marked_by: UserId\"\n FROM session_attendance WHERE app_user = $1\n ORDER BY session DESC, app_user DESC", "describe": { "columns": [ { @@ -27,12 +27,12 @@ }, { "ordinal": 2, - "name": "course: CourseId", + "name": "class_course: ClassCourseId", "type_info": "Uuid", "origin": { "Table": { "table": "session_attendance", - "name": "course" + "name": "class_course" } } }, @@ -61,7 +61,6 @@ ], "parameters": { "Left": [ - "Uuid", "Uuid" ] }, @@ -73,5 +72,5 @@ false ] }, - "hash": "6098baf8e32ee3c6eb3bd37515b930c0ce298bc70225c495d101fd61ea326466" + "hash": "0571110cc25b54c354dd07addbc04cfc921361ef0adfda6c4bf7fd7b2030acd5" } diff --git a/.sqlx/query-ea7ff9d9a99aaab7958441ece5fd6ab36bd33ad09c12a0b8668cc3c084237be8.json b/.sqlx/query-07855fc52d457a8d9e5e10ad3997ba433fcce7d204d713b52303ef109795998c.json similarity index 53% rename from .sqlx/query-ea7ff9d9a99aaab7958441ece5fd6ab36bd33ad09c12a0b8668cc3c084237be8.json rename to .sqlx/query-07855fc52d457a8d9e5e10ad3997ba433fcce7d204d713b52303ef109795998c.json index 14759a5..dd6f59f 100644 --- a/.sqlx/query-ea7ff9d9a99aaab7958441ece5fd6ab36bd33ad09c12a0b8668cc3c084237be8.json +++ b/.sqlx/query-07855fc52d457a8d9e5e10ad3997ba433fcce7d204d713b52303ef109795998c.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "DELETE FROM enrollment WHERE course = $1", + "query": "DELETE FROM class_member WHERE class = $1", "describe": { "columns": [], "parameters": { @@ -10,5 +10,5 @@ }, "nullable": [] }, - "hash": "ea7ff9d9a99aaab7958441ece5fd6ab36bd33ad09c12a0b8668cc3c084237be8" + "hash": "07855fc52d457a8d9e5e10ad3997ba433fcce7d204d713b52303ef109795998c" } diff --git a/.sqlx/query-97201bc98edb694a2e07d8da4fd91718e519bfe092a9cdb735d65f654da2f58d.json b/.sqlx/query-08f24207b6ab068c44d1d0728d3bbac39f2b341ea5ecb24040b051f5f4862c49.json similarity index 67% rename from .sqlx/query-97201bc98edb694a2e07d8da4fd91718e519bfe092a9cdb735d65f654da2f58d.json rename to .sqlx/query-08f24207b6ab068c44d1d0728d3bbac39f2b341ea5ecb24040b051f5f4862c49.json index 417b36d..245c0cc 100644 --- a/.sqlx/query-97201bc98edb694a2e07d8da4fd91718e519bfe092a9cdb735d65f654da2f58d.json +++ b/.sqlx/query-08f24207b6ab068c44d1d0728d3bbac39f2b341ea5ecb24040b051f5f4862c49.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO session_attendance (session, app_user, course, status, marked_by, marked_at)\n VALUES ($1, $2, $3, $4, $5, $6)\n ON CONFLICT (session, app_user) DO UPDATE\n SET status = EXCLUDED.status, marked_by = EXCLUDED.marked_by,\n marked_at = EXCLUDED.marked_at\n RETURNING session AS \"session: CourseSessionId\", app_user AS \"user: UserId\",\n course AS \"course: CourseId\", status AS \"status: AttendanceStatus\",\n marked_by AS \"marked_by: UserId\"", + "query": "INSERT INTO session_attendance (session, app_user, class_course, status, marked_by, marked_at)\n VALUES ($1, $2, $3, $4, $5, $6)\n ON CONFLICT (session, app_user) DO UPDATE\n SET status = EXCLUDED.status, marked_by = EXCLUDED.marked_by,\n marked_at = EXCLUDED.marked_at\n RETURNING session AS \"session: CourseSessionId\", app_user AS \"user: UserId\",\n class_course AS \"class_course: ClassCourseId\",\n status AS \"status: AttendanceStatus\",\n marked_by AS \"marked_by: UserId\"", "describe": { "columns": [ { @@ -27,12 +27,12 @@ }, { "ordinal": 2, - "name": "course: CourseId", + "name": "class_course: ClassCourseId", "type_info": "Uuid", "origin": { "Table": { "table": "session_attendance", - "name": "course" + "name": "class_course" } } }, @@ -77,5 +77,5 @@ false ] }, - "hash": "97201bc98edb694a2e07d8da4fd91718e519bfe092a9cdb735d65f654da2f58d" + "hash": "08f24207b6ab068c44d1d0728d3bbac39f2b341ea5ecb24040b051f5f4862c49" } diff --git a/.sqlx/query-81b4c9db5438f7ef71b99fd3b6708567d54c1e79ab50e00647543dc20b44a512.json b/.sqlx/query-092906c006f4b98f4e115c3d35605b690d0493d9efb3e9e38f444900a2fd10da.json similarity index 70% rename from .sqlx/query-81b4c9db5438f7ef71b99fd3b6708567d54c1e79ab50e00647543dc20b44a512.json rename to .sqlx/query-092906c006f4b98f4e115c3d35605b690d0493d9efb3e9e38f444900a2fd10da.json index 7f15464..b8fff75 100644 --- a/.sqlx/query-81b4c9db5438f7ef71b99fd3b6708567d54c1e79ab50e00647543dc20b44a512.json +++ b/.sqlx/query-092906c006f4b98f4e115c3d35605b690d0493d9efb3e9e38f444900a2fd10da.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT ai.file FROM answer_image ai\n JOIN exam e ON e.id = ai.exam WHERE e.course = $1", + "query": "SELECT ai.file FROM answer_image ai\n JOIN exam e ON e.id = ai.exam\n JOIN class_course cc ON cc.id = e.class_course\n WHERE cc.course = $1", "describe": { "columns": [ { @@ -24,5 +24,5 @@ false ] }, - "hash": "81b4c9db5438f7ef71b99fd3b6708567d54c1e79ab50e00647543dc20b44a512" + "hash": "092906c006f4b98f4e115c3d35605b690d0493d9efb3e9e38f444900a2fd10da" } diff --git a/.sqlx/query-0df7e90f4408e635e281f54b466ad67696507ef0587488c1327f74d66e3641a3.json b/.sqlx/query-0df7e90f4408e635e281f54b466ad67696507ef0587488c1327f74d66e3641a3.json new file mode 100644 index 0000000..0a1e19e --- /dev/null +++ b/.sqlx/query-0df7e90f4408e635e281f54b466ad67696507ef0587488c1327f74d66e3641a3.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM class_course_teacher WHERE class_course = $1 AND teacher = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "0df7e90f4408e635e281f54b466ad67696507ef0587488c1327f74d66e3641a3" +} diff --git a/.sqlx/query-0efbc9fb8e602d2decf3f88b9755835dbd832c36b42d09d1c5313716065bf8d5.json b/.sqlx/query-0efbc9fb8e602d2decf3f88b9755835dbd832c36b42d09d1c5313716065bf8d5.json deleted file mode 100644 index 588aae6..0000000 --- a/.sqlx/query-0efbc9fb8e602d2decf3f88b9755835dbd832c36b42d09d1c5313716065bf8d5.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT cm.class AS \"class: uuid::Uuid\"\n FROM class_member cm\n JOIN class_course cc ON cc.class = cm.class AND cc.course = $1\n WHERE cm.app_user = $2 AND cm.class <> $3\n ORDER BY cm.class\n LIMIT 1", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "class: uuid::Uuid", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "class_member", - "name": "class" - } - } - } - ], - "parameters": { - "Left": [ - "Uuid", - "Uuid", - "Uuid" - ] - }, - "nullable": [ - false - ] - }, - "hash": "0efbc9fb8e602d2decf3f88b9755835dbd832c36b42d09d1c5313716065bf8d5" -} diff --git a/.sqlx/query-0ff8fde329075207ce1da4a660269a0139f3bb25479dd1cce209527699100ca4.json b/.sqlx/query-0ff8fde329075207ce1da4a660269a0139f3bb25479dd1cce209527699100ca4.json new file mode 100644 index 0000000..bf05a39 --- /dev/null +++ b/.sqlx/query-0ff8fde329075207ce1da4a660269a0139f3bb25479dd1cce209527699100ca4.json @@ -0,0 +1,30 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id AS \"id: uuid::Uuid\" FROM class_course\n WHERE class = $1 AND course = $2\n AND source = (SELECT id FROM class_blueprint WHERE grade = $3)\n FOR UPDATE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: uuid::Uuid", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "id" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Uuid", + "Text" + ] + }, + "nullable": [ + false + ] + }, + "hash": "0ff8fde329075207ce1da4a660269a0139f3bb25479dd1cce209527699100ca4" +} diff --git a/.sqlx/query-ab04850be17ccfa612ec851c4754d89cec1cc4631b1c76ce237b7859c90c333e.json b/.sqlx/query-1105ea5febf1c2c9314b456dc8190a943a329f1319335a7ca8a89a71d6709a6f.json similarity index 91% rename from .sqlx/query-ab04850be17ccfa612ec851c4754d89cec1cc4631b1c76ce237b7859c90c333e.json rename to .sqlx/query-1105ea5febf1c2c9314b456dc8190a943a329f1319335a7ca8a89a71d6709a6f.json index c766345..5867e8d 100644 --- a/.sqlx/query-ab04850be17ccfa612ec851c4754d89cec1cc4631b1c76ce237b7859c90c333e.json +++ b/.sqlx/query-1105ea5febf1c2c9314b456dc8190a943a329f1319335a7ca8a89a71d6709a6f.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT r.exam AS \"exam: ExamId\", r.app_user AS \"user: UserId\", r.seq,\n r.mark AS \"mark: Mark\", r.graded_by AS \"graded_by: UserId\"\n FROM exam_result r JOIN exam e ON e.id = r.exam\n WHERE r.app_user = $1 AND e.course = $2\n ORDER BY r.exam DESC, r.seq DESC", + "query": "SELECT r.exam AS \"exam: ExamId\", r.app_user AS \"user: UserId\", r.seq,\n r.mark AS \"mark: Mark\", r.graded_by AS \"graded_by: UserId\"\n FROM exam_result r JOIN exam e ON e.id = r.exam\n WHERE r.app_user = $1 AND e.term = $2\n ORDER BY r.exam DESC, r.seq DESC", "describe": { "columns": [ { @@ -73,5 +73,5 @@ false ] }, - "hash": "ab04850be17ccfa612ec851c4754d89cec1cc4631b1c76ce237b7859c90c333e" + "hash": "1105ea5febf1c2c9314b456dc8190a943a329f1319335a7ca8a89a71d6709a6f" } diff --git a/.sqlx/query-329a782baf49baadc80e6c3a233f203c9eea7308e773738dfd905a9eb131dcb2.json b/.sqlx/query-12d52c7ee480928e91938e0f1f20ca2daf8e253b7f3498b463042f09d56b7919.json similarity index 53% rename from .sqlx/query-329a782baf49baadc80e6c3a233f203c9eea7308e773738dfd905a9eb131dcb2.json rename to .sqlx/query-12d52c7ee480928e91938e0f1f20ca2daf8e253b7f3498b463042f09d56b7919.json index 023071f..23b5784 100644 --- a/.sqlx/query-329a782baf49baadc80e6c3a233f203c9eea7308e773738dfd905a9eb131dcb2.json +++ b/.sqlx/query-12d52c7ee480928e91938e0f1f20ca2daf8e253b7f3498b463042f09d56b7919.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "DELETE FROM course_teacher WHERE course = $1", + "query": "DELETE FROM exam_audience WHERE exam = $1", "describe": { "columns": [], "parameters": { @@ -10,5 +10,5 @@ }, "nullable": [] }, - "hash": "329a782baf49baadc80e6c3a233f203c9eea7308e773738dfd905a9eb131dcb2" + "hash": "12d52c7ee480928e91938e0f1f20ca2daf8e253b7f3498b463042f09d56b7919" } diff --git a/.sqlx/query-8d790a1eea5cee4318551ecbbba9620df93fc80d550dd340f1a1cb91922ffc7f.json b/.sqlx/query-13a8d540e8d0a10833fb4ce5db62e56b8dde68fc37030e90caf641430a50fa79.json similarity index 77% rename from .sqlx/query-8d790a1eea5cee4318551ecbbba9620df93fc80d550dd340f1a1cb91922ffc7f.json rename to .sqlx/query-13a8d540e8d0a10833fb4ce5db62e56b8dde68fc37030e90caf641430a50fa79.json index a2c8448..d29cbbf 100644 --- a/.sqlx/query-8d790a1eea5cee4318551ecbbba9620df93fc80d550dd340f1a1cb91922ffc7f.json +++ b/.sqlx/query-13a8d540e8d0a10833fb4ce5db62e56b8dde68fc37030e90caf641430a50fa79.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: ExamId\", creator AS \"creator: UserId\", course AS \"course: CourseId\",\n title AS \"title: ExamTitle\", description AS \"description: ExamDescription\",\n kind AS \"kind: ExamKind\", mode AS \"mode: ExamMode\",\n starts_at AS \"starts_at: Timestamp\",\n ends_at AS \"ends_at: Timestamp\",\n duration_ms AS \"duration_ms: ExamDuration\",\n max_attempts AS \"max_attempts: ExamAttemptLimit\",\n allow_rejoin, allow_review, draft\n FROM exam WHERE course = $1 ORDER BY id DESC", + "query": "SELECT id AS \"id: ExamId\", creator AS \"creator: UserId\",\n class_course AS \"class_course: ClassCourseId\", term AS \"term: TermId\",\n title AS \"title: ExamTitle\", description AS \"description: ExamDescription\",\n kind AS \"kind: ExamKind\", mode AS \"mode: ExamMode\",\n starts_at AS \"starts_at: Timestamp\",\n ends_at AS \"ends_at: Timestamp\",\n duration_ms AS \"duration_ms: ExamDuration\",\n max_attempts AS \"max_attempts: ExamAttemptLimit\",\n allow_rejoin, allow_review, draft\n FROM exam WHERE id = $1", "describe": { "columns": [ { @@ -27,17 +27,28 @@ }, { "ordinal": 2, - "name": "course: CourseId", + "name": "class_course: ClassCourseId", "type_info": "Uuid", "origin": { "Table": { "table": "exam", - "name": "course" + "name": "class_course" } } }, { "ordinal": 3, + "name": "term: TermId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "exam", + "name": "term" + } + } + }, + { + "ordinal": 4, "name": "title: ExamTitle", "type_info": "Text", "origin": { @@ -48,7 +59,7 @@ } }, { - "ordinal": 4, + "ordinal": 5, "name": "description: ExamDescription", "type_info": "Text", "origin": { @@ -59,7 +70,7 @@ } }, { - "ordinal": 5, + "ordinal": 6, "name": "kind: ExamKind", "type_info": "Text", "origin": { @@ -70,7 +81,7 @@ } }, { - "ordinal": 6, + "ordinal": 7, "name": "mode: ExamMode", "type_info": "Text", "origin": { @@ -81,7 +92,7 @@ } }, { - "ordinal": 7, + "ordinal": 8, "name": "starts_at: Timestamp", "type_info": "Int8", "origin": { @@ -92,7 +103,7 @@ } }, { - "ordinal": 8, + "ordinal": 9, "name": "ends_at: Timestamp", "type_info": "Int8", "origin": { @@ -103,7 +114,7 @@ } }, { - "ordinal": 9, + "ordinal": 10, "name": "duration_ms: ExamDuration", "type_info": "Int8", "origin": { @@ -114,7 +125,7 @@ } }, { - "ordinal": 10, + "ordinal": 11, "name": "max_attempts: ExamAttemptLimit", "type_info": "Int8", "origin": { @@ -125,7 +136,7 @@ } }, { - "ordinal": 11, + "ordinal": 12, "name": "allow_rejoin", "type_info": "Bool", "origin": { @@ -136,7 +147,7 @@ } }, { - "ordinal": 12, + "ordinal": 13, "name": "allow_review", "type_info": "Bool", "origin": { @@ -147,7 +158,7 @@ } }, { - "ordinal": 13, + "ordinal": 14, "name": "draft", "type_info": "Bool", "origin": { @@ -170,6 +181,7 @@ false, false, false, + false, true, true, true, @@ -180,5 +192,5 @@ false ] }, - "hash": "8d790a1eea5cee4318551ecbbba9620df93fc80d550dd340f1a1cb91922ffc7f" + "hash": "13a8d540e8d0a10833fb4ce5db62e56b8dde68fc37030e90caf641430a50fa79" } diff --git a/.sqlx/query-4f831a3b18f1a0e8221fd5b43610cc540576bed7241370578889dfbe673e19ea.json b/.sqlx/query-144d1f4fd9c81491220f809e88fdaf5d363272dab481625db83ed46a7ad0b556.json similarity index 60% rename from .sqlx/query-4f831a3b18f1a0e8221fd5b43610cc540576bed7241370578889dfbe673e19ea.json rename to .sqlx/query-144d1f4fd9c81491220f809e88fdaf5d363272dab481625db83ed46a7ad0b556.json index 8f4e6da..e370a08 100644 --- a/.sqlx/query-4f831a3b18f1a0e8221fd5b43610cc540576bed7241370578889dfbe673e19ea.json +++ b/.sqlx/query-144d1f4fd9c81491220f809e88fdaf5d363272dab481625db83ed46a7ad0b556.json @@ -1,16 +1,16 @@ { "db_name": "PostgreSQL", - "query": "UPDATE enrollment SET source = NULL\n WHERE course = $1 AND app_user = $2\n RETURNING course AS \"course: CourseId\", app_user AS \"user: UserId\",\n enrolled_by AS \"enrolled_by: UserId\", source AS \"source: ClassGroupId\"", + "query": "UPDATE enrollment SET source = NULL\n WHERE class_course = $1 AND app_user = $2\n RETURNING class_course AS \"class_course: ClassCourseId\",\n app_user AS \"user: UserId\", enrolled_by AS \"enrolled_by: UserId\",\n source AS \"source: ClassGroupId\",\n created_at AS \"created_at: Timestamp\"", "describe": { "columns": [ { "ordinal": 0, - "name": "course: CourseId", + "name": "class_course: ClassCourseId", "type_info": "Uuid", "origin": { "Table": { "table": "enrollment", - "name": "course" + "name": "class_course" } } }, @@ -46,6 +46,17 @@ "name": "source" } } + }, + { + "ordinal": 4, + "name": "created_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "enrollment", + "name": "created_at" + } + } } ], "parameters": { @@ -58,8 +69,9 @@ false, false, false, - true + true, + false ] }, - "hash": "4f831a3b18f1a0e8221fd5b43610cc540576bed7241370578889dfbe673e19ea" + "hash": "144d1f4fd9c81491220f809e88fdaf5d363272dab481625db83ed46a7ad0b556" } diff --git a/.sqlx/query-154463480d697fae6ea5126cecd4290f6401f2579b6f4ac3ca27fa6217c83b18.json b/.sqlx/query-154463480d697fae6ea5126cecd4290f6401f2579b6f4ac3ca27fa6217c83b18.json new file mode 100644 index 0000000..39130ab --- /dev/null +++ b/.sqlx/query-154463480d697fae6ea5126cecd4290f6401f2579b6f4ac3ca27fa6217c83b18.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT file FROM question_image WHERE exam = ANY($1)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "file", + "type_info": "Text", + "origin": { + "Table": { + "table": "question_image", + "name": "file" + } + } + } + ], + "parameters": { + "Left": [ + "UuidArray" + ] + }, + "nullable": [ + false + ] + }, + "hash": "154463480d697fae6ea5126cecd4290f6401f2579b6f4ac3ca27fa6217c83b18" +} diff --git a/.sqlx/query-17717997662b0cecc2997806564fc81433d2b524d59e9fb03aef749780c526cf.json b/.sqlx/query-17717997662b0cecc2997806564fc81433d2b524d59e9fb03aef749780c526cf.json new file mode 100644 index 0000000..1082146 --- /dev/null +++ b/.sqlx/query-17717997662b0cecc2997806564fc81433d2b524d59e9fb03aef749780c526cf.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH gone AS (\n DELETE FROM enrollment WHERE app_user = $1 RETURNING class_course\n )\n UPDATE class_course\n SET enrollment_count = GREATEST(enrollment_count - 1, 0)\n WHERE id IN (SELECT gone.class_course FROM gone)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "17717997662b0cecc2997806564fc81433d2b524d59e9fb03aef749780c526cf" +} diff --git a/.sqlx/query-182ea9d92a75c5d83a1588ff046abd4794340651318455ce9a4531eb1bc03d50.json b/.sqlx/query-182ea9d92a75c5d83a1588ff046abd4794340651318455ce9a4531eb1bc03d50.json new file mode 100644 index 0000000..7f123a8 --- /dev/null +++ b/.sqlx/query-182ea9d92a75c5d83a1588ff046abd4794340651318455ce9a4531eb1bc03d50.json @@ -0,0 +1,26 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO settings (id, exam_kinds, grade_bands, max_file_bytes,\n chatbot_history_turns, max_chatbot_message_len,\n max_chatbot_threads, meal_slots,\n meal_cancel_cutoff_minutes, branches, excuse_kinds,\n max_excused_absent_days, max_unexcused_absent_days,\n timezone)\n VALUES ('school', $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)\n ON CONFLICT (id) DO UPDATE SET\n exam_kinds = EXCLUDED.exam_kinds,\n grade_bands = EXCLUDED.grade_bands,\n max_file_bytes = EXCLUDED.max_file_bytes,\n chatbot_history_turns = EXCLUDED.chatbot_history_turns,\n max_chatbot_message_len = EXCLUDED.max_chatbot_message_len,\n max_chatbot_threads = EXCLUDED.max_chatbot_threads,\n meal_slots = EXCLUDED.meal_slots,\n meal_cancel_cutoff_minutes = EXCLUDED.meal_cancel_cutoff_minutes,\n branches = EXCLUDED.branches,\n excuse_kinds = EXCLUDED.excuse_kinds,\n max_excused_absent_days = EXCLUDED.max_excused_absent_days,\n max_unexcused_absent_days = EXCLUDED.max_unexcused_absent_days,\n timezone = EXCLUDED.timezone", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Jsonb", + "Jsonb", + "Int8", + "Int8", + "Int8", + "Int8", + "Jsonb", + "Int8", + "Jsonb", + "Jsonb", + "Int8", + "Int8", + "Text" + ] + }, + "nullable": [] + }, + "hash": "182ea9d92a75c5d83a1588ff046abd4794340651318455ce9a4531eb1bc03d50" +} diff --git a/.sqlx/query-81a7b9416011e6f61c2723adbc62c4499ac910c7d1228afb0ccfd1f28b02dc11.json b/.sqlx/query-1a258b398d6023dbb6e42c7e3f3df270d77dc6d69959d376df8be1c170e74e88.json similarity index 92% rename from .sqlx/query-81a7b9416011e6f61c2723adbc62c4499ac910c7d1228afb0ccfd1f28b02dc11.json rename to .sqlx/query-1a258b398d6023dbb6e42c7e3f3df270d77dc6d69959d376df8be1c170e74e88.json index e4c3eb1..8d877a2 100644 --- a/.sqlx/query-81a7b9416011e6f61c2723adbc62c4499ac910c7d1228afb0ccfd1f28b02dc11.json +++ b/.sqlx/query-1a258b398d6023dbb6e42c7e3f3df270d77dc6d69959d376df8be1c170e74e88.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n avatar_size\n FROM app_user WHERE role = $1 ORDER BY id DESC", + "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n branch,\n avatar_size\n FROM app_user WHERE role = $1 ORDER BY id DESC", "describe": { "columns": [ { @@ -181,6 +181,17 @@ }, { "ordinal": 16, + "name": "branch", + "type_info": "Text", + "origin": { + "Table": { + "table": "app_user", + "name": "branch" + } + } + }, + { + "ordinal": 17, "name": "avatar_size", "type_info": "Int8", "origin": { @@ -213,8 +224,9 @@ true, true, true, + true, true ] }, - "hash": "81a7b9416011e6f61c2723adbc62c4499ac910c7d1228afb0ccfd1f28b02dc11" + "hash": "1a258b398d6023dbb6e42c7e3f3df270d77dc6d69959d376df8be1c170e74e88" } diff --git a/.sqlx/query-1a78ccdb73cee51188f073d86ea66182fa57873c736f4aacedc60e36774c1e25.json b/.sqlx/query-1a78ccdb73cee51188f073d86ea66182fa57873c736f4aacedc60e36774c1e25.json deleted file mode 100644 index a428d2a..0000000 --- a/.sqlx/query-1a78ccdb73cee51188f073d86ea66182fa57873c736f4aacedc60e36774c1e25.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE term SET course_count = GREATEST(course_count - 1, 0)\n WHERE id = $1", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Uuid" - ] - }, - "nullable": [] - }, - "hash": "1a78ccdb73cee51188f073d86ea66182fa57873c736f4aacedc60e36774c1e25" -} diff --git a/.sqlx/query-1ce33939b49f6a42dcdb9508a0756bacd0a8430f82a079e51e5c2cb5e1073bcf.json b/.sqlx/query-1ce33939b49f6a42dcdb9508a0756bacd0a8430f82a079e51e5c2cb5e1073bcf.json deleted file mode 100644 index 07dcecb..0000000 --- a/.sqlx/query-1ce33939b49f6a42dcdb9508a0756bacd0a8430f82a079e51e5c2cb5e1073bcf.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT class_member_count AS \"heir_count: i64\" FROM class_group\n WHERE id = $1 FOR NO KEY UPDATE", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "heir_count: i64", - "type_info": "Int8", - "origin": { - "Table": { - "table": "class_group", - "name": "class_member_count" - } - } - } - ], - "parameters": { - "Left": [ - "Uuid" - ] - }, - "nullable": [ - false - ] - }, - "hash": "1ce33939b49f6a42dcdb9508a0756bacd0a8430f82a079e51e5c2cb5e1073bcf" -} diff --git a/.sqlx/query-72cd9aa43384131ba5489ac5b79e9108aabe3ddb6dc9522530787d3fa632b595.json b/.sqlx/query-2030dabf14da5e9f428ab9b91b92251c53e561d3f7a797f38ac45cf10c9324d1.json similarity index 73% rename from .sqlx/query-72cd9aa43384131ba5489ac5b79e9108aabe3ddb6dc9522530787d3fa632b595.json rename to .sqlx/query-2030dabf14da5e9f428ab9b91b92251c53e561d3f7a797f38ac45cf10c9324d1.json index d987869..fdb491b 100644 --- a/.sqlx/query-72cd9aa43384131ba5489ac5b79e9108aabe3ddb6dc9522530787d3fa632b595.json +++ b/.sqlx/query-2030dabf14da5e9f428ab9b91b92251c53e561d3f7a797f38ac45cf10c9324d1.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE id = $1", + "query": "SELECT id AS \"id: HomeworkId\",\n class_course AS \"class_course: ClassCourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE id = $1 FOR UPDATE", "describe": { "columns": [ { @@ -16,12 +16,12 @@ }, { "ordinal": 1, - "name": "course: CourseId", + "name": "class_course: ClassCourseId", "type_info": "Uuid", "origin": { "Table": { "table": "homework", - "name": "course" + "name": "class_course" } } }, @@ -115,5 +115,5 @@ false ] }, - "hash": "72cd9aa43384131ba5489ac5b79e9108aabe3ddb6dc9522530787d3fa632b595" + "hash": "2030dabf14da5e9f428ab9b91b92251c53e561d3f7a797f38ac45cf10c9324d1" } diff --git a/.sqlx/query-fcce69f1324abd0a60651f5f0bc3f0bcfbdf42be5b2f34f79a40d3c741055135.json b/.sqlx/query-22d8652b21f633600d075ca3aff634ad2ae34dfbc87907a1f41229365726763f.json similarity index 92% rename from .sqlx/query-fcce69f1324abd0a60651f5f0bc3f0bcfbdf42be5b2f34f79a40d3c741055135.json rename to .sqlx/query-22d8652b21f633600d075ca3aff634ad2ae34dfbc87907a1f41229365726763f.json index 99c99ea..e9bc201 100644 --- a/.sqlx/query-fcce69f1324abd0a60651f5f0bc3f0bcfbdf42be5b2f34f79a40d3c741055135.json +++ b/.sqlx/query-22d8652b21f633600d075ca3aff634ad2ae34dfbc87907a1f41229365726763f.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO app_user (id, username, person, role, created_at)\n VALUES ($1, $2, $3, $4, $5)\n RETURNING id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n avatar_size", + "query": "INSERT INTO app_user (id, username, person, role, created_at)\n VALUES ($1, $2, $3, $4, $5)\n RETURNING id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n branch,\n avatar_size", "describe": { "columns": [ { @@ -181,6 +181,17 @@ }, { "ordinal": 16, + "name": "branch", + "type_info": "Text", + "origin": { + "Table": { + "table": "app_user", + "name": "branch" + } + } + }, + { + "ordinal": 17, "name": "avatar_size", "type_info": "Int8", "origin": { @@ -217,8 +228,9 @@ true, true, true, + true, true ] }, - "hash": "fcce69f1324abd0a60651f5f0bc3f0bcfbdf42be5b2f34f79a40d3c741055135" + "hash": "22d8652b21f633600d075ca3aff634ad2ae34dfbc87907a1f41229365726763f" } diff --git a/.sqlx/query-ecacff3f8318067e8abd8d779904deeaf6feb14dd992721d1be5bee56c9d7ff4.json b/.sqlx/query-238a5985401d6a8b614a874f7157d75db9e19f14e73dc20249833d28311f7466.json similarity index 68% rename from .sqlx/query-ecacff3f8318067e8abd8d779904deeaf6feb14dd992721d1be5bee56c9d7ff4.json rename to .sqlx/query-238a5985401d6a8b614a874f7157d75db9e19f14e73dc20249833d28311f7466.json index 07d2dc0..e1d6a37 100644 --- a/.sqlx/query-ecacff3f8318067e8abd8d779904deeaf6feb14dd992721d1be5bee56c9d7ff4.json +++ b/.sqlx/query-238a5985401d6a8b614a874f7157d75db9e19f14e73dc20249833d28311f7466.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: TermId\", name AS \"name: TermName\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\",\n archived_at AS \"archived_at: Timestamp\" FROM term WHERE id = $1", + "query": "SELECT id AS \"id: TermId\", year AS \"year: AcademicYearId\",\n name AS \"name: TermName\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\",\n archived_at AS \"archived_at: Timestamp\" FROM term WHERE id = $1", "describe": { "columns": [ { @@ -16,6 +16,17 @@ }, { "ordinal": 1, + "name": "year: AcademicYearId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "term", + "name": "year" + } + } + }, + { + "ordinal": 2, "name": "name: TermName", "type_info": "Text", "origin": { @@ -26,7 +37,7 @@ } }, { - "ordinal": 2, + "ordinal": 3, "name": "starts_at: Timestamp", "type_info": "Int8", "origin": { @@ -37,7 +48,7 @@ } }, { - "ordinal": 3, + "ordinal": 4, "name": "ends_at: Timestamp", "type_info": "Int8", "origin": { @@ -48,7 +59,7 @@ } }, { - "ordinal": 4, + "ordinal": 5, "name": "archived_at: Timestamp", "type_info": "Int8", "origin": { @@ -69,8 +80,9 @@ false, false, false, + false, true ] }, - "hash": "ecacff3f8318067e8abd8d779904deeaf6feb14dd992721d1be5bee56c9d7ff4" + "hash": "238a5985401d6a8b614a874f7157d75db9e19f14e73dc20249833d28311f7466" } diff --git a/.sqlx/query-23a1369a6a30b803cafaaa75e7203ace62afc4d3bbc55cdec686920ac0fdd570.json b/.sqlx/query-23a1369a6a30b803cafaaa75e7203ace62afc4d3bbc55cdec686920ac0fdd570.json deleted file mode 100644 index 7a267ea..0000000 --- a/.sqlx/query-23a1369a6a30b803cafaaa75e7203ace62afc4d3bbc55cdec686920ac0fdd570.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "DELETE FROM class_course WHERE class = $1 AND course = $2\n AND source = (SELECT id FROM class_blueprint WHERE grade = $3)\n RETURNING 1 AS \"one\"", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "one", - "type_info": "Int4", - "origin": "Expression" - } - ], - "parameters": { - "Left": [ - "Uuid", - "Uuid", - "Text" - ] - }, - "nullable": [ - null - ] - }, - "hash": "23a1369a6a30b803cafaaa75e7203ace62afc4d3bbc55cdec686920ac0fdd570" -} diff --git a/.sqlx/query-2461d810d04aca273a98714d99f0f1d815e12943439002b4615f379f8586768d.json b/.sqlx/query-2461d810d04aca273a98714d99f0f1d815e12943439002b4615f379f8586768d.json new file mode 100644 index 0000000..ad5820c --- /dev/null +++ b/.sqlx/query-2461d810d04aca273a98714d99f0f1d815e12943439002b4615f379f8586768d.json @@ -0,0 +1,67 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH seat AS (\n UPDATE course\n SET course_membership_count = course_membership_count + 1\n WHERE id = $1\n RETURNING 1)\n INSERT INTO course_membership (course, app_user, added_by, created_at)\n SELECT $1, $2, $3, $4 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING course AS \"course: CourseId\", app_user AS \"user: UserId\",\n added_by AS \"added_by: UserId\",\n created_at AS \"created_at: Timestamp\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "course: CourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_membership", + "name": "course" + } + } + }, + { + "ordinal": 1, + "name": "user: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_membership", + "name": "app_user" + } + } + }, + { + "ordinal": 2, + "name": "added_by: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_membership", + "name": "added_by" + } + } + }, + { + "ordinal": 3, + "name": "created_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "course_membership", + "name": "created_at" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Uuid", + "Uuid", + "Int8" + ] + }, + "nullable": [ + false, + false, + false, + false + ] + }, + "hash": "2461d810d04aca273a98714d99f0f1d815e12943439002b4615f379f8586768d" +} diff --git a/.sqlx/query-1ab734e07505d4c74ae50901fb3144f303f578b1048bf96689e513848eca9185.json b/.sqlx/query-2587404e272948a34f509c791e3e9533b846175d0d29a3a6995338e54790535c.json similarity index 53% rename from .sqlx/query-1ab734e07505d4c74ae50901fb3144f303f578b1048bf96689e513848eca9185.json rename to .sqlx/query-2587404e272948a34f509c791e3e9533b846175d0d29a3a6995338e54790535c.json index eb7a4d3..d02fde1 100644 --- a/.sqlx/query-1ab734e07505d4c74ae50901fb3144f303f578b1048bf96689e513848eca9185.json +++ b/.sqlx/query-2587404e272948a34f509c791e3e9533b846175d0d29a3a6995338e54790535c.json @@ -1,16 +1,16 @@ { "db_name": "PostgreSQL", - "query": "SELECT course AS \"course: CourseId\", teacher AS \"teacher: UserId\"\n FROM course_teacher WHERE course = ANY($1)", + "query": "SELECT class_course AS \"class_course: ClassCourseId\", teacher AS \"teacher: UserId\"\n FROM class_course_teacher WHERE class_course = ANY($1)\n ORDER BY class_course, teacher", "describe": { "columns": [ { "ordinal": 0, - "name": "course: CourseId", + "name": "class_course: ClassCourseId", "type_info": "Uuid", "origin": { "Table": { - "table": "course_teacher", - "name": "course" + "table": "class_course_teacher", + "name": "class_course" } } }, @@ -20,7 +20,7 @@ "type_info": "Uuid", "origin": { "Table": { - "table": "course_teacher", + "table": "class_course_teacher", "name": "teacher" } } @@ -36,5 +36,5 @@ false ] }, - "hash": "1ab734e07505d4c74ae50901fb3144f303f578b1048bf96689e513848eca9185" + "hash": "2587404e272948a34f509c791e3e9533b846175d0d29a3a6995338e54790535c" } diff --git a/.sqlx/query-2844f173a4514ccac8bb7064eb7412b962749b10cf16c289f657743512c31130.json b/.sqlx/query-2844f173a4514ccac8bb7064eb7412b962749b10cf16c289f657743512c31130.json new file mode 100644 index 0000000..ec2ccee --- /dev/null +++ b/.sqlx/query-2844f173a4514ccac8bb7064eb7412b962749b10cf16c289f657743512c31130.json @@ -0,0 +1,210 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH room AS (\n UPDATE term SET exam_count = exam_count + 1\n WHERE id = $3\n RETURNING 1)\n INSERT INTO exam (id, creator, class_course, term, title, description, kind, mode,\n starts_at, ends_at, duration_ms, max_attempts,\n allow_rejoin, allow_review, draft)\n SELECT $1, $2, $4, $3, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15\n WHERE EXISTS (SELECT 1 FROM room)\n RETURNING id AS \"id: ExamId\", creator AS \"creator: UserId\",\n class_course AS \"class_course: ClassCourseId\",\n term AS \"term: TermId\", title AS \"title: ExamTitle\",\n description AS \"description: ExamDescription\",\n kind AS \"kind: ExamKind\", mode AS \"mode: ExamMode\",\n starts_at AS \"starts_at: Timestamp\",\n ends_at AS \"ends_at: Timestamp\",\n duration_ms AS \"duration_ms: ExamDuration\",\n max_attempts AS \"max_attempts: ExamAttemptLimit\",\n allow_rejoin, allow_review, draft", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: ExamId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "exam", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "creator: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "exam", + "name": "creator" + } + } + }, + { + "ordinal": 2, + "name": "class_course: ClassCourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "exam", + "name": "class_course" + } + } + }, + { + "ordinal": 3, + "name": "term: TermId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "exam", + "name": "term" + } + } + }, + { + "ordinal": 4, + "name": "title: ExamTitle", + "type_info": "Text", + "origin": { + "Table": { + "table": "exam", + "name": "title" + } + } + }, + { + "ordinal": 5, + "name": "description: ExamDescription", + "type_info": "Text", + "origin": { + "Table": { + "table": "exam", + "name": "description" + } + } + }, + { + "ordinal": 6, + "name": "kind: ExamKind", + "type_info": "Text", + "origin": { + "Table": { + "table": "exam", + "name": "kind" + } + } + }, + { + "ordinal": 7, + "name": "mode: ExamMode", + "type_info": "Text", + "origin": { + "Table": { + "table": "exam", + "name": "mode" + } + } + }, + { + "ordinal": 8, + "name": "starts_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "exam", + "name": "starts_at" + } + } + }, + { + "ordinal": 9, + "name": "ends_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "exam", + "name": "ends_at" + } + } + }, + { + "ordinal": 10, + "name": "duration_ms: ExamDuration", + "type_info": "Int8", + "origin": { + "Table": { + "table": "exam", + "name": "duration_ms" + } + } + }, + { + "ordinal": 11, + "name": "max_attempts: ExamAttemptLimit", + "type_info": "Int8", + "origin": { + "Table": { + "table": "exam", + "name": "max_attempts" + } + } + }, + { + "ordinal": 12, + "name": "allow_rejoin", + "type_info": "Bool", + "origin": { + "Table": { + "table": "exam", + "name": "allow_rejoin" + } + } + }, + { + "ordinal": 13, + "name": "allow_review", + "type_info": "Bool", + "origin": { + "Table": { + "table": "exam", + "name": "allow_review" + } + } + }, + { + "ordinal": 14, + "name": "draft", + "type_info": "Bool", + "origin": { + "Table": { + "table": "exam", + "name": "draft" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Uuid", + "Uuid", + "Uuid", + "Text", + "Text", + "Text", + "Text", + "Int8", + "Int8", + "Int8", + "Int8", + "Bool", + "Bool", + "Bool" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + false, + false, + true, + true, + true, + true, + false, + false, + false, + false + ] + }, + "hash": "2844f173a4514ccac8bb7064eb7412b962749b10cf16c289f657743512c31130" +} diff --git a/.sqlx/query-a06578b33fea0609b216e985ebaa1def29c4622e4e864a6e65de141b5b307dab.json b/.sqlx/query-285c758abaa028faab45383feaf8eda2d9af8bbaa2c14eacf3c67ab3fe303d89.json similarity index 59% rename from .sqlx/query-a06578b33fea0609b216e985ebaa1def29c4622e4e864a6e65de141b5b307dab.json rename to .sqlx/query-285c758abaa028faab45383feaf8eda2d9af8bbaa2c14eacf3c67ab3fe303d89.json index beb2ac1..dae5535 100644 --- a/.sqlx/query-a06578b33fea0609b216e985ebaa1def29c4622e4e864a6e65de141b5b307dab.json +++ b/.sqlx/query-285c758abaa028faab45383feaf8eda2d9af8bbaa2c14eacf3c67ab3fe303d89.json @@ -1,16 +1,16 @@ { "db_name": "PostgreSQL", - "query": "SELECT course AS \"course: uuid::Uuid\" FROM class_course WHERE class = $1", + "query": "SELECT id AS \"id: uuid::Uuid\" FROM class_course WHERE class = $1", "describe": { "columns": [ { "ordinal": 0, - "name": "course: uuid::Uuid", + "name": "id: uuid::Uuid", "type_info": "Uuid", "origin": { "Table": { "table": "class_course", - "name": "course" + "name": "id" } } } @@ -24,5 +24,5 @@ false ] }, - "hash": "a06578b33fea0609b216e985ebaa1def29c4622e4e864a6e65de141b5b307dab" + "hash": "285c758abaa028faab45383feaf8eda2d9af8bbaa2c14eacf3c67ab3fe303d89" } diff --git a/.sqlx/query-2a7f0da7e1f564430f7c7c8f1c7bb5421213ecac8fec266ef809e86462fefbe4.json b/.sqlx/query-2a7f0da7e1f564430f7c7c8f1c7bb5421213ecac8fec266ef809e86462fefbe4.json new file mode 100644 index 0000000..e3e62ef --- /dev/null +++ b/.sqlx/query-2a7f0da7e1f564430f7c7c8f1c7bb5421213ecac8fec266ef809e86462fefbe4.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE class_course\n SET enrollment_count = GREATEST(enrollment_count - 1, 0)\n WHERE id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "2a7f0da7e1f564430f7c7c8f1c7bb5421213ecac8fec266ef809e86462fefbe4" +} diff --git a/.sqlx/query-2bff8987ce85508ef7c91cc20e868617420d1f923a6704111cb83827dcf3c8d0.json b/.sqlx/query-2bff8987ce85508ef7c91cc20e868617420d1f923a6704111cb83827dcf3c8d0.json new file mode 100644 index 0000000..5f1edaa --- /dev/null +++ b/.sqlx/query-2bff8987ce85508ef7c91cc20e868617420d1f923a6704111cb83827dcf3c8d0.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE academic_year\n SET class_count = GREATEST(class_count - 1, 0)\n WHERE id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "2bff8987ce85508ef7c91cc20e868617420d1f923a6704111cb83827dcf3c8d0" +} diff --git a/.sqlx/query-41ed454c1cf5fdd24eb5597d30e1c7132eff4962ca53992c2511d67b311ea22b.json b/.sqlx/query-2d8f6523cf7856181b08678cb65b731d35db23dfe75554f4f39cf06f6518db42.json similarity index 61% rename from .sqlx/query-41ed454c1cf5fdd24eb5597d30e1c7132eff4962ca53992c2511d67b311ea22b.json rename to .sqlx/query-2d8f6523cf7856181b08678cb65b731d35db23dfe75554f4f39cf06f6518db42.json index 2eb35e9..bf12d8c 100644 --- a/.sqlx/query-41ed454c1cf5fdd24eb5597d30e1c7132eff4962ca53992c2511d67b311ea22b.json +++ b/.sqlx/query-2d8f6523cf7856181b08678cb65b731d35db23dfe75554f4f39cf06f6518db42.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "DELETE FROM class_course WHERE class = $1 AND course = $2\n RETURNING 1 AS \"one\"", + "query": "SELECT 1 AS \"one\" FROM class_member\n WHERE class = $1 AND app_user = $2 AND left_at IS NULL", "describe": { "columns": [ { @@ -20,5 +20,5 @@ null ] }, - "hash": "41ed454c1cf5fdd24eb5597d30e1c7132eff4962ca53992c2511d67b311ea22b" + "hash": "2d8f6523cf7856181b08678cb65b731d35db23dfe75554f4f39cf06f6518db42" } diff --git a/.sqlx/query-2e98a32d2edc7d1ba3b004ffb0d00fb0aa3c54b2a39a7bffd8df239011e23358.json b/.sqlx/query-2e98a32d2edc7d1ba3b004ffb0d00fb0aa3c54b2a39a7bffd8df239011e23358.json new file mode 100644 index 0000000..11b608e --- /dev/null +++ b/.sqlx/query-2e98a32d2edc7d1ba3b004ffb0d00fb0aa3c54b2a39a7bffd8df239011e23358.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE term SET exam_count = GREATEST(exam_count - 1, 0)\n WHERE id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "2e98a32d2edc7d1ba3b004ffb0d00fb0aa3c54b2a39a7bffd8df239011e23358" +} diff --git a/.sqlx/query-2f41b58fa1b14cae34c0c641210b24028b4bc319d20de364b3c5d02e9afb840f.json b/.sqlx/query-2f41b58fa1b14cae34c0c641210b24028b4bc319d20de364b3c5d02e9afb840f.json new file mode 100644 index 0000000..2c9171e --- /dev/null +++ b/.sqlx/query-2f41b58fa1b14cae34c0c641210b24028b4bc319d20de364b3c5d02e9afb840f.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id AS \"id: uuid::Uuid\" FROM class_course WHERE course = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: uuid::Uuid", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "id" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "2f41b58fa1b14cae34c0c641210b24028b4bc319d20de364b3c5d02e9afb840f" +} diff --git a/.sqlx/query-34079575aee9338011e36bb40487447cbdeb10d07d195faf4cb4f540e87788f3.json b/.sqlx/query-34079575aee9338011e36bb40487447cbdeb10d07d195faf4cb4f540e87788f3.json new file mode 100644 index 0000000..e307f19 --- /dev/null +++ b/.sqlx/query-34079575aee9338011e36bb40487447cbdeb10d07d195faf4cb4f540e87788f3.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM course_session WHERE class_course = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "34079575aee9338011e36bb40487447cbdeb10d07d195faf4cb4f540e87788f3" +} diff --git a/.sqlx/query-f14d1fb87ed6f382a95f9b5703f4494065479265f9ef011c51f443751d27447f.json b/.sqlx/query-34fba7b4b28ee6ea20e25188cbd51980a66b23372007f66c2162a4afef042806.json similarity index 84% rename from .sqlx/query-f14d1fb87ed6f382a95f9b5703f4494065479265f9ef011c51f443751d27447f.json rename to .sqlx/query-34fba7b4b28ee6ea20e25188cbd51980a66b23372007f66c2162a4afef042806.json index 041924b..c7b41ee 100644 --- a/.sqlx/query-f14d1fb87ed6f382a95f9b5703f4494065479265f9ef011c51f443751d27447f.json +++ b/.sqlx/query-34fba7b4b28ee6ea20e25188cbd51980a66b23372007f66c2162a4afef042806.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n term AS \"term: TermId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE id = ANY($1)", + "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE id = ANY($1)", "describe": { "columns": [ { @@ -49,12 +49,12 @@ }, { "ordinal": 4, - "name": "term: TermId", + "name": "year: AcademicYearId", "type_info": "Uuid", "origin": { "Table": { "table": "class_group", - "name": "term" + "name": "year" } } }, @@ -84,5 +84,5 @@ true ] }, - "hash": "f14d1fb87ed6f382a95f9b5703f4494065479265f9ef011c51f443751d27447f" + "hash": "34fba7b4b28ee6ea20e25188cbd51980a66b23372007f66c2162a4afef042806" } diff --git a/.sqlx/query-df7311334c93314352406e1097530e602a575930baf28e91933d9fa9adf7a2ed.json b/.sqlx/query-35b2fb5639850677d160f6d07f24bf197e5411d6a5547053d0dc9a5e7ece7f4b.json similarity index 53% rename from .sqlx/query-df7311334c93314352406e1097530e602a575930baf28e91933d9fa9adf7a2ed.json rename to .sqlx/query-35b2fb5639850677d160f6d07f24bf197e5411d6a5547053d0dc9a5e7ece7f4b.json index 0b46033..f6c5b03 100644 --- a/.sqlx/query-df7311334c93314352406e1097530e602a575930baf28e91933d9fa9adf7a2ed.json +++ b/.sqlx/query-35b2fb5639850677d160f6d07f24bf197e5411d6a5547053d0dc9a5e7ece7f4b.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO enrollment (course, app_user, enrolled_by, source, created_at)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (course, app_user) DO NOTHING\n RETURNING 1 AS \"one\"", + "query": "INSERT INTO enrollment (class_course, app_user, enrolled_by, source, created_at)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (class_course, app_user) DO NOTHING\n RETURNING 1 AS \"one\"", "describe": { "columns": [ { @@ -23,5 +23,5 @@ null ] }, - "hash": "df7311334c93314352406e1097530e602a575930baf28e91933d9fa9adf7a2ed" + "hash": "35b2fb5639850677d160f6d07f24bf197e5411d6a5547053d0dc9a5e7ece7f4b" } diff --git a/.sqlx/query-8ef28352094c41d4a797006c84bb13185d1bf95aba508c2a6f9fdad3ab14e2a1.json b/.sqlx/query-3a8d10b6ad79c551e94587c938b1ea3843bc9e407e9eed5b1cf9dd25f8233ce3.json similarity index 52% rename from .sqlx/query-8ef28352094c41d4a797006c84bb13185d1bf95aba508c2a6f9fdad3ab14e2a1.json rename to .sqlx/query-3a8d10b6ad79c551e94587c938b1ea3843bc9e407e9eed5b1cf9dd25f8233ce3.json index d642a28..dbd1233 100644 --- a/.sqlx/query-8ef28352094c41d4a797006c84bb13185d1bf95aba508c2a6f9fdad3ab14e2a1.json +++ b/.sqlx/query-3a8d10b6ad79c551e94587c938b1ea3843bc9e407e9eed5b1cf9dd25f8233ce3.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "DELETE FROM enrollment WHERE course = $1 AND app_user = $2", + "query": "DELETE FROM enrollment WHERE class_course = $1 AND app_user = $2", "describe": { "columns": [], "parameters": { @@ -11,5 +11,5 @@ }, "nullable": [] }, - "hash": "8ef28352094c41d4a797006c84bb13185d1bf95aba508c2a6f9fdad3ab14e2a1" + "hash": "3a8d10b6ad79c551e94587c938b1ea3843bc9e407e9eed5b1cf9dd25f8233ce3" } diff --git a/.sqlx/query-4033f72b27577d747740c96aa418736c7f8df98bf1a17083a72371155b0b553d.json b/.sqlx/query-4033f72b27577d747740c96aa418736c7f8df98bf1a17083a72371155b0b553d.json deleted file mode 100644 index 96be4bc..0000000 --- a/.sqlx/query-4033f72b27577d747740c96aa418736c7f8df98bf1a17083a72371155b0b553d.json +++ /dev/null @@ -1,107 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "WITH seat AS (\n UPDATE term\n SET course_count = course_count + 1\n WHERE id = $7 AND course_count < $8\n RETURNING 1)\n INSERT INTO course (id, creator, title, description, kind, term, capacity)\n SELECT $1, $2, $3, $4, $5, $7, $6 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "id: CourseId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "course", - "name": "id" - } - } - }, - { - "ordinal": 1, - "name": "creator: UserId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "course", - "name": "creator" - } - } - }, - { - "ordinal": 2, - "name": "title: CourseTitle", - "type_info": "Text", - "origin": { - "Table": { - "table": "course", - "name": "title" - } - } - }, - { - "ordinal": 3, - "name": "description: CourseDescription", - "type_info": "Text", - "origin": { - "Table": { - "table": "course", - "name": "description" - } - } - }, - { - "ordinal": 4, - "name": "kind: CourseKind", - "type_info": "Text", - "origin": { - "Table": { - "table": "course", - "name": "kind" - } - } - }, - { - "ordinal": 5, - "name": "term: TermId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "course", - "name": "term" - } - } - }, - { - "ordinal": 6, - "name": "capacity", - "type_info": "Int8", - "origin": { - "Table": { - "table": "course", - "name": "capacity" - } - } - } - ], - "parameters": { - "Left": [ - "Uuid", - "Uuid", - "Text", - "Text", - "Text", - "Int8", - "Uuid", - "Int8" - ] - }, - "nullable": [ - false, - false, - false, - false, - false, - true, - true - ] - }, - "hash": "4033f72b27577d747740c96aa418736c7f8df98bf1a17083a72371155b0b553d" -} diff --git a/.sqlx/query-728de093441cfaccc7832a182862ac3d5f43ba9f4349f0140b5978b5fb3378f9.json b/.sqlx/query-43ae4864f41cb19de3496a26567bd02ca377db3ea6d0bbbe5106a24c17a84692.json similarity index 81% rename from .sqlx/query-728de093441cfaccc7832a182862ac3d5f43ba9f4349f0140b5978b5fb3378f9.json rename to .sqlx/query-43ae4864f41cb19de3496a26567bd02ca377db3ea6d0bbbe5106a24c17a84692.json index 4c94f3c..248de37 100644 --- a/.sqlx/query-728de093441cfaccc7832a182862ac3d5f43ba9f4349f0140b5978b5fb3378f9.json +++ b/.sqlx/query-43ae4864f41cb19de3496a26567bd02ca377db3ea6d0bbbe5106a24c17a84692.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE exam SET title = $2, description = $3, kind = $4, mode = $5,\n starts_at = $6, ends_at = $7, duration_ms = $8,\n max_attempts = $9, allow_rejoin = $10, allow_review = $11,\n draft = $12\n WHERE id = $1\n AND title = $13 AND description = $14 AND kind = $15\n AND mode IS NOT DISTINCT FROM $16\n AND starts_at IS NOT DISTINCT FROM $17\n AND ends_at IS NOT DISTINCT FROM $18\n AND duration_ms IS NOT DISTINCT FROM $19\n AND max_attempts = $20 AND allow_rejoin = $21 AND allow_review = $22\n AND draft = $23\n AND result_count = $24\n RETURNING id AS \"id: ExamId\", creator AS \"creator: UserId\",\n course AS \"course: CourseId\", title AS \"title: ExamTitle\",\n description AS \"description: ExamDescription\",\n kind AS \"kind: ExamKind\", mode AS \"mode: ExamMode\",\n starts_at AS \"starts_at: Timestamp\",\n ends_at AS \"ends_at: Timestamp\",\n duration_ms AS \"duration_ms: ExamDuration\",\n max_attempts AS \"max_attempts: ExamAttemptLimit\",\n allow_rejoin, allow_review, draft", + "query": "UPDATE exam SET title = $2, description = $3, kind = $4, mode = $5,\n starts_at = $6, ends_at = $7, duration_ms = $8,\n max_attempts = $9, allow_rejoin = $10, allow_review = $11,\n draft = $12\n WHERE id = $1\n AND title = $13 AND description = $14 AND kind = $15\n AND mode IS NOT DISTINCT FROM $16\n AND starts_at IS NOT DISTINCT FROM $17\n AND ends_at IS NOT DISTINCT FROM $18\n AND duration_ms IS NOT DISTINCT FROM $19\n AND max_attempts = $20 AND allow_rejoin = $21 AND allow_review = $22\n AND draft = $23\n AND result_count = $24\n RETURNING id AS \"id: ExamId\", creator AS \"creator: UserId\",\n class_course AS \"class_course: ClassCourseId\",\n term AS \"term: TermId\", title AS \"title: ExamTitle\",\n description AS \"description: ExamDescription\",\n kind AS \"kind: ExamKind\", mode AS \"mode: ExamMode\",\n starts_at AS \"starts_at: Timestamp\",\n ends_at AS \"ends_at: Timestamp\",\n duration_ms AS \"duration_ms: ExamDuration\",\n max_attempts AS \"max_attempts: ExamAttemptLimit\",\n allow_rejoin, allow_review, draft", "describe": { "columns": [ { @@ -27,17 +27,28 @@ }, { "ordinal": 2, - "name": "course: CourseId", + "name": "class_course: ClassCourseId", "type_info": "Uuid", "origin": { "Table": { "table": "exam", - "name": "course" + "name": "class_course" } } }, { "ordinal": 3, + "name": "term: TermId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "exam", + "name": "term" + } + } + }, + { + "ordinal": 4, "name": "title: ExamTitle", "type_info": "Text", "origin": { @@ -48,7 +59,7 @@ } }, { - "ordinal": 4, + "ordinal": 5, "name": "description: ExamDescription", "type_info": "Text", "origin": { @@ -59,7 +70,7 @@ } }, { - "ordinal": 5, + "ordinal": 6, "name": "kind: ExamKind", "type_info": "Text", "origin": { @@ -70,7 +81,7 @@ } }, { - "ordinal": 6, + "ordinal": 7, "name": "mode: ExamMode", "type_info": "Text", "origin": { @@ -81,7 +92,7 @@ } }, { - "ordinal": 7, + "ordinal": 8, "name": "starts_at: Timestamp", "type_info": "Int8", "origin": { @@ -92,7 +103,7 @@ } }, { - "ordinal": 8, + "ordinal": 9, "name": "ends_at: Timestamp", "type_info": "Int8", "origin": { @@ -103,7 +114,7 @@ } }, { - "ordinal": 9, + "ordinal": 10, "name": "duration_ms: ExamDuration", "type_info": "Int8", "origin": { @@ -114,7 +125,7 @@ } }, { - "ordinal": 10, + "ordinal": 11, "name": "max_attempts: ExamAttemptLimit", "type_info": "Int8", "origin": { @@ -125,7 +136,7 @@ } }, { - "ordinal": 11, + "ordinal": 12, "name": "allow_rejoin", "type_info": "Bool", "origin": { @@ -136,7 +147,7 @@ } }, { - "ordinal": 12, + "ordinal": 13, "name": "allow_review", "type_info": "Bool", "origin": { @@ -147,7 +158,7 @@ } }, { - "ordinal": 13, + "ordinal": 14, "name": "draft", "type_info": "Bool", "origin": { @@ -193,6 +204,7 @@ false, false, false, + false, true, true, true, @@ -203,5 +215,5 @@ false ] }, - "hash": "728de093441cfaccc7832a182862ac3d5f43ba9f4349f0140b5978b5fb3378f9" + "hash": "43ae4864f41cb19de3496a26567bd02ca377db3ea6d0bbbe5106a24c17a84692" } diff --git a/.sqlx/query-ff6b3600e1cb9dcbd1e573b7eb4892704cb6aa9892e5344d1bde26be16f38a4a.json b/.sqlx/query-45b22b65eb9eaa820596249c17fd6d110892e40a200fb22f4998a375067fc1d1.json similarity index 54% rename from .sqlx/query-ff6b3600e1cb9dcbd1e573b7eb4892704cb6aa9892e5344d1bde26be16f38a4a.json rename to .sqlx/query-45b22b65eb9eaa820596249c17fd6d110892e40a200fb22f4998a375067fc1d1.json index 1829b75..a1757ec 100644 --- a/.sqlx/query-ff6b3600e1cb9dcbd1e573b7eb4892704cb6aa9892e5344d1bde26be16f38a4a.json +++ b/.sqlx/query-45b22b65eb9eaa820596249c17fd6d110892e40a200fb22f4998a375067fc1d1.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE course SET enrollment_count = enrollment_count + 1\n WHERE id = $1 AND enrollment_count < COALESCE(capacity, $2)\n RETURNING 1 AS \"one\"", + "query": "UPDATE class_member SET left_at = $3\n WHERE class = $1 AND app_user = $2 AND left_at IS NULL\n RETURNING 1 AS \"one\"", "describe": { "columns": [ { @@ -12,6 +12,7 @@ ], "parameters": { "Left": [ + "Uuid", "Uuid", "Int8" ] @@ -20,5 +21,5 @@ null ] }, - "hash": "ff6b3600e1cb9dcbd1e573b7eb4892704cb6aa9892e5344d1bde26be16f38a4a" + "hash": "45b22b65eb9eaa820596249c17fd6d110892e40a200fb22f4998a375067fc1d1" } diff --git a/.sqlx/query-15e1d6d5b56bbdbc817402c8b92202dc705ca27d14da7016adb201145c2229b0.json b/.sqlx/query-46be1d9c474028739e57a52bbf0ea26a101bbed607e14890aa6349fd767ec701.json similarity index 92% rename from .sqlx/query-15e1d6d5b56bbdbc817402c8b92202dc705ca27d14da7016adb201145c2229b0.json rename to .sqlx/query-46be1d9c474028739e57a52bbf0ea26a101bbed607e14890aa6349fd767ec701.json index 84be0ef..31547a4 100644 --- a/.sqlx/query-15e1d6d5b56bbdbc817402c8b92202dc705ca27d14da7016adb201145c2229b0.json +++ b/.sqlx/query-46be1d9c474028739e57a52bbf0ea26a101bbed607e14890aa6349fd767ec701.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n avatar_size\n FROM app_user WHERE username = $1", + "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n branch,\n avatar_size\n FROM app_user WHERE username = $1", "describe": { "columns": [ { @@ -181,6 +181,17 @@ }, { "ordinal": 16, + "name": "branch", + "type_info": "Text", + "origin": { + "Table": { + "table": "app_user", + "name": "branch" + } + } + }, + { + "ordinal": 17, "name": "avatar_size", "type_info": "Int8", "origin": { @@ -213,8 +224,9 @@ true, true, true, + true, true ] }, - "hash": "15e1d6d5b56bbdbc817402c8b92202dc705ca27d14da7016adb201145c2229b0" + "hash": "46be1d9c474028739e57a52bbf0ea26a101bbed607e14890aa6349fd767ec701" } diff --git a/.sqlx/query-48188b56ecdcb1e16edf51509f090685694378e1dd0f6fe7b19f6d4dc8cec676.json b/.sqlx/query-48188b56ecdcb1e16edf51509f090685694378e1dd0f6fe7b19f6d4dc8cec676.json deleted file mode 100644 index 77318b0..0000000 --- a/.sqlx/query-48188b56ecdcb1e16edf51509f090685694378e1dd0f6fe7b19f6d4dc8cec676.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT course AS \"course: uuid::Uuid\", app_user AS \"app_user: uuid::Uuid\"\n FROM enrollment WHERE app_user = $1 AND source = $2", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "course: uuid::Uuid", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "enrollment", - "name": "course" - } - } - }, - { - "ordinal": 1, - "name": "app_user: uuid::Uuid", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "enrollment", - "name": "app_user" - } - } - } - ], - "parameters": { - "Left": [ - "Uuid", - "Uuid" - ] - }, - "nullable": [ - false, - false - ] - }, - "hash": "48188b56ecdcb1e16edf51509f090685694378e1dd0f6fe7b19f6d4dc8cec676" -} diff --git a/.sqlx/query-4d6f5584543386bae2d92f27620e600eb755b1d466e134085a9aa4ece67d04d1.json b/.sqlx/query-4d6f5584543386bae2d92f27620e600eb755b1d466e134085a9aa4ece67d04d1.json new file mode 100644 index 0000000..875b779 --- /dev/null +++ b/.sqlx/query-4d6f5584543386bae2d92f27620e600eb755b1d466e134085a9aa4ece67d04d1.json @@ -0,0 +1,24 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT 1 AS \"one\" FROM class_member\n WHERE class = $1 AND app_user = $2 AND left_at IS NULL", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "one", + "type_info": "Int4", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Uuid", + "Uuid" + ] + }, + "nullable": [ + null + ] + }, + "hash": "4d6f5584543386bae2d92f27620e600eb755b1d466e134085a9aa4ece67d04d1" +} diff --git a/.sqlx/query-4f4dacffc966e98307ddf8667527398fe83ee865aa6199dbc7d807d5f1094bf7.json b/.sqlx/query-4f4dacffc966e98307ddf8667527398fe83ee865aa6199dbc7d807d5f1094bf7.json deleted file mode 100644 index 5566df5..0000000 --- a/.sqlx/query-4f4dacffc966e98307ddf8667527398fe83ee865aa6199dbc7d807d5f1094bf7.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE enrollment SET source = $1 WHERE course = $2 AND app_user = $3", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Uuid", - "Uuid", - "Uuid" - ] - }, - "nullable": [] - }, - "hash": "4f4dacffc966e98307ddf8667527398fe83ee865aa6199dbc7d807d5f1094bf7" -} diff --git a/.sqlx/query-4fc84b8b8bc1fd2da27b3db19f5405c1d15e51cbbfbfb494239ccce056470ca0.json b/.sqlx/query-4fc84b8b8bc1fd2da27b3db19f5405c1d15e51cbbfbfb494239ccce056470ca0.json new file mode 100644 index 0000000..a9f7c60 --- /dev/null +++ b/.sqlx/query-4fc84b8b8bc1fd2da27b3db19f5405c1d15e51cbbfbfb494239ccce056470ca0.json @@ -0,0 +1,124 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id AS \"id: AcademicYearId\", name AS \"name: AcademicYearName\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\",\n archived_at AS \"archived_at: Timestamp\", creator AS \"creator: UserId\",\n grade_promotions AS \"grade_promotions: Json>\",\n class_count, term_count\n FROM academic_year WHERE id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: AcademicYearId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "academic_year", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "name: AcademicYearName", + "type_info": "Text", + "origin": { + "Table": { + "table": "academic_year", + "name": "name" + } + } + }, + { + "ordinal": 2, + "name": "starts_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "academic_year", + "name": "starts_at" + } + } + }, + { + "ordinal": 3, + "name": "ends_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "academic_year", + "name": "ends_at" + } + } + }, + { + "ordinal": 4, + "name": "archived_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "academic_year", + "name": "archived_at" + } + } + }, + { + "ordinal": 5, + "name": "creator: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "academic_year", + "name": "creator" + } + } + }, + { + "ordinal": 6, + "name": "grade_promotions: Json>", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "academic_year", + "name": "grade_promotions" + } + } + }, + { + "ordinal": 7, + "name": "class_count", + "type_info": "Int8", + "origin": { + "Table": { + "table": "academic_year", + "name": "class_count" + } + } + }, + { + "ordinal": 8, + "name": "term_count", + "type_info": "Int8", + "origin": { + "Table": { + "table": "academic_year", + "name": "term_count" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + false, + false, + false, + true, + false, + false, + false, + false + ] + }, + "hash": "4fc84b8b8bc1fd2da27b3db19f5405c1d15e51cbbfbfb494239ccce056470ca0" +} diff --git a/.sqlx/query-6907da40c5b42ea56fb9c257cd9b486869381275626163e8bd75e928188875b1.json b/.sqlx/query-5010047bffcbc995e623e4902c3efc3514edb3d09e33df6c9c93780278199077.json similarity index 80% rename from .sqlx/query-6907da40c5b42ea56fb9c257cd9b486869381275626163e8bd75e928188875b1.json rename to .sqlx/query-5010047bffcbc995e623e4902c3efc3514edb3d09e33df6c9c93780278199077.json index 1668a7e..32ab4c9 100644 --- a/.sqlx/query-6907da40c5b42ea56fb9c257cd9b486869381275626163e8bd75e928188875b1.json +++ b/.sqlx/query-5010047bffcbc995e623e4902c3efc3514edb3d09e33df6c9c93780278199077.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity\n FROM course WHERE id = $1", + "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", class_course_count, course_membership_count\n FROM course WHERE id = $1", "describe": { "columns": [ { @@ -60,23 +60,23 @@ }, { "ordinal": 5, - "name": "term: TermId", - "type_info": "Uuid", + "name": "class_course_count", + "type_info": "Int8", "origin": { "Table": { "table": "course", - "name": "term" + "name": "class_course_count" } } }, { "ordinal": 6, - "name": "capacity", + "name": "course_membership_count", "type_info": "Int8", "origin": { "Table": { "table": "course", - "name": "capacity" + "name": "course_membership_count" } } } @@ -92,9 +92,9 @@ false, false, false, - true, - true + false, + false ] }, - "hash": "6907da40c5b42ea56fb9c257cd9b486869381275626163e8bd75e928188875b1" + "hash": "5010047bffcbc995e623e4902c3efc3514edb3d09e33df6c9c93780278199077" } diff --git a/.sqlx/query-3af1f73e479f61d79291a8318ee6dc7bd7201115f3dfcb37aa46576befd2b817.json b/.sqlx/query-508239762c35fa66a85134694106d0e57157af3985d9238fd5f84e1c3d2a2eb0.json similarity index 61% rename from .sqlx/query-3af1f73e479f61d79291a8318ee6dc7bd7201115f3dfcb37aa46576befd2b817.json rename to .sqlx/query-508239762c35fa66a85134694106d0e57157af3985d9238fd5f84e1c3d2a2eb0.json index 3d3ad88..776038b 100644 --- a/.sqlx/query-3af1f73e479f61d79291a8318ee6dc7bd7201115f3dfcb37aa46576befd2b817.json +++ b/.sqlx/query-508239762c35fa66a85134694106d0e57157af3985d9238fd5f84e1c3d2a2eb0.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "DELETE FROM class_member WHERE class = $1 AND app_user = $2\n RETURNING 1 AS \"one\"", + "query": "SELECT 1 AS \"one\" FROM enrollment\n WHERE class_course = $1 AND app_user = $2", "describe": { "columns": [ { @@ -20,5 +20,5 @@ null ] }, - "hash": "3af1f73e479f61d79291a8318ee6dc7bd7201115f3dfcb37aa46576befd2b817" + "hash": "508239762c35fa66a85134694106d0e57157af3985d9238fd5f84e1c3d2a2eb0" } diff --git a/.sqlx/query-f7d2187dc89a2bba3b521b0ea67282392ba1739904fcb1d40006e34c78d4afa9.json b/.sqlx/query-51c9b50b0722b0d49f8202387bc06f833d34598d7556f0f6c02171230b72cd6e.json similarity index 74% rename from .sqlx/query-f7d2187dc89a2bba3b521b0ea67282392ba1739904fcb1d40006e34c78d4afa9.json rename to .sqlx/query-51c9b50b0722b0d49f8202387bc06f833d34598d7556f0f6c02171230b72cd6e.json index 475b902..ea27ddc 100644 --- a/.sqlx/query-f7d2187dc89a2bba3b521b0ea67282392ba1739904fcb1d40006e34c78d4afa9.json +++ b/.sqlx/query-51c9b50b0722b0d49f8202387bc06f833d34598d7556f0f6c02171230b72cd6e.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE course = $1 ORDER BY id DESC", + "query": "SELECT id AS \"id: HomeworkId\",\n class_course AS \"class_course: ClassCourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE id = $1", "describe": { "columns": [ { @@ -16,12 +16,12 @@ }, { "ordinal": 1, - "name": "course: CourseId", + "name": "class_course: ClassCourseId", "type_info": "Uuid", "origin": { "Table": { "table": "homework", - "name": "course" + "name": "class_course" } } }, @@ -115,5 +115,5 @@ false ] }, - "hash": "f7d2187dc89a2bba3b521b0ea67282392ba1739904fcb1d40006e34c78d4afa9" + "hash": "51c9b50b0722b0d49f8202387bc06f833d34598d7556f0f6c02171230b72cd6e" } diff --git a/.sqlx/query-528eb8c289d6edc05eaa85b4f0361933a88f3d8ecce63236da73f0b03b59d722.json b/.sqlx/query-528eb8c289d6edc05eaa85b4f0361933a88f3d8ecce63236da73f0b03b59d722.json new file mode 100644 index 0000000..6a4238f --- /dev/null +++ b/.sqlx/query-528eb8c289d6edc05eaa85b4f0361933a88f3d8ecce63236da73f0b03b59d722.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH gone AS (\n UPDATE class_member SET left_at = $2\n WHERE app_user = $1 AND left_at IS NULL\n RETURNING class\n )\n UPDATE class_group\n SET class_member_count = GREATEST(class_member_count - 1, 0)\n WHERE id IN (SELECT gone.class FROM gone)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Int8" + ] + }, + "nullable": [] + }, + "hash": "528eb8c289d6edc05eaa85b4f0361933a88f3d8ecce63236da73f0b03b59d722" +} diff --git a/.sqlx/query-551eaaaae5e29620d8d75f74fa7559353e088b89cc026bc1baf7edc7f085419b.json b/.sqlx/query-551eaaaae5e29620d8d75f74fa7559353e088b89cc026bc1baf7edc7f085419b.json new file mode 100644 index 0000000..b439b20 --- /dev/null +++ b/.sqlx/query-551eaaaae5e29620d8d75f74fa7559353e088b89cc026bc1baf7edc7f085419b.json @@ -0,0 +1,121 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH updated AS (\n UPDATE class_course\n SET ders_saati = COALESCE($2::bigint, ders_saati::bigint)::smallint,\n counts_toward_karne = COALESCE($3, counts_toward_karne)\n WHERE id = $1\n RETURNING *)\n SELECT u.id AS \"id: ClassCourseId\", u.class AS \"class: ClassGroupId\",\n u.course AS \"course: CourseId\", u.attached_by AS \"attached_by: UserId\",\n b.grade AS \"source?: ClassBlueprintId\",\n u.ders_saati::bigint AS \"ders_saati!: DersSaati\",\n u.counts_toward_karne, u.enrollment_count,\n u.attached_at AS \"attached_at: Timestamp\"\n FROM updated u\n LEFT JOIN class_blueprint b ON b.id = u.source", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: ClassCourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "class: ClassGroupId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "class" + } + } + }, + { + "ordinal": 2, + "name": "course: CourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "course" + } + } + }, + { + "ordinal": 3, + "name": "attached_by: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "attached_by" + } + } + }, + { + "ordinal": 4, + "name": "source?: ClassBlueprintId", + "type_info": "Text", + "origin": { + "Table": { + "table": "class_blueprint", + "name": "grade" + } + } + }, + { + "ordinal": 5, + "name": "ders_saati!: DersSaati", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 6, + "name": "counts_toward_karne", + "type_info": "Bool", + "origin": { + "Table": { + "table": "class_course", + "name": "counts_toward_karne" + } + } + }, + { + "ordinal": 7, + "name": "enrollment_count", + "type_info": "Int8", + "origin": { + "Table": { + "table": "class_course", + "name": "enrollment_count" + } + } + }, + { + "ordinal": 8, + "name": "attached_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "class_course", + "name": "attached_at" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Int8", + "Bool" + ] + }, + "nullable": [ + false, + false, + false, + false, + true, + null, + false, + false, + false + ] + }, + "hash": "551eaaaae5e29620d8d75f74fa7559353e088b89cc026bc1baf7edc7f085419b" +} diff --git a/.sqlx/query-56698618a156770cdb1475134c16e1f513cb6613c0e21bdf033978b2be5d7842.json b/.sqlx/query-56698618a156770cdb1475134c16e1f513cb6613c0e21bdf033978b2be5d7842.json new file mode 100644 index 0000000..c2ff80c --- /dev/null +++ b/.sqlx/query-56698618a156770cdb1475134c16e1f513cb6613c0e21bdf033978b2be5d7842.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM course_membership WHERE course = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "56698618a156770cdb1475134c16e1f513cb6613c0e21bdf033978b2be5d7842" +} diff --git a/.sqlx/query-6ce455efe2f18ee3bf4a217db31b91d188bfff40e5e1e0af2789e92ca110c71f.json b/.sqlx/query-57440348e01f5416cefe71d9d638ce723e9ec1cda075ba99093b5fd3ebd88b9c.json similarity index 74% rename from .sqlx/query-6ce455efe2f18ee3bf4a217db31b91d188bfff40e5e1e0af2789e92ca110c71f.json rename to .sqlx/query-57440348e01f5416cefe71d9d638ce723e9ec1cda075ba99093b5fd3ebd88b9c.json index 2fccff2..48f5694 100644 --- a/.sqlx/query-6ce455efe2f18ee3bf4a217db31b91d188bfff40e5e1e0af2789e92ca110c71f.json +++ b/.sqlx/query-57440348e01f5416cefe71d9d638ce723e9ec1cda075ba99093b5fd3ebd88b9c.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity\n FROM course WHERE creator = $1 OR id IN (\n SELECT course FROM course_teacher WHERE teacher = $2)\n ORDER BY id DESC", + "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", class_course_count, course_membership_count\n FROM course WHERE id IN (\n SELECT cc.course FROM class_course_teacher t\n JOIN class_course cc ON cc.id = t.class_course\n WHERE t.teacher = $1)\n ORDER BY id DESC", "describe": { "columns": [ { @@ -60,30 +60,29 @@ }, { "ordinal": 5, - "name": "term: TermId", - "type_info": "Uuid", + "name": "class_course_count", + "type_info": "Int8", "origin": { "Table": { "table": "course", - "name": "term" + "name": "class_course_count" } } }, { "ordinal": 6, - "name": "capacity", + "name": "course_membership_count", "type_info": "Int8", "origin": { "Table": { "table": "course", - "name": "capacity" + "name": "course_membership_count" } } } ], "parameters": { "Left": [ - "Uuid", "Uuid" ] }, @@ -93,9 +92,9 @@ false, false, false, - true, - true + false, + false ] }, - "hash": "6ce455efe2f18ee3bf4a217db31b91d188bfff40e5e1e0af2789e92ca110c71f" + "hash": "57440348e01f5416cefe71d9d638ce723e9ec1cda075ba99093b5fd3ebd88b9c" } diff --git a/.sqlx/query-57e14f7219a606a952093053b513fd2a6c8aa10ed7a8676483debf76723cce2b.json b/.sqlx/query-57e14f7219a606a952093053b513fd2a6c8aa10ed7a8676483debf76723cce2b.json new file mode 100644 index 0000000..3690aaa --- /dev/null +++ b/.sqlx/query-57e14f7219a606a952093053b513fd2a6c8aa10ed7a8676483debf76723cce2b.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT file FROM homework_file\n WHERE submission IN (\n SELECT id FROM homework_submission\n WHERE homework IN (\n SELECT h.id FROM homework h\n JOIN class_course cc ON cc.id = h.class_course\n WHERE cc.course = $1)\n )", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "file", + "type_info": "Text", + "origin": { + "Table": { + "table": "homework_file", + "name": "file" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "57e14f7219a606a952093053b513fd2a6c8aa10ed7a8676483debf76723cce2b" +} diff --git a/.sqlx/query-58cc273a1c6380cd70ba606245369cf8b4ea505a2123ebeece417921d6392901.json b/.sqlx/query-58cc273a1c6380cd70ba606245369cf8b4ea505a2123ebeece417921d6392901.json new file mode 100644 index 0000000..f794e34 --- /dev/null +++ b/.sqlx/query-58cc273a1c6380cd70ba606245369cf8b4ea505a2123ebeece417921d6392901.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT file FROM answer_image WHERE exam = ANY($1)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "file", + "type_info": "Text", + "origin": { + "Table": { + "table": "answer_image", + "name": "file" + } + } + } + ], + "parameters": { + "Left": [ + "UuidArray" + ] + }, + "nullable": [ + false + ] + }, + "hash": "58cc273a1c6380cd70ba606245369cf8b4ea505a2123ebeece417921d6392901" +} diff --git a/.sqlx/query-5b5835aef1c88f6a2476c6e763cdce4afa5cd33c7bae3aa67c62488d31eb8c1f.json b/.sqlx/query-5b5835aef1c88f6a2476c6e763cdce4afa5cd33c7bae3aa67c62488d31eb8c1f.json new file mode 100644 index 0000000..a60756a --- /dev/null +++ b/.sqlx/query-5b5835aef1c88f6a2476c6e763cdce4afa5cd33c7bae3aa67c62488d31eb8c1f.json @@ -0,0 +1,119 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT cc.id AS \"id: ClassCourseId\", cc.class AS \"class: ClassGroupId\",\n cc.course AS \"course: CourseId\", cc.attached_by AS \"attached_by: UserId\",\n b.grade AS \"source?: ClassBlueprintId\",\n cc.ders_saati::bigint AS \"ders_saati!: DersSaati\",\n cc.counts_toward_karne, cc.enrollment_count,\n cc.attached_at AS \"attached_at: Timestamp\"\n FROM class_course cc\n LEFT JOIN class_blueprint b ON b.id = cc.source\n WHERE cc.id = ANY($1)\n ORDER BY cc.attached_at DESC, cc.id DESC", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: ClassCourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "class: ClassGroupId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "class" + } + } + }, + { + "ordinal": 2, + "name": "course: CourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "course" + } + } + }, + { + "ordinal": 3, + "name": "attached_by: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "attached_by" + } + } + }, + { + "ordinal": 4, + "name": "source?: ClassBlueprintId", + "type_info": "Text", + "origin": { + "Table": { + "table": "class_blueprint", + "name": "grade" + } + } + }, + { + "ordinal": 5, + "name": "ders_saati!: DersSaati", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 6, + "name": "counts_toward_karne", + "type_info": "Bool", + "origin": { + "Table": { + "table": "class_course", + "name": "counts_toward_karne" + } + } + }, + { + "ordinal": 7, + "name": "enrollment_count", + "type_info": "Int8", + "origin": { + "Table": { + "table": "class_course", + "name": "enrollment_count" + } + } + }, + { + "ordinal": 8, + "name": "attached_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "class_course", + "name": "attached_at" + } + } + } + ], + "parameters": { + "Left": [ + "UuidArray" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + null, + false, + false, + false + ] + }, + "hash": "5b5835aef1c88f6a2476c6e763cdce4afa5cd33c7bae3aa67c62488d31eb8c1f" +} diff --git a/.sqlx/query-ff03e27f1d286af08d2468fee7c3e5121c55d9721e19c46c5e05b7ca79c785f4.json b/.sqlx/query-5ebfcdfad4e6eb3342cb60e5743a7478fd357924360cf46a635c63aa072c19bf.json similarity index 59% rename from .sqlx/query-ff03e27f1d286af08d2468fee7c3e5121c55d9721e19c46c5e05b7ca79c785f4.json rename to .sqlx/query-5ebfcdfad4e6eb3342cb60e5743a7478fd357924360cf46a635c63aa072c19bf.json index 7a9a77b..4b8c652 100644 --- a/.sqlx/query-ff03e27f1d286af08d2468fee7c3e5121c55d9721e19c46c5e05b7ca79c785f4.json +++ b/.sqlx/query-5ebfcdfad4e6eb3342cb60e5743a7478fd357924360cf46a635c63aa072c19bf.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO term (id, name, starts_at, ends_at, archived_at)\n VALUES ($1, $2, $3, $4, NULL)\n RETURNING id AS \"id: TermId\", name AS \"name: TermName\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\",\n archived_at AS \"archived_at: Timestamp\"", + "query": "WITH room AS (\n UPDATE academic_year SET term_count = term_count + 1\n WHERE id = $5\n RETURNING 1)\n INSERT INTO term (id, name, year, starts_at, ends_at, archived_at)\n SELECT $1, $2, $5, $3, $4, NULL WHERE EXISTS (SELECT 1 FROM room)\n RETURNING id AS \"id: TermId\", year AS \"year: AcademicYearId\",\n name AS \"name: TermName\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\",\n archived_at AS \"archived_at: Timestamp\"", "describe": { "columns": [ { @@ -16,6 +16,17 @@ }, { "ordinal": 1, + "name": "year: AcademicYearId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "term", + "name": "year" + } + } + }, + { + "ordinal": 2, "name": "name: TermName", "type_info": "Text", "origin": { @@ -26,7 +37,7 @@ } }, { - "ordinal": 2, + "ordinal": 3, "name": "starts_at: Timestamp", "type_info": "Int8", "origin": { @@ -37,7 +48,7 @@ } }, { - "ordinal": 3, + "ordinal": 4, "name": "ends_at: Timestamp", "type_info": "Int8", "origin": { @@ -48,7 +59,7 @@ } }, { - "ordinal": 4, + "ordinal": 5, "name": "archived_at: Timestamp", "type_info": "Int8", "origin": { @@ -64,7 +75,8 @@ "Uuid", "Text", "Int8", - "Int8" + "Int8", + "Uuid" ] }, "nullable": [ @@ -72,8 +84,9 @@ false, false, false, + false, true ] }, - "hash": "ff03e27f1d286af08d2468fee7c3e5121c55d9721e19c46c5e05b7ca79c785f4" + "hash": "5ebfcdfad4e6eb3342cb60e5743a7478fd357924360cf46a635c63aa072c19bf" } diff --git a/.sqlx/query-619c4c92014c8910ea8278b655d76d295ea421e1e27a8d0dca769b8896df5470.json b/.sqlx/query-619c4c92014c8910ea8278b655d76d295ea421e1e27a8d0dca769b8896df5470.json new file mode 100644 index 0000000..7796277 --- /dev/null +++ b/.sqlx/query-619c4c92014c8910ea8278b655d76d295ea421e1e27a8d0dca769b8896df5470.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT term AS \"term: TermId\" FROM exam WHERE id = $1 FOR UPDATE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "term: TermId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "exam", + "name": "term" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "619c4c92014c8910ea8278b655d76d295ea421e1e27a8d0dca769b8896df5470" +} diff --git a/.sqlx/query-61b2b846ba3a7a820c73bb3f0f81ccb3fefb6d3a83c081f6d0ed9caeab3e0bac.json b/.sqlx/query-61b2b846ba3a7a820c73bb3f0f81ccb3fefb6d3a83c081f6d0ed9caeab3e0bac.json new file mode 100644 index 0000000..99c7def --- /dev/null +++ b/.sqlx/query-61b2b846ba3a7a820c73bb3f0f81ccb3fefb6d3a83c081f6d0ed9caeab3e0bac.json @@ -0,0 +1,17 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO karne_snapshot (term, app_user, payload, created_at)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (term, app_user) DO UPDATE\n SET payload = EXCLUDED.payload, created_at = EXCLUDED.created_at", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Uuid", + "Jsonb", + "Int8" + ] + }, + "nullable": [] + }, + "hash": "61b2b846ba3a7a820c73bb3f0f81ccb3fefb6d3a83c081f6d0ed9caeab3e0bac" +} diff --git a/.sqlx/query-63bfd49bc95190d30571715c41de8dd2fe98a6a4ab2dfffc47c253c5e0cc6414.json b/.sqlx/query-63bfd49bc95190d30571715c41de8dd2fe98a6a4ab2dfffc47c253c5e0cc6414.json new file mode 100644 index 0000000..868dee0 --- /dev/null +++ b/.sqlx/query-63bfd49bc95190d30571715c41de8dd2fe98a6a4ab2dfffc47c253c5e0cc6414.json @@ -0,0 +1,119 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT cc.id AS \"id: ClassCourseId\", cc.class AS \"class: ClassGroupId\",\n cc.course AS \"course: CourseId\", cc.attached_by AS \"attached_by: UserId\",\n b.grade AS \"source?: ClassBlueprintId\",\n cc.ders_saati::bigint AS \"ders_saati!: DersSaati\",\n cc.counts_toward_karne, cc.enrollment_count,\n cc.attached_at AS \"attached_at: Timestamp\"\n FROM class_course cc\n LEFT JOIN class_blueprint b ON b.id = cc.source\n WHERE cc.class = ANY($1)\n ORDER BY cc.attached_at DESC, cc.id DESC", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: ClassCourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "class: ClassGroupId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "class" + } + } + }, + { + "ordinal": 2, + "name": "course: CourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "course" + } + } + }, + { + "ordinal": 3, + "name": "attached_by: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "attached_by" + } + } + }, + { + "ordinal": 4, + "name": "source?: ClassBlueprintId", + "type_info": "Text", + "origin": { + "Table": { + "table": "class_blueprint", + "name": "grade" + } + } + }, + { + "ordinal": 5, + "name": "ders_saati!: DersSaati", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 6, + "name": "counts_toward_karne", + "type_info": "Bool", + "origin": { + "Table": { + "table": "class_course", + "name": "counts_toward_karne" + } + } + }, + { + "ordinal": 7, + "name": "enrollment_count", + "type_info": "Int8", + "origin": { + "Table": { + "table": "class_course", + "name": "enrollment_count" + } + } + }, + { + "ordinal": 8, + "name": "attached_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "class_course", + "name": "attached_at" + } + } + } + ], + "parameters": { + "Left": [ + "UuidArray" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + null, + false, + false, + false + ] + }, + "hash": "63bfd49bc95190d30571715c41de8dd2fe98a6a4ab2dfffc47c253c5e0cc6414" +} diff --git a/.sqlx/query-6975e1ab374116eef46d9453fc93b6a64ba56a775aa5db356d212db2f54de648.json b/.sqlx/query-6975e1ab374116eef46d9453fc93b6a64ba56a775aa5db356d212db2f54de648.json new file mode 100644 index 0000000..3031340 --- /dev/null +++ b/.sqlx/query-6975e1ab374116eef46d9453fc93b6a64ba56a775aa5db356d212db2f54de648.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM class_course_teacher WHERE class_course = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "6975e1ab374116eef46d9453fc93b6a64ba56a775aa5db356d212db2f54de648" +} diff --git a/.sqlx/query-f3a4cec1ec1f46679602989fab57cc89a722030f6200af053c392dd6aa9ee9d3.json b/.sqlx/query-6a15b173fd0d6d1771319de73aaa95795ab707290b067d1115009dc2d824f6a3.json similarity index 93% rename from .sqlx/query-f3a4cec1ec1f46679602989fab57cc89a722030f6200af053c392dd6aa9ee9d3.json rename to .sqlx/query-6a15b173fd0d6d1771319de73aaa95795ab707290b067d1115009dc2d824f6a3.json index 7c4b41c..ec4695b 100644 --- a/.sqlx/query-f3a4cec1ec1f46679602989fab57cc89a722030f6200af053c392dd6aa9ee9d3.json +++ b/.sqlx/query-6a15b173fd0d6d1771319de73aaa95795ab707290b067d1115009dc2d824f6a3.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: HomeworkResultId\",\n homework AS \"homework: HomeworkId\",\n app_user AS \"user: UserId\",\n status AS \"status: HomeworkStatus\",\n mark AS \"mark: Mark\",\n graded_by AS \"graded_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework_result\n WHERE app_user = $1\n AND homework IN (SELECT id FROM homework WHERE course = $2)\n ORDER BY id DESC", + "query": "SELECT id AS \"id: HomeworkResultId\",\n homework AS \"homework: HomeworkId\",\n app_user AS \"user: UserId\",\n status AS \"status: HomeworkStatus\",\n mark AS \"mark: Mark\",\n graded_by AS \"graded_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework_result\n WHERE app_user = $1\n AND homework IN (SELECT id FROM homework WHERE class_course = $2)\n ORDER BY id DESC", "describe": { "columns": [ { @@ -97,5 +97,5 @@ false ] }, - "hash": "f3a4cec1ec1f46679602989fab57cc89a722030f6200af053c392dd6aa9ee9d3" + "hash": "6a15b173fd0d6d1771319de73aaa95795ab707290b067d1115009dc2d824f6a3" } diff --git a/.sqlx/query-6b3d5b06e9cdedb2bd7972fb7d5f01db24f8ac1167e4d5e8c0f885c131cfb716.json b/.sqlx/query-6b3d5b06e9cdedb2bd7972fb7d5f01db24f8ac1167e4d5e8c0f885c131cfb716.json deleted file mode 100644 index 06eacbf..0000000 --- a/.sqlx/query-6b3d5b06e9cdedb2bd7972fb7d5f01db24f8ac1167e4d5e8c0f885c131cfb716.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE course SET enrollment_count = enrollment_count - 1\n WHERE id = $1", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Uuid" - ] - }, - "nullable": [] - }, - "hash": "6b3d5b06e9cdedb2bd7972fb7d5f01db24f8ac1167e4d5e8c0f885c131cfb716" -} diff --git a/.sqlx/query-f19d64790b8c145113b680276ff897b1f4786e15116846e0288035e6ef1ca091.json b/.sqlx/query-6c4c14b2948967fa110b0af4e4d2b30b7af969358f18c389713e89056bb0b0cc.json similarity index 67% rename from .sqlx/query-f19d64790b8c145113b680276ff897b1f4786e15116846e0288035e6ef1ca091.json rename to .sqlx/query-6c4c14b2948967fa110b0af4e4d2b30b7af969358f18c389713e89056bb0b0cc.json index dc76186..0d18deb 100644 --- a/.sqlx/query-f19d64790b8c145113b680276ff897b1f4786e15116846e0288035e6ef1ca091.json +++ b/.sqlx/query-6c4c14b2948967fa110b0af4e4d2b30b7af969358f18c389713e89056bb0b0cc.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework\n WHERE course = $1\n AND (NOT EXISTS (SELECT 1 FROM homework_assignment a\n WHERE a.homework = homework.id)\n OR EXISTS (SELECT 1 FROM homework_assignment a\n WHERE a.homework = homework.id AND a.student = $2))\n ORDER BY id DESC", + "query": "SELECT id AS \"id: HomeworkId\",\n class_course AS \"class_course: ClassCourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework\n WHERE class_course = $1\n AND (NOT EXISTS (SELECT 1 FROM homework_assignment a\n WHERE a.homework = homework.id)\n OR EXISTS (SELECT 1 FROM homework_assignment a\n WHERE a.homework = homework.id AND a.student = $2))\n ORDER BY id DESC", "describe": { "columns": [ { @@ -16,12 +16,12 @@ }, { "ordinal": 1, - "name": "course: CourseId", + "name": "class_course: ClassCourseId", "type_info": "Uuid", "origin": { "Table": { "table": "homework", - "name": "course" + "name": "class_course" } } }, @@ -116,5 +116,5 @@ false ] }, - "hash": "f19d64790b8c145113b680276ff897b1f4786e15116846e0288035e6ef1ca091" + "hash": "6c4c14b2948967fa110b0af4e4d2b30b7af969358f18c389713e89056bb0b0cc" } diff --git a/.sqlx/query-6d9fc2433d41081225b1d03b1944965c9e35f61c3423e7c0ea36fd951ea9f988.json b/.sqlx/query-6d9fc2433d41081225b1d03b1944965c9e35f61c3423e7c0ea36fd951ea9f988.json new file mode 100644 index 0000000..de1bc71 --- /dev/null +++ b/.sqlx/query-6d9fc2433d41081225b1d03b1944965c9e35f61c3423e7c0ea36fd951ea9f988.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT teacher AS \"teacher: UserId\" FROM class_course_teacher\n WHERE class_course = $1 ORDER BY teacher", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "teacher: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course_teacher", + "name": "teacher" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "6d9fc2433d41081225b1d03b1944965c9e35f61c3423e7c0ea36fd951ea9f988" +} diff --git a/.sqlx/query-6efeb49c4351e1dfb26a97ab0e2f2e2dfd7b11cd99856f35a41e06d55004bede.json b/.sqlx/query-6efeb49c4351e1dfb26a97ab0e2f2e2dfd7b11cd99856f35a41e06d55004bede.json new file mode 100644 index 0000000..9496f51 --- /dev/null +++ b/.sqlx/query-6efeb49c4351e1dfb26a97ab0e2f2e2dfd7b11cd99856f35a41e06d55004bede.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO class_course_teacher (class_course, teacher)\n SELECT $1, $2 WHERE EXISTS (SELECT 1 FROM class_course WHERE id = $1)\n ON CONFLICT DO NOTHING", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "6efeb49c4351e1dfb26a97ab0e2f2e2dfd7b11cd99856f35a41e06d55004bede" +} diff --git a/.sqlx/query-6fafd69d5084dbc0da5c59746eeb6bdbb55926ea72f4ab85493e1bceb94f2754.json b/.sqlx/query-6fafd69d5084dbc0da5c59746eeb6bdbb55926ea72f4ab85493e1bceb94f2754.json new file mode 100644 index 0000000..d45395f --- /dev/null +++ b/.sqlx/query-6fafd69d5084dbc0da5c59746eeb6bdbb55926ea72f4ab85493e1bceb94f2754.json @@ -0,0 +1,24 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT 1 AS \"one\" FROM (\n SELECT e.app_user FROM enrollment e\n WHERE e.app_user = $2\n AND e.class_course IN (SELECT id FROM class_course WHERE course = $1)\n UNION ALL\n SELECT m.app_user FROM course_membership m\n WHERE m.course = $1 AND m.app_user = $2\n ) people LIMIT 1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "one", + "type_info": "Int4", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Uuid", + "Uuid" + ] + }, + "nullable": [ + null + ] + }, + "hash": "6fafd69d5084dbc0da5c59746eeb6bdbb55926ea72f4ab85493e1bceb94f2754" +} diff --git a/.sqlx/query-11181bfd9a0abc840f00738f1649925944ca1b05a034647d82835e7f12337591.json b/.sqlx/query-70d3d8c7cb74016eb71516a9db2fd7dd62bf80c388814ee0f5cdd771f22a5120.json similarity index 59% rename from .sqlx/query-11181bfd9a0abc840f00738f1649925944ca1b05a034647d82835e7f12337591.json rename to .sqlx/query-70d3d8c7cb74016eb71516a9db2fd7dd62bf80c388814ee0f5cdd771f22a5120.json index e0c68a9..b338739 100644 --- a/.sqlx/query-11181bfd9a0abc840f00738f1649925944ca1b05a034647d82835e7f12337591.json +++ b/.sqlx/query-70d3d8c7cb74016eb71516a9db2fd7dd62bf80c388814ee0f5cdd771f22a5120.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT course AS \"course: CourseId\", app_user AS \"user: UserId\",\n enrolled_by AS \"enrolled_by: UserId\", source AS \"source: ClassGroupId\"\n FROM enrollment WHERE course = $1 AND app_user = $2", + "query": "SELECT course AS \"course: CourseId\", app_user AS \"user: UserId\",\n added_by AS \"added_by: UserId\", created_at AS \"created_at: Timestamp\"\n FROM course_membership WHERE course = $1 AND app_user = $2", "describe": { "columns": [ { @@ -9,7 +9,7 @@ "type_info": "Uuid", "origin": { "Table": { - "table": "enrollment", + "table": "course_membership", "name": "course" } } @@ -20,30 +20,30 @@ "type_info": "Uuid", "origin": { "Table": { - "table": "enrollment", + "table": "course_membership", "name": "app_user" } } }, { "ordinal": 2, - "name": "enrolled_by: UserId", + "name": "added_by: UserId", "type_info": "Uuid", "origin": { "Table": { - "table": "enrollment", - "name": "enrolled_by" + "table": "course_membership", + "name": "added_by" } } }, { "ordinal": 3, - "name": "source: ClassGroupId", - "type_info": "Uuid", + "name": "created_at: Timestamp", + "type_info": "Int8", "origin": { "Table": { - "table": "enrollment", - "name": "source" + "table": "course_membership", + "name": "created_at" } } } @@ -58,8 +58,8 @@ false, false, false, - true + false ] }, - "hash": "11181bfd9a0abc840f00738f1649925944ca1b05a034647d82835e7f12337591" + "hash": "70d3d8c7cb74016eb71516a9db2fd7dd62bf80c388814ee0f5cdd771f22a5120" } diff --git a/.sqlx/query-719a5da335489982564b3334fd52f86ae36ff88ab1ee7ada8129de8baadea9cf.json b/.sqlx/query-719a5da335489982564b3334fd52f86ae36ff88ab1ee7ada8129de8baadea9cf.json new file mode 100644 index 0000000..6faf395 --- /dev/null +++ b/.sqlx/query-719a5da335489982564b3334fd52f86ae36ff88ab1ee7ada8129de8baadea9cf.json @@ -0,0 +1,65 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH gone AS (\n DELETE FROM course_membership\n WHERE course = $1 AND app_user = $2\n RETURNING course, app_user, added_by, created_at),\n counted AS (\n UPDATE course\n SET course_membership_count = GREATEST(\n course_membership_count - (SELECT count(*) FROM gone), 0)\n WHERE id = $1\n RETURNING 1)\n SELECT course AS \"course: CourseId\", app_user AS \"user: UserId\",\n added_by AS \"added_by: UserId\", created_at AS \"created_at: Timestamp\"\n FROM gone", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "course: CourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_membership", + "name": "course" + } + } + }, + { + "ordinal": 1, + "name": "user: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_membership", + "name": "app_user" + } + } + }, + { + "ordinal": 2, + "name": "added_by: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_membership", + "name": "added_by" + } + } + }, + { + "ordinal": 3, + "name": "created_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "course_membership", + "name": "created_at" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Uuid" + ] + }, + "nullable": [ + false, + false, + false, + false + ] + }, + "hash": "719a5da335489982564b3334fd52f86ae36ff88ab1ee7ada8129de8baadea9cf" +} diff --git a/.sqlx/query-f18d958fcfb0551be235244ab8b98856fd579f252ccf2a24c37cd34be968421c.json b/.sqlx/query-76cda1c341acce57e3f3fe57a377af9c9671ba4d7771d70d05449d3e0e15f348.json similarity index 65% rename from .sqlx/query-f18d958fcfb0551be235244ab8b98856fd579f252ccf2a24c37cd34be968421c.json rename to .sqlx/query-76cda1c341acce57e3f3fe57a377af9c9671ba4d7771d70d05449d3e0e15f348.json index 0dd9023..36cce64 100644 --- a/.sqlx/query-f18d958fcfb0551be235244ab8b98856fd579f252ccf2a24c37cd34be968421c.json +++ b/.sqlx/query-76cda1c341acce57e3f3fe57a377af9c9671ba4d7771d70d05449d3e0e15f348.json @@ -1,11 +1,11 @@ { "db_name": "PostgreSQL", - "query": "SELECT id FROM exam WHERE course = $1", + "query": "SELECT id AS \"id: uuid::Uuid\" FROM exam WHERE class_course = $1", "describe": { "columns": [ { "ordinal": 0, - "name": "id", + "name": "id: uuid::Uuid", "type_info": "Uuid", "origin": { "Table": { @@ -24,5 +24,5 @@ false ] }, - "hash": "f18d958fcfb0551be235244ab8b98856fd579f252ccf2a24c37cd34be968421c" + "hash": "76cda1c341acce57e3f3fe57a377af9c9671ba4d7771d70d05449d3e0e15f348" } diff --git a/.sqlx/query-77a3e1d1772a5d54ec33452c037aa8d10e9a27ed79880fb43b71f5ba9d9a6cc7.json b/.sqlx/query-77a3e1d1772a5d54ec33452c037aa8d10e9a27ed79880fb43b71f5ba9d9a6cc7.json deleted file mode 100644 index f268d64..0000000 --- a/.sqlx/query-77a3e1d1772a5d54ec33452c037aa8d10e9a27ed79880fb43b71f5ba9d9a6cc7.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE term SET class_count = GREATEST(class_count - 1, 0)\n WHERE id = $1", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Uuid" - ] - }, - "nullable": [] - }, - "hash": "77a3e1d1772a5d54ec33452c037aa8d10e9a27ed79880fb43b71f5ba9d9a6cc7" -} diff --git a/.sqlx/query-553487a166d9b3d9c0e3d4c7a5270c13768fb537393c70e006466df156a319a2.json b/.sqlx/query-77fc62012bd6363d83114c5814f981ae46af9b926746e5b37bcd937fab754437.json similarity index 73% rename from .sqlx/query-553487a166d9b3d9c0e3d4c7a5270c13768fb537393c70e006466df156a319a2.json rename to .sqlx/query-77fc62012bd6363d83114c5814f981ae46af9b926746e5b37bcd937fab754437.json index 8995ab3..9022522 100644 --- a/.sqlx/query-553487a166d9b3d9c0e3d4c7a5270c13768fb537393c70e006466df156a319a2.json +++ b/.sqlx/query-77fc62012bd6363d83114c5814f981ae46af9b926746e5b37bcd937fab754437.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO course (id, creator, title, description, kind, term, capacity)\n VALUES ($1, $2, $3, $4, $5, NULL, $6)\n RETURNING id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity", + "query": "INSERT INTO course (id, creator, title, description, kind)\n VALUES ($1, $2, $3, $4, $5)\n RETURNING id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", class_course_count, course_membership_count", "describe": { "columns": [ { @@ -60,23 +60,23 @@ }, { "ordinal": 5, - "name": "term: TermId", - "type_info": "Uuid", + "name": "class_course_count", + "type_info": "Int8", "origin": { "Table": { "table": "course", - "name": "term" + "name": "class_course_count" } } }, { "ordinal": 6, - "name": "capacity", + "name": "course_membership_count", "type_info": "Int8", "origin": { "Table": { "table": "course", - "name": "capacity" + "name": "course_membership_count" } } } @@ -87,8 +87,7 @@ "Uuid", "Text", "Text", - "Text", - "Int8" + "Text" ] }, "nullable": [ @@ -97,9 +96,9 @@ false, false, false, - true, - true + false, + false ] }, - "hash": "553487a166d9b3d9c0e3d4c7a5270c13768fb537393c70e006466df156a319a2" + "hash": "77fc62012bd6363d83114c5814f981ae46af9b926746e5b37bcd937fab754437" } diff --git a/.sqlx/query-786cd981b243bf0c325c5e3aedd34f93f78c53ca5744f1117af3701acdc4a26b.json b/.sqlx/query-786cd981b243bf0c325c5e3aedd34f93f78c53ca5744f1117af3701acdc4a26b.json new file mode 100644 index 0000000..990b8e1 --- /dev/null +++ b/.sqlx/query-786cd981b243bf0c325c5e3aedd34f93f78c53ca5744f1117af3701acdc4a26b.json @@ -0,0 +1,129 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO academic_year (id, name, starts_at, ends_at, creator, grade_promotions)\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING id AS \"id: AcademicYearId\", name AS \"name: AcademicYearName\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\",\n archived_at AS \"archived_at: Timestamp\", creator AS \"creator: UserId\",\n grade_promotions AS \"grade_promotions: Json>\",\n class_count, term_count", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: AcademicYearId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "academic_year", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "name: AcademicYearName", + "type_info": "Text", + "origin": { + "Table": { + "table": "academic_year", + "name": "name" + } + } + }, + { + "ordinal": 2, + "name": "starts_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "academic_year", + "name": "starts_at" + } + } + }, + { + "ordinal": 3, + "name": "ends_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "academic_year", + "name": "ends_at" + } + } + }, + { + "ordinal": 4, + "name": "archived_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "academic_year", + "name": "archived_at" + } + } + }, + { + "ordinal": 5, + "name": "creator: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "academic_year", + "name": "creator" + } + } + }, + { + "ordinal": 6, + "name": "grade_promotions: Json>", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "academic_year", + "name": "grade_promotions" + } + } + }, + { + "ordinal": 7, + "name": "class_count", + "type_info": "Int8", + "origin": { + "Table": { + "table": "academic_year", + "name": "class_count" + } + } + }, + { + "ordinal": 8, + "name": "term_count", + "type_info": "Int8", + "origin": { + "Table": { + "table": "academic_year", + "name": "term_count" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Text", + "Int8", + "Int8", + "Uuid", + "Jsonb" + ] + }, + "nullable": [ + false, + false, + false, + false, + true, + false, + false, + false, + false + ] + }, + "hash": "786cd981b243bf0c325c5e3aedd34f93f78c53ca5744f1117af3701acdc4a26b" +} diff --git a/.sqlx/query-798274cfd929c9142c52291dfb3860ecb756799f7593b3f8a2d0a7b0696bf8b1.json b/.sqlx/query-798274cfd929c9142c52291dfb3860ecb756799f7593b3f8a2d0a7b0696bf8b1.json new file mode 100644 index 0000000..967ed3e --- /dev/null +++ b/.sqlx/query-798274cfd929c9142c52291dfb3860ecb756799f7593b3f8a2d0a7b0696bf8b1.json @@ -0,0 +1,52 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT class_member_count, class_course_count, year AS \"year: uuid::Uuid\"\n FROM class_group WHERE id = $1 FOR UPDATE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "class_member_count", + "type_info": "Int8", + "origin": { + "Table": { + "table": "class_group", + "name": "class_member_count" + } + } + }, + { + "ordinal": 1, + "name": "class_course_count", + "type_info": "Int8", + "origin": { + "Table": { + "table": "class_group", + "name": "class_course_count" + } + } + }, + { + "ordinal": 2, + "name": "year: uuid::Uuid", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_group", + "name": "year" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + false, + true + ] + }, + "hash": "798274cfd929c9142c52291dfb3860ecb756799f7593b3f8a2d0a7b0696bf8b1" +} diff --git a/.sqlx/query-61c84c00d51c17a737b8358ac320d7b7d17420cdc12bd26939b3eca27088d275.json b/.sqlx/query-7bfe416ea8b08f2d1a4aaa81aef82762f91183c32dbc6114d7b1a02dafb1d51b.json similarity index 60% rename from .sqlx/query-61c84c00d51c17a737b8358ac320d7b7d17420cdc12bd26939b3eca27088d275.json rename to .sqlx/query-7bfe416ea8b08f2d1a4aaa81aef82762f91183c32dbc6114d7b1a02dafb1d51b.json index 077c691..4e4e8f0 100644 --- a/.sqlx/query-61c84c00d51c17a737b8358ac320d7b7d17420cdc12bd26939b3eca27088d275.json +++ b/.sqlx/query-7bfe416ea8b08f2d1a4aaa81aef82762f91183c32dbc6114d7b1a02dafb1d51b.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "DELETE FROM homework_assignment WHERE homework IN (\n SELECT id FROM homework WHERE course = $1)", + "query": "DELETE FROM homework_assignment WHERE homework IN (\n SELECT id FROM homework WHERE class_course = $1)", "describe": { "columns": [], "parameters": { @@ -10,5 +10,5 @@ }, "nullable": [] }, - "hash": "61c84c00d51c17a737b8358ac320d7b7d17420cdc12bd26939b3eca27088d275" + "hash": "7bfe416ea8b08f2d1a4aaa81aef82762f91183c32dbc6114d7b1a02dafb1d51b" } diff --git a/.sqlx/query-3f35044808071da4e1275f141b5f80b6974dff0cb59238f7ab0e1b51a389e6b1.json b/.sqlx/query-7ec20ef74e4c4c474e7b6d52a903bafdb4ffe23880c98df3870cd35dc7433448.json similarity index 74% rename from .sqlx/query-3f35044808071da4e1275f141b5f80b6974dff0cb59238f7ab0e1b51a389e6b1.json rename to .sqlx/query-7ec20ef74e4c4c474e7b6d52a903bafdb4ffe23880c98df3870cd35dc7433448.json index 38ab6be..f97d356 100644 --- a/.sqlx/query-3f35044808071da4e1275f141b5f80b6974dff0cb59238f7ab0e1b51a389e6b1.json +++ b/.sqlx/query-7ec20ef74e4c4c474e7b6d52a903bafdb4ffe23880c98df3870cd35dc7433448.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE id = $1 FOR UPDATE", + "query": "SELECT id AS \"id: HomeworkId\",\n class_course AS \"class_course: ClassCourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE class_course = $1 ORDER BY id DESC", "describe": { "columns": [ { @@ -16,12 +16,12 @@ }, { "ordinal": 1, - "name": "course: CourseId", + "name": "class_course: ClassCourseId", "type_info": "Uuid", "origin": { "Table": { "table": "homework", - "name": "course" + "name": "class_course" } } }, @@ -115,5 +115,5 @@ false ] }, - "hash": "3f35044808071da4e1275f141b5f80b6974dff0cb59238f7ab0e1b51a389e6b1" + "hash": "7ec20ef74e4c4c474e7b6d52a903bafdb4ffe23880c98df3870cd35dc7433448" } diff --git a/.sqlx/query-eefb6fc7a7f418d165f92618225b689ce8619494c52d43ddb09097744fb12565.json b/.sqlx/query-7ef15b73d204f84bbf71ddef3381b2cb2b8d818bb1aaf58197b8ab1e9afc425d.json similarity index 77% rename from .sqlx/query-eefb6fc7a7f418d165f92618225b689ce8619494c52d43ddb09097744fb12565.json rename to .sqlx/query-7ef15b73d204f84bbf71ddef3381b2cb2b8d818bb1aaf58197b8ab1e9afc425d.json index e362674..f0b85ab 100644 --- a/.sqlx/query-eefb6fc7a7f418d165f92618225b689ce8619494c52d43ddb09097744fb12565.json +++ b/.sqlx/query-7ef15b73d204f84bbf71ddef3381b2cb2b8d818bb1aaf58197b8ab1e9afc425d.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT app_user AS \"app_user: uuid::Uuid\" FROM class_member WHERE class = $1", + "query": "SELECT app_user AS \"app_user: uuid::Uuid\" FROM class_member\n WHERE class = $1 AND left_at IS NULL", "describe": { "columns": [ { @@ -24,5 +24,5 @@ false ] }, - "hash": "eefb6fc7a7f418d165f92618225b689ce8619494c52d43ddb09097744fb12565" + "hash": "7ef15b73d204f84bbf71ddef3381b2cb2b8d818bb1aaf58197b8ab1e9afc425d" } diff --git a/.sqlx/query-8cfb7acdfe6bb096f83920c104c8c45fafa1e717db6630c7e3fde77816d9e3a7.json b/.sqlx/query-7f1e995a1c731d6083e1c841f0c5d18de461c676133753c70cbffa5fe3bca6b5.json similarity index 74% rename from .sqlx/query-8cfb7acdfe6bb096f83920c104c8c45fafa1e717db6630c7e3fde77816d9e3a7.json rename to .sqlx/query-7f1e995a1c731d6083e1c841f0c5d18de461c676133753c70cbffa5fe3bca6b5.json index 66f563a..cf1842b 100644 --- a/.sqlx/query-8cfb7acdfe6bb096f83920c104c8c45fafa1e717db6630c7e3fde77816d9e3a7.json +++ b/.sqlx/query-7f1e995a1c731d6083e1c841f0c5d18de461c676133753c70cbffa5fe3bca6b5.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE course = ANY($1) ORDER BY id DESC", + "query": "SELECT id AS \"id: HomeworkId\",\n class_course AS \"class_course: ClassCourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE class_course = ANY($1) ORDER BY id DESC", "describe": { "columns": [ { @@ -16,12 +16,12 @@ }, { "ordinal": 1, - "name": "course: CourseId", + "name": "class_course: ClassCourseId", "type_info": "Uuid", "origin": { "Table": { "table": "homework", - "name": "course" + "name": "class_course" } } }, @@ -115,5 +115,5 @@ false ] }, - "hash": "8cfb7acdfe6bb096f83920c104c8c45fafa1e717db6630c7e3fde77816d9e3a7" + "hash": "7f1e995a1c731d6083e1c841f0c5d18de461c676133753c70cbffa5fe3bca6b5" } diff --git a/.sqlx/query-86f14780a8f9f8ec6df2ba19902c4bbe0c3aa2a987115e1231ba3726b496a10c.json b/.sqlx/query-8043002e1c5ae4f4158daa2f4598197a279e5d696b9fb6267bddc3aae64a6a4a.json similarity index 73% rename from .sqlx/query-86f14780a8f9f8ec6df2ba19902c4bbe0c3aa2a987115e1231ba3726b496a10c.json rename to .sqlx/query-8043002e1c5ae4f4158daa2f4598197a279e5d696b9fb6267bddc3aae64a6a4a.json index 90239ce..d61bbc6 100644 --- a/.sqlx/query-86f14780a8f9f8ec6df2ba19902c4bbe0c3aa2a987115e1231ba3726b496a10c.json +++ b/.sqlx/query-8043002e1c5ae4f4158daa2f4598197a279e5d696b9fb6267bddc3aae64a6a4a.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: ExamId\", creator AS \"creator: UserId\", course AS \"course: CourseId\",\n title AS \"title: ExamTitle\", description AS \"description: ExamDescription\",\n kind AS \"kind: ExamKind\", mode AS \"mode: ExamMode\",\n starts_at AS \"starts_at: Timestamp\",\n ends_at AS \"ends_at: Timestamp\",\n duration_ms AS \"duration_ms: ExamDuration\",\n max_attempts AS \"max_attempts: ExamAttemptLimit\",\n allow_rejoin, allow_review, draft\n FROM exam WHERE course = ANY($1) ORDER BY id DESC", + "query": "SELECT DISTINCT ON (e.id)\n e.id AS \"id: ExamId\", e.creator AS \"creator: UserId\",\n e.class_course AS \"class_course: ClassCourseId\",\n e.term AS \"term: TermId\", e.title AS \"title: ExamTitle\",\n e.description AS \"description: ExamDescription\",\n e.kind AS \"kind: ExamKind\", e.mode AS \"mode: ExamMode\",\n e.starts_at AS \"starts_at: Timestamp\",\n e.ends_at AS \"ends_at: Timestamp\",\n e.duration_ms AS \"duration_ms: ExamDuration\",\n e.max_attempts AS \"max_attempts: ExamAttemptLimit\",\n e.allow_rejoin, e.allow_review, e.draft\n FROM exam e\n JOIN exam_audience a ON a.exam = e.id\n WHERE a.class_course = ANY($1)\n ORDER BY e.id DESC", "describe": { "columns": [ { @@ -27,17 +27,28 @@ }, { "ordinal": 2, - "name": "course: CourseId", + "name": "class_course: ClassCourseId", "type_info": "Uuid", "origin": { "Table": { "table": "exam", - "name": "course" + "name": "class_course" } } }, { "ordinal": 3, + "name": "term: TermId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "exam", + "name": "term" + } + } + }, + { + "ordinal": 4, "name": "title: ExamTitle", "type_info": "Text", "origin": { @@ -48,7 +59,7 @@ } }, { - "ordinal": 4, + "ordinal": 5, "name": "description: ExamDescription", "type_info": "Text", "origin": { @@ -59,7 +70,7 @@ } }, { - "ordinal": 5, + "ordinal": 6, "name": "kind: ExamKind", "type_info": "Text", "origin": { @@ -70,7 +81,7 @@ } }, { - "ordinal": 6, + "ordinal": 7, "name": "mode: ExamMode", "type_info": "Text", "origin": { @@ -81,7 +92,7 @@ } }, { - "ordinal": 7, + "ordinal": 8, "name": "starts_at: Timestamp", "type_info": "Int8", "origin": { @@ -92,7 +103,7 @@ } }, { - "ordinal": 8, + "ordinal": 9, "name": "ends_at: Timestamp", "type_info": "Int8", "origin": { @@ -103,7 +114,7 @@ } }, { - "ordinal": 9, + "ordinal": 10, "name": "duration_ms: ExamDuration", "type_info": "Int8", "origin": { @@ -114,7 +125,7 @@ } }, { - "ordinal": 10, + "ordinal": 11, "name": "max_attempts: ExamAttemptLimit", "type_info": "Int8", "origin": { @@ -125,7 +136,7 @@ } }, { - "ordinal": 11, + "ordinal": 12, "name": "allow_rejoin", "type_info": "Bool", "origin": { @@ -136,7 +147,7 @@ } }, { - "ordinal": 12, + "ordinal": 13, "name": "allow_review", "type_info": "Bool", "origin": { @@ -147,7 +158,7 @@ } }, { - "ordinal": 13, + "ordinal": 14, "name": "draft", "type_info": "Bool", "origin": { @@ -170,6 +181,7 @@ false, false, false, + false, true, true, true, @@ -180,5 +192,5 @@ false ] }, - "hash": "86f14780a8f9f8ec6df2ba19902c4bbe0c3aa2a987115e1231ba3726b496a10c" + "hash": "8043002e1c5ae4f4158daa2f4598197a279e5d696b9fb6267bddc3aae64a6a4a" } diff --git a/.sqlx/query-83d5da7f52ee983e49f3c4dcd99472f5a8ba4a9017363f04c35173284da42037.json b/.sqlx/query-83d5da7f52ee983e49f3c4dcd99472f5a8ba4a9017363f04c35173284da42037.json deleted file mode 100644 index 826c30a..0000000 --- a/.sqlx/query-83d5da7f52ee983e49f3c4dcd99472f5a8ba4a9017363f04c35173284da42037.json +++ /dev/null @@ -1,145 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "WITH new_row AS (\n INSERT INTO settings (id, exam_kinds, grade_bands, max_file_bytes,\n chatbot_history_turns, max_chatbot_message_len,\n max_chatbot_threads, meal_slots,\n meal_cancel_cutoff_minutes)\n VALUES ('school', $1, $3, $4, $5, $6, $7, $8, $10)\n ON CONFLICT (id) DO UPDATE SET\n exam_kinds = $1,\n grade_bands = $3,\n max_file_bytes = $4,\n chatbot_history_turns = $5,\n max_chatbot_message_len = $6,\n max_chatbot_threads = $7,\n meal_slots = $8,\n meal_cancel_cutoff_minutes = $10\n WHERE settings.exam_kinds IS NOT DISTINCT FROM $13\n AND settings.grade_bands IS NOT DISTINCT FROM $14\n AND settings.max_file_bytes IS NOT DISTINCT FROM $15\n AND settings.chatbot_history_turns IS NOT DISTINCT FROM $16\n AND settings.max_chatbot_message_len IS NOT DISTINCT FROM $17\n AND settings.max_chatbot_threads IS NOT DISTINCT FROM $18\n AND settings.meal_slots IS NOT DISTINCT FROM $19\n AND settings.meal_cancel_cutoff_minutes IS NOT DISTINCT FROM $20\n AND COALESCE((SELECT array_agg(s.status ORDER BY s.status)\n FROM settings_attendance_status s\n WHERE s.settings = settings.id), '{}')\n IS NOT DISTINCT FROM $11::text[]\n AND (SELECT array_agg(t.tag ORDER BY t.tag)\n FROM settings_dietary_tag t\n WHERE t.settings = settings.id)\n IS NOT DISTINCT FROM $12::text[]\n RETURNING exam_kinds, grade_bands, max_file_bytes,\n chatbot_history_turns, max_chatbot_message_len,\n max_chatbot_threads, meal_slots, meal_cancel_cutoff_minutes),\n status_del AS (\n DELETE FROM settings_attendance_status\n WHERE settings = 'school' AND EXISTS (SELECT 1 FROM new_row)\n RETURNING 1),\n status_ins AS (\n INSERT INTO settings_attendance_status (settings, status)\n SELECT 'school', t.status FROM unnest($2::text[]) AS t(status)\n CROSS JOIN (SELECT count(*) AS deleted FROM status_del) d\n WHERE EXISTS (SELECT 1 FROM new_row)\n RETURNING status),\n tag_del AS (\n DELETE FROM settings_dietary_tag\n WHERE settings = 'school' AND EXISTS (SELECT 1 FROM new_row)\n RETURNING 1),\n tag_ins AS (\n INSERT INTO settings_dietary_tag (settings, tag)\n SELECT 'school', t.tag FROM unnest($9::text[]) AS t(tag)\n CROSS JOIN (SELECT count(*) AS deleted FROM tag_del) d\n WHERE EXISTS (SELECT 1 FROM new_row)\n RETURNING tag)\n SELECT r.exam_kinds AS \"exam_kinds: Json>\",\n COALESCE((SELECT array_agg(status ORDER BY status)\n FROM status_ins), '{}') AS \"attendance_statuses!: Vec\",\n r.grade_bands AS \"grade_bands: Json>\",\n r.max_file_bytes,\n r.chatbot_history_turns,\n r.max_chatbot_message_len,\n r.max_chatbot_threads,\n r.meal_slots AS \"meal_slots: Json>\",\n (SELECT array_agg(tag ORDER BY tag) FROM tag_ins) AS dietary_tags,\n r.meal_cancel_cutoff_minutes\n FROM new_row r", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "exam_kinds: Json>", - "type_info": "Jsonb", - "origin": { - "Table": { - "table": "settings", - "name": "exam_kinds" - } - } - }, - { - "ordinal": 1, - "name": "attendance_statuses!: Vec", - "type_info": "TextArray", - "origin": "Expression" - }, - { - "ordinal": 2, - "name": "grade_bands: Json>", - "type_info": "Jsonb", - "origin": { - "Table": { - "table": "settings", - "name": "grade_bands" - } - } - }, - { - "ordinal": 3, - "name": "max_file_bytes", - "type_info": "Int8", - "origin": { - "Table": { - "table": "settings", - "name": "max_file_bytes" - } - } - }, - { - "ordinal": 4, - "name": "chatbot_history_turns", - "type_info": "Int8", - "origin": { - "Table": { - "table": "settings", - "name": "chatbot_history_turns" - } - } - }, - { - "ordinal": 5, - "name": "max_chatbot_message_len", - "type_info": "Int8", - "origin": { - "Table": { - "table": "settings", - "name": "max_chatbot_message_len" - } - } - }, - { - "ordinal": 6, - "name": "max_chatbot_threads", - "type_info": "Int8", - "origin": { - "Table": { - "table": "settings", - "name": "max_chatbot_threads" - } - } - }, - { - "ordinal": 7, - "name": "meal_slots: Json>", - "type_info": "Jsonb", - "origin": { - "Table": { - "table": "settings", - "name": "meal_slots" - } - } - }, - { - "ordinal": 8, - "name": "dietary_tags", - "type_info": "TextArray", - "origin": "Expression" - }, - { - "ordinal": 9, - "name": "meal_cancel_cutoff_minutes", - "type_info": "Int8", - "origin": { - "Table": { - "table": "settings", - "name": "meal_cancel_cutoff_minutes" - } - } - } - ], - "parameters": { - "Left": [ - "Jsonb", - "TextArray", - "Jsonb", - "Int8", - "Int8", - "Int8", - "Int8", - "Jsonb", - "TextArray", - "Int8", - "TextArray", - "TextArray", - "Jsonb", - "Jsonb", - "Int8", - "Int8", - "Int8", - "Int8", - "Jsonb", - "Int8" - ] - }, - "nullable": [ - false, - null, - false, - true, - true, - true, - true, - true, - null, - true - ] - }, - "hash": "83d5da7f52ee983e49f3c4dcd99472f5a8ba4a9017363f04c35173284da42037" -} diff --git a/.sqlx/query-a92d51459fd6a61999d70d959abd8bf67e730615135df1850ccf57de3090a402.json b/.sqlx/query-852e8ede2b2713be5244b108c8e74d5fe800c12fa4e1f6c30f68b80f07509ef9.json similarity index 74% rename from .sqlx/query-a92d51459fd6a61999d70d959abd8bf67e730615135df1850ccf57de3090a402.json rename to .sqlx/query-852e8ede2b2713be5244b108c8e74d5fe800c12fa4e1f6c30f68b80f07509ef9.json index 72f5172..c63761f 100644 --- a/.sqlx/query-a92d51459fd6a61999d70d959abd8bf67e730615135df1850ccf57de3090a402.json +++ b/.sqlx/query-852e8ede2b2713be5244b108c8e74d5fe800c12fa4e1f6c30f68b80f07509ef9.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT session AS \"session: CourseSessionId\", app_user AS \"user: UserId\",\n course AS \"course: CourseId\", status AS \"status: AttendanceStatus\",\n marked_by AS \"marked_by: UserId\"\n FROM session_attendance WHERE app_user = $1\n ORDER BY session DESC, app_user DESC", + "query": "SELECT session AS \"session: CourseSessionId\", app_user AS \"user: UserId\",\n class_course AS \"class_course: ClassCourseId\",\n status AS \"status: AttendanceStatus\",\n marked_by AS \"marked_by: UserId\"\n FROM session_attendance\n WHERE session = $1 AND app_user = $2\n FOR UPDATE", "describe": { "columns": [ { @@ -27,12 +27,12 @@ }, { "ordinal": 2, - "name": "course: CourseId", + "name": "class_course: ClassCourseId", "type_info": "Uuid", "origin": { "Table": { "table": "session_attendance", - "name": "course" + "name": "class_course" } } }, @@ -61,6 +61,7 @@ ], "parameters": { "Left": [ + "Uuid", "Uuid" ] }, @@ -72,5 +73,5 @@ false ] }, - "hash": "a92d51459fd6a61999d70d959abd8bf67e730615135df1850ccf57de3090a402" + "hash": "852e8ede2b2713be5244b108c8e74d5fe800c12fa4e1f6c30f68b80f07509ef9" } diff --git a/.sqlx/query-e7049ca4ddf6a6103dbecabe61f56992e9e2105e5c2de3b148d5533e4ffc8989.json b/.sqlx/query-85c6837e943dbff5b411062672966a15f9eaa9da3501ac6ab774842587b3158f.json similarity index 92% rename from .sqlx/query-e7049ca4ddf6a6103dbecabe61f56992e9e2105e5c2de3b148d5533e4ffc8989.json rename to .sqlx/query-85c6837e943dbff5b411062672966a15f9eaa9da3501ac6ab774842587b3158f.json index d198823..fc7463a 100644 --- a/.sqlx/query-e7049ca4ddf6a6103dbecabe61f56992e9e2105e5c2de3b148d5533e4ffc8989.json +++ b/.sqlx/query-85c6837e943dbff5b411062672966a15f9eaa9da3501ac6ab774842587b3158f.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n avatar_size\n FROM app_user WHERE id = $1 FOR UPDATE", + "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n branch,\n avatar_size\n FROM app_user WHERE id = $1 FOR UPDATE", "describe": { "columns": [ { @@ -181,6 +181,17 @@ }, { "ordinal": 16, + "name": "branch", + "type_info": "Text", + "origin": { + "Table": { + "table": "app_user", + "name": "branch" + } + } + }, + { + "ordinal": 17, "name": "avatar_size", "type_info": "Int8", "origin": { @@ -213,8 +224,9 @@ true, true, true, + true, true ] }, - "hash": "e7049ca4ddf6a6103dbecabe61f56992e9e2105e5c2de3b148d5533e4ffc8989" + "hash": "85c6837e943dbff5b411062672966a15f9eaa9da3501ac6ab774842587b3158f" } diff --git a/.sqlx/query-716d9e1ecf8ea90abaf127ffb5b1b437be5acb0b4b8e49f53de51a1d31566c07.json b/.sqlx/query-87d155cfa8873b0ef20d5c940bb40effbc3eff4648cc6383428794385d6e5381.json similarity index 66% rename from .sqlx/query-716d9e1ecf8ea90abaf127ffb5b1b437be5acb0b4b8e49f53de51a1d31566c07.json rename to .sqlx/query-87d155cfa8873b0ef20d5c940bb40effbc3eff4648cc6383428794385d6e5381.json index 23abb84..b60a2a4 100644 --- a/.sqlx/query-716d9e1ecf8ea90abaf127ffb5b1b437be5acb0b4b8e49f53de51a1d31566c07.json +++ b/.sqlx/query-87d155cfa8873b0ef20d5c940bb40effbc3eff4648cc6383428794385d6e5381.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT file FROM homework_file\n WHERE submission IN (\n SELECT id FROM homework_submission\n WHERE homework IN (SELECT id FROM homework WHERE course = $1)\n )", + "query": "SELECT file FROM homework_file\n WHERE submission IN (SELECT id FROM homework_submission WHERE homework IN (\n SELECT id FROM homework WHERE class_course = $1))", "describe": { "columns": [ { @@ -24,5 +24,5 @@ false ] }, - "hash": "716d9e1ecf8ea90abaf127ffb5b1b437be5acb0b4b8e49f53de51a1d31566c07" + "hash": "87d155cfa8873b0ef20d5c940bb40effbc3eff4648cc6383428794385d6e5381" } diff --git a/.sqlx/query-2ab51ad375937884da43590de2ca4810dd0a8bfb1290a626ae40f31ca469a632.json b/.sqlx/query-881c48b6dbe3f2a277a120b9b50c21b51853743ede360b1cd589b2540ddc5663.json similarity index 80% rename from .sqlx/query-2ab51ad375937884da43590de2ca4810dd0a8bfb1290a626ae40f31ca469a632.json rename to .sqlx/query-881c48b6dbe3f2a277a120b9b50c21b51853743ede360b1cd589b2540ddc5663.json index caf3499..7bb0e82 100644 --- a/.sqlx/query-2ab51ad375937884da43590de2ca4810dd0a8bfb1290a626ae40f31ca469a632.json +++ b/.sqlx/query-881c48b6dbe3f2a277a120b9b50c21b51853743ede360b1cd589b2540ddc5663.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity\n FROM course WHERE id = ANY($1)", + "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", class_course_count, course_membership_count\n FROM course WHERE id = ANY($1)", "describe": { "columns": [ { @@ -60,23 +60,23 @@ }, { "ordinal": 5, - "name": "term: TermId", - "type_info": "Uuid", + "name": "class_course_count", + "type_info": "Int8", "origin": { "Table": { "table": "course", - "name": "term" + "name": "class_course_count" } } }, { "ordinal": 6, - "name": "capacity", + "name": "course_membership_count", "type_info": "Int8", "origin": { "Table": { "table": "course", - "name": "capacity" + "name": "course_membership_count" } } } @@ -92,9 +92,9 @@ false, false, false, - true, - true + false, + false ] }, - "hash": "2ab51ad375937884da43590de2ca4810dd0a8bfb1290a626ae40f31ca469a632" + "hash": "881c48b6dbe3f2a277a120b9b50c21b51853743ede360b1cd589b2540ddc5663" } diff --git a/.sqlx/query-8aae97d23b8c2da4be5def3d350c2fe1fb78b8157c1db427bee32014dfa3dc84.json b/.sqlx/query-8aae97d23b8c2da4be5def3d350c2fe1fb78b8157c1db427bee32014dfa3dc84.json deleted file mode 100644 index 45ac74d..0000000 --- a/.sqlx/query-8aae97d23b8c2da4be5def3d350c2fe1fb78b8157c1db427bee32014dfa3dc84.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "WITH gone AS (\n DELETE FROM class_member WHERE app_user = $1 RETURNING class\n )\n UPDATE class_group\n SET class_member_count = GREATEST(class_member_count - 1, 0)\n WHERE id IN (SELECT gone.class FROM gone)", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Uuid" - ] - }, - "nullable": [] - }, - "hash": "8aae97d23b8c2da4be5def3d350c2fe1fb78b8157c1db427bee32014dfa3dc84" -} diff --git a/.sqlx/query-8c2168cfc71adc23d664dc5cf830c9e25d5af1371fd17c109826757b76a558a2.json b/.sqlx/query-8c2168cfc71adc23d664dc5cf830c9e25d5af1371fd17c109826757b76a558a2.json new file mode 100644 index 0000000..a364e99 --- /dev/null +++ b/.sqlx/query-8c2168cfc71adc23d664dc5cf830c9e25d5af1371fd17c109826757b76a558a2.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH gone AS (\n DELETE FROM course_membership WHERE app_user = $1 RETURNING course\n )\n UPDATE course\n SET course_membership_count = GREATEST(course_membership_count - 1, 0)\n WHERE id IN (SELECT gone.course FROM gone)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "8c2168cfc71adc23d664dc5cf830c9e25d5af1371fd17c109826757b76a558a2" +} diff --git a/.sqlx/query-8d42c2a8b87d9f503f123515bc00554d4a9dc13dfa7f3acc707d464a83899777.json b/.sqlx/query-8d42c2a8b87d9f503f123515bc00554d4a9dc13dfa7f3acc707d464a83899777.json new file mode 100644 index 0000000..ddb2b30 --- /dev/null +++ b/.sqlx/query-8d42c2a8b87d9f503f123515bc00554d4a9dc13dfa7f3acc707d464a83899777.json @@ -0,0 +1,24 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM class_member\n WHERE class = $1 AND app_user = $2 AND left_at IS NULL\n RETURNING 1 AS \"one\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "one", + "type_info": "Int4", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Uuid", + "Uuid" + ] + }, + "nullable": [ + null + ] + }, + "hash": "8d42c2a8b87d9f503f123515bc00554d4a9dc13dfa7f3acc707d464a83899777" +} diff --git a/.sqlx/query-8d76160e8b143ddee72c34878fbe9bf3140bea9c12f8c3ba324fc16c81167905.json b/.sqlx/query-8d76160e8b143ddee72c34878fbe9bf3140bea9c12f8c3ba324fc16c81167905.json new file mode 100644 index 0000000..7bcf42d --- /dev/null +++ b/.sqlx/query-8d76160e8b143ddee72c34878fbe9bf3140bea9c12f8c3ba324fc16c81167905.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH gone AS (\n DELETE FROM exam WHERE class_course = $1\n RETURNING term),\n terms AS (\n SELECT term, count(*) AS n FROM gone GROUP BY term)\n UPDATE term t SET exam_count = GREATEST(t.exam_count - c.n, 0)\n FROM terms c WHERE t.id = c.term", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "8d76160e8b143ddee72c34878fbe9bf3140bea9c12f8c3ba324fc16c81167905" +} diff --git a/.sqlx/query-58e602261d1ddb31b9b0d25cb87f46934b0c584727551c8f85d4744b543af99f.json b/.sqlx/query-8fb4f8d22b9aca20a9cfa7de35bd4bac5ce3a0bfdbd4059a08b0b27d25b62537.json similarity index 92% rename from .sqlx/query-58e602261d1ddb31b9b0d25cb87f46934b0c584727551c8f85d4744b543af99f.json rename to .sqlx/query-8fb4f8d22b9aca20a9cfa7de35bd4bac5ce3a0bfdbd4059a08b0b27d25b62537.json index 531efb0..7ce8f53 100644 --- a/.sqlx/query-58e602261d1ddb31b9b0d25cb87f46934b0c584727551c8f85d4744b543af99f.json +++ b/.sqlx/query-8fb4f8d22b9aca20a9cfa7de35bd4bac5ce3a0bfdbd4059a08b0b27d25b62537.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n avatar_size\n FROM app_user WHERE id = $1", + "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n branch,\n avatar_size\n FROM app_user WHERE id = $1", "describe": { "columns": [ { @@ -181,6 +181,17 @@ }, { "ordinal": 16, + "name": "branch", + "type_info": "Text", + "origin": { + "Table": { + "table": "app_user", + "name": "branch" + } + } + }, + { + "ordinal": 17, "name": "avatar_size", "type_info": "Int8", "origin": { @@ -213,8 +224,9 @@ true, true, true, + true, true ] }, - "hash": "58e602261d1ddb31b9b0d25cb87f46934b0c584727551c8f85d4744b543af99f" + "hash": "8fb4f8d22b9aca20a9cfa7de35bd4bac5ce3a0bfdbd4059a08b0b27d25b62537" } diff --git a/.sqlx/query-1f177f50cbca268c6586d099964dc9970bcc3aea1a65bb486f4510803f4d0019.json b/.sqlx/query-8fcc7fe1692f122310769d3575feabbf9648a92d9c0ad9ecb62a69779c21ef43.json similarity index 80% rename from .sqlx/query-1f177f50cbca268c6586d099964dc9970bcc3aea1a65bb486f4510803f4d0019.json rename to .sqlx/query-8fcc7fe1692f122310769d3575feabbf9648a92d9c0ad9ecb62a69779c21ef43.json index 271dabe..76220d8 100644 --- a/.sqlx/query-1f177f50cbca268c6586d099964dc9970bcc3aea1a65bb486f4510803f4d0019.json +++ b/.sqlx/query-8fcc7fe1692f122310769d3575feabbf9648a92d9c0ad9ecb62a69779c21ef43.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity\n FROM course ORDER BY id DESC", + "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", class_course_count, course_membership_count\n FROM course ORDER BY id DESC", "describe": { "columns": [ { @@ -60,23 +60,23 @@ }, { "ordinal": 5, - "name": "term: TermId", - "type_info": "Uuid", + "name": "class_course_count", + "type_info": "Int8", "origin": { "Table": { "table": "course", - "name": "term" + "name": "class_course_count" } } }, { "ordinal": 6, - "name": "capacity", + "name": "course_membership_count", "type_info": "Int8", "origin": { "Table": { "table": "course", - "name": "capacity" + "name": "course_membership_count" } } } @@ -90,9 +90,9 @@ false, false, false, - true, - true + false, + false ] }, - "hash": "1f177f50cbca268c6586d099964dc9970bcc3aea1a65bb486f4510803f4d0019" + "hash": "8fcc7fe1692f122310769d3575feabbf9648a92d9c0ad9ecb62a69779c21ef43" } diff --git a/.sqlx/query-92ea6ff42015debf72f3b8c0ddd7231567b66c5dbd0dfd2963a28b4c165f06ab.json b/.sqlx/query-92ea6ff42015debf72f3b8c0ddd7231567b66c5dbd0dfd2963a28b4c165f06ab.json deleted file mode 100644 index 9bf30f2..0000000 --- a/.sqlx/query-92ea6ff42015debf72f3b8c0ddd7231567b66c5dbd0dfd2963a28b4c165f06ab.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "DELETE FROM class_group\n WHERE id = $1\n AND class_member_count = 0 AND class_course_count = 0\n RETURNING term AS \"term: uuid::Uuid\"", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "term: uuid::Uuid", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "class_group", - "name": "term" - } - } - } - ], - "parameters": { - "Left": [ - "Uuid" - ] - }, - "nullable": [ - true - ] - }, - "hash": "92ea6ff42015debf72f3b8c0ddd7231567b66c5dbd0dfd2963a28b4c165f06ab" -} diff --git a/.sqlx/query-9940a3506ed6882085ce27f65989e951ea068ae7b732f465dc51153f7bc6179f.json b/.sqlx/query-9940a3506ed6882085ce27f65989e951ea068ae7b732f465dc51153f7bc6179f.json deleted file mode 100644 index 3f159f1..0000000 --- a/.sqlx/query-9940a3506ed6882085ce27f65989e951ea068ae7b732f465dc51153f7bc6179f.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE course SET enrollment_count = GREATEST(enrollment_count - 1, 0)\n WHERE id = $1", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Uuid" - ] - }, - "nullable": [] - }, - "hash": "9940a3506ed6882085ce27f65989e951ea068ae7b732f465dc51153f7bc6179f" -} diff --git a/.sqlx/query-9deffffa653f4fd1ca19b27972a9fcdbc399d9548adbff68bfd32af4a1adc4dd.json b/.sqlx/query-9deffffa653f4fd1ca19b27972a9fcdbc399d9548adbff68bfd32af4a1adc4dd.json new file mode 100644 index 0000000..095719f --- /dev/null +++ b/.sqlx/query-9deffffa653f4fd1ca19b27972a9fcdbc399d9548adbff68bfd32af4a1adc4dd.json @@ -0,0 +1,215 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH new_row AS (\n INSERT INTO settings (id, exam_kinds, grade_bands, max_file_bytes,\n chatbot_history_turns, max_chatbot_message_len,\n max_chatbot_threads, meal_slots,\n meal_cancel_cutoff_minutes, branches, excuse_kinds,\n max_excused_absent_days, max_unexcused_absent_days,\n timezone)\n VALUES ('school', $1, $3, $4, $5, $6, $7, $8, $10, $21, $22, $23, $24, $25)\n ON CONFLICT (id) DO UPDATE SET\n exam_kinds = $1,\n grade_bands = $3,\n max_file_bytes = $4,\n chatbot_history_turns = $5,\n max_chatbot_message_len = $6,\n max_chatbot_threads = $7,\n meal_slots = $8,\n meal_cancel_cutoff_minutes = $10,\n branches = $21,\n excuse_kinds = $22,\n max_excused_absent_days = $23,\n max_unexcused_absent_days = $24,\n timezone = $25\n WHERE settings.exam_kinds IS NOT DISTINCT FROM $13\n AND settings.grade_bands IS NOT DISTINCT FROM $14\n AND settings.max_file_bytes IS NOT DISTINCT FROM $15\n AND settings.chatbot_history_turns IS NOT DISTINCT FROM $16\n AND settings.max_chatbot_message_len IS NOT DISTINCT FROM $17\n AND settings.max_chatbot_threads IS NOT DISTINCT FROM $18\n AND settings.meal_slots IS NOT DISTINCT FROM $19\n AND settings.meal_cancel_cutoff_minutes IS NOT DISTINCT FROM $20\n AND settings.branches IS NOT DISTINCT FROM $26\n AND settings.excuse_kinds IS NOT DISTINCT FROM $27\n AND settings.max_excused_absent_days IS NOT DISTINCT FROM $28\n AND settings.max_unexcused_absent_days IS NOT DISTINCT FROM $29\n AND settings.timezone IS NOT DISTINCT FROM $30\n AND COALESCE((SELECT array_agg(s.status ORDER BY s.status)\n FROM settings_attendance_status s\n WHERE s.settings = settings.id), '{}')\n IS NOT DISTINCT FROM $11::text[]\n AND (SELECT array_agg(t.tag ORDER BY t.tag)\n FROM settings_dietary_tag t\n WHERE t.settings = settings.id)\n IS NOT DISTINCT FROM $12::text[]\n RETURNING exam_kinds, grade_bands, max_file_bytes,\n chatbot_history_turns, max_chatbot_message_len,\n max_chatbot_threads, meal_slots, meal_cancel_cutoff_minutes,\n branches, excuse_kinds, max_excused_absent_days,\n max_unexcused_absent_days, timezone),\n status_del AS (\n DELETE FROM settings_attendance_status\n WHERE settings = 'school' AND EXISTS (SELECT 1 FROM new_row)\n RETURNING 1),\n status_ins AS (\n INSERT INTO settings_attendance_status (settings, status)\n SELECT 'school', t.status FROM unnest($2::text[]) AS t(status)\n CROSS JOIN (SELECT count(*) AS deleted FROM status_del) d\n WHERE EXISTS (SELECT 1 FROM new_row)\n RETURNING status),\n tag_del AS (\n DELETE FROM settings_dietary_tag\n WHERE settings = 'school' AND EXISTS (SELECT 1 FROM new_row)\n RETURNING 1),\n tag_ins AS (\n INSERT INTO settings_dietary_tag (settings, tag)\n SELECT 'school', t.tag FROM unnest($9::text[]) AS t(tag)\n CROSS JOIN (SELECT count(*) AS deleted FROM tag_del) d\n WHERE EXISTS (SELECT 1 FROM new_row)\n RETURNING tag)\n SELECT r.exam_kinds AS \"exam_kinds: Json>\",\n COALESCE((SELECT array_agg(status ORDER BY status)\n FROM status_ins), '{}') AS \"attendance_statuses!: Vec\",\n r.grade_bands AS \"grade_bands: Json>\",\n r.max_file_bytes,\n r.chatbot_history_turns,\n r.max_chatbot_message_len,\n r.max_chatbot_threads,\n r.meal_slots AS \"meal_slots: Json>\",\n (SELECT array_agg(tag ORDER BY tag) FROM tag_ins) AS dietary_tags,\n r.meal_cancel_cutoff_minutes,\n r.branches AS \"branches: Json>\",\n r.excuse_kinds AS \"excuse_kinds: Json>\",\n r.max_excused_absent_days,\n r.max_unexcused_absent_days,\n r.timezone\n FROM new_row r", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "exam_kinds: Json>", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "settings", + "name": "exam_kinds" + } + } + }, + { + "ordinal": 1, + "name": "attendance_statuses!: Vec", + "type_info": "TextArray", + "origin": "Expression" + }, + { + "ordinal": 2, + "name": "grade_bands: Json>", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "settings", + "name": "grade_bands" + } + } + }, + { + "ordinal": 3, + "name": "max_file_bytes", + "type_info": "Int8", + "origin": { + "Table": { + "table": "settings", + "name": "max_file_bytes" + } + } + }, + { + "ordinal": 4, + "name": "chatbot_history_turns", + "type_info": "Int8", + "origin": { + "Table": { + "table": "settings", + "name": "chatbot_history_turns" + } + } + }, + { + "ordinal": 5, + "name": "max_chatbot_message_len", + "type_info": "Int8", + "origin": { + "Table": { + "table": "settings", + "name": "max_chatbot_message_len" + } + } + }, + { + "ordinal": 6, + "name": "max_chatbot_threads", + "type_info": "Int8", + "origin": { + "Table": { + "table": "settings", + "name": "max_chatbot_threads" + } + } + }, + { + "ordinal": 7, + "name": "meal_slots: Json>", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "settings", + "name": "meal_slots" + } + } + }, + { + "ordinal": 8, + "name": "dietary_tags", + "type_info": "TextArray", + "origin": "Expression" + }, + { + "ordinal": 9, + "name": "meal_cancel_cutoff_minutes", + "type_info": "Int8", + "origin": { + "Table": { + "table": "settings", + "name": "meal_cancel_cutoff_minutes" + } + } + }, + { + "ordinal": 10, + "name": "branches: Json>", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "settings", + "name": "branches" + } + } + }, + { + "ordinal": 11, + "name": "excuse_kinds: Json>", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "settings", + "name": "excuse_kinds" + } + } + }, + { + "ordinal": 12, + "name": "max_excused_absent_days", + "type_info": "Int8", + "origin": { + "Table": { + "table": "settings", + "name": "max_excused_absent_days" + } + } + }, + { + "ordinal": 13, + "name": "max_unexcused_absent_days", + "type_info": "Int8", + "origin": { + "Table": { + "table": "settings", + "name": "max_unexcused_absent_days" + } + } + }, + { + "ordinal": 14, + "name": "timezone", + "type_info": "Text", + "origin": { + "Table": { + "table": "settings", + "name": "timezone" + } + } + } + ], + "parameters": { + "Left": [ + "Jsonb", + "TextArray", + "Jsonb", + "Int8", + "Int8", + "Int8", + "Int8", + "Jsonb", + "TextArray", + "Int8", + "TextArray", + "TextArray", + "Jsonb", + "Jsonb", + "Int8", + "Int8", + "Int8", + "Int8", + "Jsonb", + "Int8", + "Jsonb", + "Jsonb", + "Int8", + "Int8", + "Text", + "Jsonb", + "Jsonb", + "Int8", + "Int8", + "Text" + ] + }, + "nullable": [ + false, + null, + false, + true, + true, + true, + true, + true, + null, + true, + true, + true, + true, + true, + true + ] + }, + "hash": "9deffffa653f4fd1ca19b27972a9fcdbc399d9548adbff68bfd32af4a1adc4dd" +} diff --git a/.sqlx/query-9e70ed1446d7ca45b78aa8dfb9842a877dfac056dea7b17e702bdea174b0993a.json b/.sqlx/query-9e70ed1446d7ca45b78aa8dfb9842a877dfac056dea7b17e702bdea174b0993a.json deleted file mode 100644 index 967830d..0000000 --- a/.sqlx/query-9e70ed1446d7ca45b78aa8dfb9842a877dfac056dea7b17e702bdea174b0993a.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO course_teacher (course, teacher)\n SELECT $1, $2 WHERE EXISTS (SELECT 1 FROM course WHERE id = $1)\n ON CONFLICT DO NOTHING", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Uuid", - "Uuid" - ] - }, - "nullable": [] - }, - "hash": "9e70ed1446d7ca45b78aa8dfb9842a877dfac056dea7b17e702bdea174b0993a" -} diff --git a/.sqlx/query-9e916d8594cc7fba78ed9661a00e146c2128431f24d78885cddf87325bae9cd5.json b/.sqlx/query-9e916d8594cc7fba78ed9661a00e146c2128431f24d78885cddf87325bae9cd5.json new file mode 100644 index 0000000..e0be11d --- /dev/null +++ b/.sqlx/query-9e916d8594cc7fba78ed9661a00e146c2128431f24d78885cddf87325bae9cd5.json @@ -0,0 +1,29 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id AS \"id: uuid::Uuid\" FROM class_course\n WHERE class = $1 AND course = $2 FOR UPDATE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: uuid::Uuid", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "id" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "9e916d8594cc7fba78ed9661a00e146c2128431f24d78885cddf87325bae9cd5" +} diff --git a/.sqlx/query-fb46d17a76c6111308068c735184bbb68a2b726f7a1c98068d506d51aa52785e.json b/.sqlx/query-a16a5a66d59d7658e931ed1a9796a46317fd0820fa5eefc6fb4a3316948d9026.json similarity index 66% rename from .sqlx/query-fb46d17a76c6111308068c735184bbb68a2b726f7a1c98068d506d51aa52785e.json rename to .sqlx/query-a16a5a66d59d7658e931ed1a9796a46317fd0820fa5eefc6fb4a3316948d9026.json index 20d9d01..6cff0b2 100644 --- a/.sqlx/query-fb46d17a76c6111308068c735184bbb68a2b726f7a1c98068d506d51aa52785e.json +++ b/.sqlx/query-a16a5a66d59d7658e931ed1a9796a46317fd0820fa5eefc6fb4a3316948d9026.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT s.exam_kinds AS \"exam_kinds: Json>\",\n COALESCE((SELECT array_agg(t.status ORDER BY t.status)\n FROM settings_attendance_status t\n WHERE t.settings = s.id), '{}') AS \"attendance_statuses!: Vec\",\n s.grade_bands AS \"grade_bands: Json>\",\n s.max_file_bytes,\n s.chatbot_history_turns,\n s.max_chatbot_message_len,\n s.max_chatbot_threads,\n s.meal_slots AS \"meal_slots: Json>\",\n (SELECT array_agg(t.tag ORDER BY t.tag)\n FROM settings_dietary_tag t\n WHERE t.settings = s.id) AS dietary_tags,\n s.meal_cancel_cutoff_minutes\n FROM settings s WHERE s.id = 'school'", + "query": "SELECT s.exam_kinds AS \"exam_kinds: Json>\",\n COALESCE((SELECT array_agg(t.status ORDER BY t.status)\n FROM settings_attendance_status t\n WHERE t.settings = s.id), '{}') AS \"attendance_statuses!: Vec\",\n s.grade_bands AS \"grade_bands: Json>\",\n s.max_file_bytes,\n s.chatbot_history_turns,\n s.max_chatbot_message_len,\n s.max_chatbot_threads,\n s.meal_slots AS \"meal_slots: Json>\",\n (SELECT array_agg(t.tag ORDER BY t.tag)\n FROM settings_dietary_tag t\n WHERE t.settings = s.id) AS dietary_tags,\n s.meal_cancel_cutoff_minutes,\n s.branches AS \"branches: Json>\",\n s.excuse_kinds AS \"excuse_kinds: Json>\",\n s.max_excused_absent_days,\n s.max_unexcused_absent_days,\n s.timezone\n FROM settings s WHERE s.id = 'school'", "describe": { "columns": [ { @@ -102,6 +102,61 @@ "name": "meal_cancel_cutoff_minutes" } } + }, + { + "ordinal": 10, + "name": "branches: Json>", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "settings", + "name": "branches" + } + } + }, + { + "ordinal": 11, + "name": "excuse_kinds: Json>", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "settings", + "name": "excuse_kinds" + } + } + }, + { + "ordinal": 12, + "name": "max_excused_absent_days", + "type_info": "Int8", + "origin": { + "Table": { + "table": "settings", + "name": "max_excused_absent_days" + } + } + }, + { + "ordinal": 13, + "name": "max_unexcused_absent_days", + "type_info": "Int8", + "origin": { + "Table": { + "table": "settings", + "name": "max_unexcused_absent_days" + } + } + }, + { + "ordinal": 14, + "name": "timezone", + "type_info": "Text", + "origin": { + "Table": { + "table": "settings", + "name": "timezone" + } + } } ], "parameters": { @@ -117,8 +172,13 @@ true, true, null, + true, + true, + true, + true, + true, true ] }, - "hash": "fb46d17a76c6111308068c735184bbb68a2b726f7a1c98068d506d51aa52785e" + "hash": "a16a5a66d59d7658e931ed1a9796a46317fd0820fa5eefc6fb4a3316948d9026" } diff --git a/.sqlx/query-a4497c443cfa5d3f204d6e6828901739f328bad5f1c4ecb4e7a7973b7f0a5791.json b/.sqlx/query-a4497c443cfa5d3f204d6e6828901739f328bad5f1c4ecb4e7a7973b7f0a5791.json deleted file mode 100644 index 56585f8..0000000 --- a/.sqlx/query-a4497c443cfa5d3f204d6e6828901739f328bad5f1c4ecb4e7a7973b7f0a5791.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "DELETE FROM exam_result WHERE exam = ANY($1)", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "UuidArray" - ] - }, - "nullable": [] - }, - "hash": "a4497c443cfa5d3f204d6e6828901739f328bad5f1c4ecb4e7a7973b7f0a5791" -} diff --git a/.sqlx/query-a4a9fe4a625d4ad55e5daf16c7d99791cd0002767262bef6b2520661c9da64b4.json b/.sqlx/query-a4a9fe4a625d4ad55e5daf16c7d99791cd0002767262bef6b2520661c9da64b4.json new file mode 100644 index 0000000..912ed91 --- /dev/null +++ b/.sqlx/query-a4a9fe4a625d4ad55e5daf16c7d99791cd0002767262bef6b2520661c9da64b4.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH gone AS (\n DELETE FROM exam_question WHERE exam = ANY($1)\n RETURNING subject),\n subs AS (\n SELECT subject, count(*) AS n FROM gone GROUP BY subject)\n UPDATE subject s SET exam_question_count = GREATEST(s.exam_question_count - c.n, 0)\n FROM subs c WHERE s.id = c.subject", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "UuidArray" + ] + }, + "nullable": [] + }, + "hash": "a4a9fe4a625d4ad55e5daf16c7d99791cd0002767262bef6b2520661c9da64b4" +} diff --git a/.sqlx/query-19a3c810ccfbf79cfc58404e2146eb5907c4f09ceb46b5c79e7c26cb1eb5988d.json b/.sqlx/query-a7ca96bf0f9172c9c7ff2fc94a42dc7ee59d20419cf4cf3ebd90fcefeba21db0.json similarity index 60% rename from .sqlx/query-19a3c810ccfbf79cfc58404e2146eb5907c4f09ceb46b5c79e7c26cb1eb5988d.json rename to .sqlx/query-a7ca96bf0f9172c9c7ff2fc94a42dc7ee59d20419cf4cf3ebd90fcefeba21db0.json index 4f687e3..d21d4a8 100644 --- a/.sqlx/query-19a3c810ccfbf79cfc58404e2146eb5907c4f09ceb46b5c79e7c26cb1eb5988d.json +++ b/.sqlx/query-a7ca96bf0f9172c9c7ff2fc94a42dc7ee59d20419cf4cf3ebd90fcefeba21db0.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "DELETE FROM homework_submission WHERE homework IN (\n SELECT id FROM homework WHERE course = $1)", + "query": "DELETE FROM homework_submission WHERE homework IN (\n SELECT id FROM homework WHERE class_course = $1)", "describe": { "columns": [], "parameters": { @@ -10,5 +10,5 @@ }, "nullable": [] }, - "hash": "19a3c810ccfbf79cfc58404e2146eb5907c4f09ceb46b5c79e7c26cb1eb5988d" + "hash": "a7ca96bf0f9172c9c7ff2fc94a42dc7ee59d20419cf4cf3ebd90fcefeba21db0" } diff --git a/.sqlx/query-5275fe61292bfb7d4e5ee166495d2fb149a7557d1aef52d35b8c91e4b9543cf5.json b/.sqlx/query-a8a57bfd25073fc000010b532e400519cedea0c852d914156a90e774f3a23398.json similarity index 71% rename from .sqlx/query-5275fe61292bfb7d4e5ee166495d2fb149a7557d1aef52d35b8c91e4b9543cf5.json rename to .sqlx/query-a8a57bfd25073fc000010b532e400519cedea0c852d914156a90e774f3a23398.json index 2fbf91c..3e45197 100644 --- a/.sqlx/query-5275fe61292bfb7d4e5ee166495d2fb149a7557d1aef52d35b8c91e4b9543cf5.json +++ b/.sqlx/query-a8a57bfd25073fc000010b532e400519cedea0c852d914156a90e774f3a23398.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO exam (id, creator, course, title, description, kind, mode,\n starts_at, ends_at, duration_ms, max_attempts,\n allow_rejoin, allow_review, draft)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)\n RETURNING id AS \"id: ExamId\", creator AS \"creator: UserId\",\n course AS \"course: CourseId\", title AS \"title: ExamTitle\",\n description AS \"description: ExamDescription\",\n kind AS \"kind: ExamKind\", mode AS \"mode: ExamMode\",\n starts_at AS \"starts_at: Timestamp\",\n ends_at AS \"ends_at: Timestamp\",\n duration_ms AS \"duration_ms: ExamDuration\",\n max_attempts AS \"max_attempts: ExamAttemptLimit\",\n allow_rejoin, allow_review, draft", + "query": "SELECT DISTINCT ON (e.id)\n e.id AS \"id: ExamId\", e.creator AS \"creator: UserId\",\n e.class_course AS \"class_course: ClassCourseId\",\n e.term AS \"term: TermId\", e.title AS \"title: ExamTitle\",\n e.description AS \"description: ExamDescription\",\n e.kind AS \"kind: ExamKind\", e.mode AS \"mode: ExamMode\",\n e.starts_at AS \"starts_at: Timestamp\",\n e.ends_at AS \"ends_at: Timestamp\",\n e.duration_ms AS \"duration_ms: ExamDuration\",\n e.max_attempts AS \"max_attempts: ExamAttemptLimit\",\n e.allow_rejoin, e.allow_review, e.draft\n FROM exam e\n JOIN exam_audience a ON a.exam = e.id\n JOIN class_course cc ON cc.id = a.class_course\n WHERE cc.course = ANY($1)\n ORDER BY e.id DESC", "describe": { "columns": [ { @@ -27,17 +27,28 @@ }, { "ordinal": 2, - "name": "course: CourseId", + "name": "class_course: ClassCourseId", "type_info": "Uuid", "origin": { "Table": { "table": "exam", - "name": "course" + "name": "class_course" } } }, { "ordinal": 3, + "name": "term: TermId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "exam", + "name": "term" + } + } + }, + { + "ordinal": 4, "name": "title: ExamTitle", "type_info": "Text", "origin": { @@ -48,7 +59,7 @@ } }, { - "ordinal": 4, + "ordinal": 5, "name": "description: ExamDescription", "type_info": "Text", "origin": { @@ -59,7 +70,7 @@ } }, { - "ordinal": 5, + "ordinal": 6, "name": "kind: ExamKind", "type_info": "Text", "origin": { @@ -70,7 +81,7 @@ } }, { - "ordinal": 6, + "ordinal": 7, "name": "mode: ExamMode", "type_info": "Text", "origin": { @@ -81,7 +92,7 @@ } }, { - "ordinal": 7, + "ordinal": 8, "name": "starts_at: Timestamp", "type_info": "Int8", "origin": { @@ -92,7 +103,7 @@ } }, { - "ordinal": 8, + "ordinal": 9, "name": "ends_at: Timestamp", "type_info": "Int8", "origin": { @@ -103,7 +114,7 @@ } }, { - "ordinal": 9, + "ordinal": 10, "name": "duration_ms: ExamDuration", "type_info": "Int8", "origin": { @@ -114,7 +125,7 @@ } }, { - "ordinal": 10, + "ordinal": 11, "name": "max_attempts: ExamAttemptLimit", "type_info": "Int8", "origin": { @@ -125,7 +136,7 @@ } }, { - "ordinal": 11, + "ordinal": 12, "name": "allow_rejoin", "type_info": "Bool", "origin": { @@ -136,7 +147,7 @@ } }, { - "ordinal": 12, + "ordinal": 13, "name": "allow_review", "type_info": "Bool", "origin": { @@ -147,7 +158,7 @@ } }, { - "ordinal": 13, + "ordinal": 14, "name": "draft", "type_info": "Bool", "origin": { @@ -160,20 +171,7 @@ ], "parameters": { "Left": [ - "Uuid", - "Uuid", - "Uuid", - "Text", - "Text", - "Text", - "Text", - "Int8", - "Int8", - "Int8", - "Int8", - "Bool", - "Bool", - "Bool" + "UuidArray" ] }, "nullable": [ @@ -183,6 +181,7 @@ false, false, false, + false, true, true, true, @@ -193,5 +192,5 @@ false ] }, - "hash": "5275fe61292bfb7d4e5ee166495d2fb149a7557d1aef52d35b8c91e4b9543cf5" + "hash": "a8a57bfd25073fc000010b532e400519cedea0c852d914156a90e774f3a23398" } diff --git a/.sqlx/query-a915f3e40d94c95904da3523a5e961930cf26070e0e85da66011c4adb85de2f3.json b/.sqlx/query-a915f3e40d94c95904da3523a5e961930cf26070e0e85da66011c4adb85de2f3.json new file mode 100644 index 0000000..c11596d --- /dev/null +++ b/.sqlx/query-a915f3e40d94c95904da3523a5e961930cf26070e0e85da66011c4adb85de2f3.json @@ -0,0 +1,119 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT cc.id AS \"id: ClassCourseId\", cc.class AS \"class: ClassGroupId\",\n cc.course AS \"course: CourseId\", cc.attached_by AS \"attached_by: UserId\",\n b.grade AS \"source?: ClassBlueprintId\",\n cc.ders_saati::bigint AS \"ders_saati!: DersSaati\",\n cc.counts_toward_karne, cc.enrollment_count,\n cc.attached_at AS \"attached_at: Timestamp\"\n FROM class_course cc\n LEFT JOIN class_blueprint b ON b.id = cc.source\n WHERE cc.id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: ClassCourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "class: ClassGroupId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "class" + } + } + }, + { + "ordinal": 2, + "name": "course: CourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "course" + } + } + }, + { + "ordinal": 3, + "name": "attached_by: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "attached_by" + } + } + }, + { + "ordinal": 4, + "name": "source?: ClassBlueprintId", + "type_info": "Text", + "origin": { + "Table": { + "table": "class_blueprint", + "name": "grade" + } + } + }, + { + "ordinal": 5, + "name": "ders_saati!: DersSaati", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 6, + "name": "counts_toward_karne", + "type_info": "Bool", + "origin": { + "Table": { + "table": "class_course", + "name": "counts_toward_karne" + } + } + }, + { + "ordinal": 7, + "name": "enrollment_count", + "type_info": "Int8", + "origin": { + "Table": { + "table": "class_course", + "name": "enrollment_count" + } + } + }, + { + "ordinal": 8, + "name": "attached_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "class_course", + "name": "attached_at" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + false, + false, + false, + true, + null, + false, + false, + false + ] + }, + "hash": "a915f3e40d94c95904da3523a5e961930cf26070e0e85da66011c4adb85de2f3" +} diff --git a/.sqlx/query-afbe9f23e7231c752aaf28226d82dade41124a5729a341956dd8360a408b7f2e.json b/.sqlx/query-afbe9f23e7231c752aaf28226d82dade41124a5729a341956dd8360a408b7f2e.json new file mode 100644 index 0000000..07a5ec3 --- /dev/null +++ b/.sqlx/query-afbe9f23e7231c752aaf28226d82dade41124a5729a341956dd8360a408b7f2e.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT DISTINCT app_user AS \"user!: UserId\" FROM (\n SELECT e.app_user FROM enrollment e\n JOIN class_course cc ON cc.id = e.class_course\n WHERE cc.course = $1\n UNION ALL\n SELECT m.app_user FROM course_membership m WHERE m.course = $1\n ) people ORDER BY app_user", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "user!: UserId", + "type_info": "Uuid", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + null + ] + }, + "hash": "afbe9f23e7231c752aaf28226d82dade41124a5729a341956dd8360a408b7f2e" +} diff --git a/.sqlx/query-b070f136735d0bf35608fe7a27dc7889c0a74943acb9706478311d799142334f.json b/.sqlx/query-b070f136735d0bf35608fe7a27dc7889c0a74943acb9706478311d799142334f.json new file mode 100644 index 0000000..60ae29d --- /dev/null +++ b/.sqlx/query-b070f136735d0bf35608fe7a27dc7889c0a74943acb9706478311d799142334f.json @@ -0,0 +1,88 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE year = $1 ORDER BY id", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: ClassGroupId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_group", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "creator: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_group", + "name": "creator" + } + } + }, + { + "ordinal": 2, + "name": "name: ClassName", + "type_info": "Text", + "origin": { + "Table": { + "table": "class_group", + "name": "name" + } + } + }, + { + "ordinal": 3, + "name": "grade: ClassGrade", + "type_info": "Text", + "origin": { + "Table": { + "table": "class_group", + "name": "grade" + } + } + }, + { + "ordinal": 4, + "name": "year: AcademicYearId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_group", + "name": "year" + } + } + }, + { + "ordinal": 5, + "name": "teacher: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_group", + "name": "teacher" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + false, + false, + true, + true, + true + ] + }, + "hash": "b070f136735d0bf35608fe7a27dc7889c0a74943acb9706478311d799142334f" +} diff --git a/.sqlx/query-09a4d21a85fc3b3fe59438874316ee35b4f80e3be898fa0f0f4dec4dde44bd4e.json b/.sqlx/query-b1485b93a061e8735c6ec5eb2cbeb83e1f73ba2220d7e85e79904c26062dbffd.json similarity index 65% rename from .sqlx/query-09a4d21a85fc3b3fe59438874316ee35b4f80e3be898fa0f0f4dec4dde44bd4e.json rename to .sqlx/query-b1485b93a061e8735c6ec5eb2cbeb83e1f73ba2220d7e85e79904c26062dbffd.json index fc6d764..be8ddf8 100644 --- a/.sqlx/query-09a4d21a85fc3b3fe59438874316ee35b4f80e3be898fa0f0f4dec4dde44bd4e.json +++ b/.sqlx/query-b1485b93a061e8735c6ec5eb2cbeb83e1f73ba2220d7e85e79904c26062dbffd.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT 1 AS \"one\" FROM class_member WHERE class = $1 AND app_user = $2", + "query": "SELECT 1 AS \"one\" FROM enrollment WHERE class_course = $1 AND app_user = $2", "describe": { "columns": [ { @@ -20,5 +20,5 @@ null ] }, - "hash": "09a4d21a85fc3b3fe59438874316ee35b4f80e3be898fa0f0f4dec4dde44bd4e" + "hash": "b1485b93a061e8735c6ec5eb2cbeb83e1f73ba2220d7e85e79904c26062dbffd" } diff --git a/.sqlx/query-b16588dd57a34e3647a1d5b87b2a477635f271ca98359faadfd9bb6b17c18bc9.json b/.sqlx/query-b16588dd57a34e3647a1d5b87b2a477635f271ca98359faadfd9bb6b17c18bc9.json new file mode 100644 index 0000000..5148888 --- /dev/null +++ b/.sqlx/query-b16588dd57a34e3647a1d5b87b2a477635f271ca98359faadfd9bb6b17c18bc9.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT class AS \"class: ClassGroupId\" FROM class_course WHERE id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "class: ClassGroupId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_course", + "name": "class" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "b16588dd57a34e3647a1d5b87b2a477635f271ca98359faadfd9bb6b17c18bc9" +} diff --git a/.sqlx/query-49ede4ebf9c7ab70d842755888e65aaf496d03b01d135459ccd9b99a3f51d49c.json b/.sqlx/query-b1c1bb3f134a510cb5ccba24ce030ca195f78e51790efd07dc5b026938b41a63.json similarity index 54% rename from .sqlx/query-49ede4ebf9c7ab70d842755888e65aaf496d03b01d135459ccd9b99a3f51d49c.json rename to .sqlx/query-b1c1bb3f134a510cb5ccba24ce030ca195f78e51790efd07dc5b026938b41a63.json index 9586bc1..f9ac8ac 100644 --- a/.sqlx/query-49ede4ebf9c7ab70d842755888e65aaf496d03b01d135459ccd9b99a3f51d49c.json +++ b/.sqlx/query-b1c1bb3f134a510cb5ccba24ce030ca195f78e51790efd07dc5b026938b41a63.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "DELETE FROM exam WHERE course = $1", + "query": "DELETE FROM class_group WHERE id = $1", "describe": { "columns": [], "parameters": { @@ -10,5 +10,5 @@ }, "nullable": [] }, - "hash": "49ede4ebf9c7ab70d842755888e65aaf496d03b01d135459ccd9b99a3f51d49c" + "hash": "b1c1bb3f134a510cb5ccba24ce030ca195f78e51790efd07dc5b026938b41a63" } diff --git a/.sqlx/query-b2a05e29db69841f2a0d727e5b0f820722a33a939b88e40956092dbc20af9947.json b/.sqlx/query-b2a05e29db69841f2a0d727e5b0f820722a33a939b88e40956092dbc20af9947.json deleted file mode 100644 index f3e179b..0000000 --- a/.sqlx/query-b2a05e29db69841f2a0d727e5b0f820722a33a939b88e40956092dbc20af9947.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "WITH gone AS (\n DELETE FROM enrollment WHERE app_user = $1 RETURNING course\n )\n UPDATE course\n SET enrollment_count = GREATEST(enrollment_count - 1, 0)\n WHERE id IN (SELECT gone.course FROM gone)", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Uuid" - ] - }, - "nullable": [] - }, - "hash": "b2a05e29db69841f2a0d727e5b0f820722a33a939b88e40956092dbc20af9947" -} diff --git a/.sqlx/query-59e72e6dab4c94b31994810b4bf1d195587319a4ab757166a046b394e86938a5.json b/.sqlx/query-b2c320ebdee88e24b250ece9fbe186401f010aa4e3119e9a7cc7491b8af8a80c.json similarity index 72% rename from .sqlx/query-59e72e6dab4c94b31994810b4bf1d195587319a4ab757166a046b394e86938a5.json rename to .sqlx/query-b2c320ebdee88e24b250ece9fbe186401f010aa4e3119e9a7cc7491b8af8a80c.json index 6ebb70d..d9876bc 100644 --- a/.sqlx/query-59e72e6dab4c94b31994810b4bf1d195587319a4ab757166a046b394e86938a5.json +++ b/.sqlx/query-b2c320ebdee88e24b250ece9fbe186401f010aa4e3119e9a7cc7491b8af8a80c.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "WITH seat AS (\n UPDATE subject SET homework_count = homework_count + 1\n WHERE id = $1\n RETURNING 1\n )\n INSERT INTO homework (id, course, subject, title, description, due_at, created_by, created_at)\n SELECT $2, $3, $1, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n NULL::uuid[] AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"", + "query": "WITH seat AS (\n UPDATE subject SET homework_count = homework_count + 1\n WHERE id = $1\n RETURNING 1\n )\n INSERT INTO homework (id, class_course, subject, title, description, due_at, created_by, created_at)\n SELECT $2, $3, $1, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING id AS \"id: HomeworkId\",\n class_course AS \"class_course: ClassCourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n NULL::uuid[] AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"", "describe": { "columns": [ { @@ -16,12 +16,12 @@ }, { "ordinal": 1, - "name": "course: CourseId", + "name": "class_course: ClassCourseId", "type_info": "Uuid", "origin": { "Table": { "table": "homework", - "name": "course" + "name": "class_course" } } }, @@ -122,5 +122,5 @@ false ] }, - "hash": "59e72e6dab4c94b31994810b4bf1d195587319a4ab757166a046b394e86938a5" + "hash": "b2c320ebdee88e24b250ece9fbe186401f010aa4e3119e9a7cc7491b8af8a80c" } diff --git a/.sqlx/query-b2c9927ef99caca43fd99d7d733a6aa2fa38683560363486a80505005b5ef03d.json b/.sqlx/query-b2c9927ef99caca43fd99d7d733a6aa2fa38683560363486a80505005b5ef03d.json new file mode 100644 index 0000000..f3ef10e --- /dev/null +++ b/.sqlx/query-b2c9927ef99caca43fd99d7d733a6aa2fa38683560363486a80505005b5ef03d.json @@ -0,0 +1,77 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH gone AS (\n DELETE FROM enrollment\n WHERE class_course = $1 AND app_user = $2\n RETURNING class_course, app_user, enrolled_by, source, created_at),\n seated AS (\n UPDATE class_course\n SET enrollment_count = GREATEST(\n enrollment_count - (SELECT count(*) FROM gone), 0)\n WHERE id = $1\n RETURNING 1)\n SELECT class_course AS \"class_course: ClassCourseId\",\n app_user AS \"user: UserId\", enrolled_by AS \"enrolled_by: UserId\",\n source AS \"source: ClassGroupId\", created_at AS \"created_at: Timestamp\"\n FROM gone", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "class_course: ClassCourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "enrollment", + "name": "class_course" + } + } + }, + { + "ordinal": 1, + "name": "user: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "enrollment", + "name": "app_user" + } + } + }, + { + "ordinal": 2, + "name": "enrolled_by: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "enrollment", + "name": "enrolled_by" + } + } + }, + { + "ordinal": 3, + "name": "source: ClassGroupId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "enrollment", + "name": "source" + } + } + }, + { + "ordinal": 4, + "name": "created_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "enrollment", + "name": "created_at" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Uuid" + ] + }, + "nullable": [ + false, + false, + false, + true, + false + ] + }, + "hash": "b2c9927ef99caca43fd99d7d733a6aa2fa38683560363486a80505005b5ef03d" +} diff --git a/.sqlx/query-b3547497886ccad1d6ed673b2abf52da7e219b9548114f4f12a8e3ae8c1a8681.json b/.sqlx/query-b3547497886ccad1d6ed673b2abf52da7e219b9548114f4f12a8e3ae8c1a8681.json new file mode 100644 index 0000000..6ce08c0 --- /dev/null +++ b/.sqlx/query-b3547497886ccad1d6ed673b2abf52da7e219b9548114f4f12a8e3ae8c1a8681.json @@ -0,0 +1,88 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE teacher = $1 ORDER BY id DESC", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: ClassGroupId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_group", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "creator: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_group", + "name": "creator" + } + } + }, + { + "ordinal": 2, + "name": "name: ClassName", + "type_info": "Text", + "origin": { + "Table": { + "table": "class_group", + "name": "name" + } + } + }, + { + "ordinal": 3, + "name": "grade: ClassGrade", + "type_info": "Text", + "origin": { + "Table": { + "table": "class_group", + "name": "grade" + } + } + }, + { + "ordinal": 4, + "name": "year: AcademicYearId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_group", + "name": "year" + } + } + }, + { + "ordinal": 5, + "name": "teacher: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_group", + "name": "teacher" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + false, + false, + true, + true, + true + ] + }, + "hash": "b3547497886ccad1d6ed673b2abf52da7e219b9548114f4f12a8e3ae8c1a8681" +} diff --git a/.sqlx/query-a693d7fe95bd9da9fcd8ef12db5ba1aa133b09ccdcc25c07f6dd51e319b9f3e2.json b/.sqlx/query-b44d8f55249502fac3cc2650e29cb4799e4db87d6574b2a47ff8fd43ace4ed59.json similarity index 68% rename from .sqlx/query-a693d7fe95bd9da9fcd8ef12db5ba1aa133b09ccdcc25c07f6dd51e319b9f3e2.json rename to .sqlx/query-b44d8f55249502fac3cc2650e29cb4799e4db87d6574b2a47ff8fd43ace4ed59.json index f3800d5..d829ca5 100644 --- a/.sqlx/query-a693d7fe95bd9da9fcd8ef12db5ba1aa133b09ccdcc25c07f6dd51e319b9f3e2.json +++ b/.sqlx/query-b44d8f55249502fac3cc2650e29cb4799e4db87d6574b2a47ff8fd43ace4ed59.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "WITH seat AS (\n UPDATE term SET class_count = class_count + 1\n WHERE id = $1\n RETURNING 1)\n INSERT INTO class_group (id, creator, name, grade, term, teacher)\n SELECT $2, $3, $4, $5, $1, $6 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n term AS \"term: TermId\", teacher AS \"teacher: UserId\"", + "query": "WITH seat AS (\n UPDATE academic_year SET class_count = class_count + 1\n WHERE id = $1\n RETURNING 1)\n INSERT INTO class_group (id, creator, name, grade, year, teacher)\n SELECT $2, $3, $4, $5, $1, $6 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"", "describe": { "columns": [ { @@ -49,12 +49,12 @@ }, { "ordinal": 4, - "name": "term: TermId", + "name": "year: AcademicYearId", "type_info": "Uuid", "origin": { "Table": { "table": "class_group", - "name": "term" + "name": "year" } } }, @@ -89,5 +89,5 @@ true ] }, - "hash": "a693d7fe95bd9da9fcd8ef12db5ba1aa133b09ccdcc25c07f6dd51e319b9f3e2" + "hash": "b44d8f55249502fac3cc2650e29cb4799e4db87d6574b2a47ff8fd43ace4ed59" } diff --git a/.sqlx/query-33937eda61e33ee52f82bf7e6338428bdccf4e2d95f2499d9feb46ff6238f51d.json b/.sqlx/query-b4deb88802c1d87668aab3480b64e7f3228f3d2f6ac284761d7e5ca8bd0df499.json similarity index 72% rename from .sqlx/query-33937eda61e33ee52f82bf7e6338428bdccf4e2d95f2499d9feb46ff6238f51d.json rename to .sqlx/query-b4deb88802c1d87668aab3480b64e7f3228f3d2f6ac284761d7e5ca8bd0df499.json index c057865..a4c637d 100644 --- a/.sqlx/query-33937eda61e33ee52f82bf7e6338428bdccf4e2d95f2499d9feb46ff6238f51d.json +++ b/.sqlx/query-b4deb88802c1d87668aab3480b64e7f3228f3d2f6ac284761d7e5ca8bd0df499.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "DELETE FROM homework WHERE id = $1\n RETURNING id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"", + "query": "DELETE FROM homework WHERE id = $1\n RETURNING id AS \"id: HomeworkId\",\n class_course AS \"class_course: ClassCourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"", "describe": { "columns": [ { @@ -16,12 +16,12 @@ }, { "ordinal": 1, - "name": "course: CourseId", + "name": "class_course: ClassCourseId", "type_info": "Uuid", "origin": { "Table": { "table": "homework", - "name": "course" + "name": "class_course" } } }, @@ -115,5 +115,5 @@ false ] }, - "hash": "33937eda61e33ee52f82bf7e6338428bdccf4e2d95f2499d9feb46ff6238f51d" + "hash": "b4deb88802c1d87668aab3480b64e7f3228f3d2f6ac284761d7e5ca8bd0df499" } diff --git a/.sqlx/query-9d97ae40f2a231fef7a322d0f55dc794d109326032412ae2e6b6582cc3d2e893.json b/.sqlx/query-b564bc324da8ba9a7ee453cc85a6c187f98da879650f240ddec4ad11854f16d3.json similarity index 55% rename from .sqlx/query-9d97ae40f2a231fef7a322d0f55dc794d109326032412ae2e6b6582cc3d2e893.json rename to .sqlx/query-b564bc324da8ba9a7ee453cc85a6c187f98da879650f240ddec4ad11854f16d3.json index 7c928f7..6cea21b 100644 --- a/.sqlx/query-9d97ae40f2a231fef7a322d0f55dc794d109326032412ae2e6b6582cc3d2e893.json +++ b/.sqlx/query-b564bc324da8ba9a7ee453cc85a6c187f98da879650f240ddec4ad11854f16d3.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "WITH seat AS (\n UPDATE class_group SET class_member_count = class_member_count + 1\n WHERE id = $1 AND class_member_count < $2\n RETURNING 1)\n INSERT INTO class_member (class, app_user, added_by, added_at)\n SELECT $1, $3, $4, $5 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING 1 AS \"one\"", + "query": "WITH seat AS (\n UPDATE class_group SET class_member_count = class_member_count + 1\n WHERE id = $1 AND class_member_count < $2\n RETURNING 1)\n INSERT INTO class_member (id, class, app_user, added_by, joined_at, left_at,\n source_class_group)\n SELECT $3, $1, $4, $5, $6, NULL, $7 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING 1 AS \"one\"", "describe": { "columns": [ { @@ -16,12 +16,14 @@ "Int8", "Uuid", "Uuid", - "Int8" + "Uuid", + "Int8", + "Uuid" ] }, "nullable": [ null ] }, - "hash": "9d97ae40f2a231fef7a322d0f55dc794d109326032412ae2e6b6582cc3d2e893" + "hash": "b564bc324da8ba9a7ee453cc85a6c187f98da879650f240ddec4ad11854f16d3" } diff --git a/.sqlx/query-4c38288787f424c39261947ba1f1097285ea04432869fef7fc411496a9087cd4.json b/.sqlx/query-b859cdc3e09e10907ba2cc39ab90a96086a5bdd374250cc6677057dbc925f81d.json similarity index 77% rename from .sqlx/query-4c38288787f424c39261947ba1f1097285ea04432869fef7fc411496a9087cd4.json rename to .sqlx/query-b859cdc3e09e10907ba2cc39ab90a96086a5bdd374250cc6677057dbc925f81d.json index 4f3f21f..acc5ef1 100644 --- a/.sqlx/query-4c38288787f424c39261947ba1f1097285ea04432869fef7fc411496a9087cd4.json +++ b/.sqlx/query-b859cdc3e09e10907ba2cc39ab90a96086a5bdd374250cc6677057dbc925f81d.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: ExamId\", creator AS \"creator: UserId\", course AS \"course: CourseId\",\n title AS \"title: ExamTitle\", description AS \"description: ExamDescription\",\n kind AS \"kind: ExamKind\", mode AS \"mode: ExamMode\",\n starts_at AS \"starts_at: Timestamp\",\n ends_at AS \"ends_at: Timestamp\",\n duration_ms AS \"duration_ms: ExamDuration\",\n max_attempts AS \"max_attempts: ExamAttemptLimit\",\n allow_rejoin, allow_review, draft\n FROM exam ORDER BY id DESC", + "query": "SELECT id AS \"id: ExamId\", creator AS \"creator: UserId\",\n class_course AS \"class_course: ClassCourseId\", term AS \"term: TermId\",\n title AS \"title: ExamTitle\", description AS \"description: ExamDescription\",\n kind AS \"kind: ExamKind\", mode AS \"mode: ExamMode\",\n starts_at AS \"starts_at: Timestamp\",\n ends_at AS \"ends_at: Timestamp\",\n duration_ms AS \"duration_ms: ExamDuration\",\n max_attempts AS \"max_attempts: ExamAttemptLimit\",\n allow_rejoin, allow_review, draft\n FROM exam ORDER BY id DESC", "describe": { "columns": [ { @@ -27,17 +27,28 @@ }, { "ordinal": 2, - "name": "course: CourseId", + "name": "class_course: ClassCourseId", "type_info": "Uuid", "origin": { "Table": { "table": "exam", - "name": "course" + "name": "class_course" } } }, { "ordinal": 3, + "name": "term: TermId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "exam", + "name": "term" + } + } + }, + { + "ordinal": 4, "name": "title: ExamTitle", "type_info": "Text", "origin": { @@ -48,7 +59,7 @@ } }, { - "ordinal": 4, + "ordinal": 5, "name": "description: ExamDescription", "type_info": "Text", "origin": { @@ -59,7 +70,7 @@ } }, { - "ordinal": 5, + "ordinal": 6, "name": "kind: ExamKind", "type_info": "Text", "origin": { @@ -70,7 +81,7 @@ } }, { - "ordinal": 6, + "ordinal": 7, "name": "mode: ExamMode", "type_info": "Text", "origin": { @@ -81,7 +92,7 @@ } }, { - "ordinal": 7, + "ordinal": 8, "name": "starts_at: Timestamp", "type_info": "Int8", "origin": { @@ -92,7 +103,7 @@ } }, { - "ordinal": 8, + "ordinal": 9, "name": "ends_at: Timestamp", "type_info": "Int8", "origin": { @@ -103,7 +114,7 @@ } }, { - "ordinal": 9, + "ordinal": 10, "name": "duration_ms: ExamDuration", "type_info": "Int8", "origin": { @@ -114,7 +125,7 @@ } }, { - "ordinal": 10, + "ordinal": 11, "name": "max_attempts: ExamAttemptLimit", "type_info": "Int8", "origin": { @@ -125,7 +136,7 @@ } }, { - "ordinal": 11, + "ordinal": 12, "name": "allow_rejoin", "type_info": "Bool", "origin": { @@ -136,7 +147,7 @@ } }, { - "ordinal": 12, + "ordinal": 13, "name": "allow_review", "type_info": "Bool", "origin": { @@ -147,7 +158,7 @@ } }, { - "ordinal": 13, + "ordinal": 14, "name": "draft", "type_info": "Bool", "origin": { @@ -168,6 +179,7 @@ false, false, false, + false, true, true, true, @@ -178,5 +190,5 @@ false ] }, - "hash": "4c38288787f424c39261947ba1f1097285ea04432869fef7fc411496a9087cd4" + "hash": "b859cdc3e09e10907ba2cc39ab90a96086a5bdd374250cc6677057dbc925f81d" } diff --git a/.sqlx/query-e2000c1bf26bc866f2bd0de9c15895b38a05e22b13b6db494a69d92eebeece76.json b/.sqlx/query-b9237fa66d33731d7480f924978202890d7a2b39aefb09b00be6db9767af0264.json similarity index 76% rename from .sqlx/query-e2000c1bf26bc866f2bd0de9c15895b38a05e22b13b6db494a69d92eebeece76.json rename to .sqlx/query-b9237fa66d33731d7480f924978202890d7a2b39aefb09b00be6db9767af0264.json index ee84aeb..c2be9f5 100644 --- a/.sqlx/query-e2000c1bf26bc866f2bd0de9c15895b38a05e22b13b6db494a69d92eebeece76.json +++ b/.sqlx/query-b9237fa66d33731d7480f924978202890d7a2b39aefb09b00be6db9767af0264.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: CourseSessionId\", course AS \"course: CourseId\",\n teacher AS \"teacher: UserId\", topic AS \"topic: SessionTopic\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\"\n FROM course_session WHERE id = $1", + "query": "SELECT id AS \"id: CourseSessionId\",\n class_course AS \"class_course: ClassCourseId\",\n teacher AS \"teacher: UserId\", topic AS \"topic: SessionTopic\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\"\n FROM course_session WHERE id = $1", "describe": { "columns": [ { @@ -16,12 +16,12 @@ }, { "ordinal": 1, - "name": "course: CourseId", + "name": "class_course: ClassCourseId", "type_info": "Uuid", "origin": { "Table": { "table": "course_session", - "name": "course" + "name": "class_course" } } }, @@ -84,5 +84,5 @@ true ] }, - "hash": "e2000c1bf26bc866f2bd0de9c15895b38a05e22b13b6db494a69d92eebeece76" + "hash": "b9237fa66d33731d7480f924978202890d7a2b39aefb09b00be6db9767af0264" } diff --git a/.sqlx/query-b9bd402798dd82f0b13e78b03ac9ba1278fcd5fe3d956d9996e1c615b346b1b8.json b/.sqlx/query-b9bd402798dd82f0b13e78b03ac9ba1278fcd5fe3d956d9996e1c615b346b1b8.json new file mode 100644 index 0000000..c71b182 --- /dev/null +++ b/.sqlx/query-b9bd402798dd82f0b13e78b03ac9ba1278fcd5fe3d956d9996e1c615b346b1b8.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH gone AS (\n DELETE FROM exam_result WHERE exam = ANY($1)\n RETURNING exam),\n kinds AS (\n SELECT e.kind AS kind, count(*) AS n\n FROM gone g JOIN exam e ON e.id = g.exam\n GROUP BY e.kind)\n UPDATE kind_ref k SET count = GREATEST(k.count - c.n, 0)\n FROM kinds c WHERE k.name = c.kind", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "UuidArray" + ] + }, + "nullable": [] + }, + "hash": "b9bd402798dd82f0b13e78b03ac9ba1278fcd5fe3d956d9996e1c615b346b1b8" +} diff --git a/.sqlx/query-7035991f21ff426c7c9e7c9912c376a564002eb6013154a75c756df495ccf697.json b/.sqlx/query-b9cd5a0a2b4274ec3b904a125167e2f27c966f3c27a0a26f9c2365d271c67cf5.json similarity index 84% rename from .sqlx/query-7035991f21ff426c7c9e7c9912c376a564002eb6013154a75c756df495ccf697.json rename to .sqlx/query-b9cd5a0a2b4274ec3b904a125167e2f27c966f3c27a0a26f9c2365d271c67cf5.json index 2dcd1e7..429505c 100644 --- a/.sqlx/query-7035991f21ff426c7c9e7c9912c376a564002eb6013154a75c756df495ccf697.json +++ b/.sqlx/query-b9cd5a0a2b4274ec3b904a125167e2f27c966f3c27a0a26f9c2365d271c67cf5.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n term AS \"term: TermId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE id = $1", + "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE id = $1", "describe": { "columns": [ { @@ -49,12 +49,12 @@ }, { "ordinal": 4, - "name": "term: TermId", + "name": "year: AcademicYearId", "type_info": "Uuid", "origin": { "Table": { "table": "class_group", - "name": "term" + "name": "year" } } }, @@ -84,5 +84,5 @@ true ] }, - "hash": "7035991f21ff426c7c9e7c9912c376a564002eb6013154a75c756df495ccf697" + "hash": "b9cd5a0a2b4274ec3b904a125167e2f27c966f3c27a0a26f9c2365d271c67cf5" } diff --git a/.sqlx/query-bbdea4fc1c294d8aff18288094153f6dc55cec1672a5761cd31cb1ea48d94423.json b/.sqlx/query-bbdea4fc1c294d8aff18288094153f6dc55cec1672a5761cd31cb1ea48d94423.json deleted file mode 100644 index b7d516f..0000000 --- a/.sqlx/query-bbdea4fc1c294d8aff18288094153f6dc55cec1672a5761cd31cb1ea48d94423.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE kind_ref k\n SET count = GREATEST(k.count - s.n, 0)\n FROM (SELECT e.kind, count(*) AS n FROM exam_result r\n JOIN exam e ON r.exam = e.id\n WHERE r.exam = ANY($1) GROUP BY e.kind) s\n WHERE k.name = s.kind", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "UuidArray" - ] - }, - "nullable": [] - }, - "hash": "bbdea4fc1c294d8aff18288094153f6dc55cec1672a5761cd31cb1ea48d94423" -} diff --git a/.sqlx/query-bcdb9a4b449617cf405b3abb592e68ad4a6eb5e1715a773eeb1ec939338c6e2e.json b/.sqlx/query-bcdb9a4b449617cf405b3abb592e68ad4a6eb5e1715a773eeb1ec939338c6e2e.json new file mode 100644 index 0000000..2d8f44d --- /dev/null +++ b/.sqlx/query-bcdb9a4b449617cf405b3abb592e68ad4a6eb5e1715a773eeb1ec939338c6e2e.json @@ -0,0 +1,77 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT r.exam AS \"exam: ExamId\", r.app_user AS \"user: UserId\", r.seq,\n r.mark AS \"mark: Mark\", r.graded_by AS \"graded_by: UserId\"\n FROM exam_result r JOIN exam e ON e.id = r.exam\n WHERE r.app_user = $1 AND e.class_course = $2\n ORDER BY r.exam DESC, r.seq DESC", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "exam: ExamId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "exam_result", + "name": "exam" + } + } + }, + { + "ordinal": 1, + "name": "user: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "exam_result", + "name": "app_user" + } + } + }, + { + "ordinal": 2, + "name": "seq", + "type_info": "Int8", + "origin": { + "Table": { + "table": "exam_result", + "name": "seq" + } + } + }, + { + "ordinal": 3, + "name": "mark: Mark", + "type_info": "Int8", + "origin": { + "Table": { + "table": "exam_result", + "name": "mark" + } + } + }, + { + "ordinal": 4, + "name": "graded_by: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "exam_result", + "name": "graded_by" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Uuid" + ] + }, + "nullable": [ + false, + false, + false, + false, + false + ] + }, + "hash": "bcdb9a4b449617cf405b3abb592e68ad4a6eb5e1715a773eeb1ec939338c6e2e" +} diff --git a/.sqlx/query-aacd58dae08eb43636a52ea734310e4d9bbd691bc75a61c6db1e62fc8cad77c3.json b/.sqlx/query-c43cea61dd61df88dea3e87cc981a3d9750608bafa4306222afa42cff3d45230.json similarity index 71% rename from .sqlx/query-aacd58dae08eb43636a52ea734310e4d9bbd691bc75a61c6db1e62fc8cad77c3.json rename to .sqlx/query-c43cea61dd61df88dea3e87cc981a3d9750608bafa4306222afa42cff3d45230.json index a1dccbd..18034e0 100644 --- a/.sqlx/query-aacd58dae08eb43636a52ea734310e4d9bbd691bc75a61c6db1e62fc8cad77c3.json +++ b/.sqlx/query-c43cea61dd61df88dea3e87cc981a3d9750608bafa4306222afa42cff3d45230.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE term SET archived_at = NULL\n WHERE id = $1 AND archived_at IS NOT NULL\n RETURNING id AS \"id: TermId\", name AS \"name: TermName\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\",\n archived_at AS \"archived_at: Timestamp\"", + "query": "UPDATE term SET archived_at = NULL\n WHERE id = $1 AND archived_at IS NOT NULL\n RETURNING id AS \"id: TermId\", year AS \"year: AcademicYearId\",\n name AS \"name: TermName\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\",\n archived_at AS \"archived_at: Timestamp\"", "describe": { "columns": [ { @@ -16,6 +16,17 @@ }, { "ordinal": 1, + "name": "year: AcademicYearId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "term", + "name": "year" + } + } + }, + { + "ordinal": 2, "name": "name: TermName", "type_info": "Text", "origin": { @@ -26,7 +37,7 @@ } }, { - "ordinal": 2, + "ordinal": 3, "name": "starts_at: Timestamp", "type_info": "Int8", "origin": { @@ -37,7 +48,7 @@ } }, { - "ordinal": 3, + "ordinal": 4, "name": "ends_at: Timestamp", "type_info": "Int8", "origin": { @@ -48,7 +59,7 @@ } }, { - "ordinal": 4, + "ordinal": 5, "name": "archived_at: Timestamp", "type_info": "Int8", "origin": { @@ -69,8 +80,9 @@ false, false, false, + false, true ] }, - "hash": "aacd58dae08eb43636a52ea734310e4d9bbd691bc75a61c6db1e62fc8cad77c3" + "hash": "c43cea61dd61df88dea3e87cc981a3d9750608bafa4306222afa42cff3d45230" } diff --git a/.sqlx/query-c7061a9a18a1da2cc178b22322cd1efd71d69681d050511d8c05e913ae6c62ae.json b/.sqlx/query-c7061a9a18a1da2cc178b22322cd1efd71d69681d050511d8c05e913ae6c62ae.json deleted file mode 100644 index 36d27fd..0000000 --- a/.sqlx/query-c7061a9a18a1da2cc178b22322cd1efd71d69681d050511d8c05e913ae6c62ae.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "DELETE FROM course_session WHERE course = $1", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Uuid" - ] - }, - "nullable": [] - }, - "hash": "c7061a9a18a1da2cc178b22322cd1efd71d69681d050511d8c05e913ae6c62ae" -} diff --git a/.sqlx/query-f77abe223a46882261b27bf5ac8f2c814c76e00836c1fd8a77483074fb2cd5eb.json b/.sqlx/query-c9e8539ffc001f4fea89e28319703294b33a9312693ff2f9e795227ee1bb50db.json similarity index 53% rename from .sqlx/query-f77abe223a46882261b27bf5ac8f2c814c76e00836c1fd8a77483074fb2cd5eb.json rename to .sqlx/query-c9e8539ffc001f4fea89e28319703294b33a9312693ff2f9e795227ee1bb50db.json index b4f218f..a9498ac 100644 --- a/.sqlx/query-f77abe223a46882261b27bf5ac8f2c814c76e00836c1fd8a77483074fb2cd5eb.json +++ b/.sqlx/query-c9e8539ffc001f4fea89e28319703294b33a9312693ff2f9e795227ee1bb50db.json @@ -1,27 +1,27 @@ { "db_name": "PostgreSQL", - "query": "SELECT enrollment_count, term FROM course WHERE id = $1 FOR UPDATE", + "query": "SELECT class_course_count, course_membership_count FROM course\n WHERE id = $1 FOR UPDATE", "describe": { "columns": [ { "ordinal": 0, - "name": "enrollment_count", + "name": "class_course_count", "type_info": "Int8", "origin": { "Table": { "table": "course", - "name": "enrollment_count" + "name": "class_course_count" } } }, { "ordinal": 1, - "name": "term", - "type_info": "Uuid", + "name": "course_membership_count", + "type_info": "Int8", "origin": { "Table": { "table": "course", - "name": "term" + "name": "course_membership_count" } } } @@ -33,8 +33,8 @@ }, "nullable": [ false, - true + false ] }, - "hash": "f77abe223a46882261b27bf5ac8f2c814c76e00836c1fd8a77483074fb2cd5eb" + "hash": "c9e8539ffc001f4fea89e28319703294b33a9312693ff2f9e795227ee1bb50db" } diff --git a/.sqlx/query-27bb824aa228c524d6ccfcd5fd13ff34c5a5e218f1b013021866d52a0f5d8474.json b/.sqlx/query-ca6514056875c3acd3cf79f227cfb3b09093a0bf5c7708c65504e3fc60c7f118.json similarity index 52% rename from .sqlx/query-27bb824aa228c524d6ccfcd5fd13ff34c5a5e218f1b013021866d52a0f5d8474.json rename to .sqlx/query-ca6514056875c3acd3cf79f227cfb3b09093a0bf5c7708c65504e3fc60c7f118.json index 31bb183..3512fd7 100644 --- a/.sqlx/query-27bb824aa228c524d6ccfcd5fd13ff34c5a5e218f1b013021866d52a0f5d8474.json +++ b/.sqlx/query-ca6514056875c3acd3cf79f227cfb3b09093a0bf5c7708c65504e3fc60c7f118.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "DELETE FROM session_attendance WHERE course = $1", + "query": "DELETE FROM exam_audience WHERE class_course = $1", "describe": { "columns": [], "parameters": { @@ -10,5 +10,5 @@ }, "nullable": [] }, - "hash": "27bb824aa228c524d6ccfcd5fd13ff34c5a5e218f1b013021866d52a0f5d8474" + "hash": "ca6514056875c3acd3cf79f227cfb3b09093a0bf5c7708c65504e3fc60c7f118" } diff --git a/.sqlx/query-425c4b69c806d2f70999dea4dfd56f471b95a2e0c99a880e428f5550abc05695.json b/.sqlx/query-caad4a6fe3555a38b1ac2f7dc3a4df74def95a0356454a07f9281103b19fdacc.json similarity index 53% rename from .sqlx/query-425c4b69c806d2f70999dea4dfd56f471b95a2e0c99a880e428f5550abc05695.json rename to .sqlx/query-caad4a6fe3555a38b1ac2f7dc3a4df74def95a0356454a07f9281103b19fdacc.json index 2803730..2f2abe4 100644 --- a/.sqlx/query-425c4b69c806d2f70999dea4dfd56f471b95a2e0c99a880e428f5550abc05695.json +++ b/.sqlx/query-caad4a6fe3555a38b1ac2f7dc3a4df74def95a0356454a07f9281103b19fdacc.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "DELETE FROM course_teacher WHERE teacher = $1", + "query": "DELETE FROM enrollment WHERE class_course = $1", "describe": { "columns": [], "parameters": { @@ -10,5 +10,5 @@ }, "nullable": [] }, - "hash": "425c4b69c806d2f70999dea4dfd56f471b95a2e0c99a880e428f5550abc05695" + "hash": "caad4a6fe3555a38b1ac2f7dc3a4df74def95a0356454a07f9281103b19fdacc" } diff --git a/.sqlx/query-ccb478d5d6140d28698b183ad905af36a014f483dc548b0068be808eb7b38df0.json b/.sqlx/query-ccb478d5d6140d28698b183ad905af36a014f483dc548b0068be808eb7b38df0.json new file mode 100644 index 0000000..4da6b81 --- /dev/null +++ b/.sqlx/query-ccb478d5d6140d28698b183ad905af36a014f483dc548b0068be808eb7b38df0.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM academic_year\n WHERE id = $1 AND class_count = 0 AND term_count = 0", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "ccb478d5d6140d28698b183ad905af36a014f483dc548b0068be808eb7b38df0" +} diff --git a/.sqlx/query-e8a08dbbc2d58b7fd391beea26491ac2c61ac38d35a6805cc95dc2f370822b07.json b/.sqlx/query-cd0f57c1fa26beeb650ed043fe80dc698082f8f17e7ee0fbd7467ff091fe8ff7.json similarity index 63% rename from .sqlx/query-e8a08dbbc2d58b7fd391beea26491ac2c61ac38d35a6805cc95dc2f370822b07.json rename to .sqlx/query-cd0f57c1fa26beeb650ed043fe80dc698082f8f17e7ee0fbd7467ff091fe8ff7.json index 478d43b..749c634 100644 --- a/.sqlx/query-e8a08dbbc2d58b7fd391beea26491ac2c61ac38d35a6805cc95dc2f370822b07.json +++ b/.sqlx/query-cd0f57c1fa26beeb650ed043fe80dc698082f8f17e7ee0fbd7467ff091fe8ff7.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "WITH seat AS (\n UPDATE class_group SET class_course_count = class_course_count + 1\n WHERE id = $1 AND class_course_count < $2\n RETURNING 1)\n INSERT INTO class_course (class, course, attached_by, attached_at, source)\n SELECT $1, $3, $4, $5, $6 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING 1 AS \"one\"", + "query": "WITH seat AS (\n UPDATE class_group SET class_course_count = class_course_count + 1\n WHERE id = $1 AND class_course_count < $2\n RETURNING 1)\n INSERT INTO class_course (id, class, course, attached_by, attached_at, source)\n SELECT $3, $1, $4, $5, $6, $7 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING 1 AS \"one\"", "describe": { "columns": [ { @@ -16,6 +16,7 @@ "Int8", "Uuid", "Uuid", + "Uuid", "Int8", "Uuid" ] @@ -24,5 +25,5 @@ null ] }, - "hash": "e8a08dbbc2d58b7fd391beea26491ac2c61ac38d35a6805cc95dc2f370822b07" + "hash": "cd0f57c1fa26beeb650ed043fe80dc698082f8f17e7ee0fbd7467ff091fe8ff7" } diff --git a/.sqlx/query-cd362195df1a2d07ac2c505cce03429f1a538e31d82e6ede3836d7f39c68efa4.json b/.sqlx/query-cd362195df1a2d07ac2c505cce03429f1a538e31d82e6ede3836d7f39c68efa4.json new file mode 100644 index 0000000..5c31ab4 --- /dev/null +++ b/.sqlx/query-cd362195df1a2d07ac2c505cce03429f1a538e31d82e6ede3836d7f39c68efa4.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT enrollment_count AS \"count: i64\" FROM class_course WHERE id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "count: i64", + "type_info": "Int8", + "origin": { + "Table": { + "table": "class_course", + "name": "enrollment_count" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "cd362195df1a2d07ac2c505cce03429f1a538e31d82e6ede3836d7f39c68efa4" +} diff --git a/.sqlx/query-0d0c13c18d5098eb1c581ea5e6d51af848d59f79a590386f898d85900022f8b1.json b/.sqlx/query-cf05e53c62f31d20f07e1f702e4f4d21bdbefaf19b3a14d8478ec3fdc8bcfc31.json similarity index 78% rename from .sqlx/query-0d0c13c18d5098eb1c581ea5e6d51af848d59f79a590386f898d85900022f8b1.json rename to .sqlx/query-cf05e53c62f31d20f07e1f702e4f4d21bdbefaf19b3a14d8478ec3fdc8bcfc31.json index eeb3d7b..8acfe97 100644 --- a/.sqlx/query-0d0c13c18d5098eb1c581ea5e6d51af848d59f79a590386f898d85900022f8b1.json +++ b/.sqlx/query-cf05e53c62f31d20f07e1f702e4f4d21bdbefaf19b3a14d8478ec3fdc8bcfc31.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "DELETE FROM course_session WHERE id = $1\n RETURNING id AS \"id: CourseSessionId\", course AS \"course: CourseId\",\n teacher AS \"teacher: UserId\", topic AS \"topic: SessionTopic\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\"", + "query": "DELETE FROM course_session WHERE id = $1\n RETURNING id AS \"id: CourseSessionId\",\n class_course AS \"class_course: ClassCourseId\",\n teacher AS \"teacher: UserId\", topic AS \"topic: SessionTopic\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\"", "describe": { "columns": [ { @@ -16,12 +16,12 @@ }, { "ordinal": 1, - "name": "course: CourseId", + "name": "class_course: ClassCourseId", "type_info": "Uuid", "origin": { "Table": { "table": "course_session", - "name": "course" + "name": "class_course" } } }, @@ -84,5 +84,5 @@ true ] }, - "hash": "0d0c13c18d5098eb1c581ea5e6d51af848d59f79a590386f898d85900022f8b1" + "hash": "cf05e53c62f31d20f07e1f702e4f4d21bdbefaf19b3a14d8478ec3fdc8bcfc31" } diff --git a/.sqlx/query-cf84beaac0eb97a92e8a2fde1cc7688b2d1a239f0604d945885c1c3a09b305b4.json b/.sqlx/query-cf84beaac0eb97a92e8a2fde1cc7688b2d1a239f0604d945885c1c3a09b305b4.json deleted file mode 100644 index f42da98..0000000 --- a/.sqlx/query-cf84beaac0eb97a92e8a2fde1cc7688b2d1a239f0604d945885c1c3a09b305b4.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO settings (id, exam_kinds, grade_bands, max_file_bytes,\n chatbot_history_turns, max_chatbot_message_len,\n max_chatbot_threads, meal_slots,\n meal_cancel_cutoff_minutes)\n VALUES ('school', $1, $2, $3, $4, $5, $6, $7, $8)\n ON CONFLICT (id) DO UPDATE SET\n exam_kinds = EXCLUDED.exam_kinds,\n grade_bands = EXCLUDED.grade_bands,\n max_file_bytes = EXCLUDED.max_file_bytes,\n chatbot_history_turns = EXCLUDED.chatbot_history_turns,\n max_chatbot_message_len = EXCLUDED.max_chatbot_message_len,\n max_chatbot_threads = EXCLUDED.max_chatbot_threads,\n meal_slots = EXCLUDED.meal_slots,\n meal_cancel_cutoff_minutes = EXCLUDED.meal_cancel_cutoff_minutes", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Jsonb", - "Jsonb", - "Int8", - "Int8", - "Int8", - "Int8", - "Jsonb", - "Int8" - ] - }, - "nullable": [] - }, - "hash": "cf84beaac0eb97a92e8a2fde1cc7688b2d1a239f0604d945885c1c3a09b305b4" -} diff --git a/.sqlx/query-d06525ead7b0e7e9a589950826700212d313d65c3feab3aaa029723ee2bee7cf.json b/.sqlx/query-d06525ead7b0e7e9a589950826700212d313d65c3feab3aaa029723ee2bee7cf.json new file mode 100644 index 0000000..f366bb3 --- /dev/null +++ b/.sqlx/query-d06525ead7b0e7e9a589950826700212d313d65c3feab3aaa029723ee2bee7cf.json @@ -0,0 +1,29 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT payload AS \"payload: Json\"\n FROM karne_snapshot WHERE term = $1 AND app_user = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "payload: Json", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "karne_snapshot", + "name": "payload" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "d06525ead7b0e7e9a589950826700212d313d65c3feab3aaa029723ee2bee7cf" +} diff --git a/.sqlx/query-d1be78d4182f131ba6792925a4557e4b4d9d43197d1b013ce3e5b4eb08b05cf6.json b/.sqlx/query-d1be78d4182f131ba6792925a4557e4b4d9d43197d1b013ce3e5b4eb08b05cf6.json deleted file mode 100644 index 36dbd36..0000000 --- a/.sqlx/query-d1be78d4182f131ba6792925a4557e4b4d9d43197d1b013ce3e5b4eb08b05cf6.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "DELETE FROM term\n WHERE id = $1 AND course_count = 0 AND class_count = 0", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Uuid" - ] - }, - "nullable": [] - }, - "hash": "d1be78d4182f131ba6792925a4557e4b4d9d43197d1b013ce3e5b4eb08b05cf6" -} diff --git a/.sqlx/query-d227e7369f4eabea326711629151cf5ff0e114ee97fb681e9463703f2ac2fb64.json b/.sqlx/query-d227e7369f4eabea326711629151cf5ff0e114ee97fb681e9463703f2ac2fb64.json new file mode 100644 index 0000000..11379f2 --- /dev/null +++ b/.sqlx/query-d227e7369f4eabea326711629151cf5ff0e114ee97fb681e9463703f2ac2fb64.json @@ -0,0 +1,24 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT 1 AS \"one\" FROM course_membership\n WHERE course = $1 AND app_user = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "one", + "type_info": "Int4", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Uuid", + "Uuid" + ] + }, + "nullable": [ + null + ] + }, + "hash": "d227e7369f4eabea326711629151cf5ff0e114ee97fb681e9463703f2ac2fb64" +} diff --git a/.sqlx/query-27dd38ebf96a18059c72db4b6b23f70b916a6273b29e768e303d612a29609fb1.json b/.sqlx/query-d5744188d2347496462ff093b7a8d06d1be3c44cf25b8bc40403e26196feb6ae.json similarity index 52% rename from .sqlx/query-27dd38ebf96a18059c72db4b6b23f70b916a6273b29e768e303d612a29609fb1.json rename to .sqlx/query-d5744188d2347496462ff093b7a8d06d1be3c44cf25b8bc40403e26196feb6ae.json index aa0c7a0..f0cce89 100644 --- a/.sqlx/query-27dd38ebf96a18059c72db4b6b23f70b916a6273b29e768e303d612a29609fb1.json +++ b/.sqlx/query-d5744188d2347496462ff093b7a8d06d1be3c44cf25b8bc40403e26196feb6ae.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "DELETE FROM course_teacher WHERE course = $1 AND teacher = $2", + "query": "INSERT INTO exam_audience (exam, class_course) VALUES ($1, $2)", "describe": { "columns": [], "parameters": { @@ -11,5 +11,5 @@ }, "nullable": [] }, - "hash": "27dd38ebf96a18059c72db4b6b23f70b916a6273b29e768e303d612a29609fb1" + "hash": "d5744188d2347496462ff093b7a8d06d1be3c44cf25b8bc40403e26196feb6ae" } diff --git a/.sqlx/query-d8f2d5db166767ffdeedd219bf24f44ac8614fea1b45c3935082e511653e23dc.json b/.sqlx/query-d8f2d5db166767ffdeedd219bf24f44ac8614fea1b45c3935082e511653e23dc.json new file mode 100644 index 0000000..552f914 --- /dev/null +++ b/.sqlx/query-d8f2d5db166767ffdeedd219bf24f44ac8614fea1b45c3935082e511653e23dc.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM class_course_teacher WHERE teacher = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "d8f2d5db166767ffdeedd219bf24f44ac8614fea1b45c3935082e511653e23dc" +} diff --git a/.sqlx/query-f60be76484071d1a16789dcc7b7d8eabcc179e9ce8efee2afe90635c6553fb1e.json b/.sqlx/query-da4c055f25da6b0e2fae8a7ccc4c7e7f806e731ca5dbaffe3cfc83b2a548be9f.json similarity index 59% rename from .sqlx/query-f60be76484071d1a16789dcc7b7d8eabcc179e9ce8efee2afe90635c6553fb1e.json rename to .sqlx/query-da4c055f25da6b0e2fae8a7ccc4c7e7f806e731ca5dbaffe3cfc83b2a548be9f.json index 445b2cf..7c98b0f 100644 --- a/.sqlx/query-f60be76484071d1a16789dcc7b7d8eabcc179e9ce8efee2afe90635c6553fb1e.json +++ b/.sqlx/query-da4c055f25da6b0e2fae8a7ccc4c7e7f806e731ca5dbaffe3cfc83b2a548be9f.json @@ -1,16 +1,16 @@ { "db_name": "PostgreSQL", - "query": "WITH gone AS (\n DELETE FROM enrollment\n WHERE course = $1 AND app_user = $2\n RETURNING course, app_user, enrolled_by, source),\n seated AS (\n UPDATE course\n SET enrollment_count = GREATEST(\n enrollment_count - (SELECT count(*) FROM gone), 0)\n WHERE id = $1\n RETURNING 1)\n SELECT course AS \"course: CourseId\", app_user AS \"user: UserId\",\n enrolled_by AS \"enrolled_by: UserId\", source AS \"source: ClassGroupId\" FROM gone", + "query": "SELECT class_course AS \"class_course: ClassCourseId\", app_user AS \"user: UserId\",\n enrolled_by AS \"enrolled_by: UserId\", source AS \"source: ClassGroupId\",\n created_at AS \"created_at: Timestamp\"\n FROM enrollment WHERE class_course = $1 AND app_user = $2", "describe": { "columns": [ { "ordinal": 0, - "name": "course: CourseId", + "name": "class_course: ClassCourseId", "type_info": "Uuid", "origin": { "Table": { "table": "enrollment", - "name": "course" + "name": "class_course" } } }, @@ -46,6 +46,17 @@ "name": "source" } } + }, + { + "ordinal": 4, + "name": "created_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "enrollment", + "name": "created_at" + } + } } ], "parameters": { @@ -58,8 +69,9 @@ false, false, false, - true + true, + false ] }, - "hash": "f60be76484071d1a16789dcc7b7d8eabcc179e9ce8efee2afe90635c6553fb1e" + "hash": "da4c055f25da6b0e2fae8a7ccc4c7e7f806e731ca5dbaffe3cfc83b2a548be9f" } diff --git a/.sqlx/query-b8279c8d5178f05cc4c3ee2afadd75e4759cf97aa94103d300dd19149c6c92f0.json b/.sqlx/query-da8172853a9900e6572ec43020f316f9d034f53ba696a5c9ad300663e8e5db2c.json similarity index 76% rename from .sqlx/query-b8279c8d5178f05cc4c3ee2afadd75e4759cf97aa94103d300dd19149c6c92f0.json rename to .sqlx/query-da8172853a9900e6572ec43020f316f9d034f53ba696a5c9ad300663e8e5db2c.json index 3b53c9b..a301e51 100644 --- a/.sqlx/query-b8279c8d5178f05cc4c3ee2afadd75e4759cf97aa94103d300dd19149c6c92f0.json +++ b/.sqlx/query-da8172853a9900e6572ec43020f316f9d034f53ba696a5c9ad300663e8e5db2c.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "DELETE FROM exam WHERE id = $1\n RETURNING id AS \"id: ExamId\", creator AS \"creator: UserId\",\n course AS \"course: CourseId\", title AS \"title: ExamTitle\",\n description AS \"description: ExamDescription\",\n kind AS \"kind: ExamKind\", mode AS \"mode: ExamMode\",\n starts_at AS \"starts_at: Timestamp\",\n ends_at AS \"ends_at: Timestamp\",\n duration_ms AS \"duration_ms: ExamDuration\",\n max_attempts AS \"max_attempts: ExamAttemptLimit\",\n allow_rejoin, allow_review, draft", + "query": "DELETE FROM exam WHERE id = $1\n RETURNING id AS \"id: ExamId\", creator AS \"creator: UserId\",\n class_course AS \"class_course: ClassCourseId\",\n term AS \"term: TermId\", title AS \"title: ExamTitle\",\n description AS \"description: ExamDescription\",\n kind AS \"kind: ExamKind\", mode AS \"mode: ExamMode\",\n starts_at AS \"starts_at: Timestamp\",\n ends_at AS \"ends_at: Timestamp\",\n duration_ms AS \"duration_ms: ExamDuration\",\n max_attempts AS \"max_attempts: ExamAttemptLimit\",\n allow_rejoin, allow_review, draft", "describe": { "columns": [ { @@ -27,17 +27,28 @@ }, { "ordinal": 2, - "name": "course: CourseId", + "name": "class_course: ClassCourseId", "type_info": "Uuid", "origin": { "Table": { "table": "exam", - "name": "course" + "name": "class_course" } } }, { "ordinal": 3, + "name": "term: TermId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "exam", + "name": "term" + } + } + }, + { + "ordinal": 4, "name": "title: ExamTitle", "type_info": "Text", "origin": { @@ -48,7 +59,7 @@ } }, { - "ordinal": 4, + "ordinal": 5, "name": "description: ExamDescription", "type_info": "Text", "origin": { @@ -59,7 +70,7 @@ } }, { - "ordinal": 5, + "ordinal": 6, "name": "kind: ExamKind", "type_info": "Text", "origin": { @@ -70,7 +81,7 @@ } }, { - "ordinal": 6, + "ordinal": 7, "name": "mode: ExamMode", "type_info": "Text", "origin": { @@ -81,7 +92,7 @@ } }, { - "ordinal": 7, + "ordinal": 8, "name": "starts_at: Timestamp", "type_info": "Int8", "origin": { @@ -92,7 +103,7 @@ } }, { - "ordinal": 8, + "ordinal": 9, "name": "ends_at: Timestamp", "type_info": "Int8", "origin": { @@ -103,7 +114,7 @@ } }, { - "ordinal": 9, + "ordinal": 10, "name": "duration_ms: ExamDuration", "type_info": "Int8", "origin": { @@ -114,7 +125,7 @@ } }, { - "ordinal": 10, + "ordinal": 11, "name": "max_attempts: ExamAttemptLimit", "type_info": "Int8", "origin": { @@ -125,7 +136,7 @@ } }, { - "ordinal": 11, + "ordinal": 12, "name": "allow_rejoin", "type_info": "Bool", "origin": { @@ -136,7 +147,7 @@ } }, { - "ordinal": 12, + "ordinal": 13, "name": "allow_review", "type_info": "Bool", "origin": { @@ -147,7 +158,7 @@ } }, { - "ordinal": 13, + "ordinal": 14, "name": "draft", "type_info": "Bool", "origin": { @@ -170,6 +181,7 @@ false, false, false, + false, true, true, true, @@ -180,5 +192,5 @@ false ] }, - "hash": "b8279c8d5178f05cc4c3ee2afadd75e4759cf97aa94103d300dd19149c6c92f0" + "hash": "da8172853a9900e6572ec43020f316f9d034f53ba696a5c9ad300663e8e5db2c" } diff --git a/.sqlx/query-dbcf7f63fb683407d48601841aab230a2323c676e7886509be184361747f9c8a.json b/.sqlx/query-dbcf7f63fb683407d48601841aab230a2323c676e7886509be184361747f9c8a.json new file mode 100644 index 0000000..8827f0c --- /dev/null +++ b/.sqlx/query-dbcf7f63fb683407d48601841aab230a2323c676e7886509be184361747f9c8a.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE enrollment SET source = NULL WHERE source = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "dbcf7f63fb683407d48601841aab230a2323c676e7886509be184361747f9c8a" +} diff --git a/.sqlx/query-dc4e699d21300e00e144794ce36ebe0a50ed9833393af07b727e69f3def66d42.json b/.sqlx/query-dc4e699d21300e00e144794ce36ebe0a50ed9833393af07b727e69f3def66d42.json new file mode 100644 index 0000000..0829133 --- /dev/null +++ b/.sqlx/query-dc4e699d21300e00e144794ce36ebe0a50ed9833393af07b727e69f3def66d42.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM session_attendance WHERE class_course = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "dc4e699d21300e00e144794ce36ebe0a50ed9833393af07b727e69f3def66d42" +} diff --git a/.sqlx/query-e19b652daae920d9095b3485060cbf36828c7d4a794005fc5a5252c8b6af62ca.json b/.sqlx/query-e19b652daae920d9095b3485060cbf36828c7d4a794005fc5a5252c8b6af62ca.json deleted file mode 100644 index 2b54a2f..0000000 --- a/.sqlx/query-e19b652daae920d9095b3485060cbf36828c7d4a794005fc5a5252c8b6af62ca.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "DELETE FROM homework_file WHERE submission IN (\n SELECT id FROM homework_submission\n WHERE homework IN (SELECT id FROM homework WHERE course = $1))", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Uuid" - ] - }, - "nullable": [] - }, - "hash": "e19b652daae920d9095b3485060cbf36828c7d4a794005fc5a5252c8b6af62ca" -} diff --git a/.sqlx/query-178ed4347a442f045bdfdab1153fd3b72c901f9278c37d4c9f5385f639a7fa1d.json b/.sqlx/query-e50aac98a42832e61a62d8b1a7e3aef9758ddc0d246de5622473d9011897f363.json similarity index 73% rename from .sqlx/query-178ed4347a442f045bdfdab1153fd3b72c901f9278c37d4c9f5385f639a7fa1d.json rename to .sqlx/query-e50aac98a42832e61a62d8b1a7e3aef9758ddc0d246de5622473d9011897f363.json index 052f949..8a0a4da 100644 --- a/.sqlx/query-178ed4347a442f045bdfdab1153fd3b72c901f9278c37d4c9f5385f639a7fa1d.json +++ b/.sqlx/query-e50aac98a42832e61a62d8b1a7e3aef9758ddc0d246de5622473d9011897f363.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO course_session (id, course, teacher, topic, starts_at, ends_at)\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING id AS \"id: CourseSessionId\", course AS \"course: CourseId\",\n teacher AS \"teacher: UserId\", topic AS \"topic: SessionTopic\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\"", + "query": "INSERT INTO course_session (id, class_course, teacher, topic, starts_at, ends_at)\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING id AS \"id: CourseSessionId\",\n class_course AS \"class_course: ClassCourseId\",\n teacher AS \"teacher: UserId\", topic AS \"topic: SessionTopic\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\"", "describe": { "columns": [ { @@ -16,12 +16,12 @@ }, { "ordinal": 1, - "name": "course: CourseId", + "name": "class_course: ClassCourseId", "type_info": "Uuid", "origin": { "Table": { "table": "course_session", - "name": "course" + "name": "class_course" } } }, @@ -89,5 +89,5 @@ true ] }, - "hash": "178ed4347a442f045bdfdab1153fd3b72c901f9278c37d4c9f5385f639a7fa1d" + "hash": "e50aac98a42832e61a62d8b1a7e3aef9758ddc0d246de5622473d9011897f363" } diff --git a/.sqlx/query-e61998707fa0030ed51a367b56e3a62bee785870b91d97998eaa7e3af29ae87e.json b/.sqlx/query-e61998707fa0030ed51a367b56e3a62bee785870b91d97998eaa7e3af29ae87e.json new file mode 100644 index 0000000..cf05838 --- /dev/null +++ b/.sqlx/query-e61998707fa0030ed51a367b56e3a62bee785870b91d97998eaa7e3af29ae87e.json @@ -0,0 +1,128 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE academic_year\n SET name = COALESCE($2, name),\n starts_at = COALESCE($3, starts_at),\n ends_at = COALESCE($4, ends_at),\n grade_promotions = COALESCE($5, grade_promotions)\n WHERE id = $1\n AND COALESCE($4, ends_at) > COALESCE($3, starts_at)\n RETURNING id AS \"id: AcademicYearId\", name AS \"name: AcademicYearName\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\",\n archived_at AS \"archived_at: Timestamp\", creator AS \"creator: UserId\",\n grade_promotions AS \"grade_promotions: Json>\",\n class_count, term_count", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: AcademicYearId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "academic_year", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "name: AcademicYearName", + "type_info": "Text", + "origin": { + "Table": { + "table": "academic_year", + "name": "name" + } + } + }, + { + "ordinal": 2, + "name": "starts_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "academic_year", + "name": "starts_at" + } + } + }, + { + "ordinal": 3, + "name": "ends_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "academic_year", + "name": "ends_at" + } + } + }, + { + "ordinal": 4, + "name": "archived_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "academic_year", + "name": "archived_at" + } + } + }, + { + "ordinal": 5, + "name": "creator: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "academic_year", + "name": "creator" + } + } + }, + { + "ordinal": 6, + "name": "grade_promotions: Json>", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "academic_year", + "name": "grade_promotions" + } + } + }, + { + "ordinal": 7, + "name": "class_count", + "type_info": "Int8", + "origin": { + "Table": { + "table": "academic_year", + "name": "class_count" + } + } + }, + { + "ordinal": 8, + "name": "term_count", + "type_info": "Int8", + "origin": { + "Table": { + "table": "academic_year", + "name": "term_count" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Text", + "Int8", + "Int8", + "Jsonb" + ] + }, + "nullable": [ + false, + false, + false, + false, + true, + false, + false, + false, + false + ] + }, + "hash": "e61998707fa0030ed51a367b56e3a62bee785870b91d97998eaa7e3af29ae87e" +} diff --git a/.sqlx/query-6c518ef0581ca1549988917c39135198f1bf92d9a7b4984b227849771bec8699.json b/.sqlx/query-e7fd2e1221613ddef9bc36d6b2ed44b3e8b351471573a4f84e0ce06cb49aeebc.json similarity index 74% rename from .sqlx/query-6c518ef0581ca1549988917c39135198f1bf92d9a7b4984b227849771bec8699.json rename to .sqlx/query-e7fd2e1221613ddef9bc36d6b2ed44b3e8b351471573a4f84e0ce06cb49aeebc.json index b0df317..579ceca 100644 --- a/.sqlx/query-6c518ef0581ca1549988917c39135198f1bf92d9a7b4984b227849771bec8699.json +++ b/.sqlx/query-e7fd2e1221613ddef9bc36d6b2ed44b3e8b351471573a4f84e0ce06cb49aeebc.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework ORDER BY id DESC", + "query": "SELECT id AS \"id: HomeworkId\",\n class_course AS \"class_course: ClassCourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework ORDER BY id DESC", "describe": { "columns": [ { @@ -16,12 +16,12 @@ }, { "ordinal": 1, - "name": "course: CourseId", + "name": "class_course: ClassCourseId", "type_info": "Uuid", "origin": { "Table": { "table": "homework", - "name": "course" + "name": "class_course" } } }, @@ -113,5 +113,5 @@ false ] }, - "hash": "6c518ef0581ca1549988917c39135198f1bf92d9a7b4984b227849771bec8699" + "hash": "e7fd2e1221613ddef9bc36d6b2ed44b3e8b351471573a4f84e0ce06cb49aeebc" } diff --git a/.sqlx/query-b99095e17c379fb32aea7db2926a9cc78bb3e7ed3200aca3e8019f4103c148d6.json b/.sqlx/query-e9e9c3f5b35f35338501485a155be2784075bb0a5b29a270093da5e409ada3ed.json similarity index 69% rename from .sqlx/query-b99095e17c379fb32aea7db2926a9cc78bb3e7ed3200aca3e8019f4103c148d6.json rename to .sqlx/query-e9e9c3f5b35f35338501485a155be2784075bb0a5b29a270093da5e409ada3ed.json index 3823be6..e9c7ef4 100644 --- a/.sqlx/query-b99095e17c379fb32aea7db2926a9cc78bb3e7ed3200aca3e8019f4103c148d6.json +++ b/.sqlx/query-e9e9c3f5b35f35338501485a155be2784075bb0a5b29a270093da5e409ada3ed.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT qi.file FROM question_image qi\n JOIN exam e ON e.id = qi.exam WHERE e.course = $1", + "query": "SELECT qi.file FROM question_image qi\n JOIN exam e ON e.id = qi.exam\n JOIN class_course cc ON cc.id = e.class_course\n WHERE cc.course = $1", "describe": { "columns": [ { @@ -24,5 +24,5 @@ false ] }, - "hash": "b99095e17c379fb32aea7db2926a9cc78bb3e7ed3200aca3e8019f4103c148d6" + "hash": "e9e9c3f5b35f35338501485a155be2784075bb0a5b29a270093da5e409ada3ed" } diff --git a/.sqlx/query-0f4855352631239aaf9aac48ad4510afd1081f61c523106c60c62ae3c7ad9944.json b/.sqlx/query-ea2f28046b3ef41ed15703197135e3be14d9568d9795278a8afbc14dd52e448f.json similarity index 92% rename from .sqlx/query-0f4855352631239aaf9aac48ad4510afd1081f61c523106c60c62ae3c7ad9944.json rename to .sqlx/query-ea2f28046b3ef41ed15703197135e3be14d9568d9795278a8afbc14dd52e448f.json index 381fcee..e18e8bb 100644 --- a/.sqlx/query-0f4855352631239aaf9aac48ad4510afd1081f61c523106c60c62ae3c7ad9944.json +++ b/.sqlx/query-ea2f28046b3ef41ed15703197135e3be14d9568d9795278a8afbc14dd52e448f.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n avatar_size\n FROM app_user WHERE id = ANY($1)", + "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n branch,\n avatar_size\n FROM app_user WHERE id = ANY($1)", "describe": { "columns": [ { @@ -181,6 +181,17 @@ }, { "ordinal": 16, + "name": "branch", + "type_info": "Text", + "origin": { + "Table": { + "table": "app_user", + "name": "branch" + } + } + }, + { + "ordinal": 17, "name": "avatar_size", "type_info": "Int8", "origin": { @@ -213,8 +224,9 @@ true, true, true, + true, true ] }, - "hash": "0f4855352631239aaf9aac48ad4510afd1081f61c523106c60c62ae3c7ad9944" + "hash": "ea2f28046b3ef41ed15703197135e3be14d9568d9795278a8afbc14dd52e448f" } diff --git a/.sqlx/query-44493997240e532ba46452ef0222b2de5524cbf7ef435d7dd57a7e185a02891e.json b/.sqlx/query-ea7346e8dcbf509401f3e89f0570b1c356222b02e85aa0571337f7a670792abb.json similarity index 63% rename from .sqlx/query-44493997240e532ba46452ef0222b2de5524cbf7ef435d7dd57a7e185a02891e.json rename to .sqlx/query-ea7346e8dcbf509401f3e89f0570b1c356222b02e85aa0571337f7a670792abb.json index bfa45d4..ed6741e 100644 --- a/.sqlx/query-44493997240e532ba46452ef0222b2de5524cbf7ef435d7dd57a7e185a02891e.json +++ b/.sqlx/query-ea7346e8dcbf509401f3e89f0570b1c356222b02e85aa0571337f7a670792abb.json @@ -1,16 +1,16 @@ { "db_name": "PostgreSQL", - "query": "SELECT course AS \"course: uuid::Uuid\", app_user AS \"app_user: uuid::Uuid\"\n FROM enrollment WHERE course = $1 AND source = $2", + "query": "SELECT class_course AS \"class_course: uuid::Uuid\",\n app_user AS \"app_user: uuid::Uuid\"\n FROM enrollment WHERE app_user = $1 AND source = $2", "describe": { "columns": [ { "ordinal": 0, - "name": "course: uuid::Uuid", + "name": "class_course: uuid::Uuid", "type_info": "Uuid", "origin": { "Table": { "table": "enrollment", - "name": "course" + "name": "class_course" } } }, @@ -37,5 +37,5 @@ false ] }, - "hash": "44493997240e532ba46452ef0222b2de5524cbf7ef435d7dd57a7e185a02891e" + "hash": "ea7346e8dcbf509401f3e89f0570b1c356222b02e85aa0571337f7a670792abb" } diff --git a/.sqlx/query-eb3422e43b27e70b5b4eac909cb191ed8c89b0caeb2e2f27f93ea6a5469300e0.json b/.sqlx/query-eb3422e43b27e70b5b4eac909cb191ed8c89b0caeb2e2f27f93ea6a5469300e0.json deleted file mode 100644 index 683f707..0000000 --- a/.sqlx/query-eb3422e43b27e70b5b4eac909cb191ed8c89b0caeb2e2f27f93ea6a5469300e0.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "DELETE FROM exam_question WHERE exam = ANY($1)", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "UuidArray" - ] - }, - "nullable": [] - }, - "hash": "eb3422e43b27e70b5b4eac909cb191ed8c89b0caeb2e2f27f93ea6a5469300e0" -} diff --git a/.sqlx/query-f64594c9dd40fc944bcc77ae1bf62adc1a6d90c8cf53d4807dfa4db26d4faf41.json b/.sqlx/query-eb5fb3b8d7b2b7e6f199b036ae94637a4485b71ab52385a3016c9bdad24bd712.json similarity index 93% rename from .sqlx/query-f64594c9dd40fc944bcc77ae1bf62adc1a6d90c8cf53d4807dfa4db26d4faf41.json rename to .sqlx/query-eb5fb3b8d7b2b7e6f199b036ae94637a4485b71ab52385a3016c9bdad24bd712.json index 534e8ba..5b6725a 100644 --- a/.sqlx/query-f64594c9dd40fc944bcc77ae1bf62adc1a6d90c8cf53d4807dfa4db26d4faf41.json +++ b/.sqlx/query-eb5fb3b8d7b2b7e6f199b036ae94637a4485b71ab52385a3016c9bdad24bd712.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE app_user SET role = $2\n WHERE id = $1\n AND NOT (role = 'admin'\n AND $2 <> 'admin'\n AND (SELECT count(*) FROM app_user\n WHERE role = 'admin' AND id <> $1) = 0)\n RETURNING id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n avatar_size", + "query": "UPDATE app_user SET role = $2\n WHERE id = $1\n AND NOT (role = 'admin'\n AND $2 <> 'admin'\n AND (SELECT count(*) FROM app_user\n WHERE role = 'admin' AND id <> $1) = 0)\n RETURNING id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n branch,\n avatar_size", "describe": { "columns": [ { @@ -181,6 +181,17 @@ }, { "ordinal": 16, + "name": "branch", + "type_info": "Text", + "origin": { + "Table": { + "table": "app_user", + "name": "branch" + } + } + }, + { + "ordinal": 17, "name": "avatar_size", "type_info": "Int8", "origin": { @@ -214,8 +225,9 @@ true, true, true, + true, true ] }, - "hash": "f64594c9dd40fc944bcc77ae1bf62adc1a6d90c8cf53d4807dfa4db26d4faf41" + "hash": "eb5fb3b8d7b2b7e6f199b036ae94637a4485b71ab52385a3016c9bdad24bd712" } diff --git a/.sqlx/query-ee474f7fcb2cd36d33ed13426c0f0ef265646de1ecb1f3f928ecaa6a9a36ea26.json b/.sqlx/query-ee474f7fcb2cd36d33ed13426c0f0ef265646de1ecb1f3f928ecaa6a9a36ea26.json new file mode 100644 index 0000000..08add7f --- /dev/null +++ b/.sqlx/query-ee474f7fcb2cd36d33ed13426c0f0ef265646de1ecb1f3f928ecaa6a9a36ea26.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH gone AS (\n DELETE FROM term\n WHERE id = $1 AND exam_count = 0\n AND NOT EXISTS (SELECT 1 FROM karne_snapshot WHERE term = $1)\n RETURNING year)\n UPDATE academic_year\n SET term_count = GREATEST(term_count - 1, 0)\n FROM gone\n WHERE academic_year.id = gone.year", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "ee474f7fcb2cd36d33ed13426c0f0ef265646de1ecb1f3f928ecaa6a9a36ea26" +} diff --git a/.sqlx/query-c2dab6249cebf45a0a61c542700e05679a5bd6e335cc76767a167d00b3aa964d.json b/.sqlx/query-eea12c0e9e29b452028c242afe9f5fe6328a014793d2fefc12cd0cc4c4d6421e.json similarity index 84% rename from .sqlx/query-c2dab6249cebf45a0a61c542700e05679a5bd6e335cc76767a167d00b3aa964d.json rename to .sqlx/query-eea12c0e9e29b452028c242afe9f5fe6328a014793d2fefc12cd0cc4c4d6421e.json index 15d2a43..a7f553e 100644 --- a/.sqlx/query-c2dab6249cebf45a0a61c542700e05679a5bd6e335cc76767a167d00b3aa964d.json +++ b/.sqlx/query-eea12c0e9e29b452028c242afe9f5fe6328a014793d2fefc12cd0cc4c4d6421e.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n term AS \"term: TermId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE grade = $1", + "query": "SELECT id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"\n FROM class_group WHERE grade = $1", "describe": { "columns": [ { @@ -49,12 +49,12 @@ }, { "ordinal": 4, - "name": "term: TermId", + "name": "year: AcademicYearId", "type_info": "Uuid", "origin": { "Table": { "table": "class_group", - "name": "term" + "name": "year" } } }, @@ -84,5 +84,5 @@ true ] }, - "hash": "c2dab6249cebf45a0a61c542700e05679a5bd6e335cc76767a167d00b3aa964d" + "hash": "eea12c0e9e29b452028c242afe9f5fe6328a014793d2fefc12cd0cc4c4d6421e" } diff --git a/.sqlx/query-2db4b9a7ae30282e36229c463126bfe5d8670dc1a44a326704c8a503f537ab2f.json b/.sqlx/query-eeef9fa58c5f58e8758e184fa0b686b192a18463f4cb43e2334535861a372217.json similarity index 61% rename from .sqlx/query-2db4b9a7ae30282e36229c463126bfe5d8670dc1a44a326704c8a503f537ab2f.json rename to .sqlx/query-eeef9fa58c5f58e8758e184fa0b686b192a18463f4cb43e2334535861a372217.json index 6b36534..905de88 100644 --- a/.sqlx/query-2db4b9a7ae30282e36229c463126bfe5d8670dc1a44a326704c8a503f537ab2f.json +++ b/.sqlx/query-eeef9fa58c5f58e8758e184fa0b686b192a18463f4cb43e2334535861a372217.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "DELETE FROM homework_result WHERE homework IN (\n SELECT id FROM homework WHERE course = $1)", + "query": "DELETE FROM homework_result WHERE homework IN (\n SELECT id FROM homework WHERE class_course = $1)", "describe": { "columns": [], "parameters": { @@ -10,5 +10,5 @@ }, "nullable": [] }, - "hash": "2db4b9a7ae30282e36229c463126bfe5d8670dc1a44a326704c8a503f537ab2f" + "hash": "eeef9fa58c5f58e8758e184fa0b686b192a18463f4cb43e2334535861a372217" } diff --git a/.sqlx/query-f0670cba23b45c7dd4e88531aed7c10ecbdf9f108165b055794a3c8ba5d7031b.json b/.sqlx/query-f0670cba23b45c7dd4e88531aed7c10ecbdf9f108165b055794a3c8ba5d7031b.json new file mode 100644 index 0000000..5333644 --- /dev/null +++ b/.sqlx/query-f0670cba23b45c7dd4e88531aed7c10ecbdf9f108165b055794a3c8ba5d7031b.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH gone AS (\n DELETE FROM homework WHERE class_course = $1\n RETURNING subject),\n subs AS (\n SELECT subject, count(*) AS n FROM gone GROUP BY subject)\n UPDATE subject s SET homework_count = GREATEST(s.homework_count - c.n, 0)\n FROM subs c WHERE s.id = c.subject", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "f0670cba23b45c7dd4e88531aed7c10ecbdf9f108165b055794a3c8ba5d7031b" +} diff --git a/.sqlx/query-57ab52a67001f23abd0c94617d41d0a35ba6fee7fb71e0523c3c28862f2e7874.json b/.sqlx/query-f0a41ad9450035b1fc8d52e4a4a4b1ada1998252bc516846e1d4f88b489e7c3c.json similarity index 54% rename from .sqlx/query-57ab52a67001f23abd0c94617d41d0a35ba6fee7fb71e0523c3c28862f2e7874.json rename to .sqlx/query-f0a41ad9450035b1fc8d52e4a4a4b1ada1998252bc516846e1d4f88b489e7c3c.json index 391d407..1766f8f 100644 --- a/.sqlx/query-57ab52a67001f23abd0c94617d41d0a35ba6fee7fb71e0523c3c28862f2e7874.json +++ b/.sqlx/query-f0a41ad9450035b1fc8d52e4a4a4b1ada1998252bc516846e1d4f88b489e7c3c.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT EXISTS(SELECT 1 FROM class_member WHERE class = $1 AND app_user = $2)\n AS \"present!\"", + "query": "SELECT EXISTS(SELECT 1 FROM class_member\n WHERE class = $1 AND app_user = $2 AND left_at IS NULL)\n AS \"present!\"", "describe": { "columns": [ { @@ -20,5 +20,5 @@ null ] }, - "hash": "57ab52a67001f23abd0c94617d41d0a35ba6fee7fb71e0523c3c28862f2e7874" + "hash": "f0a41ad9450035b1fc8d52e4a4a4b1ada1998252bc516846e1d4f88b489e7c3c" } diff --git a/.sqlx/query-f12076e5b4bce06b50cc5923837f943560b4f8b9bc4f9bde9d3c4908513b8ae7.json b/.sqlx/query-f12076e5b4bce06b50cc5923837f943560b4f8b9bc4f9bde9d3c4908513b8ae7.json new file mode 100644 index 0000000..f176ffb --- /dev/null +++ b/.sqlx/query-f12076e5b4bce06b50cc5923837f943560b4f8b9bc4f9bde9d3c4908513b8ae7.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM homework_file\n WHERE submission IN (SELECT id FROM homework_submission WHERE homework IN (\n SELECT id FROM homework WHERE class_course = $1))", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "f12076e5b4bce06b50cc5923837f943560b4f8b9bc4f9bde9d3c4908513b8ae7" +} diff --git a/.sqlx/query-b12b099fc63ee82716606640bd2321aea103d8ec7cde10154c37aac7f5a0d429.json b/.sqlx/query-f5547737eed659d69097999705426f0a827f9e7eeaeaf64c7a808784c6a95d95.json similarity index 64% rename from .sqlx/query-b12b099fc63ee82716606640bd2321aea103d8ec7cde10154c37aac7f5a0d429.json rename to .sqlx/query-f5547737eed659d69097999705426f0a827f9e7eeaeaf64c7a808784c6a95d95.json index 00721cf..452cc6b 100644 --- a/.sqlx/query-b12b099fc63ee82716606640bd2321aea103d8ec7cde10154c37aac7f5a0d429.json +++ b/.sqlx/query-f5547737eed659d69097999705426f0a827f9e7eeaeaf64c7a808784c6a95d95.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT 1 AS \"one\" FROM enrollment WHERE course = $1 AND app_user = $2", + "query": "SELECT 1 AS \"one\" FROM course_membership WHERE course = $1 AND app_user = $2", "describe": { "columns": [ { @@ -20,5 +20,5 @@ null ] }, - "hash": "b12b099fc63ee82716606640bd2321aea103d8ec7cde10154c37aac7f5a0d429" + "hash": "f5547737eed659d69097999705426f0a827f9e7eeaeaf64c7a808784c6a95d95" } diff --git a/.sqlx/query-1426cb1fc87d2e06ea919254bac9cb3403d07318c2bb43388a8dca245a952fc8.json b/.sqlx/query-f6110c3d1f0e072aa0f0c62c631bb9846f1b6d509f4688f7e86e93c48a7f9d9f.json similarity index 50% rename from .sqlx/query-1426cb1fc87d2e06ea919254bac9cb3403d07318c2bb43388a8dca245a952fc8.json rename to .sqlx/query-f6110c3d1f0e072aa0f0c62c631bb9846f1b6d509f4688f7e86e93c48a7f9d9f.json index a71595d..0b30038 100644 --- a/.sqlx/query-1426cb1fc87d2e06ea919254bac9cb3403d07318c2bb43388a8dca245a952fc8.json +++ b/.sqlx/query-f6110c3d1f0e072aa0f0c62c631bb9846f1b6d509f4688f7e86e93c48a7f9d9f.json @@ -1,16 +1,16 @@ { "db_name": "PostgreSQL", - "query": "WITH seat AS (\n UPDATE course\n SET enrollment_count = enrollment_count + 1\n WHERE id = $1\n AND enrollment_count < COALESCE(capacity, $2)\n RETURNING 1)\n INSERT INTO enrollment (course, app_user, enrolled_by, source, created_at)\n SELECT $1, $3, $4, NULL, $5 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING course AS \"course: CourseId\", app_user AS \"user: UserId\",\n enrolled_by AS \"enrolled_by: UserId\", source AS \"source: ClassGroupId\"", + "query": "WITH seat AS (\n UPDATE class_course\n SET enrollment_count = enrollment_count + 1\n WHERE id = $1\n RETURNING 1)\n INSERT INTO enrollment (class_course, app_user, enrolled_by, source, created_at)\n SELECT $1, $2, $3, $4, $5 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING class_course AS \"class_course: ClassCourseId\",\n app_user AS \"user: UserId\", enrolled_by AS \"enrolled_by: UserId\",\n source AS \"source: ClassGroupId\",\n created_at AS \"created_at: Timestamp\"", "describe": { "columns": [ { "ordinal": 0, - "name": "course: CourseId", + "name": "class_course: ClassCourseId", "type_info": "Uuid", "origin": { "Table": { "table": "enrollment", - "name": "course" + "name": "class_course" } } }, @@ -46,12 +46,23 @@ "name": "source" } } + }, + { + "ordinal": 4, + "name": "created_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "enrollment", + "name": "created_at" + } + } } ], "parameters": { "Left": [ "Uuid", - "Int8", + "Uuid", "Uuid", "Uuid", "Int8" @@ -61,8 +72,9 @@ false, false, false, - true + true, + false ] }, - "hash": "1426cb1fc87d2e06ea919254bac9cb3403d07318c2bb43388a8dca245a952fc8" + "hash": "f6110c3d1f0e072aa0f0c62c631bb9846f1b6d509f4688f7e86e93c48a7f9d9f" } diff --git a/.sqlx/query-1df2ab45fdf2662a7d8b6a37eabf921e159e9a526b8a3f16086c2db3f390ae78.json b/.sqlx/query-f72a0bb5098304333748ff839953de5e2f9bc6a7bb92295c4514026842c282a0.json similarity index 54% rename from .sqlx/query-1df2ab45fdf2662a7d8b6a37eabf921e159e9a526b8a3f16086c2db3f390ae78.json rename to .sqlx/query-f72a0bb5098304333748ff839953de5e2f9bc6a7bb92295c4514026842c282a0.json index 047519e..235d3f0 100644 --- a/.sqlx/query-1df2ab45fdf2662a7d8b6a37eabf921e159e9a526b8a3f16086c2db3f390ae78.json +++ b/.sqlx/query-f72a0bb5098304333748ff839953de5e2f9bc6a7bb92295c4514026842c282a0.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "DELETE FROM homework WHERE course = $1", + "query": "DELETE FROM class_course WHERE id = $1", "describe": { "columns": [], "parameters": { @@ -10,5 +10,5 @@ }, "nullable": [] }, - "hash": "1df2ab45fdf2662a7d8b6a37eabf921e159e9a526b8a3f16086c2db3f390ae78" + "hash": "f72a0bb5098304333748ff839953de5e2f9bc6a7bb92295c4514026842c282a0" } diff --git a/.sqlx/query-f8000bdc282afa0ebfc1c258f1478c504fc10234c6099f677a2cb3b59f001a67.json b/.sqlx/query-f8000bdc282afa0ebfc1c258f1478c504fc10234c6099f677a2cb3b59f001a67.json new file mode 100644 index 0000000..a755ac2 --- /dev/null +++ b/.sqlx/query-f8000bdc282afa0ebfc1c258f1478c504fc10234c6099f677a2cb3b59f001a67.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE course SET class_course_count = GREATEST(class_course_count - 1, 0)\n WHERE id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "f8000bdc282afa0ebfc1c258f1478c504fc10234c6099f677a2cb3b59f001a67" +} diff --git a/.sqlx/query-9bb792ad62ed64306b9812bb3a049fe742604c0ad3162c9466869a1fe55e7463.json b/.sqlx/query-f99618110767c8805bdbef2de1ba16f90a0430ee6ba734af80f90b8ab4527e71.json similarity index 72% rename from .sqlx/query-9bb792ad62ed64306b9812bb3a049fe742604c0ad3162c9466869a1fe55e7463.json rename to .sqlx/query-f99618110767c8805bdbef2de1ba16f90a0430ee6ba734af80f90b8ab4527e71.json index 895a04f..5df5573 100644 --- a/.sqlx/query-9bb792ad62ed64306b9812bb3a049fe742604c0ad3162c9466869a1fe55e7463.json +++ b/.sqlx/query-f99618110767c8805bdbef2de1ba16f90a0430ee6ba734af80f90b8ab4527e71.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE term SET archived_at = $2\n WHERE id = $1 AND archived_at IS NULL\n RETURNING id AS \"id: TermId\", name AS \"name: TermName\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\",\n archived_at AS \"archived_at: Timestamp\"", + "query": "UPDATE term SET archived_at = $2\n WHERE id = $1 AND archived_at IS NULL\n RETURNING id AS \"id: TermId\", year AS \"year: AcademicYearId\",\n name AS \"name: TermName\",\n starts_at AS \"starts_at: Timestamp\", ends_at AS \"ends_at: Timestamp\",\n archived_at AS \"archived_at: Timestamp\"", "describe": { "columns": [ { @@ -16,6 +16,17 @@ }, { "ordinal": 1, + "name": "year: AcademicYearId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "term", + "name": "year" + } + } + }, + { + "ordinal": 2, "name": "name: TermName", "type_info": "Text", "origin": { @@ -26,7 +37,7 @@ } }, { - "ordinal": 2, + "ordinal": 3, "name": "starts_at: Timestamp", "type_info": "Int8", "origin": { @@ -37,7 +48,7 @@ } }, { - "ordinal": 3, + "ordinal": 4, "name": "ends_at: Timestamp", "type_info": "Int8", "origin": { @@ -48,7 +59,7 @@ } }, { - "ordinal": 4, + "ordinal": 5, "name": "archived_at: Timestamp", "type_info": "Int8", "origin": { @@ -70,8 +81,9 @@ false, false, false, + false, true ] }, - "hash": "9bb792ad62ed64306b9812bb3a049fe742604c0ad3162c9466869a1fe55e7463" + "hash": "f99618110767c8805bdbef2de1ba16f90a0430ee6ba734af80f90b8ab4527e71" } diff --git a/.sqlx/query-a9cffc647c52f9d65cae0c72f929ee49afac7e4d54606e6f084d2892b8a9d517.json b/.sqlx/query-fbd7a89fd61ebc90848f0f0f245710f89503db6f210ada24e3692d86f0bdcdee.json similarity index 84% rename from .sqlx/query-a9cffc647c52f9d65cae0c72f929ee49afac7e4d54606e6f084d2892b8a9d517.json rename to .sqlx/query-fbd7a89fd61ebc90848f0f0f245710f89503db6f210ada24e3692d86f0bdcdee.json index 5baca31..2b7b905 100644 --- a/.sqlx/query-a9cffc647c52f9d65cae0c72f929ee49afac7e4d54606e6f084d2892b8a9d517.json +++ b/.sqlx/query-fbd7a89fd61ebc90848f0f0f245710f89503db6f210ada24e3692d86f0bdcdee.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO class_group (id, creator, name, grade, term, teacher)\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n term AS \"term: TermId\", teacher AS \"teacher: UserId\"", + "query": "INSERT INTO class_group (id, creator, name, grade, year, teacher)\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING id AS \"id: ClassGroupId\", creator AS \"creator: UserId\",\n name AS \"name: ClassName\", grade AS \"grade: ClassGrade\",\n year AS \"year: AcademicYearId\", teacher AS \"teacher: UserId\"", "describe": { "columns": [ { @@ -49,12 +49,12 @@ }, { "ordinal": 4, - "name": "term: TermId", + "name": "year: AcademicYearId", "type_info": "Uuid", "origin": { "Table": { "table": "class_group", - "name": "term" + "name": "year" } } }, @@ -89,5 +89,5 @@ true ] }, - "hash": "a9cffc647c52f9d65cae0c72f929ee49afac7e4d54606e6f084d2892b8a9d517" + "hash": "fbd7a89fd61ebc90848f0f0f245710f89503db6f210ada24e3692d86f0bdcdee" } diff --git a/.sqlx/query-fcfc67fdb7773a04fa9ebee659009b6b63ce8844a9ebdc4a4e8eb51c3b01eed1.json b/.sqlx/query-fcfc67fdb7773a04fa9ebee659009b6b63ce8844a9ebdc4a4e8eb51c3b01eed1.json new file mode 100644 index 0000000..655ea3c --- /dev/null +++ b/.sqlx/query-fcfc67fdb7773a04fa9ebee659009b6b63ce8844a9ebdc4a4e8eb51c3b01eed1.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE class_member SET source_class_group = NULL WHERE source_class_group = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "fcfc67fdb7773a04fa9ebee659009b6b63ce8844a9ebdc4a4e8eb51c3b01eed1" +} diff --git a/.sqlx/query-60dc8924b722dbdeafa1686248b574aca9089ae24b9d87521a134267f4f76caa.json b/.sqlx/query-fe0ff8dba66bad35ba49676eb0c95eb348e85a428efed42e790b1e7b2d465677.json similarity index 75% rename from .sqlx/query-60dc8924b722dbdeafa1686248b574aca9089ae24b9d87521a134267f4f76caa.json rename to .sqlx/query-fe0ff8dba66bad35ba49676eb0c95eb348e85a428efed42e790b1e7b2d465677.json index 0ec1dca..f4cf1f4 100644 --- a/.sqlx/query-60dc8924b722dbdeafa1686248b574aca9089ae24b9d87521a134267f4f76caa.json +++ b/.sqlx/query-fe0ff8dba66bad35ba49676eb0c95eb348e85a428efed42e790b1e7b2d465677.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE homework SET subject = $2, title = $3, description = $4,\n due_at = $5\n WHERE id = $1\n RETURNING id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"", + "query": "UPDATE homework SET subject = $2, title = $3, description = $4,\n due_at = $5\n WHERE id = $1\n RETURNING id AS \"id: HomeworkId\",\n class_course AS \"class_course: ClassCourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"", "describe": { "columns": [ { @@ -16,12 +16,12 @@ }, { "ordinal": 1, - "name": "course: CourseId", + "name": "class_course: ClassCourseId", "type_info": "Uuid", "origin": { "Table": { "table": "homework", - "name": "course" + "name": "class_course" } } }, @@ -119,5 +119,5 @@ false ] }, - "hash": "60dc8924b722dbdeafa1686248b574aca9089ae24b9d87521a134267f4f76caa" + "hash": "fe0ff8dba66bad35ba49676eb0c95eb348e85a428efed42e790b1e7b2d465677" } diff --git a/.sqlx/query-ff85736b704c5450668adf038604d75ae4af5267133d088123eb8aace992cd2b.json b/.sqlx/query-ff85736b704c5450668adf038604d75ae4af5267133d088123eb8aace992cd2b.json new file mode 100644 index 0000000..0437e16 --- /dev/null +++ b/.sqlx/query-ff85736b704c5450668adf038604d75ae4af5267133d088123eb8aace992cd2b.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE course SET class_course_count = class_course_count + 1 WHERE id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "ff85736b704c5450668adf038604d75ae4af5267133d088123eb8aace992cd2b" +} diff --git a/README.md b/README.md index 0d4b0be..423d512 100644 --- a/README.md +++ b/README.md @@ -14,36 +14,43 @@ per-file size cap is school policy in settings (`max_file_bytes`, default body into the recipient's inbox, each side filing its own copy through archive/trash with a read flag the sender sees as a receipt (the only place a `parent` writes). Attendance is event + attendees: create an event with an **audience** -(the whole school, one role, a course's enrollment, a **class section's** -roster, or a **registration** signup list — omit for school-wide), then teachers mark the expected attendees +(the whole school, one role, a course **instance's** enrollment, a **class +section's** roster, or a **registration** signup list — omit for school-wide), then teachers mark the expected attendees present / absent / late / excused (students never self-mark), and a **roster report** shows who was expected and who missed. Registration lists fill seat by seat: teachers register students (never the other way round), staff register only themselves, an optional `capacity` caps the seats, and the list closes the moment the event starts (or, for an event with only an end time — a pure signup deadline — the moment that end passes). Every event stays visible to everyone — -the audience is a roster, not a wall. Marks are course-shaped -(Google Classroom style): a teacher creates a course — kind **`course`** (a +the audience is a roster, not a wall. Marks are **instance-shaped**. A **course** in `/courses` is a +school-wide catalog row — kind **`course`** (a regular taught course), **`study`** (a supervised study session — *etüt*), or -**`club`** (a student club — *kulüp*; same behavior, different label), -optionally capped by a `capacity` that refuses new enrolls once the roster is -full — lays out its **subjects** (curriculum topics — +**`club`** (a student club — *kulüp*; same behavior, different label) — and it +owns its **subjects** (curriculum topics — every exam question must be tagged with one of its course's subjects, so -results can later be read per topic), enrolls students, adds -exams inside it, and grades — enrolling, sitting exams, roll call, and marks are -all student-only, staff never take part. A course is run by whoever created it -plus any teachers a **manager assigns** to it (`POST /courses/{id}/teachers`): -an assigned teacher manages everything inside the course — exams, sessions, -subjects, roster, grading — but can't delete it or change who else teaches it, -and a demotion below `teacher` sweeps their assignments away. Students are +results can later be read per topic). Nobody is enrolled in a catalog course: +teaching happens in the **instance** — one class section × one course, created +when the course is attached to the section (`POST /classes/{id}/instances`) and +living at `/instances/{id}` with its own `ders_saati` (weekly lesson hours, its +weight in the karne average), `counts_toward_karne` flag, teachers, roster, +exams, lesson sessions and homework. Two sections that attach Matematik get +**two** instances and share nothing: adding a student to 5-A enrolls them in +5-A's Matematik only, and an exam written on 5-A's Matematik is invisible to +5-B. The catalog row is office-owned (creator or manager+; clubs and etüt are +the exception — see "Courses (catalog)"), while an instance is run by the +teachers a **manager assigns** to it (`POST /instances/{id}/teachers`) plus the +section's homeroom teacher: an assigned teacher manages everything inside the +instance — exams, sessions, subjects, roster, grading — and a demotion below +`teacher` sweeps their assignments away. Students are grouped into a **class section** (*şube* — 9-A, 10-B) when a school teaches -that way: it is bulk enrollment, not a second kind of membership — attaching a -course to it enrolls the whole roster, adding a member enrolls them into every -course already attached, and what lands are ordinary enrollment rows tagged -with the section that pumped them (untagged = placed by hand, and hand-placed -rows are never adopted and never swept). A course without room for everyone -refuses the whole operation, naming it (see "Class sections (şube)"). A section -may also +that way; the şube belongs to an **academic year** (`/academic-years`), and a +term is a grading slice inside that year. Membership is a live stint: leaving +(`DELETE /classes/{id}/members/{user}`) stamps `left_at` and gives the seat +back, and re-adding inserts a fresh row — the section's history is never +erased. Attaching a course to a section enrolls the whole roster, adding a +member enrolls them into every instance already attached, and what lands are +ordinary enrollment rows tagged with the section that pumped them (untagged = +placed by hand; a şube sweep never adopts or removes those). A section may also name a **homeroom teacher** (*sınıf öğretmeni*, `teacher_id` — any teacher+ account, cleared automatically when that account is demoted), and while every other class read is teacher+, a student reads their own section at @@ -58,10 +65,15 @@ label (matched exactly, `?grade=` alone the ones carrying none), and `GET /classes/blueprints/{grade}/status` names, per section, the template courses it is still missing — which is how a partial pump is chased down after the response that reported it is gone. Students read a -per-course weighted average and +per-instance weighted average and an overall average from their mark report — each exam weighted by its **kind** -(midterms can count double, orals once: weights are set per kind in settings, -not per exam). Exams run **sync** (one +(a yazılı can count double, a sözlü once: weights are set per kind in settings, +not per exam) — and `GET /marks/karne` rolls the whole year up: per-instance +averages mapped to the school's grade bands, a year-to-date average weighting +each instance by its `ders_saati`, and a `gecti`/`kaldi` verdict read off the +band labelled `"2"`. Once a term is archived the karne serves the **frozen +snapshot** taken at archive time, so a past report never changes under a staff +edit. Exams run **sync** (one fixed window), **async** (start anytime inside the window, with a personal time budget), or **open** (sit anytime, optionally timed per attempt); students *sit* them via attempts — retakes metered by a per-exam limit @@ -96,7 +108,8 @@ backend records the focus stints — every one of them, though only stints of at least 5 minutes and at most 16 a UTC day *count* towards the badges — and teachers can read any student's log), and every user has an -**attendance report** (event + per-course lesson tallies with rates). +**attendance report** (event + per-instance lesson tallies with rates, plus +the per-dönem devamsızlık day counts). A school-wide **question pool** runs on moderation: a student asks a question (optionally attaching one photo of the problem — raster only, same `max_file_bytes` cap), a teacher+ **approves** it into the pool (or deletes @@ -704,7 +717,7 @@ drift from it**, which is enforced rather than asked for: and fails unless each one is either referenced by `src/web/limits.rs` or listed as a deliberate exclusion *with a reason*. A new constant breaks the suite until someone decides, consciously, whether clients need it. -- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 204 published +- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 219 published bounds back out of the emitted JSON, and asserts each equals its constant. This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal only** — a `const` there does not compile — so the annotations are @@ -1036,30 +1049,36 @@ bought answers `403 {"error": "module disabled", …}` instead — see "Modules" A course is a regular taught course (kind `course`, the default), an *etüt* (kind `study` — a supervised study session), or a *kulüp* (kind `club` — a student -club). The three kinds behave identically everywhere — enrollment, exams, -sessions, marks — the kind is a label the UI renders differently, settable at -creation and editable later. A course may also carry a `capacity`: once the -roster reaches it, new enrolls are refused with `409` (members already on the -roster are unaffected, even if the cap is later lowered below them; `null` -lifts the cap). - -**Who runs a course.** Its **creator** owns it for good — only they (or a -manager+) may delete it. On top of that, a manager can **assign** any -`teacher`+ to the course with `POST /courses/{id}/teachers` (`{user_id}`, -idempotent) and drop them again with `DELETE /courses/{id}/teachers/{user}`. -An assigned teacher gets full **course-management rights** — edit the course, -enroll and unenroll students, add exams, sessions and subjects, grade, take -roll call — but *not* the two owner powers: they cannot delete the course, and -they cannot change who else teaches it. Staffing is deliberately the office's -call, so a course's own creator cannot hand rights to their peers; only -manager+ may touch the list. Every course response carries its `teachers` -array alongside `creator`, and a user demoted below `teacher` is swept off -every course they were assigned to (the mirror of promotion dropping -enrollments). That sweep runs once, so an assignment landing in the same -instant would survive it: the assign call therefore re-reads the account's live -role **after** its write and answers `409` — dropping the assignment again — if -it has since fallen below `teacher`. Same guard, same wording, as a class's -homeroom teacher. +club). The three kinds behave identically everywhere, and the kind is a label +the UI renders differently, settable at creation and editable later. A course +is a **catalog row**: it owns its **subjects** (curriculum topics) and carries +counters — `class_course_count`, `course_membership_count` — never a roster of +its own. There is no `capacity` anywhere: no route refuses an enroll for room, +and a counter is a count, not a cap. Teaching happens in the **instance** +(`/instances`): one class × course row, minted by attaching the course to a +section, carrying its own teachers, hours, roster, exams, sessions and homework. + +A catalog course is **office-owned**: only its **creator** (or a manager+) may +edit or delete it. The two kinds a section does not teach are the exception — +a *kulüp* or an *etüt* is joined directly, with `POST /courses/{id}/members` +(the school-scoped membership a student may join and leave on their own). A +`course`-kind row refuses that join (`409`): a ders is taken through a şube's +instance, never directly. + +**Who runs an instance.** Its **teachers** — each a `teacher`+ account a +manager assigned with `POST /instances/{id}/teachers` (`{user_id}`, idempotent; +drop them with `DELETE /instances/{id}/teachers/{user}`) — plus the **homeroom +teacher of its class**. Instance teachers manage everything inside it: its +`ders_saati` and karne weight, its roster, its exams, sessions and homework, +grading and roll call. Staffing is deliberately the office's call; a manager+ +caller may always do the same, and nobody else may touch the teacher list. +Every instance response carries its `teachers` array. A user demoted below +`teacher` is swept off every instance they were assigned to (the mirror of +promotion dropping enrollments) and off every homeroom they held. That sweep +runs once, so an assignment landing in the same instant would survive it: the +assign call therefore re-reads the account's live role **after** its write and +answers `409` — dropping the assignment again — if it has since fallen below +`teacher`. Same guard, same wording, as a class's homeroom teacher. Ownership is **not** a standing grant. `creator` is a historical column that no demotion sweeps (unlike the assignment list above), so every course-management @@ -1070,23 +1089,28 @@ manager+, who can hand it to someone else. Nothing below is a right a caller holds while under `teacher`. The column is deliberately **not** swept the way the assignment list is: it answers "who made this", which stays true after a demotion — it is the *grant* that is role-gated, not the history. The same -floor applies to the catalogs: a demoted creator's own course drops out of -their `/courses`, `/exams` and `/homework` lists, and comes back only if they -are enrolled in it, as any student would be. A session's `teacher` behaves +floor applies to the catalogs: a demoted creator's own catalog row drops out +of their `/courses` list, and comes back only if they are enrolled in one of +its instances, as any student would be. A session's `teacher` behaves identically — teaching a session grants no roll call, and no view of it, once the account is below `teacher`. -Course data is walled per course. A course, its exams, its sessions, and its -subjects are -**visible** only to its enrolled users, its creator, its assigned teachers, -and manager+ — a student -sees just the classes they were added to, and the `/courses` / `/exams` -catalogs are filtered accordingly. Teacher-level reads *inside* a course +Teaching data is walled **per instance**. An instance, its exams, its sessions, +its homework and its rosters are +**visible** only to its enrolled students, its assigned teachers, its class's +homeroom teacher, and manager+ — a student +sees just the instances their sections carry or they joined, and `/exams`, +`/homework` and `/instances/me` are filtered accordingly. The catalog row, its +subjects and its membership list are readable by that same audience (a student +enrolled in any of its instances, a teacher assigned to one, a member of the +catalog row itself, its creator, manager+). Teacher-level reads *inside* an +instance (roster, results, statistics, the question list, answer sheets, the live -monitor) additionally need **course-management rights** (creator, an assigned -teacher, or manager+ — each of them still `teacher`+ today): -one teacher cannot look into another teacher's course, and the per-user -marks/attendance reports narrow to the courses the caller manages. +monitor) additionally need **instance-management rights** (manager+, one of its +assigned teachers, or its class's homeroom teacher — each of them still +`teacher`+ today): +one teacher cannot look into another teacher's instance, and the per-user +marks/attendance reports narrow to the instances the caller manages. **Paging.** Every list endpoint below (the rows tagged **· paged**) accepts `?limit=&offset=` and returns a `{ items, total, limit, offset }` envelope @@ -1119,6 +1143,12 @@ window filtering, before paging; negative values are a `400` naming the field. | Method | Path | Auth | Description | |--------|------------------------------------------------------------------|---------|-------------| | GET | `/` | no | Same as `/health` | +| GET | `/academic-years` | teacher | List every academic year, newest first. Requires teacher+. Paged via `?limit=&offset=` (omit `limit` for the full list); returns a `{items, total, limit, offset}` envelope. | +| POST | `/academic-years` | manager | Create an academic year. Requires manager+. Past dates are allowed — years are calendar structure, not schedules. `grade_promotions` is the sınıf-geçme policy the rollover applies. | +| GET | `/academic-years/{id}` | teacher | Fetch a single academic year by id. Requires teacher+. | +| PATCH | `/academic-years/{id}` | manager | Update an academic year. Requires manager+. Omitted fields keep their value; `grade_promotions` is replaced as a whole when sent. An archived year is read-only. | +| DELETE | `/academic-years/{id}` | manager | Delete an academic year. Requires manager+. Refused with a 409 while any şube or dönem still links it — move or delete them first. An archived year must be re-opened (`PATCH` is not enough: there is no unarchive here, so the row is only deletable while open) like every other past-structure write. | +| POST | `/academic-years/{id}/rollover` | manager | Carry another year's şubeler into this one. Requires manager+. Each şube of `from_year` whose grade the target year promotes is planted afresh here — same name, mapped grade, and copies of its instances (`ders_saati`, karne policy, teachers) and of every live member, who are also enrolled into the new instances. A grade with no promotion entry stays behind: that is graduation, and `graduated` names it. The target must be empty (a second rollover into it is a 409, which is what makes the command idempotent), open, and different from the source. | | GET | `/ai/certificate` | no | The AI bridge's certificate (PEM + SHA-256 fingerprint) for a service to pin; `404` when the bridge is off. | | GET | `/api-docs/openapi.json` | no | Raw OpenAPI 3 spec | | GET | `/appointments` | student | List bookings, newest first. Students and parents see the ones they requested; teacher+ see the ones aimed at their own slots — their request inbox. Managers and admins read their own inbox too (they may still decide any booking by id). Paged via `?limit=&offset=` (omit `limit` for every booking); returns a `{items, total, limit, offset}` envelope. | @@ -1133,8 +1163,8 @@ window filtering, before paging; negative values are a `400` naming the field. | PATCH | `/appointments/{id}/reschedule` | teacher | Counter-propose another time for a booking, on the same row (the reason and the history stay in one place). Requires teacher+ and ownership of the slot (or manager/admin). | | PATCH | `/appointments/{id}/reschedule/accept` | student | Accept the teacher's counter-proposal. The requester's call alone — it is their commitment. Accepting *is* approval at the proposed time, so the double-booking guard runs again for both sides (`409` if the moved time now collides with something else, or has already started — agreeing to a window that began would mint a meeting nobody can cancel). | | PATCH | `/appointments/{id}/reschedule/decline` | student | Refuse the teacher's counter-proposal. The requester's call alone, and it **cancels the booking**: the proposal replaced the time that was asked for, so there is nothing left to fall back to — book another slot instead. The slot frees up, and the original request stays readable as `cancelled` with the refused proposal still on it. Declining is a cancel, so it answers to the same deadline: `409` once the meeting's effective window has started. | -| GET | `/attendance/me` | student | The current user's attendance report: event tallies, lesson roll-call tallies, and a per-course breakdown with attendance rates. | -| GET | `/attendance/{user}` | teacher | Any user's attendance report. Requires teacher+, or a parent tied to the target student. Managers, admins, and parents see every course; a teacher sees the event tallies plus only the roll-call blocks of the target's courses they manage. | +| GET | `/attendance/me` | student | The current user's attendance report: event tallies, lesson roll-call tallies, a per-instance breakdown with attendance rates, and the per-dönem devamsızlık. | +| GET | `/attendance/{user}` | teacher | Any user's attendance report. Requires teacher+, or a parent tied to the target student. Managers, admins, and parents see every instance; a teacher sees the event tallies plus only the roll-call blocks — and the devamsızlık days — of the instances they run. | | POST | `/auth/login` | no | Log in with username + password — no school. Sets a `session` cookie on success: exactly one active membership enters that school right away (`.` and the full [`UserResponse`], unchanged for single-school clients), several answer a [`SchoolChoiceResponse`] with a `person.` cookie that `POST /auth/school` binds. | | POST | `/auth/logout` | no | Log out: revoke the current session (if any) and clear the cookie. Idempotent — no session required; answers `204` either way. | | GET | `/auth/me` | student | Return the currently authenticated user. | @@ -1175,7 +1205,7 @@ window filtering, before paging; negative values are a `400` naming the field. | GET | `/chatbot/threads/{id}/messages/{mid}` | student | Poll one turn. The non-SSE fallback for `/stream`, reading the same row — including the projection that presents a long-stale `pending` as `failed`, so the two can never disagree about a turn's state. | | GET | `/chatbot/threads/{id}/messages/{mid}/stream` | student | Watch one turn as Server-Sent Events: `delta` chunks of the answer, then a single `done` carrying the finished message, or one `error`. The stream closes after `done`/`error` — one stream per turn, not per thread. | | GET | `/classes` | teacher | List every class, newest first. Requires teacher+. `?grade=` narrows to one grade label, matched exactly as written — the label a blueprint is keyed by, so this is the read that shows which sections a `POST /classes/blueprints` pump covered (and `?grade=` on its own lists the sections with no grade at all). An unknown label is an empty page, not a `404`. Paged via `?limit=&offset=` (omit `limit` for the full list); returns a `{items, total, limit, offset}` envelope whose `total` counts every class under the same filter, not just this page. | -| POST | `/classes` | manager | Create a class. Requires manager+ — a class is school structure, not a teacher's own room. `grade` is a free-text label for the year ("9", "10-A"), `term_id` links the school calendar, `teacher_id` names the homeroom teacher (sınıf öğretmeni, a teacher+ account); all optional. | +| POST | `/classes` | manager | Create a class. Requires manager+ — a class is school structure, not a teacher's own room. `grade` is a free-text label for the year ("9", "10-A"), `year` links the academic year (which is what binds the şube to a karne and to the rollover), `teacher_id` names the homeroom teacher (sınıf öğretmeni, a teacher+ account); all optional. | | GET | `/classes/blueprints` | manager | List every grade blueprint, by grade label. Requires manager+. Paged via `?limit=&offset=` (omit `limit` for all of them). | | POST | `/classes/blueprints` | manager | Create a grade's course blueprint and stock every class section already at that grade with it. Requires manager+. | | GET | `/classes/blueprints/{grade}` | manager | Fetch one grade's blueprint. Requires manager+. | @@ -1185,17 +1215,17 @@ window filtering, before paging; negative values are a `400` naming the field. | GET | `/classes/me` | student | The classes the caller is a member of, newest membership first. Any authenticated role — this is the one class read a student (or a parent, for themselves) can make, since every other `/classes` route is teacher+. Paged via `?limit=&offset=` (omit `limit` for all of them); returns a `{items, total, limit, offset}` envelope. Staff, who are never class members, simply get an empty page. | | GET | `/classes/user/{user}` | teacher | Another user's classes. Requires teacher+, or a parent tied to the target student — the same bar the per-student reports hold, and the same 403 for everyone else (a student reads their own at `GET /classes/me`). | | GET | `/classes/{id}` | teacher | Fetch a single class by id. Requires teacher+. | -| PATCH | `/classes/{id}` | manager | Update a class. Requires manager+. Omitted fields keep their value; `grade`, `term_id` and `teacher_id` are nullable, so an explicit `null` clears them. | +| PATCH | `/classes/{id}` | manager | Update a class. Requires manager+. Omitted fields keep their value; `grade`, `year` and `teacher_id` are nullable, so an explicit `null` clears them. | | DELETE | `/classes/{id}` | manager | Delete a class. Requires manager+. Refused with a 409 while it still holds students or courses — nothing cascades, because dropping the class silently would leave the enrollments it pumped with nothing left to sweep them. | | POST | `/classes/{id}/blueprint` | manager | Stock one class section from its grade's blueprint. Requires manager+ — this writes the roster of every course in the template, which is the office's call, not one course owner's. | -| GET | `/classes/{id}/courses` | teacher | List the courses a class is attached to, newest first, paged via `?limit=&offset=` (omit `limit` for all of them). Requires teacher+. Returns a `{items, total, limit, offset}` envelope. | -| POST | `/classes/{id}/courses` | teacher | Attach a course to a class. Requires teacher+ and management rights **on that course** — attaching writes its roster, so it takes exactly the right enrolling into it does. The class's whole roster is enrolled in one go: a course that cannot hold all of them takes none (409), and students already enrolled by hand keep their own rows. Attaching the same course twice is a 409. | -| DELETE | `/classes/{id}/courses/{course}` | teacher | Detach a course from a class. Requires teacher+ and management rights on that course, like attaching. The enrollments the class pumped into it are swept — except rows another attached class still claims (re-tagged to it) and rows placed by hand (left standing). A course that was not attached is a 404 — but a course row that is *gone* is not: the link a deleted course left behind detaches (the rights check has nothing left to read, and no roster left to protect), or the class holding it could never be deleted. | +| GET | `/classes/{id}/instances` | teacher | List the instances a class carries — each a catalog course as this section teaches it, with its hours, karne policy and teachers — newest first, paged via `?limit=&offset=` (omit `limit` for all of them). Requires teacher+. Returns a `{items, total, limit, offset}` envelope. `POST /instances/{id}` edits one; this is the read that names them. | +| POST | `/classes/{id}/instances` | teacher | Attach a course to a class: this is what **mints the instance** — the class×course row every exam, session, lesson and roster under this class's course now keys on. Requires teacher+ and catalog rights on that course (its creator, or a manager/admin): attaching writes that course's roster for this section, and the weekly hours and karne policy the instance starts with. The class's whole roster is enrolled in one go, and students already enrolled by hand keep their own rows. Attaching the same course twice is a 409. | +| DELETE | `/classes/{id}/instances/{instance}` | teacher | Detach an instance from a class: the instance and everything the class taught under it — exams (with results, questions and images), homework (with submissions and grades), sessions and roll call, the roster it pumped and its teacher links — are swept, and the uploaded files those rows named are unlinked from disk. Requires teacher+ and catalog rights on the course the instance teaches (its creator, or a manager/admin): this is the inverse of attaching. | | GET | `/classes/{id}/members` | teacher | List a class's roster, newest first, paged via `?limit=&offset=` (omit `limit` for the whole roster). Requires teacher+. Returns a `{items, total, limit, offset}` envelope. | -| POST | `/classes/{id}/members` | manager | Put a student in a class. Requires manager+. They are enrolled into every course the class already carries, in one go: a course with no free seat refuses the whole join with a 409 naming it, and a student already enrolled by hand keeps the row they have (no second seat, and it survives their removal from the class). Adding the same student twice is a 409. | -| DELETE | `/classes/{id}/members/{user}` | manager | Take a student out of a class. Requires manager+. The enrollments the class pumped for them are swept with it — except rows another attached class still claims (re-tagged to it) and rows placed by hand (left standing). A student who was not in the class is a 404. | -| GET | `/course-notes` | student | List a course's notes, newest first. Visible to whoever can view the course (its enrolled users, creator, assigned teachers, and managers/admins). Paged via `?limit=&offset=`. | -| POST | `/course-notes` | teacher | Create a note on a course. Requires teacher+ and management rights over the course (its creator, an assigned teacher, or a manager/admin). | +| POST | `/classes/{id}/members` | manager | Put a student in a class. Requires manager+. They are enrolled into every instance the class already carries, in one go, and a student already enrolled by hand keeps the row they have (and it survives their removal from the class). Adding the same student twice is a 409; a student who *left* is added afresh — the roster is a history, and the partial index only holds one live stint per pair. | +| DELETE | `/classes/{id}/members/{user}` | manager | Take a student out of a class. Requires manager+. The enrollments the class pumped for them are swept with it — except rows placed by hand, which are left standing. There is no heir to hand a swept row to: a second section teaching the same course holds its **own** instance, so its roster is its own row and this one is released. A student who was not in the class is a 404. | +| GET | `/course-notes` | student | List a course's notes, newest first. Visible to whoever can view the course (its creator, a manager/admin, or anyone the course reaches). Paged via `?limit=&offset=`. | +| POST | `/course-notes` | teacher | Create a note on a course. Requires teacher+ and catalog rights over the course (its creator or a manager/admin). | | GET | `/course-notes/{id}` | student | Fetch a single course note by id. Visible to whoever can view its course. | | PATCH | `/course-notes/{id}` | teacher | Update a course note's title and/or content. Omitted fields keep their value. Requires teacher+ and management rights over the course. | | DELETE | `/course-notes/{id}` | teacher | Delete a course note, along with its files. Requires teacher+ and management rights over the course. | @@ -1205,25 +1235,17 @@ window filtering, before paging; negative values are a `400` naming the field. | DELETE | `/course-notes/{id}/files/{file_id}` | teacher | Delete a course note file (row first, then its blob). Requires teacher+ and management rights over the course. | | GET | `/course-notes/{id}/rag` | student | List a course note's AI outputs, newest first. Visible to whoever can view the course. Paged via `?limit=&offset=`. | | DELETE | `/course-notes/{id}/rag/{output_id}` | teacher | Delete one stored AI output. Requires teacher+ and management rights over the course. Dropping an output does not stop the next note or file change from regenerating one. | -| GET | `/courses` | student | List the courses visible to the caller: every course for manager+, otherwise the courses they created plus the ones they're enrolled in. Paged via `?limit=&offset=` (omit `limit` for the full list); returns a `{items, total, limit, offset}` envelope. | -| POST | `/courses` | teacher | Create a course owned by the current user. Requires the `teacher` role or higher. `kind` picks the flavor — `course` (a regular class, the default), `study` (a supervised study session — etüt), or `club` (a student club — kulüp); all behave identically. `capacity` caps the roster at enroll time (omit for unlimited). | -| GET | `/courses/me` | student | The courses the current user is enrolled in, paged via `?limit=&offset=` (omit `limit` for all of them); returns a `{items, total, limit, offset}` envelope. | -| GET | `/courses/{id}` | student | Fetch a single course by id. Visible to its enrolled users, and to its creator, its assigned teachers and managers/admins while those accounts are still `teacher`+ — a demoted creator sees it only if they are enrolled, like any other student (see [`can_manage_course`]). | -| PATCH | `/courses/{id}` | teacher | Update a course. Requires teacher+ and course management rights — its creator, a teacher assigned to it, or a manager/admin. Omitted fields keep their value. | -| DELETE | `/courses/{id}` | teacher | Delete a course. Requires teacher+; only its creator or a manager/admin may delete it — an assigned teacher runs the course but does not own it. Refused with a 409 while anyone is still enrolled — empty the roster first, so a course that carries students is never dropped by accident. Once empty, it cascades the course's exams (with their results, questions, answers, and question images), its homework (with submissions, submission files, and grades), its sessions and roll call, and its subjects. It also detaches the course from every class that carried it and strikes its id out of every class blueprint that named it — a template holding a course nothing can resolve is a stocking run that skips it and a `PATCH` that refuses the very list the template already holds. | -| GET | `/courses/{id}/enrollments` | teacher | List a course's roster, paged via `?limit=&offset=` (omit `limit` for the whole roster). Requires teacher+ and course management rights — students see their own courses via `GET /courses/me`. Returns a `{items, total, limit, offset}` envelope. | -| POST | `/courses/{id}/enrollments` | teacher | Enroll a user into a course (idempotent upsert). Requires teacher+ and course management rights. Only students can be enrolled — enrollment is student membership, and it gates sitting exams, being graded, and the class roster, all student-only. A course with a `capacity` refuses new members once the roster is full (someone already enrolled is returned as-is). Enrolling a student a class pumped in takes the row *off* that class — `source` comes back `null` — so a later class sweep can no longer undo a placement made by hand, the mirror of a manual unenroll winning permanently. | -| DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll a user from a course. Requires teacher+ and course management rights. Existing exam results are kept (they disappear from the user's marks report until re-enrolled). | -| GET | `/courses/{id}/exams` | student | List a course's exams, paged via `?limit=&offset=` (omit `limit` for all of them). Visible to the course's enrolled users, its creator, and managers/admins — but drafts appear only to the course's managers. Returns a `{items, total, limit, offset}` envelope. | -| POST | `/courses/{id}/exams` | teacher | Create an exam inside a course. Requires teacher+ and course management rights; the exam's marks count into the course average with its kind's weight (`GET /settings`). Omit `mode` for an offline-graded exam nobody can sit; `sync`/`async` take a window (async also `duration_ms`), `open` is sittable anytime with an optional per-attempt `duration_ms`. `max_attempts` (default 1, `0` = unlimited) meters retakes and `allow_rejoin` (default `true`) is the exam-room door — both stay editable while the exam runs. Send `draft: true` to keep the exam private while it's still being written: only the course's managers see it, and sitting and grading are blocked until it's published (`PATCH` `draft: false`). | -| GET | `/courses/{id}/homework` | student | List a course's homework, newest first, paged via `?limit=&offset=` (omit `limit` for all of it). Visible to the course's enrolled users, its creator, its assigned teachers, and managers/admins — but a student sees only the homework they are assigned (whole-course ones plus subsets that name them, each with its `assigned` narrowed to themselves). Returns a `{items, total, limit, offset}` envelope. | -| POST | `/courses/{id}/homework` | teacher | Assign a homework inside a course. Requires teacher+ and course management rights. The homework is tagged with one of the course's subjects and given a future `due_at`; `assigned` optionally narrows it to a subset of the enrolled students (omit or empty = the whole course). | -| GET | `/courses/{id}/sessions` | student | List a course's lesson sessions, most recent first, paged via `?limit=&offset=` (omit `limit` for all of them). Visible to the course's enrolled users, its creator, and managers/admins. Returns a `{items, total, limit, offset}` envelope. | -| POST | `/courses/{id}/sessions` | teacher | Create a lesson session inside a course. Requires teacher+ and course management rights. The session's teacher defaults to the caller. | -| GET | `/courses/{id}/subjects` | student | List a course's subjects in creation order, paged via `?limit=&offset=` (omit `limit` for all of them). Visible to the course's enrolled users, its creator, and managers/admins. Returns a `{items, total, limit, offset}` envelope. | -| POST | `/courses/{id}/subjects` | teacher | Create a subject inside a course. Requires teacher+ and course management rights. Subjects are the course's curriculum topics — every exam question must be tagged with one of its course's subjects. | -| POST | `/courses/{id}/teachers` | manager | Assign a teacher to a course (idempotent). Manager+ only — staffing is the office's call, so a course's own creator cannot hand management rights to their peers. The assignee must already hold the `teacher` role or higher; assigning gives them full management of the course (exams, sessions, subjects, roster, grading) but not the power to delete it or change this list. The course's assigned teachers are returned on every course response. | -| DELETE | `/courses/{id}/teachers/{user}` | manager | Unassign a teacher from a course. Manager+ only. The course itself, its exams, sessions, and roster are untouched — the teacher just loses their management rights over it. A user who was never assigned is a 404. | +| GET | `/courses` | student | List the catalog courses visible to the caller: every course for manager+, otherwise the courses they teach somewhere plus the ones they're enrolled in. Paged via `?limit=&offset=` (omit `limit` for the full list); returns a `{items, total, limit, offset}` envelope. | +| POST | `/courses` | teacher | Create a catalog course owned by the current user. Requires the `teacher` role or higher. `kind` picks the flavor — `course` (a regular class, the default), `study` (a supervised study session — etüt), or `club` (a student club — kulüp). A catalog row teaches nobody by itself: a şube attaches it into an instance (`POST /classes/{id}/instances`), and a `study`/`club` is joined school-wide (`POST /courses/{id}/members`). | +| GET | `/courses/me` | student | The catalog courses the current user is reached by, paged via `?limit=&offset=` (omit `limit` for all of them); returns a `{items, total, limit, offset}` envelope. | +| GET | `/courses/{id}` | student | Fetch a single catalog course by id. Visible to the people it reaches — students enrolled in any of its instances, members of the course itself — and to its creator and managers/admins while those accounts are still `teacher`+. | +| PATCH | `/courses/{id}` | teacher | Update a catalog course. Requires teacher+ and catalog rights — its creator, or a manager/admin. Omitted fields keep their value. | +| DELETE | `/courses/{id}` | teacher | Delete a catalog course. Requires teacher+; only its creator or a manager/admin may delete it. Refused with a 409 while the course is still taught anywhere — detach it from every şube (`DELETE /classes/{id}/instances/{instance}`) and remove its individual members first, so a course that carries teaching is never dropped by accident. Once free, it cascades the instances' exams (with their results, questions, answers, and question images), homework (with submissions, submission files, and grades), sessions and roll call, its individual memberships, its subjects, and the teacher links. It also strikes its id out of every class blueprint that named it — a template holding a course nothing can resolve is a stocking run that skips it and a `PATCH` that refuses the very list the template already holds. | +| GET | `/courses/{id}/members` | teacher | List a club/etüt's members, newest first, paged via `?limit=&offset=` (omit `limit` for the whole list). Requires teacher+ and catalog rights. Returns a `{items, total, limit, offset}` envelope. An instance's roster is `GET /instances/{id}/enrollments`. | +| POST | `/courses/{id}/members` | teacher | Add a user to a club or etüt — the **school-scoped** membership tier. Requires teacher+ and catalog rights (its creator, or a manager/admin). Only students can be added, and only to a `study` (etüt) or `club` (kulüp): a regular ders (`kind` `course`) has no school-wide roster — its students come from the şubeler that teach it, and that join is `POST /instances/{id}/enrollments` (400 here). Idempotent: a pair that already holds a membership is returned as-is. | +| DELETE | `/courses/{id}/members/{user}` | teacher | Remove a user from a club or etüt. Requires teacher+ and catalog rights. Existing exam results and badges are untouched — the membership is a door, not a record of what happened inside. A pair holding no membership is a 404. | +| GET | `/courses/{id}/subjects` | student | List a course's subjects in creation order, paged via `?limit=&offset=` (omit `limit` for all of them). Visible to its creator, to managers/admins, and to anyone the course reaches (a student enrolled in one of its instances, or a member of it). Returns a `{items, total, limit, offset}` envelope. | +| POST | `/courses/{id}/subjects` | teacher | Create a subject inside a course. Requires teacher+ and catalog rights (its creator, or a manager/admin). Subjects are the curriculum topics of the *catalog* row — every exam of every instance teaching it tags its questions with one of them. | | GET | `/events` | student | List all events, newest first. Paged via `?limit=&offset=` (omit `limit` for every event); returns a `{items, total, limit, offset}` envelope. | | POST | `/events` | teacher | Create an event owned by the current user. Requires the `teacher` role or higher. `audience` targets it at a role, a course's enrollment, a class section's roster, or a registration list (filled via `POST /events/{id}/register`); omitted it is school-wide. Everyone still sees every event — the audience is the expected-attendee roster, not a visibility wall. | | GET | `/events/{id}` | student | Fetch a single event by id. | @@ -1235,67 +1257,83 @@ window filtering, before paging; negative values are a `400` naming the field. | POST | `/events/{id}/register` | teacher | Put a user on a registration-audience event's signup list. Requires teacher+. `user_id` must name a student — students are placed by staff and never register themselves; omit it to take a seat yourself (staff self-serve, so registering another teacher/manager is refused). Registering the same person twice is a no-op returning the existing seat. The list closes when the event starts (or its ends_at-only deadline passes) and refuses to grow past `capacity`. | | DELETE | `/events/{id}/register/{user}` | teacher | Take a user off the signup list — the register rules mirrored: teacher+, students' seats or your own (another *staff* member's seat only if their account no longer exists), and only while the list is open (the event hasn't started or, ends_at-only, passed). A seat held by a `parent` is freeable by any teacher+ as well: no route lets that account free it itself, so a stranded seat needs a door. Attendance already marked stays recorded. | | GET | `/events/{id}/roster` | teacher | The event's expected-attendee roster joined with its attendance marks — the who-came/who-missed report. Resolved live from the audience (today's role holders, current enrollment, the current class roster, the current signup list), so it always reflects the present roster; attendance rows for people no longer in the audience are omitted here (they remain in `GET /events/{id}/attendance`). Requires teacher+. Paged via `?limit=&offset=` (omit `limit` for the whole roster). | -| GET | `/exams` | student | List the exams visible to the caller: every exam for manager+, otherwise the exams of the courses they created or are enrolled in — minus other people's drafts (a draft shows only to its course's managers). Paged via `?limit=&offset=` (omit `limit` for the full list); returns a `{items, total, limit, offset}` envelope. | -| GET | `/exams/{id}` | student | Fetch a single exam by id. Visible to its course's enrolled users, the course creator, and managers/admins — except drafts, which only the course's managers see (everyone else gets a `404`, as if the exam doesn't exist yet — because it doesn't, officially). | -| PATCH | `/exams/{id}` | teacher | Update an exam. Requires teacher+ and management rights over the exam's course (its creator, or manager/admin). Omitted fields keep their value; an explicit `null` clears a schedule field; the course itself is not updatable. The schedule must stay consistent as a whole (see the create endpoint), and `mode` is frozen once anyone has started an attempt — times, duration, `max_attempts`, and `allow_rejoin` stay editable so a running exam can be extended, granted retakes, or have its rejoin door opened live. `draft: false` publishes a draft; `draft: true` re-hides an exam, but only while it has no attempts and no results (`409` otherwise) — students never lose sight of an exam they've already sat or been graded on. | -| DELETE | `/exams/{id}` | teacher | Delete an exam. Requires teacher+ and management rights over the exam's course (its creator, or manager/admin). Cascades the exam's results, attempts, questions, answers, and question + answer images (blobs included). | +| GET | `/exams` | student | List the exams visible to the caller: every exam for manager+, otherwise the exams of the instances they teach or are enrolled in — minus other people's drafts (a draft shows only to its instance's managers). Paged via `?limit=&offset=` (omit `limit` for the full list); returns a `{items, total, limit, offset}` envelope. | +| GET | `/exams/{id}` | student | Fetch a single exam by id. Visible to its instance's enrolled students, its teachers (or its class's homeroom teacher), and managers/admins — except drafts, which only the instance's managers see (everyone else gets a `404`, as if the exam doesn't exist yet — because it doesn't, officially). | +| PATCH | `/exams/{id}` | teacher | Update an exam. Requires teacher+ and management rights over the exam's instance (an assigned teacher, its class's homeroom teacher, or a manager/admin). Omitted fields keep their value; an explicit `null` clears a schedule field; the instance an exam hangs off is not updatable here. The schedule must stay consistent as a whole (see the create endpoint), and `mode` is frozen once anyone has started an attempt — times, duration, `max_attempts`, and `allow_rejoin` stay editable so a running exam can be extended, granted retakes, or have its rejoin door opened live. `draft: false` publishes a draft; `draft: true` re-hides an exam, but only while it has no attempts and no results (`409` otherwise) — students never lose sight of an exam they've already sat or been graded on. | +| DELETE | `/exams/{id}` | teacher | Delete an exam. Requires teacher+ and management rights over the exam's instance (an assigned teacher, its class's homeroom teacher, or a manager/admin). Cascades the exam's results, attempts, questions, answers, and question + answer images (blobs included). | | GET | `/exams/{id}/attempt` | student | The caller's own (latest) attempt: status, deadline, remaining time, and mark once graded — everything a student's live exam screen needs, judged by the server clock. `404` until an attempt is started. | -| POST | `/exams/{id}/attempt` | student | Start, resume, or retake the caller's attempt. Requires the student role (staff run exams, they don't sit them), enrollment in the exam's course, a sittable exam (`sync`/`async`/`open` mode), and — when a window exists — the window to be open. A still-running attempt is returned as-is (`200` instead of `201`), so a reconnecting client gets its original clock back — re-starting never resets the time. Once the latest attempt is submitted or expired, re-posting starts the next sitting (`201`, blank answer sheet) while the exam's `max_attempts` (0 = unlimited) allows it. | -| POST | `/exams/{id}/attempt/answers` | student | Save (or overwrite) one answer in the caller's in-progress attempt. `choice` questions take `selected`; `text` questions take `text`. Requires the student role and enrollment in the exam's course — an unenrollment (or a promotion out of `student`) mid-exam closes the sheet. Rejected once the attempt is submitted or its deadline has passed — the server clock, not the client's, is the judge — and rejected while the student has left the exam room with the rejoin door closed. | +| POST | `/exams/{id}/attempt` | student | Start, resume, or retake the caller's attempt. Requires the student role (staff run exams, they don't sit them), enrollment in the exam's instance, a sittable exam (`sync`/`async`/`open` mode), and — when a window exists — the window to be open. A still-running attempt is returned as-is (`200` instead of `201`), so a reconnecting client gets its original clock back — re-starting never resets the time. Once the latest attempt is submitted or expired, re-posting starts the next sitting (`201`, blank answer sheet) while the exam's `max_attempts` (0 = unlimited) allows it. | +| POST | `/exams/{id}/attempt/answers` | student | Save (or overwrite) one answer in the caller's in-progress attempt. `choice` questions take `selected`; `text` questions take `text`. Requires the student role and enrollment in the exam's instance — an unenrollment (or a promotion out of `student`) mid-exam closes the sheet. Rejected once the attempt is submitted or its deadline has passed — the server clock, not the client's, is the judge — and rejected while the student has left the exam room with the rejoin door closed. | | GET | `/exams/{id}/attempt/answers/{qid}/image` | student | The caller's own drawn-answer bytes. Same visibility wall as the sitting question view — enrollment plus a started attempt (404 before that). | | POST | `/exams/{id}/attempt/answers/{qid}/image` | student | Attach (or replace) the caller's drawn answer to a question inside their in-progress attempt. `multipart/form-data` with the drawing under a `file` field; the declared content type must be `image/png`, `image/jpeg`, `image/webp`, or `image/gif` (rasters only — no SVG), the bytes at most the school's `max_file_bytes`. Rides the exact `POST /exams/{id}/attempt/answers` gate chain: the student role, an in-progress attempt, current enrollment, and the rejoin door. | | DELETE | `/exams/{id}/attempt/answers/{qid}/image` | student | Clear the caller's drawn answer to a question. Same writable-attempt gate chain as the upload. | | POST | `/exams/{id}/attempt/finish` | student | Submit the caller's attempt. Allowed while the deadline hasn't passed; after it, the attempt is already `expired` (a valid terminal state — the student used their full time) and submitting is a `409`. | -| GET | `/exams/{id}/attempt/questions` | student | The exam's questions as the sitting student sees them: `correct` stripped, their own saved answers embedded — the latest sitting's, since a retake starts from a blank sheet. Requires enrollment in the exam's course (the questions are course content — leaving the course closes them) and an attempt — start one with `POST /exams/{id}/attempt` first (404 until then). Readable in every attempt state, so a submitted student can still review what they wrote. | +| GET | `/exams/{id}/attempt/questions` | student | The exam's questions as the sitting student sees them: `correct` stripped, their own saved answers embedded — the latest sitting's, since a retake starts from a blank sheet. Requires enrollment in the exam's instance (the questions are the instance's content — leaving it closes them) and an attempt — start one with `POST /exams/{id}/attempt` first (404 until then). Readable in every attempt state, so a submitted student can still review what they wrote. | | GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see "Taking an exam") | -| GET | `/exams/{id}/attempts/{user}/answers` | teacher | One student's answer sheet with correctness flags — always the *latest* sitting's answers (a retake starts from a blank sheet). Every row carries the saved answer plus `is_correct` (`null` for text questions — those are the grader's call), and the machine's `auto_score` over the choice questions is attached as a *suggestion*: the final mark stays human, via `POST /exams/{id}/results`. Requires teacher+ and management rights over the exam's course. | -| GET | `/exams/{id}/attempts/{user}/answers/{qid}/image` | teacher | One student's drawn-answer bytes, for the grader. Requires teacher+ and management rights over the exam's course — the `attempt_answers` gate. | -| GET | `/exams/{id}/live` | teacher | A one-shot live snapshot of the exam: who's in, who's still writing (and on which sitting), who walked out of the room (`left_at`), who never showed at all (`absent`, once the window is over), time each student has left, and marks as they land. Requires teacher+ and management rights over the exam's course. Poll it to keep a monitor up to date. | -| GET | `/exams/{id}/questions` | teacher | The exam's question list, `correct` choice ids included — the answer key, paged via `?limit=&offset=` (omit `limit` for the whole list). Requires teacher+ and management rights over the exam's course. Students read questions through `GET /exams/{id}/attempt/questions`. Returns a `{items, total, limit, offset}` envelope. | -| POST | `/exams/{id}/questions` | teacher | Add a question to an exam. Requires teacher+ and management rights over the exam's course. `subject_id` must name one of the course's subjects (`GET /courses/{id}/subjects`) — every question belongs to a subject. `choice` questions carry 2–10 `choices` plus `correct` naming one of them by id; `text` questions carry neither. Locked once attempts exist. | -| POST | `/exams/{id}/questions/from-bank/{bid}` | teacher | Instantiate a bank template into this exam as a fresh question. Requires teacher+, management rights over the exam's course, and a template the caller may see (their own, or one published to the school) — anything else is a 404. `subject_id` must name one of the course's subjects — the template's own subject is origin metadata and does not carry over. The template (and its blobs) stay untouched; a full copy — text, points, spec, illustration, and option pictures — lands under a new question id. Locked once attempts exist. | -| PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question. Requires teacher+ and management rights over the exam's course. Omitted fields keep their value; `kind`/`choices`/`correct` are re-validated as a unit, so a kind switch must bring the matching fields along. `subject_id` re-tags within the course's subjects. Locked once attempts exist. An omitted `subject_id` is filled from the stored row, so any edit here — not just a re-tag — is refused with a `409` when someone else moved the question's subject after the caller read it. | -| DELETE | `/exams/{id}/questions/{qid}` | teacher | Remove a question (and every answer to it). Requires teacher+ and management rights over the exam's course. Locked once attempts exist. | +| GET | `/exams/{id}/attempts/{user}/answers` | teacher | One student's answer sheet with correctness flags — always the *latest* sitting's answers (a retake starts from a blank sheet). Every row carries the saved answer plus `is_correct` (`null` for text questions — those are the grader's call), and the machine's `auto_score` over the choice questions is attached as a *suggestion*: the final mark stays human, via `POST /exams/{id}/results`. Requires teacher+ and management rights over the exam's instance. | +| GET | `/exams/{id}/attempts/{user}/answers/{qid}/image` | teacher | One student's drawn-answer bytes, for the grader. Requires teacher+ and management rights over the exam's instance — the `attempt_answers` gate. | +| GET | `/exams/{id}/live` | teacher | A one-shot live snapshot of the exam: who's in, who's still writing (and on which sitting), who walked out of the room (`left_at`), who never showed at all (`absent`, once the window is over), time each student has left, and marks as they land. Requires teacher+ and management rights over the exam's instance. Poll it to keep a monitor up to date. | +| GET | `/exams/{id}/questions` | teacher | The exam's question list, `correct` choice ids included — the answer key, paged via `?limit=&offset=` (omit `limit` for the whole list). Requires teacher+ and management rights over the exam's instance. Students read questions through `GET /exams/{id}/attempt/questions`. Returns a `{items, total, limit, offset}` envelope. | +| POST | `/exams/{id}/questions` | teacher | Add a question to an exam. Requires teacher+ and management rights over the exam's instance. `subject_id` must name one of the subjects of that instance's catalog course (`GET /courses/{id}/subjects`) — every question belongs to a subject. `choice` questions carry 2–10 `choices` plus `correct` naming one of them by id; `text` questions carry neither. Locked once attempts exist. | +| POST | `/exams/{id}/questions/from-bank/{bid}` | teacher | Instantiate a bank template into this exam as a fresh question. Requires teacher+, management rights over the exam's instance, and a template the caller may see (their own, or one published to the school) — anything else is a 404. `subject_id` must name one of the subjects of the instance's catalog course — the template's own subject is origin metadata and does not carry over. The template (and its blobs) stay untouched; a full copy — text, points, spec, illustration, and option pictures — lands under a new question id. Locked once attempts exist. | +| PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question. Requires teacher+ and management rights over the exam's instance. Omitted fields keep their value; `kind`/`choices`/`correct` are re-validated as a unit, so a kind switch must bring the matching fields along. `subject_id` re-tags within the instance's catalog course. Locked once attempts exist. An omitted `subject_id` is filled from the stored row, so any edit here — not just a re-tag — is refused with a `409` when someone else moved the question's subject after the caller read it. | +| DELETE | `/exams/{id}/questions/{qid}` | teacher | Remove a question (and every answer to it). Requires teacher+ and management rights over the exam's instance. Locked once attempts exist. | | GET | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | student | One option's picture bytes. Same access wall as the question-image read. | | POST | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Attach (or replace) one option's picture on a `choice` question — so the options themselves can be images (four map crops, pick the right one). Same form, limits, and rights as the question-image upload; `choice_id` is the `id` carried on that choice, as returned in the question's `choices` (not a position — an unknown id is a `400`). Replacing the question's `choices` list drops all its option pictures — re-upload against the new list. | -| DELETE | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Remove one option's picture. Requires teacher+ and management rights over the exam's course; frozen once attempts exist. | -| GET | `/exams/{id}/questions/{qid}/image` | student | The question's illustration bytes. Course managers read anytime; students through the same wall as the sitting view — enrollment plus a started attempt (404 before that, like the question list itself). | -| POST | `/exams/{id}/questions/{qid}/image` | teacher | Attach (or replace) a question's illustration — any question kind may carry one, e.g. the map the prompt asks about. `multipart/form-data` with the image under a `file` field; the declared content type must be `image/png`, `image/jpeg`, `image/webp`, or `image/gif` (rasters only — no SVG), the bytes at most the school's `max_file_bytes` (settings). Requires teacher+ and management rights over the exam's course; frozen once attempts exist, like every other question edit. | -| DELETE | `/exams/{id}/questions/{qid}/image` | teacher | Remove a question's illustration. Requires teacher+ and management rights over the exam's course; frozen once attempts exist. | -| POST | `/exams/{id}/questions/{qid}/refresh-from-bank` | teacher | Re-copy a bank template's *current* content over the exam question that was instantiated from it — the escape hatch for the divergence a deep copy creates: fixing a typo in the template does not reach the copies, so this is how a copy is brought back in line, explicitly and per question. Requires teacher+, management rights over the exam's course, and a template the caller may still see. | -| POST | `/exams/{id}/questions/{qid}/to-bank` | teacher | Save one of this exam's questions into the school-wide bank as a reusable template. Requires teacher+ and management rights over the exam's course. The caller becomes the template's owner; the question's subject rides along as origin metadata. A full copy — text, points, spec, illustration, and option pictures — lands under a new bank id. Provenance rides both ways: the origin exam is recorded on the template as `source_exam`, and the exam question's `banked_as` is pointed at the new template (a repeat save is allowed and repoints it at the newest one). `from_bank` is left alone — it records the other direction and a save never changes where a question came from. | +| DELETE | `/exams/{id}/questions/{qid}/choices/{choice_id}/image` | teacher | Remove one option's picture. Requires teacher+ and management rights over the exam's instance; frozen once attempts exist. | +| GET | `/exams/{id}/questions/{qid}/image` | student | The question's illustration bytes. Instance managers read anytime; students through the same wall as the sitting view — enrollment plus a started attempt (404 before that, like the question list itself). | +| POST | `/exams/{id}/questions/{qid}/image` | teacher | Attach (or replace) a question's illustration — any question kind may carry one, e.g. the map the prompt asks about. `multipart/form-data` with the image under a `file` field; the declared content type must be `image/png`, `image/jpeg`, `image/webp`, or `image/gif` (rasters only — no SVG), the bytes at most the school's `max_file_bytes` (settings). Requires teacher+ and management rights over the exam's instance; frozen once attempts exist, like every other question edit. | +| DELETE | `/exams/{id}/questions/{qid}/image` | teacher | Remove a question's illustration. Requires teacher+ and management rights over the exam's instance; frozen once attempts exist. | +| POST | `/exams/{id}/questions/{qid}/refresh-from-bank` | teacher | Re-copy a bank template's *current* content over the exam question that was instantiated from it — the escape hatch for the divergence a deep copy creates: fixing a typo in the template does not reach the copies, so this is how a copy is brought back in line, explicitly and per question. Requires teacher+, management rights over the exam's instance, and a template the caller may still see. | +| POST | `/exams/{id}/questions/{qid}/to-bank` | teacher | Save one of this exam's questions into the school-wide bank as a reusable template. Requires teacher+ and management rights over the exam's instance. The caller becomes the template's owner; the question's subject rides along as origin metadata. A full copy — text, points, spec, illustration, and option pictures — lands under a new bank id. Provenance rides both ways: the origin exam is recorded on the template as `source_exam`, and the exam question's `banked_as` is pointed at the new template (a repeat save is allowed and repoints it at the newest one). `from_bank` is left alone — it records the other direction and a save never changes where a question came from. | | GET | `/exams/{id}/result` | student | The current user's own result for an exam. Any authenticated user may read their own mark; `404` while ungraded (or when the exam doesn't exist). | -| GET | `/exams/{id}/results` | teacher | List an exam's results, paged via `?limit=&offset=` (omit `limit` for all of them). Requires teacher+ and management rights over the exam's course — students read only their own via `GET /exams/{id}/result`. Returns a `{items, total, limit, offset}` envelope. | -| POST | `/exams/{id}/results` | teacher | Record (or overwrite) a student's mark for an exam. Requires teacher+ and management rights over the exam's course; the target must be a student and enrolled. Only students carry marks; students never grade — and nobody grades themselves. A draft can't be graded (`409`) — a mark would point at an exam its student can't see. | -| DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result from an exam. Requires teacher+ and management rights over the exam's course. | +| GET | `/exams/{id}/results` | teacher | List an exam's results, paged via `?limit=&offset=` (omit `limit` for all of them). Requires teacher+ and management rights over the exam's instance — students read only their own via `GET /exams/{id}/result`. Returns a `{items, total, limit, offset}` envelope. | +| POST | `/exams/{id}/results` | teacher | Record (or overwrite) a student's mark for an exam. Requires teacher+ and management rights over the exam's instance; the target must be a student and enrolled. Only students carry marks; students never grade — and nobody grades themselves. A draft can't be graded (`409`) — a mark would point at an exam its student can't see. | +| DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result from an exam. Requires teacher+ and management rights over the exam's instance. | | GET | `/exams/{id}/review/attempts` | student | The caller's own sitting numbers at an exam — every seq that carries answers or a mark, ascending. Own-scoped review view; opens once the teacher enables review and has marked the caller, and closes again (409) while the caller can still sit the exam. | | GET | `/exams/{id}/review/attempts/{seq}/answers` | student | One of the caller's own sittings, judged — the `seq`th attempt's answers, drawing refs, correctness flags, and auto-score suggestion. Own-scoped review view; 409 while the caller can still sit the exam, so a retake can't read its own correctness off an earlier seq. | | GET | `/exams/{id}/review/attempts/{seq}/answers/{qid}/image` | student | The caller's own drawn-answer bytes for one of their sittings — the seq-scoped, own-scoped mirror of the grader's drawing read. Same 409 while a sitting is still available. | | GET | `/exams/{id}/review/questions` | student | The exam's full question list, `correct` choice ids included — the answer key the caller reviews their own sheet against. Same review gate as the other self-review reads; revealing `correct` is the point (the gate already proves the caller was marked and can no longer sit the exam). Paged via `?limit=&offset=`. | -| GET | `/exams/{id}/statistics` | teacher | Summary statistics for an exam's graded results. Requires teacher+ and management rights over the exam's course. | -| GET | `/exams/{id}/students/{user}/attempts` | teacher | The sitting numbers a student has left at an exam — every seq that carries answers or a mark, ascending. Requires teacher+ and management rights over the exam's course. Drives the FE's attempt-by-attempt picker. | -| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers` | teacher | One prior sitting's judged answer sheet — the `seq`th attempt's answers, drawing refs, correctness flags, and auto-score suggestion. Requires teacher+ and management rights over the exam's course. Serves an empty sheet for a seq the student never wrote in. | -| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image` | teacher | A prior sitting's drawn-answer bytes. Requires teacher+ and management rights over the exam's course — the seq-scoped mirror of the grader's latest-sitting drawing read. | -| GET | `/exams/{id}/students/{user}/marks` | teacher | A student's full mark history at an exam — every sitting's mark, oldest first (the grade-of-record is the latest). Requires teacher+ and management rights over the exam's course. | +| GET | `/exams/{id}/statistics` | teacher | Summary statistics for an exam's graded results. Requires teacher+ and management rights over the exam's instance. | +| GET | `/exams/{id}/students/{user}/attempts` | teacher | The sitting numbers a student has left at an exam — every seq that carries answers or a mark, ascending. Requires teacher+ and management rights over the exam's instance. Drives the FE's attempt-by-attempt picker. | +| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers` | teacher | One prior sitting's judged answer sheet — the `seq`th attempt's answers, drawing refs, correctness flags, and auto-score suggestion. Requires teacher+ and management rights over the exam's instance. Serves an empty sheet for a seq the student never wrote in. | +| GET | `/exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image` | teacher | A prior sitting's drawn-answer bytes. Requires teacher+ and management rights over the exam's instance — the seq-scoped mirror of the grader's latest-sitting drawing read. | +| GET | `/exams/{id}/students/{user}/marks` | teacher | A student's full mark history at an exam — every sitting's mark, oldest first (the grade-of-record is the latest). Requires teacher+ and management rights over the exam's instance. | | GET | `/health` | no | Health probe: the database verdict and the AI bridge, `503` when degraded. | -| GET | `/homework` | student | List the homework across the caller's courses — their "my homework" view — paged via `?limit=&offset=` (omit `limit` for all of it). Manager+ see every course's homework; a teacher sees the homework of courses they run; a student sees only the homework they are assigned (whole-course ones plus any subset that names them, each with its `assigned` narrowed to themselves). Returns a `{items, total, limit, offset}` envelope. | -| GET | `/homework/report/{user}` | teacher | A student's homework report across their enrolled courses, paged via `?limit=&offset=` (omit `limit` for all of it): one row per homework in their audience — submitted/late/missing state plus the grade once one exists. Statuses and marks, never the submitted files (observers get the report, not the bytes). Requires teacher+, or a parent linked to the target student. Managers, admins, and parents see every course; a teacher sees only the target's courses they manage. Returns a `{items, total, limit, offset}` envelope. | -| GET | `/homework/{id}` | student | Fetch a single homework by id. Visible to whoever can view its course (its enrolled users, creator, assigned teachers, and managers/admins). A student the homework is *not* assigned to gets a 404 — the same no-leak an unseen exam draft gets, so a subset assignment never reveals itself to the students left out of it. To a caller without course-management rights the `assigned` subset comes back narrowed to their own id: being named is theirs to know, the rest of the roster is not. | -| PATCH | `/homework/{id}` | teacher | Edit a homework's title, description, due date, subject, or assigned subset. Requires teacher+ and management rights over its course. Omitted fields keep their value; a newly set `due_at` is re-checked against now and a new `subject_id` re-checked against the course. Narrowing `assigned` is refused (409) while it would orphan an existing submission or result. | -| DELETE | `/homework/{id}` | teacher | Delete a homework and everything under it — submissions, their files, and results — then unlink the file blobs from disk. Requires teacher+ and management rights over its course. The cascade is one transaction whose homework-row lock keeps a submission from landing under the homework mid-delete; the blob names are collected inside that transaction, before the rows are wiped, and removed after, so a crash in between strands at worst an unreachable file. | +| GET | `/homework` | student | List the homework across the caller's instances — their "my homework" view — paged via `?limit=&offset=` (omit `limit` for all of it). Manager+ see every instance's homework; a teacher sees the homework of instances they run; a student sees only the homework they are assigned (whole-roster ones plus any subset that names them, each with its `assigned` narrowed to themselves). Returns a `{items, total, limit, offset}` envelope. | +| GET | `/homework/report/{user}` | teacher | A student's homework report across the instances their şube carries, paged via `?limit=&offset=` (omit `limit` for all of it): one row per homework in their audience — submitted/late/missing state plus the grade once one exists. Statuses and marks, never the submitted files (observers get the report, not the bytes). Requires teacher+, or a parent linked to the target student. Managers, admins, and parents see every instance; a teacher sees only the target's instances they manage. Returns a `{items, total, limit, offset}` envelope. | +| GET | `/homework/{id}` | student | Fetch a single homework by id. Visible to whoever can view its instance (its enrolled students, its teachers, its şube's homeroom teacher, and managers/admins). A student the homework is *not* assigned to gets a 404 — the same no-leak an unseen exam draft gets, so a subset assignment never reveals itself to the students left out of it. To a caller without instance-management rights the `assigned` subset comes back narrowed to their own id: being named is theirs to know, the rest of the roster is not. | +| PATCH | `/homework/{id}` | teacher | Edit a homework's title, description, due date, subject, or assigned subset. Requires teacher+ and management rights over its instance. Omitted fields keep their value; a newly set `due_at` is re-checked against now and a new `subject_id` re-checked against the instance's course. Narrowing `assigned` is refused (409) while it would orphan an existing submission or result. | +| DELETE | `/homework/{id}` | teacher | Delete a homework and everything under it — submissions, their files, and results — then unlink the file blobs from disk. Requires teacher+ and management rights over its instance. The cascade is one transaction whose homework-row lock keeps a submission from landing under the homework mid-delete; the blob names are collected inside that transaction, before the rows are wiped, and removed after, so a crash in between strands at worst an unreachable file. | | GET | `/homework/{id}/result` | student | The caller's own grade for a homework. Any authenticated user may read their own; `404` while ungraded (or when the homework doesn't exist). This is the one read a student graded `missing` *without* ever submitting has — their submission endpoints 404 while nothing is submitted. | -| POST | `/homework/{id}/results` | teacher | Record (or overwrite) a student's grade for a homework: a status (`done`/`incomplete`/`missing`) plus an optional 0–100 mark. Requires teacher+ and management rights over the homework's course; the target must be a live student, enrolled in the course, and in the homework's audience. Nobody grades themselves. Grading before the due date, or before any submission exists (`missing` for work never handed in), is allowed. A stored grade freezes the student's submission until it is removed. | -| DELETE | `/homework/{id}/results/{user}` | teacher | Remove a student's grade from a homework — un-grading, which unfreezes the student's submission and files for further edits. Requires teacher+ and management rights over the homework's course. | +| POST | `/homework/{id}/results` | teacher | Record (or overwrite) a student's grade for a homework: a status (`done`/`incomplete`/`missing`) plus an optional 0–100 mark. Requires teacher+ and management rights over the homework's instance; the target must be a live student, enrolled in the instance, and in the homework's audience. Nobody grades themselves. Grading before the due date, or before any submission exists (`missing` for work never handed in), is allowed. A stored grade freezes the student's submission until it is removed. | +| DELETE | `/homework/{id}/results/{user}` | teacher | Remove a student's grade from a homework — un-grading, which unfreezes the student's submission and files for further edits. Requires teacher+ and management rights over the homework's instance. | | GET | `/homework/{id}/submission` | student | Read the caller's own submission to a homework: their text, files, the computed late flag, and the grade if one exists. Same visibility gates as submitting (student, enrolled, assigned). `404` until they have submitted. | -| POST | `/homework/{id}/submission` | student | Submit (or re-submit) the caller's own work for a homework: optional text, files added separately. Requires the student role, enrollment in the course, and that the homework is assigned to the caller (a subset it doesn't name 404s, never leaking the assignment). Text replaces the previous text; the first-submit stamp is pinned once and `updated_at` moves to now. `201` on the first submit, `200` on a later edit. Refused (409) once the work is graded — ask the teacher to remove the grade to reopen it. | +| POST | `/homework/{id}/submission` | student | Submit (or re-submit) the caller's own work for a homework: optional text, files added separately. Requires the student role, enrollment in the instance, and that the homework is assigned to the caller (a subset it doesn't name 404s, never leaking the assignment). Text replaces the previous text; the first-submit stamp is pinned once and `updated_at` moves to now. `201` on the first submit, `200` on a later edit. Refused (409) once the work is graded — ask the teacher to remove the grade to reopen it. | | DELETE | `/homework/{id}/submission` | student | Withdraw the caller's own submission — its text, its file rows, and their blobs. Same visibility gates as submitting. Refused (409) once the work is graded. The file rows fall in one transaction with the submission (children first); their blob names are collected before the wipe and unlinked after. | | POST | `/homework/{id}/submission/files` | student | Attach a file to the caller's own submission. `multipart/form-data` with the bytes under a `file` field (its `filename` required); any content type, at most the school's `max_file_bytes`, up to 10 files per submission. Same visibility gates as submitting. A submission need not exist first — a photo-only homework never types text, so this auto-creates an empty submission to hang the file off (an existing one's text is preserved). Adding a file re-stamps the submission's `updated_at`. Refused (409) once graded, or once the 10-file cap is reached. | -| GET | `/homework/{id}/submission/files/{fid}` | student | Download a submission file's bytes. Two callers, one handler: a student reads their own file (behind the submission gate), or a teacher who manages the homework's course reads any file under it. A parent never reaches here — observers get the report, never the bytes. The file is scoped to the homework in the path, so a managed homework's id can't be used to pull a file from another one. | +| GET | `/homework/{id}/submission/files/{fid}` | student | Download a submission file's bytes. Two callers, one handler: a student reads their own file (behind the submission gate), or a teacher who manages the homework's instance reads any file under it. A parent never reaches here — observers get the report, never the bytes. The file is scoped to the homework in the path, so a managed homework's id can't be used to pull a file from another one. | | DELETE | `/homework/{id}/submission/files/{fid}` | student | Remove a file from the caller's own submission — row first, then its blob. Same visibility gates as submitting. Refused (409) once graded. Removing a file re-stamps the submission's `updated_at`. | -| GET | `/homework/{id}/submissions` | teacher | The teacher's roster for a homework, paged via `?limit=&offset=` (omit `limit` for all of it): one row per student in the audience — the assigned subset, or every currently enrolled student for a whole-course homework — plus any student outside it who still owns a submission or grade (an unenrollment or an audience change leaves work behind; it stays visible here, flagged). Each row carries the submission with its files and computed late flag, the grade, a computed `missing`, and a computed `unenrolled`. Requires teacher+ and management rights over the homework's course. Returns a `{items, total, limit, offset}` envelope. | +| GET | `/homework/{id}/submissions` | teacher | The teacher's roster for a homework, paged via `?limit=&offset=` (omit `limit` for all of it): one row per student in the audience — the assigned subset, or every student currently enrolled in the instance when the homework carries none — plus any student outside it who still owns a submission or grade (an unenrollment or an audience change leaves work behind; it stays visible here, flagged). Each row carries the submission with its files and computed late flag, the grade, a computed `missing`, and a computed `unenrolled`. Requires teacher+ and management rights over the homework's instance. Returns a `{items, total, limit, offset}` envelope. | +| GET | `/instances/me` | student | The instances the caller is a live member of, newest first, paged via `?limit=&offset=` (omit `limit` for all of them); returns a `{items, total, limit, offset}` envelope. The route a student reads to find the courses their section is being taught. | +| GET | `/instances/{id}` | student | Fetch one instance by id. Visible to its enrolled students, its assigned teachers, its şube's homeroom teacher, and managers/admins. | +| PATCH | `/instances/{id}` | teacher | Update one instance's own policy. Requires teacher+ and a right over this instance: manager+, one of its assigned teachers, or its şube's homeroom teacher. Omitted fields keep their value; both are non-clearable. | +| GET | `/instances/{id}/enrollments` | teacher | List this instance's roster, paged via `?limit=&offset=` (omit `limit` for the whole roster). Requires teacher+ and a right over the instance — students see their own instances via `GET /instances/me`. Returns a `{items, total, limit, offset}` envelope. | +| POST | `/instances/{id}/enrollments` | teacher | Enroll a student into this instance (idempotent upsert). Requires teacher+ and a right over the instance. Only students can be enrolled — enrollment is student membership, and it gates sitting exams, being graded, and the roster. The row is hand-placed (`source` `null`), so no şube sweep can take it back. | +| DELETE | `/instances/{id}/enrollments/{user}` | teacher | Unenroll a student from this instance. Requires teacher+ and a right over the instance. Existing exam results are kept (they disappear from the student's marks report until re-enrolled). | +| GET | `/instances/{id}/exams` | student | List one instance's exams, paged via `?limit=&offset=` (omit `limit` for all of them). Visible to the instance's enrolled students, its teachers, its şube's homeroom teacher, and managers/admins — but drafts appear only to the instance's managers. Returns a `{items, total, limit, offset}` envelope. | +| POST | `/instances/{id}/exams` | teacher | Create an exam inside one instance. Requires teacher+ and a right over the instance; the exam's marks count into the instance's average with its kind's weight (`GET /settings`) and into the dönem's karne named by `term`. Omit `mode` for an offline-graded exam nobody can sit; `sync`/`async` take a window (async also `duration_ms`), `open` is sittable anytime with an optional per-attempt `duration_ms`. `max_attempts` (default 1, `0` = unlimited) meters retakes and `allow_rejoin` (default `true`) is the exam-room door — both stay editable while the exam runs. Send `draft: true` to keep the exam private while it's still being written: only the instance's managers see it, and sitting and grading are blocked until it's published (`PATCH` `draft: false`). Only a class-delivered course (`kind` `course`) carries exams. | +| GET | `/instances/{id}/homework` | student | List one instance's homework, newest first, paged via `?limit=&offset=` (omit `limit` for all of it). Visible to the instance's enrolled students, its teachers, and managers/admins — but a student sees only the homework they are assigned (whole-roster ones plus subsets that name them, each with its `assigned` narrowed to themselves). Returns a `{items, total, limit, offset}` envelope. | +| POST | `/instances/{id}/homework` | teacher | Assign homework inside one instance. Requires teacher+ and a right over the instance. The homework is tagged with one of the catalog course's subjects and given a future `due_at`; `assigned` optionally narrows it to a subset of the enrolled students (omit or empty = the whole roster). | +| GET | `/instances/{id}/sessions` | student | List one instance's lesson sessions, most recent first, paged via `?limit=&offset=` (omit `limit` for all of them). Visible to the instance's enrolled students, its teachers, and managers/admins. Returns a `{items, total, limit, offset}` envelope. | +| POST | `/instances/{id}/sessions` | teacher | Create a lesson session inside one instance. Requires teacher+ and a right over the instance. The session's teacher defaults to the caller. | +| POST | `/instances/{id}/teachers` | manager | Assign a teacher to this instance (idempotent). Manager+ only — staffing is the office's call. The assignee must already hold the `teacher` role or higher; the assignment gives them full management of the instance (exams, sessions, homework, roster, grading) but they keep no catalog rights over the course itself. | +| DELETE | `/instances/{id}/teachers/{user}` | manager | Unassign a teacher from this instance. Manager+ only. The instance, its exams, sessions, and roster are untouched — the teacher just loses their management rights over it. A user who was never assigned is a 404. | | GET | `/limits` | no | Every fixed validation bound the API enforces. Unauthenticated: the registration and login forms need the username and password bounds before a session exists, and none of these values are secrets — they are the same rules a 400 would spell out. | -| GET | `/marks/me` | student | The current user's mark report: every enrolled course with its graded exams, weighted course averages, and the overall average. | -| GET | `/marks/{user}` | teacher | Any user's mark report. Requires teacher+, or a parent tied to the target student. Managers, admins, and parents see every course; a teacher sees only the target's courses they manage — the rest of the report (other teachers' courses) stays out of reach. | +| GET | `/marks/karne` | student | The current user's karne for one dönem: every instance of their şubeler that counts toward the karne, the `ders_saati`-weighted average across them, and the verdict. An archived dönem serves the snapshot the school froze when it was closed; an open one computes live. | +| GET | `/marks/karne/{user}` | teacher | Any user's karne for one dönem. Requires teacher+, or a parent tied to the target student. A linked parent and manager+ read the whole karne; an exactly-teacher caller sees only the lines of the instances they run, with the dönem average recomputed over those and no verdict (see [`narrow_karne`]). | +| GET | `/marks/me` | student | The current user's mark report: every instance they sit, with its graded exams, weighted instance averages, and the overall average. | +| GET | `/marks/{user}` | teacher | Any user's mark report. Requires teacher+, or a parent tied to the target student. Managers, admins, and parents see every instance; a teacher sees only the target's instances they run — the rest of the report (other sections) stays out of reach. | | GET | `/meals/attendance/{user}` | teacher | One student's meal-attendance history, newest mark first. Requires teacher+, or a parent linked to them — the caller's own id always passes, like the balance and ledger reads. Narrow to a date range with `?from=&to=` (inclusive `YYYY-MM-DD` bounds on the menu's day, each held to the same real-calendar-day rule the menu's own date is). Paged via `?limit=&offset=`. | | GET | `/meals/balance/me` | student | What the caller owes or has on account, in minor units (negative = owes). | | GET | `/meals/balance/{user}` | manager | One student's meal balance. Requires manager+, or a parent link to them — the caller's own id always passes. A teacher gets a `403`: canteen debt is family debt, gated exactly like `/payments`. | @@ -1378,24 +1416,24 @@ window filtering, before paging; negative values are a `400` naming the field. | PATCH | `/schools/{slug}/modules` | builder | Re-sell a school's whole shelf in one call: any mix of modules and packages, in either direction. Every list is optional and an empty body is a no-op. | | POST | `/schools/{slug}/modules/{module}` | builder | Sell a school one module. Idempotent: a module it already has is a `200` with the unchanged set. Refused while what the module structurally needs is off — enable those in the same `PATCH` instead. | | DELETE | `/schools/{slug}/modules/{module}` | builder | Take one module back. Idempotent, and refused while a module the school still has depends on it — the mirror of the enable direction. | -| GET | `/sessions/{id}` | student | Fetch a single session by id. Visible to its course's enrolled users, the session's teacher, the course's own teachers, and managers/admins. | -| PATCH | `/sessions/{id}` | teacher | Update a session. Requires teacher+ with course-management rights. Omitted fields keep their value; an explicit `null` clears `ends_at`. | -| DELETE | `/sessions/{id}` | teacher | Delete a session and its roll-call rows. Requires teacher+ with course-management rights. | -| GET | `/sessions/{id}/attendance` | teacher | List a session's roll call, paged via `?limit=&offset=` (omit `limit` for the whole roster). Same rights as taking it: the session's teacher or a course manager — students see their own tallies via `GET /attendance/me`. Returns a `{items, total, limit, offset}` envelope. | -| POST | `/sessions/{id}/attendance` | teacher | Record a user's roll-call state for a session. The session's teacher or a course manager marks **enrolled students** (only students attend classes); marking the **session's teacher** requires manager+ (staff presence is management's call, so a teacher can't mark themselves present). Students never self-mark a lesson. | -| DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a user's roll-call row from a session. Same rights as marking: session teacher or course manager for students, manager+ for a staff row (any target holding teacher or higher). | +| GET | `/sessions/{id}` | student | Fetch a single session by id. Visible to the instance's enrolled students, the session's own teacher, the instance's teachers, and managers/admins. | +| PATCH | `/sessions/{id}` | teacher | Update a session. Requires teacher+ with instance-management rights. Omitted fields keep their value; an explicit `null` clears `ends_at`. | +| DELETE | `/sessions/{id}` | teacher | Delete a session and its roll-call rows. Requires teacher+ with instance-management rights. | +| GET | `/sessions/{id}/attendance` | teacher | List a session's roll call, paged via `?limit=&offset=` (omit `limit` for the whole roster). Same rights as taking it: the session's teacher or a manager of its instance — students see their own tallies via `GET /attendance/me`. Returns a `{items, total, limit, offset}` envelope. | +| POST | `/sessions/{id}/attendance` | teacher | Record a user's roll-call state for a session. The session's teacher or a manager of its instance marks **enrolled students** (only students attend classes); marking the **session's teacher** requires manager+ (staff presence is management's call, so a teacher can't mark themselves present). Students never self-mark a lesson. | +| DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a user's roll-call row from a session. Same rights as marking: the session's teacher or a manager of its instance for students, manager+ for a staff row (any target holding teacher or higher). | | GET | `/settings` | student | The school's current policy. Any authenticated user — clients need it to render pickers and grades. Falls back to the built-in defaults until a manager edits it. | | PATCH | `/settings` | manager | Update the school's policy. Requires manager+. Omitted fields keep their value; a present field replaces its list wholesale. Existing rows are untouched — a removed exam kind or status lives on in old records; only new writes are held to the new lists. Kind weights, though, apply live: mark reports read them at request time, so editing a weight re-weights every exam of that kind. For that reason a kind whose exams already carry marks cannot be dropped from the list (409) — those marks would silently re-weight to 1; an unmarked kind leaves freely, and an exam whose kind is gone counts with weight 1 but cannot be graded (409) until the kind returns — the other end of the same rule. `max_file_bytes` likewise applies at upload time only — already-stored files keep their size, and the chatbot knobs apply to the next chat request only. `meal_slots` follows the exam-kind rule: a slot a menu was already published for cannot be dropped (409), because the menu snapshotted its name. Slot names must not contain `/ \ ? # %` (400) — a menu's id carries the name into a URL — but a name already on the school's stored list is exempt, so a list written before that rule can still be edited around it. | -| GET | `/subjects/{id}` | student | Fetch a single subject by id. Visible to whoever can view its course: the course's enrolled users, its creator, its assigned teachers, and managers/admins. | +| GET | `/subjects/{id}` | student | Fetch a single subject by id. Visible to whoever can view its course: its creator, a manager/admin, or anyone the course reaches. | | PATCH | `/subjects/{id}` | teacher | Update a subject's name or description. Requires teacher+ and management rights over its course. Omitted fields keep their value; the course link is fixed at creation. | | DELETE | `/subjects/{id}` | teacher | Delete a subject. Requires teacher+ and management rights over its course. Refused with a 409 while any exam question or homework still references it — re-tag or delete those first, so nothing is left pointing at a subject that no longer exists. | | GET | `/swagger` | no | Interactive API docs (Swagger UI) | | GET | `/terms` | student | List every term, newest first. Any authenticated user — students need the calendar to make sense of their courses. Paged via `?limit=&offset=` (omit `limit` for the full list); returns a `{items, total, limit, offset}` envelope. | -| POST | `/terms` | manager | Create an academic term. Requires manager+. Past dates are allowed — terms are calendar structure, not schedules. | +| POST | `/terms` | manager | Create a dönem inside an academic year. Requires manager+. Past dates are allowed — dönemler are calendar structure, not schedules; an *archived* year refuses the new dönem (`409`), because past years take no new structure. | | GET | `/terms/{id}` | student | Fetch a single term by id. | | PATCH | `/terms/{id}` | manager | Update a term. Requires manager+. Omitted fields keep their value; the merged range must stay ordered. | -| DELETE | `/terms/{id}` | manager | Delete a term. Requires manager+. Refused with a 409 while any course still links to it — unlink those courses (`PATCH /courses/{id}` with `"term_id": null`) or delete them first, so a term is never dropped out from under the calendar its courses hang on. | -| POST | `/terms/{id}/archive` | manager | Archive a term. Requires manager+. An archived term is frozen: it takes no edits, no delete, and no new course or class link. Idempotent — archiving an already-archived term answers `200` with the stamp it already had. | +| DELETE | `/terms/{id}` | manager | Delete a dönem. Requires manager+. Refused with a 409 while anything still hangs off it — an exam filed in it, or a karne frozen for it — so a dönem is never dropped out from under marks that name it; move or delete those first. The dönem's own academic year is untouched (that is `DELETE /academic-years/{id}`, which refuses while a dönem still links it). | +| POST | `/terms/{id}/archive` | manager | Archive a dönem. Requires manager+. Archiving **freezes the karnes**: every student with a roster row under the dönem's year gets a snapshot of their report, and from then on `GET /marks/karne` serves that record instead of recomputing — a mark corrected after the fact no longer rewrites what a family holds. An archived dönem takes no edits and no delete; exams may still be created in it while its *year* is open (the archive is a record, not a wall). Idempotent — archiving an already-archived dönem answers `200` with the stamp it already had and never re-freezes. | | POST | `/terms/{id}/unarchive` | manager | Re-open an archived term. Requires manager+. Idempotent the same way as archiving: an already-open term answers `200`. | | GET | `/time` | no | Server clock: `{now}` UTC unix-millis, for a frontend to sync against. | | GET | `/users` | admin | List every user with their role, newest first. Admin only. Paged: pass `?limit=&offset=` to take a window (omit `limit` for the whole list); the response is a `{items, total, limit, offset}` envelope where `total` counts every user. | @@ -1431,13 +1469,16 @@ window filtering, before paging; negative values are a `400` naming the field. the core four `present | absent | late | excused` always exist, plus whatever the school added. `kind` must be one of the school's exam kinds (`GET /settings`; defaults: -`homework | quiz | midterm | final | project | oral`). The kind carries the -exam's weight in the course average — an integer `1`–`100` set per **kind** in +`yazili | sozlu | uygulama`). The kind carries the +exam's weight in the instance average — an integer `1`–`100` set per **kind** in settings (defaults all `1`), resolved when a report is read; an exam whose kind was later removed from settings counts with weight `1`. -A course may carry a `term_id` (`null` = unassigned); on `PATCH -/courses/{id}`, an omitted `term_id` keeps the link and an explicit `null` -clears it. +A course carries **no** term — the calendar hangs off the class instead. The +academic stack is three levels: an **academic year** (`/academic-years`) holds +the terms (`/terms`), and a **class section** names the year it runs in +(`year`), so every instance under it and every exam filed in one of that year's +terms shares one calendar. On `PATCH /classes/{id}`, an omitted `year` keeps the +link and an explicit `null` clears it. `role` ∈ `parent | student | teacher | manager | admin`. Ids in responses are hyphenated UUIDv7s. `parent` accounts are made by an admin (register as `student`, then `PATCH /users/{id}/role`) and observe only the students an admin tied to them @@ -1503,8 +1544,9 @@ free their own, and a closed list is never rewritten. Pre-existing hand-picked ( audiences convert on boot: each listed user becomes a signup row credited to the event's creator, and the audience becomes an uncapped registration list. Reading a child collection of a missing parent (`/events/{id}/attendance`, -`/exams/{id}/results`, `/courses/{id}/enrollments`, `/courses/{id}/exams`, -`/courses/{id}/sessions`, `/courses/{id}/subjects`, `/courses/{id}/homework`, +`/exams/{id}/results`, `/instances/{id}/enrollments`, `/instances/{id}/exams`, +`/instances/{id}/sessions`, `/instances/{id}/homework`, +`/courses/{id}/subjects`, `/classes/{id}/members`, `/classes/{id}/instances`, `/homework/{id}/submissions`, `/sessions/{id}/attendance`) is a `404`, not an empty list. Personal info (`name`, `surname`, `email`, `phone`, `birth_date`) is the same @@ -2149,13 +2191,17 @@ why grading an exam whose kind has left the list is refused). The kitchen is data too: a manager publishes a **menu** per calendar day and meal slot, with its dishes, their dietary tags, and prices in minor units; booking a seat charges that price as a snapshot and an admin records the cash that comes back in (see "Food program: menus, dishes, bookings & the ledger"). The one shape rule on a **meal slot's name** lives here: it may not contain `/`, `\`, `?`, `#` or `%` (`400`), because the name is copied verbatim into a menu's record id and that id is a URL path segment — a slot the settings accepted but no menu could be addressed under would be a slot the canteen cannot use. A name the stored list *already* carries is exempt, so a list written before the rule existed can still be edited around the offending name — otherwise one bad slot froze the whole list, since re-sending it is a `400` and dropping it is a `409` once a menu used it. The grandfathered name still cannot carry a new menu, and dropping it is still the only way to remove it. -Academic structure is data too. **Terms** (`/terms`) model whatever calendar -the school runs — semester, trimester, quarter systems are just rows with a -name and a date range. Courses *and classes* may link to one via `term_id` (nullable), -and deleting a term is refused with a `409` while any of them still links to -it — unlink them (`PATCH /courses/{id}` or `PATCH /classes/{id}` with -`"term_id": null`) or delete them first, so the calendar never disappears -under them. Term dates may lie in the past, +Academic structure is data too, in three levels. An **academic year** +(`/academic-years`) carries the school's year — a name, a date range, the +sınıf-geçme policy (`grade_promotions`) the next rollover applies, and, once +you ask for one, `POST /academic-years/{id}/rollover` plants the previous +year's şubeler into it. A **class section** names the year it runs in (`year`), +and **terms** (`/terms`) hang off that year: semester, trimester and quarter +systems are all just rows with a name, a date range and their `year`. +A year refuses deletion with a `409` while any şube or dönem still belongs to +it, and a term refuses it while any exam is filed in it — move or delete those +first, so the calendar never disappears +under the structure. Term dates may lie in the past, deliberately: a school adopting the app mid-year backfills its calendar — unlike exam/lesson/event times, which reject backdating. @@ -2633,7 +2679,9 @@ a new plan instead. That freeze is a **counter on the plan row** (`assignment_count`), incremented in the *same transaction* as the assignment row it counts, and the edit and the delete are single-record conditional writes against it — the same shape as a -term's `course_count`. It used to be a `SELECT` taken before the write, which a +term's `exam_count` (the term's own delete is one `DELETE … WHERE +exam_count = 0 AND NOT EXISTS (SELECT 1 FROM karne_snapshot WHERE term = $1)`, +with the year's reference handed back in the same statement). It used to be a `SELECT` taken before the write, which a concurrent assign could land behind, leaving a plan edited *and* assigned, or deleted with a live assignment naming it. Now the two contend on one record: an assign either freezes the plan first (and the edit or delete is a `409`) or @@ -3149,8 +3197,8 @@ half-applied refresh. ## Homework -A course hands out **homework**: `POST /courses/{id}/homework` with a title, -an optional description, a **required subject** (one of the course's own — and +An **instance** hands out **homework**: `POST /instances/{id}/homework` with a title, +an optional description, a **required subject** (one of the instance's course's subjects — and the same delete guard questions have: a subject with homework refuses deletion with a `409` until the homework is re-tagged via `PATCH /homework/{id}` or deleted), and a **required `due_at`** that must not lie in the past (same 60s @@ -3222,7 +3270,7 @@ grades. ## Lesson sessions, roll call, the work log, pomodoro & attendance reports -Events cover ad-hoc gatherings; **sessions** are a course's lessons. A session +Events cover ad-hoc gatherings; **sessions** are an instance's lessons. A session belongs to a course and carries a `teacher` (defaults to whoever creates it; any explicit `teacher_id` must hold teacher+ — a student cannot teach), an optional `topic`, a required `starts_at`, and an optional `ends_at` (when both @@ -3300,135 +3348,167 @@ as the longest run ever held (see "Badges"). **Attendance reports** mirror the marks report: `GET /attendance/me` for any logged-in user, `GET /attendance/{user}` for teacher+ — narrowed to the -courses the caller manages (manager+ sees every course; event tallies are +instances the caller manages (manager+ sees every instance; event tallies are school-wide either way). The report tallies event attendance and lesson roll -call separately, plus a per-course breakdown: +call separately, plus a per-instance breakdown and the per-dönem devamsızlık +counts: ```json { "user": "01J…", "events": { "present": 4, "absent": 1, "late": 0, "excused": 1, "total": 6, "rate": 0.8 }, "sessions": { "present": 9, "absent": 2, "late": 1, "excused": 0, "total": 12, "rate": 0.8333 }, - "courses": [ { "course": { "id": "01J…", "title": "algebra", … }, "counts": { … } } ] + "courses": [ { "instance": "01J…", "course": { "id": "01J…", "title": "algebra", … }, "counts": { … } } ], + "devamsizlik": [ + { "term": "01J…", "name": "1. Dönem", "absent_days": 3, "excused_days": 1, + "unexcused_days": 3, + "limits": { "max_excused_days": 10, "max_unexcused_days": 20 }, + "over_limit": false } + ] } ``` `rate = (present + late) / (present + absent + late)`: arriving late still counts as attending, and an excused absence counts against no one (`rate` is -`null` when every row is excused, or there are none). Per-course blocks appear -for every course the user has roll-call rows in — attendance is a historical +`null` when every row is excused, or there are none). Per-instance blocks appear +for every instance the user has roll-call rows in — attendance is a historical record, so unenrolling hides marks from the marks report but never hides an absence. +**Devamsızlık (the legal absence tally).** The same report carries a +`devamsizlik` block, one entry per **term**: `absent_days` (distinct calendar +days the student has at least one `absent` roll-call row on), `excused_days` +(idem for `excused`), `unexcused_days` (the `absent` count — the two are one +bucket in the schema), the school's `limits` +(`max_excused_absent_days`, `max_unexcused_absent_days`, each `null` when +unset), and `over_limit`. Days are bucketed in the school's **timezone** +(`GET /settings`, `timezone`, default `Europe/Istanbul`), so a 23:30 and a +00:30 lesson are two days or one depending on where the school is — never on +where the server runs. Two absences on one day count once, because veli +excuses and the yönetmelik count days, not lessons. The limits are advisory +here: nothing refuses a roll-call row that pushes a student past them. + ## Class sections (şube) A **class section** is the group a school actually teaches in — 9-A, 10-B — and -here it is a bulk-enrollment tool rather than a second kind of membership. Its -row carries a name, an optional free-text `grade` label in the school's own -vocabulary (`"9"`, `"Lise 2"`; `""` means no grade, exactly like omitting it) -and an optional `term_id`; nothing else about a course changes because a class -exists. Schools that run electives or a college-style timetable simply never -create one — individual enrollment is untouched, and classes are a -convenience. +it is the **academic anchor**: a student's membership, the courses it carries, +their exams and their homework all hang off it. Its row carries a name, an +optional free-text `grade` label in the school's own vocabulary (`"9"`, +`"Lise 2"`; `""` means no grade, exactly like omitting it) and the **academic +year** it runs in (`year`, nullable while a section is being prepared). A +section does not teach a course directly: attaching one mints an **instance** +(`/instances`) — its own row, with its own teachers, `ders_saati`, karne weight, +roster, exams, sessions and homework — and two sections that attach the same +course share nothing at all. Schools that run electives or a college-style +timetable simply never create one — individual enrollment and the school-scoped +course membership are untouched, and classes are a convenience. **The homeroom teacher.** A class may also name one — the *sınıf öğretmeni* — with `teacher_id` on create or `PATCH`, and it rides back out as a `teacher` person block (`null` when there is none, exactly like `grade`; both `null` and `""` clear it). The account must exist and hold **teacher, manager or admin** (anything else is a `400` naming `teacher_id`, the same shape a non-student -member gets). It is a label and nothing more: it grants no rights over the -class, is not counted, and is not a second teacher assignment — courses keep -their own `teachers` list. A role change that takes the account below `teacher` +member gets). It is a **teaching right**, not a label: the homeroom teacher +manages every **instance** their section carries — its hours and karne weight, +its roster, its exams, sessions, homework and grading — under the same rule an +assigned instance teacher gets (manager+, one of the instance's assigned +teachers, or the section's homeroom teacher). It is not counted as a teacher +assignment of its own and grants nothing on the catalog: instances keep their +own `teachers` list, and editing a section is still manager+. A role change +that takes the account below `teacher` clears the column on **every** class it held, in the same sweep that drops -their course assignments, so no section ever lists a demoted account. +their instance assignments, so no section ever lists a demoted account. That sweep runs once, over the rows that exist when it runs — so a demotion that lands *between* a request's role check and its write would sweep nothing and leave the assignment standing forever. Both writers close it from the other -end: `POST /classes`, `PATCH /classes/{id}` and `POST /courses/{id}/teachers` +end: `POST /classes`, `PATCH /classes/{id}` and `POST /instances/{id}/teachers` re-read the account's live role **after** their write and answer `409` if it has since dropped below `teacher`, taking the assignment back (a create is rolled back whole — no half-made class is left behind). Whichever side is second catches it; the ordinary path costs one extra read and no extra write. -**The pump.** A class holds **members** (students) and **attached courses**, -and owes the product of the two: every member enrolled in every attached -course. So both writes push the same way — attaching a course -(`POST /classes/{id}/courses`) enrolls the whole roster into it, adding a -member (`POST /classes/{id}/members`) enrolls them into every course the class +**The pump.** A class holds **members** (students) and **instances** (the +courses it teaches), and owes the product of the two: every member enrolled in +every instance. So both writes push the same way — attaching a course +(`POST /classes/{id}/instances`, body `{"course_id": …}`) enrolls the whole +roster into the new instance, adding a +member (`POST /classes/{id}/members`) enrolls them into every instance the class already carries — and what gets written is an ordinary `enrollment` row, the -same one `POST /courses/{id}/enrollments` writes, counted against the same +same one `POST /instances/{id}/enrollments` writes, counted against the same `enrollment_count`. Each row a class writes is tagged with it as the row's `source`; **no `source` means placed by hand**, and that one bit is what makes the sweeps below safe. It rides back out on every enrollment response -(`GET /courses/{id}/enrollments`) as the class's id, or `null` for a +(`GET /instances/{id}/enrollments`) as the class's id, or `null` for a hand-placed row — without it no client could tell which of the roster rows it is showing a class change is about to remove. -**Already enrolled is skipped.** A pair that already has an enrollment row is -left exactly as it stands — no second seat charged, no `source` rewritten. A +**Already enrolled is skipped.** An (instance, student) pair that already has +an enrollment row is +left exactly as it stands — no second row, no `source` rewritten. A student a teacher enrolled by hand *stays* hand-placed when the class later attaches that course, so the class never quietly adopts someone else's roster decision. -**Capacity is all-or-nothing.** Attaching a course, or adding a member, claims -one seat per pair that needs a new row, each against its own course's -`capacity` — and if any single course has no room the whole call is a `409` -naming it (`course: is full, so the class cannot take this student`, -`course: cannot hold the whole class`). Nothing lands, not even the seats -claimed earlier in the same run: a half-enrolled class is worse than a refused -one, and the refusal names the course whose capacity to raise. - -A second `409` reads off the same claim and is deliberately told apart from it: -one of the class's attached courses **no longer exists** -(`course: no longer exists — detach it from this class first`). A seat -claim that matches nothing means "full" *or* "no such row", and reporting a -stale attachment as a full course would send staff off to raise a capacity that -is not there — on a class every member-add now fails on. Detach the link and -the class works again. - -**Removals take back only what the class pumped, and repair before they -delete.** Removing a member (`DELETE /classes/{id}/members/{user}`) or -detaching a course (`DELETE /classes/{id}/courses/{course}`) sweeps the +**A link to a course that no longer exists blocks the pump.** Adding a member +walks every instance the class carries, and one of them may point at a course +row that is gone: the call is a `409` and names it +(`course: no longer exists — detach it from this class first`, code +`linked_course_missing`). Reporting it as anything else would send staff off to +raise a cap that does not exist — on a class every member-add now fails on. +Detach the link and the class works again. + +**Removing a member ends the stint; the row stays.** `DELETE +/classes/{id}/members/{user}` is a **soft leave**: it stamps `left_at`, gives +the class its seat back (the counter counts live members only), and sweeps the +instance enrollments the class pumped for that student. The history is not +erased — a second `POST /classes/{id}/members` inserts a **fresh** row for the +same pair (the live-pair index is partial, so both can exist), and +`class_member_count` never exceeds the live rows. Removing the wrong student +from a class mid-year is therefore something the product can undo without +losing who was there when. + +**Removals take back only what the class pumped.** A leave, or detaching an +instance (`DELETE /classes/{id}/instances/{instance}`) sweeps the enrollment rows whose `source` is *this* class and no others — hand-placed -rows survive every class operation. Even a tagged row is not automatically -deleted: if a **second class** still claims that pair (it holds the same -student *and* that course attached), the row is re-tagged to that class -instead, because the row it skipped writing is the row now being swept and the -student is still owed the seat. The heir is the lowest class id among the -claimants, so repeating a sweep lands on the same class. Only a row nobody is -left to claim is deleted and its seat handed back. Sweeps also tolerate rows -that are already gone — deleting a course wipes its enrollments wholesale +rows survive every class operation, and every swept row's seat is handed back +to its instance's counter. There is no heir to consider: a second section +teaching the same course holds its **own** instance and therefore its own +roster row, so this class's row is released outright. Sweeps also tolerate rows +that are already gone — deleting a course or detaching an instance wipes its +enrollments wholesale while the class memberships survive — so "this class has a member" and "that member holds a pumped row" are independent facts. -**A manual unenroll wins, permanently.** `DELETE /courses/{id}/enrollments/{user}` +**A manual unenroll wins, permanently.** `DELETE /instances/{id}/enrollments/{user}` on a pumped student is allowed and sticks: nothing re-pumps them while they remain a member, because the pump runs on writes, never on a schedule. Staff put them back by enrolling them by hand (which makes the row hand-placed) or by detaching and re-attaching the course. -**And a manual enroll wins too, permanently.** `POST /courses/{id}/enrollments` +**And a manual enroll wins too, permanently.** `POST /instances/{id}/enrollments` landing on a row a class pumped takes the row *off* that class — its `source` is cleared, the response comes back with `"source": null` — so no later class sweep can undo a placement an operator made on purpose. That is the mirror of the rule above: hand-placed beats pumped in both directions, and without it "hand-placed" was a state only a *first* enroll could ever reach. -**Delete guards.** A class still holding members or attached courses refuses -deletion with a `409` ("remove its members and detach its courses first") — +**Delete guards.** A class still holding live members or instances refuses +deletion with a `409` ("remove its members and detach its instances first") — the roster it owes is never dropped out from under the courses silently. A -term linked by any class refuses deletion the same way courses make it refuse. -Deleting a **course** detaches it from every class it was on (its enrollments -go with it), and a role change that takes a user off `student` drops their +**term** carrying exams refuses deletion, and an **academic year** refuses while +any class or term still belongs to it: the calendar never disappears under the +structure. Deleting a **course** detaches it from every class it was on (its +instances and their enrollments go with it, and the files those rows held are +unlinked), and a role change that takes a user off `student` drops their class memberships exactly as it drops their enrollments — in one transaction, -because a membership left behind would keep pumping them back into courses, +because a membership left behind would keep pumping them back into instances, while an enrollment left behind would stay tagged with a class the released counters had already made deletable, and nothing could ever sweep it again. **A link to a deleted course detaches instead of refusing.** Should a `class_course` row ever be left pointing at a course row that is gone, -`DELETE /classes/{id}/courses/{course}` still answers `204`: management rights +`DELETE /classes/{id}/instances/{instance}` still answers `204`: management rights are read *off* the course, so a stale link had no readable owner and the detach used to `404` forever — which also left the class permanently undeletable, its attachment counter counting a row nothing could sweep. There is no roster left @@ -3436,11 +3516,13 @@ to protect, and the caller is already teacher+. **Who may.** Creating, editing and deleting a class, and adding or removing its members, is **manager+** — a class is school structure, not classroom -work. Attaching or detaching a course takes management rights on **that -course** (its creator, a teacher assigned to it, or manager+), since the call -writes that course's roster and nothing else: the same right enrolling one -student takes. Every read (`GET /classes`, `/classes/{id}`, its members and -its courses, all paged, newest first) is **teacher+** — and "newest" here means +work. Attaching or detaching a course takes catalog rights on **that +course** (its creator, or manager+), since the call writes that course's roster +for this section and nothing else. Editing an instance's own policy +(`PATCH /instances/{id}`) and its roster take instance rights (manager+, an +assigned teacher, or the section's homeroom teacher). Every read +(`GET /classes`, `/classes/{id}`, its members and its instances, all paged, +newest first) is **teacher+** — and "newest" here means when the student was *added* or the course *attached*, not the student's or the course's own id, which is what a link row keyed on the pair would otherwise sort by. Rows written before that stamp existed carry none, and sort last. @@ -3501,8 +3583,9 @@ grade's template — idempotent, so it is safe on a class that already carries some of the courses. The blueprint is a template, not a new kind of membership. Applying it calls -the same attach a manager's own `POST /classes/{id}/courses` does, so what -lands is ordinary `class_course` links and ordinary `enrollment` rows, and an +the same attach a manager's own `POST /classes/{id}/instances` does, so what +lands is ordinary `class_course` **instances** and the ordinary `enrollment` +rows each implies, and an elective a student takes alone stays an individual enrollment nothing here can see. @@ -3626,8 +3709,8 @@ so the skip is reported once for the whole grade — the sections after the firs one are not asked again — and never again on a later pump), `class_at_course_ceiling`, `class_roster_too_large` (the section holds more students than one attach may enroll at once), -`course_full` (no free -seat for the whole section), and +`linked_course_missing` (an instance the section already carries points at a +course that no longer exists), and `blueprint_deleted` (the template itself was deleted while the pump ran — nothing was attached, and there is nothing left to retry). That last one **ends the run**: it says nothing about the (section, course) pair it names, so every @@ -3641,8 +3724,8 @@ code out of: | route | codes | | --- | --- | -| `POST /classes/{id}/courses` | `duplicate`, `class_at_course_ceiling`, `class_roster_too_large`, `course_full` | -| `POST /classes/{id}/members` | `duplicate`, `class_at_roster_ceiling`, `class_course_list_too_large`, `course_full`, `linked_course_missing` | +| `POST /classes/{id}/instances` | `duplicate`, `class_at_course_ceiling`, `class_roster_too_large` | +| `POST /classes/{id}/members` | `duplicate`, `class_at_roster_ceiling`, `class_course_list_too_large`, `linked_course_missing` | The three *deleted* codes are a pump's alone: on a manual attach a deleted class or course is a `404`, and `blueprint_deleted` needs a blueprint nobody handed @@ -3662,14 +3745,18 @@ pump, which only ever attaches courses, reports that second pair. One cause therefore reads the same whether a manager hit it by hand or a pump hit it in bulk, which is what lets a bilingual client branch and word it once. `code` is published on those two routes only and is simply **absent** from every other -error body. +error body — with one addition since the instance model: `linked_course_missing`, +which only a member add can meet, is published on that route. -**Removal spares what a human placed.** Every attachment a blueprint makes is +**Removal spares what a human placed.** Every instance a blueprint mints is tagged with it. Dropping a course from the list detaches it only where the -blueprint attached it (sweeping the enrollments it pumped, repairing to a rival -class first exactly as a manual detach does), and a course a human attached to +blueprint attached it — sweeping the enrollments it pumped, repairing to a rival +class first exactly as a manual detach does, and **unlinking the files** the +detached instances' exams, homework and submissions held (the sweep returns +their blob keys, and the route unlinks them the way a manual detach does) — and +a course a human attached to that class by hand carries no tag and is left exactly where it is. Deleting a -blueprint applies that to its whole list. +blueprint applies that to its whole list, and unlinks those files too. **Deleting the course itself takes it out of every template naming it**, in the same transaction that detaches it from the sections. A template holds its @@ -3687,7 +3774,8 @@ and pumps it while the delete runs would otherwise leave rows tagged with a blueprint that no longer exists, and since the grade label *is* the record id, nothing could ever reach them again. The pump carries the other half of that — an attach whose blueprint was deleted mid-run writes nothing and is reported as -`blueprint_deleted`. The attach's in-transaction claim is a `FOR KEY SHARE` +`blueprint_deleted`. The delete returns the swept subtree's blob keys and the +route unlinks them. The attach's in-transaction claim is a `FOR KEY SHARE` row lock on `class_blueprint` — the one strength a `DELETE` of the row cannot take — so a sourced attach that started first holds the row and the delete waits behind it; an attach starting after the delete finds no row @@ -3699,9 +3787,12 @@ recreated at the same grade with the same list satisfies that comparison, which is accepted, since the end state is the one the caller asked for. The remaining cost is a **process crash** between the delete and its sweep, which no lock survives: it leaves inert tagged attachments behind, still detachable one at a -time at `DELETE /classes/{id}/courses/{course}`, with every counter exact. +time at `DELETE /classes/{id}/instances/{instance}`, with every counter exact — +the crash window's files outlive their rows, which is the one leak the model +cannot close from here. -A blueprint names no term — the class names its own. The grade label is the +A blueprint names no year — the class names its own, and the year is what the +exam calendar hangs off. The grade label is the blueprint's id, so there is one per grade (a second is a `409`), and it must be non-empty and contain none of `/ \ ? # %`. @@ -3742,27 +3833,50 @@ curl -s -b $JAR $BASE/events/$EV/attendance -H 'content-type: application/json' -d '{"status":"present"}' curl -s -b $JAR $BASE/events/$EV/attendance -# courses + weighted marks (as a teacher) -# optional, manager+: weigh midterms triple — school policy, per kind -curl -s -b $JAR -X PATCH $BASE/settings -H 'content-type: application/json' \ - -d '{"exam_kinds":[{"name":"midterm","weight":3},{"name":"quiz","weight":1}]}' +# the academic calendar: a year, then a term inside it (manager+) +YR=$(curl -s -b $JAR $BASE/academic-years -H 'content-type: application/json' \ + -d '{"name":"2026-2027","starts_at":1788000000000,"ends_at":1811000000000}' \ + | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4) +TE=$(curl -s -b $JAR $BASE/terms -H 'content-type: application/json' \ + -d '{"name":"1. Dönem","year":"'$YR'","starts_at":1788000000000,"ends_at":1794000000000}' \ + | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4) + +# the class section: the academic anchor, in that year. Naming yourself as the +# homeroom teacher is what gives this teacher rights over its instances (D10) — +# a manager could assign an instance teacher afterwards instead. +ME=$(curl -s -b $JAR $BASE/users/me | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4) +CL=$(curl -s -b $JAR $BASE/classes -H 'content-type: application/json' \ + -d '{"name":"9-A","grade":"9","year":"'$YR'","teacher_id":"'$ME'"}' \ + | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4) + +# the catalog course, then the instance this section teaches it in +CO=$(curl -s -b $JAR $BASE/courses -H 'content-type: application/json' \ + -d '{"title":"Matematik"}' | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4) +IN=$(curl -s -b $JAR $BASE/classes/$CL/instances -H 'content-type: application/json' \ + -d '{"course_id":"'$CO'"}' | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4) +curl -s -b $JAR $BASE/instances/$IN # hours, karne weight, teachers + +# roster: adding a member to the section enrolls them into $IN (the pump); +# a teacher can also enroll one student by hand # find the student to enroll (here: a registered user "veli"): fragment # search over username/name, role-narrowed (teacher+) SID=$(curl -s -b $JAR "$BASE/users/search?q=vel&role=student" \ | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4) -CO=$(curl -s -b $JAR $BASE/courses -H 'content-type: application/json' \ - -d '{"title":"algebra"}' | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4) -curl -s -b $JAR $BASE/courses/$CO/enrollments -H 'content-type: application/json' \ +curl -s -b $JAR $BASE/classes/$CL/members -H 'content-type: application/json' \ -d "{\"user_id\":\"$SID\"}" -EX=$(curl -s -b $JAR $BASE/courses/$CO/exams -H 'content-type: application/json' \ - -d '{"title":"midterm","kind":"midterm"}' | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4) +curl -s -b $JAR $BASE/instances/$IN/enrollments # lists the pumped row + +# exams live on the instance and are filed in a dönem; weighted marks +EX=$(curl -s -b $JAR $BASE/instances/$IN/exams -H 'content-type: application/json' \ + -d '{"title":"1. Yazılı","kind":"yazili","term":"'$TE'"}' \ + | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4) curl -s -b $JAR $BASE/exams/$EX/results -H 'content-type: application/json' \ -d "{\"mark\":90,\"user_id\":\"$SID\"}" curl -s -b $JAR $BASE/exams/$EX/statistics -# lesson sessions + roll call (course manager creates; the session's teacher -# or a course manager marks enrolled students) -SE=$(curl -s -b $JAR $BASE/courses/$CO/sessions -H 'content-type: application/json' \ +# lesson sessions + roll call (instance teacher creates; the session's teacher +# or an instance manager marks the enrolled students) +SE=$(curl -s -b $JAR $BASE/instances/$IN/sessions -H 'content-type: application/json' \ -d '{"topic":"limits","starts_at":1900000000000}' | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4) curl -s -b $JAR $BASE/sessions/$SE/attendance -H 'content-type: application/json' \ -d "{\"status\":\"present\",\"user_id\":\"$SID\"}" @@ -3773,7 +3887,9 @@ curl -s -b $JAR -X POST $BASE/work/check-out curl -s -b $JAR $BASE/work/me # ...and as the student: +curl -s -b $STUDENT_JAR $BASE/instances/me # the sections' instances curl -s -b $STUDENT_JAR $BASE/marks/me +curl -s -b $STUDENT_JAR "$BASE/marks/karne?term=$TE" # the report card curl -s -b $STUDENT_JAR $BASE/attendance/me # pomodoro: start when the timer starts, finish when it rings curl -s -b $STUDENT_JAR -X POST $BASE/pomodoro/start @@ -4438,8 +4554,9 @@ which half of a class gets to draw. **Inviting a group discloses that group.** A board's roster is visible to every participant, so each source carries the gate its own listing route carries — -teacher+ for a class (`GET /classes/{id}/members`), the course's creator, an -assigned teacher or a manager+ for a course (`GET /courses/{id}/enrollments`), +teacher+ for a class (`GET /classes/{id}/members`), a manager+, one of the +instance's assigned teachers or its class's homeroom teacher for an instance +(`GET /instances/{id}/enrollments`), teacher+ for an event (`GET /events/{id}/roster`). A student may still build a board one id at a time; they cannot pour a class roster into one. A source that does not exist is a `400` naming the field, never a `404` — on these routes a @@ -4657,11 +4774,14 @@ database itself decides the winner. Three tiers: `INSERT … SELECT … WHERE EXISTS` behind a real `FOREIGN KEY` (the existence proofs), the CTE recipes in `db::cap`. Used where the rule reads the row being written (state machines, delete guards). - "Is anything still attached?" is answered the same way, by a counter on the + "Is anything still attached?" is answered the same way, by counters on the row being deleted rather than a `SELECT` over the children: a course is - deletable while its `enrollment_count` is zero, a term while its - `course_count` is (courses claim that reference *before* they write the - link, and give it back when the link moves or the course is deleted). A fee + deletable while its `class_course_count` **and** `course_membership_count` + are zero (a şube attach or a club/etüt join claims that reference *before* it + writes the link, and gives it back when the link moves or is deleted), and a + term while its `exam_count` is zero and no `karne_snapshot` names it — the + count is the fast path, the snapshot `NOT EXISTS` is the record a `DELETE` + must not take with it. A fee plan reads the same way — editable *and* deletable while its `assignment_count` is zero, and frozen for good once it is not, since an assignment is never taken back. @@ -4776,17 +4896,25 @@ src/ disk under FILES_PATH; FileName/FileContentType shared with note_file.rs) rag_output.rs RagOutputId · RagOutput (what an AI service produced for a course note; derived, disposable, cascaded from note and file) - course_session.rs CourseSessionId · SessionTopic · CourseSession (a course's lesson) + course_session.rs CourseSessionId · SessionTopic · CourseSession (an instance's lesson) session_attendance.rs SessionAttendanceId · SessionAttendance (roll call; one row per session+user) work_entry.rs WorkEntryId · WorkEntry (staff stint; one open per user by construction) - enrollment.rs EnrollmentId · Enrollment (one row per course+user; `source` + enrollment.rs EnrollmentId · Enrollment (one row per instance+student; `source` names the class that pumped it, absent when hand-placed) - class_group.rs ClassGroupId · ClassName · ClassGrade · ClassGroup (a class section; - deletable only with no members and no attached courses) - class_member.rs ClassMember (one student in a class; adding them enrolls - them into every course the class holds) - class_course.rs ClassCourse (one course on a class; attaching it enrolls - the class's whole roster) + course_membership.rs CourseMembershipId · CourseMembership (one row per + catalog course+user: the club/etüt join a student makes alone) + academic_year.rs AcademicYearId · GradePromotion · AcademicYear (the school + year: its terms, its sınıf geçme policy, its rollover) + class_group.rs ClassGroupId · ClassName · ClassGrade · ClassGroup (a class + section; belongs to an academic year; deletable only with no + live members and no instances) + class_member.rs ClassMemberId · ClassMember (one student's stint in a class; + `left_at` ends it — the row stays, the seat comes back, and a + re-add is a fresh row) + class_course.rs ClassCourseId · DersSaati · ClassCourse (the **instance**: + one course as one class teaches it — hours, karne weight, + teachers, roster, and the key every exam/session/homework + under it carries) class_blueprint.rs ClassBlueprintId · ClassBlueprint (a grade's course list; applying it stocks every section at that grade, best-effort) class_pump.rs attach/detach (the shared transaction behind both of those: @@ -4869,7 +4997,7 @@ src/ solution.rs SolutionId · SolutionBody · Solution (discussion thread on an approved pool question; dies with the question) homework.rs HomeworkId · HomeworkTitle · HomeworkDescription · Homework - (per-course assignment; required subject; optional `assigned` + (per-instance assignment; required subject; optional `assigned` student subset — absent/empty = the whole enrolled course) homework_submission.rs HomeworkSubmissionId · SubmissionText · HomeworkSubmission (one row per homework+user; immutable @@ -4914,7 +5042,7 @@ src/ images.rs · review.rs (prior sittings) bank_questions.rs marks.rs work.rs pomodoro.rs attendance.rs settings.rs terms.rs meals.rs payments.rs ai.rs chatbot.rs - boards.rs classes.rs + boards.rs classes.rs instances.rs academic_years.rs limits.rs GET /limits: every constant.rs bound served as JSON ``` diff --git a/migrations/school/20260916000001_k12_remodel.sql b/migrations/school/20260916000001_k12_remodel.sql new file mode 100644 index 0000000..9c18d5b --- /dev/null +++ b/migrations/school/20260916000001_k12_remodel.sql @@ -0,0 +1,457 @@ +-- School-database schema, part 5: the Turkish-K12 remodel — the class×course +-- *instance* (`class_course`) becomes the academic anchor. +-- +-- Before this migration `course` was a school-wide singleton and every +-- downstream row keyed off it (`enrollment (course, app_user)`, +-- `exam.course`, `course_session.course`, `session_attendance.course`, +-- `homework.course`), while `class_course` was a hollow join carrying only +-- (`class`, `course`, `attached_by`, `source`). Two şubeler attaching the +-- same course therefore shared one roster, one exam set and one timetable. +-- +-- After it: `class_course` is the instance (it carries the teachers, the +-- weekly `ders_saati` and the karne weight), exams/sessions/roll-call/ +-- homework/enrollment re-key onto it, a şube belongs to an `academic_year` +-- (a dönem is a grading slice inside the year), and `course` is a pure +-- catalog. +-- +-- Compatibility is waived (pre-customer): the identity-changing tables below +-- are dropped and recreated empty rather than backfilled, which keeps every +-- refcount seeded in this file consistent at 0. The drop list therefore also +-- includes the tables that merely *reference* a dropped one (bank_question, +-- question_image, answer_image, homework_assignment) so their foreign keys +-- are recreated instead of silently lost to CASCADE. +-- +-- Same translation rules as parts 1-4: entity ids are app-minted UUID v7 (no +-- DB default), timestamps stay BIGINT unix-ms, counter columns are BIGINT +-- NOT NULL DEFAULT 0 and stay out of the Rust structs, all FKs ON DELETE NO +-- ACTION. + +-- --------------------------------------------------------------------------- +-- 1. Academic year, above Term. +-- --------------------------------------------------------------------------- +CREATE TABLE academic_year ( + id uuid PRIMARY KEY, + name TEXT NOT NULL CONSTRAINT academic_year_name_key UNIQUE, + starts_at BIGINT NOT NULL, + ends_at BIGINT NOT NULL, + archived_at BIGINT NULL, + creator uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + -- Sınıf geçme policy: [{from_grade, to_grade}, …]. A grade absent from + -- this list is not rolled over — that is how graduation is expressed. + grade_promotions JSONB NOT NULL DEFAULT '[]', + class_count BIGINT NOT NULL DEFAULT 0, + term_count BIGINT NOT NULL DEFAULT 0 +); + +-- --------------------------------------------------------------------------- +-- 2. Backfill one default year, bind term to it, move the class counter and +-- drop the term's course counter (course.term is removed in §6). +-- --------------------------------------------------------------------------- +-- Only on a database that already has terms: a fresh one needs no synthetic +-- year, and `creator` is NOT NULL so the row needs a real app_user to name. +INSERT INTO academic_year (id, name, starts_at, ends_at, creator, grade_promotions) +SELECT '00000000-0000-0000-0000-000000000001', 'Varsayılan Eğitim Yılı', + COALESCE((SELECT min(starts_at) FROM term), 0), + COALESCE((SELECT max(ends_at) FROM term), 0), + (SELECT id FROM app_user ORDER BY created_at LIMIT 1), + '[]' +WHERE EXISTS (SELECT 1 FROM term); + +ALTER TABLE term ADD COLUMN year uuid REFERENCES academic_year(id) ON DELETE NO ACTION; +UPDATE term SET year = '00000000-0000-0000-0000-000000000001'; +ALTER TABLE term ALTER COLUMN year SET NOT NULL; + +-- The term now tracks how many exams sit in it; the class counter moves to +-- the academic year (§3) and the course counter had no referent. +ALTER TABLE term ADD COLUMN exam_count BIGINT NOT NULL DEFAULT 0; +ALTER TABLE term DROP COLUMN course_count; +ALTER TABLE term DROP COLUMN class_count; + +UPDATE academic_year SET term_count = (SELECT count(*) FROM term); + +-- --------------------------------------------------------------------------- +-- 3. Şube belongs to the year, not to a term. +-- --------------------------------------------------------------------------- +ALTER TABLE class_group ADD COLUMN year uuid REFERENCES academic_year(id) ON DELETE NO ACTION; +UPDATE class_group c SET year = t.year FROM term t WHERE t.id = c.term; +ALTER TABLE class_group DROP COLUMN term; + +UPDATE academic_year SET class_count = (SELECT count(*) FROM class_group WHERE year = academic_year.id); + +-- --------------------------------------------------------------------------- +-- 4. course is a pure catalog: no capacity, no seat count, no term. +-- --------------------------------------------------------------------------- +ALTER TABLE course DROP COLUMN capacity; +ALTER TABLE course DROP COLUMN enrollment_count; +ALTER TABLE course DROP COLUMN term; +ALTER TABLE course ADD COLUMN class_course_count BIGINT NOT NULL DEFAULT 0; +ALTER TABLE course ADD COLUMN course_membership_count BIGINT NOT NULL DEFAULT 0; + +-- --------------------------------------------------------------------------- +-- 5. Drop the identity-changing tables (and every table that references one), +-- then recreate them empty against the instance key. +-- --------------------------------------------------------------------------- +DROP TABLE IF EXISTS + exam_audience, + exam_answer, + answer_image, + exam_attempt, + exam_result, + question_image, + exam_question, + bank_question_image, + bank_question, + exam, + homework_assignment, + homework_file, + homework_submission, + homework_result, + homework, + session_attendance, + course_session, + enrollment, + course_membership, + class_course_teacher, + class_course, + class_member, + course_teacher +CASCADE; + +-- --------------------------------------------------------------------------- +-- 5b. The emptied tables leave phantom counts on the KEPT ones. +-- Every counter below lives on a table this migration keeps but counts rows +-- in a table that was just emptied. Left alone on a non-empty database, the +-- phantom blocks the guard that reads it: a class_group would refuse its own +-- `class_member_count = 0 AND class_course_count = 0` delete guard (and eat +-- MAX_CLASS_MEMBERS seats) over members that no longer exist, a subject would +-- refuse its delete over questions/homework that are gone, and a kind_ref +-- would refuse its kind's retirement over marks that went with exam_result. +-- Counters on columns this migration *adds* (`course.class_course_count`, +-- `course.course_membership_count`, `term.exam_count`) are not listed: they +-- are born with DEFAULT 0. +-- --------------------------------------------------------------------------- +UPDATE class_group SET class_member_count = 0, class_course_count = 0; +UPDATE subject SET exam_question_count = 0, homework_count = 0; +UPDATE kind_ref SET count = 0; + +-- The instance. It now carries the teachers (a junction), the weekly hours +-- and whether it counts toward the karne; `source` still marks blueprint vs +-- hand-placed. `enrollment_count` is the instance roster size — a counter, +-- not a capacity gate (the seat-claim 409 is deleted with D4/D5). +CREATE TABLE class_course ( + id uuid PRIMARY KEY, + class uuid NOT NULL REFERENCES class_group(id) ON DELETE NO ACTION, + course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION, + attached_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + source uuid NULL REFERENCES class_blueprint(id) ON DELETE NO ACTION, + ders_saati SMALLINT NOT NULL DEFAULT 1, + counts_toward_karne BOOLEAN NOT NULL DEFAULT TRUE, + enrollment_count BIGINT NOT NULL DEFAULT 0, + attached_at BIGINT NOT NULL, + CONSTRAINT class_course_class_course UNIQUE (class, course) +); + +CREATE INDEX class_course_course ON class_course (course); +CREATE INDEX class_course_class ON class_course (class); + +-- D6: teacher assignment moves off the catalog course onto the instance. +CREATE TABLE class_course_teacher ( + class_course uuid NOT NULL REFERENCES class_course(id) ON DELETE NO ACTION, + teacher uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + CONSTRAINT class_course_teacher_pk PRIMARY KEY (class_course, teacher) +); + +CREATE INDEX class_course_teacher_teacher ON class_course_teacher (teacher); + +-- D11: a history table with a surrogate id. `left_at` NULL is the live stint; +-- the partial unique index enforces one live stint per (class, user) pair +-- while preserving rejoin history. A soft-left row holds no seat, so the +-- roster read and MAX_CLASS_MEMBERS always filter on `left_at IS NULL`. +CREATE TABLE class_member ( + id uuid PRIMARY KEY, + class uuid NOT NULL REFERENCES class_group(id) ON DELETE NO ACTION, + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + added_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + joined_at BIGINT NOT NULL, + left_at BIGINT NULL, + source_class_group uuid NULL REFERENCES class_group(id) ON DELETE NO ACTION +); + +CREATE UNIQUE INDEX class_member_live_pair ON class_member (class, app_user) WHERE left_at IS NULL; +CREATE INDEX class_member_user ON class_member (app_user); + +-- D4: the roster is pumped per instance; individual (seçmeli) enrollment is +-- the same row shape, hand-placed (`source` NULL). +CREATE TABLE enrollment ( + class_course uuid NOT NULL REFERENCES class_course(id) ON DELETE NO ACTION, + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + enrolled_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + source uuid NULL REFERENCES class_group(id) ON DELETE NO ACTION, + created_at BIGINT NOT NULL, + CONSTRAINT enrollment_class_course_user PRIMARY KEY (class_course, app_user) +); + +-- D9: clubs/etüt are school-scoped memberships, not class-delivered. +CREATE TABLE course_membership ( + course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION, + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + added_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + created_at BIGINT NOT NULL, + CONSTRAINT course_membership_course_user PRIMARY KEY (course, app_user) +); + +-- Exam now hangs off the instance and the dönem it belongs to. +CREATE TABLE exam ( + id uuid PRIMARY KEY, + creator uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + class_course uuid NOT NULL REFERENCES class_course(id) ON DELETE NO ACTION, + term uuid NOT NULL REFERENCES term(id) ON DELETE NO ACTION, + title TEXT NOT NULL, + description TEXT NOT NULL, + kind TEXT NOT NULL, + mode TEXT NULL, + starts_at BIGINT NULL, + ends_at BIGINT NULL, + duration_ms BIGINT NULL, + max_attempts BIGINT NOT NULL, + allow_rejoin BOOLEAN NOT NULL, + allow_review BOOLEAN NOT NULL, + draft BOOLEAN NOT NULL, + result_count BIGINT NOT NULL DEFAULT 0 +); + +CREATE INDEX exam_class_course ON exam (class_course); +CREATE INDEX exam_term ON exam (term); + +-- The sitting instances of one exam. The owning instance always gets a row, +-- so every exam read is one path: JOIN exam_audience. +CREATE TABLE exam_audience ( + exam uuid NOT NULL REFERENCES exam(id) ON DELETE NO ACTION, + class_course uuid NOT NULL REFERENCES class_course(id) ON DELETE NO ACTION, + CONSTRAINT exam_audience_pk PRIMARY KEY (exam, class_course) +); + +-- --------------------------------------------------------------------------- +-- 6. Recreate the exam / question-bank subtree verbatim (no key change: it +-- keys on exam, which now carries the instance). +-- --------------------------------------------------------------------------- +CREATE TABLE bank_question ( + id uuid PRIMARY KEY, + owner uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + subject uuid NULL REFERENCES subject(id) ON DELETE NO ACTION, + text TEXT NOT NULL, + kind TEXT NOT NULL, + points BIGINT NOT NULL, + choices JSONB NULL, + correct TEXT NULL, + source_exam uuid NULL REFERENCES exam(id) ON DELETE NO ACTION, + visibility TEXT NOT NULL DEFAULT 'private', + created_at BIGINT NOT NULL +); + +CREATE INDEX bank_question_owner ON bank_question (owner); +CREATE INDEX bank_question_subject ON bank_question (subject); + +CREATE TABLE bank_question_image ( + bank_question uuid NOT NULL REFERENCES bank_question(id) ON DELETE NO ACTION, + slot TEXT NULL, + file TEXT NOT NULL, + content_type TEXT NOT NULL, + size BIGINT NOT NULL, + CONSTRAINT bank_question_image_question_slot UNIQUE NULLS NOT DISTINCT (bank_question, slot) +); + +CREATE TABLE exam_question ( + id uuid PRIMARY KEY, + exam uuid NOT NULL REFERENCES exam(id) ON DELETE NO ACTION, + text TEXT NOT NULL, + kind TEXT NOT NULL, + points BIGINT NOT NULL, + choices JSONB NULL, + correct TEXT NULL, + subject uuid NOT NULL REFERENCES subject(id) ON DELETE NO ACTION, + from_bank uuid NULL REFERENCES bank_question(id) ON DELETE NO ACTION, + banked_as uuid NULL REFERENCES bank_question(id) ON DELETE NO ACTION, + CONSTRAINT exam_question_id_exam UNIQUE (id, exam) +); + +CREATE INDEX exam_question_exam ON exam_question (exam); +CREATE INDEX exam_question_subject ON exam_question (subject); + +CREATE TABLE question_image ( + exam uuid NOT NULL, + question uuid NOT NULL, + slot TEXT NULL, + file TEXT NOT NULL, + content_type TEXT NOT NULL, + size BIGINT NOT NULL, + CONSTRAINT question_image_question_slot UNIQUE NULLS NOT DISTINCT (question, slot), + CONSTRAINT question_image_exam_question_fkey FOREIGN KEY (exam, question) + REFERENCES exam_question (exam, id) ON DELETE NO ACTION +); + +CREATE INDEX question_image_exam ON question_image (exam); +CREATE INDEX question_image_question ON question_image (question); + +CREATE TABLE exam_attempt ( + exam uuid NOT NULL REFERENCES exam(id) ON DELETE NO ACTION, + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + seq BIGINT NOT NULL DEFAULT 1, + started_at BIGINT NOT NULL, + finished_at BIGINT NULL, + left_at BIGINT NULL, + CONSTRAINT exam_attempt_exam_user_seq PRIMARY KEY (exam, app_user, seq) +); + +CREATE TABLE exam_answer ( + exam uuid NOT NULL, + question uuid NOT NULL, + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + selected TEXT NULL, + text TEXT NULL, + updated_at BIGINT NOT NULL, + seq BIGINT NOT NULL DEFAULT 1, + CONSTRAINT exam_answer_question_user_seq PRIMARY KEY (question, app_user, seq), + CONSTRAINT exam_answer_exam_question_fkey FOREIGN KEY (exam, question) + REFERENCES exam_question (exam, id) ON DELETE NO ACTION +); + +CREATE INDEX exam_answer_exam_user ON exam_answer (exam, app_user); + +CREATE TABLE answer_image ( + exam uuid NOT NULL, + question uuid NOT NULL, + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + file TEXT NOT NULL, + content_type TEXT NOT NULL, + size BIGINT NOT NULL, + seq BIGINT NOT NULL DEFAULT 1, + CONSTRAINT answer_image_question_user_seq PRIMARY KEY (question, app_user, seq), + CONSTRAINT answer_image_exam_question_fkey FOREIGN KEY (exam, question) + REFERENCES exam_question (exam, id) ON DELETE NO ACTION +); + +CREATE INDEX answer_image_exam ON answer_image (exam); +CREATE INDEX answer_image_user ON answer_image (app_user); + +CREATE TABLE exam_result ( + exam uuid NOT NULL REFERENCES exam(id) ON DELETE NO ACTION, + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + mark BIGINT NOT NULL, + graded_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + graded_at BIGINT NOT NULL, + seq BIGINT NOT NULL DEFAULT 1, + CONSTRAINT exam_result_exam_user_seq PRIMARY KEY (exam, app_user, seq) +); + +-- --------------------------------------------------------------------------- +-- 7. Sessions, roll-call and homework re-key onto the instance. +-- --------------------------------------------------------------------------- +CREATE TABLE course_session ( + id uuid PRIMARY KEY, + class_course uuid NOT NULL REFERENCES class_course(id) ON DELETE NO ACTION, + teacher uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + topic TEXT NOT NULL, + starts_at BIGINT NOT NULL, + ends_at BIGINT NULL, + held_counted_at BIGINT NULL +); + +CREATE INDEX course_session_class_course ON course_session (class_course); + +CREATE TABLE session_attendance ( + session uuid NOT NULL REFERENCES course_session(id) ON DELETE NO ACTION, + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + class_course uuid NOT NULL REFERENCES class_course(id) ON DELETE NO ACTION, + status TEXT NOT NULL, + marked_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + marked_at BIGINT NOT NULL, + CONSTRAINT session_attendance_session_user PRIMARY KEY (session, app_user) +); + +CREATE INDEX session_attendance_user ON session_attendance (app_user); +CREATE INDEX session_attendance_class_course ON session_attendance (class_course); + +CREATE TABLE homework ( + id uuid PRIMARY KEY, + class_course uuid NOT NULL REFERENCES class_course(id) ON DELETE NO ACTION, + subject uuid NOT NULL REFERENCES subject(id) ON DELETE NO ACTION, + title TEXT NOT NULL, + description TEXT NULL, + due_at BIGINT NOT NULL, + created_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + created_at BIGINT NOT NULL +); + +CREATE INDEX homework_class_course ON homework (class_course); + +CREATE TABLE homework_assignment ( + homework uuid NOT NULL REFERENCES homework(id) ON DELETE NO ACTION, + student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + CONSTRAINT homework_assignment_homework_student PRIMARY KEY (homework, student) +); + +CREATE INDEX homework_assignment_student ON homework_assignment (student); + +CREATE TABLE homework_result ( + id uuid PRIMARY KEY, + homework uuid NOT NULL REFERENCES homework(id) ON DELETE NO ACTION, + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + status TEXT NOT NULL, + mark BIGINT NULL, + graded_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + created_at BIGINT NOT NULL, + CONSTRAINT homework_result_homework_user UNIQUE (homework, app_user) +); + +CREATE INDEX homework_result_homework ON homework_result (homework); + +CREATE TABLE homework_submission ( + id uuid PRIMARY KEY, + homework uuid NOT NULL REFERENCES homework(id) ON DELETE NO ACTION, + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + text TEXT NULL, + submitted_at BIGINT NOT NULL, + updated_at BIGINT NOT NULL, + file_count BIGINT NOT NULL DEFAULT 0, + counted_on_time BOOLEAN NULL, + graded_by_result uuid NULL REFERENCES homework_result(id) ON DELETE NO ACTION, + CONSTRAINT homework_submission_homework_user UNIQUE (homework, app_user) +); + +CREATE INDEX homework_submission_homework ON homework_submission (homework); + +CREATE TABLE homework_file ( + id uuid PRIMARY KEY, + submission uuid NOT NULL REFERENCES homework_submission(id) ON DELETE NO ACTION, + name TEXT NOT NULL, + content_type TEXT NOT NULL, + size BIGINT NOT NULL, + file TEXT NOT NULL, + created_at BIGINT NOT NULL +); + +CREATE INDEX homework_file_submission ON homework_file (submission); + +-- --------------------------------------------------------------------------- +-- 8. Karne snapshot: the frozen per-student per-dönem report written when the +-- dönem is archived (karne is otherwise a computed read). +-- --------------------------------------------------------------------------- +CREATE TABLE karne_snapshot ( + term uuid NOT NULL REFERENCES term(id) ON DELETE NO ACTION, + app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + payload JSONB NOT NULL, + created_at BIGINT NOT NULL, + CONSTRAINT karne_snapshot_term_user PRIMARY KEY (term, app_user) +); + +-- --------------------------------------------------------------------------- +-- 9. Settings and profile additions (branş, absence limits, timezone). +-- --------------------------------------------------------------------------- +ALTER TABLE settings ADD COLUMN branches JSONB NULL; +ALTER TABLE settings ADD COLUMN excuse_kinds JSONB NULL; +ALTER TABLE settings ADD COLUMN max_excused_absent_days BIGINT NULL; +ALTER TABLE settings ADD COLUMN max_unexcused_absent_days BIGINT NULL; +ALTER TABLE settings ADD COLUMN timezone TEXT NULL; + +ALTER TABLE app_user ADD COLUMN branch TEXT NULL; diff --git a/src/config.rs b/src/config.rs index 462f9a9..e67ba1d 100644 --- a/src/config.rs +++ b/src/config.rs @@ -59,8 +59,9 @@ impl Config { Self { host: env::var("HOST").unwrap_or_else(|_| "127.0.0.1".into()), port: parse_port(env::var("PORT").ok()), - database_url: env::var("DATABASE_URL") - .unwrap_or_else(|_| "postgres://hezarfen:hezarfen@127.0.0.1:5432/hezarfen_control".into()), + database_url: env::var("DATABASE_URL").unwrap_or_else(|_| { + "postgres://hezarfen:hezarfen@127.0.0.1:5432/hezarfen_control".into() + }), files_path: env::var("FILES_PATH").unwrap_or_else(|_| "./data/files".into()), cookie_secure: parse_flag(env::var("COOKIE_SECURE").ok()), rate_limit: RateLimitConfig { diff --git a/src/constant.rs b/src/constant.rs index 1482754..7bd2304 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -135,6 +135,17 @@ pub const MAX_CLASS_GRADE_LEN: usize = 20; pub const MAX_CLASS_MEMBERS: i64 = 200; pub const MAX_CLASS_COURSES: i64 = 50; +/// Weekly lesson hours of a class×course instance (D8's karne weight). Bounded +/// so a typo cannot make one instance dominate the year average. +pub const MIN_DERS_SAATI: i64 = 1; +pub const MAX_DERS_SAATI: i64 = 40; + +/// The default grade-display bands: the Türkiye 5-point scale (85–100 = 5, +/// … 0–44 = 1). Schools edit the list via `PATCH /settings`; the karne verdict +/// reads the band labelled `"2"` as the pass boundary. +pub const DEFAULT_GRADE_BANDS: [(i64, &str); 5] = + [(85, "5"), (70, "4"), (55, "3"), (45, "2"), (0, "1")]; + pub const MAX_SUBJECT_NAME_LEN: usize = 200; pub const MAX_SUBJECT_DESCRIPTION_LEN: usize = 2_000; @@ -161,15 +172,9 @@ pub const MAX_SESSION_TOPIC_LEN: usize = 200; /// The default exam kinds with their weights; schools replace the list via /// `PATCH /settings`. An exam's kind decides how heavily it counts into the /// course average — the defaults all weigh 1 (a plain average) so weighting -/// is opt-in policy, not baked-in opinion. -pub const DEFAULT_EXAM_KINDS: [(&str, i64); 6] = [ - ("homework", 1), - ("quiz", 1), - ("midterm", 1), - ("final", 1), - ("project", 1), - ("oral", 1), -]; +/// is opt-in policy, not baked-in opinion. The defaults are the Turkish K12 +/// classroom's own: yazılı, sözlü, uygulama. +pub const DEFAULT_EXAM_KINDS: [(&str, i64); 3] = [("yazili", 1), ("sozlu", 1), ("uygulama", 1)]; /// Bounds for the school-editable lists in settings (exam kinds, attendance /// statuses): entry count and per-entry character length. @@ -189,6 +194,22 @@ pub const CAS_UPDATE_RETRIES: usize = 3; pub const MAX_TERM_NAME_LEN: usize = 100; +/// An academic year is named like a term ("2026-2027"). +pub const MAX_ACADEMIC_YEAR_NAME_LEN: usize = 100; + +/// The per-dönem devamsızlık limits a school may configure; a bound so a typo +/// cannot disable the rule or make it absurd. +pub const MAX_ABSENCE_DAYS: i64 = 365; + +/// The timezone a school's day-bucketing falls back to when none is set, and +/// the one the default deployment runs in. +pub const DEFAULT_TIMEZONE: &str = "Europe/Istanbul"; + +/// The timezones a school may configure. A short allow-list on purpose: the +/// backend has no timezone database of its own, and day-bucketing needs the +/// offset to be trustworthy. +pub const TIMEZONES: [&str; 2] = ["Europe/Istanbul", "UTC"]; + /// A published availability slot's optional note ("bring your report card"). pub const MAX_APPOINTMENT_NOTE_LEN: usize = 500; @@ -908,19 +929,14 @@ pub const SLOT_REF_TABLE: &str = "slot_ref"; /// SCHEMAFULL refusing the write. pub const ENROLLMENT_COUNT_FIELD: &str = "enrollment_count"; pub const REGISTRATION_COUNT_FIELD: &str = "registration_count"; -/// Not a cap — a refcount, and the whole of the term delete guard: how many -/// courses link this term. A term may only be dropped at zero, and the count -/// is claimed before a course's link is written, so the two decisions contend -/// on the term row instead of on a cross-table `SELECT` no transaction orders. -pub const COURSE_COUNT_FIELD: &str = "course_count"; /// The two refcounts on a class row: how many students it holds and how many /// courses it is attached to. A class may only be dropped at zero on both. pub const CLASS_MEMBER_COUNT_FIELD: &str = "class_member_count"; pub const CLASS_COURSE_COUNT_FIELD: &str = "class_course_count"; -/// Classes linking a term, the second half of the term delete guard. Deliberately -/// *not* `COURSE_COUNT_FIELD`: boot recounts that one from the course rows alone, -/// so a class claiming into it would be wiped on the next migration. -pub const TERM_CLASS_COUNT_FIELD: &str = "class_count"; +/// Classes belonging to an academic year, the second half of the year's delete +/// guard. Its own column: a class's share is never confused with another +/// roster's count. +pub const ACADEMIC_YEAR_CLASS_COUNT_FIELD: &str = "class_count"; /// A refcount too, and the whole of the fee-plan edit *and* delete guard: how /// many students are on this plan. A plan may only be edited or deleted at /// zero, and the count is claimed in the same transaction as the assignment diff --git a/src/db/academic_year.rs b/src/db/academic_year.rs new file mode 100644 index 0000000..15c8297 --- /dev/null +++ b/src/db/academic_year.rs @@ -0,0 +1,213 @@ +//! The `academic_year` table: the row mint, the paged calendar listing, the +//! field-scoped PATCH whose `WHERE` re-checks the merged range, and the 0/0 +//! delete guard. +//! +//! The year is the top of the academic calendar (D3): a şube belongs to a year +//! and a dönem ([`crate::db::term`]) is a grading slice inside it. Its two +//! counters are the delete guard — a year that still carries a şube or a dönem +//! is refused outright, because dropping it silently would strand the year's +//! structure. The rollover that reads and writes the şubeler lives one layer +//! up ([`crate::service::academic_year::rollover`]). + +use sqlx::types::Json; + +use crate::database::Database; +use crate::db::page::PagedList; +use crate::domain::academic_year::{ + AcademicYear, AcademicYearId, AcademicYearName, GradePromotion, +}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// Mint one year. The creator is a foreign key: a gone account is the same +/// `NotFound` the web layer's own read answers with, never an orphan row. +pub async fn create( + db: &Database, + creator: &UserId, + name: AcademicYearName, + starts_at: Timestamp, + ends_at: Timestamp, + grade_promotions: Vec, +) -> Result { + let promotions = Json(grade_promotions); + let created = sqlx::query_as!( + AcademicYear, + r#"INSERT INTO academic_year (id, name, starts_at, ends_at, creator, grade_promotions) + VALUES ($1, $2, $3, $4, $5, $6) + RETURNING id AS "id: AcademicYearId", name AS "name: AcademicYearName", + starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp", + archived_at AS "archived_at: Timestamp", creator AS "creator: UserId", + grade_promotions AS "grade_promotions: Json>", + class_count, term_count"#, + AcademicYearId::generate().uuid(), + name.as_str(), + starts_at.as_millis(), + ends_at.as_millis(), + creator.uuid(), + promotions as _, + ) + .fetch_one(db) + .await; + match created { + Ok(year) => Ok(year), + Err(err) if crate::database::foreign_key_violation(&err) => Err(AppError::NotFound), + // The name carries a UNIQUE constraint; a duplicate is a legacy-year + // naming clash. The web layer pre-checks it and answers 409 with a + // readable message, so reaching here is a race — reported as the same + // conflict rather than a 500. + Err(err) if crate::database::unique_violation(&err).is_some() => Err(AppError::Conflict( + "an academic year with that name already exists", + )), + Err(err) => Err(err.into()), + } +} + +pub async fn read(db: &Database, id: &AcademicYearId) -> Result, AppError> { + let year = sqlx::query_as!( + AcademicYear, + r#"SELECT id AS "id: AcademicYearId", name AS "name: AcademicYearName", + starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp", + archived_at AS "archived_at: Timestamp", creator AS "creator: UserId", + grade_promotions AS "grade_promotions: Json>", + class_count, term_count + FROM academic_year WHERE id = $1"#, + id.uuid(), + ) + .fetch_optional(db) + .await?; + Ok(year) +} + +/// Every year, newest first — the calendar is small by nature. +pub async fn list_all( + db: &Database, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new("academic_year", "ORDER BY starts_at DESC, id DESC") + .run::(limit, offset, db) + .await +} + +/// Write only the fields the PATCH carried — `None` means the request omitted +/// it, so the column keeps the value it holds rather than being re-stated from +/// the snapshot the handler read. Every column here is non-clearable, so +/// `COALESCE` is the whole rule: absent = keep. +/// +/// The merged range is re-checked by the `WHERE` (`ends_at > starts_at` on the +/// values this write will leave behind), so two PATCHes each moving one end +/// cannot commit an inverted year between them. `Err(NotFound)` when the row +/// is gone. +pub async fn update( + db: &Database, + id: &AcademicYearId, + name: Option, + starts_at: Option, + ends_at: Option, + grade_promotions: Option>, +) -> Result { + let promotions = grade_promotions.map(Json); + let starts_millis = starts_at.map(|at| at.as_millis()); + let ends_millis = ends_at.map(|at| at.as_millis()); + let updated = sqlx::query_as!( + AcademicYear, + r#"UPDATE academic_year + SET name = COALESCE($2, name), + starts_at = COALESCE($3, starts_at), + ends_at = COALESCE($4, ends_at), + grade_promotions = COALESCE($5, grade_promotions) + WHERE id = $1 + AND COALESCE($4, ends_at) > COALESCE($3, starts_at) + RETURNING id AS "id: AcademicYearId", name AS "name: AcademicYearName", + starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp", + archived_at AS "archived_at: Timestamp", creator AS "creator: UserId", + grade_promotions AS "grade_promotions: Json>", + class_count, term_count"#, + id.uuid(), + name.as_ref().map(AcademicYearName::as_str), + starts_millis, + ends_millis, + promotions as _, + ) + .fetch_optional(db) + .await?; + match updated { + Some(year) => Ok(year), + // Either the row is gone or the merged range is inverted — the same + // shape the caller's own pre-flight range check answers, one instant + // later. Only the refusal path pays for the read that tells them + // apart. + None => match read(db, id).await? { + Some(_) => Err(AppError::Validation( + crate::error::ValidationError::Invalid { + field: "ends_at", + reason: "must be after starts_at", + }, + )), + None => Err(AppError::NotFound), + }, + } +} + +/// Delete the year, but only while no şube and no dönem links it — nothing +/// here unlinks or cascades. `false` = refused, nothing was written. +/// +/// Both counts are read off the year's own row, so the check and the delete +/// are one conditional write on one record: a class or term write racing this +/// either claims first (and the delete is refused) or finds the row gone (and +/// is refused itself). The referencing foreign keys (`class_group.year`, +/// `term.year`, both `NO ACTION`) are the backstop behind the counters, not a +/// second guard. The `Err(NotFound)` keeps the answer a concurrent *delete* +/// used to get. +pub async fn delete(db: &Database, year: AcademicYear) -> Result { + let gone = sqlx::query!( + r#"DELETE FROM academic_year + WHERE id = $1 AND class_count = 0 AND term_count = 0"#, + year.get_id().uuid(), + ) + .execute(db) + .await?; + if gone.rows_affected() > 0 { + return Ok(true); + } + // Still linked or already gone: the one statement cannot tell those apart, + // and only the refusal path pays for the read that can. + match read(db, year.get_id()).await? { + Some(_) => Ok(false), + None => Err(AppError::NotFound), + } +} + +/// A real academic year for the fixtures of the tables that hang off one: a +/// dönem ([`crate::db::term::a_test_term`]) and, through it, every exam. Minted +/// per call — the name is unique — with a creator that is a real `app_user` +/// row, because `creator` is a foreign key. +#[cfg(test)] +pub(crate) async fn a_test_year(db: &Database) -> AcademicYearId { + let creator = UserId::generate(); + // The last six hex digits of the uuid, not a fixed-width byte range: a + // `key()` is 36 characters, so `[30..38]` — the range a `[30..]` suffix + // suggests — panics before the fixture ever reaches the store. + let suffix = &creator.key()[30..]; + sqlx::query( + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, 'manager')", + ) + .bind(creator.uuid()) + .bind(format!("year-fixture-{suffix}")) + .execute(db) + .await + .unwrap(); + let year = crate::db::academic_year::create( + db, + &creator, + AcademicYearName::try_new(&format!("year-{suffix}")).unwrap(), + Timestamp::from_millis(0), + Timestamp::from_millis(1), + Vec::new(), + ) + .await + .unwrap(); + *year.get_id() +} diff --git a/src/db/answer_image.rs b/src/db/answer_image.rs index 736a896..4774b2d 100644 --- a/src/db/answer_image.rs +++ b/src/db/answer_image.rs @@ -179,7 +179,9 @@ pub async fn file_keys_for_course( ) -> Result, AppError> { let rows = sqlx::query!( r#"SELECT ai.file FROM answer_image ai - JOIN exam e ON e.id = ai.exam WHERE e.course = $1"#, + JOIN exam e ON e.id = ai.exam + JOIN class_course cc ON cc.id = e.class_course + WHERE cc.course = $1"#, course.uuid(), ) .fetch_all(db) @@ -346,9 +348,12 @@ mod tests { let exam_b = exam_row(&db).await; let user = a_student(&db).await; let question = a_question(&db, &exam_a).await; - upsert(&db, AnswerImage::new(&exam_a, &question, &user, 1, png(), 1)) - .await - .unwrap(); + upsert( + &db, + AnswerImage::new(&exam_a, &question, &user, 1, png(), 1), + ) + .await + .unwrap(); assert_eq!( list_for_exam_user(&db, &exam_a, &user, 1) .await diff --git a/src/db/appointment.rs b/src/db/appointment.rs index ac7e579..d1dd943 100644 --- a/src/db/appointment.rs +++ b/src/db/appointment.rs @@ -9,12 +9,14 @@ use crate::database::{Database, tx_with_retry}; use crate::db::cap::Claimed; use crate::db::page::PagedList; -use crate::domain::appointment::{Appointment, AppointmentId, AppointmentReason, AppointmentStatus}; +use crate::domain::appointment::{ + Appointment, AppointmentId, AppointmentReason, AppointmentStatus, +}; use crate::domain::appointment_slot::AppointmentSlotId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; -use sqlx::{query, query_as, PgConnection, Postgres}; +use sqlx::{PgConnection, Postgres, query, query_as}; /// Is `[starts_at, ends_at)` already taken for either party? Both sides are /// checked: a teacher can't be in two meetings at once, and neither can a @@ -80,7 +82,10 @@ where })) } -pub(crate) async fn read_on<'e, E>(executor: E, id: &AppointmentId) -> Result, AppError> +pub(crate) async fn read_on<'e, E>( + executor: E, + id: &AppointmentId, +) -> Result, AppError> where E: sqlx::Executor<'e, Database = Postgres>, { @@ -103,10 +108,7 @@ where Ok(appointment) } -pub async fn read( - db: &Database, - id: &AppointmentId, -) -> Result, AppError> { +pub async fn read(db: &Database, id: &AppointmentId) -> Result, AppError> { read_on(db, id).await } diff --git a/src/db/appointment_slot.rs b/src/db/appointment_slot.rs index 424890f..a564697 100644 --- a/src/db/appointment_slot.rs +++ b/src/db/appointment_slot.rs @@ -138,7 +138,12 @@ pub async fn windows_in_span( .await?; Ok(rows .into_iter() - .map(|row| (Timestamp::from_millis(row.starts_at), Timestamp::from_millis(row.ends_at))) + .map(|row| { + ( + Timestamp::from_millis(row.starts_at), + Timestamp::from_millis(row.ends_at), + ) + }) .collect()) } diff --git a/src/db/badge.rs b/src/db/badge.rs index 495e9f9..ce289ae 100644 --- a/src/db/badge.rs +++ b/src/db/badge.rs @@ -111,7 +111,7 @@ pub async fn sync(db: &Database, user: &UserId) -> Result<(), AppError> { SET earned_at = badge_award.earned_at \ WHERE badge_award.earned_at IS NULL" ))) -.bind(user.uuid()) + .bind(user.uuid()) .bind(badge) .bind(now) .execute(db) diff --git a/src/db/bank_question.rs b/src/db/bank_question.rs index 59b16d4..cdc501b 100644 --- a/src/db/bank_question.rs +++ b/src/db/bank_question.rs @@ -589,11 +589,7 @@ mod tests { let (db, _leases) = crate::database::init_test_db().await; let owner = a_person(&db, "owner").await; let other = a_person(&db, "other").await; - async fn mine( - db: &Database, - owner: &UserId, - text: &str, - ) -> Result { + async fn mine(db: &Database, owner: &UserId, text: &str) -> Result { create( db, *owner, diff --git a/src/db/board.rs b/src/db/board.rs index 1102ef3..38a97bd 100644 --- a/src/db/board.rs +++ b/src/db/board.rs @@ -356,9 +356,12 @@ pub async fn close(db: &Database, board: &Board) -> Result { /// longer exists. pub async fn delete(db: &Database, board: Board) -> Result { tx_with_retry(db, true, async move |conn| { - sqlx::query!("DELETE FROM board_participant WHERE board = $1", board.id.uuid()) - .execute(&mut *conn) - .await?; + sqlx::query!( + "DELETE FROM board_participant WHERE board = $1", + board.id.uuid() + ) + .execute(&mut *conn) + .await?; sqlx::query!("DELETE FROM board_stroke WHERE board = $1", board.id.uuid()) .execute(&mut *conn) .await?; @@ -407,8 +410,7 @@ mod tests { #[tokio::test] async fn field_scoped_writes_return_the_row_and_a_gone_board_refuses() { let (db, _leases) = crate::database::init_test_db().await; - let creator = - crate::db::class_member::tests::fixture_user(&db, "board-creator").await; + let creator = crate::db::class_member::tests::fixture_user(&db, "board-creator").await; let board = create( &db, &creator, @@ -425,8 +427,7 @@ mod tests { let locked = set_locked(&db, &board, true, &creator).await.unwrap(); assert!(locked.is_locked()); - let member = - crate::db::class_member::tests::fixture_user(&db, "board-member").await; + let member = crate::db::class_member::tests::fixture_user(&db, "board-member").await; let roster = vec![member]; let re_rostered = set_participants(&db, &board, roster).await.unwrap(); assert_eq!(re_rostered.get_participants().len(), 1); @@ -440,8 +441,7 @@ mod tests { #[tokio::test] async fn the_cap_refuses_and_delete_releases_the_seat() { let (db, _leases) = crate::database::init_test_db().await; - let creator = - crate::db::class_member::tests::fixture_user(&db, "board-creator").await; + let creator = crate::db::class_member::tests::fixture_user(&db, "board-creator").await; for index in 0..MAX_BOARDS_PER_CREATOR { create( &db, diff --git a/src/db/cap.rs b/src/db/cap.rs index 488e147..4d1f6af 100644 --- a/src/db/cap.rs +++ b/src/db/cap.rs @@ -236,7 +236,12 @@ pub(crate) enum FullKind { /// guard/gone case, folds into [`FullKind::Hard`], whose contract already /// covers it. This is the old claim order (hard claim, guard attached, before /// the soft one) expressed as a re-read. -pub(crate) fn full_kind(soft_count: i64, soft_cap: i64, hard_count: i64, hard_cap: i64) -> FullKind { +pub(crate) fn full_kind( + soft_count: i64, + soft_cap: i64, + hard_count: i64, + hard_cap: i64, +) -> FullKind { if soft_count >= soft_cap && hard_count < hard_cap { FullKind::Soft } else { diff --git a/src/db/chatbot_thread.rs b/src/db/chatbot_thread.rs index 2bef1b2..ac703d9 100644 --- a/src/db/chatbot_thread.rs +++ b/src/db/chatbot_thread.rs @@ -205,14 +205,13 @@ mod tests { /// The owner's counter and the threads it counts, both re-read out of the /// store — never off a return value. async fn stored(db: &Database) -> (i64, usize) { - let counter = - sqlx::query("SELECT chatbot_thread_count FROM app_user WHERE id = $1") - .bind(UserId::from_key(U).uuid()) - .fetch_one(db) - .await - .unwrap() - .try_get::(0) - .unwrap(); + let counter = sqlx::query("SELECT chatbot_thread_count FROM app_user WHERE id = $1") + .bind(UserId::from_key(U).uuid()) + .fetch_one(db) + .await + .unwrap() + .try_get::(0) + .unwrap(); let rows = sqlx::query("SELECT count(*) FROM chatbot_thread") .fetch_one(db) .await diff --git a/src/db/class_blueprint.rs b/src/db/class_blueprint.rs index de63fa5..a3fb46f 100644 --- a/src/db/class_blueprint.rs +++ b/src/db/class_blueprint.rs @@ -375,9 +375,12 @@ async fn delete_claimed( if stored != held { return Ok(false); } - sqlx::query!(r#"DELETE FROM blueprint_course WHERE blueprint = $1"#, row.key) - .execute(&mut *tx) - .await?; + sqlx::query!( + r#"DELETE FROM blueprint_course WHERE blueprint = $1"#, + row.key + ) + .execute(&mut *tx) + .await?; sqlx::query!(r#"DELETE FROM class_blueprint WHERE id = $1"#, row.key) .execute(&mut *tx) .await?; @@ -533,13 +536,28 @@ pub async fn sourced_links( /// detached detached, each with its counter released and its enrollments /// swept, and the rest exactly as they were: a partial removal the next call /// finishes. +/// +/// Answers the **blob keys** every detach's cascade removed — the +/// question/answer images and homework files of each swept instance subtree — +/// for the caller's route to unlink after the commits. Each detach commits its +/// own transaction, so the keys of the rows already swept come back even when +/// a later link refuses ([`crate::db::class_pump::detach_course`] answers +/// `None` for a pair that held no instance, which contributes nothing); a +/// failure before a link's detach returns the Err and drops the keys gathered +/// so far, which is the same accepted window +/// [`crate::service::course::delete`] documents: at worst an unreachable blob. pub async fn drop_links( db: &Database, id: &ClassBlueprintId, links: Vec, -) -> Result<(), AppError> { +) -> Result, AppError> { + let mut blobs = Vec::new(); for link in links { - class_pump::detach_course(db, &link.class, &link.course, Some(id)).await?; + if let Some(keys) = + class_pump::detach_course(db, &link.class, &link.course, Some(id)).await? + { + blobs.extend(keys); + } } - Ok(()) + Ok(blobs) } diff --git a/src/db/class_course.rs b/src/db/class_course.rs index 1b492ec..22c06a0 100644 --- a/src/db/class_course.rs +++ b/src/db/class_course.rs @@ -1,19 +1,39 @@ //! The `class_course` table: the course-axis attach entry point and the -//! attachment listing. The refusals-to-errors policy and the detach that turns -//! a zero-row sweep into a 404 live in [`crate::service::class_course`]; the -//! transaction itself is the pump's, [`crate::db::class_pump`]. +//! instance reads behind `/instances`. The refusals-to-errors policy and the +//! detach that turns a zero-row sweep into a 404 live in +//! [`crate::service::class_course`]; the transaction itself is the pump's, +//! [`crate::db::class_pump`]. +//! +//! An instance is the academic anchor now: it carries the weekly hours +//! (`ders_saati`), whether it counts toward the karne, the roster counter and +//! its own teachers ([`crate::db::class_course_teacher`]). Reads speak the +//! *bare uuid* id of the instance; the (class, course) pair survives as the +//! UNIQUE key the attach gates on. use crate::constant::CLASS_COURSE_TABLE; use crate::database::Database; use crate::db::class_pump::Attached; use crate::db::page::PagedList; use crate::domain::class_blueprint::ClassBlueprintId; -use crate::domain::class_course::ClassCourse; +use crate::domain::class_course::{ClassCourse, ClassCourseId, DersSaati}; use crate::domain::class_group::ClassGroupId; use crate::domain::course::CourseId; +use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; +/// The projection every instance read shares. +/// +/// Two translations ride it: `source` is stored as the blueprint's surrogate +/// uuid while the domain speaks the grade label the API does (a hand attach, +/// source NULL, survives the LEFT JOIN as NULL), and `ders_saati` is a +/// `SMALLINT` column while [`DersSaati`] is an `i64` newtype — decoded +/// through a `bigint` cast so the type the driver checks is the one the +/// newtype names. +const INSTANCE_COLUMNS: &str = "cc.id, cc.class, cc.course, cc.attached_by, \ + b.grade AS source, cc.ders_saati::bigint AS ders_saati, \ + cc.counts_toward_karne, cc.enrollment_count, cc.attached_at"; + /// The attach itself, with the refusals left *unmapped*. /// /// A hand attach ([`crate::service::class_course::attach`]) turns each of them @@ -39,30 +59,183 @@ pub(crate) async fn attach_sourced( crate::db::class_pump::attach_course(db, class, course, attached_by, source).await } -/// The courses a class is attached to, newest first — by when they were -/// attached. The composite primary key is the tiebreaker (class, then course: -/// the two halves of the id this order used to sort), which makes the order -/// total. +/// The instances a class carries, newest first — by when they were attached, +/// the instance id breaking the tie (v7 ids sort in mint order, so the order +/// is total and reads as creation order within one instant). pub async fn list_for_class( db: &Database, class: &ClassGroupId, limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - // The stored `source` is the blueprint's surrogate uuid; the domain row - // speaks the grade label, so the projection joins it back (a hand attach, - // source NULL, survives the LEFT JOIN as NULL). PagedList::new( format!( - "(SELECT cc.class, cc.course, cc.attached_by, cc.attached_at, \ - b.grade AS source \ - FROM {CLASS_COURSE_TABLE} cc \ + "(SELECT {INSTANCE_COLUMNS} FROM {CLASS_COURSE_TABLE} cc \ LEFT JOIN class_blueprint b ON b.id = cc.source) \ AS {CLASS_COURSE_TABLE} WHERE class = $1" ), - "ORDER BY attached_at DESC NULLS LAST, class DESC, course DESC", + "ORDER BY attached_at DESC, id DESC", ) .bind(class.uuid()) .run(limit, offset, db) .await } + +/// The instances one catalog course is taught in, newest first — the read +/// behind "which şubeler run this course". +pub async fn list_for_course( + db: &Database, + course: &CourseId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new( + format!( + "(SELECT {INSTANCE_COLUMNS} FROM {CLASS_COURSE_TABLE} cc \ + LEFT JOIN class_blueprint b ON b.id = cc.source) \ + AS {CLASS_COURSE_TABLE} WHERE course = $1" + ), + "ORDER BY attached_at DESC, id DESC", + ) + .bind(course.uuid()) + .run(limit, offset, db) + .await +} + +/// Every instance held by any of `classes` (one query, unpaged) — the join +/// half of the class-layer reads that already hold class ids (a roster read, +/// a blueprint status diff). Ids that name no class are simply absent from +/// the result. +pub async fn list_for_class_ids( + db: &Database, + classes: &[ClassGroupId], +) -> Result, AppError> { + if classes.is_empty() { + return Ok(Vec::new()); + } + let ids: Vec = classes.iter().map(ClassGroupId::uuid).collect(); + let rows = sqlx::query_as!( + ClassCourse, + r#"SELECT cc.id AS "id: ClassCourseId", cc.class AS "class: ClassGroupId", + cc.course AS "course: CourseId", cc.attached_by AS "attached_by: UserId", + b.grade AS "source?: ClassBlueprintId", + cc.ders_saati::bigint AS "ders_saati!: DersSaati", + cc.counts_toward_karne, cc.enrollment_count, + cc.attached_at AS "attached_at: Timestamp" + FROM class_course cc + LEFT JOIN class_blueprint b ON b.id = cc.source + WHERE cc.class = ANY($1) + ORDER BY cc.attached_at DESC, cc.id DESC"#, + &ids, + ) + .fetch_all(db) + .await?; + Ok(rows) +} + +/// Load every instance behind `ids` (one query) — the join half of the reads +/// that already hold instance ids (a marks report's per-instance blocks). +pub async fn list_by_ids( + db: &Database, + ids: &[ClassCourseId], +) -> Result, AppError> { + if ids.is_empty() { + return Ok(Vec::new()); + } + let keys: Vec = ids.iter().map(ClassCourseId::uuid).collect(); + let rows = sqlx::query_as!( + ClassCourse, + r#"SELECT cc.id AS "id: ClassCourseId", cc.class AS "class: ClassGroupId", + cc.course AS "course: CourseId", cc.attached_by AS "attached_by: UserId", + b.grade AS "source?: ClassBlueprintId", + cc.ders_saati::bigint AS "ders_saati!: DersSaati", + cc.counts_toward_karne, cc.enrollment_count, + cc.attached_at AS "attached_at: Timestamp" + FROM class_course cc + LEFT JOIN class_blueprint b ON b.id = cc.source + WHERE cc.id = ANY($1) + ORDER BY cc.attached_at DESC, cc.id DESC"#, + &keys, + ) + .fetch_all(db) + .await?; + Ok(rows) +} + +/// One instance, or `None` when the id names no row. +pub async fn read(db: &Database, id: &ClassCourseId) -> Result, AppError> { + let row = sqlx::query_as!( + ClassCourse, + r#"SELECT cc.id AS "id: ClassCourseId", cc.class AS "class: ClassGroupId", + cc.course AS "course: CourseId", cc.attached_by AS "attached_by: UserId", + b.grade AS "source?: ClassBlueprintId", + cc.ders_saati::bigint AS "ders_saati!: DersSaati", + cc.counts_toward_karne, cc.enrollment_count, + cc.attached_at AS "attached_at: Timestamp" + FROM class_course cc + LEFT JOIN class_blueprint b ON b.id = cc.source + WHERE cc.id = $1"#, + id.uuid(), + ) + .fetch_optional(db) + .await?; + Ok(row) +} + +/// The class this instance belongs to, or `None` when the id names no row — +/// the seam every instance-scoped route reads the şube (and, through it, the +/// year) off. +pub async fn class_of(db: &Database, id: &ClassCourseId) -> Result, AppError> { + let row = sqlx::query!( + r#"SELECT class AS "class: ClassGroupId" FROM class_course WHERE id = $1"#, + id.uuid(), + ) + .fetch_optional(db) + .await?; + Ok(row.map(|row| row.class)) +} + +/// Write only the fields the PATCH carried — `None` means the request omitted +/// it, so the column keeps the value it holds rather than being re-stated +/// from the snapshot the handler read. Both fields are non-clearable, so +/// `COALESCE` is the whole rule: absent = keep the stored value. +/// +/// No counter moves and no compare-and-set is needed: neither field is +/// refcounted, and each is an independent scalar, so two PATCHes touching +/// different ones cannot revert each other. `Err(NotFound)` when the instance +/// is gone — the same answer the caller's own read gives one instant earlier. +pub async fn update( + db: &Database, + id: &ClassCourseId, + staff: Option, + counts: Option, +) -> Result { + // `i64`, cast down by the statement itself: the column is a `SMALLINT` + // and the newtype wraps an `i64`, so naming both types explicitly is what + // keeps the driver's type check honest in either direction. + let hours = staff.map(|hours| hours.as_i64()); + let row = sqlx::query_as!( + ClassCourse, + r#"WITH updated AS ( + UPDATE class_course + SET ders_saati = COALESCE($2::bigint, ders_saati::bigint)::smallint, + counts_toward_karne = COALESCE($3, counts_toward_karne) + WHERE id = $1 + RETURNING *) + SELECT u.id AS "id: ClassCourseId", u.class AS "class: ClassGroupId", + u.course AS "course: CourseId", u.attached_by AS "attached_by: UserId", + b.grade AS "source?: ClassBlueprintId", + u.ders_saati::bigint AS "ders_saati!: DersSaati", + u.counts_toward_karne, u.enrollment_count, + u.attached_at AS "attached_at: Timestamp" + FROM updated u + LEFT JOIN class_blueprint b ON b.id = u.source"#, + id.uuid(), + hours, + counts, + ) + .fetch_optional(db) + .await? + .ok_or(AppError::NotFound)?; + Ok(row) +} diff --git a/src/db/class_course_teacher.rs b/src/db/class_course_teacher.rs new file mode 100644 index 0000000..974f43a --- /dev/null +++ b/src/db/class_course_teacher.rs @@ -0,0 +1,139 @@ +//! The `class_course_teacher` junction: who teaches one instance. +//! +//! D6 moved teacher assignment off the catalog course and onto the instance — +//! two şubeler teaching the same course may legitimately have different +//! teachers — so this is the table every instance-membership gate reads +//! ([`crate::service::class_course::ensure_instance_teacher`]) and the one the +//! demotion sweep strips ([`crate::db::user::set_role_cascade`]). +//! +//! The shape is the `course_teacher` junction's, keyed on the instance: +//! assignment is an idempotent `INSERT` whose `(class_course, teacher)` key +//! answers a duplicate with `DO NOTHING`, so two requests naming the same +//! teacher at once land one row. + +use crate::database::{Database, foreign_key_violation}; +use crate::domain::class_course::{ClassCourse, ClassCourseId}; +use crate::domain::user::UserId; +use crate::error::AppError; + +use std::collections::HashMap; + +/// Assign `teacher` to teach this instance. `false` when they already did +/// (assignment is idempotent, so a repeat is a no-op rather than an error); +/// `Err(NotFound)` when the instance is gone — the same answer the caller's +/// own read gives one instant earlier. +pub async fn assign( + db: &Database, + instance: &ClassCourseId, + teacher: &UserId, +) -> Result { + let written = match sqlx::query!( + r#"INSERT INTO class_course_teacher (class_course, teacher) + SELECT $1, $2 WHERE EXISTS (SELECT 1 FROM class_course WHERE id = $1) + ON CONFLICT DO NOTHING"#, + instance.uuid(), + teacher.uuid(), + ) + .execute(db) + .await + { + Ok(result) => result.rows_affected(), + // The teacher row (or the instance) vanished mid-write: a foreign key + // answers, and a gone target is the `NotFound` the read below gives. + Err(e) if foreign_key_violation(&e) => return Err(AppError::NotFound), + Err(e) => return Err(e.into()), + }; + if written == 0 + && crate::db::class_course::class_of(db, instance) + .await? + .is_none() + { + // Zero rows and no instance: the conditional select matched nothing, + // rather than the pair already holding its row. + return Err(AppError::NotFound); + } + Ok(written > 0) +} + +/// Drop `teacher` from this instance. `false` when they were not assigned to +/// it, so the web layer can answer 404 instead of pretending it removed +/// someone. +pub async fn unassign( + db: &Database, + instance: &ClassCourseId, + teacher: &UserId, +) -> Result { + let deleted = sqlx::query!( + r#"DELETE FROM class_course_teacher WHERE class_course = $1 AND teacher = $2"#, + instance.uuid(), + teacher.uuid(), + ) + .execute(db) + .await?; + Ok(deleted.rows_affected() > 0) +} + +/// Strip `user` from every instance they were assigned to — the sweep for a +/// user demoted below `teacher`, who may no longer run anything. +pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), AppError> { + sqlx::query!( + r#"DELETE FROM class_course_teacher WHERE teacher = $1"#, + user.uuid(), + ) + .execute(db) + .await?; + Ok(()) +} + +/// The teachers of one instance, by uuid — the read behind a single +/// `/instances/{id}` response. +pub async fn list_for_instance( + db: &Database, + instance: &ClassCourseId, +) -> Result, AppError> { + let rows = sqlx::query!( + r#"SELECT teacher AS "teacher: UserId" FROM class_course_teacher + WHERE class_course = $1 ORDER BY teacher"#, + instance.uuid(), + ) + .fetch_all(db) + .await?; + Ok(rows.into_iter().map(|row| row.teacher).collect()) +} + +/// Assemble `(instance, teachers)` pairs out of a batch of instance reads: +/// one `class_course_teacher` query for the whole batch, so a page of `n` +/// instances costs one extra statement rather than `n`. An instance nobody is +/// assigned to reads an empty list, the shape +/// [`crate::db::course`]'s old `into_courses` gave a course. +pub async fn into_instances( + db: &Database, + rows: Vec, +) -> Result)>, AppError> { + if rows.is_empty() { + return Ok(Vec::new()); + } + let ids: Vec = rows.iter().map(|row| row.get_id().uuid()).collect(); + let links = sqlx::query!( + r#"SELECT class_course AS "class_course: ClassCourseId", teacher AS "teacher: UserId" + FROM class_course_teacher WHERE class_course = ANY($1) + ORDER BY class_course, teacher"#, + &ids, + ) + .fetch_all(db) + .await?; + let mut by_instance: HashMap> = HashMap::new(); + for link in links { + by_instance + .entry(link.class_course.uuid()) + .or_default() + .push(link.teacher); + } + Ok(rows + .into_iter() + .map(|row| { + let teachers = by_instance.remove(&row.get_id().uuid()).unwrap_or_default(); + (row, teachers) + }) + .collect()) +} diff --git a/src/db/class_group.rs b/src/db/class_group.rs index f7b9bb7..1fa7ce7 100644 --- a/src/db/class_group.rs +++ b/src/db/class_group.rs @@ -1,50 +1,75 @@ -//! The `class_group` table: the row, its term reference claimed through the -//! [`crate::db::cap`] shapes in the same statement as the link, and the 0/0 -//! delete guard. The archived-term guard and the route-facing wrappers live in -//! [`crate::service::class_group`]. +//! The `class_group` table: the row, its academic-year reference claimed +//! through the [`crate::db::cap`] shapes in the same statement as the link, +//! and the 0/0 delete guard. The archived-year guard and the route-facing +//! wrappers live in [`crate::service::class_group`]. -use crate::constant::{CLASS_GROUP_TABLE, TERM_CLASS_COUNT_FIELD}; +use crate::constant::{ACADEMIC_YEAR_CLASS_COUNT_FIELD, CLASS_GROUP_TABLE}; use crate::database::{Database, tx_with_retry}; use crate::db::field_update::{FieldUpdate, Refcount}; use crate::db::page::PagedList; +use crate::domain::academic_year::AcademicYearId; use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId, ClassName}; -use crate::domain::term::{self, TermId}; use crate::domain::user::UserId; -use crate::error::AppError; - -/// Create the class, claiming a reference on the term it links (if any) in -/// the *same statement* as the row, exactly as -/// [`crate::db::course::create`] does: the claim is a -/// conditional write on the term row, so it fails when the term is already -/// gone, it makes the term undeletable the instant this link exists, and — the -/// claim and the insert being one CTE — no crash and no refused claim can -/// leave either half without the other. +use crate::error::{AppError, ValidationError}; + +/// The refusal a şube write naming a year that is not there gets — the mirror +/// of [`crate::domain::term::gone_error`], one layer up the calendar. +fn year_gone() -> AppError { + AppError::Validation(ValidationError::Invalid { + field: "year", + reason: "academic year does not exist", + }) +} + +/// What a PATCH's `year` field owes the refcounts: the year to claim and the +/// one to give back. Covers all three moves — set (none→some), move +/// (some→other) and clear (some→none) — and moves nothing for a PATCH that +/// omitted the field or re-stated the link it already had. The same shape +/// [`crate::domain::term::ref_move`] gives the term link. +fn year_ref_move( + current: Option<&AcademicYearId>, + patch: &Option>, +) -> (Option, Option) { + match patch { + None => (None, None), + Some(next) if next.as_ref() == current => (None, None), + Some(next) => (*next, current.copied()), + } +} + +/// Create the class, claiming a reference on the academic year it links (if +/// any) in the *same statement* as the row, exactly as +/// [`crate::db::course::create`] did for the term: the claim is a conditional +/// write on the year row, so it fails when the year is already gone, it makes +/// the year undeletable the instant this link exists, and — the claim and the +/// insert being one CTE — no crash and no refused claim can leave either half +/// without the other. pub async fn create( db: &Database, creator: &UserId, name: ClassName, grade: Option, - term: Option, + year: Option, teacher: Option, ) -> Result { let id = ClassGroupId::generate(); - match &term { - Some(term) => { + match &year { + Some(year) => { // The claim and the insert are one statement: atomic without an // explicit transaction, exactly like every other // single-statement guard. let written = sqlx::query_as!( ClassGroup, r#"WITH seat AS ( - UPDATE term SET class_count = class_count + 1 + UPDATE academic_year SET class_count = class_count + 1 WHERE id = $1 RETURNING 1) - INSERT INTO class_group (id, creator, name, grade, term, teacher) + INSERT INTO class_group (id, creator, name, grade, year, teacher) SELECT $2, $3, $4, $5, $1, $6 WHERE EXISTS (SELECT 1 FROM seat) RETURNING id AS "id: ClassGroupId", creator AS "creator: UserId", name AS "name: ClassName", grade AS "grade: ClassGrade", - term AS "term: TermId", teacher AS "teacher: UserId""#, - term.uuid(), + year AS "year: AcademicYearId", teacher AS "teacher: UserId""#, + year.uuid(), id.uuid(), creator.uuid(), name.as_str(), @@ -56,12 +81,12 @@ pub async fn create( match written { Ok(Some(created)) => Ok(created), // Uncapped, so a zero-row claim can only mean the conditional - // write matched no term row at all — the claim doubles as the + // write matched no year row at all — the claim doubles as the // existence check. - Ok(None) => Err(term::gone_error()), - // The term row is locked by the claim's own UPDATE, so this + Ok(None) => Err(year_gone()), + // The year row is locked by the claim's own UPDATE, so this // is unreachable; a defensible answer beats a 500. - Err(e) if crate::database::foreign_key_violation(&e) => Err(term::gone_error()), + Err(e) if crate::database::foreign_key_violation(&e) => Err(year_gone()), // Unreachable: the id was minted one line above. Err(e) if crate::database::unique_violation(&e).is_some() => { Err(AppError::Internal("failed to create class".into())) @@ -72,16 +97,16 @@ pub async fn create( None => { let created = sqlx::query_as!( ClassGroup, - r#"INSERT INTO class_group (id, creator, name, grade, term, teacher) + r#"INSERT INTO class_group (id, creator, name, grade, year, teacher) VALUES ($1, $2, $3, $4, $5, $6) RETURNING id AS "id: ClassGroupId", creator AS "creator: UserId", name AS "name: ClassName", grade AS "grade: ClassGrade", - term AS "term: TermId", teacher AS "teacher: UserId""#, + year AS "year: AcademicYearId", teacher AS "teacher: UserId""#, id.uuid(), creator.uuid(), name.as_str(), grade.as_ref().map(ClassGrade::as_str), - term.as_ref().map(TermId::uuid), + year.as_ref().map(AcademicYearId::uuid), teacher.as_ref().map(UserId::uuid) ) .fetch_optional(db) @@ -97,7 +122,7 @@ pub async fn read(db: &Database, id: &ClassGroupId) -> Result ClassGroup, r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId", name AS "name: ClassName", grade AS "grade: ClassGrade", - term AS "term: TermId", teacher AS "teacher: UserId" + year AS "year: AcademicYearId", teacher AS "teacher: UserId" FROM class_group WHERE id = $1"#, id.uuid() ) @@ -137,45 +162,45 @@ pub async fn list_all( /// Write only the fields the PATCH carried — `None` means the request /// omitted it, so the column is left alone rather than re-stated from the -/// snapshot this struct was read into. `grade`, `term` and `teacher` are +/// snapshot this struct was read into. `grade`, `year` and `teacher` are /// nullable, so they take the outer/inner `Option>`: `None` = /// omitted (keep), `Some(None)` = clear. /// -/// A term move claims the new term and releases the old one inside the very +/// A year move claims the new year and releases the old one inside the very /// transaction that moves the link, exactly as in -/// [`crate::db::course::update`]: both counters and the link -/// commit together, so no crash can strand a count on a term nothing links. +/// [`crate::db::course::update`] did for the term: both counters and the link +/// commit together, so no crash can strand a count on a year nothing links. pub async fn update( db: &Database, class: ClassGroup, name: Option, grade: Option>, - term: Option>, + year: Option>, teacher: Option>, ) -> Result { - let (claim, release) = term::ref_move(class.term.as_ref(), &term); - let expected = class.term.as_ref().map(TermId::uuid); + let (claim, release) = year_ref_move(class.year.as_ref(), &year); + let expected = class.year.as_ref().map(AcademicYearId::uuid); FieldUpdate::new(CLASS_GROUP_TABLE, class.id.uuid()) .set("name", name.map(|name| name.as_str().to_string())) .set( "grade", grade.map(|grade| grade.map(|grade| grade.as_str().to_string())), ) - .set("term", term.map(|term| term.map(|term| term.uuid()))) + .set("year", year.map(|year| year.map(|year| year.uuid()))) // Not refcounted: a homeroom assignment is a label, so it rides the - // plain `set` path and never arms the term CAS. + // plain `set` path and never arms the year CAS. .set( "teacher", teacher.map(|teacher| teacher.map(|teacher| teacher.uuid())), ) .refcount(Refcount { - counter_table: "term", - counter_field: TERM_CLASS_COUNT_FIELD, - link: "term", + counter_table: "academic_year", + counter_field: ACADEMIC_YEAR_CLASS_COUNT_FIELD, + link: "year", expected, - claim: claim.map(|term| term.uuid()), - release: release.map(|term| term.uuid()), - refused: term::gone_error(), + claim: claim.map(|year| year.uuid()), + release: release.map(|year| year.uuid()), + refused: year_gone(), }) .run::(db) .await @@ -194,7 +219,7 @@ pub async fn list_by_ids(db: &Database, ids: &[ClassGroupId]) -> Result Result, AppError> { + let classes = sqlx::query_as!( + ClassGroup, + r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId", + name AS "name: ClassName", grade AS "grade: ClassGrade", + year AS "year: AcademicYearId", teacher AS "teacher: UserId" + FROM class_group WHERE year = $1 ORDER BY id"#, + year.uuid() + ) + .fetch_all(db) + .await?; + Ok(classes) +} + +/// Every class `user` is the homeroom teacher (sınıf öğretmeni) of, newest +/// first — the same order [`list_all`] gives, since this is a narrowing of +/// that list and not a second one. +/// +/// It is the read behind "which şubeler do I run": the homeroom teacher of a +/// section may act on every instance of it (D10, the third arm of +/// [`crate::service::class_course::ensure_instance_teacher`]) without being a +/// member of it or assigned to the instance — and without a read like this the +/// section would be invisible to them, so their own instances' exams, +/// sessions and homework could not be listed at all. +/// +/// Unpaged like [`list_for_grade`] and [`list_for_year`]: the caller resolves +/// a *visible set*, and a page would silently hide the sections past the +/// window. A user who homerooms nothing — including one every sweep has +/// cleared (`unassign_everywhere`) — simply gets an empty list. +pub async fn list_for_teacher(db: &Database, user: &UserId) -> Result, AppError> { + let classes = sqlx::query_as!( + ClassGroup, + r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId", + name AS "name: ClassName", grade AS "grade: ClassGrade", + year AS "year: AcademicYearId", teacher AS "teacher: UserId" + FROM class_group WHERE teacher = $1 ORDER BY id DESC"#, + user.uuid() + ) + .fetch_all(db) + .await?; + Ok(classes) +} + /// Clear the homeroom teacher everywhere `user` held one — the /// sweep for a user demoted below `teacher`, who may no longer hold one. /// The mirror of [`crate::db::course::unassign_everywhere`]; @@ -237,20 +311,49 @@ pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), App Ok(()) } -/// Delete the class and give its term reference back. Nothing else cascades: -/// a class that still holds students or courses is refused outright, because -/// dropping it silently would leave the enrollments it pumped behind with -/// nothing left to sweep them. An event aimed at the class keeps standing -/// with `audience_class` cleared — the course twin's documented outcome +/// Delete the class and give its academic-year reference back. A class that +/// still holds students or courses is refused outright, because dropping it +/// silently would leave the enrollments it pumped behind with nothing left to +/// sweep them. What the guard cannot see is the *history* standing beside the +/// live rows, and that is what this delete sweeps first: every `class_member` +/// stint of the class (a soft-left student holds no seat, so the 0/0 guard +/// passes while their row still stands, and `class_member.class` would refuse +/// the delete as a `23503`), plus the provenance tags naming it from rows that +/// outlive it — a rollover copy's `source_class_group` and a handed-over +/// enrollment's `source`, both hard foreign keys into this table. Dropping a +/// şube takes its own history with it; a row that merely *remembers* the şube +/// keeps standing, untagged. An event aimed at the class keeps standing with +/// `audience_class` cleared — the course twin's documented outcome /// (`db::course::delete`): the roster resolves live, so it simply reads empty. /// -/// `false` = refused, nothing was written. Both counts are read off the -/// class's own row, so the check and the delete are one conditional write on -/// one record — a member or attach racing this either claims first (and the -/// delete is refused) or finds the row gone (and is refused itself). The -/// `Err(NotFound)` keeps the answer a concurrent *delete* used to get. +/// `false` = refused, nothing was written — not even the sweeps below. The +/// guard locks the class row (`FOR UPDATE`) and reads its own two counters, so +/// a member or an attach racing this either claims first (and the delete is +/// refused, untouched) or finds the row gone (and is refused itself). +/// `Err(NotFound)` keeps the answer a concurrent *delete* used to get — and +/// unlike the old one-statement guard, this one tells the two apart without a +/// second read. The row lock is what makes the sweeps safe to run before the +/// final delete: no counter can move under this transaction, so the verdict +/// this read settled is still the verdict when the children are gone. pub async fn delete(db: &Database, class: ClassGroup) -> Result { tx_with_retry(db, false, async move |tx| { + // The guard and the lock, in one read — the shape + // [`crate::db::course::delete`] uses. A refused delete must leave the + // class's history exactly as it found it, so nothing may be swept + // until this verdict is in. + let guard = sqlx::query!( + r#"SELECT class_member_count, class_course_count, year AS "year: uuid::Uuid" + FROM class_group WHERE id = $1 FOR UPDATE"#, + class.id.uuid() + ) + .fetch_optional(&mut *tx) + .await?; + let Some(guard) = guard else { + return Err(AppError::NotFound); + }; + if guard.class_member_count != 0 || guard.class_course_count != 0 { + return Ok(false); + } // Events aimed at this class keep standing, audience cleared — the // hard FK on `event.audience_class` would otherwise refuse the delete // outright, and a dangling audience resolves to an empty roster. @@ -260,37 +363,45 @@ pub async fn delete(db: &Database, class: ClassGroup) -> Result ) .execute(&mut *tx) .await?; - let gone = sqlx::query!( - r#"DELETE FROM class_group - WHERE id = $1 - AND class_member_count = 0 AND class_course_count = 0 - RETURNING term AS "term: uuid::Uuid""#, + // The roster history goes with the şube. The 0/0 guard counts *live* + // stints, so a class whose last student soft-left passes it with the + // history row still standing — and `class_member.class` is a hard + // foreign key, which would answer the delete below as a `23503`. + sqlx::query!( + r#"DELETE FROM class_member WHERE class = $1"#, class.id.uuid() ) - .fetch_optional(&mut *tx) + .execute(&mut *tx) .await?; - let Some(row) = gone else { - // Still linked or already gone: the guard cannot tell those - // apart, and only the refusal path pays for the extra read that - // can. - let standing = sqlx::query_scalar!( - r#"SELECT 1 AS "one" FROM class_group WHERE id = $1"#, - class.id.uuid() - ) - .fetch_optional(&mut *tx) - .await? - .is_some(); - return if standing { - Ok(false) - } else { - Err(AppError::NotFound) - }; - }; - if let Some(term) = row.term { + // …and the same key from the *other* side: a stint another şube holds + // remembers where it came from (a rollover copy's `source_class_group`) + // and an enrollment a class wrote remembers which class pumped it + // (its `source`). Both are hard keys into this row, so both would + // refuse the delete. The rows outlive the şube and stay; only the tag + // goes. + sqlx::query!( + r#"UPDATE class_member SET source_class_group = NULL WHERE source_class_group = $1"#, + class.id.uuid() + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + r#"UPDATE enrollment SET source = NULL WHERE source = $1"#, + class.id.uuid() + ) + .execute(&mut *tx) + .await?; + // Last, and FK-silent: every child row whose key names this class is + // either taken or untagged by now. + sqlx::query!(r#"DELETE FROM class_group WHERE id = $1"#, class.id.uuid()) + .execute(&mut *tx) + .await?; + if let Some(year) = guard.year { sqlx::query!( - r#"UPDATE term SET class_count = GREATEST(class_count - 1, 0) - WHERE id = $1"#, - term + r#"UPDATE academic_year + SET class_count = GREATEST(class_count - 1, 0) + WHERE id = $1"#, + year ) .execute(&mut *tx) .await?; @@ -305,7 +416,7 @@ mod tests { use super::*; use sqlx::Row as _; - use crate::domain::term::{Term, TermName}; + use crate::domain::academic_year::{AcademicYear, AcademicYearName}; /// A real `app_user` row: creator, teacher, and attached-by are foreign /// keys now, so every fixture participant is a row, not a fabricated id. @@ -321,32 +432,47 @@ mod tests { .execute(db) .await .unwrap(); - let id: uuid::Uuid = - sqlx::query("SELECT id FROM app_user WHERE username = $1") - .bind(username) - .fetch_one(db) - .await - .unwrap() - .try_get(0) - .unwrap(); + let id: uuid::Uuid = sqlx::query("SELECT id FROM app_user WHERE username = $1") + .bind(username) + .fetch_one(db) + .await + .unwrap() + .try_get(0) + .unwrap(); UserId::from_key(&id.to_string()) } - async fn class_on(term: Option, db: &Database) -> ClassGroup { + /// A real academic year: the şube's year link is a foreign key now, and + /// the class-count claim it carries is what these tests are about. + async fn a_year(name: &str, db: &Database) -> AcademicYear { + let at = crate::domain::timestamp::Timestamp::from_millis; + crate::db::academic_year::create( + db, + &a_named_user(db, "manager").await, + AcademicYearName::try_new(name).unwrap(), + at(100), + at(200), + Vec::new(), + ) + .await + .unwrap() + } + + async fn class_on(year: Option, db: &Database) -> ClassGroup { let manager = a_named_user(db, "manager").await; create( db, &manager, ClassName::try_new("9-A").unwrap(), None, - term, + year, None, ) .await .unwrap() } - /// A class with a homeroom teacher, no term. + /// A class with a homeroom teacher, no year. async fn class_of(teacher: Option, db: &Database) -> ClassGroup { let manager = a_named_user(db, "manager").await; create( @@ -371,13 +497,6 @@ mod tests { .cloned() } - async fn a_term(db: &Database) -> Term { - let at = crate::domain::timestamp::Timestamp::from_millis; - crate::db::term::create(db, TermName::try_new("2026").unwrap(), at(100), at(200)) - .await - .unwrap() - } - /// The single integer `sql` selects — the stored counter, re-read, never /// off a return value. The SQL is built from literals in this module, so /// the audit wrapper is a formality. @@ -390,11 +509,14 @@ mod tests { .unwrap() } - /// The stored `class_count` on one term, absent counting as zero. - async fn count_on(term: &TermId, db: &Database) -> i64 { + /// The stored `class_count` on one academic year, absent counting as zero. + async fn count_on(year: &AcademicYearId, db: &Database) -> i64 { one_i64( db, - format!("SELECT COALESCE(class_count, 0) FROM term WHERE id = '{}'", term.uuid()), + format!( + "SELECT COALESCE(class_count, 0) FROM academic_year WHERE id = '{}'", + year.uuid() + ), ) .await } @@ -494,29 +616,40 @@ mod tests { assert_eq!(teacher_of(none.get_id(), &db).await, None); } - /// The bite test for the class half of the term delete guard: a term is - /// undeletable while a *class* links it, on its own column, and every way - /// that link can end gives the reference back. Claiming into `course_count` - /// instead would pass the first assert and fail the roundtrip through boot. + /// The bite test for the class half of the academic-year delete guard + /// (D3): a year is undeletable while a *şube* links it, on its own + /// column, and every way that link can end gives the reference back. + /// Claiming into `term_count` instead would pass the first assert and + /// fail the roundtrip through the year's own delete. #[tokio::test] - async fn a_term_is_deletable_only_once_no_class_links_it() { + async fn a_year_is_deletable_only_once_no_class_links_it() { let (db, _leases) = crate::database::init_test_db().await; - let term = a_term(&db).await; + let year = a_year("2026-2027", &db).await; - let linked = class_on(Some(*term.get_id()), &db).await; - let patched = class_on(Some(*term.get_id()), &db).await; + let linked = class_on(Some(*year.get_id()), &db).await; + let patched = class_on(Some(*year.get_id()), &db).await; assert_eq!( - one_i64(&db, "SELECT COALESCE(class_count, 0) FROM term".to_string()).await, + one_i64( + &db, + "SELECT COALESCE(class_count, 0) FROM academic_year".to_string() + ) + .await, 2, - "classes must count on class_count, not course_count" + "classes must count on class_count, not term_count" ); assert_eq!( - one_i64(&db, "SELECT COALESCE(course_count, 0) FROM term".to_string()).await, + one_i64( + &db, + "SELECT COALESCE(term_count, 0) FROM academic_year".to_string() + ) + .await, 0, - "the courses' counter is seeded from course rows and must stay untouched" + "the terms' counter is seeded from term rows and must stay untouched" ); assert!( - !crate::db::term::delete(&db, term.clone()).await.unwrap(), + !crate::db::academic_year::delete(&db, year.clone()) + .await + .unwrap(), "two linked classes must refuse the delete" ); @@ -524,33 +657,42 @@ mod tests { .await .unwrap(); assert!( - !crate::db::term::delete(&db, term.clone()).await.unwrap(), + !crate::db::academic_year::delete(&db, year.clone()) + .await + .unwrap(), "one link is still one link" ); assert!(delete(&db, linked).await.unwrap()); assert!( - crate::db::term::delete(&db, term.clone()).await.unwrap(), - "the last link gone, the term may go" + crate::db::academic_year::delete(&db, year.clone()) + .await + .unwrap(), + "the last link gone, the year may go" + ); + let again = crate::db::academic_year::delete(&db, year).await; + assert!( + matches!(again, Err(AppError::NotFound)), + "a second delete is a 404, not a refusal: {again:?}" ); } /// The bite test for the class delete guard, both arms: either count above - /// zero refuses, having written nothing — the term reference least of all, + /// zero refuses, having written nothing — the year reference least of all, /// which a refusal that released it would strand. #[tokio::test] async fn a_class_with_members_or_courses_refuses_to_delete() { for field in ["class_member_count", "class_course_count"] { let (db, _leases) = crate::database::init_test_db().await; - let term = a_term(&db).await; - let class = class_on(Some(*term.get_id()), &db).await; + let year = a_year("2026-2027", &db).await; + let class = class_on(Some(*year.get_id()), &db).await; sqlx::query(sqlx::AssertSqlSafe(format!( "UPDATE class_group SET {field} = 1 WHERE id = $1" ))) - .bind(class.get_id().uuid()) - .execute(&db) - .await - .unwrap(); + .bind(class.get_id().uuid()) + .execute(&db) + .await + .unwrap(); assert!( !delete(&db, class.clone()).await.unwrap(), @@ -561,24 +703,21 @@ mod tests { "a refused delete may write nothing" ); assert_eq!( - one_i64(&db, "SELECT COALESCE(class_count, 0) FROM term".to_string()).await, + count_on(year.get_id(), &db).await, 1, - "…the term reference least of all" + "…the year reference least of all" ); - // Back to zero, and the same class deletes and releases the term. + // Back to zero, and the same class deletes and releases the year. sqlx::query(sqlx::AssertSqlSafe(format!( "UPDATE class_group SET {field} = 0 WHERE id = $1" ))) - .bind(class.get_id().uuid()) - .execute(&db) - .await - .unwrap(); + .bind(class.get_id().uuid()) + .execute(&db) + .await + .unwrap(); assert!(delete(&db, class.clone()).await.unwrap()); - assert_eq!( - one_i64(&db, "SELECT COALESCE(class_count, 0) FROM term".to_string()).await, - 0 - ); + assert_eq!(count_on(year.get_id(), &db).await, 0); let again = delete(&db, class).await; assert!( matches!(again, Err(AppError::NotFound)), @@ -588,14 +727,14 @@ mod tests { } /// The class half of the invariant on the create path: a refused create - /// leaves neither the row nor a count stranded on a term (which the term's + /// leaves neither the row nor a count stranded on a year (which the year's /// delete guard reads, so a stray one would make it undeletable forever). #[tokio::test] async fn a_refused_create_writes_neither_row_nor_count() { let (db, _leases) = crate::database::init_test_db().await; - let term = a_term(&db).await; - let id = *term.get_id(); - assert!(crate::db::term::delete(&db, term).await.unwrap()); + let year = a_year("2026-2027", &db).await; + let id = *year.get_id(); + assert!(crate::db::academic_year::delete(&db, year).await.unwrap()); let error = create( &db, @@ -606,39 +745,33 @@ mod tests { None, ) .await - .expect_err("a term that is gone must not be linkable"); - assert!(error.to_string().contains("term does not exist")); + .expect_err("a year that is gone must not be linkable"); + assert!(error.to_string().contains("academic year does not exist")); assert_eq!( row_count(&db, "class_group").await, 0, "a refused create may write no row" ); assert_eq!( - row_count(&db, "term").await, + row_count(&db, "academic_year").await, 0, - "…and least of all a count on a term it just brought back" + "…and least of all a count on a year it just brought back" ); } /// The class mirror of - /// [`crate::db::course`]'s move tests: a term move carries both - /// counters with the link, and a move to a term that is gone rolls the - /// release back with the abort (the transaction releases before it claims, - /// so the old count would be 0 if the abort did not undo it). + /// [`crate::db::course`]'s move tests: a year move carries the count with + /// the link, and a move to a year that is gone rolls the release back with + /// the abort (the transaction releases before it claims, so the old count + /// would be 0 if the abort did not undo it). #[tokio::test] - async fn a_class_term_move_moves_both_counts_or_neither() { + async fn a_class_year_move_moves_the_count_or_neither() { let (db, _leases) = crate::database::init_test_db().await; - let at = crate::domain::timestamp::Timestamp::from_millis; - let from = a_term(&db).await; - let to = crate::db::term::create(&db, TermName::try_new("2027").unwrap(), at(100), at(200)) - .await - .unwrap(); - let dead = - crate::db::term::create(&db, TermName::try_new("2028").unwrap(), at(100), at(200)) - .await - .unwrap(); + let from = a_year("2026-2027", &db).await; + let to = a_year("2027-2028", &db).await; + let dead = a_year("2028-2029", &db).await; let dead_id = *dead.get_id(); - assert!(crate::db::term::delete(&db, dead).await.unwrap()); + assert!(crate::db::academic_year::delete(&db, dead).await.unwrap()); let class = class_on(Some(*from.get_id()), &db).await; let error = update( @@ -650,10 +783,10 @@ mod tests { None, ) .await - .expect_err("a term that is gone must not be linkable"); - assert!(error.to_string().contains("term does not exist")); + .expect_err("a year that is gone must not be linkable"); + assert!(error.to_string().contains("academic year does not exist")); let stored = read(&db, class.get_id()).await.unwrap().unwrap(); - assert_eq!(stored.get_term(), Some(from.get_id()), "the link stays put"); + assert_eq!(stored.get_year(), Some(from.get_id()), "the link stays put"); assert_eq!(stored.get_name().as_str(), "9-A", "…and so does the row"); assert_eq!( count_on(from.get_id(), &db).await, @@ -661,28 +794,21 @@ mod tests { "the release must roll back with the abort" ); - let moved = update( - &db, - class, - None, - None, - Some(Some(*to.get_id())), - None, - ) - .await - .unwrap(); - assert_eq!(moved.get_term(), Some(to.get_id())); + let moved = update(&db, class, None, None, Some(Some(*to.get_id())), None) + .await + .unwrap(); + assert_eq!(moved.get_year(), Some(to.get_id())); assert_eq!( count_on(from.get_id(), &db).await, 0, - "the old term is free" + "the old year is free" ); assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); } - /// The class twin of - /// [`crate::domain::course`]'s `a_stale_mover_is_refused_and_claims_nothing` - /// and `a_stale_re_stater_is_refused_and_reverts_nothing`, in one: both + /// The class twin of [`crate::db::course`]'s + /// `a_stale_mover_is_refused_and_claims_nothing` and + /// `a_stale_re_stater_is_refused_and_reverts_nothing`, in one: both /// PATCHes compute their counter move from the row as *they* read it, so a /// second one running on the pre-move struct would claim a second seat for /// one link (the mover) or drag the link back and strand the winner's claim @@ -690,29 +816,16 @@ mod tests { /// stopped by a guard armed off the *carried column*). Both must be refused /// with the counts reading as if they never ran. #[tokio::test] - async fn a_stale_class_term_write_is_refused_and_moves_no_count() { + async fn a_stale_class_year_write_is_refused_and_moves_no_count() { let (db, _leases) = crate::database::init_test_db().await; - let at = crate::domain::timestamp::Timestamp::from_millis; - let from = a_term(&db).await; - let to = crate::db::term::create(&db, TermName::try_new("2027").unwrap(), at(100), at(200)) - .await - .unwrap(); - let other = - crate::db::term::create(&db, TermName::try_new("2028").unwrap(), at(100), at(200)) - .await - .unwrap(); + let from = a_year("2026-2027", &db).await; + let to = a_year("2027-2028", &db).await; + let other = a_year("2028-2029", &db).await; let class = class_on(Some(*from.get_id()), &db).await; let stale = class.clone(); - update( - &db, - class, - None, - None, - Some(Some(*to.get_id())), - None, - ) - .await - .unwrap(); + update(&db, class, None, None, Some(Some(*to.get_id())), None) + .await + .unwrap(); // The mover: its snapshot says `from`, so it would release `from` and // claim `other` on top of the winner's claim on `to`. @@ -741,73 +854,80 @@ mod tests { assert!(matches!(error, AppError::Conflict(_)), "{error:?}"); let stored = read(&db, stale.get_id()).await.unwrap().unwrap(); - assert_eq!(stored.get_term(), Some(to.get_id()), "the winner's link"); + assert_eq!(stored.get_year(), Some(to.get_id()), "the winner's link"); assert_eq!(count_on(from.get_id(), &db).await, 0, "released once"); assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once"); assert_eq!(count_on(other.get_id(), &db).await, 0, "never claimed"); // A genuine no-op re-state still lands and still moves nothing. - let same = update( - &db, - stored, - None, - None, - Some(Some(*to.get_id())), - None, - ) - .await - .expect("re-stating the link the row really holds is not a conflict"); - assert_eq!(same.get_term(), Some(to.get_id())); + let same = update(&db, stored, None, None, Some(Some(*to.get_id())), None) + .await + .expect("re-stating the link the row really holds is not a conflict"); + assert_eq!(same.get_year(), Some(to.get_id())); assert_eq!(count_on(to.get_id(), &db).await, 1, "still one seat"); } - /// [`crate::db::course::delete`]'s class sweep: deleting a course - /// takes its `class_course` attachments with it and gives each class its - /// count back, or the classes would be undeletable forever over rows that - /// point at nothing. + /// The delete guard counts *live* stints, and a soft-left student holds + /// none — so the class passes it with the history row still standing, and + /// `class_member.class` (a hard foreign key) is what used to answer this + /// delete, as a `23503` the route turns into a 500. The roster history + /// goes with the şube it belongs to. #[tokio::test] - async fn deleting_a_course_sweeps_its_class_attachments() { - use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; + async fn a_soft_left_member_does_not_block_the_delete_and_goes_with_it() { + use crate::db::class_pump::{self, Attached}; let (db, _leases) = crate::database::init_test_db().await; let manager = a_named_user(&db, "manager").await; - let course = crate::db::course::create( - &db, - &manager, - CourseTitle::try_new("algebra").unwrap(), - CourseDescription::try_new("").unwrap(), - CourseKind::course(), - None, - None, - ) - .await - .unwrap(); - let class = class_on(None, &db).await; - sqlx::query("INSERT INTO class_course (class, course, attached_by) VALUES ($1, $2, $3)") - .bind(class.get_id().uuid()) - .bind(course.get_id().uuid()) - .bind(manager.uuid()) - .execute(&db) - .await - .unwrap(); - sqlx::query("UPDATE class_group SET class_course_count = 1 WHERE id = $1") - .bind(class.get_id().uuid()) + let class = class_of(None, &db).await; + // The pump's member axis claims the `student` role on the user row, + // and a stint is a real write, not a row fabricated into place. + let student = a_named_user(&db, "ada").await; + sqlx::query("UPDATE app_user SET role = 'student' WHERE id = $1") + .bind(student.uuid()) .execute(&db) .await .unwrap(); + assert!(matches!( + class_pump::add_member(&db, class.get_id(), &student, &manager) + .await + .unwrap(), + Attached::Made(_) + )); - assert!(crate::db::course::delete(&db, course).await.unwrap()); assert_eq!( - row_count(&db, "class_course").await, - 0, - "the attachment rows must go with the course" + class_pump::leave_member(&db, class.get_id(), &student) + .await + .unwrap(), + 1, + "the one live stint is the one the leave ends" ); + // Exactly what the guard is blind to: the counters read zero, the + // history does not. assert_eq!( - one_i64(&db, "SELECT COALESCE(class_course_count, 0) FROM class_group".to_string()).await, + one_i64( + &db, + format!( + "SELECT class_member_count FROM class_group WHERE id = '{}'", + class.get_id().uuid() + ) + ) + .await, + 0 + ); + assert_eq!(row_count(&db, "class_member").await, 1); + + assert!( + delete(&db, class.clone()).await.unwrap(), + "a soft-left member must not block the delete" + ); + assert_eq!( + row_count(&db, "class_member").await, 0, - "…and each class must get its count back" + "…and the roster history goes with the şube" + ); + assert!( + matches!(delete(&db, class).await, Err(AppError::NotFound)), + "a second delete is still a 404" ); - // Which is the whole point: the class is deletable again. - assert!(delete(&db, class).await.unwrap()); } } diff --git a/src/db/class_member.rs b/src/db/class_member.rs index 23c4071..62308ad 100644 --- a/src/db/class_member.rs +++ b/src/db/class_member.rs @@ -2,6 +2,11 @@ //! pump's, along the member axis ([`crate::db::class_pump`]); the //! refusals-to-errors policy and the detach live in //! [`crate::service::class_member`]. +//! +//! The table is a history: `left_at` NULL is the live stint, and every read +//! here filters on it — a student who left the şube holds no seat and appears +//! on no roster, while their earlier row survives for the record (and for the +//! karne's attribution). use crate::constant::CLASS_MEMBER_TABLE; use crate::database::Database; @@ -11,9 +16,8 @@ use crate::domain::class_member::ClassMember; use crate::domain::user::UserId; use crate::error::AppError; -/// The class's roster, newest first — by when the student was added. The -/// composite primary key is the tiebreaker (class, then user: the two halves -/// of the id this order used to sort), which makes the order total. +/// The class's live roster, newest first — by when the student joined. The +/// surrogate id breaks the tie, so the order is total. pub async fn list_for_class( db: &Database, class: &ClassGroupId, @@ -21,17 +25,17 @@ pub async fn list_for_class( offset: i64, ) -> Result<(Vec, i64), AppError> { PagedList::new( - format!("{CLASS_MEMBER_TABLE} WHERE class = $1"), - "ORDER BY added_at DESC NULLS LAST, class DESC, app_user DESC", + format!("{CLASS_MEMBER_TABLE} WHERE class = $1 AND left_at IS NULL"), + "ORDER BY joined_at DESC, id DESC", ) .bind(class.uuid()) .run(limit, offset, db) .await } -/// The classes one student belongs to, newest membership first — the read -/// behind "which class section (şube) am I in". Same ordering story as -/// [`list_for_class`], along the other axis of the same index. +/// The classes one student is currently in, newest stint first — the read +/// behind "which class section (şube) am I in". A left stint is history and +/// does not appear. pub async fn list_for_user( db: &Database, user: &UserId, @@ -39,14 +43,32 @@ pub async fn list_for_user( offset: i64, ) -> Result<(Vec, i64), AppError> { PagedList::new( - format!("{CLASS_MEMBER_TABLE} WHERE app_user = $1"), - "ORDER BY added_at DESC NULLS LAST, class DESC, app_user DESC", + format!("{CLASS_MEMBER_TABLE} WHERE app_user = $1 AND left_at IS NULL"), + "ORDER BY joined_at DESC, id DESC", ) .bind(user.uuid()) .run(limit, offset, db) .await } +/// Whether `user` holds a live stint in `class` right now — the membership +/// gate a class-scoped route reads before it writes. +pub async fn is_live_member( + db: &Database, + class: &ClassGroupId, + user: &UserId, +) -> Result { + let row = sqlx::query!( + r#"SELECT 1 AS "one" FROM class_member + WHERE class = $1 AND app_user = $2 AND left_at IS NULL"#, + class.uuid(), + user.uuid(), + ) + .fetch_optional(db) + .await?; + Ok(row.is_some()) +} + #[cfg(test)] pub(crate) mod tests { use super::*; @@ -80,6 +102,8 @@ pub(crate) mod tests { UserId::from_key(&id.to_string()) } + /// A class with no year and no grade: the shape most fixtures want, since + /// the year only matters to the academic-calendar reads. pub(crate) async fn a_class(name: &str, db: &Database) -> ClassGroupId { let manager = fixture_user(db, "manager").await; crate::db::class_group::create( @@ -96,7 +120,9 @@ pub(crate) mod tests { .clone() } - pub(crate) async fn a_course(title: &str, capacity: Option, db: &Database) -> CourseId { + /// A catalog course. Capacity is gone from the catalog (D5): the instance + /// carries the roster counter and there is no seat gate to trip. + pub(crate) async fn a_course(title: &str, db: &Database) -> CourseId { let manager = fixture_user(db, "manager").await; crate::db::course::create( db, @@ -104,8 +130,6 @@ pub(crate) mod tests { CourseTitle::try_new(title).unwrap(), CourseDescription::try_new("").unwrap(), CourseKind::course(), - None, - capacity, ) .await .unwrap() @@ -114,23 +138,34 @@ pub(crate) mod tests { } /// A counter column on its row, re-read out of the store — never off a - /// return value. The column name picks the table: every `*_count` these - /// suites read lives on exactly one. + /// return value. The field picks the table for the counters whose home is + /// unambiguous; `class_course_count` now exists on *both* the class (how + /// many courses it carries) and the catalog course (how many instances are + /// taught in), so that one names the class here and + /// [`counter_on`] is the way to read the course's. pub(crate) async fn counter(field: &str, of: uuid::Uuid, db: &Database) -> i64 { let table = match field { - "enrollment_count" => "course", + // The roster counter is the *instance's* (the catalog course has + // no roster since D4/D5). + "enrollment_count" => "class_course", "class_member_count" | "class_course_count" => "class_group", other => panic!("no table known for the counter {other}"), }; + counter_on(table, field, of, db).await + } + + /// [`counter`] with the table named outright, for the columns two tables + /// share. + pub(crate) async fn counter_on(table: &str, field: &str, of: uuid::Uuid, db: &Database) -> i64 { sqlx::query(sqlx::AssertSqlSafe(format!( "SELECT COALESCE({field}, 0) FROM {table} WHERE id = $1" ))) - .bind(of) - .fetch_one(db) - .await - .unwrap() - .try_get::(0) - .unwrap() + .bind(of) + .fetch_one(db) + .await + .unwrap() + .try_get::(0) + .unwrap() } /// How many rows `table` holds. @@ -155,12 +190,12 @@ pub(crate) mod tests { /// Whether the enrollment pair still has its row. pub(crate) async fn enrollment_exists( - course: &CourseId, + class_course: &crate::domain::class_course::ClassCourseId, user: &UserId, db: &Database, ) -> bool { - sqlx::query("SELECT 1 FROM enrollment WHERE course = $1 AND app_user = $2") - .bind(course.uuid()) + sqlx::query("SELECT 1 FROM enrollment WHERE class_course = $1 AND app_user = $2") + .bind(class_course.uuid()) .bind(user.uuid()) .fetch_optional(db) .await @@ -183,13 +218,14 @@ pub(crate) mod tests { .is_some() } - /// The class that wrote an enrollment, or `None` for a hand-placed row. + /// The class that wrote an instance's enrollment, or `None` for a + /// hand-placed row. pub(crate) async fn source_of( - course: &CourseId, + class_course: &crate::domain::class_course::ClassCourseId, user: &UserId, db: &Database, ) -> Option> { - crate::db::enrollment::read_for_user(db, course, user) + crate::db::enrollment::read_for_user(db, class_course, user) .await .unwrap() .map(|row| row.get_source().cloned()) diff --git a/src/db/class_pump.rs b/src/db/class_pump.rs index feb6610..aa48349 100644 --- a/src/db/class_pump.rs +++ b/src/db/class_pump.rs @@ -2,37 +2,41 @@ //! `enrollment` row that link implies reconciled with it, in one transaction. //! //! A class section (şube) has two link tables — `class_member` (a student in -//! it) and `class_course` (a course attached to it) — and the *product* of the -//! two is the roster it owes: every member is enrolled in every attached -//! course, in real `enrollment` rows tagged [`source`](crate::domain::enrollment) -//! with the class that wrote them. Adding a member and attaching a course are -//! therefore the same operation seen along its two axes, and so are removing +//! it) and `class_course` (a course attached to it, as that class×course +//! *instance*) — and the *product* of the two is the roster it owes: every +//! live member is enrolled in every instance the class carries, in real +//! `enrollment` rows tagged [`source`](crate::domain::enrollment) with the +//! class that wrote them. Adding a member and attaching a course are +//! therefore the same operation seen along its two axes, and so are ending //! one and detaching the other. //! //! What is *not* one primitive is attach and detach. They share no statement: //! one gates on "this pair already holds a row" and claims a counter upwards, -//! the other gates on nothing, releases, and has to decide per enrollment row -//! whether a *rival* class still claims it. +//! the other takes the instance and everything the class taught under it, and +//! the member exits release the enrollment rows the ended stint owned — one +//! row per *instance*, so a section's exit never touches the seat the student +//! holds in another section. //! //! Every invariant is one Postgres statement or one row lock, in the shapes //! [`crate::db::cap`] documents: the class counter is claimed by a conditional //! `UPDATE` fused with the link's `INSERT` (one CTE — a refused insert takes -//! its own seat bump back), a duplicate is the link table's natural composite -//! primary key answering as `23505`, a gone parent is a real `FOREIGN KEY` -//! answering as `23503`, and the row locks (`FOR KEY SHARE` / `FOR NO KEY -//! UPDATE`) put each transaction on the very record a racing writer must -//! touch. A refusal is an early `Err` (or an `Ok` verdict) from the +//! its own bump back), a duplicate live stint is the partial unique index +//! `class_member_live_pair` answering as `23505` (and enrollment's natural +//! `(class_course, app_user)` key doing the same job through `ON CONFLICT`), +//! a gone parent is a real `FOREIGN KEY` answering as `23503`, and the row +//! locks (`FOR KEY SHARE` / `FOR NO KEY UPDATE` / `FOR UPDATE`) put each +//! transaction on the very record a racing writer must touch. A refusal is an +//! early `Err` (or an `Ok` verdict) from the //! [`crate::database::tx_with_retry`] closure — a decision, never a retry. use sqlx::postgres::PgConnection; use crate::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS}; use crate::database::{Database, foreign_key_violation, tx_with_retry, unique_violation}; -use crate::db::cap; use crate::domain::class_blueprint::ClassBlueprintId; -use crate::domain::class_course::ClassCourse; +use crate::domain::class_course::{ClassCourse, ClassCourseId, DersSaati}; use crate::domain::class_group::ClassGroupId; -use crate::domain::class_member::ClassMember; +use crate::domain::class_member::{ClassMember, ClassMemberId}; use crate::domain::course::CourseId; use crate::domain::role::Role; use crate::domain::timestamp::Timestamp; @@ -72,13 +76,12 @@ pub(crate) enum Attached { /// be. Only a class predating the ceilings can be here, and only its own /// axis can make room — which is why it is not [`Attached::ClassFull`]. ClassOverloaded, - /// One of the courses had no free seat, named by its key. Nothing was - /// written — not one of the earlier seats in the same run, which is the - /// whole point of doing this in a transaction. - Full(String), - /// One of the courses the class carries no longer exists, named by its id: - /// a stale `class_course` link. Nothing was written, and no capacity anyone - /// can raise will change that answer. + /// One of the class's instances no longer exists, named by its id: a + /// `class_course` row a concurrent detach took while this pump was walking + /// its pairs. Nothing was written — not one of the earlier rows in the + /// same run, which is the whole point of doing this in a transaction. No + /// capacity anyone can raise will change that answer; the attach must be + /// retried against the class as it now stands. CourseGone(String), /// The blueprint this attach was sourced from is gone — a delete landed /// between the pump reading the template and this transaction running. @@ -105,8 +108,9 @@ impl Attached { /// *course* delete ([`Attached::PivotGone`] → `course_deleted`) — and /// telling a manager the class vanished when the course did sends them to /// look at a section that is standing right there. `linked_course_missing` - /// is a third: *another* course already attached to this class no longer - /// exists, and it must be detached before this attach can be retried. + /// is a third: one of the class's *instances* vanished while the pump was + /// walking its pairs (a concurrent detach), so the attach must be retried + /// against the class as it now stands. /// `blueprint_deleted` is a pump losing the template itself mid-run — the /// only refusal that says nothing about the (class, course) pair it names. /// @@ -124,7 +128,6 @@ impl Attached { Attached::PivotGone => Some("course_deleted"), Attached::ClassFull => Some(axis.at_ceiling_code()), Attached::ClassOverloaded => Some(axis.other().over_ceiling_code()), - Attached::Full(_) => Some("course_full"), Attached::CourseGone(_) => Some("linked_course_missing"), Attached::SourceGone => Some("blueprint_deleted"), } @@ -228,11 +231,14 @@ fn refusal_of(early: Early) -> Attached { /// The gates that run before any counter moves, in the order their answers /// outrank each other: /// -/// 1. **Duplicate** — "you are already in" outranks "there is no room": a -/// caller whose row a rival placed a moment ago must not be told a course -/// is full about seats they already hold. (The link table's own primary key -/// re-answers this below as `23505` for a rival landing inside the window — -/// same verdict, no second seat.) +/// 1. **Duplicate** — "you are already in" outranks every other answer: a +/// caller whose row a rival placed a moment ago must be told they are in, +/// not refused for a class ceiling they are not near. The member axis reads +/// a **live** stint (a left one claims nothing, so rejoining is not a +/// duplicate); the course axis reads the (class, course) pair. (The link +/// tables re-answer this below — `23505` on the live-stint partial index, +/// `ON CONFLICT DO NOTHING` on the enrollment pair — for a rival landing +/// inside the window: same verdict, no second count.) /// 2. **Source** — the blueprint that asked for this attach is still there. A /// `FOR KEY SHARE` row lock on the blueprint row: it serializes the attach /// against the blueprint's own delete — the closure the old process-wide @@ -265,7 +271,8 @@ async fn early_verdicts( ) -> Result<(Option, Option), AppError> { let held = match pivot { Pivot::User(user) => sqlx::query_scalar!( - r#"SELECT 1 AS "one" FROM class_member WHERE class = $1 AND app_user = $2"#, + r#"SELECT 1 AS "one" FROM class_member + WHERE class = $1 AND app_user = $2 AND left_at IS NULL"#, class as _, user as _ ) @@ -350,13 +357,12 @@ async fn early_verdicts( Ok((over.then_some(Early::Overloaded), source_id)) } -/// Write the member link and enroll the student into every course the class is -/// already attached to, or write nothing at all. +/// Write the member stint and enroll the student into every instance the +/// class already carries, or write nothing at all. /// -/// A student already enrolled in one of those courses keeps the row they -/// have — no seat is charged, and the existing row's `source` is left exactly +/// A student already enrolled in one of those instances keeps the row they +/// have — no count charged, and the existing row's `source` is left exactly /// as it was, so a hand-placed student is never quietly adopted by a class. -/// A course with no free seat refuses the *whole* join rather than half of it. /// /// The class counter is claimed by the conditional half of the CTE below /// rather than a bare increment, so a class deleted out from under this run @@ -366,18 +372,45 @@ async fn early_verdicts( /// this transaction — finite: [`Attached::ClassFull`] once the class is at its /// ceiling. Claim and insert are one statement, so a refused insert takes its /// own seat bump back. +/// +/// The stint is live (`left_at` NULL) by construction, which is the row the +/// partial unique index `class_member_live_pair` guards: a rival landing in +/// the window is answered as [`Attached::Duplicate`] rather than a second +/// live stint for the same pair. A student who left earlier keeps their +/// history row — it claims nothing. pub(crate) async fn add_member( db: &Database, class: &ClassGroupId, user: &UserId, by: &UserId, ) -> Result, AppError> { - let added_at = Timestamp::now(); + add_member_sourced(db, class, user, by, None).await +} + +/// [`add_member`] carrying the stint's *provenance*: the şube the student was +/// copied from, written into `source_class_group` in the same statement as +/// the row. `None` is the hand add — a student someone put here, who came +/// from nowhere (the pump is the only writer of this column, and a rollover +/// is the only caller that has a source to name). +/// +/// Everything else — the claim, the cap, the duplicate verdict, the pair loop +/// — is identical, and deliberately so: the tag rides the member axis's own +/// single statement rather than a follow-up write, so a crash cannot leave a +/// copied stint that lost its provenance. +pub(crate) async fn add_member_sourced( + db: &Database, + class: &ClassGroupId, + user: &UserId, + by: &UserId, + source: Option<&ClassGroupId>, +) -> Result, AppError> { + let joined_at = Timestamp::now(); let class = class.clone(); + let source = source.cloned(); let (user, by) = (*user, *by); + let id = ClassMemberId::generate(); let outcome = tx_with_retry(db, false, async move |tx| { - let (early, _) = - early_verdicts(tx, &class, Axis::Member, Pivot::User(&user), None).await?; + let (early, _) = early_verdicts(tx, &class, Axis::Member, Pivot::User(&user), None).await?; if let Some(early) = early { return Ok(refusal_of(early)); } @@ -389,23 +422,27 @@ pub(crate) async fn add_member( UPDATE class_group SET class_member_count = class_member_count + 1 WHERE id = $1 AND class_member_count < $2 RETURNING 1) - INSERT INTO class_member (class, app_user, added_by, added_at) - SELECT $1, $3, $4, $5 WHERE EXISTS (SELECT 1 FROM seat) + INSERT INTO class_member (id, class, app_user, added_by, joined_at, left_at, + source_class_group) + SELECT $3, $1, $4, $5, $6, NULL, $7 WHERE EXISTS (SELECT 1 FROM seat) RETURNING 1 AS "one""#, class as _, Axis::Member.cap(), + id.uuid(), user as _, by as _, - added_at as _ + joined_at as _, + source.as_ref().map(ClassGroupId::uuid), ) .fetch_optional(&mut *tx) .await { Ok(result) => result, // A rival landed in the window between the gate and the insert: - // the link table's own primary key answers, same verdict as the - // gate, no second seat. - Err(e) if unique_violation(&e) == Some("class_member_class_user") => { + // the live-stint partial index answers, same verdict as the gate, + // no second seat. (A left row is not in that index, so a rejoin + // after a leave is never a duplicate.) + Err(e) if unique_violation(&e) == Some("class_member_live_pair") => { return Ok(Attached::Duplicate); } // The student row vanished mid-run despite the locked pivot claim. @@ -428,36 +465,59 @@ pub(crate) async fn add_member( Attached::Gone }); } - let courses: Vec = sqlx::query_scalar!( - r#"SELECT course AS "course: uuid::Uuid" FROM class_course WHERE class = $1"#, + // The pairs are the class's *instances*, one per attached course: the + // member axis now enrolls into the class×course instance, not into a + // school-wide course row. + let instances: Vec = sqlx::query_scalar!( + r#"SELECT id AS "id: uuid::Uuid" FROM class_course WHERE class = $1"#, class as _ ) .fetch_all(&mut *tx) .await?; - let pairs = courses.into_iter().map(|course| (course, user.uuid())); + let pairs = instances + .into_iter() + .map(|instance| (instance, user.uuid())); enroll_pairs(tx, &class, pairs, &by).await?; Ok(Attached::Made(ClassMember { + id: id.clone(), class: class.clone(), user, added_by: by, + joined_at, + left_at: None, + source_class_group: source.clone(), })) }) .await; map_sweep_abort(outcome) } -/// Write the course link and enroll the class's whole roster into it, or +/// Write the instance and enroll the class's whole live roster into it, or /// write nothing at all. /// -/// Students already in the course keep the rows they have — no seat charged, -/// `source` untouched — and a roster that does not fit refuses the whole -/// attach rather than filling the course to its cap and stopping. +/// Students already enrolled in it keep the rows they have — no count charged, +/// `source` untouched. There is no roster-size gate any more (D5: the +/// counter is a count, not a capacity), so the only refusals left are the +/// class's own ceilings and a vanished pivot. /// /// `source` is the blueprint whose behalf this attach runs on, and supplying /// it adds one more claim: that it is still there when the transaction runs /// ([`Attached::SourceGone`]) — the `FOR KEY SHARE` lock that serializes this /// transaction against the blueprint's own delete. A hand attach owns itself /// and passes `None`. +/// +/// The instance's own id is minted here (v7, so a class's instances list in +/// creation order) and its policy columns take the schema defaults: one weekly +/// hour, counted toward the karne, an empty roster. A PATCH on `/instances` +/// changes them afterwards. +/// +/// Two counters ride the write, both in this one transaction: the class's +/// `class_course_count` (claimed by the conditional CTE, so a full or gone +/// class writes nothing) and the *catalog's* `class_course_count` — how many +/// şubeler teach this course, which is what [`crate::db::course::delete`]'s +/// guard reads. This is the only insert path into `class_course`; every layer +/// above it (hand attach, blueprint pump, rollover copy) reaches the counter +/// through here. pub(crate) async fn attach_course( db: &Database, class: &ClassGroupId, @@ -470,6 +530,7 @@ pub(crate) async fn attach_course( let course = course.clone(); let by = *by; let source = source.cloned(); + let id = ClassCourseId::generate(); let outcome = tx_with_retry(db, false, async move |tx| { let (early, source_id) = early_verdicts( tx, @@ -487,11 +548,12 @@ pub(crate) async fn attach_course( UPDATE class_group SET class_course_count = class_course_count + 1 WHERE id = $1 AND class_course_count < $2 RETURNING 1) - INSERT INTO class_course (class, course, attached_by, attached_at, source) - SELECT $1, $3, $4, $5, $6 WHERE EXISTS (SELECT 1 FROM seat) + INSERT INTO class_course (id, class, course, attached_by, attached_at, source) + SELECT $3, $1, $4, $5, $6, $7 WHERE EXISTS (SELECT 1 FROM seat) RETURNING 1 AS "one""#, class as _, Axis::Course.cap(), + id.uuid(), course as _, by as _, attached_at as _, @@ -521,19 +583,51 @@ pub(crate) async fn attach_course( Attached::Gone }); } + // The catalog's own counter: how many şubeler teach this course. It is + // what [`crate::db::course::delete`]'s guard reads — a course a class + // still teaches may not go — and this insert is the only place it can + // be claimed. It is a *count*, not a capacity (D5: nothing is refused + // for being near it), so it is a plain increment in the same + // transaction as the row: the link and its count commit together, and + // the early refusals above (a full or gone class, a lost insert) have + // already returned, so no give-back path exists to get wrong. + sqlx::query!( + r#"UPDATE course SET class_course_count = class_course_count + 1 WHERE id = $1"#, + course as _ + ) + .execute(&mut *tx) + .await?; + // The roster is the class's *live* stints: a student who left holds no + // seat and is enrolled in nothing the class attaches afterwards. let members: Vec = sqlx::query_scalar!( - r#"SELECT app_user AS "app_user: uuid::Uuid" FROM class_member WHERE class = $1"#, + r#"SELECT app_user AS "app_user: uuid::Uuid" FROM class_member + WHERE class = $1 AND left_at IS NULL"#, class as _ ) .fetch_all(&mut *tx) .await?; - let pairs = members.into_iter().map(|user| (course.uuid(), user)); + let pairs = members.into_iter().map(|user| (id.uuid(), user)); enroll_pairs(tx, &class, pairs, &by).await?; + // The counter the pair loop just moved, read back inside the + // transaction so the returned row reports the roster it now has + // rather than the empty one it was inserted with. + let enrollment_count = sqlx::query_scalar!( + r#"SELECT enrollment_count AS "count: i64" FROM class_course WHERE id = $1"#, + id.uuid() + ) + .fetch_one(&mut *tx) + .await?; Ok(Attached::Made(ClassCourse { + id: id.clone(), class: class.clone(), course: course.clone(), attached_by: by, source: source.clone(), + ders_saati: DersSaati::try_new(crate::constant::MIN_DERS_SAATI) + .expect("the schema default is a valid weekly-hours count"), + counts_toward_karne: true, + enrollment_count, + attached_at, })) }) .await; @@ -543,11 +637,10 @@ pub(crate) async fn attach_course( /// Abort markers the pair loop raises where the old transaction `THROW` did, /// in the [`crate::db::field_update`] style: a refusal found *after* earlier /// pairs wrote must take the whole run down with it — returning it as `Ok` -/// would COMMIT the partial enrollment. The marker carries the course's key +/// would COMMIT the partial enrollment. The marker carries the instance's id /// and is mapped back to [`Attached`] right after [`tx_with_retry`] returns /// ([`map_sweep_abort`]); it never reaches the wire. const COURSE_GONE_MARK: &str = "class_pump_course_gone:"; -const COURSE_FULL_MARK: &str = "class_pump_course_full:"; /// The pair loop's abort markers back into their [`Attached`] refusals — /// every other outcome passes through untouched. @@ -556,28 +649,24 @@ fn map_sweep_abort(outcome: Result, AppError>) -> Result Ok(Attached::CourseGone( m[COURSE_GONE_MARK.len()..].to_string(), )), - Err(AppError::Internal(m)) if m.starts_with(COURSE_FULL_MARK) => { - Ok(Attached::Full(m[COURSE_FULL_MARK.len()..].to_string())) - } other => other, } } -/// Enroll every `(course, user)` pair that has no row yet, each against its -/// own course's capacity, skipping — never charging — the pairs that do. +/// Enroll every `(instance, user)` pair that has no row yet, and charge the +/// instance's roster counter only for the rows actually written. /// -/// Per pair, in the order the refusals outrank each other: the pair's own row -/// answers "already enrolled" (skip, no seat); the course row answers "gone" -/// *before* the seat claim, so a stale link is never mis-reported as a -/// capacity problem; the seat claim is a conditional `UPDATE` on the course -/// row (live cap — `capacity` as it stands at write time, `NULL` reading as -/// unlimited); and the insert rides the seat it claimed. A rival that lands -/// between the gate and the insert answers `23505`, and the bump is given -/// back before the skip — the outcome a re-sent transaction used to reach by -/// seeing the rival's row at its gate. +/// Per pair, in the order the answers outrank each other: the pair's own row +/// answers "already enrolled" (skip, no count moved); the counter claim is a +/// plain increment on the instance row, so it doubles as the existence check — +/// a claim matching nothing is an instance a concurrent detach took, which is +/// the abort marker rather than a refusal of this pair alone; and then the +/// row is inserted with `ON CONFLICT DO NOTHING`, so a rival landing between +/// the gate and the insert leaves *their* row standing and this run gives its +/// own claim back before the skip. /// /// Every abort stops the loop inside the caller's transaction: not one of the -/// earlier seats in the same run survives, which is the whole point of doing +/// earlier rows in the same run survives, which is the whole point of doing /// this in a transaction. async fn enroll_pairs( tx: &mut PgConnection, @@ -586,10 +675,10 @@ async fn enroll_pairs( by: &UserId, ) -> Result<(), AppError> { let now = Timestamp::now(); - for (course, user) in pairs { + for (instance, user) in pairs { let held = sqlx::query_scalar!( - r#"SELECT 1 AS "one" FROM enrollment WHERE course = $1 AND app_user = $2"#, - course, + r#"SELECT 1 AS "one" FROM enrollment WHERE class_course = $1 AND app_user = $2"#, + instance, user ) .fetch_optional(&mut *tx) @@ -598,32 +687,27 @@ async fn enroll_pairs( if held { continue; } - let alive = sqlx::query_scalar!(r#"SELECT 1 AS "one" FROM course WHERE id = $1"#, course) - .fetch_optional(&mut *tx) - .await? - .is_some(); - if !alive { - return Err(AppError::Internal(format!("{COURSE_GONE_MARK}{course}"))); - } - let seat = sqlx::query_scalar!( - r#"UPDATE course SET enrollment_count = enrollment_count + 1 - WHERE id = $1 AND enrollment_count < COALESCE(capacity, $2) + // The claim doubles as the existence check: there is no capacity to + // refuse on, so an increment that matches no row means the instance is + // gone — a stale link, never a full roster. + let claimed = sqlx::query_scalar!( + r#"UPDATE class_course SET enrollment_count = enrollment_count + 1 + WHERE id = $1 RETURNING 1 AS "one""#, - course, - cap::UNLIMITED, + instance, ) .fetch_optional(&mut *tx) .await? .is_some(); - if !seat { - return Err(AppError::Internal(format!("{COURSE_FULL_MARK}{course}"))); + if !claimed { + return Err(AppError::Internal(format!("{COURSE_GONE_MARK}{instance}"))); } let wrote = sqlx::query_scalar!( - r#"INSERT INTO enrollment (course, app_user, enrolled_by, source, created_at) + r#"INSERT INTO enrollment (class_course, app_user, enrolled_by, source, created_at) VALUES ($1, $2, $3, $4, $5) - ON CONFLICT (course, app_user) DO NOTHING + ON CONFLICT (class_course, app_user) DO NOTHING RETURNING 1 AS "one""#, - course, + instance, user, by as _, class as _, @@ -634,23 +718,15 @@ async fn enroll_pairs( match wrote { Ok(Some(_)) => {} // A rival placed the pair in the window: their row stands, no - // second seat, and the claim this run took is given back — the - // skip wins over the capacity answer, exactly as a re-sent - // transaction found the row at its gate. + // second count, and the claim this run took is given back — the + // skip wins, exactly as a re-sent transaction found the row at its + // gate. Ok(None) => { sqlx::query!( - r#"UPDATE course SET enrollment_count = enrollment_count - 1 - WHERE id = $1"#, - course - ) - .execute(&mut *tx) - .await?; - } - Err(e) if unique_violation(&e) == Some("enrollment_course_user") => { - sqlx::query!( - r#"UPDATE course SET enrollment_count = enrollment_count - 1 - WHERE id = $1"#, - course + r#"UPDATE class_course + SET enrollment_count = GREATEST(enrollment_count - 1, 0) + WHERE id = $1"#, + instance ) .execute(&mut *tx) .await?; @@ -672,54 +748,106 @@ async fn enroll_pairs( // were left pointing at a class no sweep could ever reach again. /// Take a student out of a class and sweep the enrollments the class pumped -/// for them. Answers how many link rows went (0 or 1), so the caller can turn +/// for them. Answers how many stints went (0 or 1), so the caller can turn /// zero into a 404. /// -/// The sweep is *repair-first*: an enrollment this class wrote is only deleted -/// once no other class still claims it. Two classes attached to the same -/// course share a student — the second attach skipped the row the first had -/// already written, so the row carries only the first class's name — and -/// deleting it on the first class's way out would unenroll a student the -/// second class is still responsible for. So the row is re-tagged to that -/// rival instead, and only a row nobody is left to claim is deleted and its -/// seat given back. The heir is the lowest class id among the claimants: a -/// deterministic pick (uuid order is mint order), so a repeat of the same -/// sweep lands on the same class. +/// This is the hard form — the row is deleted — and it is kept only for the +/// transfer rollback path, where the stint being undone must leave no trace. +/// The route uses [`leave_member`], which stamps `left_at` and keeps the +/// history. +pub(crate) async fn remove_member( + db: &Database, + class: &ClassGroupId, + user: &UserId, +) -> Result { + drop_member(db, class, user, false).await +} + +/// The same exit, soft: `left_at` is stamped and the row stays as history. +/// The roster read and the cap both filter on `left_at IS NULL`, so the +/// student holds no seat from this moment — and a rejoin later inserts a +/// fresh live row beside this one (the partial unique index only guards the +/// live stint), which is how "left in October, came back in January" is +/// represented. +/// +/// Both exits take the user row `FOR NO KEY UPDATE` first — the same lock the +/// pump's pivot claim and a role-change sweep take — so a demotion cannot +/// interleave with this write in either direction. +pub(crate) async fn leave_member( + db: &Database, + class: &ClassGroupId, + user: &UserId, +) -> Result { + drop_member(db, class, user, true).await +} + +/// The one body both exits run: find the live stint, end it, give the class +/// its seat back, and release the enrollments the class pumped for the +/// student. /// -/// That pick is then **claimed** — a `FOR NO KEY UPDATE` read of the heir's -/// class row, no counter moved — before the row is handed over. Both reads -/// behind it are pure, and this sweep is long — one pass per enrollment row -/// the link implies — so `DELETE /classes/{heir}/members/{user}` and -/// `DELETE /classes/{heir}/courses/{course}` could both commit inside it and -/// leave the row tagged with a class holding neither link: a `class_group` -/// whose own 0/0 delete guard then passes, stranding an enrollment nothing can -/// ever sweep. Every one of those writers moves a counter on the heir's own -/// row, so the row lock here puts this transaction on the record they write -/// and the two settle in either order. A claim that matches nothing is an -/// heir whose class row is gone — a stale link outliving its class — and it -/// takes the release arm rather than tagging the row with an id no route can -/// reach. +/// The sweep's rule, and it is the whole rule: **every row the ended stint +/// owned goes, and each instance gets its roster count back**. An enrollment +/// is keyed `(class_course, app_user)` — one row per *instance* — so a student +/// in two şubeler that teach the same course holds two rows, one on each +/// section's instance, and the seat they keep is the other section's own row, +/// written when they joined it. Handing this row over to a rival class (the +/// pre-remodel rule, when one school-wide course carried one roster) would +/// leave the leaving section's roster, exams and roll-call still listing a +/// student who left it, with its `enrollment_count` inflated on top — a +/// "repair" that repairs nothing, because there was never a shortage of rows +/// to repair. /// -/// Sweeps tolerate rows that are already gone. A course delete wipes a -/// course's enrollments wholesale while the `class_member` rows survive it, so +/// Only the rows *this class* wrote are in the list ([`drop_member`] reads +/// `source = `), so a hand-placed enrollment — the operator's own, or +/// one a section handed over before this rule — is never touched. +/// +/// Sweeps tolerate rows that are already gone: an instance detach wipes its +/// own enrollments wholesale while the `class_member` rows survive it, so /// "this class has a member" and "that member has a live pumped row" are -/// independent facts and the loop simply finds nothing to sweep. -pub(crate) async fn remove_member( +/// independent facts and the loop simply finds nothing to sweep (and, because +/// [`release`] only gives a count back for a row it actually deleted, takes +/// nothing back twice). +async fn drop_member( db: &Database, class: &ClassGroupId, user: &UserId, + soft: bool, ) -> Result { let class = class.clone(); let user = *user; + let now = Timestamp::now(); tx_with_retry(db, true, async move |tx| { - let gone = sqlx::query_scalar!( - r#"DELETE FROM class_member WHERE class = $1 AND app_user = $2 - RETURNING 1 AS "one""#, - class as _, + // The role-claim handshake: the same `FOR NO KEY UPDATE` the pump's + // pivot takes, so a demotion's sweep and this exit serialize on the + // user row rather than interleaving. + sqlx::query!( + r#"SELECT role FROM app_user WHERE id = $1 FOR NO KEY UPDATE"#, user as _ ) .fetch_optional(&mut *tx) .await?; + let gone = if soft { + sqlx::query_scalar!( + r#"UPDATE class_member SET left_at = $3 + WHERE class = $1 AND app_user = $2 AND left_at IS NULL + RETURNING 1 AS "one""#, + class as _, + user as _, + now as _ + ) + .fetch_optional(&mut *tx) + .await? + } else { + sqlx::query_scalar!( + r#"DELETE FROM class_member + WHERE class = $1 AND app_user = $2 AND left_at IS NULL + RETURNING 1 AS "one""#, + class as _, + user as _ + ) + .fetch_optional(&mut *tx) + .await? + }; let Some(_) = gone else { return Ok(0); }; @@ -731,8 +859,11 @@ pub(crate) async fn remove_member( ) .execute(&mut *tx) .await?; + // Only the rows *this class* wrote: a hand-placed enrollment is the + // operator's and is never taken back by a class sweep. let rows = sqlx::query!( - r#"SELECT course AS "course: uuid::Uuid", app_user AS "app_user: uuid::Uuid" + r#"SELECT class_course AS "class_course: uuid::Uuid", + app_user AS "app_user: uuid::Uuid" FROM enrollment WHERE app_user = $1 AND source = $2"#, user as _, class as _ @@ -740,36 +871,70 @@ pub(crate) async fn remove_member( .fetch_all(&mut *tx) .await? .into_iter() - .map(|row| (row.course, row.app_user)) + .map(|row| (row.class_course, row.app_user)) .collect::>(); - sweep_enrollments(tx, &class, rows).await?; + // Every row this class's tag owns goes, and each instance gets its + // roster count back — see the doc above: the student's seat in a + // second şube teaching the same course is that şube's *own* row, so + // there is no heir to hand this one over to. + for (instance, member) in rows { + release(tx, instance, member).await?; + } Ok(1) }) .await } -/// Detach `course` from `class` and sweep the enrollments the class pumped -/// into it. `source`, when given, re-asserts the provenance tag on the link's -/// own delete — a blueprint sweep may only take back rows its own tag owns. -/// Answers how many link rows went, so a caller whose link was a single pair -/// can turn zero into a 404. The sweep underneath is the shared one: a student -/// a second class still claims is re-tagged rather than unenrolled. +/// Detach one instance from its class and sweep what hangs off it. `source`, +/// when given, re-asserts the provenance tag on the link's own delete — a +/// blueprint sweep may only take back rows its own tag owns. Answers the blob +/// keys of the image and homework-file rows the sweep removed, or `None` when +/// the pair held no instance at all (nothing written), so a caller whose link +/// was a single pair can turn `None` into a 404 while a detach that removed an +/// instance carrying no uploads still reads as one that went. +/// +/// The instance is the anchor now, so detaching it takes everything the class +/// taught under it: its exams (with their results and questions), its sessions +/// with their roll call, its homework with its submissions, its roster and its +/// teacher links. That is the same cascade a course delete runs +/// ([`crate::db::course::sweep_instance_subtree`]), scoped to one instance — +/// and it has to be, because every one of those rows names the instance as its +/// parent key (`ON DELETE NO ACTION`), so deleting the instance while they +/// stand is refused by the store itself. +/// +/// The sweep runs behind a `FOR UPDATE` claim on the instance row: a rival +/// detach waits here and finds nothing left to sweep, so exactly one +/// transaction unlinks the pair and gives the class its counter back — and +/// with it the catalog's `class_course_count`, the count +/// [`crate::db::course::delete`]'s guard reads (`course::delete` needs no +/// release of its own: it deletes the course row the counter lives on). +/// This is the only delete path for an instance that does *not* remove the +/// course: the hand detach and the blueprint sweep both come through it. +/// +/// The image and homework-file *blobs* the cascade removes come back as keys +/// and are unlinked by the caller, after the commit — the same shape +/// [`crate::service::course::delete`] has. The rows are gone the moment this +/// returns, so a caller that drops the list strands the bytes on disk with +/// nothing left pointing at them. pub(crate) async fn detach_course( db: &Database, class: &ClassGroupId, course: &CourseId, source: Option<&ClassBlueprintId>, -) -> Result { +) -> Result>, AppError> { let class = class.clone(); let course = course.clone(); let source = source.cloned(); tx_with_retry(db, true, async move |tx| { - let gone = match &source { + // The claim and the resolution in one read: the row this returns is + // the very row the lock holds against a rival detach. + let target = match &source { Some(source) => { sqlx::query_scalar!( - r#"DELETE FROM class_course WHERE class = $1 AND course = $2 + r#"SELECT id AS "id: uuid::Uuid" FROM class_course + WHERE class = $1 AND course = $2 AND source = (SELECT id FROM class_blueprint WHERE grade = $3) - RETURNING 1 AS "one""#, + FOR UPDATE"#, class as _, course as _, source as _ @@ -779,8 +944,8 @@ pub(crate) async fn detach_course( } None => { sqlx::query_scalar!( - r#"DELETE FROM class_course WHERE class = $1 AND course = $2 - RETURNING 1 AS "one""#, + r#"SELECT id AS "id: uuid::Uuid" FROM class_course + WHERE class = $1 AND course = $2 FOR UPDATE"#, class as _, course as _ ) @@ -788,9 +953,13 @@ pub(crate) async fn detach_course( .await? } }; - let Some(_) = gone else { - return Ok(0); + let Some(instance) = target else { + return Ok(None); }; + let blobs = crate::db::course::sweep_instance_subtree(&mut *tx, instance).await?; + sqlx::query!(r#"DELETE FROM class_course WHERE id = $1"#, instance) + .execute(&mut *tx) + .await?; sqlx::query!( r#"UPDATE class_group SET class_course_count = GREATEST(class_course_count - 1, 0) @@ -799,92 +968,41 @@ pub(crate) async fn detach_course( ) .execute(&mut *tx) .await?; - let rows = sqlx::query!( - r#"SELECT course AS "course: uuid::Uuid", app_user AS "app_user: uuid::Uuid" - FROM enrollment WHERE course = $1 AND source = $2"#, - course as _, - class as _ - ) - .fetch_all(&mut *tx) - .await? - .into_iter() - .map(|row| (row.course, row.app_user)) - .collect::>(); - sweep_enrollments(tx, &class, rows).await?; - Ok(1) - }) - .await -} - -/// The repair-first tail both detaches share: for every enrollment row the -/// deleted link owned, hand it to a rival class that still claims it, or -/// delete it and give the course its seat back. -/// -/// The heir is the lowest class id among the rivals that carry both this -/// course *and* the student — the same deterministic pick on every repeat. Its -/// class row is read `FOR NO KEY UPDATE` (a claim that moves no counter: the -/// class_member row already covers the student, and the enrollment is counted -/// on the course) so a concurrent member/course write on the heir serializes -/// behind this transaction; a claim matching nothing is a gone heir, and the -/// row takes the release arm. -async fn sweep_enrollments( - tx: &mut PgConnection, - class: &ClassGroupId, - rows: Vec<(uuid::Uuid, uuid::Uuid)>, -) -> Result<(), AppError> { - for (course, user) in rows { - let heir = sqlx::query_scalar!( - r#"SELECT cm.class AS "class: uuid::Uuid" - FROM class_member cm - JOIN class_course cc ON cc.class = cm.class AND cc.course = $1 - WHERE cm.app_user = $2 AND cm.class <> $3 - ORDER BY cm.class - LIMIT 1"#, - course, - user, - class as _ - ) - .fetch_optional(&mut *tx) - .await?; - let Some(heir) = heir else { - release(tx, course, user).await?; - continue; - }; - let claimed = sqlx::query_scalar!( - r#"SELECT class_member_count AS "heir_count: i64" FROM class_group - WHERE id = $1 FOR NO KEY UPDATE"#, - heir - ) - .fetch_optional(&mut *tx) - .await?; - if claimed.is_none() { - release(tx, course, user).await?; - continue; - } + // …and the catalog's own counter: the course is taught in one fewer + // şube from this commit. Same transaction as the delete, so the link + // and its count move together — `course::delete`'s guard reads this, + // and a course whose last instance was just detached is deletable the + // moment this lands. `GREATEST` for the same reason the class counter + // uses it: a drift can only ever be repaired downward, never refused. sqlx::query!( - r#"UPDATE enrollment SET source = $1 WHERE course = $2 AND app_user = $3"#, - heir, - course, - user + r#"UPDATE course SET class_course_count = GREATEST(class_course_count - 1, 0) + WHERE id = $1"#, + course as _ ) .execute(&mut *tx) .await?; - } - Ok(()) + Ok(Some(blobs)) + }) + .await } -/// Nobody is left to claim the row: it goes, and its seat with it. The seat -/// is only given back when the delete actually took the row — a course -/// delete's wholesale sweep may have taken both while this transaction read -/// them, and both halves vanish together there. +/// The row goes, and the instance's roster count with it. It is the *only* +/// fate for an enrollment a section's exit owns: the roster is per instance +/// (D4), so a student who is also in another şube teaching the same course +/// keeps their seat there through that section's own row — see +/// [`drop_member`]. +/// +/// The count is only given back when the delete actually took the row — an +/// instance detach's wholesale sweep may have taken both while this +/// transaction read them, and both halves vanish together there. async fn release( tx: &mut PgConnection, - course: uuid::Uuid, + instance: uuid::Uuid, user: uuid::Uuid, ) -> Result<(), AppError> { let deleted = sqlx::query!( - r#"DELETE FROM enrollment WHERE course = $1 AND app_user = $2"#, - course, + r#"DELETE FROM enrollment WHERE class_course = $1 AND app_user = $2"#, + instance, user ) .execute(&mut *tx) @@ -892,22 +1010,24 @@ async fn release( .rows_affected(); if deleted > 0 { sqlx::query!( - r#"UPDATE course SET enrollment_count = GREATEST(enrollment_count - 1, 0) - WHERE id = $1"#, - course + r#"UPDATE class_course + SET enrollment_count = GREATEST(enrollment_count - 1, 0) + WHERE id = $1"#, + instance ) .execute(&mut *tx) .await?; } Ok(()) } + #[cfg(test)] mod tests { - + use crate::db::class_member::tests::{a_class, counter, fixture_user, rows}; use crate::domain::class_group::ClassGroupId; use crate::error::AppError; - use crate::service::{class_course, class_member}; + use crate::service::class_member; /// The class counter is claimed conditionally, so a class that is not there /// stops the cascade before anything is written — rather than leaving a @@ -971,100 +1091,4 @@ mod tests { "a second removal is a 404, not a silent no-op: {again:?}" ); } - - /// The heir a sweep hands a shared enrollment to must still hold *both* - /// links when the transaction commits — not merely when it read them. - /// - /// Two classes carry one course and one student, so the row names the first - /// and the second is its heir. While that first class's detach sweeps — a - /// pass per enrollment row, up to a full roster long — the heir drops the - /// student and detaches the course, both committed. Its two reads see an - /// heir that is already gone, and its write set (its own class, its own - /// link, the enrollment) touches nothing the heir's two deletes wrote: with - /// no read-set conflict detection, both sides commit and the row is left - /// tagged with a class holding neither link, which then passes its own 0/0 - /// delete guard. The claim on the heir's counter is what puts the two - /// transactions on one record. - /// - /// Real server, and `#[ignore]`d for it, exactly like - /// [`crate::domain::class_course`]'s course-delete twin: the subject *is* - /// the store's conflict detection, which `init_mem`'s embedded engine does - /// not have — it commits both sides and answers `Ok` to each, so this passes - /// there on broken code. - /// - /// The window the old engine needed a schema event to open is the row - /// lock now: the owner's sweep claims the heir's class row before it - /// chooses the heir, so the heir's own member/course writes either land - /// wholly before the sweep reads them or wait behind it — and the - /// invariant below must hold in both orders. A barrier start lets every - /// interleaving happen instead of pinning one. - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - async fn a_detached_row_is_never_handed_to_a_class_that_let_it_go() { - use crate::db::class_member::tests::{a_course, fixture_user, source_of}; - - let (db, _leases) = crate::database::init_test_db().await; - let manager = fixture_user(&db, "manager").await; - let student = fixture_user(&db, "student").await; - let (mut raced, mut stranded) = (0, 0); - for round in 0..4 { - let algebra = a_course(&format!("algebra{round}"), None, &db).await; - let owner = a_class(&format!("9-{round}-owner"), &db).await; - let heir = a_class(&format!("9-{round}-heir"), &db).await; - for class in [&owner, &heir] { - class_member::add(&db, class, &student, &manager) - .await - .unwrap(); - class_course::attach(&db, class, &algebra, &manager) - .await - .unwrap(); - } - assert_eq!( - source_of(&algebra, &student, &db).await, - Some(Some(owner.clone())), - "round {round}: the row must start out owned by the first class" - ); - - let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); - let detaching = { - let (db, owner, algebra, gate) = - (db.clone(), owner.clone(), algebra.clone(), gate.clone()); - tokio::spawn(async move { - gate.wait().await; - class_course::detach(&db, &owner, &algebra).await - }) - }; - // The heir lets the row go, twice over, while the sweep is racing - // it for the same enrollment row. - let heir_moves = { - let (db, heir, algebra, gate) = - (db.clone(), heir.clone(), algebra.clone(), gate); - tokio::spawn(async move { - gate.wait().await; - class_member::remove(&db, &heir, &student).await?; - class_course::detach(&db, &heir, &algebra).await - }) - }; - let swept = detaching.await.unwrap(); - heir_moves.await.unwrap().unwrap(); - assert!( - !matches!(swept, Err(AppError::Db(_))), - "round {round}: a raced detach must be answered, not 500: {swept:?}" - ); - - // Stored state is the whole verdict; a return value is not evidence. - if swept.is_ok() { - raced += 1; - } - if source_of(&algebra, &student, &db).await == Some(Some(heir.clone())) { - stranded += 1; - } - } - eprintln!("a detach raced by its heir: {raced}/4 rounds swept"); - assert!(raced > 0, "no round ever committed its sweep"); - assert_eq!( - stranded, 0, - "an enrollment was left tagged with a class holding neither link" - ); - } - } diff --git a/src/db/course.rs b/src/db/course.rs index b13a57d..10cc16c 100644 --- a/src/db/course.rs +++ b/src/db/course.rs @@ -1,25 +1,25 @@ -//! The `course` table: the unit exams, sessions, subjects and enrollments -//! hang off. Listed newest first; deleted with its whole subtree in one -//! guarded cascade. +//! The `course` table: the school-level catalog exams, sessions, subjects and +//! enrollments hang off *through their instances* ([`crate::db::class_course`]). +//! Listed newest first; deleted with its whole subtree in one guarded cascade. +//! +//! The catalog is a template since the K12 remodel (D1): the academic work — +//! roster, exams, timetable, teachers — lives on the instances a şube attaches, +//! so this row carries only what every instance shares (title, description, +//! kind) and two counters. The catalog is Manager+-owned (D6): there is no +//! per-teacher ownership list, and the two counters are the delete guard. use crate::constant::COURSE_TABLE; use crate::database::{Database, tx_with_retry, unique_violation}; -use crate::db::cap; -use crate::db::field_update::{FieldUpdate, Refcount}; use crate::db::page::PagedList; use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle}; -use crate::domain::term::{self, TermId}; use crate::domain::user::UserId; use crate::error::AppError; +use sqlx::PgConnection; -use std::collections::HashMap; - -/// The stored columns of a `course` row. The assigned teachers live across -/// the `course_teacher` junction, not on this row, so every read joins them -/// on in one batch afterwards ([`into_courses`]) — the two generic readers -/// below (the paged list and the field-scoped PATCH) both read whole rows -/// (`SELECT *` / `RETURNING *`), which is a shape no aggregate column can -/// ride. +/// The stored columns of a `course` row — the whole row. The assigned-teacher +/// list this struct used to join on moved to the instances +/// ([`crate::db::class_course_teacher`]), so a course read is one statement +/// again. #[derive(Debug, sqlx::FromRow)] struct CourseRow { id: CourseId, @@ -27,131 +27,56 @@ struct CourseRow { title: CourseTitle, description: CourseDescription, kind: CourseKind, - term: Option, - capacity: Option, + class_course_count: i64, + course_membership_count: i64, } impl CourseRow { - fn into_course(self, teachers: Vec) -> Course { + fn into_course(self) -> Course { Course { id: self.id, creator: self.creator, - teachers, title: self.title, description: self.description, kind: self.kind, - term: self.term, - capacity: self.capacity, + class_course_count: self.class_course_count, + course_membership_count: self.course_membership_count, } } } -/// Assemble [`Course`]s (their assigned teachers included) out of row reads: -/// one `course_teacher` query for the whole batch, a course nobody is -/// assigned to reading an empty list. -async fn into_courses(db: &Database, rows: Vec) -> Result, AppError> { - if rows.is_empty() { - return Ok(Vec::new()); - } - let ids: Vec = rows.iter().map(|row| row.id.uuid()).collect(); - let links = sqlx::query!( - r#"SELECT course AS "course: CourseId", teacher AS "teacher: UserId" - FROM course_teacher WHERE course = ANY($1)"#, - &ids, - ) - .fetch_all(db) - .await?; - let mut by_course: HashMap> = HashMap::new(); - for link in links { - by_course - .entry(link.course.uuid()) - .or_default() - .push(link.teacher); - } - Ok(rows - .into_iter() - .map(|row| { - let teachers = by_course.remove(&row.id.uuid()).unwrap_or_default(); - row.into_course(teachers) - }) - .collect()) -} - -/// [`into_courses`] for a single row. -async fn one_course(db: &Database, row: CourseRow) -> Result { - let course = into_courses(db, vec![row]) - .await? - .pop() - .expect("one row in, one course out"); - Ok(course) -} - +/// Mint a catalog course. No term is claimed any more: the catalog is not +/// bound to a dönem (exams are, through their instance), and no capacity is +/// stored — the roster counter lives on the instance and gates nothing. pub async fn create( db: &Database, creator: &UserId, title: CourseTitle, description: CourseDescription, kind: CourseKind, - term: Option, - capacity: Option, ) -> Result { let id = CourseId::generate(); - let Some(term) = term else { - let created = sqlx::query_as!( - CourseRow, - r#"INSERT INTO course (id, creator, title, description, kind, term, capacity) - VALUES ($1, $2, $3, $4, $5, NULL, $6) - RETURNING id AS "id: CourseId", creator AS "creator: UserId", - title AS "title: CourseTitle", - description AS "description: CourseDescription", - kind AS "kind: CourseKind", term AS "term: TermId", capacity"#, - id.uuid(), - creator.uuid(), - title.as_str(), - description.as_str(), - kind.as_str(), - capacity, - ) - .fetch_one(db) - .await?; - // A new course has no assigned teachers; the join reads an empty list. - return one_course(db, created).await; - }; - // Claim a reference on the term in the *same statement* as the row: the - // claim is a conditional write on the term row, so it fails when the - // term is already gone and it makes the term undeletable the instant - // this link exists — and a crash can never leave one without the other, - // which a claim sent as its own query could (the count would strand and - // the term be undeletable forever). let created = sqlx::query_as!( CourseRow, - r#"WITH seat AS ( - UPDATE term - SET course_count = course_count + 1 - WHERE id = $7 AND course_count < $8 - RETURNING 1) - INSERT INTO course (id, creator, title, description, kind, term, capacity) - SELECT $1, $2, $3, $4, $5, $7, $6 WHERE EXISTS (SELECT 1 FROM seat) + r#"INSERT INTO course (id, creator, title, description, kind) + VALUES ($1, $2, $3, $4, $5) RETURNING id AS "id: CourseId", creator AS "creator: UserId", - title AS "title: CourseTitle", - description AS "description: CourseDescription", - kind AS "kind: CourseKind", term AS "term: TermId", capacity"#, + title AS "title: CourseTitle", + description AS "description: CourseDescription", + kind AS "kind: CourseKind", class_course_count, course_membership_count"#, id.uuid(), creator.uuid(), title.as_str(), description.as_str(), kind.as_str(), - capacity, - term.uuid(), - cap::UNLIMITED, ) .fetch_one(db) .await; match created { - Ok(created) => one_course(db, created).await, - // Uncapped, so "full" can only mean the conditional write matched no - // term row at all — the existence check the pre-flight lookup makes. - Err(sqlx::Error::RowNotFound) => Err(term::gone_error()), + Ok(created) => Ok(created.into_course()), + // The creator is a foreign key: a gone account is the same `NotFound` + // the web layer's own read answers with, never an orphan row. + Err(err) if crate::database::foreign_key_violation(&err) => Err(AppError::NotFound), // Unreachable: the id was minted above. Err(err) if unique_violation(&err).is_some() => { Err(AppError::Internal("failed to create course".into())) @@ -166,7 +91,7 @@ async fn read_row(db: &Database, id: &CourseId) -> Result, App r#"SELECT id AS "id: CourseId", creator AS "creator: UserId", title AS "title: CourseTitle", description AS "description: CourseDescription", - kind AS "kind: CourseKind", term AS "term: TermId", capacity + kind AS "kind: CourseKind", class_course_count, course_membership_count FROM course WHERE id = $1"#, id.uuid(), ) @@ -176,10 +101,7 @@ async fn read_row(db: &Database, id: &CourseId) -> Result, App } pub async fn read(db: &Database, id: &CourseId) -> Result, AppError> { - match read_row(db, id).await? { - Some(row) => Ok(Some(one_course(db, row).await?)), - None => Ok(None), - } + Ok(read_row(db, id).await?.map(CourseRow::into_course)) } pub async fn list_all(db: &Database) -> Result, AppError> { @@ -188,16 +110,17 @@ pub async fn list_all(db: &Database) -> Result, AppError> { r#"SELECT id AS "id: CourseId", creator AS "creator: UserId", title AS "title: CourseTitle", description AS "description: CourseDescription", - kind AS "kind: CourseKind", term AS "term: TermId", capacity + kind AS "kind: CourseKind", class_course_count, course_membership_count FROM course ORDER BY id DESC"#, ) .fetch_all(db) .await?; - into_courses(db, rows).await + Ok(rows.into_iter().map(CourseRow::into_course).collect()) } -/// The courses `user` is enrolled in — the spine of `/courses/me` and the -/// marks report. +/// The courses `user` is enrolled in — read through the *instances* their +/// enrollments name, since an enrollment keys on the class×course instance. +/// The spine of `/courses/me` and the marks report. pub async fn list_enrolled( db: &Database, user: &UserId, @@ -205,42 +128,49 @@ pub async fn list_enrolled( offset: i64, ) -> Result<(Vec, i64), AppError> { let (rows, total) = PagedList::new( - "course WHERE id IN (SELECT course FROM enrollment WHERE app_user = $1)", + "course WHERE id IN ( + SELECT cc.course FROM enrollment e + JOIN class_course cc ON cc.id = e.class_course + WHERE e.app_user = $1)", "ORDER BY id DESC", ) .bind(user.uuid()) .run::(limit, offset, db) .await?; - Ok((into_courses(db, rows).await?, total)) + Ok(( + rows.into_iter().map(CourseRow::into_course).collect(), + total, + )) } -/// The courses `user` runs — the ones they created plus the ones a manager -/// assigned them to. A teacher's slice of the catalog. +/// The courses `user` teaches somewhere — the ones a manager assigned them to +/// on some instance. A teacher's slice of the catalog. /// -/// The assigned half reads `course_teacher` by its `teacher` index (the -/// shape `enrollment` already has) instead of an array membership test — -/// that test was the corner-cut here once, and the junction is exactly the -/// upgrade path the old comment called structural. +/// It reads `class_course_teacher` by its `teacher` index and follows each +/// assignment to the catalog course its instance teaches: a teacher who runs +/// 5-A's Matematik sees Matematik. The old creator-membership half is gone +/// with D6 — the catalog is Manager+ owned. pub async fn list_for_teacher(db: &Database, user: &UserId) -> Result, AppError> { let rows = sqlx::query_as!( CourseRow, r#"SELECT id AS "id: CourseId", creator AS "creator: UserId", title AS "title: CourseTitle", description AS "description: CourseDescription", - kind AS "kind: CourseKind", term AS "term: TermId", capacity - FROM course WHERE creator = $1 OR id IN ( - SELECT course FROM course_teacher WHERE teacher = $2) + kind AS "kind: CourseKind", class_course_count, course_membership_count + FROM course WHERE id IN ( + SELECT cc.course FROM class_course_teacher t + JOIN class_course cc ON cc.id = t.class_course + WHERE t.teacher = $1) ORDER BY id DESC"#, user.uuid(), - user.uuid(), ) .fetch_all(db) .await?; - into_courses(db, rows).await + Ok(rows.into_iter().map(CourseRow::into_course).collect()) } /// Load every course behind `ids` (one query) — the join half of the -/// attendance report's per-course blocks. +/// attendance and marks reports' per-course blocks. pub async fn list_by_ids(db: &Database, ids: &[CourseId]) -> Result, AppError> { if ids.is_empty() { return Ok(Vec::new()); @@ -251,144 +181,58 @@ pub async fn list_by_ids(db: &Database, ids: &[CourseId]) -> Result, r#"SELECT id AS "id: CourseId", creator AS "creator: UserId", title AS "title: CourseTitle", description AS "description: CourseDescription", - kind AS "kind: CourseKind", term AS "term: TermId", capacity + kind AS "kind: CourseKind", class_course_count, course_membership_count FROM course WHERE id = ANY($1)"#, &keys, ) .fetch_all(db) .await?; - into_courses(db, rows).await + Ok(rows.into_iter().map(CourseRow::into_course).collect()) } -/// Field-scoped: nothing guards the course row across the handler's read -/// and this write (the term it links is guarded by its own refcount write, -/// and the assign path takes no lock at all) — so a field the request omitted -/// (`None`) is not written at all. Sending the snapshot's value back -/// instead would revert a concurrent edit of that field; scoping the `SET` -/// alone does not stop that, the values have to come from the request. -/// `term` and `capacity` are nullable, so they take the outer/inner -/// `Option>`: `None` = omitted (keep), `Some(None)` = clear. +/// Field-scoped: a field the request omitted (`None`) is not written at all. +/// Sending the snapshot's value back instead would revert a concurrent edit of +/// that field; scoping the `SET` alone does not stop that, the values have to +/// come from the request. /// -/// The assigned teachers are not fields of this row — they are -/// `course_teacher` rows, written only by [`assign_teacher`], -/// [`unassign_teacher`] and the demotion sweep — so a PATCH can neither -/// carry nor clobber them. +/// The two counters and `creator` are not editable: the counters are what the +/// delete guard reads (a PATCH is not a roster change), and the creator is the +/// catalog's of record. pub async fn update( db: &Database, course: Course, title: Option, description: Option, kind: Option, - term: Option>, - capacity: Option>, ) -> Result { - // A term move claims the new term and releases the old one inside the - // very transaction that moves the link, so no crash can leave a count - // without its link (the term would be undeletable forever) or a link - // without its count. A PATCH that carried no `term_id`, or re-stated the - // link it already had, moves neither counter. - let (claim, release) = term::ref_move(course.term.as_ref(), &term); - let row = FieldUpdate::new(COURSE_TABLE, course.id.uuid()) + let row = crate::db::field_update::FieldUpdate::new(COURSE_TABLE, course.id.uuid()) .set("title", title.map(|title| title.as_str().to_owned())) .set( "description", description.map(|description| description.as_str().to_owned()), ) .set("kind", kind.map(|kind| kind.as_str().to_owned())) - .set( - "term", - term.map(|term| crate::db::page::Param::OptUuid(term.map(|term| term.uuid()))), - ) - .set("capacity", capacity.map(crate::db::page::Param::OptI64)) - .refcount(Refcount { - counter_table: "term", - counter_field: "course_count", - link: "term", - expected: course.term.as_ref().map(|term| term.uuid()), - claim: claim.map(|term| term.uuid()), - release: release.map(|term| term.uuid()), - refused: term::gone_error(), - }) .run::(db) .await?; - // The teachers are joined on after the write, off the junction. - one_course(db, row).await + Ok(row.into_course()) } -/// Assign `teacher` to run this course, or return the course untouched if -/// they already run it — assignment is idempotent, like enrollment: the -/// link is an `INSERT` whose `(course, teacher)` key answers a duplicate -/// with `DO NOTHING`, so two requests naming the same teacher at once land -/// one row (the early return only sees a stale snapshot). -pub async fn assign_teacher( - db: &Database, - course: Course, - teacher: &UserId, -) -> Result { - if course.is_assigned(teacher) { - return Ok(course); - } - // `WHERE EXISTS` keeps the insert a no-op when the course went between - // the caller's read and this write — the answer is the `NotFound` the - // fresh read below gives, not a foreign-key 500. - sqlx::query!( - r#"INSERT INTO course_teacher (course, teacher) - SELECT $1, $2 WHERE EXISTS (SELECT 1 FROM course WHERE id = $1) - ON CONFLICT DO NOTHING"#, - course.id.uuid(), - teacher.uuid(), - ) - .execute(db) - .await?; - // Fresh read, like the `RETURNING` this replaced: the snapshot's - // teacher list can be stale (a concurrent assign). - let row = read_row(db, &course.id).await?.ok_or(AppError::NotFound)?; - one_course(db, row).await -} - -/// Drop `teacher` from this course. `None` when they weren't assigned, so -/// the web layer can answer 404 instead of pretending it removed someone. -pub async fn unassign_teacher( - db: &Database, - course: Course, - teacher: &UserId, -) -> Result, AppError> { - if !course.is_assigned(teacher) { - return Ok(None); - } - let deleted = sqlx::query!( - r#"DELETE FROM course_teacher WHERE course = $1 AND teacher = $2"#, - course.id.uuid(), - teacher.uuid(), - ) - .execute(db) - .await?; - if deleted.rows_affected() == 0 { - // Unassigned under the caller's feet — nothing was removed. - return Ok(None); - } - read(db, &course.id).await -} - -/// Strip `user` from every course they were assigned to — the sweep for a -/// user demoted below `teacher`, who may no longer run anything. -pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), AppError> { - sqlx::query!(r#"DELETE FROM course_teacher WHERE teacher = $1"#, user.uuid(),) - .execute(db) - .await?; - Ok(()) -} - -/// Delete the course and cascade-remove everything inside it: results, -/// attempts, answers, and question/answer images of its exams, its -/// homework with their submissions, submission files, and grades, its -/// enrollments, the class attachments that pumped some of them (each class -/// gets its count back, or it would be undeletable over rows pointing at -/// nothing), its sessions with their roll call, its subjects, and the -/// exams themselves. The children go in one transaction so a crash can't -/// leave an exam pointing at a deleted course. The image and -/// homework-file *blobs* are the web layer's to remove — it collects -/// their names before calling this. +/// Delete the course and cascade-remove everything inside it *through its +/// instances*: results, attempts, answers, and question/answer images of +/// their exams, their homework with submissions, submission files, and +/// grades, their enrollments, their sessions with their roll call, their +/// teachers, and — last — the `class_course` rows themselves (each class +/// getting its attachment counter back, or it would be undeletable over rows +/// pointing at nothing). The children go in one transaction so a crash can't +/// leave an exam pointing at a deleted course. The image and homework-file +/// *blobs* are the web layer's to remove — it collects their names before +/// calling this. +/// +/// The guard is the two counters on the locked row (D5/D6): an instance still +/// teaching this course refuses the delete, and so does an individual club +/// membership, because nothing here unlinks either. Detach the instances and +/// empty the memberships first — a catalog course whose last instance goes is +/// then deletable, which is the whole point of the catalog being a template. /// /// **Bank templates** survive it — they are a separate, reusable library /// spanning every course — so their `source_exam` and `subject` links are @@ -405,46 +249,48 @@ pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), App /// here like any other link, so a template stops naming a course the /// instant that course goes (the old `teachers`-style array made the id a /// permanent dangling value only the pump's [`crate::db::class_blueprint:: -/// prune`] could chase). The same transaction takes the course's -/// `course_teacher` assignment rows: an assigned teacher loses the course -/// with it. +/// prune`] could chase). The same transaction takes the instances' +/// `class_course_teacher` assignment rows: an assigned teacher loses the +/// instance with it. /// /// The **derived AI rows** (`rag_output` carries a denormalized `course` /// besides its note link) and the event **audience links** are FK children /// the old store let dangle: `rag_output` is disposable and dies here, and /// an event whose audience was "this course's students" keeps standing with /// `audience_course` cleared — an empty roster, exactly the documented -/// outcome of the class twin (`Course::delete` never touched `event`; it -/// still doesn't delete one). +/// outcome of the class twin (`ClassGroup::delete` never touched `event`; +/// it still doesn't delete one). /// /// The marks going with it give their exam kinds' references back, counted /// per kind inside this same transaction — the mirror of `Exam::delete`. /// Skipping it would leave every kind the course graded under counted /// forever, and a counted kind can never leave the school's settings. /// -/// **Order is the foreign-key graph, children first** (the old store had -/// no FKs, so its order was free): exam results/attempts/answers/images -/// and question images before `exam_question`; `exam_question` before -/// `exam`; homework files before submissions before results before -/// `homework`; roll-call rows before `course_session`; note files and -/// rag rows before `course_note`; `blueprint_course` and `course_teacher` -/// before the `course` row itself, whose `NO ACTION` FKs are checked the -/// moment the final `DELETE` runs. +/// **Order is the foreign-key graph, children first**: exam results/attempts/ +/// answers/audiences/images and question images before `exam_question`; +/// `exam_question` before `exam`; homework files before submissions before +/// results before `homework`; roll-call rows before `course_session`; +/// enrollment / teacher / audience rows before `class_course`; note files and +/// rag rows before `course_note`; `blueprint_course`, `course_membership` and +/// `class_course` before the `course` row itself, whose `NO ACTION` FKs are +/// checked the moment the final `DELETE` runs. /// -/// `false` = refused, nothing was written: someone is still enrolled. The -/// guard locks the course row (`FOR UPDATE`) and reads its own -/// `enrollment_count`, so an enroll racing this either takes its seat -/// first (and the delete is refused) or finds the row gone (and is refused -/// itself). `Err(NotFound)` keeps the answer a concurrent *delete* used -/// to get — and unlike the old one-statement guard, this one tells the two -/// apart without a second read. +/// `false` = refused, nothing was written: a class still teaches it, or +/// someone still holds a membership. The guard locks the course row +/// (`FOR UPDATE`) and reads its own counters, so an attach or a join racing +/// this either claims first (and the delete is refused) or finds the row gone +/// (and is refused itself). `Err(NotFound)` keeps the answer a concurrent +/// *delete* used to get — and unlike the old one-statement guard, this one +/// tells the two apart without a second read. pub async fn delete(db: &Database, course: Course) -> Result { tx_with_retry(db, true, async move |tx| { - // The guard and the lock: the row (and its roster count) cannot - // change under this transaction, and every enroll claim contends on - // this very row, so check and cascade are one decision. + // The guard and the lock: the row (and its two counters) cannot + // change under this transaction, and every attach or membership + // claim contends on this very row, so check and cascade are one + // decision. let guard = sqlx::query!( - r#"SELECT enrollment_count, term FROM course WHERE id = $1 FOR UPDATE"#, + r#"SELECT class_course_count, course_membership_count FROM course + WHERE id = $1 FOR UPDATE"#, course.id.uuid(), ) .fetch_optional(&mut *tx) @@ -452,43 +298,9 @@ pub async fn delete(db: &Database, course: Course) -> Result { let Some(guard) = guard else { return Err(AppError::NotFound); }; - if guard.enrollment_count != 0 { + if guard.class_course_count != 0 || guard.course_membership_count != 0 { return Ok(false); } - // The exam ids are needed twice — the kind_ref refund and the bank's - // source_exam clear — and must be collected before the sweeps take - // the rows they name. - let exams: Vec = - sqlx::query!(r#"SELECT id FROM exam WHERE course = $1"#, course.id.uuid(),) - .fetch_all(&mut *tx) - .await? - .into_iter() - .map(|row| row.id) - .collect(); - // Every mark the course ever gave gives its exam kind's reference - // back, counted per kind (mirrors `Exam::delete`). The kind rides - // the exam row — `exam_result` names its exam, not its kind. - sqlx::query!( - r#"UPDATE kind_ref k - SET count = GREATEST(k.count - s.n, 0) - FROM (SELECT e.kind, count(*) AS n FROM exam_result r - JOIN exam e ON r.exam = e.id - WHERE r.exam = ANY($1) GROUP BY e.kind) s - WHERE k.name = s.kind"#, - &exams, - ) - .execute(&mut *tx) - .await?; - // The term gets its reference back inside the same transaction. - if let Some(term) = guard.term { - sqlx::query!( - r#"UPDATE term SET course_count = GREATEST(course_count - 1, 0) - WHERE id = $1"#, - term, - ) - .execute(&mut *tx) - .await?; - } // Events aimed at this course keep standing, audience cleared. sqlx::query!( r#"UPDATE event SET audience_course = NULL WHERE audience_course = $1"#, @@ -496,49 +308,21 @@ pub async fn delete(db: &Database, course: Course) -> Result { ) .execute(&mut *tx) .await?; - // The exam subtree, deepest children first. - sqlx::query!(r#"DELETE FROM exam_result WHERE exam = ANY($1)"#, &exams) - .execute(&mut *tx) - .await?; - sqlx::query!(r#"DELETE FROM exam_attempt WHERE exam = ANY($1)"#, &exams) - .execute(&mut *tx) - .await?; - sqlx::query!(r#"DELETE FROM exam_answer WHERE exam = ANY($1)"#, &exams) - .execute(&mut *tx) - .await?; - sqlx::query!(r#"DELETE FROM answer_image WHERE exam = ANY($1)"#, &exams) - .execute(&mut *tx) - .await?; - sqlx::query!(r#"DELETE FROM question_image WHERE exam = ANY($1)"#, &exams) - .execute(&mut *tx) - .await?; - sqlx::query!(r#"DELETE FROM exam_question WHERE exam = ANY($1)"#, &exams) - .execute(&mut *tx) - .await?; - // The homework subtree: files, then submissions (whose graded_by - // link names a result deleted after them), then results. - sqlx::query!( - r#"DELETE FROM homework_file WHERE submission IN ( - SELECT id FROM homework_submission - WHERE homework IN (SELECT id FROM homework WHERE course = $1))"#, + // The instances and everything under them. The guard above refuses a + // course that still carries one, so this sweep is defensive: a counter + // is the guard's *input*, and a guard reading a stale number is + // exactly the shape this exists to survive. The blob keys it returns + // are already collected by the caller (`file_keys_for_course`), which + // reads them before the rows go, so they are dropped here. + let instances: Vec = sqlx::query_scalar!( + r#"SELECT id AS "id: uuid::Uuid" FROM class_course WHERE course = $1"#, course.id.uuid(), ) - .execute(&mut *tx) - .await?; - sqlx::query!( - r#"DELETE FROM homework_submission WHERE homework IN ( - SELECT id FROM homework WHERE course = $1)"#, - course.id.uuid(), - ) - .execute(&mut *tx) - .await?; - sqlx::query!( - r#"DELETE FROM homework_result WHERE homework IN ( - SELECT id FROM homework WHERE course = $1)"#, - course.id.uuid(), - ) - .execute(&mut *tx) + .fetch_all(&mut *tx) .await?; + for instance in &instances { + let _blobs = sweep_instance_subtree(&mut *tx, *instance).await?; + } // Derived AI rows for this course's notes — links before the rows // (`ON DELETE NO ACTION`). sqlx::query!( @@ -568,8 +352,8 @@ pub async fn delete(db: &Database, course: Course) -> Result { ) .execute(&mut *tx) .await?; - // Class attachments: detach and hand each class its count back in - // one statement, then strike the course out of every blueprint. + // The instances, each class handed its attachment counter back in + // the same statement. sqlx::query!( r#"WITH detached AS ( DELETE FROM class_course WHERE course = $1 RETURNING class) @@ -581,40 +365,20 @@ pub async fn delete(db: &Database, course: Course) -> Result { .execute(&mut *tx) .await?; sqlx::query!( - r#"DELETE FROM blueprint_course WHERE course = $1"#, - course.id.uuid(), - ) - .execute(&mut *tx) - .await?; - // The assignment links die with the course, before the row itself. - sqlx::query!( - r#"DELETE FROM course_teacher WHERE course = $1"#, + r#"DELETE FROM course_membership WHERE course = $1"#, course.id.uuid(), ) .execute(&mut *tx) .await?; - // Sessions with their roll call, then the roster itself. sqlx::query!( - r#"DELETE FROM session_attendance WHERE course = $1"#, + r#"DELETE FROM blueprint_course WHERE course = $1"#, course.id.uuid(), ) .execute(&mut *tx) .await?; - sqlx::query!( - r#"DELETE FROM course_session WHERE course = $1"#, - course.id.uuid() - ) - .execute(&mut *tx) - .await?; - sqlx::query!( - r#"DELETE FROM enrollment WHERE course = $1"#, - course.id.uuid() - ) - .execute(&mut *tx) - .await?; // The bank keeps its templates; their links to this course's - // content go first, so the subject/exam deletes below cannot trip - // a foreign key behind them. + // content go first, so the subject delete below cannot trip a + // foreign key behind them. sqlx::query!( r#"UPDATE bank_question SET subject = NULL WHERE subject IN (SELECT id FROM subject WHERE course = $1)"#, @@ -622,29 +386,6 @@ pub async fn delete(db: &Database, course: Course) -> Result { ) .execute(&mut *tx) .await?; - sqlx::query!( - r#"UPDATE bank_question SET source_exam = NULL WHERE source_exam = ANY($1)"#, - &exams, - ) - .execute(&mut *tx) - .await?; - // Subjects before exams would trip `exam.subject` — exams go first. - sqlx::query!(r#"DELETE FROM exam WHERE course = $1"#, course.id.uuid()) - .execute(&mut *tx) - .await?; - sqlx::query!( - r#"DELETE FROM homework_assignment WHERE homework IN ( - SELECT id FROM homework WHERE course = $1)"#, - course.id.uuid(), - ) - .execute(&mut *tx) - .await?; - sqlx::query!( - r#"DELETE FROM homework WHERE course = $1"#, - course.id.uuid() - ) - .execute(&mut *tx) - .await?; sqlx::query!(r#"DELETE FROM subject WHERE course = $1"#, course.id.uuid()) .execute(&mut *tx) .await?; @@ -657,10 +398,237 @@ pub async fn delete(db: &Database, course: Course) -> Result { .await } +/// Everything hanging off one instance, deleted children-first with the +/// counters it holds refunded — the sweep both [`crate::db::class_pump:: +/// detach_course`] and [`delete`] run, and the only place the instance's +/// foreign-key graph is spelled. +/// +/// The order is the graph: exam results/attempts/answers/audiences and +/// question/answer images before `exam_question`; the question rows give their +/// subjects' `exam_question_count` back and the results their kinds' +/// `kind_ref` count; bank templates keep standing with `source_exam` cleared; +/// homework files before submissions (whose `grad_by_result` stamp points at a +/// result row) before results before assignments before `homework`; roll-call +/// rows before `course_session`; then the roster, the teacher links and the +/// audience rows, and the caller takes the instance row itself last. +/// +/// Returns the blob keys of the image and homework-file rows it removed, so a +/// caller whose web route unlinks bytes can do it after the commit; a caller +/// that collected them beforehand ([`crate::service::course::delete`]) drops +/// them. +/// +/// **Every reference counter it gives back is driven by the rows a +/// `DELETE … RETURNING` actually removed** — `exam`→`term.exam_count`, +/// `exam_result`→`kind_ref.count`, `exam_question`→`subject.exam_question_count`, +/// `homework`→`subject.homework_count` — never by a count taken off a +/// statement-start snapshot. The difference is a race: `Exam::delete` and +/// `remove_result` release some of these counters themselves, so a +/// count-then-subtract pair would hand one row's reference back twice (a +/// counter one low, permanently — `GREATEST` only floors at zero), and a kind +/// still carrying marks could then be retired from settings. Fused this way an +/// interleaving is exact from either side: the loser's `DELETE` simply does +/// not return the row the winner took. +/// +/// The row locks it takes are the ones the children's own writers take (the +/// instance row `FOR UPDATE` is the caller's, before this runs), so a grade or +/// an upload racing the sweep either lands before it (and is swept) or finds +/// its parent gone and is refused. +pub(crate) async fn sweep_instance_subtree( + tx: &mut PgConnection, + instance: uuid::Uuid, +) -> Result, AppError> { + let exams: Vec = sqlx::query_scalar!( + r#"SELECT id AS "id: uuid::Uuid" FROM exam WHERE class_course = $1"#, + instance, + ) + .fetch_all(&mut *tx) + .await?; + // Every release below is driven by the rows a `DELETE … RETURNING` + // actually removed, in the shape [`crate::db::exam_result::remove`] uses, + // and never by a count taken off a statement-start snapshot: a concurrent + // `Exam::delete` or `remove_result` releases the same counters itself, so + // a count-then-subtract pair would release its row twice — a `kind_ref` + // one low permanently (GREATEST only floors at zero), which then lets a + // kind still carrying marks be retired from settings. + let image_files: Vec = sqlx::query_scalar!( + r#"SELECT file FROM question_image WHERE exam = ANY($1)"#, + &exams, + ) + .fetch_all(&mut *tx) + .await?; + let answer_image_files: Vec = sqlx::query_scalar!( + r#"SELECT file FROM answer_image WHERE exam = ANY($1)"#, + &exams, + ) + .fetch_all(&mut *tx) + .await?; + sqlx::query!( + r#"DELETE FROM exam_audience WHERE class_course = $1"#, + instance + ) + .execute(&mut *tx) + .await?; + // Every mark this sweep takes gives its exam kind's reference back, per + // kind, off the rows this statement removed. The kind rides the exam row — + // `exam_result` names its exam, not its kind — so the deleted rows are + // joined back to the exam they named *before* it goes (the exam row is + // still there: this runs ahead of the `DELETE FROM exam` at the end). + sqlx::query!( + r#"WITH gone AS ( + DELETE FROM exam_result WHERE exam = ANY($1) + RETURNING exam), + kinds AS ( + SELECT e.kind AS kind, count(*) AS n + FROM gone g JOIN exam e ON e.id = g.exam + GROUP BY e.kind) + UPDATE kind_ref k SET count = GREATEST(k.count - c.n, 0) + FROM kinds c WHERE k.name = c.kind"#, + &exams, + ) + .execute(&mut *tx) + .await?; + sqlx::query!(r#"DELETE FROM exam_attempt WHERE exam = ANY($1)"#, &exams) + .execute(&mut *tx) + .await?; + sqlx::query!(r#"DELETE FROM exam_answer WHERE exam = ANY($1)"#, &exams) + .execute(&mut *tx) + .await?; + sqlx::query!(r#"DELETE FROM answer_image WHERE exam = ANY($1)"#, &exams) + .execute(&mut *tx) + .await?; + sqlx::query!(r#"DELETE FROM question_image WHERE exam = ANY($1)"#, &exams) + .execute(&mut *tx) + .await?; + // The cascaded questions give their subject references back off the rows + // this statement removed, per subject — released with the delete, never + // counted ahead of it. + sqlx::query!( + r#"WITH gone AS ( + DELETE FROM exam_question WHERE exam = ANY($1) + RETURNING subject), + subs AS ( + SELECT subject, count(*) AS n FROM gone GROUP BY subject) + UPDATE subject s SET exam_question_count = GREATEST(s.exam_question_count - c.n, 0) + FROM subs c WHERE s.id = c.subject"#, + &exams, + ) + .execute(&mut *tx) + .await?; + // Bank templates survive the exam they were saved from — only the + // provenance link is cleared. + sqlx::query!( + r#"UPDATE bank_question SET source_exam = NULL WHERE source_exam = ANY($1)"#, + &exams, + ) + .execute(&mut *tx) + .await?; + // The swept exams give their dönem's reference back off the rows this + // statement removed, per term (the mirror of `Exam::delete`'s + // single-exam release): `db::exam::create` claimed `term.exam_count` for + // each of them, and a claim nothing releases leaves the dönem's + // `exam_count = 0` delete guard permanently failing — which takes the + // term, and the academic year whose own guard counts its dönems, down + // with it. Fused with the delete for the same reason the two releases + // above are: a concurrent single-exam delete releases its own claim, so a + // count taken before this statement could give one back twice. + sqlx::query!( + r#"WITH gone AS ( + DELETE FROM exam WHERE class_course = $1 + RETURNING term), + terms AS ( + SELECT term, count(*) AS n FROM gone GROUP BY term) + UPDATE term t SET exam_count = GREATEST(t.exam_count - c.n, 0) + FROM terms c WHERE t.id = c.term"#, + instance, + ) + .execute(&mut *tx) + .await?; + let homework_files: Vec = sqlx::query_scalar!( + r#"SELECT file FROM homework_file + WHERE submission IN (SELECT id FROM homework_submission WHERE homework IN ( + SELECT id FROM homework WHERE class_course = $1))"#, + instance, + ) + .fetch_all(&mut *tx) + .await?; + sqlx::query!( + r#"DELETE FROM homework_file + WHERE submission IN (SELECT id FROM homework_submission WHERE homework IN ( + SELECT id FROM homework WHERE class_course = $1))"#, + instance, + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + r#"DELETE FROM homework_submission WHERE homework IN ( + SELECT id FROM homework WHERE class_course = $1)"#, + instance, + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + r#"DELETE FROM homework_result WHERE homework IN ( + SELECT id FROM homework WHERE class_course = $1)"#, + instance, + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + r#"DELETE FROM homework_assignment WHERE homework IN ( + SELECT id FROM homework WHERE class_course = $1)"#, + instance, + ) + .execute(&mut *tx) + .await?; + // The homework rows give their subjects' counters back off the rows this + // statement removed, per subject — the same fused shape as the two above. + sqlx::query!( + r#"WITH gone AS ( + DELETE FROM homework WHERE class_course = $1 + RETURNING subject), + subs AS ( + SELECT subject, count(*) AS n FROM gone GROUP BY subject) + UPDATE subject s SET homework_count = GREATEST(s.homework_count - c.n, 0) + FROM subs c WHERE s.id = c.subject"#, + instance, + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + r#"DELETE FROM session_attendance WHERE class_course = $1"#, + instance + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + r#"DELETE FROM course_session WHERE class_course = $1"#, + instance + ) + .execute(&mut *tx) + .await?; + // The roster: every enrollment row of the instance, hand-placed included — + // the instance is the row's own parent key, so none can outlive it. + sqlx::query!( + r#"DELETE FROM enrollment WHERE class_course = $1"#, + instance + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + r#"DELETE FROM class_course_teacher WHERE class_course = $1"#, + instance + ) + .execute(&mut *tx) + .await?; + let mut blobs = image_files; + blobs.extend(answer_image_files); + blobs.extend(homework_files); + Ok(blobs) +} + /// A real course row, for the tests of every child that must now prove its -/// parent exists (`Exam`, `CourseSession`, `Subject` — see -/// [`cap::touch_and_create`]). A minted id nothing wrote is a 404 there, the -/// way a minted subject id already is for an exam question. +/// parent exists. A minted id nothing wrote is a 404 there, the way a minted +/// subject id already is for an exam question. #[cfg(test)] pub(crate) async fn a_test_course(db: &Database) -> CourseId { // The creator is a foreign key now: a real row, minted per call so @@ -681,17 +649,55 @@ pub(crate) async fn a_test_course(db: &Database) -> CourseId { CourseTitle::try_new("test course").unwrap(), CourseDescription::try_new("").unwrap(), CourseKind::course(), - None, - None, ) .await .unwrap() .id } +/// A real *instance* of that course, attached to a fresh class — the parent +/// every re-keyed child (exam, session, homework, enrollment) now hangs off, +/// for the tests of those children. +/// +/// Returned as a pair because a child write that names the instance usually +/// also wants the catalog course (a subject's `course`, a marks read's +/// course grouping); both are real rows, minted per call. +#[cfg(test)] +pub(crate) async fn a_test_instance( + db: &Database, +) -> (crate::domain::class_course::ClassCourseId, CourseId) { + use crate::domain::class_group::ClassName; + + let manager = UserId::generate(); + sqlx::query( + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, 'manager')", + ) + .bind(manager.uuid()) + .bind(format!("instance-fixture-{}", &manager.key()[30..])) + .execute(db) + .await + .unwrap(); + let class = crate::db::class_group::create( + db, + &manager, + ClassName::try_new("9-A").unwrap(), + None, + None, + None, + ) + .await + .unwrap(); + let course = a_test_course(db).await; + let attached = crate::service::class_course::attach(db, class.get_id(), &course, &manager) + .await + .unwrap(); + (attached.get_id().clone(), course) +} + /// The race half of "a child of a course must not survive its deletion", run /// for one child table: [`delete`] is held open by the schema and -/// `make` fires its create inside that window, four rounds. +/// `make` fires its create inside that window, eight rounds. /// /// The harness lives here, beside the cascade being raced, and each child names /// its own pin in its own module (`exam`, `course_session`, `subject`) — the @@ -700,12 +706,15 @@ pub(crate) async fn a_test_course(db: &Database) -> CourseId { /// things. The sequential half — a create against a course that is already gone /// — is `tests/regress_course_child_orphans.rs`, which needs no server. /// -/// The window is opened by the database rather than by a lucky interleaving: a -/// `DEFINE EVENT` on `course` fires *inside* the delete's own transaction the -/// instant the row goes, so the `SLEEP` lands between the delete and its -/// `DELETE WHERE course = $course` sweep every time — and a create -/// fired into it reads a course that is still there (removed, uncommitted) -/// while the sweep already ran on a snapshot without its row. +/// The orphan query is the caller's, because the child's key to the course is +/// not: `subject` still names the course directly, while an exam or a session +/// hangs off an *instance* ([`crate::db::class_course`]) and reaches the course +/// through it. Either way it takes the course uuid as `$1`. +/// +/// The window is opened by the database rather than by a lucky interleaving: +/// Postgres puts the racing create and delete on the same rows (the FK claims +/// and the cascade), so a barrier start covers every interleaving — and the +/// child may never outlive the course in any of them. /// /// One child per round, for the reason the menu and `class_course` twins /// document: a second writer makes the delete lose and re-send, and the re-sent @@ -718,6 +727,7 @@ pub(crate) async fn a_test_course(db: &Database) -> CourseId { #[cfg(test)] pub(crate) async fn assert_no_child_outlives_a_course_delete( table: &str, + orphan_count_sql: &str, make: fn(CourseId, Database) -> tokio::task::JoinHandle>, ) { use sqlx::Row as _; @@ -774,15 +784,13 @@ pub(crate) async fn assert_no_child_outlives_a_course_delete( // Stored state is the whole verdict; a return value is not evidence. if read(&db, &course).await.unwrap().is_none() { swept += 1; - orphans += sqlx::query(sqlx::AssertSqlSafe(format!( - "SELECT count(*) FROM {table} WHERE course = $1" - ))) - .bind(course.uuid()) - .fetch_one(&db) - .await - .unwrap() - .try_get::(0) - .unwrap() as usize; + orphans += sqlx::query(sqlx::AssertSqlSafe(orphan_count_sql.to_string())) + .bind(course.uuid()) + .fetch_one(&db) + .await + .unwrap() + .try_get::(0) + .unwrap() as usize; } else if matches!(dropped, Ok(true)) { panic!("{table} round {round}: the delete reported success, the course is still there"); } @@ -799,9 +807,8 @@ pub(crate) async fn assert_no_child_outlives_a_course_delete( mod tests { use super::*; use sqlx::Row as _; - use crate::domain::term::{Term, TermName}; - /// A real `app_user` row: creators, students and enrollers are foreign + /// A real `app_user` row: creators, attached-bys and managers are foreign /// keys now. The label names the row's username; the id is minted, so /// repeated calls are new people, not the same row. async fn a_person(db: &Database, label: &str, role: &str) -> UserId { @@ -819,129 +826,43 @@ mod tests { user } - async fn course_on(term: Option, db: &Database) -> Course { + /// A catalog course, minted per call. The catalog is a school-wide + /// template since the remodel: no dönem to link, no capacity to store. + async fn a_course(db: &Database) -> Course { create( db, &a_person(db, "teacher", "teacher").await, CourseTitle::try_new("algebra").unwrap(), CourseDescription::try_new("").unwrap(), CourseKind::course(), - term, - None, ) .await .unwrap() } - /// The bite test for the delete guard that replaced `ENROLL_LOCK`: the - /// roster check is now the `WHERE` on the delete itself, so only the guard - /// can refuse — and it must refuse having written nothing, cascade - /// included. A `>= 0` guard passes the roster branch and fails here. - #[tokio::test] - async fn a_course_with_a_roster_refuses_to_delete() { - let (db, _leases) = crate::database::init_test_db().await; - let teacher = a_person(&db, "teacher", "teacher").await; - let student = a_person(&db, "student", "student").await; - let course = course_on(None, &db).await; - crate::db::enrollment::enroll(&db, course.get_id(), &student, &teacher) - .await - .unwrap(); - - assert!( - !delete(&db, course.clone()).await.unwrap(), - "a non-empty roster must refuse the delete" - ); - assert!( - read(&db, course.get_id()).await.unwrap().is_some(), - "a refused delete may write nothing" - ); - assert!( - crate::db::enrollment::read_for_user(&db, course.get_id(), &student) - .await - .unwrap() - .is_some(), - "…the cascade least of all" - ); - - crate::db::enrollment::remove(&db, course.get_id(), &student) - .await - .unwrap(); - assert!(delete(&db, course.clone()).await.unwrap()); - assert!(read(&db, course.get_id()).await.unwrap().is_none()); - - // The other half of the same guard: once the course row is gone the - // seat claim matches nothing, so a late enroll is a 404 rather than a - // roster row that outlived its course. - let late = crate::db::enrollment::enroll(&db, course.get_id(), &student, &teacher) - .await - .expect_err("enrolling into a deleted course must fail"); - assert!(matches!(late, AppError::NotFound), "got {late:?}"); - } - - /// The bite test for the refcount that replaced `TERM_LOCK`: a term is - /// undeletable exactly while a course links it, and every way a link can - /// end — PATCH away, and the course's own delete — gives the reference - /// back. Dropping the release in `delete` leaves the term deletable never. - #[tokio::test] - async fn a_term_is_deletable_only_once_no_course_links_it() { - let (db, _leases) = crate::database::init_test_db().await; - let at = crate::domain::timestamp::Timestamp::from_millis; - let term = - crate::db::term::create(&db, TermName::try_new("2026").unwrap(), at(100), at(200)) - .await - .unwrap(); - - let linked = course_on(Some(*term.get_id()), &db).await; - let patched = course_on(Some(*term.get_id()), &db).await; - assert!( - !crate::db::term::delete(&db, term.clone()).await.unwrap(), - "two linked courses must refuse the delete" - ); - - update(&db, patched, None, None, None, Some(None), None) - .await - .unwrap(); - assert!( - !crate::db::term::delete(&db, term.clone()).await.unwrap(), - "one link is still one link" - ); - - assert!(delete(&db, linked).await.unwrap()); - assert!( - crate::db::term::delete(&db, term.clone()).await.unwrap(), - "the last link gone, the term may go" - ); - let again = crate::db::term::delete(&db, term).await; - assert!( - matches!(again, Err(AppError::NotFound)), - "a second delete is a 404, not a refusal: {again:?}" - ); - } - - /// The claim doubles as the existence check the lock used to make safe: - /// a term that is already gone cannot be linked, with the same 400 the - /// web layer's pre-flight lookup gives. - #[tokio::test] - async fn a_course_cannot_link_a_term_that_is_gone() { - let (db, _leases) = crate::database::init_test_db().await; - let error = create( - &db, - &a_person(&db, "teacher", "teacher").await, - CourseTitle::try_new("algebra").unwrap(), - CourseDescription::try_new("").unwrap(), - CourseKind::course(), - Some(TermId::from_key("gone")), + /// A şube, for the tests that need an instance attached to it. + async fn a_class( + on: &UserId, + name: &str, + db: &Database, + ) -> crate::domain::class_group::ClassGroup { + crate::db::class_group::create( + db, + on, + crate::domain::class_group::ClassName::try_new(name).unwrap(), + None, + None, None, ) .await - .expect_err("a missing term must not be linkable"); - assert!(error.to_string().contains("term does not exist")); + .unwrap() } - /// The stored `course_count` on one term, absent counting as zero. - async fn count_on(term: &TermId, db: &Database) -> i64 { - sqlx::query("SELECT COALESCE(course_count, 0) FROM term WHERE id = $1") - .bind(term.uuid()) + /// The instances a course is attached through, re-read from storage — + /// never off a return value. + async fn instance_rows(course: &CourseId, db: &Database) -> i64 { + sqlx::query("SELECT count(*) FROM class_course WHERE course = $1") + .bind(course.uuid()) .fetch_one(db) .await .unwrap() @@ -959,352 +880,138 @@ mod tests { .unwrap() as usize } - async fn a_term(name: &str, db: &Database) -> Term { - let at = crate::domain::timestamp::Timestamp::from_millis; - crate::db::term::create(db, TermName::try_new(name).unwrap(), at(100), at(200)) - .await - .unwrap() - } - - /// The invariant, on the create path: a claim and the row it accounts for - /// commit together or not at all. A refused create must therefore leave - /// *neither* — no course row, and no count stranded on a term (which is - /// worse than it sounds: the term's delete guard reads that count, so a - /// stray one makes the term undeletable forever). - #[tokio::test] - async fn a_refused_create_writes_neither_row_nor_count() { - let (db, _leases) = crate::database::init_test_db().await; - let term = a_term("2026", &db).await; - let id = *term.get_id(); - assert!(crate::db::term::delete(&db, term).await.unwrap()); - - let error = create( - &db, - &a_person(&db, "teacher", "teacher").await, - CourseTitle::try_new("algebra").unwrap(), - CourseDescription::try_new("").unwrap(), - CourseKind::course(), - Some(id), - None, - ) - .await - .expect_err("a term that is gone must not be linkable"); - assert!(error.to_string().contains("term does not exist")); - assert_eq!( - rows("course", &db).await, - 0, - "a refused create may write no row" - ); - assert_eq!( - rows("term", &db).await, - 0, - "…and least of all a count on a term it just brought back" - ); - } - - /// The invariant on the PATCH path, both directions: a move carries the new - /// term's claim and the old term's release with the link itself. - #[tokio::test] - async fn a_term_move_moves_the_count() { - let (db, _leases) = crate::database::init_test_db().await; - let from = a_term("2026", &db).await; - let to = a_term("2027", &db).await; - let course = course_on(Some(*from.get_id()), &db).await; - assert_eq!(count_on(from.get_id(), &db).await, 1); - - let moved = update( - &db, - course, - None, - None, - None, - Some(Some(*to.get_id())), - None, - ) - .await - .unwrap(); - assert_eq!(moved.get_term(), Some(to.get_id())); - assert_eq!( - count_on(from.get_id(), &db).await, - 0, - "the old term is free" - ); - assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); - assert!(crate::db::term::delete(&db, from.clone()).await.unwrap()); - assert!(!crate::db::term::delete(&db, to.clone()).await.unwrap()); - } - - /// The double-claim guard. Both movers compute their claim and release from - /// the row as *they* read it, so two PATCHes moving the same course off the - /// same term both release it and both claim their target — two counts for - /// one link, and the loser's target is undeletable forever. The second call - /// here runs on the struct read before the first one landed, which is that - /// race with the interleaving pinned: it must be refused outright, and the - /// counts must read as if it never ran. + /// The bite test for the delete guard that replaced `ENROLL_LOCK`: the + /// guard is the two counters on the locked course row, so the anchor's + /// refusal is a live instance — and it must refuse having written + /// nothing, the instance least of all. A `>= 0` guard passes the guard + /// branch and fails here by deleting the course out from under its class. #[tokio::test] - async fn a_stale_mover_is_refused_and_claims_nothing() { + async fn a_course_an_instance_still_teaches_refuses_to_delete() { let (db, _leases) = crate::database::init_test_db().await; - let from = a_term("2026", &db).await; - let to = a_term("2027", &db).await; - let other = a_term("2028", &db).await; - let course = course_on(Some(*from.get_id()), &db).await; - let stale = course.clone(); - update( - &db, - course, - None, - None, - None, - Some(Some(*to.get_id())), - None, - ) - .await - .unwrap(); + let manager = a_person(&db, "manager", "manager").await; + let course = a_course(&db).await; + let class = a_class(&manager, "9-A", &db).await; + let instance = + crate::service::class_course::attach(&db, class.get_id(), course.get_id(), &manager) + .await + .unwrap(); - let error = update( - &db, - stale.clone(), - None, - None, - None, - Some(Some(*other.get_id())), - None, - ) - .await - .expect_err("a mover that read a link it no longer holds must be refused"); assert!( - matches!(error, AppError::Conflict(_)), - "a lost CAS is a conflict, not a 404 or a 500: {error:?}" - ); - let stored = read(&db, stale.get_id()).await.unwrap().unwrap(); - assert_eq!(stored.get_term(), Some(to.get_id()), "the winner's link"); - assert_eq!( - count_on(from.get_id(), &db).await, - 0, - "released once, not twice" - ); - assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once"); - assert_eq!(count_on(other.get_id(), &db).await, 0, "never claimed"); - - // Same race from the other end: the snapshot says *no* link, so the CAS - // is against an absent column — the shape a bound `NONE` has to match. - let unlinked = course_on(None, &db).await; - let stale = unlinked.clone(); - update( - &db, - unlinked, - None, - None, - None, - Some(Some(*to.get_id())), - None, - ) - .await - .unwrap(); - let error = update( - &db, - stale.clone(), - None, - None, - None, - Some(Some(*other.get_id())), - None, - ) - .await - .expect_err("a mover that read an absent link someone else filled must be refused"); - assert!(matches!(error, AppError::Conflict(_)), "{error:?}"); - assert_eq!(count_on(to.get_id(), &db).await, 2, "one claim per link"); - assert_eq!( - count_on(other.get_id(), &db).await, - 0, - "still never claimed" + !delete(&db, course.clone()).await.unwrap(), + "a course a class still teaches must refuse the delete" ); - // …and the unraced set still lands, so the CAS did not just break moves. - let stored = read(&db, stale.get_id()).await.unwrap().unwrap(); - assert_eq!(stored.get_term(), Some(to.get_id())); - } - - /// The same race with the counters taken out of it. A PATCH that re-states - /// the term its snapshot showed shifts *nothing* — [`term::ref_move`] hands - /// back no claim and no release — so if the guard were armed off the counter - /// move it would not be armed here at all, and the write would land: the - /// winner's link silently dragged back, its claim stranded on a term nothing - /// points at (undeletable forever) and the reverted-to term linked at a - /// count of zero (deletable while linked). The guard is armed by the request - /// *carrying* the column instead, which is why this is refused. - #[tokio::test] - async fn a_stale_re_stater_is_refused_and_reverts_nothing() { - let (db, _leases) = crate::database::init_test_db().await; - let from = a_term("2026", &db).await; - let to = a_term("2027", &db).await; - let course = course_on(Some(*from.get_id()), &db).await; - let stale = course.clone(); - update( - &db, - course, - None, - None, - None, - Some(Some(*to.get_id())), - None, - ) - .await - .unwrap(); - - let error = update( - &db, - stale.clone(), - None, - None, - None, - Some(Some(*from.get_id())), - None, - ) - .await - .expect_err("re-stating a link someone else moved must be refused"); assert!( - matches!(error, AppError::Conflict(_)), - "a lost CAS is a conflict, not a silent 200: {error:?}" - ); - let stored = read(&db, stale.get_id()).await.unwrap().unwrap(); - assert_eq!(stored.get_term(), Some(to.get_id()), "the winner's link"); - assert_eq!( - count_on(from.get_id(), &db).await, - 0, - "the reverted-to term must not end up linked at zero" + read(&db, course.get_id()).await.unwrap().is_some(), + "a refused delete may write nothing" ); - assert_eq!( - count_on(to.get_id(), &db).await, - 1, - "…nor the winner's term counted with nothing pointing at it" + assert!( + crate::db::class_course::read(&db, instance.get_id()) + .await + .unwrap() + .is_some(), + "…the instance least of all" ); - // A *genuine* no-op re-state — nobody moved underneath it — still lands, - // and still moves no counter: the CAS passes trivially. - let fresh = read(&db, stale.get_id()).await.unwrap().unwrap(); - let same = update( - &db, - fresh, - None, - None, - None, - Some(Some(*to.get_id())), - None, - ) - .await - .expect("re-stating the link the row really holds is not a conflict"); - assert_eq!(same.get_term(), Some(to.get_id())); - assert_eq!(count_on(from.get_id(), &db).await, 0, "nothing moved"); - assert_eq!(count_on(to.get_id(), &db).await, 1, "…in either direction"); - } - - /// The rollback proof. The transaction releases the old term *before* it - /// claims the new one, so a move to a term that is gone has already - /// decremented when the claim throws — the old count still being 1 is the - /// abort undoing a write that really happened, not a branch that never ran. - /// The title moves in the same PATCH, and must not stick either. - #[tokio::test] - async fn a_term_move_to_a_dead_term_leaves_everything_untouched() { - let (db, _leases) = crate::database::init_test_db().await; - let from = a_term("2026", &db).await; - let dead = a_term("2027", &db).await; - let dead_id = *dead.get_id(); - assert!(crate::db::term::delete(&db, dead).await.unwrap()); - let course = course_on(Some(*from.get_id()), &db).await; - - let error = update( - &db, - course.clone(), - Some(CourseTitle::try_new("moved").unwrap()), - None, - None, - Some(Some(dead_id)), - None, - ) - .await - .expect_err("a term that is gone must not be linkable"); - assert!(error.to_string().contains("term does not exist")); + // Detaching the last instance frees the row: the catalog is a + // template, and the template whose last class let it go is deletable. + crate::service::class_course::detach(&db, class.get_id(), course.get_id()) + .await + .unwrap(); + assert!(delete(&db, course.clone()).await.unwrap()); + assert!(read(&db, course.get_id()).await.unwrap().is_none()); - let stored = read(&db, course.get_id()).await.unwrap().unwrap(); - assert_eq!(stored.get_term(), Some(from.get_id()), "the link stays put"); - assert_eq!( - stored.get_title().as_str(), - "algebra", - "…and so does the row" - ); + // …and the counter the guard read is back to zero with it, not left + // stranded by the cascade. assert_eq!( - count_on(from.get_id(), &db).await, - 1, - "the release must roll back with the abort" + instance_rows(course.get_id(), &db).await, + 0, + "the instance rows must go with the course" ); assert_eq!( - rows("term", &db).await, - 1, - "the dead term must not be resurrected by the claim" + rows("course", &db).await, + 0, + "no row may outlive the delete" ); } - /// MEASUREMENT — the one race test that actually measures the retry, and - /// the only one of the four that does. The other three (subject, term, - /// exam) are status-code guards; each says so on itself. + /// MEASUREMENT — the one race test for `Course::delete`, and the only + /// test that measures `tx_with_retry` on this path at all. /// - /// [`delete`] is one `BEGIN…COMMIT` whose guard reads - /// `enrollment_count` off the very record a concurrent enroll increments, - /// so the two contend by design, and its cascade is long enough that a + /// [`delete`] is one `BEGIN…COMMIT` whose guard locks the course row the + /// very counter an attach claims, so the two contend by design: the + /// attach is several statements long (the early verdicts, the counter + /// claim, the roster pump) and the delete's cascade is longer, so a /// rival's write lands mid-transaction. Losing that round writes nothing, /// which is what makes re-sending it the recovery. Without - /// [`crate::database::transaction_with_retry`] a lost round comes out as a - /// 500: mutation-tested by cutting that retry loop to one attempt, which + /// [`crate::database::transaction_with_retry`] a lost round comes out as + /// a 500: mutation-tested by cutting that retry loop to one attempt, which /// turns this test red at 1-2 of 20 rounds (3 runs in 5 — the window is - /// real but narrow, so a single green run under the mutation means nothing). + /// real but narrow, so a single green run under the mutation means + /// nothing). /// /// A refusal (`Ok(false)`) or an `Err(NotFound)` is *correct* here and - /// must not fail this test: the only defect is `AppError::Db`. + /// must not fail this test: the only defect is `AppError::Db`. The stored + /// half of the verdict is the orphan check — an instance may never name a + /// course that is gone, whichever side of the race it was on. /// /// The rate is counted over the whole loop instead of asserted per round, /// because a per-round `assert!` aborts at the first hit and would report /// "1 of 1" for a bug the point of this test is to *quantify*. /// - /// Multi-threaded and on a real server for the reasons spelled out on - /// [`crate::domain::fee_plan_assignment`]'s pair of race tests: the - /// current-thread runtime never interleaves the two, and the embedded - /// engine does not conflict-check concurrent writes to one record at all. + /// Each side gets a clear head start on every other round — 2ms is a + /// separation the several-statement rival cannot cross (the same spacing + /// [`crate::db::term`]'s race test settled on). Without it the two sides + /// compete for the same course row and whichever one is marginally faster + /// takes every round, leaving one half of the verdict (`swept > 0`, or + /// `attached > 0`) a coin toss under load. + /// + /// Multi-threaded and on a real server: the current-thread runtime never + /// interleaves the two, and an embedded engine does not conflict-check + /// concurrent writes at all. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - async fn a_delete_racing_an_enroll_never_answers_500() { + async fn a_delete_racing_an_attach_never_answers_500() { let (db, _leases) = crate::database::init_test_db().await; - // The roster rows are foreign keys now: the burst's six racers and - // their enroller are real people, reused every round (each round's - // delete cascade frees the seats back). - let mgr = a_person(&db, "mgr", "manager").await; - let mut students = Vec::new(); + let manager = a_person(&db, "mgr", "manager").await; + // One şube per racer; each round attaches them all into one fresh + // catalog course, so the round's delete has six rival claims to meet. + let mut classes = Vec::new(); for seat in 0..6 { - students.push(a_person(&db, &format!("stu{seat}"), "student").await); + classes.push(a_class(&manager, &format!("9-{seat}"), &db).await); } - let (mut delete_500, mut enroll_500, mut enrolled) = (0, 0, 0); - let (mut last_delete, mut last_enroll) = (String::new(), String::new()); + let (mut delete_500, mut attach_500, mut attached, mut swept) = (0, 0, 0, 0); + let (mut last_delete, mut last_attach) = (String::new(), String::new()); for round in 0..20 { - let course = course_on(None, &db).await; + let course = a_course(&db).await; - // A *burst* of enrolls, and a delete held back by a sweeping beat. - // Released together the delete is one statement while an enroll - // spends two round trips reading before it claims, so it wins every - // round and the guard is never contended at all (measured: 0/20 - // seats placed). Six racers over a 0-3ms sweep put the single - // statement somewhere inside the counter writes instead. + // Every other round the attaches are held back so the delete wins + // outright (the course goes, and nothing may survive it); the rest + // release the attaches first, which is the round where the guard + // has to read their claim and refuse the delete. + let clear = std::time::Duration::from_millis(2); + let (delete_beat, attach_beat) = if round % 2 == 0 { + (std::time::Duration::ZERO, clear) + } else { + (clear, std::time::Duration::ZERO) + }; let drop_it = { let (course, db) = (course.clone(), db.clone()); - let beat = std::time::Duration::from_millis(round % 4); tokio::spawn(async move { - tokio::time::sleep(beat).await; + tokio::time::sleep(delete_beat).await; delete(&db, course).await }) }; - let joins: Vec<_> = (0..6) - .map(|seat| { - let (id, db, mgr) = (course.get_id().clone(), db.clone(), mgr); - let student = students[seat]; + let joins: Vec<_> = classes + .iter() + .map(|class| { + let (class, course, db, mgr) = ( + class.get_id().clone(), + course.get_id().clone(), + db.clone(), + manager, + ); tokio::spawn(async move { - crate::db::enrollment::enroll(&db, &id, &student, &mgr).await + tokio::time::sleep(attach_beat).await; + crate::service::class_course::attach(&db, &class, &course, &mgr).await }) }) .collect(); @@ -1316,36 +1023,41 @@ mod tests { for join in joins { let join = join.await.unwrap(); if matches!(join, Err(AppError::Db(_))) { - enroll_500 += 1; - last_enroll = format!("{join:?}"); + attach_500 += 1; + last_attach = format!("{join:?}"); } } - // Stored state, not the return values: a seat that landed is what - // the guard had to see. - if !crate::db::enrollment::list_for_course(&db, course.get_id(), None, 0) - .await - .unwrap() - .0 - .is_empty() - { - enrolled += 1; + // Stored state, not the return values: an instance that landed is + // what the guard had to see, and one that outlived a deleted + // course is the defect this whole shape exists to catch. + let live = instance_rows(course.get_id(), &db).await; + if live > 0 { + attached += 1; + } + if read(&db, course.get_id()).await.unwrap().is_none() { + swept += 1; + assert_eq!( + live, 0, + "round {round}: an instance outlived the course it names" + ); } } eprintln!( - "Course::delete raced: {delete_500}/20 delete 500s, {enroll_500} enroll 500s, \ - {enrolled}/20 rounds with a seat placed" + "Course::delete raced: {delete_500}/20 delete 500s, {attach_500} attach 500s, \ + {attached} rounds with an instance attached / {swept} rounds the course went" ); assert!( - enrolled > 0, - "no round ever placed an enrollment, so the delete guard was never contended" + attached > 0 && swept > 0, + "the sweep never crossed the window ({attached} attached / {swept} swept), \ + so at least one verdict was never exercised" ); assert_eq!( delete_500, 0, "a raced delete must be refused, not 500: {delete_500}/20 rounds, last {last_delete}" ); assert_eq!( - enroll_500, 0, - "a raced enroll must retry, not 500: {enroll_500}/20 rounds, last {last_enroll}" + attach_500, 0, + "a raced attach must be answered, not 500: {attach_500}/20 rounds, last {last_attach}" ); } } diff --git a/src/db/course_membership.rs b/src/db/course_membership.rs new file mode 100644 index 0000000..69d3082 --- /dev/null +++ b/src/db/course_membership.rs @@ -0,0 +1,222 @@ +//! The `course_membership` table: a student's individual membership in a +//! *school-scoped* course (D9) — a kulüp or an etüt, joined directly rather +//! than through a şube's instance. +//! +//! It is the `enrollment` table's twin minus two things: the instance key (a +//! club has no class to belong to) and the roster pump's `source` tag (a +//! membership is placed by a human and swept by no class). The membership +//! counter on the course moves in the same statement as the row, so the +//! catalog's delete guard reads a number its own writes maintain. +//! +//! Whether a given course *may* be joined this way is +//! [`crate::service::enrollment::join_activity`]'s decision: a class-delivered +//! ders ([`crate::domain::course::CourseKind::is_class_delivered`]) is joined +//! through its instance, never here. + +use crate::database::{Database, tx_with_retry, unique_violation}; +use crate::db::page::PagedList; +use crate::domain::course::CourseId; +use crate::domain::course_membership::CourseMembership; +use crate::domain::role::Role; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; + +/// What [`add`]'s transaction settled on. +enum Verdict { + /// This pair already holds a row — the idempotent hit. + Held, + /// The person being added is no longer a student. + Unfit, + /// The row is written. + Made(CourseMembership), +} + +/// Add (idempotently) `user` to one school-scoped course. The table's primary +/// key *is* the (course, user) pair, so concurrent calls converge on one row +/// instead of racing into a 500: the loser reads the winner's row back and +/// returns it, and the counter moves once. +/// +/// The role check takes the user row `FOR NO KEY UPDATE` — the same lock a +/// demotion cascade takes before it sweeps memberships — so an add and a +/// demotion serialize in both directions. +pub async fn add( + db: &Database, + course: &CourseId, + user: &UserId, + added_by: &UserId, +) -> Result { + if let Some(existing) = read_for_user(db, course, user).await? { + return Ok(existing); + } + let course_id = course.clone(); + let (user_id, added_by_id) = (*user, *added_by); + let created_at = Timestamp::now(); + let verdict = tx_with_retry(db, false, async move |tx| { + // The duplicate gate rides ahead of the role check, so "you are + // already in" still outranks everything. + let held = sqlx::query!( + r#"SELECT 1 AS "one" FROM course_membership WHERE course = $1 AND app_user = $2"#, + course_id.uuid(), + user_id.uuid(), + ) + .fetch_optional(&mut *tx) + .await?; + if held.is_some() { + return Ok(Verdict::Held); + } + let role = sqlx::query!( + r#"SELECT role FROM app_user WHERE id = $1 FOR NO KEY UPDATE"#, + user_id.uuid(), + ) + .fetch_optional(&mut *tx) + .await?; + if role.map(|row| row.role).as_deref() != Some(Role::Student.as_str()) { + return Ok(Verdict::Unfit); + } + // The counter and the row in one statement: zero rows means the + // course is gone — the caller's own read answers that 404 one instant + // earlier. + let row = sqlx::query_as!( + CourseMembership, + r#"WITH seat AS ( + UPDATE course + SET course_membership_count = course_membership_count + 1 + WHERE id = $1 + RETURNING 1) + INSERT INTO course_membership (course, app_user, added_by, created_at) + SELECT $1, $2, $3, $4 WHERE EXISTS (SELECT 1 FROM seat) + RETURNING course AS "course: CourseId", app_user AS "user: UserId", + added_by AS "added_by: UserId", + created_at AS "created_at: Timestamp""#, + course_id.uuid(), + user_id.uuid(), + added_by_id.uuid(), + created_at.as_millis(), + ) + .fetch_optional(&mut *tx) + .await?; + match row { + Some(row) => Ok(Verdict::Made(row)), + None => { + let now_held = sqlx::query!( + r#"SELECT 1 AS "one" FROM course_membership + WHERE course = $1 AND app_user = $2"#, + course_id.uuid(), + user_id.uuid(), + ) + .fetch_optional(&mut *tx) + .await?; + if now_held.is_some() { + return Ok(Verdict::Held); + } + Err(AppError::NotFound) + } + } + }) + .await; + // A rival landing between the gate and the insert is answered off the + // table's own primary key — same verdict, no second count. + let verdict = match verdict { + Err(AppError::Db(err)) + if unique_violation(&err) == Some("course_membership_course_user") => + { + Ok(Verdict::Held) + } + other => other, + }; + match verdict { + Ok(Verdict::Made(row)) => Ok(row), + Ok(Verdict::Held) => match read_for_user(db, course, user).await? { + Some(existing) => Ok(existing), + None => Err(AppError::Internal("failed to add course membership".into())), + }, + Ok(Verdict::Unfit) => Err(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "only students can join a course", + })), + Err(err) => Err(err), + } +} + +/// Some(_) iff `user` holds a membership in `course`. +pub async fn read_for_user( + db: &Database, + course: &CourseId, + user: &UserId, +) -> Result, AppError> { + let row = sqlx::query_as!( + CourseMembership, + r#"SELECT course AS "course: CourseId", app_user AS "user: UserId", + added_by AS "added_by: UserId", created_at AS "created_at: Timestamp" + FROM course_membership WHERE course = $1 AND app_user = $2"#, + course.uuid(), + user.uuid(), + ) + .fetch_optional(db) + .await?; + Ok(row) +} + +/// One course's members, newest first. +pub async fn list_for_course( + db: &Database, + course: &CourseId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new( + "course_membership WHERE course = $1", + "ORDER BY course DESC, app_user DESC", + ) + .bind(course.uuid()) + .run::(limit, offset, db) + .await +} + +/// Every membership `user` holds, newest first — the "my clubs and etüts" +/// read. +pub async fn list_for_user( + db: &Database, + user: &UserId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new( + "course_membership WHERE app_user = $1", + "ORDER BY course DESC, app_user DESC", + ) + .bind(user.uuid()) + .run::(limit, offset, db) + .await +} + +/// Take the row and give the course's membership counter back in one +/// statement. `None` when the pair held no row. +pub async fn remove( + db: &Database, + course: &CourseId, + user: &UserId, +) -> Result, AppError> { + let gone = sqlx::query_as!( + CourseMembership, + r#"WITH gone AS ( + DELETE FROM course_membership + WHERE course = $1 AND app_user = $2 + RETURNING course, app_user, added_by, created_at), + counted AS ( + UPDATE course + SET course_membership_count = GREATEST( + course_membership_count - (SELECT count(*) FROM gone), 0) + WHERE id = $1 + RETURNING 1) + SELECT course AS "course: CourseId", app_user AS "user: UserId", + added_by AS "added_by: UserId", created_at AS "created_at: Timestamp" + FROM gone"#, + course.uuid(), + user.uuid(), + ) + .fetch_optional(db) + .await?; + Ok(gone) +} diff --git a/src/db/course_note.rs b/src/db/course_note.rs index 2241998..63db375 100644 --- a/src/db/course_note.rs +++ b/src/db/course_note.rs @@ -167,16 +167,13 @@ mod tests { #[tokio::test] async fn delete_returns_the_attachment_rows_it_removed() { let (db, _leases) = crate::database::init_test_db().await; - let creator = - crate::db::class_member::tests::fixture_user(&db, "course-note-author").await; + let creator = crate::db::class_member::tests::fixture_user(&db, "course-note-author").await; let course = crate::db::course::create( &db, &creator, CourseTitle::try_new("Math").unwrap(), CourseDescription::try_new("").unwrap(), CourseKind::try_new("course").unwrap(), - None, - None, ) .await .unwrap(); diff --git a/src/db/course_note_file.rs b/src/db/course_note_file.rs index 26c4ff9..cf50fd0 100644 --- a/src/db/course_note_file.rs +++ b/src/db/course_note_file.rs @@ -186,8 +186,6 @@ mod tests { CourseTitle::try_new("c").unwrap(), CourseDescription::try_new("").unwrap(), CourseKind::try_new("course").unwrap(), - None, - None, ) .await .unwrap(); diff --git a/src/db/course_session.rs b/src/db/course_session.rs index 03d1e89..6fa65bc 100644 --- a/src/db/course_session.rs +++ b/src/db/course_session.rs @@ -1,14 +1,15 @@ -//! The `course_session` table: reads, a course's timetable listing, the +//! The `course_session` table: reads, an instance's timetable listing, the //! request-scoped field update, and the delete that sweeps roll-call rows in -//! one transaction. Creation stands on the course foreign key, so a lesson -//! can never outlive its course; the web-facing doors and the -//! teacher-resolution rule live in [`crate::service::course_session`]. +//! one transaction. Creation stands on the instance foreign key, so a lesson +//! can never outlive the class×course instance it is a lesson of; the +//! web-facing doors and the teacher-resolution rule live in +//! [`crate::service::course_session`]. use crate::constant::COURSE_SESSION_TABLE; use crate::database::{Database, foreign_key_violation, tx_with_retry}; use crate::db::field_update::FieldUpdate; use crate::db::page::PagedList; -use crate::domain::course::CourseId; +use crate::domain::class_course::ClassCourseId; use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic}; use crate::domain::timestamp::{Timestamp, range_error}; use crate::domain::user::UserId; @@ -16,7 +17,7 @@ use crate::error::AppError; pub async fn create( db: &Database, - course: &CourseId, + class_course: &ClassCourseId, teacher: &UserId, topic: SessionTopic, starts_at: Timestamp, @@ -24,28 +25,29 @@ pub async fn create( ) -> Result { let session = CourseSession { id: CourseSessionId::generate(), - course: course.clone(), + class_course: class_course.clone(), teacher: *teacher, topic, starts_at, ends_at, }; - // The course foreign key is the existence proof the old bump-and-restore - // "touch" trick faked: a lesson whose course is already gone — or which - // is deleted while this insert is in flight — is refused here, so a - // lesson can never outlive its course and 404 through - // `session_with_course` forever — unreadable, unpatchable, undeletable. - // `23503` is the parent-gone refusal, the same answer the touch - // produced. + // The instance foreign key is the existence proof the old + // bump-and-restore "touch" trick faked: a lesson whose instance is + // already gone — or which is detached while this insert is in flight — is + // refused here, so a lesson can never outlive the instance and 404 + // through the session reads forever — unreadable, unpatchable, + // undeletable. `23503` is the parent-gone refusal, the same answer the + // touch produced. let created = sqlx::query_as!( CourseSession, - r#"INSERT INTO course_session (id, course, teacher, topic, starts_at, ends_at) + r#"INSERT INTO course_session (id, class_course, teacher, topic, starts_at, ends_at) VALUES ($1, $2, $3, $4, $5, $6) - RETURNING id AS "id: CourseSessionId", course AS "course: CourseId", + RETURNING id AS "id: CourseSessionId", + class_course AS "class_course: ClassCourseId", teacher AS "teacher: UserId", topic AS "topic: SessionTopic", starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp""#, session.id.uuid(), - session.course.uuid(), + session.class_course.uuid(), session.teacher.uuid(), session.topic.as_str(), session.starts_at.as_millis(), @@ -63,7 +65,8 @@ pub async fn create( pub async fn read(db: &Database, id: &CourseSessionId) -> Result, AppError> { let session = sqlx::query_as!( CourseSession, - r#"SELECT id AS "id: CourseSessionId", course AS "course: CourseId", + r#"SELECT id AS "id: CourseSessionId", + class_course AS "class_course: ClassCourseId", teacher AS "teacher: UserId", topic AS "topic: SessionTopic", starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp" FROM course_session WHERE id = $1"#, @@ -74,20 +77,20 @@ pub async fn read(db: &Database, id: &CourseSessionId) -> Result, offset: i64, ) -> Result<(Vec, i64), AppError> { PagedList::new( - "course_session WHERE course = $1", + "course_session WHERE class_course = $1", "ORDER BY starts_at DESC, id DESC", ) - .bind(course.uuid()) + .bind(class_course.uuid()) .run::(limit, offset, db) .await } @@ -147,7 +150,8 @@ pub async fn delete(db: &Database, session: CourseSession) -> Result tokio::task::JoinHandle> { tokio::spawn(async move { // The creator is a foreign key now: a real `app_user` row. @@ -188,9 +195,27 @@ mod tests { .execute(&db) .await .unwrap(); + // The lesson hangs off the instance now, so the round has to + // attach one — that claim is exactly what the racing delete + // contends on, and a course already gone refuses right here. + let class = crate::db::class_group::create( + &db, + &creator, + crate::domain::class_group::ClassName::try_new("9-A").unwrap(), + None, + None, + None, + ) + .await? + .get_id() + .clone(); + let instance = crate::service::class_course::attach(&db, &class, &course, &creator) + .await? + .get_id() + .clone(); create( &db, - &course, + &instance, &creator, SessionTopic::try_new("limits").unwrap(), Timestamp::from_millis(1), @@ -200,6 +225,13 @@ mod tests { .map(|_| ()) }) } - crate::db::course::assert_no_child_outlives_a_course_delete("course_session", make).await; + crate::db::course::assert_no_child_outlives_a_course_delete( + "course_session", + "SELECT count(*) FROM course_session s + JOIN class_course cc ON cc.id = s.class_course + WHERE cc.course = $1", + make, + ) + .await; } } diff --git a/src/db/enrollment.rs b/src/db/enrollment.rs index 4119782..62c8f77 100644 --- a/src/db/enrollment.rs +++ b/src/db/enrollment.rs @@ -1,12 +1,18 @@ -//! The `enrollment` table: the roster read and listing, the seat-returning -//! delete, and the enroll claim — one transaction that checks the pair free, -//! the member still a student, and the roster under capacity while it -//! spends the seat. The target-user gates the HTTP handlers pay live in -//! [`crate::service::enrollment`]. +//! The `enrollment` table: the roster read and listing, the counter-returning +//! delete, and the enroll claim — one transaction that checks the pair free +//! and the member still a student. The target-user gates the HTTP handlers pay +//! live in [`crate::service::enrollment`]. +//! +//! Enrollment keys on the *instance* now (D4): a student is enrolled in the +//! Matematik that 5-A teaches, not in a school-wide Matematik row. The seat +//! gate is gone with the catalog's `capacity` (D5) — the roster counter is a +//! count, not a ceiling — so the only refusals left are "already enrolled" +//! (which is an idempotent hit, not an error) and "that user is not a +//! student". use crate::database::{Database, tx_with_retry, unique_violation}; -use crate::db::cap; use crate::db::page::PagedList; +use crate::domain::class_course::ClassCourseId; use crate::domain::class_group::ClassGroupId; use crate::domain::course::CourseId; use crate::domain::enrollment::Enrollment; @@ -15,61 +21,59 @@ use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; -/// What [`enroll`]'s transaction settled on — the three old `THROW` markers -/// (`enroll_held`, `enroll_not_student`, `enroll_full`) as Rust verdicts. +/// What [`enroll`]'s transaction settled on. enum Verdict { /// This pair already holds a row. Held, /// The person being enrolled is no longer a student. Unfit, - /// The roster is full — or the course is gone; the caller reads which. - Full, - /// The seat is spent and the row is written. + /// The row is written. Made(Enrollment), } -/// The primary key the natural composite PK carries — the constraint name -/// that surfaces in SQLSTATE 23505 when a rival lands first. -const PAIR_CONSTRAINT: &str = "enrollment_course_user"; - -/// Enroll (idempotently) `user` into `course`. The table's primary key *is* -/// the (course, user) pair, so concurrent enrolls of the same pair converge -/// on one row instead of racing into a 500: the loser reads the winner's row -/// back and returns it. When the course carries a capacity, a full roster -/// refuses new members (409) — the seat is taken by a single-record -/// conditional write on the course row whose bound is the row's *own* -/// `capacity` column, read inside the same statement that spends the seat. A -/// snapshot integer taken by a read beforehand would be exactly the number a -/// concurrent capacity PATCH invalidates. An already enrolled user is -/// returned as-is even when the roster is full, and never charged a seat. -/// The same claim is the delete guard's other half: it matches nothing once -/// the course row is gone, and while it holds a seat the course cannot be -/// deleted — so no roster row can outlive its course. +/// Enroll (idempotently) `user` into one instance. The table's primary key +/// *is* the (instance, user) pair, so concurrent enrolls of the same pair +/// converge on one row instead of racing into a 500: the loser reads the +/// winner's row back and returns it. An already enrolled user is returned +/// as-is — the counter moves once, and never twice for one row — except that a +/// row a class pumped is *disowned* on the way out (see +/// [`disown_if_pumped`]): the operator's hand enroll is what the row now +/// records. +/// +/// `source` is the class the roster pump wrote this row on behalf of, or +/// `None` for a hand-placed (seçmeli) enrollment. The two halves of that +/// rule: only a row carrying the key is a class's to take back +/// ([`crate::db::class_pump`]), and a hand unenroll wins permanently. +/// +/// The `enrollment_count` counter moves in the same statement as the row (a +/// refused insert takes its own bump back), so the instance's roster size +/// cannot drift from the rows behind it. /// /// Gate order is the old THROW order: an existing pair outranks the role -/// check, which outranks a full roster. The role check takes the user row -/// `FOR NO KEY UPDATE`, the same row a demotion cascade updates before its -/// sweep, so grant and demotion serialize on the row lock in both -/// directions — a row landing after the sweep is impossible, and a demotion -/// landing before this check refuses it. +/// check. The role check takes the user row `FOR NO KEY UPDATE`, the same row +/// a demotion cascade updates before its sweep, so grant and demotion +/// serialize on the row lock in both directions — a row landing after the +/// sweep is impossible, and a demotion landing before this check refuses it. pub async fn enroll( db: &Database, - course: &CourseId, + class_course: &ClassCourseId, user: &UserId, enrolled_by: &UserId, + source: Option<&ClassGroupId>, ) -> Result { - if let Some(existing) = read_for_user(db, course, user).await? { + if let Some(existing) = read_for_user(db, class_course, user).await? { return disown_if_pumped(db, existing).await; } - let course_id = course.clone(); + let instance = class_course.clone(); let (user_id, enrolled_by_id) = (*user, *enrolled_by); + let source_id = source.map(ClassGroupId::uuid); let created_at = Timestamp::now(); let verdict = tx_with_retry(db, false, async move |tx| { // The duplicate gate rides ahead of the role check, so "you are // already in" still outranks everything. let held = sqlx::query!( - r#"SELECT 1 AS "one" FROM enrollment WHERE course = $1 AND app_user = $2"#, - course_id.uuid(), + r#"SELECT 1 AS "one" FROM enrollment WHERE class_course = $1 AND app_user = $2"#, + instance.uuid(), user_id.uuid(), ) .fetch_optional(&mut *tx) @@ -89,27 +93,27 @@ pub async fn enroll( if role.map(|row| row.role).as_deref() != Some(Role::Student.as_str()) { return Ok(Verdict::Unfit); } - // The seat and the row in one statement (the cap recipe): a refused - // insert takes its own seat bump back; zero rows means the roster is - // full or the course is gone — only the caller pays for the read - // that tells those apart. + // The counter and the row in one statement: zero rows means the + // instance is gone — the `404` the caller's own read gives an + // instant earlier. let row = sqlx::query_as!( Enrollment, r#"WITH seat AS ( - UPDATE course + UPDATE class_course SET enrollment_count = enrollment_count + 1 WHERE id = $1 - AND enrollment_count < COALESCE(capacity, $2) RETURNING 1) - INSERT INTO enrollment (course, app_user, enrolled_by, source, created_at) - SELECT $1, $3, $4, NULL, $5 WHERE EXISTS (SELECT 1 FROM seat) - RETURNING course AS "course: CourseId", app_user AS "user: UserId", - enrolled_by AS "enrolled_by: UserId", source AS "source: ClassGroupId""#, - course_id.uuid(), - cap::UNLIMITED, + INSERT INTO enrollment (class_course, app_user, enrolled_by, source, created_at) + SELECT $1, $2, $3, $4, $5 WHERE EXISTS (SELECT 1 FROM seat) + RETURNING class_course AS "class_course: ClassCourseId", + app_user AS "user: UserId", enrolled_by AS "enrolled_by: UserId", + source AS "source: ClassGroupId", + created_at AS "created_at: Timestamp""#, + instance.uuid(), user_id.uuid(), enrolled_by_id.uuid(), - created_at as _, + source_id, + created_at.as_millis(), ) .fetch_optional(&mut *tx) .await?; @@ -117,13 +121,14 @@ pub async fn enroll( Some(row) => Ok(Verdict::Made(row)), None => { // A same-student racer whose held-check predated the winner's - // commit queues on the role lock, wakes to a full roster, and - // its own row is already the winner's: that is the replay, - // not a refusal. Fresh snapshot per statement, so this read - // sees the committed winner. + // commit queues on the role lock and wakes to its own row + // already there: that is the replay, not a refusal. Fresh + // snapshot per statement, so this read sees the committed + // winner. let now_held = sqlx::query!( - r#"SELECT 1 AS "one" FROM enrollment WHERE course = $1 AND app_user = $2"#, - course_id.uuid(), + r#"SELECT 1 AS "one" FROM enrollment + WHERE class_course = $1 AND app_user = $2"#, + instance.uuid(), user_id.uuid(), ) .fetch_optional(&mut *tx) @@ -131,24 +136,27 @@ pub async fn enroll( if now_held.is_some() { return Ok(Verdict::Held); } - Ok(Verdict::Full) + // No row and no winner: the instance itself is gone. + Err(AppError::NotFound) } } }) .await; // The 23505 backstop folds into the Held verdict before the mapping: // someone placed this pair between the gate and the insert, and their - // row is the answer — no seat was spent finding that out. + // row is the answer — no counter move was spent finding that out. let verdict = match verdict { - Err(AppError::Db(err)) if unique_violation(&err) == Some(PAIR_CONSTRAINT) => { + Err(AppError::Db(err)) + if unique_violation(&err) == Some("enrollment_class_course_user") => + { Ok(Verdict::Held) } other => other, }; match verdict { Ok(Verdict::Made(row)) => Ok(row), - Ok(Verdict::Held) => match read_for_user(db, course, user).await? { - Some(existing) => disown_if_pumped(db, existing).await, + Ok(Verdict::Held) => match read_for_user(db, class_course, user).await? { + Some(existing) => Ok(existing), None => Err(AppError::Internal("failed to enroll user".into())), }, // Demoted while this ran: the same refusal the service's own gate @@ -157,26 +165,19 @@ pub async fn enroll( field: "user_id", reason: "only students can be enrolled in a course", })), - // Full, or the course is gone — the conditional write matches - // nothing either way, and only this path pays for the read that - // tells them apart. - Ok(Verdict::Full) => match crate::db::course::read(db, course).await? { - Some(_) => Err(AppError::Conflict("the course is full")), - None => Err(AppError::NotFound), - }, Err(err) => Err(err), } } /// A hand enroll landing on a row a class pumped takes the row *off* the /// class: `source` goes, so no later class sweep can unenroll a student an -/// operator placed on purpose. The mirror of the rule the sweep already -/// holds in the other direction — a manual unenroll wins, permanently — and -/// without it "hand-placed" was a state only a first enroll could reach. +/// operator placed on purpose. The mirror of the rule the sweep already holds +/// in the other direction — a manual unenroll wins, permanently — and without +/// it "hand-placed" was a state only a first enroll could reach. /// /// `NULL`, not absence: the column is a nullable uuid whose NULL *is* the -/// meaning a missing key used to carry (see the struct doc), and it is what -/// a hand enroll writes on the create path too. +/// meaning a missing key used to carry, and it is what a hand enroll writes on +/// the create path too. async fn disown_if_pumped(db: &Database, existing: Enrollment) -> Result { if existing.get_source().is_none() { return Ok(existing); @@ -184,35 +185,37 @@ async fn disown_if_pumped(db: &Database, existing: Enrollment) -> Result Result, AppError> { let row = sqlx::query_as!( Enrollment, - r#"SELECT course AS "course: CourseId", app_user AS "user: UserId", - enrolled_by AS "enrolled_by: UserId", source AS "source: ClassGroupId" - FROM enrollment WHERE course = $1 AND app_user = $2"#, - course.uuid(), + r#"SELECT class_course AS "class_course: ClassCourseId", app_user AS "user: UserId", + enrolled_by AS "enrolled_by: UserId", source AS "source: ClassGroupId", + created_at AS "created_at: Timestamp" + FROM enrollment WHERE class_course = $1 AND app_user = $2"#, + class_course.uuid(), user.uuid(), ) .fetch_optional(db) @@ -220,46 +223,105 @@ pub async fn read_for_user( Ok(row) } -pub async fn list_for_course( +/// Whether `user` is one of `course`'s students right now — the point probe +/// behind an event addressed at a course. +/// +/// The two membership tiers again: an enrollment in any of the course's +/// instances, or an individual club/etüt membership. Both are existence +/// probes on their own indexes; one entity's audience must not fold a whole +/// roster to answer yes. +pub async fn user_is_in_course( db: &Database, course: &CourseId, + user: &UserId, +) -> Result { + let row = sqlx::query!( + r#"SELECT 1 AS "one" FROM ( + SELECT e.app_user FROM enrollment e + WHERE e.app_user = $2 + AND e.class_course IN (SELECT id FROM class_course WHERE course = $1) + UNION ALL + SELECT m.app_user FROM course_membership m + WHERE m.course = $1 AND m.app_user = $2 + ) people LIMIT 1"#, + course.uuid(), + user.uuid(), + ) + .fetch_optional(db) + .await?; + Ok(row.is_some()) +} + +/// Every student the catalog course reaches right now — the union of its +/// instances' rosters and its own individual memberships. +/// +/// One course's "students" is two populations since D9 split the two tiers: a +/// ders reaches them through the instance a şube teaches (enrollment), and a +/// club/etüt through the school-scoped membership. A reader that wants the +/// course's audience — an event addressed at the course, a who-missed report — +/// means both, and deduping in SQL keeps a student who is in two of its +/// instances on the list once. +pub async fn list_users_for_course( + db: &Database, + course: &CourseId, +) -> Result, AppError> { + let rows = sqlx::query!( + r#"SELECT DISTINCT app_user AS "user!: UserId" FROM ( + SELECT e.app_user FROM enrollment e + JOIN class_course cc ON cc.id = e.class_course + WHERE cc.course = $1 + UNION ALL + SELECT m.app_user FROM course_membership m WHERE m.course = $1 + ) people ORDER BY app_user"#, + course.uuid(), + ) + .fetch_all(db) + .await?; + Ok(rows.into_iter().map(|row| row.user).collect()) +} + +/// The instance's roster, newest first — the natural-PK columns sort the way +/// the old composite key did, with its instance prefix constant. +pub async fn list_for_class_course( + db: &Database, + class_course: &ClassCourseId, limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - // The old composite key `{course}_{user}` sorted by user within a - // course — its course prefix was constant — so the natural-PK columns - // sort the same way. PagedList::new( - "enrollment WHERE course = $1", - "ORDER BY course DESC, app_user DESC", + "enrollment WHERE class_course = $1", + "ORDER BY class_course DESC, app_user DESC", ) - .bind(course.uuid()) + .bind(class_course.uuid()) .run::(limit, offset, db) .await } -/// Take the row and give its seat back in one statement, so nothing but a -/// lost transaction can drift the counter. `None` when the pair held no row. +/// Take the row and give the instance's roster counter back in one statement, +/// so nothing but a lost transaction can drift the counter. `None` when the +/// pair held no row. pub async fn remove( db: &Database, - course: &CourseId, + class_course: &ClassCourseId, user: &UserId, ) -> Result, AppError> { let gone = sqlx::query_as!( Enrollment, r#"WITH gone AS ( DELETE FROM enrollment - WHERE course = $1 AND app_user = $2 - RETURNING course, app_user, enrolled_by, source), + WHERE class_course = $1 AND app_user = $2 + RETURNING class_course, app_user, enrolled_by, source, created_at), seated AS ( - UPDATE course + UPDATE class_course SET enrollment_count = GREATEST( enrollment_count - (SELECT count(*) FROM gone), 0) WHERE id = $1 RETURNING 1) - SELECT course AS "course: CourseId", app_user AS "user: UserId", - enrolled_by AS "enrolled_by: UserId", source AS "source: ClassGroupId" FROM gone"#, - course.uuid(), + SELECT class_course AS "class_course: ClassCourseId", + app_user AS "user: UserId", enrolled_by AS "enrolled_by: UserId", + source AS "source: ClassGroupId", created_at AS "created_at: Timestamp" + FROM gone"#, + class_course.uuid(), user.uuid(), ) .fetch_optional(db) @@ -289,82 +351,72 @@ mod tests { user } + /// A real instance — class, course and the link between them — because + /// the enrollment's own key is a foreign key now. + async fn an_instance(db: &Database) -> (ClassCourseId, UserId) { + use crate::db::class_member::tests::{a_class, a_course}; + use crate::domain::class_course::ClassCourseId; - /// A pumped row that vanishes under the disown — a concurrent unenroll, or - /// the sweep a role change runs — must answer the row the caller was - /// handed, not a 500. The `UPDATE` matches nothing and used to fall through - /// to `AppError::Internal`, turning a race the old code answered 200 into a - /// server error on an ordinary `POST /courses/{id}/enrollments`. - #[tokio::test] - async fn a_vanished_row_is_not_an_internal_error() { - let (db, _leases) = crate::database::init_test_db().await; - let class = crate::domain::class_group::ClassGroupId::generate(); - sqlx::query("INSERT INTO class_group (id, name, creator) VALUES ($1, '9a', $2)") + let manager = crate::db::class_member::tests::fixture_user(db, "manager").await; + let class = a_class("9-A", db).await; + let course = a_course("algebra", db).await; + crate::service::class_course::attach(db, &class, &course, &manager) + .await + .unwrap(); + let id: uuid::Uuid = sqlx::query_scalar("SELECT id FROM class_course WHERE class = $1") .bind(class.uuid()) - .bind({ - let mgr = UserId::generate(); - sqlx::query( - "INSERT INTO app_user (id, username, created_at, role) \ - VALUES ($1, 'enroll-fixture', 0, 'manager')", - ) - .bind(mgr.uuid()) - .execute(&db) - .await - .unwrap(); - mgr.uuid() - }) - .execute(&db) + .fetch_one(db) .await .unwrap(); - // The course and student are foreign keys now: real rows, like the - // class. The enrollment itself is never written — the same store state - // a delete in the window leaves. - let course = crate::db::course::a_test_course(&db).await; - let student = a_person(&db, "student", "student").await; - let ghost = Enrollment { - course: course.clone(), - user: student, - enrolled_by: a_person(&db, "mgr", "manager").await, - source: Some(class), - }; - - let answered = disown_if_pumped(&db, ghost).await.unwrap(); - assert_eq!(answered.get_user(), &student); - assert_eq!(answered.get_course(), &course); + ( + ClassCourseId::from_key(&id.to_string()), + a_person(db, "student", "student").await, + ) } - /// And the other half of "absence is the meaning": a hand-placed enrollment - /// must store *no* source key, or a class sweep would take back a row it - /// never wrote. Asserted on the stored row, not the returned one. + /// Enrollment is idempotent and the roster counter moves once: a repeat + /// enroll answers the row already there and leaves the counter as it + /// stands. #[tokio::test] - async fn a_hand_placed_enrollment_stores_no_source_key() { - use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; - + async fn a_repeat_enroll_moves_the_counter_once() { let (db, _leases) = crate::database::init_test_db().await; - let teacher = a_person(&db, "teacher", "teacher").await; - let course = crate::db::course::create( - &db, - &teacher, - CourseTitle::try_new("algebra").unwrap(), - CourseDescription::try_new("").unwrap(), - CourseKind::course(), - None, - None, - ) - .await - .unwrap(); - enroll(&db, course.get_id(), &a_person(&db, "student", "student").await, &teacher) - .await - .unwrap(); + let (instance, student) = an_instance(&db).await; + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; - let source_rows: i64 = - sqlx::query_scalar("SELECT count(*) FROM enrollment WHERE source IS NOT NULL") - .fetch_one(&db) + for _ in 0..2 { + enroll(&db, &instance, &student, &manager, None) .await .unwrap(); + } assert_eq!( - source_rows, 0, + crate::db::class_member::tests::counter("enrollment_count", instance.uuid(), &db).await, + 1, + "one row, one count" + ); + } + + /// A hand-placed enrollment carries no source key, and removing it gives + /// the counter back in the same statement. + #[tokio::test] + async fn a_hand_placed_row_carries_no_source_and_gives_its_count_back() { + let (db, _leases) = crate::database::init_test_db().await; + let (instance, student) = an_instance(&db).await; + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; + + let row = enroll(&db, &instance, &student, &manager, None) + .await + .unwrap(); + assert!( + row.get_source().is_none(), "a hand-placed row may carry no source key" ); + + let removed = remove(&db, &instance, &student).await.unwrap(); + assert!(removed.is_some(), "the row was there to take back"); + assert_eq!( + crate::db::class_member::tests::counter("enrollment_count", instance.uuid(), &db).await, + 0, + "the counter goes back with the row" + ); } } diff --git a/src/db/event.rs b/src/db/event.rs index a30e350..6963fa8 100644 --- a/src/db/event.rs +++ b/src/db/event.rs @@ -26,20 +26,24 @@ pub async fn includes(db: &Database, event: &Event, user: &User) -> Result { Ok(Some(user.get_role()) == event.get_audience_role()) } - crate::domain::event::EventAudienceKind::Course => { - match event.get_audience_course() { - Some(course) => Ok(crate::db::enrollment::read_for_user(db, course, user.get_id()) - .await? - .is_some()), - None => Ok(false), + crate::domain::event::EventAudienceKind::Course => match event.get_audience_course() { + Some(course) => { + Ok(crate::db::enrollment::user_is_in_course(db, course, user.get_id()).await?) } - } - // The (class, user) pair is the membership row's own primary key, so - // the point check is one existence probe — no scan, no index needed. + None => Ok(false), + }, + // The (class, user) pair is the membership row's own key, so the point + // check is one existence probe — and `left_at IS NULL` makes it the + // *live* stint's, the row the partial unique index + // `class_member_live_pair` carries: a student who left the şube is + // history, not audience, and a stale probe would let them be marked + // present at (and counted by) an event their section no longer + // attends. crate::domain::event::EventAudienceKind::Class => match event.get_audience_class() { Some(class) => { let row = sqlx::query!( - "SELECT EXISTS(SELECT 1 FROM class_member WHERE class = $1 AND app_user = $2) + "SELECT EXISTS(SELECT 1 FROM class_member + WHERE class = $1 AND app_user = $2 AND left_at IS NULL) AS \"present!\"", class.uuid(), user.get_id().uuid() @@ -50,11 +54,11 @@ pub async fn includes(db: &Database, event: &Event, user: &User) -> Result Ok(false), }, - crate::domain::event::EventAudienceKind::Registration => { - Ok(crate::db::registration::read_for_user(db, event.get_id(), user.get_id()) + crate::domain::event::EventAudienceKind::Registration => Ok( + crate::db::registration::read_for_user(db, event.get_id(), user.get_id()) .await? - .is_some()) - } + .is_some(), + ), } } @@ -63,31 +67,26 @@ pub async fn includes(db: &Database, event: &Event, user: &User) -> Result Result, AppError> { match event.get_audience_kind() { - crate::domain::event::EventAudienceKind::School => Ok(crate::db::user::list_all(db, None, 0) - .await? - .0 - .iter() - .map(|user| *user.get_id()) - .collect()), - crate::domain::event::EventAudienceKind::Role => { - match event.get_audience_role() { - Some(role) => Ok(crate::db::user::list_by_role(db, role) - .await? - .iter() - .map(|user| *user.get_id()) - .collect()), - None => Ok(Vec::new()), - } - } - crate::domain::event::EventAudienceKind::Course => match event.get_audience_course() { - Some(course) => Ok(crate::db::enrollment::list_for_course(db, course, None, 0) + crate::domain::event::EventAudienceKind::School => { + Ok(crate::db::user::list_all(db, None, 0) .await? .0 .iter() - .map(|enrollment| *enrollment.get_user()) + .map(|user| *user.get_id()) + .collect()) + } + crate::domain::event::EventAudienceKind::Role => match event.get_audience_role() { + Some(role) => Ok(crate::db::user::list_by_role(db, role) + .await? + .iter() + .map(|user| *user.get_id()) .collect()), None => Ok(Vec::new()), }, + crate::domain::event::EventAudienceKind::Course => match event.get_audience_course() { + Some(course) => Ok(crate::db::enrollment::list_users_for_course(db, course).await?), + None => Ok(Vec::new()), + }, crate::domain::event::EventAudienceKind::Class => match event.get_audience_class() { Some(class) => Ok(crate::db::class_member::list_for_class(db, class, None, 0) .await? @@ -225,11 +224,15 @@ pub async fn update( ) .set( "audience_course", - audience.as_ref().map(|a| Param::OptUuid(a.course.as_ref().map(|c| c.uuid()))), + audience + .as_ref() + .map(|a| Param::OptUuid(a.course.as_ref().map(|c| c.uuid()))), ) .set( "audience_class", - audience.as_ref().map(|a| Param::OptUuid(a.class.as_ref().map(|c| c.uuid()))), + audience + .as_ref() + .map(|a| Param::OptUuid(a.class.as_ref().map(|c| c.uuid()))), ) .set( "audience_capacity", diff --git a/src/db/exam.rs b/src/db/exam.rs index 61dab3f..86a96c2 100644 --- a/src/db/exam.rs +++ b/src/db/exam.rs @@ -2,12 +2,16 @@ //! course that is gone, the compare-and-set every PATCH writes through, and //! the cascading delete. The PATCH re-derive lives in [`crate::service::exam`]. +use sqlx::PgConnection; + use crate::database::{Database, foreign_key_violation, tx_with_retry}; +use crate::domain::class_course::ClassCourseId; use crate::domain::course::CourseId; use crate::domain::exam::{ Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode, ExamSchedule, ExamTitle, redraft_error, }; +use crate::domain::term::TermId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; @@ -19,7 +23,8 @@ use crate::error::AppError; pub async fn create( db: &Database, creator: &UserId, - course: &CourseId, + class_course: &ClassCourseId, + term: &TermId, title: ExamTitle, description: ExamDescription, kind: ExamKind, @@ -29,55 +34,163 @@ pub async fn create( allow_review: bool, draft: bool, ) -> Result { - // A missing parent is refused by the real foreign keys: a course or a - // creator that is gone is `SQLSTATE 23503`, and this call site's - // parent-gone answer is the same `NotFound` the old existence-proof - // touch (`cap::touch_and_create`, deleted) answered with. The bump that - // touch made and unmade is gone with it — an exam was never counted - // anywhere. - let created = sqlx::query_as!( + // A missing parent is refused by the real foreign keys: an instance, a + // dönem or a creator that is gone is `SQLSTATE 23503`, and this call + // site's parent-gone answer is the same `NotFound` the old + // existence-proof touch answered with. + // + // The dönem is *claimed* in the same statement as the row (`exam_count` + // +1, a conditional write on the term row), the shape the old course + // create used against `term.course_count`: the count is what the term's + // own delete guard reads, and claim-and-insert in one CTE means no crash + // can leave one half without the other. + // + // The owner's `exam_audience` row is written in the same transaction, + // *always*: the audience is what every listing reads through, so an exam + // with no audience row would be invisible to its own instance. An ortak + // sınav is extra audience rows on this one exam (D2), never a second + // shape. + let id = ExamId::generate(); + let creator = *creator; + let class_course = class_course.clone(); + // `TermId` is `Copy`: one copy here, and the per-attempt closure below + // re-yields values rather than clones. + let term = *term; + // The binds are hoisted to owned values so the closure below only has to + // clone them per attempt: the write itself is a named future, for the + // reason [`insert_in`] gives. + let title_text = title.as_str().to_string(); + let description_text = description.as_str().to_string(); + let kind_text = kind.as_str().to_string(); + let mode_text = schedule.mode.as_ref().map(|mode| mode.as_str().to_string()); + let starts_at = schedule.starts_at.map(|at| at.as_millis()); + let ends_at = schedule.ends_at.map(|at| at.as_millis()); + let duration_ms = schedule.duration_ms.map(|duration| duration.as_millis()); + let max_attempts = max_attempts.as_i64(); + let created = tx_with_retry(db, false, async move |tx| { + insert_in( + tx, + id.clone(), + creator, + class_course.clone(), + term, + title_text.clone(), + description_text.clone(), + kind_text.clone(), + mode_text.clone(), + starts_at, + ends_at, + duration_ms, + max_attempts, + allow_rejoin, + allow_review, + draft, + ) + .await + }) + .await?; + Ok(created) +} + +/// The claim, the row and its audience row, on one connection — [`create`]'s +/// body as a *named* future. +/// +/// Named, and taking owned values, because the anonymous `async move |tx|` +/// closure does not work here: with this many binds, rustc cannot prove the +/// closure's future is `Send` under [`tx_with_retry`]'s +/// `AsyncFnMut(&mut PgConnection)` higher-ranked bound, so every axum handler +/// that awaits [`create`] fails with "implementation of `Send` is not general +/// enough" pointing at its `routes!` entry. A named `async fn` has a concrete +/// future type rustc can check, exactly as +/// [`crate::db::answer_image::upsert_in`] does for the same reason. +/// +/// Everything it decides is the closure's own: a claim that matched no dönem +/// row is [`crate::domain::term::gone_error`], any other foreign key is the +/// parent-gone `NotFound`, and the audience row is written in the same +/// transaction as the row it names. +#[expect( + clippy::too_many_arguments, + reason = "the create's own field list, spelled once for the named future" +)] +pub(crate) async fn insert_in( + tx: &mut PgConnection, + id: ExamId, + creator: UserId, + class_course: ClassCourseId, + term: TermId, + title: String, + description: String, + kind: String, + mode: Option, + starts_at: Option, + ends_at: Option, + duration_ms: Option, + max_attempts: i64, + allow_rejoin: bool, + allow_review: bool, + draft: bool, +) -> Result { + let written = sqlx::query_as!( Exam, - r#"INSERT INTO exam (id, creator, course, title, description, kind, mode, - starts_at, ends_at, duration_ms, max_attempts, - allow_rejoin, allow_review, draft) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14) - RETURNING id AS "id: ExamId", creator AS "creator: UserId", - course AS "course: CourseId", title AS "title: ExamTitle", - description AS "description: ExamDescription", - kind AS "kind: ExamKind", mode AS "mode: ExamMode", - starts_at AS "starts_at: Timestamp", - ends_at AS "ends_at: Timestamp", - duration_ms AS "duration_ms: ExamDuration", - max_attempts AS "max_attempts: ExamAttemptLimit", - allow_rejoin, allow_review, draft"#, - ExamId::generate().uuid(), + r#"WITH room AS ( + UPDATE term SET exam_count = exam_count + 1 + WHERE id = $3 + RETURNING 1) + INSERT INTO exam (id, creator, class_course, term, title, description, kind, mode, + starts_at, ends_at, duration_ms, max_attempts, + allow_rejoin, allow_review, draft) + SELECT $1, $2, $4, $3, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15 + WHERE EXISTS (SELECT 1 FROM room) + RETURNING id AS "id: ExamId", creator AS "creator: UserId", + class_course AS "class_course: ClassCourseId", + term AS "term: TermId", title AS "title: ExamTitle", + description AS "description: ExamDescription", + kind AS "kind: ExamKind", mode AS "mode: ExamMode", + starts_at AS "starts_at: Timestamp", + ends_at AS "ends_at: Timestamp", + duration_ms AS "duration_ms: ExamDuration", + max_attempts AS "max_attempts: ExamAttemptLimit", + allow_rejoin, allow_review, draft"#, + id.uuid(), creator.uuid(), - course.uuid(), + term.uuid(), + class_course.uuid(), title.as_str(), description.as_str(), kind.as_str(), - schedule.mode.as_ref().map(ExamMode::as_str), - schedule.starts_at.map(|at| at.as_millis()), - schedule.ends_at.map(|at| at.as_millis()), - schedule.duration_ms.map(|duration| duration.as_millis()), - max_attempts.as_i64(), + mode.as_deref(), + starts_at, + ends_at, + duration_ms, + max_attempts, allow_rejoin, allow_review, draft, ) - .fetch_one(db) + .fetch_optional(&mut *tx) .await; - match created { - Err(err) if foreign_key_violation(&err) => Err(AppError::NotFound), - Err(err) => Err(err.into()), - Ok(exam) => Ok(exam), - } + let exam = match written { + Ok(Some(exam)) => exam, + // The conditional claim matched no dönem row: the term is gone. + Ok(None) => return Err(crate::domain::term::gone_error()), + Err(err) if foreign_key_violation(&err) => return Err(AppError::NotFound), + Err(err) => return Err(err.into()), + }; + sqlx::query!( + r#"INSERT INTO exam_audience (exam, class_course) VALUES ($1, $2)"#, + exam.id.uuid(), + exam.class_course.uuid(), + ) + .execute(&mut *tx) + .await?; + Ok(exam) } pub async fn read(db: &Database, id: &ExamId) -> Result, AppError> { Ok(sqlx::query_as!( Exam, - r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", course AS "course: CourseId", + r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", + class_course AS "class_course: ClassCourseId", term AS "term: TermId", title AS "title: ExamTitle", description AS "description: ExamDescription", kind AS "kind: ExamKind", mode AS "mode: ExamMode", starts_at AS "starts_at: Timestamp", @@ -97,7 +210,8 @@ pub async fn read(db: &Database, id: &ExamId) -> Result, AppError> pub async fn list_all(db: &Database) -> Result, AppError> { Ok(sqlx::query_as!( Exam, - r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", course AS "course: CourseId", + r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", + class_course AS "class_course: ClassCourseId", term AS "term: TermId", title AS "title: ExamTitle", description AS "description: ExamDescription", kind AS "kind: ExamKind", mode AS "mode: ExamMode", starts_at AS "starts_at: Timestamp", @@ -111,26 +225,84 @@ pub async fn list_all(db: &Database) -> Result, AppError> { .await?) } -pub async fn list_for_course(db: &Database, course: &CourseId) -> Result, AppError> { +/// The exams of one instance, newest first. +/// +/// It reads through `exam_audience` rather than off `exam.class_course`: the +/// owner's row is always there (the create writes it), so the two agree for +/// every exam this instance owns, and the join is what lets an ortak sınav be +/// one exam addressed to several instances (D2) without a second read path. +pub async fn list_for_class_course( + db: &Database, + class_course: &ClassCourseId, +) -> Result, AppError> { Ok(sqlx::query_as!( Exam, - r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", course AS "course: CourseId", - title AS "title: ExamTitle", description AS "description: ExamDescription", - kind AS "kind: ExamKind", mode AS "mode: ExamMode", - starts_at AS "starts_at: Timestamp", - ends_at AS "ends_at: Timestamp", - duration_ms AS "duration_ms: ExamDuration", - max_attempts AS "max_attempts: ExamAttemptLimit", - allow_rejoin, allow_review, draft - FROM exam WHERE course = $1 ORDER BY id DESC"#, - course.uuid(), + r#"SELECT DISTINCT ON (e.id) + e.id AS "id: ExamId", e.creator AS "creator: UserId", + e.class_course AS "class_course: ClassCourseId", + e.term AS "term: TermId", e.title AS "title: ExamTitle", + e.description AS "description: ExamDescription", + e.kind AS "kind: ExamKind", e.mode AS "mode: ExamMode", + e.starts_at AS "starts_at: Timestamp", + e.ends_at AS "ends_at: Timestamp", + e.duration_ms AS "duration_ms: ExamDuration", + e.max_attempts AS "max_attempts: ExamAttemptLimit", + e.allow_rejoin, e.allow_review, e.draft + FROM exam e + JOIN exam_audience a ON a.exam = e.id + WHERE a.class_course = $1 + ORDER BY e.id DESC"#, + class_course.uuid(), ) .fetch_all(db) .await?) } -/// Every exam of every course in `courses` (one query) — the catalog as one -/// user sees it. +/// Every exam of every instance in `instances` (one query) — the karne and +/// marks reports' cross-instance read, and the list behind a caller's visible +/// courses. +/// +/// `DISTINCT ON (e.id)` because an exam may be addressed to several instances +/// at once (an ortak sınav): the filters ask "is this exam visible here", not +/// "how many audiences does it have", so each exam is returned once with its +/// own owner instance. +pub async fn list_for_class_course_courses( + db: &Database, + instances: &[ClassCourseId], +) -> Result, AppError> { + if instances.is_empty() { + return Ok(Vec::new()); + } + let instances = instances + .iter() + .map(ClassCourseId::uuid) + .collect::>(); + Ok(sqlx::query_as!( + Exam, + r#"SELECT DISTINCT ON (e.id) + e.id AS "id: ExamId", e.creator AS "creator: UserId", + e.class_course AS "class_course: ClassCourseId", + e.term AS "term: TermId", e.title AS "title: ExamTitle", + e.description AS "description: ExamDescription", + e.kind AS "kind: ExamKind", e.mode AS "mode: ExamMode", + e.starts_at AS "starts_at: Timestamp", + e.ends_at AS "ends_at: Timestamp", + e.duration_ms AS "duration_ms: ExamDuration", + e.max_attempts AS "max_attempts: ExamAttemptLimit", + e.allow_rejoin, e.allow_review, e.draft + FROM exam e + JOIN exam_audience a ON a.exam = e.id + WHERE a.class_course = ANY($1) + ORDER BY e.id DESC"#, + &instances, + ) + .fetch_all(db) + .await?) +} + +/// Every exam of every *catalog* course in `courses` (one query) — the +/// catalog as one user sees it, across the instances those courses are taught +/// in. pub async fn list_for_courses(db: &Database, courses: &[CourseId]) -> Result, AppError> { if courses.is_empty() { return Ok(Vec::new()); @@ -138,15 +310,22 @@ pub async fn list_for_courses(db: &Database, courses: &[CourseId]) -> Result>(); Ok(sqlx::query_as!( Exam, - r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", course AS "course: CourseId", - title AS "title: ExamTitle", description AS "description: ExamDescription", - kind AS "kind: ExamKind", mode AS "mode: ExamMode", - starts_at AS "starts_at: Timestamp", - ends_at AS "ends_at: Timestamp", - duration_ms AS "duration_ms: ExamDuration", - max_attempts AS "max_attempts: ExamAttemptLimit", - allow_rejoin, allow_review, draft - FROM exam WHERE course = ANY($1) ORDER BY id DESC"#, + r#"SELECT DISTINCT ON (e.id) + e.id AS "id: ExamId", e.creator AS "creator: UserId", + e.class_course AS "class_course: ClassCourseId", + e.term AS "term: TermId", e.title AS "title: ExamTitle", + e.description AS "description: ExamDescription", + e.kind AS "kind: ExamKind", e.mode AS "mode: ExamMode", + e.starts_at AS "starts_at: Timestamp", + e.ends_at AS "ends_at: Timestamp", + e.duration_ms AS "duration_ms: ExamDuration", + e.max_attempts AS "max_attempts: ExamAttemptLimit", + e.allow_rejoin, e.allow_review, e.draft + FROM exam e + JOIN exam_audience a ON a.exam = e.id + JOIN class_course cc ON cc.id = a.class_course + WHERE cc.course = ANY($1) + ORDER BY e.id DESC"#, &courses, ) .fetch_all(db) @@ -272,7 +451,8 @@ pub async fn update_if_unchanged( AND draft = $23 AND result_count = $24 RETURNING id AS "id: ExamId", creator AS "creator: UserId", - course AS "course: CourseId", title AS "title: ExamTitle", + class_course AS "class_course: ClassCourseId", + term AS "term: TermId", title AS "title: ExamTitle", description AS "description: ExamDescription", kind AS "kind: ExamKind", mode AS "mode: ExamMode", starts_at AS "starts_at: Timestamp", @@ -355,16 +535,19 @@ pub async fn delete(db: &Database, target: Exam) -> Result { db, true, async move |conn| { - // The row lock every other exam-child writer contends on. + // The row lock every other exam-child writer contends on. The + // dönem rides out of the same read: the term's `exam_count` is + // given back in this transaction, and the row that names it is + // the one being deleted. let locked = sqlx::query!( - r#"SELECT id AS "id: ExamId" FROM exam WHERE id = $1 FOR UPDATE"#, + r#"SELECT term AS "term: TermId" FROM exam WHERE id = $1 FOR UPDATE"#, target.id.uuid(), ) .fetch_optional(&mut *conn) .await?; - if locked.is_none() { + let Some(locked) = locked else { return Err(AppError::NotFound); - } + }; // The blob names, collected *before* the rows go — inside the // lock, so an image row written after this snapshot cannot // strand its bytes on disk even though the row itself would be @@ -441,11 +624,21 @@ pub async fn delete(db: &Database, target: Exam) -> Result { ) .execute(&mut *conn) .await?; + // The sitting instances go with the exam: every read goes through + // the audience join, so a row pointing at a deleted exam would be + // both invisible and undeletable. + sqlx::query!( + r#"DELETE FROM exam_audience WHERE exam = $1"#, + target.id.uuid(), + ) + .execute(&mut *conn) + .await?; let deleted = sqlx::query_as!( Exam, r#"DELETE FROM exam WHERE id = $1 RETURNING id AS "id: ExamId", creator AS "creator: UserId", - course AS "course: CourseId", title AS "title: ExamTitle", + class_course AS "class_course: ClassCourseId", + term AS "term: TermId", title AS "title: ExamTitle", description AS "description: ExamDescription", kind AS "kind: ExamKind", mode AS "mode: ExamMode", starts_at AS "starts_at: Timestamp", @@ -460,6 +653,15 @@ pub async fn delete(db: &Database, target: Exam) -> Result { let Some(exam) = deleted else { return Err(AppError::NotFound); }; + // The dönem gets its exam reference back inside the same + // transaction — the other half of the claim `create` makes. + sqlx::query!( + r#"UPDATE term SET exam_count = GREATEST(exam_count - 1, 0) + WHERE id = $1"#, + locked.term.uuid(), + ) + .execute(&mut *conn) + .await?; Ok(Deleted { exam, question_image_files: image_files, @@ -494,13 +696,20 @@ pub(crate) async fn published_exam(db: &Database) -> Exam { .execute(db) .await .unwrap(); + // The exam hangs off the *instance* and carries the dönem it is graded in + // (both foreign keys): both are real rows, minted per call — + // [`crate::db::course::a_test_instance`] mints the class, the course and + // the link, [`crate::db::term::a_test_term`] the year under the term. + let (instance, _course) = crate::db::course::a_test_instance(db).await; + let term = crate::db::term::a_test_term(db).await; create( db, &creator, - &crate::db::course::a_test_course(db).await, + &instance, + &term, ExamTitle::try_new("midterm").unwrap(), ExamDescription::try_new("").unwrap(), - ExamKind::try_new("midterm", &allowed).unwrap(), + ExamKind::try_new("yazili", &allowed).unwrap(), ExamSchedule::try_new(None, None, None, None).unwrap(), ExamAttemptLimit::try_new(1).unwrap(), true, @@ -524,7 +733,7 @@ mod tests { /// An exam must not outlive the course it belongs to. It is the worst of /// the three children `Course::delete` used to leave behind: every exam - /// route funnels through `course_of`, which answers + /// route funnels through `class_course_of`, which answers /// `Internal("exam references a missing course")`, so an orphan **500s /// forever** on `GET`/`PATCH`/`DELETE /exams/{id}` — undeletable — while /// [`crate::db::exam::list_all`] still hands it to every manager+ on `GET /exams`. @@ -552,13 +761,34 @@ mod tests { .execute(&db) .await .unwrap(); + // The exam's parents: a dönem, and an instance of *this* + // course. Attaching it is the claim the racing delete + // contends on, so the round where the course is gone refuses + // here — which is the refusal this test wants to see answered. + let term = crate::db::term::a_test_term(&db).await; + let class = crate::db::class_group::create( + &db, + &creator, + crate::domain::class_group::ClassName::try_new("9-A").unwrap(), + None, + None, + None, + ) + .await? + .get_id() + .clone(); + let instance = crate::service::class_course::attach(&db, &class, &course, &creator) + .await? + .get_id() + .clone(); create( &db, &creator, - &course, + &instance, + &term, ExamTitle::try_new("quiz").unwrap(), ExamDescription::try_new("").unwrap(), - ExamKind::try_new("quiz", &kinds).unwrap(), + ExamKind::try_new("yazili", &kinds).unwrap(), ExamSchedule::try_new(None, None, None, None).unwrap(), ExamAttemptLimit::try_new(1).unwrap(), true, @@ -569,7 +799,13 @@ mod tests { .map(|_| ()) }) } - crate::db::course::assert_no_child_outlives_a_course_delete("exam", make).await; + crate::db::course::assert_no_child_outlives_a_course_delete( + "exam", + "SELECT count(*) FROM exam e JOIN class_course cc ON cc.id = e.class_course + WHERE cc.course = $1", + make, + ) + .await; } /// A real `app_user` row: students and graders are foreign keys now. The @@ -705,10 +941,18 @@ mod tests { let allowed: Vec = crate::domain::settings::Settings::defaults() .get_exam_kinds() .to_vec(); - for kind in ["homework", "quiz", "midterm", "final", "project", "oral"] { + // The K12 defaults, pinned by name: the acceptance set of a fresh + // school is exactly these three, and the pre-remodel vocabulary + // ("quiz", "midterm", …) is not in it. + for kind in ["yazili", "sozlu", "uygulama"] { assert_eq!(ExamKind::try_new(kind, &allowed).unwrap().as_str(), kind); } - assert!(ExamKind::try_new("essay", &allowed).is_err()); + for stale in ["quiz", "midterm", "exam"] { + assert!( + ExamKind::try_new(stale, &allowed).is_err(), + "{stale} is not in the school's list" + ); + } assert!(ExamKind::try_new("", &allowed).is_err()); // A school-defined list swaps the acceptance set wholesale. let custom = vec![ExamKindDef::try_new("lab", 2).unwrap()]; @@ -1196,8 +1440,13 @@ mod tests { }) }; let child = { - let (db, exam_id, on, student, gate) = - (db.clone(), id.clone(), question.get_id().clone(), student, gate); + let (db, exam_id, on, student, gate) = ( + db.clone(), + id.clone(), + question.get_id().clone(), + student, + gate, + ); tokio::spawn(async move { gate.wait().await; let image = AnswerImage::new( @@ -1264,7 +1513,8 @@ mod tests { }) }; let child = { - let (db, exam_id, on, gate) = (db.clone(), id.clone(), question.get_id().clone(), gate); + let (db, exam_id, on, gate) = + (db.clone(), id.clone(), question.get_id().clone(), gate); tokio::spawn(async move { gate.wait().await; let image = QuestionImage::new( diff --git a/src/db/exam_answer.rs b/src/db/exam_answer.rs index 8f1e45d..7f5290e 100644 --- a/src/db/exam_answer.rs +++ b/src/db/exam_answer.rs @@ -312,13 +312,18 @@ mod tests { let kinds = crate::domain::settings::Settings::defaults() .get_exam_kinds() .to_vec(); + // The instance and the dönem are foreign keys now: real rows the + // fixture mints. + let (instance, _course) = crate::db::course::a_test_instance(&db).await; + let term = crate::db::term::a_test_term(&db).await; let exam = crate::db::exam::create( &db, &student(), - &crate::db::course::a_test_course(&db).await, + &instance, + &term, ExamTitle::try_new("quiz").unwrap(), ExamDescription::try_new("").unwrap(), - ExamKind::try_new("quiz", &kinds).unwrap(), + ExamKind::try_new("yazili", &kinds).unwrap(), ExamSchedule::try_new(None, None, None, None).unwrap(), ExamAttemptLimit::try_new(1).unwrap(), true, @@ -396,7 +401,11 @@ mod tests { assert_eq!(stored(&db).await, Some(7), "the touch moved a real count"); // The gate that makes the touch worth having: no exam, no answer. - let orphan = choice_question(&ExamId::from_key("019732e3-7b00-7000-8000-00000000e0a0"), 10, 0); + let orphan = choice_question( + &ExamId::from_key("019732e3-7b00-7000-8000-00000000e0a0"), + 10, + 0, + ); let pick = choice_id(&orphan, 0).as_str().to_string(); let refused = save(&db, &orphan, &student(), 1, Some(pick), None).await; assert!( diff --git a/src/db/exam_attempt.rs b/src/db/exam_attempt.rs index 564cc6f..56910e8 100644 --- a/src/db/exam_attempt.rs +++ b/src/db/exam_attempt.rs @@ -400,15 +400,19 @@ mod tests { .execute(db) .await .unwrap(); - let course = crate::db::course::a_test_course(db).await; + // The instance and the dönem are foreign keys now: real rows the + // fixture mints. + let (instance, _course) = crate::db::course::a_test_instance(db).await; + let term = crate::db::term::a_test_term(db).await; let kinds = Settings::defaults().get_exam_kinds().to_vec(); let exam = crate::db::exam::create( db, &creator, - &course, + &instance, + &term, ExamTitle::try_new("practice").unwrap(), ExamDescription::try_new("").unwrap(), - ExamKind::try_new("quiz", &kinds).unwrap(), + ExamKind::try_new("yazili", &kinds).unwrap(), ExamSchedule::try_new(Some(ExamMode::try_new("open").unwrap()), None, None, None) .unwrap(), ExamAttemptLimit::try_new(max_attempts).unwrap(), diff --git a/src/db/exam_question.rs b/src/db/exam_question.rs index 1df9c55..a2b34d4 100644 --- a/src/db/exam_question.rs +++ b/src/db/exam_question.rs @@ -458,13 +458,18 @@ mod tests { .await .unwrap(); let kinds = Settings::defaults().get_exam_kinds().to_vec(); + // The instance and the dönem are foreign keys now: real rows the + // fixture mints, per call. + let (instance, _course) = crate::db::course::a_test_instance(db).await; + let term = crate::db::term::a_test_term(db).await; crate::db::exam::create( db, &creator, - &crate::db::course::a_test_course(db).await, + &instance, + &term, ExamTitle::try_new("practice").unwrap(), ExamDescription::try_new("").unwrap(), - ExamKind::try_new("quiz", &kinds).unwrap(), + ExamKind::try_new("yazili", &kinds).unwrap(), ExamSchedule::try_new(Some(ExamMode::try_new("open").unwrap()), None, None, None) .unwrap(), ExamAttemptLimit::try_new(1).unwrap(), @@ -514,13 +519,11 @@ mod tests { /// The stored `exam_question_count` on one subject, absent = zero. async fn count_on(subject: &SubjectId, db: &Database) -> i64 { - sqlx::query_scalar::<_, i64>( - "SELECT exam_question_count FROM subject WHERE id = $1", - ) - .bind(subject.uuid()) - .fetch_one(db) - .await - .unwrap() + sqlx::query_scalar::<_, i64>("SELECT exam_question_count FROM subject WHERE id = $1") + .bind(subject.uuid()) + .fetch_one(db) + .await + .unwrap() } async fn rows(sql: &str, db: &Database) -> usize { diff --git a/src/db/exam_result.rs b/src/db/exam_result.rs index 7658774..47b13da 100644 --- a/src/db/exam_result.rs +++ b/src/db/exam_result.rs @@ -6,11 +6,12 @@ use crate::constant::HIGH_MARK_MIN; use crate::database::{Database, tx_with_retry}; -use crate::domain::course::CourseId; +use crate::domain::class_course::ClassCourseId; use crate::domain::exam::ExamId; use crate::domain::exam_result::{ ExamResult, Mark, draft_error, latest_per_pair, retired_kind_error, }; +use crate::domain::term::TermId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; @@ -202,11 +203,11 @@ pub async fn grade( .await } -/// The user's graded results restricted to one course's exams — the raw -/// rows behind the per-course block of the marks report. +/// The user's graded results restricted to one instance's exams — the raw +/// rows behind the per-instance block of the marks report. pub async fn list_for_user_in_course( db: &Database, - course: &CourseId, + class_course: &ClassCourseId, user: &UserId, ) -> Result, AppError> { let rows = sqlx::query_as!( @@ -214,10 +215,33 @@ pub async fn list_for_user_in_course( r#"SELECT r.exam AS "exam: ExamId", r.app_user AS "user: UserId", r.seq, r.mark AS "mark: Mark", r.graded_by AS "graded_by: UserId" FROM exam_result r JOIN exam e ON e.id = r.exam - WHERE r.app_user = $1 AND e.course = $2 + WHERE r.app_user = $1 AND e.class_course = $2 ORDER BY r.exam DESC, r.seq DESC"#, user.uuid(), - course.uuid(), + class_course.uuid(), + ) + .fetch_all(db) + .await?; + Ok(latest_per_pair(rows)) +} + +/// The user's graded results inside one dönem — every instance's exams whose +/// `term` is `term`, which is exactly the karne's input slice (D8: a karne is +/// per dönem, and an exam belongs to the dönem it was sat in). +pub async fn list_for_user_in_term( + db: &Database, + user: &UserId, + term: &TermId, +) -> Result, AppError> { + let rows = sqlx::query_as!( + ExamResult, + r#"SELECT r.exam AS "exam: ExamId", r.app_user AS "user: UserId", r.seq, + r.mark AS "mark: Mark", r.graded_by AS "graded_by: UserId" + FROM exam_result r JOIN exam e ON e.id = r.exam + WHERE r.app_user = $1 AND e.term = $2 + ORDER BY r.exam DESC, r.seq DESC"#, + user.uuid(), + term.uuid(), ) .fetch_all(db) .await?; @@ -505,8 +529,7 @@ mod tests { .unwrap() .map(|row| row.try_get::(0).unwrap()) .unwrap_or(0); - let exam_count = - sqlx::query("SELECT COALESCE(sum(result_count), 0)::bigint FROM exam") + let exam_count = sqlx::query("SELECT COALESCE(sum(result_count), 0)::bigint FROM exam") .fetch_one(db) .await .unwrap() @@ -517,8 +540,9 @@ mod tests { async fn an_exam(db: &Database, exam: &ExamId, kind: &str) { // The exam has to be real: a mark is refused on one that isn't. Its - // creator and course are real parents now, so the fixture grows them - // too (the teacher idempotently — [`the_two_people`] re-runs it). + // creator is a real row (idempotently — [`the_two_people`] re-runs it) + // and so are its parents: the instance it is taught in and the dönem it + // is graded in, both through the shared fixtures. let teacher = UserId::from_key(TEACHER); sqlx::query( "INSERT INTO app_user (id, username, created_at, role) \ @@ -528,23 +552,17 @@ mod tests { .execute(db) .await .unwrap(); - let course = CourseId::generate(); - sqlx::query( - "INSERT INTO course (id, creator, title, description) \ - VALUES ($1, $2, 'c', '')", - ) - .bind(course.uuid()) - .bind(teacher.uuid()) - .execute(db) - .await - .unwrap(); + let (instance, _course) = crate::db::course::a_test_instance(db).await; + let term = crate::db::term::a_test_term(db).await; sqlx::query( - "INSERT INTO exam (id, creator, course, title, description, kind) \ - VALUES ($1, $2, $3, 't', '', $4)", + "INSERT INTO exam (id, creator, class_course, term, title, description, kind, \ + max_attempts, allow_rejoin, allow_review, draft) \ + VALUES ($1, $2, $3, $4, 't', '', $5, 1, true, false, false)", ) .bind(exam.uuid()) .bind(teacher.uuid()) - .bind(course.uuid()) + .bind(instance.uuid()) + .bind(term.uuid()) .bind(kind) .execute(db) .await diff --git a/src/db/fee_plan.rs b/src/db/fee_plan.rs index 4fd763f..afec0e5 100644 --- a/src/db/fee_plan.rs +++ b/src/db/fee_plan.rs @@ -177,8 +177,7 @@ mod tests { #[tokio::test] async fn installments_survive_a_round_trip_through_the_schema() { let (db, _leases) = crate::database::init_test_db().await; - let manager = - crate::db::class_member::tests::fixture_user(&db, "fee-manager").await; + let manager = crate::db::class_member::tests::fixture_user(&db, "fee-manager").await; let installments = vec![ Installment::new( LedgerAmount::try_new(150_000).unwrap(), diff --git a/src/db/field_update.rs b/src/db/field_update.rs index 5503757..ccc4bdf 100644 --- a/src/db/field_update.rs +++ b/src/db/field_update.rs @@ -336,7 +336,14 @@ async fn run_with_refcount( // lifted from an async fn's *pattern parameter* poisons the higher-ranked // `AsyncFnMut`/`Send` evaluation of any closure that captures it // ("`Send` would have to be implemented for `&'0 str`, for any lifetime"). - let Refcount { counter_table, counter_field, claim, release, refused, .. } = refcount; + let Refcount { + counter_table, + counter_field, + claim, + release, + refused, + .. + } = refcount; // Owned into the closure: a captured `&str` — even `'static` — drags the // async closure's arg lifetime off the higher-ranked one `tx_with_retry` // needs ("AsyncFnMut is not general enough" at the route registration). diff --git a/src/db/homework.rs b/src/db/homework.rs index 891f004..045d437 100644 --- a/src/db/homework.rs +++ b/src/db/homework.rs @@ -5,7 +5,7 @@ //! delete. use crate::database::{Database, tx_with_retry}; -use crate::domain::course::CourseId; +use crate::domain::class_course::ClassCourseId; use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle}; use crate::domain::subject::SubjectId; use crate::domain::timestamp::Timestamp; @@ -36,7 +36,7 @@ const STALE_MOVE: &str = "the link this update moves changed since it was read; )] pub async fn create( db: &Database, - course: &CourseId, + class_course: &ClassCourseId, subject: &SubjectId, title: HomeworkTitle, description: Option, @@ -56,7 +56,7 @@ pub async fn create( // whole-course, not even for the instant of its create. let homework = Homework { id: HomeworkId::generate(), - course: course.clone(), + class_course: class_course.clone(), subject: *subject, title, description, @@ -82,13 +82,13 @@ pub async fn create( // comes back "not general enough" over the higher-ranked connection // lease — every tx_with_retry site captures only owned values. let subject = *subject; - let course = course.clone(); + let class_course = class_course.clone(); tx_with_retry(db, false, async move |tx| { // And every bind is a precomputed value of this coroutine's own: a // bind expression reading a capture inside the macro keeps that // borrow alive across the await to the same `Send` end. let subject_uuid = subject.uuid(); - let course_uuid = course.uuid(); + let class_course_uuid = class_course.uuid(); let homework_uuid = homework.id.uuid(); let title = homework.title.clone(); let description = homework.description.clone(); @@ -103,10 +103,10 @@ pub async fn create( WHERE id = $1 RETURNING 1 ) - INSERT INTO homework (id, course, subject, title, description, due_at, created_by, created_at) + INSERT INTO homework (id, class_course, subject, title, description, due_at, created_by, created_at) SELECT $2, $3, $1, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM seat) RETURNING id AS "id: HomeworkId", - course AS "course: CourseId", + class_course AS "class_course: ClassCourseId", subject AS "subject: SubjectId", title AS "title: HomeworkTitle", description AS "description: HomeworkDescription", @@ -116,7 +116,7 @@ pub async fn create( created_at AS "created_at: Timestamp""#, subject_uuid, homework_uuid, - course_uuid, + class_course_uuid, title.as_str(), description.as_ref().map(HomeworkDescription::as_str), due_at_millis, @@ -158,7 +158,7 @@ pub async fn read(db: &Database, id: &HomeworkId) -> Result, Ap Ok(sqlx::query_as!( Homework, r#"SELECT id AS "id: HomeworkId", - course AS "course: CourseId", + class_course AS "class_course: ClassCourseId", subject AS "subject: SubjectId", title AS "title: HomeworkTitle", description AS "description: HomeworkDescription", @@ -174,13 +174,16 @@ pub async fn read(db: &Database, id: &HomeworkId) -> Result, Ap .await?) } -/// The course's homework, newest first (v7 ids sort by creation). The web +/// The instance's homework, newest first (v7 ids sort by creation). The web /// layer retains only the rows a given student `student_sees`. -pub async fn list_for_course(db: &Database, course: &CourseId) -> Result, AppError> { +pub async fn list_for_class_course( + db: &Database, + class_course: &ClassCourseId, +) -> Result, AppError> { Ok(sqlx::query_as!( Homework, r#"SELECT id AS "id: HomeworkId", - course AS "course: CourseId", + class_course AS "class_course: ClassCourseId", subject AS "subject: SubjectId", title AS "title: HomeworkTitle", description AS "description: HomeworkDescription", @@ -189,8 +192,8 @@ pub async fn list_for_course(db: &Database, course: &CourseId) -> Result", created_by AS "created_by: UserId", created_at AS "created_at: Timestamp" - FROM homework WHERE course = $1 ORDER BY id DESC"#, - course.uuid() + FROM homework WHERE class_course = $1 ORDER BY id DESC"#, + class_course.uuid() ) .fetch_all(db) .await?) @@ -202,7 +205,7 @@ pub async fn list_all(db: &Database) -> Result, AppError> { Ok(sqlx::query_as!( Homework, r#"SELECT id AS "id: HomeworkId", - course AS "course: CourseId", + class_course AS "class_course: ClassCourseId", subject AS "subject: SubjectId", title AS "title: HomeworkTitle", description AS "description: HomeworkDescription", @@ -217,22 +220,22 @@ pub async fn list_all(db: &Database) -> Result, AppError> { .await?) } -/// Every homework of every course in `courses`, newest first (one query) — -/// the cross-course list over a caller's visible courses. The web layer -/// still trims each course's rows to what the caller may see (a student to -/// the ones they `student_sees`). -pub async fn list_for_courses( +/// Every homework of every instance in `instances`, newest first (one +/// query) — the cross-instance list over a caller's visible courses. The web +/// layer still trims each instance's rows to what the caller may see (a +/// student to the ones they `student_sees`). +pub async fn list_for_class_courses( db: &Database, - courses: &[CourseId], + instances: &[ClassCourseId], ) -> Result, AppError> { - if courses.is_empty() { + if instances.is_empty() { return Ok(Vec::new()); } - let ids: Vec = courses.iter().map(CourseId::uuid).collect(); + let ids: Vec = instances.iter().map(ClassCourseId::uuid).collect(); Ok(sqlx::query_as!( Homework, r#"SELECT id AS "id: HomeworkId", - course AS "course: CourseId", + class_course AS "class_course: ClassCourseId", subject AS "subject: SubjectId", title AS "title: HomeworkTitle", description AS "description: HomeworkDescription", @@ -241,27 +244,27 @@ pub async fn list_for_courses( WHERE a.homework = homework.id) AS "assigned: Vec", created_by AS "created_by: UserId", created_at AS "created_at: Timestamp" - FROM homework WHERE course = ANY($1) ORDER BY id DESC"#, + FROM homework WHERE class_course = ANY($1) ORDER BY id DESC"#, &ids ) .fetch_all(db) .await?) } -/// The homework of `course` that `user` is meant to see — whole-course ones -/// plus any subset that names them — newest first. Backs a student's (or an -/// observer's) per-course homework report; mirrors +/// The homework of one instance that `user` is meant to see — whole-class +/// ones plus any subset that names them — newest first. Backs a student's (or +/// an observer's) per-instance homework report; mirrors /// [`Homework::student_sees`](crate::domain::homework::Homework::student_sees) /// in SQL so the filter runs in the database. pub async fn list_for_user_in_course( db: &Database, - course: &CourseId, + class_course: &ClassCourseId, user: &UserId, ) -> Result, AppError> { Ok(sqlx::query_as!( Homework, r#"SELECT id AS "id: HomeworkId", - course AS "course: CourseId", + class_course AS "class_course: ClassCourseId", subject AS "subject: SubjectId", title AS "title: HomeworkTitle", description AS "description: HomeworkDescription", @@ -271,13 +274,13 @@ pub async fn list_for_user_in_course( created_by AS "created_by: UserId", created_at AS "created_at: Timestamp" FROM homework - WHERE course = $1 + WHERE class_course = $1 AND (NOT EXISTS (SELECT 1 FROM homework_assignment a WHERE a.homework = homework.id) OR EXISTS (SELECT 1 FROM homework_assignment a WHERE a.homework = homework.id AND a.student = $2)) ORDER BY id DESC"#, - course.uuid(), + class_course.uuid(), user.uuid() ) .fetch_all(db) @@ -318,7 +321,7 @@ pub async fn update( let current = sqlx::query_as!( Homework, r#"SELECT id AS "id: HomeworkId", - course AS "course: CourseId", + class_course AS "class_course: ClassCourseId", subject AS "subject: SubjectId", title AS "title: HomeworkTitle", description AS "description: HomeworkDescription", @@ -420,7 +423,7 @@ pub async fn update( due_at = $5 WHERE id = $1 RETURNING id AS "id: HomeworkId", - course AS "course: CourseId", + class_course AS "class_course: ClassCourseId", subject AS "subject: SubjectId", title AS "title: HomeworkTitle", description AS "description: HomeworkDescription", @@ -552,7 +555,7 @@ pub async fn delete( Homework, r#"DELETE FROM homework WHERE id = $1 RETURNING id AS "id: HomeworkId", - course AS "course: CourseId", + class_course AS "class_course: ClassCourseId", subject AS "subject: SubjectId", title AS "title: HomeworkTitle", description AS "description: HomeworkDescription", @@ -596,8 +599,9 @@ mod tests { } async fn homework_on(subject: &SubjectId, db: &Database) -> Homework { - // The course and the teacher are foreign keys now: a real course row - // (the subject's own fixture path mints one) and a real teacher. + // The instance and the teacher are foreign keys now: a real instance + // row (the class, the course and their link, minted by the fixture) + // and a real teacher. let teacher = UserId::generate(); sqlx::query( "INSERT INTO app_user (id, username, created_at, role) \ @@ -610,7 +614,7 @@ mod tests { .unwrap(); create( db, - &crate::db::course::a_test_course(db).await, + &crate::db::course::a_test_instance(db).await.0, subject, HomeworkTitle::try_new("essay").unwrap(), None, @@ -655,7 +659,7 @@ mod tests { let error = create( &db, - &CourseId::from_key("course"), + &crate::domain::class_course::ClassCourseId::from_key("course"), &id, HomeworkTitle::try_new("essay").unwrap(), None, @@ -688,17 +692,9 @@ mod tests { let homework = homework_on(from.get_id(), &db).await; assert_eq!(count_on(from.get_id(), &db).await, 1); - let moved = update( - &db, - homework, - Some(*to.get_id()), - None, - None, - None, - None, - ) - .await - .unwrap(); + let moved = update(&db, homework, Some(*to.get_id()), None, None, None, None) + .await + .unwrap(); assert_eq!(moved.get_subject(), to.get_id()); assert_eq!( count_on(from.get_id(), &db).await, @@ -728,17 +724,9 @@ mod tests { crate::db::subject::delete(&db, dead).await.unwrap(); let homework = homework_on(from.get_id(), &db).await; - let error = update( - &db, - homework.clone(), - Some(gone), - None, - None, - None, - None, - ) - .await - .expect_err("a subject that is gone must not be taggable"); + let error = update(&db, homework.clone(), Some(gone), None, None, None, None) + .await + .expect_err("a subject that is gone must not be taggable"); assert!(error.to_string().contains("subject does not exist")); let stored = read(&db, homework.get_id()).await.unwrap().unwrap(); assert_eq!(stored.get_subject(), from.get_id(), "the tag never moved"); @@ -770,17 +758,9 @@ mod tests { let other = a_subject("calculus", &db).await; let homework = homework_on(from.get_id(), &db).await; let stale = homework.clone(); - update( - &db, - homework, - Some(*to.get_id()), - None, - None, - None, - None, - ) - .await - .unwrap(); + update(&db, homework, Some(*to.get_id()), None, None, None, None) + .await + .unwrap(); let error = update( &db, @@ -823,17 +803,9 @@ mod tests { let to = a_subject("geometry", &db).await; let homework = homework_on(from.get_id(), &db).await; let stale = homework.clone(); - update( - &db, - homework, - Some(*to.get_id()), - None, - None, - None, - None, - ) - .await - .unwrap(); + update(&db, homework, Some(*to.get_id()), None, None, None, None) + .await + .unwrap(); let error = update( &db, @@ -866,17 +838,9 @@ mod tests { // A *genuine* no-op re-state — nobody moved underneath it — still lands, // and still moves no counter: the CAS passes trivially. let fresh = read(&db, stale.get_id()).await.unwrap().unwrap(); - let same = update( - &db, - fresh, - Some(*to.get_id()), - None, - None, - None, - None, - ) - .await - .expect("re-stating the tag actually held is not a race"); + let same = update(&db, fresh, Some(*to.get_id()), None, None, None, None) + .await + .expect("re-stating the tag actually held is not a race"); assert_eq!(same.get_subject(), to.get_id()); assert_eq!( count_on(from.get_id(), &db).await, @@ -924,10 +888,10 @@ mod tests { .execute(&db) .await .unwrap(); - let course = crate::db::course::a_test_course(&db).await; + let instance = crate::db::course::a_test_instance(&db).await.0; let homework = create( &db, - &course, + &instance, subject.get_id(), HomeworkTitle::try_new("essay").unwrap(), None, @@ -939,27 +903,33 @@ mod tests { .unwrap(); assert_eq!(homework.get_assigned(), Some(&[ali][..])); assert_eq!( - list_for_user_in_course(&db, &course, &ali).await.unwrap().len(), + list_for_user_in_course(&db, &instance, &ali) + .await + .unwrap() + .len(), 1, "the named student sees the subset" ); assert!( - list_for_user_in_course(&db, &course, &veli) + list_for_user_in_course(&db, &instance, &veli) .await .unwrap() .is_empty(), "an unnamed student sees nothing" ); - // Widening back to the whole course (`Some(None)`) empties the + // Widening back to the whole instance (`Some(None)`) empties the // junction: everyone — including the never-named student — is covered. let widened = update(&db, homework, None, None, None, None, Some(None)) .await .unwrap(); assert_eq!(widened.get_assigned(), None); assert_eq!( - list_for_user_in_course(&db, &course, &veli).await.unwrap().len(), + list_for_user_in_course(&db, &instance, &veli) + .await + .unwrap() + .len(), 1, - "whole-course reaches the never-named student" + "whole-instance reaches the never-named student" ); } } diff --git a/src/db/homework_file.rs b/src/db/homework_file.rs index 5dbb4ea..c168aa7 100644 --- a/src/db/homework_file.rs +++ b/src/db/homework_file.rs @@ -199,7 +199,10 @@ pub async fn file_keys_for_course( r#"SELECT file FROM homework_file WHERE submission IN ( SELECT id FROM homework_submission - WHERE homework IN (SELECT id FROM homework WHERE course = $1) + WHERE homework IN ( + SELECT h.id FROM homework h + JOIN class_course cc ON cc.id = h.class_course + WHERE cc.course = $1) )"#, course.uuid() ) @@ -284,7 +287,7 @@ mod tests { use crate::domain::homework::HomeworkTitle; use crate::domain::subject::{SubjectDescription, SubjectName}; - let course = crate::db::course::a_test_course(db).await; + let (instance, course) = crate::db::course::a_test_instance(db).await; let subject = crate::db::subject::create( db, &course, @@ -295,7 +298,7 @@ mod tests { .unwrap(); hw::create( db, - &course, + &instance, subject.get_id(), HomeworkTitle::try_new("essay").unwrap(), None, @@ -310,24 +313,28 @@ mod tests { /// A real `app_user` row: submitters are foreign keys too. async fn a_student(db: &Database) -> UserId { let user = UserId::generate(); - sqlx::query("INSERT INTO app_user (id, username, created_at, role) VALUES ($1, $2, 0, 'student')") - .bind(user.uuid()) - .bind(format!("s-{}", &user.key()[30..])) - .execute(db) - .await - .unwrap(); + sqlx::query( + "INSERT INTO app_user (id, username, created_at, role) VALUES ($1, $2, 0, 'student')", + ) + .bind(user.uuid()) + .bind(format!("s-{}", &user.key()[30..])) + .execute(db) + .await + .unwrap(); user } /// A real `app_user` row: creators and submitters are foreign keys now. async fn a_teacher(db: &Database) -> UserId { let user = UserId::generate(); - sqlx::query("INSERT INTO app_user (id, username, created_at, role) VALUES ($1, $2, 0, 'teacher')") - .bind(user.uuid()) - .bind(format!("t-{}", &user.key()[30..])) - .execute(db) - .await - .unwrap(); + sqlx::query( + "INSERT INTO app_user (id, username, created_at, role) VALUES ($1, $2, 0, 'teacher')", + ) + .bind(user.uuid()) + .bind(format!("t-{}", &user.key()[30..])) + .execute(db) + .await + .unwrap(); user } diff --git a/src/db/homework_result.rs b/src/db/homework_result.rs index df63001..a55f50e 100644 --- a/src/db/homework_result.rs +++ b/src/db/homework_result.rs @@ -6,7 +6,7 @@ //! [`crate::domain::homework_result`]. use crate::database::{Database, tx_with_retry}; -use crate::domain::course::CourseId; +use crate::domain::class_course::ClassCourseId; use crate::domain::exam_result::Mark; use crate::domain::homework::HomeworkId; use crate::domain::homework_result::{HomeworkResult, HomeworkResultId, HomeworkStatus}; @@ -180,7 +180,7 @@ pub async fn list_for_homework( /// `ExamResult::list_for_user_in_course`. pub async fn list_for_user_in_course( db: &Database, - course: &CourseId, + class_course: &ClassCourseId, user: &UserId, ) -> Result, AppError> { Ok(sqlx::query_as!( @@ -194,10 +194,10 @@ pub async fn list_for_user_in_course( created_at AS "created_at: Timestamp" FROM homework_result WHERE app_user = $1 - AND homework IN (SELECT id FROM homework WHERE course = $2) + AND homework IN (SELECT id FROM homework WHERE class_course = $2) ORDER BY id DESC"#, user.uuid(), - course.uuid() + class_course.uuid() ) .fetch_all(db) .await?) @@ -304,7 +304,7 @@ mod tests { use crate::domain::homework::HomeworkTitle; use crate::domain::subject::{SubjectDescription, SubjectName}; - let course = crate::db::course::a_test_course(db).await; + let (instance, course) = crate::db::course::a_test_instance(db).await; let subject = crate::db::subject::create( db, &course, @@ -315,7 +315,7 @@ mod tests { .unwrap(); homework::create( db, - &course, + &instance, subject.get_id(), HomeworkTitle::try_new("essay").unwrap(), None, diff --git a/src/db/homework_submission.rs b/src/db/homework_submission.rs index a81ee6b..99362e2 100644 --- a/src/db/homework_submission.rs +++ b/src/db/homework_submission.rs @@ -403,7 +403,7 @@ mod tests { /// A real homework row (and the subject it must reference) due at `due_at` — /// `upsert` now reads the deadline off the entity, so the tests need one. async fn a_homework(due_at: Timestamp, db: &Database) -> Homework { - let course = crate::db::course::a_test_course(db).await; + let (instance, course) = crate::db::course::a_test_instance(db).await; let subject = crate::db::subject::create( db, &course, @@ -414,7 +414,7 @@ mod tests { .unwrap(); homework_db::create( db, - &course, + &instance, subject.get_id(), HomeworkTitle::try_new("essay").unwrap(), None, diff --git a/src/db/karne.rs b/src/db/karne.rs new file mode 100644 index 0000000..813e9d0 --- /dev/null +++ b/src/db/karne.rs @@ -0,0 +1,66 @@ +//! The `karne_snapshot` table: the frozen per-student, per-dönem report +//! written when a term is archived. +//! +//! Karne is a *computed* read (D8) — per-instance weighted average, graded +//! against the school's bands, then a `ders_saati`-weighted year average. The +//! snapshot exists for the moment that computation must stop moving: once a +//! dönem is archived, the report is a record of what the school issued, and a +//! later correction to a mark must not silently rewrite a karne a family +//! already holds. [`crate::service::karne::freeze`] writes the rows; +//! [`crate::service::karne::build`] serves the snapshot back for an archived +//! term and computes live for an open one. + +use sqlx::types::Json; + +use crate::database::Database; +use crate::domain::term::TermId; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// Write (or refresh) `user`'s frozen report for `term`. +/// +/// An upsert rather than an insert: freezing is idempotent and converges — +/// archiving an already-archived term writes nothing +/// ([`crate::db::term::archive`]), and a re-run recomputes the same payload +/// from the same rows, so overwriting it is a no-op in substance and one +/// statement instead of an existence dance. +pub async fn snapshot( + db: &Database, + term: &TermId, + user: &UserId, + payload: &serde_json::Value, +) -> Result<(), AppError> { + let payload = Json(payload.clone()); + sqlx::query!( + r#"INSERT INTO karne_snapshot (term, app_user, payload, created_at) + VALUES ($1, $2, $3, $4) + ON CONFLICT (term, app_user) DO UPDATE + SET payload = EXCLUDED.payload, created_at = EXCLUDED.created_at"#, + term.uuid(), + user.uuid(), + payload as _, + Timestamp::now().as_millis(), + ) + .execute(db) + .await?; + Ok(()) +} + +/// `user`'s frozen report for `term`, or `None` when that dönem was never +/// frozen (or they had no roster row to freeze). +pub async fn read_snapshot( + db: &Database, + term: &TermId, + user: &UserId, +) -> Result, AppError> { + let row = sqlx::query!( + r#"SELECT payload AS "payload: Json" + FROM karne_snapshot WHERE term = $1 AND app_user = $2"#, + term.uuid(), + user.uuid(), + ) + .fetch_optional(db) + .await?; + Ok(row.map(|row| row.payload.0)) +} diff --git a/src/db/meal_booking.rs b/src/db/meal_booking.rs index b622fdd..b94fca4 100644 --- a/src/db/meal_booking.rs +++ b/src/db/meal_booking.rs @@ -588,11 +588,10 @@ mod tests { "the attempt this call read is gone, so it releases nothing" ); // Stored state, not the returned value: the mem engine forges wins. - let stored = - read(&db, &MealBookingId::composite(&menu, live.get_student())) - .await - .unwrap() - .unwrap(); + let stored = read(&db, &MealBookingId::composite(&menu, live.get_student())) + .await + .unwrap() + .unwrap(); assert_eq!(stored.get_status(), MealBookingStatus::Booked); assert_eq!(stored.get_attempt(), live.get_attempt()); assert_eq!(seats(&menu, &db).await, 1, "and gives no seat back"); diff --git a/src/db/meal_ledger.rs b/src/db/meal_ledger.rs index 677adda..c03a63f 100644 --- a/src/db/meal_ledger.rs +++ b/src/db/meal_ledger.rs @@ -8,8 +8,8 @@ use crate::db::page::PagedList; use crate::domain::meal_ledger::{ LedgerAmount, LedgerMethod, LedgerNote, MealLedger, MealLedgerId, MealLedgerKind, }; -use crate::domain::timestamp::Timestamp; use crate::domain::menu::MenuId; +use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; diff --git a/src/db/message.rs b/src/db/message.rs index fcaf82f..21abb93 100644 --- a/src/db/message.rs +++ b/src/db/message.rs @@ -66,16 +66,12 @@ pub async fn list_folder( let home_arm = folder == Folder::Inbox; let mut from = match folder { Folder::Sent => "message WHERE sender = $1 AND sender_folder = 'sent'".to_string(), - Folder::Archive => { - "message WHERE (recipient = $1 AND recipient_folder = 'archive') \ + Folder::Archive => "message WHERE (recipient = $1 AND recipient_folder = 'archive') \ OR (sender = $1 AND sender_folder = 'archive')" - .to_string() - } - Folder::Trash => { - "message WHERE (recipient = $1 AND recipient_folder = 'trash') \ + .to_string(), + Folder::Trash => "message WHERE (recipient = $1 AND recipient_folder = 'trash') \ OR (sender = $1 AND sender_folder = 'trash')" - .to_string() - } + .to_string(), _ => "message WHERE recipient = $1 AND recipient_folder = $2".to_string(), }; // The `read` filter binds after whichever placeholders the folder shape diff --git a/src/db/mod.rs b/src/db/mod.rs index feb8f7c..714c92d 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -1,4 +1,5 @@ //! The only layer that executes queries. +pub mod academic_year; pub mod answer_image; pub mod appointment; pub mod appointment_slot; @@ -14,10 +15,12 @@ pub mod chatbot_message; pub mod chatbot_thread; pub mod class_blueprint; pub mod class_course; +pub mod class_course_teacher; pub mod class_group; pub mod class_member; pub mod class_pump; pub mod course; +pub mod course_membership; pub mod course_note; pub mod course_note_file; pub mod course_session; @@ -36,6 +39,7 @@ pub mod homework; pub mod homework_file; pub mod homework_result; pub mod homework_submission; +pub mod karne; pub mod meal_attendance; pub mod meal_booking; pub mod meal_ledger; @@ -46,8 +50,8 @@ pub mod note; pub mod note_file; pub mod page; pub mod parent_link; -pub mod person; pub mod payment_ledger; +pub mod person; pub mod pomodoro; pub mod pool_question; pub mod pool_question_image; diff --git a/src/db/payment_ledger.rs b/src/db/payment_ledger.rs index 5fd31fa..f16b4fd 100644 --- a/src/db/payment_ledger.rs +++ b/src/db/payment_ledger.rs @@ -302,4 +302,3 @@ pub(crate) async fn applied_to( let total = PaymentLedger::fold_balance(folds.into_iter().map(|fold| (fold.kind, fold.total))); Ok(total * -target_kind.sign()) } - diff --git a/src/db/question_image.rs b/src/db/question_image.rs index 68b3f95..7b30c3c 100644 --- a/src/db/question_image.rs +++ b/src/db/question_image.rs @@ -167,14 +167,17 @@ pub async fn delete_choices_not_in( } /// The blob names behind every image of every exam of `course` — collected -/// *before* the course-delete cascade wipes the rows. +/// *before* the course-delete cascade wipes the rows. The exams belong to the +/// course's instances since D1, so the join goes through `class_course`. pub async fn file_keys_for_course( db: &Database, course: &CourseId, ) -> Result, AppError> { let rows = sqlx::query!( r#"SELECT qi.file FROM question_image qi - JOIN exam e ON e.id = qi.exam WHERE e.course = $1"#, + JOIN exam e ON e.id = qi.exam + JOIN class_course cc ON cc.id = e.class_course + WHERE cc.course = $1"#, course.uuid(), ) .fetch_all(db) diff --git a/src/db/rag_output.rs b/src/db/rag_output.rs index 83f9018..2d362c7 100644 --- a/src/db/rag_output.rs +++ b/src/db/rag_output.rs @@ -312,8 +312,6 @@ mod tests { CourseTitle::try_new("c").unwrap(), CourseDescription::try_new("").unwrap(), CourseKind::try_new("course").unwrap(), - None, - None, ) .await .unwrap(); diff --git a/src/db/session_attendance.rs b/src/db/session_attendance.rs index 700d333..f32e8d5 100644 --- a/src/db/session_attendance.rs +++ b/src/db/session_attendance.rs @@ -7,7 +7,7 @@ use crate::database::{Database, tx_with_retry}; use crate::db::page::PagedList; use crate::domain::attendance::AttendanceStatus; -use crate::domain::course::CourseId; +use crate::domain::class_course::ClassCourseId; use crate::domain::course_session::{CourseSession, CourseSessionId}; use crate::domain::session_attendance::SessionAttendance; use crate::domain::timestamp::Timestamp; @@ -20,7 +20,7 @@ use crate::error::AppError; /// /// The "session still exists" gate is a row lock: the transaction takes the /// session row `FOR NO KEY UPDATE` before anything else, so a session (or -/// course) delete cascading beneath this mark simply waits, and a delete +/// instance) delete cascading beneath this mark simply waits, and a delete /// that got there first leaves this gate matching nothing — `404`, the /// mirror of [`crate::db::course_session::delete`]. The caller's /// pre-flight read sits several round trips in front of this write, which @@ -130,17 +130,18 @@ pub async fn mark( .unwrap_or(false); let row = sqlx::query_as!( SessionAttendance, - r#"INSERT INTO session_attendance (session, app_user, course, status, marked_by, marked_at) + r#"INSERT INTO session_attendance (session, app_user, class_course, status, marked_by, marked_at) VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (session, app_user) DO UPDATE SET status = EXCLUDED.status, marked_by = EXCLUDED.marked_by, marked_at = EXCLUDED.marked_at RETURNING session AS "session: CourseSessionId", app_user AS "user: UserId", - course AS "course: CourseId", status AS "status: AttendanceStatus", + class_course AS "class_course: ClassCourseId", + status AS "status: AttendanceStatus", marked_by AS "marked_by: UserId""#, session.id.uuid(), user.uuid(), - session.course.uuid(), + session.class_course.uuid(), status.as_str(), marked_by.uuid(), now.as_millis(), @@ -213,7 +214,8 @@ pub async fn list_for_user( let rows = sqlx::query_as!( SessionAttendance, r#"SELECT session AS "session: CourseSessionId", app_user AS "user: UserId", - course AS "course: CourseId", status AS "status: AttendanceStatus", + class_course AS "class_course: ClassCourseId", + status AS "status: AttendanceStatus", marked_by AS "marked_by: UserId" FROM session_attendance WHERE app_user = $1 ORDER BY session DESC, app_user DESC"#, @@ -251,7 +253,8 @@ pub async fn remove( let Some(gone) = sqlx::query_as!( SessionAttendance, r#"SELECT session AS "session: CourseSessionId", app_user AS "user: UserId", - course AS "course: CourseId", status AS "status: AttendanceStatus", + class_course AS "class_course: ClassCourseId", + status AS "status: AttendanceStatus", marked_by AS "marked_by: UserId" FROM session_attendance WHERE session = $1 AND app_user = $2 @@ -336,7 +339,7 @@ mod tests { async fn a_session_at(teacher: &UserId, starts_at: i64, db: &Database) -> CourseSession { crate::db::course_session::create( db, - &crate::db::course::a_test_course(db).await, + &crate::db::course::a_test_instance(db).await.0, teacher, SessionTopic::try_new("limits").unwrap(), Timestamp::from_millis(starts_at), @@ -656,8 +659,9 @@ mod tests { let teacher = a_teacher("t", &db).await; let (mut swept, mut orphans) = (0, 0); - for (round, already_counted) in - [false, true, false, true, false, true, false, true].into_iter().enumerate() + for (round, already_counted) in [false, true, false, true, false, true, false, true] + .into_iter() + .enumerate() { let session = if already_counted { // Counted by somebody else's mark, so this one credits nothing. diff --git a/src/db/settings.rs b/src/db/settings.rs index 9a7eab8..3c2501e 100644 --- a/src/db/settings.rs +++ b/src/db/settings.rs @@ -22,6 +22,18 @@ fn sorted(values: &[String]) -> Vec { sorted } +/// One optional JSONB list as the value a statement binds: the list when the +/// setting carries one, SQL `NULL` when it does not. +fn encode_optional( + values: &Option>>, +) -> Result, AppError> { + values + .as_ref() + .map(|list| serde_json::to_value(&list.0)) + .transpose() + .map_err(|e| AppError::Internal(format!("settings encode: {e}"))) +} + /// The one read: row columns plus both vocabularies re-assembled from their /// child tables. An absent dietary set reads as `None` — the same shape an /// unset column used to carry. @@ -44,7 +56,12 @@ where (SELECT array_agg(t.tag ORDER BY t.tag) FROM settings_dietary_tag t WHERE t.settings = s.id) AS dietary_tags, - s.meal_cancel_cutoff_minutes + s.meal_cancel_cutoff_minutes, + s.branches AS "branches: Json>", + s.excuse_kinds AS "excuse_kinds: Json>", + s.max_excused_absent_days, + s.max_unexcused_absent_days, + s.timezone FROM settings s WHERE s.id = 'school'"# ) .fetch_optional(db) @@ -113,6 +130,12 @@ pub async fn save(db: &Database, settings: Settings) -> Result Result Result Result>", (SELECT array_agg(tag ORDER BY tag) FROM tag_ins) AS dietary_tags, - r.meal_cancel_cutoff_minutes + r.meal_cancel_cutoff_minutes, + r.branches AS "branches: Json>", + r.excuse_kinds AS "excuse_kinds: Json>", + r.max_excused_absent_days, + r.max_unexcused_absent_days, + r.timezone FROM new_row r"#, exam_kinds, &attendance, @@ -302,6 +360,16 @@ where expected.max_chatbot_threads, expected_meal_slots, expected.meal_cancel_cutoff_minutes, + branches, + excuse_kinds, + settings.max_excused_absent_days, + settings.max_unexcused_absent_days, + settings.timezone, + expected_branches, + expected_excuse_kinds, + expected.max_excused_absent_days, + expected.max_unexcused_absent_days, + expected.timezone, ) .fetch_optional(db) .await?; diff --git a/src/db/subject.rs b/src/db/subject.rs index 65c7a8c..f89244a 100644 --- a/src/db/subject.rs +++ b/src/db/subject.rs @@ -218,7 +218,12 @@ mod tests { .map(|_| ()) }) } - crate::db::course::assert_no_child_outlives_a_course_delete("subject", make).await; + crate::db::course::assert_no_child_outlives_a_course_delete( + "subject", + "SELECT count(*) FROM subject WHERE course = $1", + make, + ) + .await; } /// GUARD, not a retry measurement — read the last paragraph before diff --git a/src/db/term.rs b/src/db/term.rs index b130ed0..045bdb2 100644 --- a/src/db/term.rs +++ b/src/db/term.rs @@ -8,44 +8,64 @@ use crate::constant::TERM_TABLE; use crate::database::Database; use crate::db::field_update::FieldUpdate; use crate::db::page::PagedList; +use crate::domain::academic_year::AcademicYearId; use crate::domain::term::{Term, TermId, TermName}; use crate::domain::timestamp::{Timestamp, range_error}; -use crate::error::AppError; +use crate::error::{AppError, ValidationError}; pub async fn create( db: &Database, name: TermName, + year: AcademicYearId, starts_at: Timestamp, ends_at: Timestamp, ) -> Result { let term = Term { id: TermId::generate(), + year, name, starts_at, ends_at, archived_at: None, }; + // The year is claimed in the same statement as the row: `academic_year. + // term_count` + 1 is what the year's own delete guard reads, and + // claim-and-insert in one CTE means no crash can strand one half without + // the other. A year that is gone matches nothing — the `gone_error` the + // web layer's own read answers one instant earlier. let created = sqlx::query_as!( Term, - r#"INSERT INTO term (id, name, starts_at, ends_at, archived_at) - VALUES ($1, $2, $3, $4, NULL) - RETURNING id AS "id: TermId", name AS "name: TermName", + r#"WITH room AS ( + UPDATE academic_year SET term_count = term_count + 1 + WHERE id = $5 + RETURNING 1) + INSERT INTO term (id, name, year, starts_at, ends_at, archived_at) + SELECT $1, $2, $5, $3, $4, NULL WHERE EXISTS (SELECT 1 FROM room) + RETURNING id AS "id: TermId", year AS "year: AcademicYearId", + name AS "name: TermName", starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp", archived_at AS "archived_at: Timestamp""#, term.id.uuid(), term.name.as_str(), term.starts_at.as_millis(), term.ends_at.as_millis(), + term.year.uuid(), ) - .fetch_one(db) + .fetch_optional(db) .await?; - Ok(created) + created.ok_or_else(|| { + AppError::Validation(ValidationError::Invalid { + field: "year", + reason: "academic year does not exist", + }) + }) } pub async fn read(db: &Database, id: &TermId) -> Result, AppError> { let term = sqlx::query_as!( Term, - r#"SELECT id AS "id: TermId", name AS "name: TermName", + r#"SELECT id AS "id: TermId", year AS "year: AcademicYearId", + name AS "name: TermName", starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp", archived_at AS "archived_at: Timestamp" FROM term WHERE id = $1"#, id.uuid(), @@ -86,25 +106,42 @@ pub async fn update( .await } -/// Delete the term, but only while no course *and no class* links it — -/// nothing here unlinks or cascades. `false` = refused, nothing was written. +/// Delete the term, but only while nothing links it — nothing here unlinks or +/// cascades. `false` = refused, nothing was written. +/// +/// Two children refuse it. Exams are counted by the term's own `exam_count` +/// refcount, claimed by [`crate::db::exam::create`] *before* it writes the +/// link, so the check and the delete are one conditional write on one record: +/// an exam write racing this either claims first (and the delete is refused) +/// or finds the row gone (and is refused itself). A frozen karne +/// ([`crate::db::karne`]) has no counter — it is written once per archived +/// dönem — so its existence is the `NOT EXISTS` half of the same guard: a +/// dönem a family holds a karne for is history, not a calendar entry. /// -/// The roster of linking courses is the term's own `course_count` -/// refcount, claimed by [`crate::db::course::create`] and -/// `update` *before* they write a link, so the check and the delete are one -/// conditional write on one record: a course write racing this either -/// claims first (and the delete is refused) or finds the row gone (and is -/// refused itself, with the same 400 the lookup gives). `Err(NotFound)` +/// The referencing foreign keys (`exam.term`, `karne_snapshot.term`, both +/// `NO ACTION`) are the backstop behind the guard, not a second one: while +/// the count is honest the `WHERE` decides every race on its own, because the +/// claim path locks this very row before it writes a link. `Err(NotFound)` /// keeps the answer a concurrent *delete* used to get. /// -/// The referencing foreign keys (`course.term`, `class_group.term`, both -/// `NO ACTION`) are the backstop behind the counters, not a second guard: -/// while the counts are honest the `WHERE` decides every race on its own, -/// because both claim paths lock this very row before they write a link. +/// The year is handed its reference back in the *same statement* — a +/// `DELETE … RETURNING year` feeding the decrement, the shape +/// [`crate::db::course::delete`] uses for its classes — so a year whose last +/// dönem was just deleted is deletable the moment this lands. The counter +/// lives on the year row and only this statement may release it: without the +/// release the year's own `term_count = 0` delete guard could never pass +/// again, and a year nobody links would be undeletable forever. pub async fn delete(db: &Database, term: Term) -> Result { let gone = sqlx::query!( - r#"DELETE FROM term - WHERE id = $1 AND course_count = 0 AND class_count = 0"#, + r#"WITH gone AS ( + DELETE FROM term + WHERE id = $1 AND exam_count = 0 + AND NOT EXISTS (SELECT 1 FROM karne_snapshot WHERE term = $1) + RETURNING year) + UPDATE academic_year + SET term_count = GREATEST(term_count - 1, 0) + FROM gone + WHERE academic_year.id = gone.year"#, term.id.uuid(), ) .execute(db) @@ -128,7 +165,8 @@ pub async fn archive(db: &Database, term: Term) -> Result { Term, r#"UPDATE term SET archived_at = $2 WHERE id = $1 AND archived_at IS NULL - RETURNING id AS "id: TermId", name AS "name: TermName", + RETURNING id AS "id: TermId", year AS "year: AcademicYearId", + name AS "name: TermName", starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp", archived_at AS "archived_at: Timestamp""#, term.id.uuid(), @@ -150,7 +188,8 @@ pub async fn unarchive(db: &Database, term: Term) -> Result { Term, r#"UPDATE term SET archived_at = NULL WHERE id = $1 AND archived_at IS NOT NULL - RETURNING id AS "id: TermId", name AS "name: TermName", + RETURNING id AS "id: TermId", year AS "year: AcademicYearId", + name AS "name: TermName", starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp", archived_at AS "archived_at: Timestamp""#, term.id.uuid(), @@ -163,6 +202,23 @@ pub async fn unarchive(db: &Database, term: Term) -> Result { } } +/// A real dönem behind a real academic year — the parent every exam names and +/// the grading slice every term-keyed read scopes to. Minted per call. +#[cfg(test)] +pub(crate) async fn a_test_term(db: &Database) -> TermId { + let year = crate::db::academic_year::a_test_year(db).await; + let term = create( + db, + TermName::try_new("1. Dönem").unwrap(), + year, + Timestamp::from_millis(0), + Timestamp::from_millis(1), + ) + .await + .unwrap(); + *term.get_id() +} + #[cfg(test)] mod tests { use super::*; @@ -175,9 +231,15 @@ mod tests { async fn a_moved_end_is_refused_against_the_stored_other_end() { let (db, _leases) = crate::database::init_test_db().await; let at = Timestamp::from_millis; - let term = create(&db, TermName::try_new("2026").unwrap(), at(100), at(200)) - .await - .unwrap(); + let term = create( + &db, + TermName::try_new("2026").unwrap(), + crate::db::academic_year::a_test_year(&db).await, + at(100), + at(200), + ) + .await + .unwrap(); let refused = update(&db, term.clone(), None, None, Some(at(50))) .await @@ -204,11 +266,13 @@ mod tests { async fn identical_starts_at_still_pages_each_term_exactly_once() { let (db, _leases) = crate::database::init_test_db().await; let at = Timestamp::from_millis; + let year = crate::db::academic_year::a_test_year(&db).await; let mut minted = Vec::new(); for i in 0..12 { let term = create( &db, TermName::try_new(&format!("t{i}")).unwrap(), + year, at(100), at(200), ) @@ -248,8 +312,8 @@ mod tests { /// through. A store answering "conflict, retry" therefore comes out as a /// 500 instead of the 404 or 409 the request owes. /// - /// The racer is [`crate::db::course::create`] against this - /// term: it claims `course_count` on the term row before it writes the + /// The racer is [`crate::db::exam::create`] against this + /// dönem: it claims `exam_count` on the term row before it writes the /// link, which is the same record and the same column the guard reads. Both /// sides are swept across each other sub-millisecond, exactly as in /// [`crate::db::subject::delete`]'s race test — a whole @@ -263,15 +327,19 @@ mod tests { /// [`write_with_retry`] is a single round trip wide — measured at 0 /// conflicts in 100 raced rounds, green with the retry loop cut to a single /// attempt. A status-code guard, then: a raced delete answers 409 or 404 and - /// never 500, and a course that got linked survives it. The retry is + /// never 500, and an exam that got linked survives it. The retry is /// measured on [`crate::db::course::delete`]. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - async fn a_delete_racing_a_course_create_never_answers_500() { - use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; + async fn a_delete_racing_an_exam_create_never_answers_500() { + use crate::domain::exam::{ + ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle, + }; use crate::domain::user::UserId; let (db, _leases) = crate::database::init_test_db().await; - // The course's teacher is a foreign key now: one real row, reused by - // every create in every round. + // The exam's parents are foreign keys now: one real instance — with + // its class and course — reused by every create in every round, and + // one real creator. + let (instance, _course) = crate::db::course::a_test_instance(&db).await; let teacher = UserId::generate(); sqlx::query( "INSERT INTO app_user (id, username, created_at, role) \ @@ -282,14 +350,24 @@ mod tests { .execute(&db) .await .unwrap(); + let kinds = crate::domain::settings::Settings::defaults() + .get_exam_kinds() + .to_vec(); + let year = crate::db::academic_year::a_test_year(&db).await; let (mut delete_500, mut create_500) = (0, 0); let (mut linked, mut wiped) = (0, 0); let (mut last_delete, mut last_create) = (String::new(), String::new()); let at = Timestamp::from_millis; for round in 0..20 { - let term = create(&db, TermName::try_new("2026").unwrap(), at(100), at(200)) - .await - .unwrap(); + let term = create( + &db, + TermName::try_new("2026").unwrap(), + year, + at(100), + at(200), + ) + .await + .unwrap(); let separated = round % 4 == 0; let drop_it = { @@ -312,7 +390,9 @@ mod tests { }; let makes: Vec<_> = (0..6) .map(|_| { - let (id, db, teacher) = (*term.get_id(), db.clone(), teacher); + let (instance, db, teacher, kinds) = + (instance.clone(), db.clone(), teacher, kinds.clone()); + let term = *term.get_id(); let head_start = if separated { std::time::Duration::from_millis(2) } else { @@ -320,14 +400,19 @@ mod tests { }; tokio::spawn(async move { tokio::time::sleep(head_start).await; - crate::db::course::create( + crate::db::exam::create( &db, &teacher, - CourseTitle::try_new("algebra").unwrap(), - CourseDescription::try_new("").unwrap(), - CourseKind::course(), - Some(id), - None, + &instance, + &term, + ExamTitle::try_new("algebra").unwrap(), + ExamDescription::try_new("").unwrap(), + ExamKind::try_new("yazili", &kinds).unwrap(), + ExamSchedule::try_new(None, None, None, None).unwrap(), + ExamAttemptLimit::try_new(1).unwrap(), + true, + false, + false, ) .await }) @@ -338,7 +423,7 @@ mod tests { delete_500 += 1; last_delete = format!("{drop_it:?}"); } - // Stored state, both sides: a linked course means the claim beat the + // Stored state, both sides: a linked exam means the claim beat the // guard, a gone term means the delete did. let mut landed = false; for make in makes { @@ -347,8 +432,8 @@ mod tests { create_500 += 1; last_create = format!("{make:?}"); } - if let Ok(course) = &make - && crate::db::course::read(&db, course.get_id()) + if let Ok(exam) = &make + && crate::db::exam::read(&db, exam.get_id()) .await .unwrap() .is_some() @@ -363,7 +448,7 @@ mod tests { } eprintln!( "Term::delete raced: {delete_500}/20 delete 500s, {create_500} create 500s, \ - {linked} rounds with a course linked / {wiped} wiped" + {linked} rounds with an exam linked / {wiped} wiped" ); assert!( linked > 0 && wiped > 0, @@ -375,7 +460,7 @@ mod tests { ); assert_eq!( create_500, 0, - "a raced course create must retry, not 500: {create_500}/20 rounds, last {last_create}" + "a raced exam create must retry, not 500: {create_500}/20 rounds, last {last_create}" ); } } diff --git a/src/db/user.rs b/src/db/user.rs index 34c6950..efed187 100644 --- a/src/db/user.rs +++ b/src/db/user.rs @@ -78,6 +78,7 @@ pub async fn create_with_role( bio AS "bio: Bio", avatar_file, avatar_content_type AS "avatar_content_type: FileContentType", + branch, avatar_size"#, id.uuid(), username.as_str(), @@ -121,6 +122,7 @@ pub async fn read(db: &Database, id: &UserId) -> Result, AppError> bio AS "bio: Bio", avatar_file, avatar_content_type AS "avatar_content_type: FileContentType", + branch, avatar_size FROM app_user WHERE id = $1"#, id.uuid() @@ -165,6 +167,7 @@ pub async fn list_by_ids(db: &Database, ids: &[UserId]) -> Result, App bio AS "bio: Bio", avatar_file, avatar_content_type AS "avatar_content_type: FileContentType", + branch, avatar_size FROM app_user WHERE id = ANY($1)"#, &ids @@ -196,6 +199,7 @@ pub async fn list_by_role(db: &Database, role: Role) -> Result, AppErr bio AS "bio: Bio", avatar_file, avatar_content_type AS "avatar_content_type: FileContentType", + branch, avatar_size FROM app_user WHERE role = $1 ORDER BY id DESC"#, role.as_str() @@ -417,6 +421,7 @@ pub async fn set_role_cascade( bio AS "bio: Bio", avatar_file, avatar_content_type AS "avatar_content_type: FileContentType", + branch, avatar_size"#, target.uuid(), role.as_str(), @@ -430,27 +435,49 @@ pub async fn set_role_cascade( }; if role != Role::Student { - // Class memberships go, and each class they were on gets its - // seat back. One row per (class, user), so one decrement each. + // Class memberships go *soft*: the live stint is stamped, not + // deleted — membership history survives a demotion, and the + // partial unique index leaves the pair free to rejoin if the + // account is promoted back — while each class they were live in + // gets its seat back (the counter counts live rows). One live row + // per (class, user), so one decrement each. sqlx::query!( r#"WITH gone AS ( - DELETE FROM class_member WHERE app_user = $1 RETURNING class + UPDATE class_member SET left_at = $2 + WHERE app_user = $1 AND left_at IS NULL + RETURNING class ) UPDATE class_group SET class_member_count = GREATEST(class_member_count - 1, 0) WHERE id IN (SELECT gone.class FROM gone)"#, target.uuid(), + now, ) .execute(&mut *tx) .await?; // Every enrollment row — hand-placed included — and each - // course's seat with it. + // *instance's* roster count with it (the roster counter lives on + // the class×course instance now). sqlx::query!( r#"WITH gone AS ( - DELETE FROM enrollment WHERE app_user = $1 RETURNING course + DELETE FROM enrollment WHERE app_user = $1 RETURNING class_course ) - UPDATE course + UPDATE class_course SET enrollment_count = GREATEST(enrollment_count - 1, 0) + WHERE id IN (SELECT gone.class_course FROM gone)"#, + target.uuid(), + ) + .execute(&mut *tx) + .await?; + // The individual club/etüt memberships go with them: a demoted + // account may hold no seat in a school-scoped course either, and + // each course gets its membership count back. + sqlx::query!( + r#"WITH gone AS ( + DELETE FROM course_membership WHERE app_user = $1 RETURNING course + ) + UPDATE course + SET course_membership_count = GREATEST(course_membership_count - 1, 0) WHERE id IN (SELECT gone.course FROM gone)"#, target.uuid(), ) @@ -562,11 +589,12 @@ pub async fn set_role_cascade( } if !role.at_least(Role::Teacher) { - // Course staffing goes — only teacher+ may hold a seat, and the - // seat is a `course_teacher` row now: one `DELETE` by its - // `teacher` index takes every assignment. + // Instance staffing goes — only teacher+ may hold a seat, and the + // seat is a `class_course_teacher` row now (D6 moved assignment + // onto the instance): one `DELETE` by its `teacher` index takes + // every assignment. sqlx::query!( - "DELETE FROM course_teacher WHERE teacher = $1", + "DELETE FROM class_course_teacher WHERE teacher = $1", target.uuid(), ) .execute(&mut *tx) @@ -643,6 +671,7 @@ pub async fn set_profile( birth_date: Option>, display_name: Option>, bio: Option>, + branch: Option>, ) -> Result { // `Some(None)` must bind an explicit NULL and `Some(Some(v))` a value: // `Param::OptText` carries both shapes of one nullable TEXT column. @@ -682,6 +711,13 @@ pub async fn set_profile( "bio", text(bio.as_ref().map(|n| n.as_ref().map(|x| x.as_str()))), ) + // The branş is plain text, not a newtype: the school's own list is + // settings data, so its membership check belongs to the write path + // that holds that list (the web layer), not to a row type. + .set( + "branch", + text(branch.as_ref().map(|n| n.as_ref().map(String::as_str))), + ) .run(db) .await } @@ -729,6 +765,7 @@ pub async fn set_avatar( bio AS "bio: Bio", avatar_file, avatar_content_type AS "avatar_content_type: FileContentType", + branch, avatar_size FROM app_user WHERE id = $1 FOR UPDATE"#, id.uuid() @@ -777,6 +814,7 @@ pub async fn clear_avatar(db: &Database, id: &UserId) -> Result, Ap bio AS "bio: Bio", avatar_file, avatar_content_type AS "avatar_content_type: FileContentType", + branch, avatar_size FROM app_user WHERE id = $1 FOR UPDATE"#, id.uuid() @@ -839,6 +877,7 @@ pub async fn find_by_username(db: &Database, username: &str) -> Result 0 { - sqlx::query_scalar!("SELECT count(*) FROM work_entry WHERE app_user = $1", user.uuid()) - .fetch_one(db) - .await? - .unwrap_or(0) + sqlx::query_scalar!( + "SELECT count(*) FROM work_entry WHERE app_user = $1", + user.uuid() + ) + .fetch_one(db) + .await? + .unwrap_or(0) } else { rows.len() as i64 }; diff --git a/src/domain/academic_year.rs b/src/domain/academic_year.rs new file mode 100644 index 0000000..e2e04ff --- /dev/null +++ b/src/domain/academic_year.rs @@ -0,0 +1,257 @@ +//! An academic year (eğitim yılı): the container a şube and its dönemler +//! belong to. Above [`crate::domain::term::Term`], which is a grading slice +//! inside it. +//! +//! The year carries the sınıf geçme policy (`grade_promotions`): a mapping +//! from one grade label to the next, applied by the explicit, idempotent +//! rollover command ([`crate::service::academic_year::rollover`]). A grade +//! absent from the list is not rolled over — that is how graduation is +//! expressed. +//! +//! The queries live in [`crate::db::academic_year`]; this file is the row +//! shape, its newtypes and the archive guard. + +use serde::{Deserialize, Serialize}; +use sqlx::types::Json; + +use crate::constant::{MAX_ACADEMIC_YEAR_NAME_LEN, MAX_CLASS_GRADE_LEN}; +use crate::domain::monotonic_id::next_uuid; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; +use crate::validate::validate_required; + +/// Typed academic-year row id. A UUIDv7 minted by the process-wide monotonic +/// generator, so `id` order is mint order. +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct AcademicYearId(uuid::Uuid); + +impl AcademicYearId { + pub fn generate() -> Self { + Self(next_uuid()) + } + + /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that + /// cannot take the newtype. Static `query!` binds take `self` directly. + pub fn uuid(&self) -> uuid::Uuid { + self.0 + } + + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, + /// which matches no row. + pub fn from_key(key: &str) -> Self { + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) + } + + pub fn key(&self) -> String { + self.0.to_string() + } +} + +/// The refusal every write against an archived year gets, coded so a client +/// can tell it from the other 409s on the same route. +pub fn archived_error() -> AppError { + AppError::ConflictCoded { + code: "academic_year_archived", + message: "this academic year is archived — past years are read-only".into(), + } +} + +/// The refusal a rollover into an already-populated target year gets. +pub fn rollover_target_not_empty() -> AppError { + AppError::ConflictCoded { + code: "rollover_target_not_empty", + message: "the target year already has classes — roll into an empty year".into(), + } +} + +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct AcademicYearName(String); + +impl AcademicYearName { + pub fn try_new(value: &str) -> Result { + validate_required("name", value, MAX_ACADEMIC_YEAR_NAME_LEN)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// One sınıf-geçme mapping: a student who finished `from_grade` moves to +/// `to_grade` at rollover. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct GradePromotion { + from_grade: String, + to_grade: String, +} + +impl GradePromotion { + pub fn try_new(from_grade: &str, to_grade: &str) -> Result { + let bound = |field: &'static str, value: &str| { + if value.is_empty() || value.chars().count() > MAX_CLASS_GRADE_LEN { + Err(ValidationError::Invalid { + field, + reason: "grade labels must be 1 to 20 characters", + }) + } else { + Ok(()) + } + }; + bound("from_grade", from_grade)?; + bound("to_grade", to_grade)?; + Ok(Self { + from_grade: from_grade.to_string(), + to_grade: to_grade.to_string(), + }) + } + + pub fn get_from_grade(&self) -> &str { + &self.from_grade + } + + pub fn get_to_grade(&self) -> &str { + &self.to_grade + } +} + +/// One academic year. Both ends are required; `archived_at` NULL = open. +#[derive(Debug, Clone, sqlx::FromRow)] +pub struct AcademicYear { + pub(crate) id: AcademicYearId, + pub(crate) name: AcademicYearName, + pub(crate) starts_at: Timestamp, + pub(crate) ends_at: Timestamp, + pub(crate) archived_at: Option, + pub(crate) creator: UserId, + pub(crate) grade_promotions: Json>, + pub(crate) class_count: i64, + pub(crate) term_count: i64, +} + +impl AcademicYear { + pub fn try_new( + name: &str, + starts_at: Timestamp, + ends_at: Timestamp, + creator: UserId, + grade_promotions: Vec, + ) -> Result { + if ends_at <= starts_at { + return Err(ValidationError::Invalid { + field: "ends_at", + reason: "must be after starts_at", + }); + } + Ok(Self { + id: AcademicYearId::generate(), + name: AcademicYearName::try_new(name)?, + starts_at, + ends_at, + archived_at: None, + creator, + grade_promotions: Json(grade_promotions), + class_count: 0, + term_count: 0, + }) + } + + pub fn get_id(&self) -> &AcademicYearId { + &self.id + } + + pub fn get_name(&self) -> &AcademicYearName { + &self.name + } + + pub fn get_starts_at(&self) -> Timestamp { + self.starts_at + } + + pub fn get_ends_at(&self) -> Timestamp { + self.ends_at + } + + pub fn get_archived_at(&self) -> Option { + self.archived_at + } + + pub fn get_creator(&self) -> &UserId { + &self.creator + } + + pub fn get_grade_promotions(&self) -> &[GradePromotion] { + &self.grade_promotions.0 + } + + /// The grade a şube of `grade` rolls into, or `None` when the grade has no + /// promotion entry (graduation). + pub fn promotion_for(&self, grade: &str) -> Option<&str> { + self.grade_promotions + .0 + .iter() + .find(|promo| promo.from_grade == grade) + .map(|promo| promo.to_grade.as_str()) + } + + pub fn get_class_count(&self) -> i64 { + self.class_count + } + + pub fn get_term_count(&self) -> i64 { + self.term_count + } + + pub fn is_archived(&self) -> bool { + self.archived_at.is_some() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ts(ms: i64) -> Timestamp { + Timestamp::from_millis(ms) + } + + #[tokio::test] + async fn name_is_required_and_bounded() { + assert!(AcademicYearName::try_new("2026-2027").is_ok()); + assert!(AcademicYearName::try_new("").is_err()); + assert!(AcademicYearName::try_new(" ").is_err()); + assert!(AcademicYearName::try_new(&"x".repeat(MAX_ACADEMIC_YEAR_NAME_LEN + 1)).is_err()); + } + + #[tokio::test] + async fn promotions_validate_both_labels() { + assert!(GradePromotion::try_new("5", "6").is_ok()); + assert!(GradePromotion::try_new("", "6").is_err()); + assert!(GradePromotion::try_new("5", &"x".repeat(MAX_CLASS_GRADE_LEN + 1)).is_err()); + } + + #[tokio::test] + async fn a_year_needs_a_forward_range() { + let creator = UserId::from_key("0198f1a2-3b4c-7d5e-8f90-aaaa2b3c4d5e"); + assert!(AcademicYear::try_new("2026-2027", ts(0), ts(1000), creator, vec![]).is_ok()); + assert!(AcademicYear::try_new("2026-2027", ts(1000), ts(1000), creator, vec![]).is_err()); + } + + #[tokio::test] + async fn promotion_for_maps_known_grades_only() { + let creator = UserId::from_key("0198f1a2-3b4c-7d5e-8f90-aaaa2b3c4d5e"); + let year = AcademicYear::try_new( + "2026-2027", + ts(0), + ts(1000), + creator, + vec![GradePromotion::try_new("5", "6").unwrap()], + ) + .unwrap(); + assert_eq!(year.promotion_for("5"), Some("6")); + assert_eq!(year.promotion_for("12"), None); + } +} diff --git a/src/domain/appointment.rs b/src/domain/appointment.rs index c4bc3a5..92d4c14 100644 --- a/src/domain/appointment.rs +++ b/src/domain/appointment.rs @@ -25,7 +25,7 @@ //! ([`crate::db::appointment::save_if_unchanged`]), decided by a conditional //! `UPDATE`. -use crate::constant::{MAX_APPOINTMENT_REASON_LEN}; +use crate::constant::MAX_APPOINTMENT_REASON_LEN; use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId}; use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; diff --git a/src/domain/appointment_slot.rs b/src/domain/appointment_slot.rs index b957ff3..e9394a5 100644 --- a/src/domain/appointment_slot.rs +++ b/src/domain/appointment_slot.rs @@ -19,9 +19,7 @@ //! live in [`crate::db::appointment_slot`]; the publish and delete workflows //! in [`crate::service::appointment_slot`]. -use crate::constant::{ - MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES, MILLIS_PER_WEEK, -}; +use crate::constant::{MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES, MILLIS_PER_WEEK}; use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; diff --git a/src/domain/chatbot_message.rs b/src/domain/chatbot_message.rs index 768cde1..05a21af 100644 --- a/src/domain/chatbot_message.rs +++ b/src/domain/chatbot_message.rs @@ -9,9 +9,7 @@ //! ([`ChatbotMessage::projected`]) — the durable repair for a dead process //! happens once, at mint, in `database.rs`'s school migration sweep. -use crate::constant::{ - CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN, STALE_ERROR_CODE, -}; +use crate::constant::{CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN, STALE_ERROR_CODE}; use crate::domain::chatbot_thread::ChatbotThreadId; use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; diff --git a/src/domain/chatbot_thread.rs b/src/domain/chatbot_thread.rs index f47bd47..5b43aaf 100644 --- a/src/domain/chatbot_thread.rs +++ b/src/domain/chatbot_thread.rs @@ -4,7 +4,7 @@ //! [`crate::db::chatbot_message`], and deleting a thread cascades them; the //! threads' own persistence lives in [`crate::db::chatbot_thread`]. -use crate::constant::{MAX_CHATBOT_THREAD_TITLE_LEN}; +use crate::constant::MAX_CHATBOT_THREAD_TITLE_LEN; use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; diff --git a/src/domain/class_blueprint.rs b/src/domain/class_blueprint.rs index a8cd385..2380f41 100644 --- a/src/domain/class_blueprint.rs +++ b/src/domain/class_blueprint.rs @@ -250,7 +250,6 @@ mod tests { (Attached::PivotGone, "course_deleted"), (Attached::ClassFull, "class_at_course_ceiling"), (Attached::ClassOverloaded, "class_roster_too_large"), - (Attached::Full("course:algebra".into()), "course_full"), ( Attached::CourseGone("course:algebra".into()), "linked_course_missing", @@ -298,7 +297,6 @@ mod tests { Attached::::Duplicate, Attached::Gone, Attached::PivotGone, - Attached::Full("course:algebra".into()), Attached::CourseGone("course:algebra".into()), Attached::SourceGone, ] { diff --git a/src/domain/class_course.rs b/src/domain/class_course.rs index 835f484..52a046e 100644 --- a/src/domain/class_course.rs +++ b/src/domain/class_course.rs @@ -1,59 +1,102 @@ -//! A course attached to a class, and the enrollments that attachment implies. +//! A course as taught in one class: the academic *instance*. //! -//! The mirror of [`crate::domain::class_member`] along the pump's other axis: -//! attaching a course enrolls the class's whole roster into it, detaching it -//! sweeps the rows that attach wrote. The attach/detach workflows live in -//! [`crate::service::class_course`]; the row's reads in -//! [`crate::db::class_course`] — this file is the row shape and its -//! composite id. +//! The anchor of the K12 model. A course in the school catalog is a template; +//! attaching it to a şube mints one of these rows, and exams, sessions, +//! roll-call, homework and enrollments all key on the instance — so two +//! şubeler teaching the same course have separate rosters, exams, timetables +//! and teachers. The row carries the weekly hours (`ders_saati`, the karne +//! weight) and whether it counts toward the karne. +//! +//! The attach/detach workflows live in [`crate::service::class_course`]; the +//! row's reads in [`crate::db::class_course`] — this file is the row shape and +//! its id. +use crate::constant::{MAX_DERS_SAATI, MIN_DERS_SAATI}; use crate::domain::class_blueprint::ClassBlueprintId; use crate::domain::class_group::ClassGroupId; use crate::domain::course::CourseId; +use crate::domain::monotonic_id::next_uuid; +use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; +use crate::error::ValidationError; -/// The identity of one (class, course) pair. Not a row column: the table's -/// primary key *is* the pair, and this struct's job is the underscore-joined -/// wire form at the HTTP edge. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ClassCourseId { - pub(crate) class: ClassGroupId, - pub(crate) course: CourseId, -} +/// The identity of one class×course instance. A UUIDv7 minted by the +/// process-wide monotonic generator, so a class's instances list in creation +/// order. +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct ClassCourseId(uuid::Uuid); impl ClassCourseId { - /// The one id a (class, course) pair can have. - pub fn composite(class: &ClassGroupId, course: &CourseId) -> Self { - Self { - class: class.clone(), - course: course.clone(), - } + pub fn generate() -> Self { + Self(next_uuid()) + } + + /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that + /// cannot take the newtype. Static `query!` binds take `self` directly. + pub fn uuid(&self) -> uuid::Uuid { + self.0 + } + + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, + /// which matches no row. + pub fn from_key(key: &str) -> Self { + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) } - /// The underscore-joined wire form (`{class}_{course}`). + /// The bare uuid wire form. pub fn key(&self) -> String { - format!("{}_{}", self.class.key(), self.course.key()) + self.0.to_string() + } +} + +/// Weekly lesson hours of an instance: the weight the instance carries in the +/// year's karne average, and the count a timetable grid would lay out. +#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct DersSaati(i64); + +impl DersSaati { + pub fn try_new(value: i64) -> Result { + if !(MIN_DERS_SAATI..=MAX_DERS_SAATI).contains(&value) { + return Err(ValidationError::Invalid { + field: "ders_saati", + reason: "must be between 1 and 40 weekly hours", + }); + } + Ok(Self(value)) + } + + pub fn as_i64(&self) -> i64 { + self.0 } } -/// One course a class is attached to. `attached_by` is who attached it. +/// One course taught in one class. `attached_by` is who attached it, `source` +/// the blueprint that placed it (absent for a hand attach). `ders_saati` and +/// `counts_toward_karne` are the instance's own policy — what two şubeler +/// teaching the same catalog course may legitimately differ on. #[derive(Debug, Clone, sqlx::FromRow)] pub struct ClassCourse { + pub(crate) id: ClassCourseId, pub(crate) class: ClassGroupId, pub(crate) course: CourseId, pub(crate) attached_by: UserId, /// The grade blueprint that placed this attachment, absent when a human - /// attached the course to this class directly — the mirror of - /// [`crate::domain::enrollment`]'s `source`, and read the same way: only a - /// row carrying the key is a blueprint's to take back, so a hand-attached - /// course survives every blueprint sweep. + /// attached the course to this class directly — read the same way as + /// [`crate::domain::enrollment`]'s `source`: only a row carrying the key + /// is a blueprint's to take back, so a hand-attached course survives every + /// blueprint sweep. pub(crate) source: Option, + pub(crate) ders_saati: DersSaati, + pub(crate) counts_toward_karne: bool, + pub(crate) enrollment_count: i64, + pub(crate) attached_at: Timestamp, } impl ClassCourse { - /// The row's identity, built back from its primary-key columns. - pub fn get_id(&self) -> ClassCourseId { - ClassCourseId::composite(&self.class, &self.course) + pub fn get_id(&self) -> &ClassCourseId { + &self.id } pub fn get_class(&self) -> &ClassGroupId { @@ -72,4 +115,20 @@ impl ClassCourse { pub fn get_source(&self) -> Option<&ClassBlueprintId> { self.source.as_ref() } + + pub fn get_ders_saati(&self) -> DersSaati { + self.ders_saati + } + + pub fn counts_toward_karne(&self) -> bool { + self.counts_toward_karne + } + + pub fn get_enrollment_count(&self) -> i64 { + self.enrollment_count + } + + pub fn get_attached_at(&self) -> Timestamp { + self.attached_at + } } diff --git a/src/domain/class_group.rs b/src/domain/class_group.rs index 2341f05..68f31ee 100644 --- a/src/domain/class_group.rs +++ b/src/domain/class_group.rs @@ -4,19 +4,21 @@ //! counted on this row — a class may only be deleted at zero on both, the same //! stored guard shape courses and terms use. //! -//! A class links a term exactly like a course does, and claims a reference on it -//! before the link is written. The reference is its *own* column -//! ([`crate::constant::TERM_CLASS_COUNT_FIELD`]) rather than the courses' `course_count`, because -//! boot seeds that one from the course rows alone and would wipe a class's share -//! of it on the next migration. +//! A class belongs to an academic year ([`crate::domain::academic_year`]), not +//! to a term: the şube keeps the same roster all year and the dönem is a +//! grading slice inside it. It claims a reference on its year before the link +//! is written; the reference is its *own* column +//! ([`crate::constant::ACADEMIC_YEAR_CLASS_COUNT_FIELD`]) rather than the +//! courses' own count, so a class's share is never confused with another +//! roster's. //! -//! The queries live in [`crate::db::class_group`]; the archived-term guard and +//! The queries live in [`crate::db::class_group`]; the archived-year guard and //! the route-facing wrappers in [`crate::service::class_group`] — this file is //! the row shape, its newtypes and getters. use crate::constant::{MAX_CLASS_GRADE_LEN, MAX_CLASS_NAME_LEN}; +use crate::domain::academic_year::AcademicYearId; use crate::domain::monotonic_id::next_uuid; -use crate::domain::term::TermId; use crate::domain::user::UserId; use crate::error::ValidationError; use crate::validate::{validate_optional, validate_required}; @@ -94,7 +96,7 @@ pub struct ClassGroup { pub(crate) creator: UserId, pub(crate) name: ClassName, pub(crate) grade: Option, - pub(crate) term: Option, + pub(crate) year: Option, pub(crate) teacher: Option, } @@ -115,8 +117,8 @@ impl ClassGroup { self.grade.as_ref() } - pub fn get_term(&self) -> Option<&TermId> { - self.term.as_ref() + pub fn get_year(&self) -> Option<&AcademicYearId> { + self.year.as_ref() } /// The homeroom teacher (sınıf öğretmeni), if one is assigned. diff --git a/src/domain/class_member.rs b/src/domain/class_member.rs index c13eb53..3f0a862 100644 --- a/src/domain/class_member.rs +++ b/src/domain/class_member.rs @@ -1,54 +1,69 @@ -//! A student's place in a class, and the enrollments that place implies. +//! A student's stint in a class, and the enrollments that place implies. //! -//! Both writes are one call into [`crate::db::class_pump`]: adding a member -//! and attaching a course to the class are the same pump seen from its two -//! ends. The refusals-to-errors policy and the detach live in +//! A history table: `left_at` NULL is the live stint, and the partial unique +//! index `(class, app_user) WHERE left_at IS NULL` keeps one live stint per +//! pair while preserving rejoin history (a student who leaves and comes back +//! has two rows). Both writes are one call into [`crate::db::class_pump`]: +//! adding a member and attaching a course to the class are the same pump seen +//! from its two ends. The refusals-to-errors policy and the detach live in //! [`crate::service::class_member`]; the roster reads in -//! [`crate::db::class_member`] — this file is the row shape and its -//! composite id. +//! [`crate::db::class_member`] — this file is the row shape and its id. use crate::domain::class_group::ClassGroupId; +use crate::domain::monotonic_id::next_uuid; +use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -/// The identity of one (class, user) pair. Not a row column: the table's -/// primary key *is* the pair, and this struct's job is the underscore-joined -/// wire form at the HTTP edge. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ClassMemberId { - pub(crate) class: ClassGroupId, - pub(crate) user: UserId, -} +/// The identity of one class-member stunt. A UUIDv7 minted by the +/// process-wide monotonic generator, so a class's roster lists in join order. +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct ClassMemberId(uuid::Uuid); impl ClassMemberId { - /// The one id a (class, user) pair can have. - pub fn composite(class: &ClassGroupId, user: &UserId) -> Self { - Self { - class: class.clone(), - user: *user, - } + pub fn generate() -> Self { + Self(next_uuid()) + } + + /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that + /// cannot take the newtype. Static `query!` binds take `self` directly. + pub fn uuid(&self) -> uuid::Uuid { + self.0 + } + + /// Parses a wire key. A key that is not a UUID parses as the nil UUID, + /// which matches no row. + pub fn from_key(key: &str) -> Self { + Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil())) } - /// The underscore-joined wire form (`{class}_{user}`). + /// The bare uuid wire form. pub fn key(&self) -> String { - format!("{}_{}", self.class.key(), self.user.key()) + self.0.to_string() } } -/// One student in one class. `added_by` is who put them there. +/// One student's stint in one class. `added_by` is who put them there; +/// `source_class_group` names the şube a rollover copied them from (absent for +/// a hand-added member). #[derive(Debug, Clone, sqlx::FromRow)] pub struct ClassMember { + pub(crate) id: ClassMemberId, pub(crate) class: ClassGroupId, /// The column is `app_user` (the reserved-word rename); the Rust name is /// the domain's. #[sqlx(rename = "app_user")] pub(crate) user: UserId, pub(crate) added_by: UserId, + pub(crate) joined_at: Timestamp, + /// When the student left; `None` while the stint is live. + pub(crate) left_at: Option, + pub(crate) source_class_group: Option, } impl ClassMember { - /// The row's identity, built back from its primary-key columns. - pub fn get_id(&self) -> ClassMemberId { - ClassMemberId::composite(&self.class, &self.user) + pub fn get_id(&self) -> &ClassMemberId { + &self.id } pub fn get_class(&self) -> &ClassGroupId { @@ -62,4 +77,21 @@ impl ClassMember { pub fn get_added_by(&self) -> &UserId { &self.added_by } + + pub fn get_joined_at(&self) -> Timestamp { + self.joined_at + } + + pub fn get_left_at(&self) -> Option { + self.left_at + } + + /// Whether this stint is live (the student is currently in the class). + pub fn is_live(&self) -> bool { + self.left_at.is_none() + } + + pub fn get_source_class_group(&self) -> Option<&ClassGroupId> { + self.source_class_group.as_ref() + } } diff --git a/src/domain/course.rs b/src/domain/course.rs index 7b2977a..51bb6fe 100644 --- a/src/domain/course.rs +++ b/src/domain/course.rs @@ -1,6 +1,5 @@ use crate::constant::{MAX_COURSE_DESCRIPTION_LEN, MAX_COURSE_TITLE_LEN}; use crate::domain::monotonic_id::next_uuid; -use crate::domain::term::TermId; use crate::domain::user::UserId; use crate::error::ValidationError; use crate::validate::{validate_course_kind, validate_optional, validate_required}; @@ -66,7 +65,8 @@ impl CourseDescription { /// A validated course kind: `course` (a regular class — ders), `study` (a /// supervised study session — etüt), or `club` (a student club — kulüp). -/// Purely a label; all kinds behave identically. +/// Only `course` is class-delivered (a şube attaches it as an instance); +/// `study`/`club` are school-scoped and joined individually. #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] #[sqlx(transparent)] pub struct CourseKind(String); @@ -85,32 +85,36 @@ impl CourseKind { pub fn as_str(&self) -> &str { &self.0 } + + /// Whether a şube attaches this kind as an instance. Only a regular ders + /// (`course`) is class-delivered; clubs and etüt are school-scoped and + /// joined individually ([`crate::domain::course_membership`]). + pub fn is_class_delivered(&self) -> bool { + self.0 == "course" + } } -/// A course: the unit exams and enrollments hang off. Marks are computed per -/// course, each exam weighted by its kind's settings weight. May belong to an -/// academic term. Comes in three behaviorally identical kinds: `course`, -/// `study` (etüt), and `club` (kulüp). An optional `capacity` caps the roster -/// at enroll time (`NULL` = unlimited). +/// A course: a school-level catalog entry. It is a *template* — the academic +/// work (roster, exams, timetable) lives on the instances a class attaches +/// ([`crate::domain::class_course::ClassCourse`]), so this row carries only +/// what every instance shares: title, description, kind. /// -/// `creator` owns the course for good — only they (or a manager+) may delete -/// it. `teachers` are the staff a manager assigned to run it: full management -/// rights inside the course, no power to delete it or change the assignment -/// list. The assignment itself is `course_teacher` rows; the struct carries -/// the resolved list, joined on by the db layer. +/// `creator` is who minted it; the catalog is Manager+-owned, so there is no +/// per-teacher ownership. The two counters are the delete guard: a course may +/// only be dropped when no class attaches it and no one holds an individual +/// membership. /// /// Fields are crate-visible: [`crate::db::course`] mints the rows on create /// and reads the id when updating and cascading a delete. -#[derive(Debug, Clone)] +#[derive(Debug, Clone, sqlx::FromRow)] pub struct Course { pub(crate) id: CourseId, pub(crate) creator: UserId, - pub(crate) teachers: Vec, pub(crate) title: CourseTitle, pub(crate) description: CourseDescription, pub(crate) kind: CourseKind, - pub(crate) term: Option, - pub(crate) capacity: Option, + pub(crate) class_course_count: i64, + pub(crate) course_membership_count: i64, } impl Course { @@ -134,30 +138,19 @@ impl Course { &self.kind } - pub fn get_term(&self) -> Option<&TermId> { - self.term.as_ref() + /// How many class instances attach this catalog course. + pub fn get_class_course_count(&self) -> i64 { + self.class_course_count } - /// The seat cap enforced at enroll time; `None` = unlimited. - pub fn get_capacity(&self) -> Option { - self.capacity + /// How many users hold an individual (club/etüt) membership. + pub fn get_course_membership_count(&self) -> i64 { + self.course_membership_count } pub fn is_creator(&self, user: &UserId) -> bool { &self.creator == user } - - /// The staff assigned to run this course. Assignment order is not kept: - /// the links are `course_teacher` rows now, and a set has no order. - pub fn get_teachers(&self) -> &[UserId] { - &self.teachers - } - - /// Whether `user` was assigned to teach this course. Says nothing about - /// the creator — they own it whether or not they also appear here. - pub fn is_assigned(&self, user: &UserId) -> bool { - self.teachers.contains(user) - } } #[cfg(test)] @@ -183,5 +176,8 @@ mod tests { assert!(CourseKind::try_new("club").is_ok()); assert!(CourseKind::try_new("etut").is_err()); assert_eq!(CourseKind::course().as_str(), "course"); + assert!(CourseKind::course().is_class_delivered()); + assert!(!CourseKind::try_new("club").unwrap().is_class_delivered()); + assert!(!CourseKind::try_new("study").unwrap().is_class_delivered()); } } diff --git a/src/domain/course_membership.rs b/src/domain/course_membership.rs new file mode 100644 index 0000000..d956cc0 --- /dev/null +++ b/src/domain/course_membership.rs @@ -0,0 +1,62 @@ +use crate::domain::course::CourseId; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; + +/// The identity of one (course, user) pair. Not a row column: the table's +/// primary key *is* the pair, which makes joining a single atomic UPSERT +/// (`ON CONFLICT (course, app_user)`) with no find-then-insert race. This +/// struct's job is the underscore-joined wire form at the HTTP edge. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CourseMembershipId { + pub(crate) course: CourseId, + pub(crate) user: UserId, +} + +impl CourseMembershipId { + pub fn composite(course: &CourseId, user: &UserId) -> Self { + Self { + course: course.clone(), + user: *user, + } + } + + /// The underscore-joined wire form (`{course}_{user}`). + pub fn key(&self) -> String { + format!("{}_{}", self.course.key(), self.user.key()) + } +} + +/// A user's individual membership in a *school-scoped* course (D9): a club or +/// an etüt a student joins directly. A class-delivered course +/// ([`crate::domain::course::CourseKind::is_class_delivered`]) is joined +/// through its instance instead, never here — that gate lives in the service. +#[derive(Debug, Clone, sqlx::FromRow)] +pub struct CourseMembership { + pub(crate) course: CourseId, + #[sqlx(rename = "app_user")] + pub(crate) user: UserId, + pub(crate) added_by: UserId, + pub(crate) created_at: Timestamp, +} + +impl CourseMembership { + pub fn get_id(&self) -> CourseMembershipId { + CourseMembershipId::composite(&self.course, &self.user) + } + + pub fn get_course(&self) -> &CourseId { + &self.course + } + + pub fn get_user(&self) -> &UserId { + &self.user + } + + pub fn get_added_by(&self) -> &UserId { + &self.added_by + } + + pub fn get_created_at(&self) -> Timestamp { + self.created_at + } +} diff --git a/src/domain/course_note_file.rs b/src/domain/course_note_file.rs index 3d962be..9431e7f 100644 --- a/src/domain/course_note_file.rs +++ b/src/domain/course_note_file.rs @@ -43,7 +43,6 @@ impl CourseNoteFileId { } } - #[derive(Debug, Clone, sqlx::FromRow)] pub struct CourseNoteFile { pub(crate) id: CourseNoteFileId, diff --git a/src/domain/course_session.rs b/src/domain/course_session.rs index 159ec01..be119a9 100644 --- a/src/domain/course_session.rs +++ b/src/domain/course_session.rs @@ -1,5 +1,5 @@ use crate::constant::MAX_SESSION_TOPIC_LEN; -use crate::domain::course::CourseId; +use crate::domain::class_course::ClassCourseId; use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; @@ -56,7 +56,7 @@ impl SessionTopic { #[derive(Debug, Clone, sqlx::FromRow)] pub struct CourseSession { pub(crate) id: CourseSessionId, - pub(crate) course: CourseId, + pub(crate) class_course: ClassCourseId, /// Who teaches this session. Must hold the `teacher` role or higher — /// enforced by [`crate::service::course_session::resolve_session_teacher`], /// where the target user row is at hand. @@ -71,8 +71,8 @@ impl CourseSession { &self.id } - pub fn get_course(&self) -> &CourseId { - &self.course + pub fn get_class_course(&self) -> &ClassCourseId { + &self.class_course } pub fn get_teacher(&self) -> &UserId { diff --git a/src/domain/dietary_profile.rs b/src/domain/dietary_profile.rs index 2ce189c..38244b9 100644 --- a/src/domain/dietary_profile.rs +++ b/src/domain/dietary_profile.rs @@ -13,7 +13,6 @@ //! //! [`Settings::get_dietary_tags`]: crate::domain::settings::Settings::get_dietary_tags - use crate::constant::{MAX_DIETARY_NOTE_LEN, MAX_DIETARY_TAGS}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; @@ -30,9 +29,7 @@ pub struct DietaryProfileId { impl DietaryProfileId { pub fn of(student: &UserId) -> Self { - Self { - student: *student, - } + Self { student: *student } } /// The student's wire key, which is the profile's. diff --git a/src/domain/enrollment.rs b/src/domain/enrollment.rs index 1bae012..9e7da35 100644 --- a/src/domain/enrollment.rs +++ b/src/domain/enrollment.rs @@ -1,34 +1,36 @@ +use crate::domain::class_course::ClassCourseId; use crate::domain::class_group::ClassGroupId; -use crate::domain::course::CourseId; +use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -/// The identity of one (course, user) pair. Not a row column: the table's +/// The identity of one (instance, user) pair. Not a row column: the table's /// primary key *is* the pair, which is what makes enrolling a single atomic -/// UPSERT (`ON CONFLICT (course, app_user)`) with no find-then-insert race -/// and one-row-per-pair by construction. This struct's job is the +/// UPSERT (`ON CONFLICT (class_course, app_user)`) with no find-then-insert +/// race and one-row-per-pair by construction. This struct's job is the /// underscore-joined wire form at the HTTP edge. #[derive(Debug, Clone, PartialEq, Eq)] pub struct EnrollmentId { - pub(crate) course: CourseId, + pub(crate) class_course: ClassCourseId, pub(crate) user: UserId, } impl EnrollmentId { - pub fn composite(course: &CourseId, user: &UserId) -> Self { + pub fn composite(class_course: &ClassCourseId, user: &UserId) -> Self { Self { - course: course.clone(), + class_course: class_course.clone(), user: *user, } } - /// The underscore-joined wire form (`{course}_{user}`). + /// The underscore-joined wire form (`{class_course}_{user}`). pub fn key(&self) -> String { - format!("{}_{}", self.course.key(), self.user.key()) + format!("{}_{}", self.class_course.key(), self.user.key()) } } -/// A user's membership in a course. Grading requires it; removing it hides the -/// user's marks from the report but never deletes result rows. +/// A user's membership in one class's instance of a course. Grading requires +/// it; removing it hides the user's marks from the report but never deletes +/// result rows. /// /// `source` names the class ([`crate::domain::class_group::ClassGroup`]) that /// pumped this row, and is NULL when a human placed the student directly — @@ -36,21 +38,22 @@ impl EnrollmentId { /// it: a class sweep may only take back the rows it wrote. #[derive(Debug, Clone, sqlx::FromRow)] pub struct Enrollment { - pub(crate) course: CourseId, + pub(crate) class_course: ClassCourseId, #[sqlx(rename = "app_user")] pub(crate) user: UserId, pub(crate) enrolled_by: UserId, pub(crate) source: Option, + pub(crate) created_at: Timestamp, } impl Enrollment { /// The row's identity, built back from its primary-key columns. pub fn get_id(&self) -> EnrollmentId { - EnrollmentId::composite(&self.course, &self.user) + EnrollmentId::composite(&self.class_course, &self.user) } - pub fn get_course(&self) -> &CourseId { - &self.course + pub fn get_class_course(&self) -> &ClassCourseId { + &self.class_course } pub fn get_user(&self) -> &UserId { @@ -65,4 +68,8 @@ impl Enrollment { pub fn get_source(&self) -> Option<&ClassGroupId> { self.source.as_ref() } + + pub fn get_created_at(&self) -> Timestamp { + self.created_at + } } diff --git a/src/domain/exam.rs b/src/domain/exam.rs index 8276cdf..3aeaa80 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -1,7 +1,8 @@ use crate::constant::{MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN, UNLIMITED_EXAM_ATTEMPTS}; -use crate::domain::course::CourseId; +use crate::domain::class_course::ClassCourseId; use crate::domain::monotonic_id::next_uuid; use crate::domain::settings::ExamKindDef; +use crate::domain::term::TermId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -286,7 +287,8 @@ impl ExamSchedule { pub struct Exam { pub(crate) id: ExamId, pub(crate) creator: UserId, - pub(crate) course: CourseId, + pub(crate) class_course: ClassCourseId, + pub(crate) term: TermId, pub(crate) title: ExamTitle, pub(crate) description: ExamDescription, pub(crate) kind: ExamKind, @@ -311,8 +313,12 @@ impl Exam { &self.creator } - pub fn get_course(&self) -> &CourseId { - &self.course + pub fn get_class_course(&self) -> &ClassCourseId { + &self.class_course + } + + pub fn get_term(&self) -> &TermId { + &self.term } pub fn get_title(&self) -> &ExamTitle { diff --git a/src/domain/exam_result.rs b/src/domain/exam_result.rs index 1dc6fdd..6372235 100644 --- a/src/domain/exam_result.rs +++ b/src/domain/exam_result.rs @@ -165,8 +165,8 @@ mod tests { let got = latest_per_pair(vec![ row(user, 1, 60), row(other, 1, 70), - row(user, 2, 85), // retake outranks the seq-1 mark - row(other, 3, 40), // third sitting of the second pair + row(user, 2, 85), // retake outranks the seq-1 mark + row(other, 3, 40), // third sitting of the second pair ]); assert_eq!(got.len(), 2); assert_eq!(got[0].get_user(), &user); diff --git a/src/domain/homework.rs b/src/domain/homework.rs index 99a2831..a15aee0 100644 --- a/src/domain/homework.rs +++ b/src/domain/homework.rs @@ -13,7 +13,7 @@ //! same-course by the web layer, exactly like an exam question's subject. use crate::constant::{MAX_HOMEWORK_DESCRIPTION_LEN, MAX_HOMEWORK_TITLE_LEN}; -use crate::domain::course::CourseId; +use crate::domain::class_course::ClassCourseId; use crate::domain::monotonic_id::next_uuid; use crate::domain::subject::SubjectId; use crate::domain::timestamp::Timestamp; @@ -90,7 +90,7 @@ impl HomeworkDescription { #[derive(Debug, Clone, sqlx::FromRow)] pub struct Homework { pub(crate) id: HomeworkId, - pub(crate) course: CourseId, + pub(crate) class_course: ClassCourseId, pub(crate) subject: SubjectId, pub(crate) title: HomeworkTitle, pub(crate) description: Option, @@ -105,8 +105,8 @@ impl Homework { &self.id } - pub fn get_course(&self) -> &CourseId { - &self.course + pub fn get_class_course(&self) -> &ClassCourseId { + &self.class_course } pub fn get_subject(&self) -> &SubjectId { @@ -177,7 +177,7 @@ mod tests { let b = UserId::from_key(B); let with = |assigned| Homework { id: HomeworkId::generate(), - course: CourseId::from_key("0198f1a2-3b4c-7d5e-8f90-cccc3c4d5e6f"), + class_course: ClassCourseId::from_key("0198f1a2-3b4c-7d5e-8f90-cccc3c4d5e6f"), subject: SubjectId::from_key("0198f1a2-3b4c-7d5e-8f90-dddd4c4d5e6f"), title: HomeworkTitle::try_new("hw").unwrap(), description: None, diff --git a/src/domain/key.rs b/src/domain/key.rs index 634f64e..0f5c5be 100644 --- a/src/domain/key.rs +++ b/src/domain/key.rs @@ -40,7 +40,10 @@ mod tests { #[test] fn a_slot_key_never_collides_with_the_illustration() { assert_eq!(slot(QUESTION, None), format!("{QUESTION}_q")); - assert_eq!(slot(QUESTION, Some(STUDENT)), format!("{QUESTION}_{STUDENT}")); + assert_eq!( + slot(QUESTION, Some(STUDENT)), + format!("{QUESTION}_{STUDENT}") + ); // A choice id is a UUID, so it can never be the literal "q". assert_ne!(slot(QUESTION, Some(STUDENT)), slot(QUESTION, None)); } @@ -49,7 +52,10 @@ mod tests { fn the_first_sitting_stays_bare_and_later_ones_are_numbered() { // Byte-for-byte the shape the four sitting-keyed tables wrote before // this helper existed; a pre-history row is keyed by the bare pair. - assert_eq!(sitting(QUESTION, STUDENT, 1), format!("{QUESTION}_{STUDENT}")); + assert_eq!( + sitting(QUESTION, STUDENT, 1), + format!("{QUESTION}_{STUDENT}") + ); assert_eq!( sitting(QUESTION, STUDENT, 2), format!("{QUESTION}_{STUDENT}_2") diff --git a/src/domain/meal_ledger.rs b/src/domain/meal_ledger.rs index deedf09..71218ce 100644 --- a/src/domain/meal_ledger.rs +++ b/src/domain/meal_ledger.rs @@ -319,11 +319,8 @@ impl MealLedger { recorded_by: &UserId, ) -> Option<(MealLedgerId, MealLedger)> { let amount = booking.get_price_minor()?; - let charge = MealLedgerId::for_attempt( - &booking.id(), - booking.get_attempt(), - MealLedgerKind::Charge, - ); + let charge = + MealLedgerId::for_attempt(&booking.id(), booking.get_attempt(), MealLedgerKind::Charge); let line = MealLedger { id: MealLedgerId::for_attempt( &booking.id(), diff --git a/src/domain/message.rs b/src/domain/message.rs index d90e4b5..f2aef4f 100644 --- a/src/domain/message.rs +++ b/src/domain/message.rs @@ -2,8 +2,8 @@ use sqlx::Type; use uuid::Uuid; use crate::constant::{ - MAX_MESSAGE_BODY_LEN, MAX_MESSAGE_LABEL_LEN, MAX_MESSAGE_SUBJECT_LEN, - RECIPIENT_FOLDERS, SENDER_FOLDERS, + MAX_MESSAGE_BODY_LEN, MAX_MESSAGE_LABEL_LEN, MAX_MESSAGE_SUBJECT_LEN, RECIPIENT_FOLDERS, + SENDER_FOLDERS, }; use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; diff --git a/src/domain/mod.rs b/src/domain/mod.rs index 88ecd6d..e9da316 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -4,6 +4,7 @@ //! newtypes derive `sqlx::Type` so a column reads straight into the validated //! wrapper. +pub mod academic_year; pub mod answer_image; pub mod appointment; pub mod appointment_slot; @@ -21,6 +22,7 @@ pub mod class_course; pub mod class_group; pub mod class_member; pub mod course; +pub mod course_membership; pub mod course_note; pub mod course_note_file; pub mod course_session; @@ -50,6 +52,7 @@ pub mod note; pub mod note_file; pub mod parent_link; pub mod payment_ledger; +pub mod person; pub mod pomodoro; pub mod pool_question; pub mod pool_question_image; @@ -58,7 +61,6 @@ pub mod profile; pub mod question_image; pub mod rag_output; pub mod registration; -pub mod person; pub mod role; pub mod session; pub mod session_attendance; diff --git a/src/domain/payment_ledger.rs b/src/domain/payment_ledger.rs index 3087ade..8d6ad5a 100644 --- a/src/domain/payment_ledger.rs +++ b/src/domain/payment_ledger.rs @@ -332,7 +332,8 @@ mod tests { fn a_charge_key_is_the_plan_the_student_and_the_installment() { const PLAN: &str = "018f1a00-0000-7000-8000-000000000001"; const STU: &str = "018f1a00-0000-7000-8000-000000000002"; - let assignment = FeePlanAssignmentId::composite(&FeePlanId::from_key(PLAN), &UserId::from_key(STU)); + let assignment = + FeePlanAssignmentId::composite(&FeePlanId::from_key(PLAN), &UserId::from_key(STU)); let first = PaymentLedgerId::for_installment(&assignment, 1); assert_eq!(first.key(), format!("{PLAN}_{STU}_c1")); assert_eq!( diff --git a/src/domain/pool_question.rs b/src/domain/pool_question.rs index c603931..f8eb885 100644 --- a/src/domain/pool_question.rs +++ b/src/domain/pool_question.rs @@ -145,4 +145,3 @@ impl PoolQuestion { self.approved_by.as_ref() } } - diff --git a/src/domain/question_image.rs b/src/domain/question_image.rs index bbcd4db..8475d4f 100644 --- a/src/domain/question_image.rs +++ b/src/domain/question_image.rs @@ -40,7 +40,10 @@ impl QuestionImageId { /// The wire form, `None` spelled with the `"q"` sentinel — the same /// spelling the stored key uses. pub fn key(&self) -> String { - crate::domain::key::slot(&self.question.key(), self.slot.as_ref().map(|id| id.as_str())) + crate::domain::key::slot( + &self.question.key(), + self.slot.as_ref().map(|id| id.as_str()), + ) } pub fn question(&self) -> &ExamQuestionId { diff --git a/src/domain/role.rs b/src/domain/role.rs index 7e2663b..d050109 100644 --- a/src/domain/role.rs +++ b/src/domain/role.rs @@ -174,7 +174,14 @@ mod tests { // never drifts from `as_str` — the CHECK constraint and the filters // spell these same words. let mut buf = sqlx::postgres::PgArgumentBuffer::default(); - for role in [Role::Ai, Role::Parent, Role::Student, Role::Teacher, Role::Manager, Role::Admin] { + for role in [ + Role::Ai, + Role::Parent, + Role::Student, + Role::Teacher, + Role::Manager, + Role::Admin, + ] { buf.clear(); let _ = sqlx::Encode::::encode_by_ref(&role, &mut buf).unwrap(); assert_eq!(std::str::from_utf8(&buf).unwrap(), role.as_str()); diff --git a/src/domain/session_attendance.rs b/src/domain/session_attendance.rs index 2a6b94e..fe093a7 100644 --- a/src/domain/session_attendance.rs +++ b/src/domain/session_attendance.rs @@ -1,5 +1,5 @@ use crate::domain::attendance::AttendanceStatus; -use crate::domain::course::CourseId; +use crate::domain::class_course::ClassCourseId; use crate::domain::course_session::CourseSessionId; use crate::domain::user::UserId; @@ -63,13 +63,13 @@ pub(crate) fn counts_as_attended(status: &AttendanceStatus) -> bool { matches!(status.as_str(), "present" | "late") } -/// One person's roll-call state for one lesson. `course` is denormalized from -/// the session so the per-course attendance report is a single indexed query -/// (`WHERE app_user = $u`) with no join. +/// One person's roll-call state for one lesson. `class_course` is +/// denormalized from the session so the per-instance attendance report is a +/// single indexed query (`WHERE app_user = $u`) with no join. #[derive(Debug, Clone, sqlx::FromRow)] pub struct SessionAttendance { pub(crate) session: CourseSessionId, - pub(crate) course: CourseId, + pub(crate) class_course: ClassCourseId, #[sqlx(rename = "app_user")] pub(crate) user: UserId, pub(crate) status: AttendanceStatus, @@ -81,8 +81,8 @@ impl SessionAttendance { &self.session } - pub fn get_course(&self) -> &CourseId { - &self.course + pub fn get_class_course(&self) -> &ClassCourseId { + &self.class_course } pub fn get_user(&self) -> &UserId { diff --git a/src/domain/settings.rs b/src/domain/settings.rs index 102cb40..7b1ffe4 100644 --- a/src/domain/settings.rs +++ b/src/domain/settings.rs @@ -16,13 +16,13 @@ use sqlx::types::Json; use crate::constant::{ DEFAULT_ATTENDANCE_STATUSES, DEFAULT_CHATBOT_HISTORY_TURNS, DEFAULT_DIETARY_TAGS, - DEFAULT_EXAM_KINDS, DEFAULT_MAX_CHATBOT_MESSAGE_LEN, DEFAULT_MAX_CHATBOT_THREADS, - DEFAULT_MAX_FILE_BYTES, DEFAULT_MEAL_SLOTS, MAX_CHATBOT_HISTORY_TURNS, MAX_EXAM_KIND_WEIGHT, - MAX_GRADE_BANDS, MAX_GRADE_LABEL_LEN, MAX_MARK, MAX_MAX_CHATBOT_MESSAGE_LEN, - MAX_MAX_CHATBOT_THREADS, MAX_MAX_FILE_BYTES, MAX_MEAL_CANCEL_CUTOFF_MINUTES, - MAX_MEAL_SERVING_MINUTE, MAX_SETTINGS_ITEM_LEN, MAX_SETTINGS_LIST_LEN, - MIN_CHATBOT_HISTORY_TURNS, MIN_EXAM_KIND_WEIGHT, MIN_MARK, MIN_MAX_CHATBOT_MESSAGE_LEN, - MIN_MAX_CHATBOT_THREADS, MIN_MAX_FILE_BYTES, + DEFAULT_EXAM_KINDS, DEFAULT_GRADE_BANDS, DEFAULT_MAX_CHATBOT_MESSAGE_LEN, + DEFAULT_MAX_CHATBOT_THREADS, DEFAULT_MAX_FILE_BYTES, DEFAULT_MEAL_SLOTS, DEFAULT_TIMEZONE, + MAX_ABSENCE_DAYS, MAX_CHATBOT_HISTORY_TURNS, MAX_EXAM_KIND_WEIGHT, MAX_GRADE_BANDS, + MAX_GRADE_LABEL_LEN, MAX_MARK, MAX_MAX_CHATBOT_MESSAGE_LEN, MAX_MAX_CHATBOT_THREADS, + MAX_MAX_FILE_BYTES, MAX_MEAL_CANCEL_CUTOFF_MINUTES, MAX_MEAL_SERVING_MINUTE, + MAX_SETTINGS_ITEM_LEN, MAX_SETTINGS_LIST_LEN, MIN_CHATBOT_HISTORY_TURNS, MIN_EXAM_KIND_WEIGHT, + MIN_MARK, MIN_MAX_CHATBOT_MESSAGE_LEN, MIN_MAX_CHATBOT_THREADS, MIN_MAX_FILE_BYTES, TIMEZONES, }; use crate::domain::text_fold; use crate::error::ValidationError; @@ -215,6 +215,21 @@ pub struct Settings { /// for both deadlines; `None` = no cutoff at all, which is also what an /// unset column reads as. pub(crate) meal_cancel_cutoff_minutes: Option, + /// Öğretmen branş lists (D6): the school's subject specialisations a + /// teacher profile may name. `None`-while-unset; an empty list is legal + /// (a school that never configured branş). + pub(crate) branches: Option>>, + /// What an absence may be excused as (raporlu/izinli/…): the vocabulary + /// pointed at by an excused roll-call row. `None`-while-unset, like + /// `branches`. + pub(crate) excuse_kinds: Option>>, + /// Devamsızlık policy (D7): the per-dönem excused/unexcused day limits a + /// student may exceed. `None` = no limit configured. + pub(crate) max_excused_absent_days: Option, + pub(crate) max_unexcused_absent_days: Option, + /// The school's IANA timezone, used to bucket attendance days. `None` + /// reads as [`crate::constant::DEFAULT_TIMEZONE`]. + pub(crate) timezone: Option, } /// Everything [`Settings::try_new`] validates, in one struct — the knobs @@ -233,6 +248,13 @@ pub struct SettingsParams { pub dietary_tags: Vec, /// `None` = no booking/cancel cutoff. pub meal_cancel_cutoff_minutes: Option, + pub branches: Vec, + pub excuse_kinds: Vec, + /// `None` = no limit configured. + pub max_excused_absent_days: Option, + pub max_unexcused_absent_days: Option, + /// `None` = the deployment default timezone. + pub timezone: Option, } impl Settings { @@ -253,7 +275,14 @@ impl Settings { statuses.sort(); statuses }, - grade_bands: Json(Vec::new()), + grade_bands: Json( + DEFAULT_GRADE_BANDS + .map(|(min, label)| GradeBand { + min, + label: label.to_string(), + }) + .to_vec(), + ), max_file_bytes: None, chatbot_history_turns: None, max_chatbot_threads: None, @@ -261,6 +290,11 @@ impl Settings { meal_slots: None, dietary_tags: None, meal_cancel_cutoff_minutes: None, + branches: None, + excuse_kinds: None, + max_excused_absent_days: None, + max_unexcused_absent_days: None, + timezone: None, } } @@ -278,6 +312,11 @@ impl Settings { meal_slots: self.get_meal_slots(), dietary_tags: self.get_dietary_tags(), meal_cancel_cutoff_minutes: self.meal_cancel_cutoff_minutes, + branches: self.get_branches(), + excuse_kinds: self.get_excuse_kinds(), + max_excused_absent_days: self.max_excused_absent_days, + max_unexcused_absent_days: self.max_unexcused_absent_days, + timezone: self.timezone.clone(), } } @@ -301,6 +340,11 @@ impl Settings { meal_slots, dietary_tags, meal_cancel_cutoff_minutes, + branches, + excuse_kinds, + max_excused_absent_days, + max_unexcused_absent_days, + timezone, } = params; in_range( "max_file_bytes", @@ -395,6 +439,41 @@ impl Settings { )?; } + // Branş and excuse-kind lists follow the same rules as the kinds and + // statuses above, but empty is legal on both — a school that never + // configured either is not forced to invent one. + let branches = if branches.is_empty() { + branches + } else { + validate_list("branches", branches)? + }; + let excuse_kinds = if excuse_kinds.is_empty() { + excuse_kinds + } else { + validate_list("excuse_kinds", excuse_kinds)? + }; + for (field, value) in [ + ("max_excused_absent_days", max_excused_absent_days), + ("max_unexcused_absent_days", max_unexcused_absent_days), + ] { + if let Some(days) = value { + in_range( + field, + days, + 0..=MAX_ABSENCE_DAYS, + "must be between 0 and 365 days", + )?; + } + } + if let Some(tz) = timezone.as_deref() + && !TIMEZONES.contains(&tz) + { + return Err(ValidationError::Invalid { + field: "timezone", + reason: "is not a supported timezone (see GET /limits)", + }); + } + Ok(Self { exam_kinds: Json(exam_kinds), attendance_statuses, @@ -406,6 +485,11 @@ impl Settings { meal_slots: Some(Json(meal_slots)), dietary_tags: Some(dietary_tags), meal_cancel_cutoff_minutes, + branches: Some(Json(branches)), + excuse_kinds: Some(Json(excuse_kinds)), + max_excused_absent_days, + max_unexcused_absent_days, + timezone, }) } @@ -496,6 +580,39 @@ impl Settings { self.meal_cancel_cutoff_minutes } + /// The branş (subject specialisation) vocabulary a teacher profile may + /// name; empty while the school never configured one. + pub fn get_branches(&self) -> Vec { + self.branches + .as_ref() + .map(|list| list.0.clone()) + .unwrap_or_default() + } + + /// The excuse-kind vocabulary an excused absence may name; empty while the + /// school never configured one. + pub fn get_excuse_kinds(&self) -> Vec { + self.excuse_kinds + .as_ref() + .map(|list| list.0.clone()) + .unwrap_or_default() + } + + /// The per-dönem excused-absence day limit; `None` = no limit configured. + pub fn get_max_excused_absent_days(&self) -> Option { + self.max_excused_absent_days + } + + /// The per-dönem unexcused-absence day limit; `None` = no limit configured. + pub fn get_max_unexcused_absent_days(&self) -> Option { + self.max_unexcused_absent_days + } + + /// The school's IANA timezone; the deployment default while unset. + pub fn get_timezone(&self) -> &str { + self.timezone.as_deref().unwrap_or(DEFAULT_TIMEZONE) + } + /// The label of the band `mark` falls into: the band with the greatest /// `min` at or below it. `None` when no bands are configured. Takes an /// `f64` so course averages label the same way plain marks do. @@ -600,7 +717,10 @@ mod tests { let defaults = Settings::defaults(); let rebuilt = Settings::try_new(defaults.params()).unwrap(); assert_eq!(rebuilt.get_exam_kinds(), defaults.get_exam_kinds()); - assert!(defaults.get_grade_bands().is_empty()); + // The Türkiye 5-point scale ships by default, so a mark always labels. + assert_eq!(defaults.get_grade_bands().len(), DEFAULT_GRADE_BANDS.len()); + assert_eq!(defaults.grade_label(90.0), Some("5")); + assert_eq!(defaults.grade_label(0.0), Some("1")); } #[tokio::test] @@ -846,7 +966,12 @@ mod tests { assert_eq!(s.grade_label(84.9), Some("CC")); assert_eq!(s.grade_label(85.0), Some("AA")); assert_eq!(s.grade_label(100.0), Some("AA")); - // No bands configured → no label, never a panic. - assert_eq!(Settings::defaults().grade_label(90.0), None); + // With no bands configured there is no label, never a panic. + let bare = Settings::try_new(SettingsParams { + grade_bands: vec![], + ..params() + }) + .unwrap(); + assert_eq!(bare.grade_label(90.0), None); } } diff --git a/src/domain/solution.rs b/src/domain/solution.rs index 6d84d86..eec1cde 100644 --- a/src/domain/solution.rs +++ b/src/domain/solution.rs @@ -97,7 +97,6 @@ impl Solution { pub fn get_offered_at(&self) -> Timestamp { self.offered_at } - } #[cfg(test)] diff --git a/src/domain/term.rs b/src/domain/term.rs index 2657b26..e22fbc8 100644 --- a/src/domain/term.rs +++ b/src/domain/term.rs @@ -2,6 +2,7 @@ use sqlx::Type; use uuid::Uuid; use crate::constant::MAX_TERM_NAME_LEN; +use crate::domain::academic_year::AcademicYearId; use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; use crate::error::{AppError, ValidationError}; @@ -92,6 +93,8 @@ impl TermName { #[derive(Debug, Clone, sqlx::FromRow)] pub struct Term { pub(crate) id: TermId, + /// The academic year this dönem is a grading slice of. + pub(crate) year: AcademicYearId, pub(crate) name: TermName, pub(crate) starts_at: Timestamp, pub(crate) ends_at: Timestamp, @@ -106,6 +109,10 @@ impl Term { &self.id } + pub fn get_year(&self) -> &AcademicYearId { + &self.year + } + pub fn get_name(&self) -> &TermName { &self.name } diff --git a/src/domain/text_fold.rs b/src/domain/text_fold.rs index f100dbd..6bd13d8 100644 --- a/src/domain/text_fold.rs +++ b/src/domain/text_fold.rs @@ -118,8 +118,7 @@ mod tests { let sql = search_fold_sql("name"); for (from, to) in TEXT_FOLD_REPLACEMENTS { assert!( - sql.contains(&"replace(".to_string()) - && sql.contains(&format!("'{from}', '{to}'")), + sql.contains(&"replace(".to_string()) && sql.contains(&format!("'{from}', '{to}'")), "rule {from} -> {to} missing from the emitted expression" ); assert_eq!(search_fold(from), *to); diff --git a/src/domain/timestamp.rs b/src/domain/timestamp.rs index 3d19c68..ba6f76a 100644 --- a/src/domain/timestamp.rs +++ b/src/domain/timestamp.rs @@ -29,7 +29,18 @@ pub(crate) fn range_error() -> AppError { /// A unix-millisecond instant (UTC by construction). Stored as a `BIGINT`. /// Also serializes as its bare number: the fee plan's installments ride the /// row as JSON, and a due date must stay a plain millisecond count there too. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, sqlx::Type, serde::Serialize, serde::Deserialize)] +#[derive( + Debug, + Clone, + Copy, + PartialEq, + Eq, + PartialOrd, + Ord, + sqlx::Type, + serde::Serialize, + serde::Deserialize, +)] #[sqlx(transparent)] pub struct Timestamp(i64); @@ -172,7 +183,8 @@ mod tests { serde_json::to_value(Timestamp::from_millis(1_700_000_000_000)).unwrap(), serde_json::json!(1_700_000_000_000i64) ); - let back: Timestamp = serde_json::from_value(serde_json::json!(1_700_000_000_000i64)).unwrap(); + let back: Timestamp = + serde_json::from_value(serde_json::json!(1_700_000_000_000i64)).unwrap(); assert_eq!(back.as_millis(), 1_700_000_000_000); } } diff --git a/src/domain/user.rs b/src/domain/user.rs index 9fead91..4c6db21 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -233,6 +233,10 @@ pub struct User { // type and size live on the row. pub(crate) display_name: Option, pub(crate) bio: Option, + /// The staff member's branş (subject area), free text validated against + /// the school's own `Settings::get_branches()` list at the web layer — + /// optional like every other profile field, and clearable. + pub(crate) branch: Option, pub(crate) avatar_file: Option, pub(crate) avatar_content_type: Option, pub(crate) avatar_size: Option, @@ -262,6 +266,7 @@ impl User { palette_color: None, display_name: None, bio: None, + branch: None, avatar_file: None, avatar_content_type: None, avatar_size: None, @@ -323,6 +328,12 @@ impl User { self.bio.as_ref() } + /// The staff member's branş, as stored (free text; membership in the + /// school's list is the write path's check, not this read's). + pub fn get_branch(&self) -> Option<&str> { + self.branch.as_deref() + } + pub fn get_avatar_file(&self) -> Option<&str> { self.avatar_file.as_deref() } diff --git a/src/error.rs b/src/error.rs index f457e4c..eee334f 100644 --- a/src/error.rs +++ b/src/error.rs @@ -115,7 +115,6 @@ pub enum AppError { Internal(String), } - impl From for AppError { fn from(e: sqlx::Error) -> Self { match e { @@ -289,7 +288,6 @@ impl AppError { mod tests { use super::*; - /// The refusal a gated nest answers with. Both keys, and the `403` — a /// client switches on `module`, so neither may drift. #[tokio::test] @@ -327,7 +325,9 @@ mod tests { let io = std::io::Error::new(std::io::ErrorKind::ConnectionReset, "gone"); assert!(matches!(AppError::from(Error::Io(io)), AppError::DbTimeout)); // A query that found no row is the caller's 404, never a 500. - assert!(matches!(AppError::from(Error::RowNotFound), AppError::NotFound)); + assert!(matches!( + AppError::from(Error::RowNotFound), + AppError::NotFound + )); } - } diff --git a/src/lib.rs b/src/lib.rs index d9057d1..3c473b2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -61,24 +61,26 @@ use crate::web::module_gate::gate; (name = "messages", description = "One-to-one mail-style messages, upward only below staff: a student or parent writes to a teacher, manager or admin (parents included — messaging is the one place a parent writes) and never to another student or parent (`403`), while staff write to anyone, each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`archive`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread — with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"), (name = "appointments", description = "Teacher availability slots and the meetings booked on them. A teacher+ publishes windows (`POST /appointments/slots`), optionally repeating weekly up to an `until` date (at most 52 occurrences, all sharing a `series` id that deletes as one). A published window may not overlap another of the *same teacher's* (`409`): the check is half-open, so 10:00–10:30 and 10:30–11:00 are two slots and not a collision, and a weekly publish is all-or-nothing — one colliding occurrence refuses the whole series. Students and parents book one with a required reason — a parent books for themselves, this is the parent-teacher conference — and the request lands `pending`: publishing availability is not consent to a person and a topic. The teacher approves, rejects, or counter-proposes another time; a counter-proposal sends the booking back to `pending` and clears `decided_by`, and the requester either accepts it (approval at the new time) or declines, which cancels the booking. A window that has already opened is closed on every side (409): such a slot cannot be booked — and the bookable list is bounded on that same `starts_at`, so it never offers one — an underway time cannot be approved, accepted, or counter-proposed, and the requester may cancel — declining included, since a decline *is* a cancel — only until the meeting's effective window starts. Cancelling is the **requester's** route alone (`403` for anyone else, the slot's teacher and a manager/admin included, since the guard compares ids and not roles): a teacher ends a booking by rejecting it while it is `pending`, and an approved one by counter-proposing another time (back to `pending`) and then rejecting it, or simply by rescheduling. Both the reject and the cancel take an optional `reason`, and the row records who settled it (`decided_by`, `cancelled_by`) with that text (`reject_reason`, `cancel_reason`) — visible only to the requester and the slot's teacher, since that is who a booking is ever rendered to. One live booking holds a slot (rejecting or cancelling frees it), no approved meeting may overlap another for the teacher *or* the requester (409), and a slot with a live booking refuses deletion (409). A demotion below `teacher` withdraws that account's whole calendar in the role change's own transaction and cancels the live bookings on it (nothing else could reach them afterwards — the requester keeps a `cancelled` row naming who dropped it and why); a slot an older build stranded is inert instead: it drops out of the bookable list and booking one is refused. The bookable list carries each slot's teacher identity (id, username, display name) to every caller, parents included — deliberate, since a conference cannot be booked from an anonymous calendar; it is the staff directory for booking, narrowed to whoever published bookable time, and the direct people routes stay closed to a parent"), (name = "events", description = "Calendar events and attendance. An event's `audience` is its expected-attendee roster, not a visibility wall: everyone sees every event. Aim it at the whole school, one role, a course's enrollment, a class section's (şube) roster, or a hand-built registration list. Rosters resolve live, so role changes, (un)enrollments and class-roster changes move people in and out by themselves. Attendance: teacher+ marks people in the audience (students never mark, not even themselves), and the roster report joins the expected list with the marks to show who missed. Registration lists are filled seat by seat (teachers place students, staff place only themselves), optionally capped by `capacity`, and close once the event starts. `GET /events` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis) that keeps only upcoming/unfinished events and lists them soonest-first; without it the list stays newest-first"), - (name = "courses", description = "Courses — kind `course` (a regular taught course), `study` (etüt, a supervised study session), or `club` (kulüp, a student club; same behavior, different label) — optional enroll-time seat `capacity`, enrollment (students only), course exams, and course sessions. A course is run by its creator plus any teachers a manager assigned to it (`POST /courses/{id}/teachers`): assigned teachers manage everything inside the course but cannot delete it or change the assignment list. Both rights are re-checked against the caller's live role on every request: `creator` is a historical column no demotion sweeps, so an account that falls below `teacher` keeps neither management nor deletion of a course it made (the course stays reachable to its assigned teachers and to manager+), and the course drops out of their `/courses`, `/exams` and `/homework` catalogs unless they are enrolled in it. A session's `teacher` column carries the same floor: teaching a session grants neither its roll call nor a view of it once the account falls below `teacher`. A roster is also filled in bulk by attaching the course to a class (see `classes`), which writes the same ordinary enrollment rows one at a time. A course with anyone still enrolled refuses deletion (409) — empty the roster first"), - (name = "course-notes", description = "Notes a teacher attaches to a course — announcements, recaps, anything worth pinning to the class rather than to one student — with file attachments, mirroring the personal `notes` stack. Writing (create, edit, delete, upload, delete a file) requires teacher+ and management rights over the course (its creator, an assigned teacher, or a manager/admin); reading (`GET /course-notes/{id}`, listing, downloading) is open to anyone who can view the course — its enrolled users plus whoever can manage it. `GET /course-notes` requires `?course=` and lists that course's notes only, newest first. At most 10 files per note, each at most the school's `max_file_bytes`. `GET /course-notes/{id}/rag` serves what the backend's `rag.index` AI service produced for a note — an index or summary, stored verbatim and unread by this side — to anyone who can view the course; `DELETE /course-notes/{id}/rag/{output_id}` drops one, and needs the same management rights as any other write. Outputs are derived data: deleting one does not suppress anything, and the next edit to the note or its files may regenerate it."), - (name = "classes", description = "Class sections (şube): a named set of students the school moves as one. A class is bulk enrollment, not a second kind of membership — adding a student enrolls them into every course the class carries, attaching a course enrolls the whole roster into it, and the rows written are ordinary enrollments, each tagged with the class that pumped it (a row with no such tag was placed individually). A course with too few seats takes none of the class — the whole call is a 409 naming the course that ran out, and not one of the seats claimed earlier in the same run is kept — and a student already enrolled by hand keeps their own row (never adopted, never swept). Removing a member or detaching a course takes back only the rows that class pumped, and even then repairs before it deletes: a row a *second* class still claims (it holds the same student and the same course) is re-tagged to that class instead of being dropped, so nobody loses a seat someone is still responsible for. Unenrolling a pumped student by hand is allowed and permanent — the class does not put them back; staff re-enroll them or detach and re-attach the course. A class may link an academic term (which then refuses deletion while it does), and a class still holding students or courses refuses deletion itself (409). A class may also name a homeroom teacher (sınıf öğretmeni) with `teacher_id` — any teacher+ account, a pure label that grants nothing, cleared on every class it held the moment that account is demoted below `teacher`. The class itself and its roster are manager+, every read is teacher+, and attaching or detaching a course takes management rights on *that course*, since it writes that course's roster. Two reads sit outside that bar so a student can learn their own section: `GET /classes/me` (any authenticated role — staff, never members, get an empty page) and `GET /classes/user/{user}` (teacher+, or a parent linked to that student); both hide the class's `creator` (always a manager or admin) from a caller below teacher+, since the office's account names are otherwise unreachable at that level. Naming a homeroom teacher who is demoted while the request runs is a `409`: the assignment is taken back, and a create is rolled back whole. A grade may also carry a **blueprint** (`/classes/blueprints`): the list of courses every section at that grade takes. It reaches sections in both directions — creating or editing one retro-pumps every class already at the grade, and a class created afterwards at a blueprinted grade is stocked from it by `POST /classes` itself, whose `201` therefore answers `{class, skipped, stocked_from}` (`stocked_from` is the grade label of the template that stocked it, `null` when none covers the grade, which is what tells that apart from a template that applied cleanly; a stocking that could not be carried out reads `null` too, and the retry for both is the idempotent `POST /classes/{id}/blueprint`). Pumping is best-effort — a section that cannot take a course (it is at its course ceiling, or the course has no free seat for the whole section) is skipped and returned in `skipped`, while every other section is still stocked, so a blueprint edit can leave a deliberately partial state. The same body carries `matched`, the number of sections the pump actually reached: a grade label is free text matched exactly, so `\"9 \"` and `\"9-A\"` are not `\"9\"`, and `matched: 0` with an empty `skipped` is a saved template that stocked nothing rather than one that stocked everything. `GET /classes?grade=