diff --git a/.sqlx/query-01137f478e8052ac393515c5a26cf1ef16e3209150b3d15d94d65c9b2ecb2824.json b/.sqlx/query-01137f478e8052ac393515c5a26cf1ef16e3209150b3d15d94d65c9b2ecb2824.json deleted file mode 100644 index 0dfec59..0000000 --- a/.sqlx/query-01137f478e8052ac393515c5a26cf1ef16e3209150b3d15d94d65c9b2ecb2824.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO person_school (person, school) VALUES ($1, $2) ON CONFLICT DO NOTHING", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Uuid", - "Text" - ] - }, - "nullable": [] - }, - "hash": "01137f478e8052ac393515c5a26cf1ef16e3209150b3d15d94d65c9b2ecb2824" -} diff --git a/.sqlx/query-0a8892a6a3eb57b0e02e4340abba3c6241102483de35c59e31fbb351bc677202.json b/.sqlx/query-0a8892a6a3eb57b0e02e4340abba3c6241102483de35c59e31fbb351bc677202.json new file mode 100644 index 0000000..f1cbaa5 --- /dev/null +++ b/.sqlx/query-0a8892a6a3eb57b0e02e4340abba3c6241102483de35c59e31fbb351bc677202.json @@ -0,0 +1,64 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT solution AS \"solution: SolutionId\", file,\n content_type AS \"content_type: FileContentType\", size\n FROM solution_image WHERE solution = ANY($1)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "solution: SolutionId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "solution_image", + "name": "solution" + } + } + }, + { + "ordinal": 1, + "name": "file", + "type_info": "Text", + "origin": { + "Table": { + "table": "solution_image", + "name": "file" + } + } + }, + { + "ordinal": 2, + "name": "content_type: FileContentType", + "type_info": "Text", + "origin": { + "Table": { + "table": "solution_image", + "name": "content_type" + } + } + }, + { + "ordinal": 3, + "name": "size", + "type_info": "Int8", + "origin": { + "Table": { + "table": "solution_image", + "name": "size" + } + } + } + ], + "parameters": { + "Left": [ + "UuidArray" + ] + }, + "nullable": [ + false, + false, + false, + false + ] + }, + "hash": "0a8892a6a3eb57b0e02e4340abba3c6241102483de35c59e31fbb351bc677202" +} diff --git a/.sqlx/query-0bbcdb6f1b8b0c7d518b5e32c2b3aad7cbdab3e8e972c619c0cb05bfc2be7cac.json b/.sqlx/query-0bbcdb6f1b8b0c7d518b5e32c2b3aad7cbdab3e8e972c619c0cb05bfc2be7cac.json new file mode 100644 index 0000000..5363d58 --- /dev/null +++ b/.sqlx/query-0bbcdb6f1b8b0c7d518b5e32c2b3aad7cbdab3e8e972c619c0cb05bfc2be7cac.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM solution_image WHERE solution = $1 RETURNING file", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "file", + "type_info": "Text", + "origin": { + "Table": { + "table": "solution_image", + "name": "file" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "0bbcdb6f1b8b0c7d518b5e32c2b3aad7cbdab3e8e972c619c0cb05bfc2be7cac" +} diff --git a/.sqlx/query-40a7f3cec635eeb143336c87ea38028e937608109e9f2bd583084a5d8febf6a4.json b/.sqlx/query-0f4855352631239aaf9aac48ad4510afd1081f61c523106c60c62ae3c7ad9944.json similarity index 79% rename from .sqlx/query-40a7f3cec635eeb143336c87ea38028e937608109e9f2bd583084a5d8febf6a4.json rename to .sqlx/query-0f4855352631239aaf9aac48ad4510afd1081f61c523106c60c62ae3c7ad9944.json index e781b45..381fcee 100644 --- a/.sqlx/query-40a7f3cec635eeb143336c87ea38028e937608109e9f2bd583084a5d8febf6a4.json +++ b/.sqlx/query-0f4855352631239aaf9aac48ad4510afd1081f61c523106c60c62ae3c7ad9944.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n password_hash AS \"password_hash: PasswordHash\",\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 avatar_size\n FROM app_user WHERE id = ANY($1)", "describe": { "columns": [ { @@ -27,12 +27,12 @@ }, { "ordinal": 2, - "name": "password_hash: PasswordHash", - "type_info": "Text", + "name": "person: PersonId", + "type_info": "Uuid", "origin": { "Table": { "table": "app_user", - "name": "password_hash" + "name": "person" } } }, @@ -199,7 +199,7 @@ "nullable": [ false, false, - false, + true, false, true, true, @@ -216,5 +216,5 @@ true ] }, - "hash": "40a7f3cec635eeb143336c87ea38028e937608109e9f2bd583084a5d8febf6a4" + "hash": "0f4855352631239aaf9aac48ad4510afd1081f61c523106c60c62ae3c7ad9944" } diff --git a/.sqlx/query-2c7c0898e7f4d8131d5683d70e718ae35e1969cbe33e21781907c572bf2a66e3.json b/.sqlx/query-110d348f669e2895d2537a67a3a5babd214d94d7d0c879a858311abc04da9560.json similarity index 82% rename from .sqlx/query-2c7c0898e7f4d8131d5683d70e718ae35e1969cbe33e21781907c572bf2a66e3.json rename to .sqlx/query-110d348f669e2895d2537a67a3a5babd214d94d7d0c879a858311abc04da9560.json index 75b7cbf..110eea0 100644 --- a/.sqlx/query-2c7c0898e7f4d8131d5683d70e718ae35e1969cbe33e21781907c572bf2a66e3.json +++ b/.sqlx/query-110d348f669e2895d2537a67a3a5babd214d94d7d0c879a858311abc04da9560.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "WITH person AS (\n -- The lock handshake comes FIRST: FOR NO KEY UPDATE waits out a\n -- racing demotion and re-checks the role against the committed\n -- row. A data-modifying CTE executes even when the INSERT below\n -- matches nothing, so the bump must depend on this CTE's result —\n -- the EXISTS reference in `seat` forces that order.\n SELECT 1 FROM app_user WHERE id = $2 AND role IS DISTINCT FROM 'parent'\n FOR NO KEY UPDATE),\n seat AS (\n UPDATE event SET registration_count = registration_count + 1\n WHERE id = $1\n AND (audience_capacity IS NULL OR registration_count < audience_capacity)\n AND EXISTS (SELECT 1 FROM person)\n RETURNING 1)\n INSERT INTO registration (event, app_user, registered_by)\n SELECT $1, $2, $3\n WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING event AS \"event: EventId\", app_user AS \"user: UserId\", registered_by AS \"registered_by: UserId\"", + "query": "WITH person AS (\n -- The lock handshake comes FIRST: FOR NO KEY UPDATE waits out a\n -- racing demotion and re-checks the role against the committed\n -- row. A data-modifying CTE executes even when the INSERT below\n -- matches nothing, so the bump must depend on this CTE's result —\n -- the EXISTS reference in `seat` forces that order.\n SELECT 1 FROM app_user WHERE id = $2 AND role IS DISTINCT FROM 'parent'\n FOR NO KEY UPDATE),\n seat AS (\n UPDATE event SET registration_count = registration_count + 1\n WHERE id = $1\n AND (audience_capacity IS NULL OR registration_count < audience_capacity)\n AND EXISTS (SELECT 1 FROM person)\n RETURNING 1)\n INSERT INTO registration (event, app_user, registered_by, created_at)\n SELECT $1, $2, $3, $4\n WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING event AS \"event: EventId\", app_user AS \"user: UserId\", registered_by AS \"registered_by: UserId\"", "describe": { "columns": [ { @@ -41,7 +41,8 @@ "Left": [ "Uuid", "Uuid", - "Uuid" + "Uuid", + "Int8" ] }, "nullable": [ @@ -50,5 +51,5 @@ false ] }, - "hash": "2c7c0898e7f4d8131d5683d70e718ae35e1969cbe33e21781907c572bf2a66e3" + "hash": "110d348f669e2895d2537a67a3a5babd214d94d7d0c879a858311abc04da9560" } diff --git a/.sqlx/query-ba87bfbbbf6cdca3ac0d1544c86306944919cf6f4026744eef245e8fbd5d982a.json b/.sqlx/query-1426cb1fc87d2e06ea919254bac9cb3403d07318c2bb43388a8dca245a952fc8.json similarity index 78% rename from .sqlx/query-ba87bfbbbf6cdca3ac0d1544c86306944919cf6f4026744eef245e8fbd5d982a.json rename to .sqlx/query-1426cb1fc87d2e06ea919254bac9cb3403d07318c2bb43388a8dca245a952fc8.json index 74ca9f2..a71595d 100644 --- a/.sqlx/query-ba87bfbbbf6cdca3ac0d1544c86306944919cf6f4026744eef245e8fbd5d982a.json +++ b/.sqlx/query-1426cb1fc87d2e06ea919254bac9cb3403d07318c2bb43388a8dca245a952fc8.json @@ -1,6 +1,6 @@ { "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)\n SELECT $1, $3, $4, NULL 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 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\"", "describe": { "columns": [ { @@ -53,7 +53,8 @@ "Uuid", "Int8", "Uuid", - "Uuid" + "Uuid", + "Int8" ] }, "nullable": [ @@ -63,5 +64,5 @@ true ] }, - "hash": "ba87bfbbbf6cdca3ac0d1544c86306944919cf6f4026744eef245e8fbd5d982a" + "hash": "1426cb1fc87d2e06ea919254bac9cb3403d07318c2bb43388a8dca245a952fc8" } diff --git a/.sqlx/query-14db52e674777efa73c824f94af93ab2d197bdbccf8d94beea4943d9a3b17f90.json b/.sqlx/query-14db52e674777efa73c824f94af93ab2d197bdbccf8d94beea4943d9a3b17f90.json deleted file mode 100644 index 56f3552..0000000 --- a/.sqlx/query-14db52e674777efa73c824f94af93ab2d197bdbccf8d94beea4943d9a3b17f90.json +++ /dev/null @@ -1,221 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE app_user SET password_hash = $2 WHERE id = $1\n RETURNING id AS \"id: UserId\",\n username AS \"username: Username\",\n password_hash AS \"password_hash: PasswordHash\",\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", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "id: UserId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "app_user", - "name": "id" - } - } - }, - { - "ordinal": 1, - "name": "username: Username", - "type_info": "Text", - "origin": { - "Table": { - "table": "app_user", - "name": "username" - } - } - }, - { - "ordinal": 2, - "name": "password_hash: PasswordHash", - "type_info": "Text", - "origin": { - "Table": { - "table": "app_user", - "name": "password_hash" - } - } - }, - { - "ordinal": 3, - "name": "role: Role", - "type_info": "Text", - "origin": { - "Table": { - "table": "app_user", - "name": "role" - } - } - }, - { - "ordinal": 4, - "name": "name: PersonName", - "type_info": "Text", - "origin": { - "Table": { - "table": "app_user", - "name": "name" - } - } - }, - { - "ordinal": 5, - "name": "surname: PersonName", - "type_info": "Text", - "origin": { - "Table": { - "table": "app_user", - "name": "surname" - } - } - }, - { - "ordinal": 6, - "name": "email: Email", - "type_info": "Text", - "origin": { - "Table": { - "table": "app_user", - "name": "email" - } - } - }, - { - "ordinal": 7, - "name": "phone: Phone", - "type_info": "Text", - "origin": { - "Table": { - "table": "app_user", - "name": "phone" - } - } - }, - { - "ordinal": 8, - "name": "birth_date: BirthDate", - "type_info": "Text", - "origin": { - "Table": { - "table": "app_user", - "name": "birth_date" - } - } - }, - { - "ordinal": 9, - "name": "theme: Theme", - "type_info": "Text", - "origin": { - "Table": { - "table": "app_user", - "name": "theme" - } - } - }, - { - "ordinal": 10, - "name": "language: Language", - "type_info": "Text", - "origin": { - "Table": { - "table": "app_user", - "name": "language" - } - } - }, - { - "ordinal": 11, - "name": "palette_color: PaletteColor", - "type_info": "Text", - "origin": { - "Table": { - "table": "app_user", - "name": "palette_color" - } - } - }, - { - "ordinal": 12, - "name": "display_name: DisplayName", - "type_info": "Text", - "origin": { - "Table": { - "table": "app_user", - "name": "display_name" - } - } - }, - { - "ordinal": 13, - "name": "bio: Bio", - "type_info": "Text", - "origin": { - "Table": { - "table": "app_user", - "name": "bio" - } - } - }, - { - "ordinal": 14, - "name": "avatar_file", - "type_info": "Text", - "origin": { - "Table": { - "table": "app_user", - "name": "avatar_file" - } - } - }, - { - "ordinal": 15, - "name": "avatar_content_type: FileContentType", - "type_info": "Text", - "origin": { - "Table": { - "table": "app_user", - "name": "avatar_content_type" - } - } - }, - { - "ordinal": 16, - "name": "avatar_size", - "type_info": "Int8", - "origin": { - "Table": { - "table": "app_user", - "name": "avatar_size" - } - } - } - ], - "parameters": { - "Left": [ - "Uuid", - "Text" - ] - }, - "nullable": [ - false, - false, - false, - false, - true, - true, - true, - true, - true, - true, - true, - true, - true, - true, - true, - true, - true - ] - }, - "hash": "14db52e674777efa73c824f94af93ab2d197bdbccf8d94beea4943d9a3b17f90" -} diff --git a/.sqlx/query-fc15e864cec24208e364d047c7c7fce91281a080da50c2c509cbb6470e7c212a.json b/.sqlx/query-15e1d6d5b56bbdbc817402c8b92202dc705ca27d14da7016adb201145c2229b0.json similarity index 79% rename from .sqlx/query-fc15e864cec24208e364d047c7c7fce91281a080da50c2c509cbb6470e7c212a.json rename to .sqlx/query-15e1d6d5b56bbdbc817402c8b92202dc705ca27d14da7016adb201145c2229b0.json index 2731f84..84be0ef 100644 --- a/.sqlx/query-fc15e864cec24208e364d047c7c7fce91281a080da50c2c509cbb6470e7c212a.json +++ b/.sqlx/query-15e1d6d5b56bbdbc817402c8b92202dc705ca27d14da7016adb201145c2229b0.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n password_hash AS \"password_hash: PasswordHash\",\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 avatar_size\n FROM app_user WHERE username = $1", "describe": { "columns": [ { @@ -27,12 +27,12 @@ }, { "ordinal": 2, - "name": "password_hash: PasswordHash", - "type_info": "Text", + "name": "person: PersonId", + "type_info": "Uuid", "origin": { "Table": { "table": "app_user", - "name": "password_hash" + "name": "person" } } }, @@ -199,7 +199,7 @@ "nullable": [ false, false, - false, + true, false, true, true, @@ -216,5 +216,5 @@ true ] }, - "hash": "fc15e864cec24208e364d047c7c7fce91281a080da50c2c509cbb6470e7c212a" + "hash": "15e1d6d5b56bbdbc817402c8b92202dc705ca27d14da7016adb201145c2229b0" } diff --git a/.sqlx/query-f9a7f1eba3e17f7aec59c1c21d9e0335d0f648a8f8c8b25f27445161b131712b.json b/.sqlx/query-201a66d66d53b7e6aa7b882bf250bad3806f7d066c09c241a2c3cbc28d58a0e5.json similarity index 64% rename from .sqlx/query-f9a7f1eba3e17f7aec59c1c21d9e0335d0f648a8f8c8b25f27445161b131712b.json rename to .sqlx/query-201a66d66d53b7e6aa7b882bf250bad3806f7d066c09c241a2c3cbc28d58a0e5.json index 352b500..1428ef4 100644 --- a/.sqlx/query-f9a7f1eba3e17f7aec59c1c21d9e0335d0f648a8f8c8b25f27445161b131712b.json +++ b/.sqlx/query-201a66d66d53b7e6aa7b882bf250bad3806f7d066c09c241a2c3cbc28d58a0e5.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO solution (id, question, author, body, offered_at)\n VALUES ($1, $2, $3, $4, $5)\n RETURNING id AS \"id: SolutionId\", question AS \"question: PoolQuestionId\",\n author AS \"author: UserId\", body AS \"body: SolutionBody\",\n offered_at AS \"offered_at: Timestamp\", image_file,\n image_content_type AS \"image_content_type: FileContentType\",\n image_size", + "query": "INSERT INTO solution (id, question, author, body, offered_at)\n VALUES ($1, $2, $3, $4, $5)\n RETURNING id AS \"id: SolutionId\", question AS \"question: PoolQuestionId\",\n author AS \"author: UserId\", body AS \"body: SolutionBody\",\n offered_at AS \"offered_at: Timestamp\"", "describe": { "columns": [ { @@ -57,39 +57,6 @@ "name": "offered_at" } } - }, - { - "ordinal": 5, - "name": "image_file", - "type_info": "Text", - "origin": { - "Table": { - "table": "solution", - "name": "image_file" - } - } - }, - { - "ordinal": 6, - "name": "image_content_type: FileContentType", - "type_info": "Text", - "origin": { - "Table": { - "table": "solution", - "name": "image_content_type" - } - } - }, - { - "ordinal": 7, - "name": "image_size", - "type_info": "Int8", - "origin": { - "Table": { - "table": "solution", - "name": "image_size" - } - } } ], "parameters": { @@ -106,11 +73,8 @@ false, false, false, - false, - true, - true, - true + false ] }, - "hash": "f9a7f1eba3e17f7aec59c1c21d9e0335d0f648a8f8c8b25f27445161b131712b" + "hash": "201a66d66d53b7e6aa7b882bf250bad3806f7d066c09c241a2c3cbc28d58a0e5" } diff --git a/.sqlx/query-8c139417415e49694c492d70fcf612de89bc3ef5dc2611d7a4cde2bf0c01d430.json b/.sqlx/query-21038488baf4bb7c99de9f75dcf11b6183596b77bb5f3eadca699acc37016367.json similarity index 73% rename from .sqlx/query-8c139417415e49694c492d70fcf612de89bc3ef5dc2611d7a4cde2bf0c01d430.json rename to .sqlx/query-21038488baf4bb7c99de9f75dcf11b6183596b77bb5f3eadca699acc37016367.json index 63551b7..ac1117d 100644 --- a/.sqlx/query-8c139417415e49694c492d70fcf612de89bc3ef5dc2611d7a4cde2bf0c01d430.json +++ b/.sqlx/query-21038488baf4bb7c99de9f75dcf11b6183596b77bb5f3eadca699acc37016367.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO exam_result (exam, app_user, seq, mark, graded_by)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (exam, app_user, seq) DO UPDATE\n SET mark = EXCLUDED.mark, graded_by = EXCLUDED.graded_by\n RETURNING exam AS \"exam: ExamId\", app_user AS \"user: UserId\", seq,\n mark AS \"mark: Mark\", graded_by AS \"graded_by: UserId\"", + "query": "INSERT INTO exam_result (exam, app_user, seq, mark, graded_by, graded_at)\n VALUES ($1, $2, $3, $4, $5, $6)\n ON CONFLICT (exam, app_user, seq) DO UPDATE\n SET mark = EXCLUDED.mark, graded_by = EXCLUDED.graded_by,\n graded_at = EXCLUDED.graded_at\n RETURNING exam AS \"exam: ExamId\", app_user AS \"user: UserId\", seq,\n mark AS \"mark: Mark\", graded_by AS \"graded_by: UserId\"", "describe": { "columns": [ { @@ -65,7 +65,8 @@ "Uuid", "Int8", "Int8", - "Uuid" + "Uuid", + "Int8" ] }, "nullable": [ @@ -76,5 +77,5 @@ false ] }, - "hash": "8c139417415e49694c492d70fcf612de89bc3ef5dc2611d7a4cde2bf0c01d430" + "hash": "21038488baf4bb7c99de9f75dcf11b6183596b77bb5f3eadca699acc37016367" } diff --git a/.sqlx/query-eab35aebb71eda25b39cb97d4437f9fd1b3cc602ef0403cae3f0eef284ad5f98.json b/.sqlx/query-23a1369a6a30b803cafaaa75e7203ace62afc4d3bbc55cdec686920ac0fdd570.json similarity index 64% rename from .sqlx/query-eab35aebb71eda25b39cb97d4437f9fd1b3cc602ef0403cae3f0eef284ad5f98.json rename to .sqlx/query-23a1369a6a30b803cafaaa75e7203ace62afc4d3bbc55cdec686920ac0fdd570.json index f1735e8..7a267ea 100644 --- a/.sqlx/query-eab35aebb71eda25b39cb97d4437f9fd1b3cc602ef0403cae3f0eef284ad5f98.json +++ b/.sqlx/query-23a1369a6a30b803cafaaa75e7203ace62afc4d3bbc55cdec686920ac0fdd570.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "DELETE FROM class_course WHERE class = $1 AND course = $2 AND source = $3\n RETURNING 1 AS \"one\"", + "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": [ { @@ -21,5 +21,5 @@ null ] }, - "hash": "eab35aebb71eda25b39cb97d4437f9fd1b3cc602ef0403cae3f0eef284ad5f98" + "hash": "23a1369a6a30b803cafaaa75e7203ace62afc4d3bbc55cdec686920ac0fdd570" } diff --git a/.sqlx/query-24753c350019e38e0d71e5ec3677999f61acb40ca3530a6f187acbec4bafe95c.json b/.sqlx/query-24753c350019e38e0d71e5ec3677999f61acb40ca3530a6f187acbec4bafe95c.json new file mode 100644 index 0000000..dda00eb --- /dev/null +++ b/.sqlx/query-24753c350019e38e0d71e5ec3677999f61acb40ca3530a6f187acbec4bafe95c.json @@ -0,0 +1,17 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO person (id, username, password_hash, created_at) VALUES ($1, $2, $3, $4)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Text", + "Text", + "Int8" + ] + }, + "nullable": [] + }, + "hash": "24753c350019e38e0d71e5ec3677999f61acb40ca3530a6f187acbec4bafe95c" +} diff --git a/.sqlx/query-2d99e80f8fedbef5029e37e426f4c95766c83f19c4bc801d6f99baee11696569.json b/.sqlx/query-2d99e80f8fedbef5029e37e426f4c95766c83f19c4bc801d6f99baee11696569.json deleted file mode 100644 index 1005bd6..0000000 --- a/.sqlx/query-2d99e80f8fedbef5029e37e426f4c95766c83f19c4bc801d6f99baee11696569.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT 1 AS \"one\" FROM class_blueprint WHERE grade = $1 FOR KEY SHARE", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "one", - "type_info": "Int4", - "origin": "Expression" - } - ], - "parameters": { - "Left": [ - "Text" - ] - }, - "nullable": [ - null - ] - }, - "hash": "2d99e80f8fedbef5029e37e426f4c95766c83f19c4bc801d6f99baee11696569" -} diff --git a/.sqlx/query-0e07d306c0ad413d269e73f90826d694154ba0e78011b42e277556069db1e1c2.json b/.sqlx/query-3b7d8a00a0bba2941ab58aa40a4f4c53d14796284b8a2eafb482d1fac06966c5.json similarity index 67% rename from .sqlx/query-0e07d306c0ad413d269e73f90826d694154ba0e78011b42e277556069db1e1c2.json rename to .sqlx/query-3b7d8a00a0bba2941ab58aa40a4f4c53d14796284b8a2eafb482d1fac06966c5.json index d6dbd96..304e034 100644 --- a/.sqlx/query-0e07d306c0ad413d269e73f90826d694154ba0e78011b42e277556069db1e1c2.json +++ b/.sqlx/query-3b7d8a00a0bba2941ab58aa40a4f4c53d14796284b8a2eafb482d1fac06966c5.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: PoolQuestionId\", asker AS \"asker: UserId\",\n title AS \"title: PoolQuestionTitle\", body AS \"body: PoolQuestionBody\",\n status, asked_at AS \"asked_at: Timestamp\",\n approved_by AS \"approved_by: UserId\", image_file,\n image_content_type AS \"image_content_type: FileContentType\",\n image_size\n FROM pool_question WHERE id = $1", + "query": "SELECT id AS \"id: PoolQuestionId\", asker AS \"asker: UserId\",\n title AS \"title: PoolQuestionTitle\", body AS \"body: PoolQuestionBody\",\n status, asked_at AS \"asked_at: Timestamp\",\n approved_by AS \"approved_by: UserId\"\n FROM pool_question\n WHERE status = $1 OR asker = $2\n ORDER BY asked_at DESC, id DESC", "describe": { "columns": [ { @@ -79,43 +79,11 @@ "name": "approved_by" } } - }, - { - "ordinal": 7, - "name": "image_file", - "type_info": "Text", - "origin": { - "Table": { - "table": "pool_question", - "name": "image_file" - } - } - }, - { - "ordinal": 8, - "name": "image_content_type: FileContentType", - "type_info": "Text", - "origin": { - "Table": { - "table": "pool_question", - "name": "image_content_type" - } - } - }, - { - "ordinal": 9, - "name": "image_size", - "type_info": "Int8", - "origin": { - "Table": { - "table": "pool_question", - "name": "image_size" - } - } } ], "parameters": { "Left": [ + "Text", "Uuid" ] }, @@ -126,11 +94,8 @@ false, false, false, - true, - true, - true, true ] }, - "hash": "0e07d306c0ad413d269e73f90826d694154ba0e78011b42e277556069db1e1c2" + "hash": "3b7d8a00a0bba2941ab58aa40a4f4c53d14796284b8a2eafb482d1fac06966c5" } diff --git a/.sqlx/query-0f9e44ea5d44c057ea95a3dd7006e5e133f6df1a0f284e41bc64ba74b3bf348b.json b/.sqlx/query-3d60209700585decbd009cd8d340e8a90d157e48fe791d84c45ed9c41ef8e745.json similarity index 70% rename from .sqlx/query-0f9e44ea5d44c057ea95a3dd7006e5e133f6df1a0f284e41bc64ba74b3bf348b.json rename to .sqlx/query-3d60209700585decbd009cd8d340e8a90d157e48fe791d84c45ed9c41ef8e745.json index cc51963..c04e258 100644 --- a/.sqlx/query-0f9e44ea5d44c057ea95a3dd7006e5e133f6df1a0f284e41bc64ba74b3bf348b.json +++ b/.sqlx/query-3d60209700585decbd009cd8d340e8a90d157e48fe791d84c45ed9c41ef8e745.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO pool_question (id, asker, title, body, status, asked_at)\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING id AS \"id: PoolQuestionId\", asker AS \"asker: UserId\",\n title AS \"title: PoolQuestionTitle\", body AS \"body: PoolQuestionBody\",\n status, asked_at AS \"asked_at: Timestamp\",\n approved_by AS \"approved_by: UserId\", image_file,\n image_content_type AS \"image_content_type: FileContentType\",\n image_size", + "query": "INSERT INTO pool_question (id, asker, title, body, status, asked_at)\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING id AS \"id: PoolQuestionId\", asker AS \"asker: UserId\",\n title AS \"title: PoolQuestionTitle\", body AS \"body: PoolQuestionBody\",\n status, asked_at AS \"asked_at: Timestamp\",\n approved_by AS \"approved_by: UserId\"", "describe": { "columns": [ { @@ -79,39 +79,6 @@ "name": "approved_by" } } - }, - { - "ordinal": 7, - "name": "image_file", - "type_info": "Text", - "origin": { - "Table": { - "table": "pool_question", - "name": "image_file" - } - } - }, - { - "ordinal": 8, - "name": "image_content_type: FileContentType", - "type_info": "Text", - "origin": { - "Table": { - "table": "pool_question", - "name": "image_content_type" - } - } - }, - { - "ordinal": 9, - "name": "image_size", - "type_info": "Int8", - "origin": { - "Table": { - "table": "pool_question", - "name": "image_size" - } - } } ], "parameters": { @@ -131,11 +98,8 @@ false, false, false, - true, - true, - true, true ] }, - "hash": "0f9e44ea5d44c057ea95a3dd7006e5e133f6df1a0f284e41bc64ba74b3bf348b" + "hash": "3d60209700585decbd009cd8d340e8a90d157e48fe791d84c45ed9c41ef8e745" } diff --git a/.sqlx/query-3e61b9438e821420c2a19b4788c2a6697d4b0f89f6ea247b40adb7ef3bfadc9b.json b/.sqlx/query-3e61b9438e821420c2a19b4788c2a6697d4b0f89f6ea247b40adb7ef3bfadc9b.json new file mode 100644 index 0000000..970ec22 --- /dev/null +++ b/.sqlx/query-3e61b9438e821420c2a19b4788c2a6697d4b0f89f6ea247b40adb7ef3bfadc9b.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT file FROM solution_image WHERE solution = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "file", + "type_info": "Text", + "origin": { + "Table": { + "table": "solution_image", + "name": "file" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "3e61b9438e821420c2a19b4788c2a6697d4b0f89f6ea247b40adb7ef3bfadc9b" +} diff --git a/.sqlx/query-447b194a72b03ed8f6ea2be70808c09778fb771a4d6a497dfc572eeec640a914.json b/.sqlx/query-447b194a72b03ed8f6ea2be70808c09778fb771a4d6a497dfc572eeec640a914.json new file mode 100644 index 0000000..abc674f --- /dev/null +++ b/.sqlx/query-447b194a72b03ed8f6ea2be70808c09778fb771a4d6a497dfc572eeec640a914.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT status FROM pool_question WHERE id = $1 FOR UPDATE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "status", + "type_info": "Text", + "origin": { + "Table": { + "table": "pool_question", + "name": "status" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "447b194a72b03ed8f6ea2be70808c09778fb771a4d6a497dfc572eeec640a914" +} diff --git a/.sqlx/query-6a9c3d65b96535b78994f3e86751b3d4d6aeea87621d61023f4bfa956e406690.json b/.sqlx/query-4a0358abcaf4cb40aa163933b0693d0a07847c927cf227111eefddbbfcdd473d.json similarity index 60% rename from .sqlx/query-6a9c3d65b96535b78994f3e86751b3d4d6aeea87621d61023f4bfa956e406690.json rename to .sqlx/query-4a0358abcaf4cb40aa163933b0693d0a07847c927cf227111eefddbbfcdd473d.json index 171e63d..7841772 100644 --- a/.sqlx/query-6a9c3d65b96535b78994f3e86751b3d4d6aeea87621d61023f4bfa956e406690.json +++ b/.sqlx/query-4a0358abcaf4cb40aa163933b0693d0a07847c927cf227111eefddbbfcdd473d.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: SolutionId\", question AS \"question: PoolQuestionId\",\n author AS \"author: UserId\", body AS \"body: SolutionBody\",\n offered_at AS \"offered_at: Timestamp\", image_file,\n image_content_type AS \"image_content_type: FileContentType\",\n image_size\n FROM solution WHERE id = $1 AND question = $2", + "query": "SELECT id AS \"id: SolutionId\", question AS \"question: PoolQuestionId\",\n author AS \"author: UserId\", body AS \"body: SolutionBody\",\n offered_at AS \"offered_at: Timestamp\"\n FROM solution WHERE id = $1 AND question = $2", "describe": { "columns": [ { @@ -57,39 +57,6 @@ "name": "offered_at" } } - }, - { - "ordinal": 5, - "name": "image_file", - "type_info": "Text", - "origin": { - "Table": { - "table": "solution", - "name": "image_file" - } - } - }, - { - "ordinal": 6, - "name": "image_content_type: FileContentType", - "type_info": "Text", - "origin": { - "Table": { - "table": "solution", - "name": "image_content_type" - } - } - }, - { - "ordinal": 7, - "name": "image_size", - "type_info": "Int8", - "origin": { - "Table": { - "table": "solution", - "name": "image_size" - } - } } ], "parameters": { @@ -103,11 +70,8 @@ false, false, false, - false, - true, - true, - true + false ] }, - "hash": "6a9c3d65b96535b78994f3e86751b3d4d6aeea87621d61023f4bfa956e406690" + "hash": "4a0358abcaf4cb40aa163933b0693d0a07847c927cf227111eefddbbfcdd473d" } diff --git a/.sqlx/query-4eb0c853e0f0dbfdab689b50ef7f49ad12806460e3181a728c9d213b86994759.json b/.sqlx/query-4eb0c853e0f0dbfdab689b50ef7f49ad12806460e3181a728c9d213b86994759.json new file mode 100644 index 0000000..b6e9eb0 --- /dev/null +++ b/.sqlx/query-4eb0c853e0f0dbfdab689b50ef7f49ad12806460e3181a728c9d213b86994759.json @@ -0,0 +1,17 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO pool_question_image (question, file, content_type, size)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (question) DO UPDATE\n SET file = EXCLUDED.file, content_type = EXCLUDED.content_type,\n size = EXCLUDED.size", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Text", + "Text", + "Int8" + ] + }, + "nullable": [] + }, + "hash": "4eb0c853e0f0dbfdab689b50ef7f49ad12806460e3181a728c9d213b86994759" +} diff --git a/.sqlx/query-5339f6bcf5b3634d8f56481af433ff85f4033d4bd9564e8c101e720ee5177b28.json b/.sqlx/query-5339f6bcf5b3634d8f56481af433ff85f4033d4bd9564e8c101e720ee5177b28.json deleted file mode 100644 index a1db4ab..0000000 --- a/.sqlx/query-5339f6bcf5b3634d8f56481af433ff85f4033d4bd9564e8c101e720ee5177b28.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE solution\n SET image_file = NULL, image_content_type = NULL, image_size = NULL\n WHERE id = $1", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Uuid" - ] - }, - "nullable": [] - }, - "hash": "5339f6bcf5b3634d8f56481af433ff85f4033d4bd9564e8c101e720ee5177b28" -} diff --git a/.sqlx/query-56efb3614b74f560c67b4eded8840fa69edaafd90370717086bf5ea33587ccc9.json b/.sqlx/query-56efb3614b74f560c67b4eded8840fa69edaafd90370717086bf5ea33587ccc9.json new file mode 100644 index 0000000..6649ec7 --- /dev/null +++ b/.sqlx/query-56efb3614b74f560c67b4eded8840fa69edaafd90370717086bf5ea33587ccc9.json @@ -0,0 +1,64 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT question AS \"question: PoolQuestionId\", file,\n content_type AS \"content_type: FileContentType\", size\n FROM pool_question_image WHERE question = ANY($1)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "question: PoolQuestionId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "pool_question_image", + "name": "question" + } + } + }, + { + "ordinal": 1, + "name": "file", + "type_info": "Text", + "origin": { + "Table": { + "table": "pool_question_image", + "name": "file" + } + } + }, + { + "ordinal": 2, + "name": "content_type: FileContentType", + "type_info": "Text", + "origin": { + "Table": { + "table": "pool_question_image", + "name": "content_type" + } + } + }, + { + "ordinal": 3, + "name": "size", + "type_info": "Int8", + "origin": { + "Table": { + "table": "pool_question_image", + "name": "size" + } + } + } + ], + "parameters": { + "Left": [ + "UuidArray" + ] + }, + "nullable": [ + false, + false, + false, + false + ] + }, + "hash": "56efb3614b74f560c67b4eded8840fa69edaafd90370717086bf5ea33587ccc9" +} diff --git a/.sqlx/query-f51d8ec191322860edab5b5691eb75608b7a97611865c7c60835b671620d341d.json b/.sqlx/query-58e602261d1ddb31b9b0d25cb87f46934b0c584727551c8f85d4744b543af99f.json similarity index 80% rename from .sqlx/query-f51d8ec191322860edab5b5691eb75608b7a97611865c7c60835b671620d341d.json rename to .sqlx/query-58e602261d1ddb31b9b0d25cb87f46934b0c584727551c8f85d4744b543af99f.json index 93ec8df..531efb0 100644 --- a/.sqlx/query-f51d8ec191322860edab5b5691eb75608b7a97611865c7c60835b671620d341d.json +++ b/.sqlx/query-58e602261d1ddb31b9b0d25cb87f46934b0c584727551c8f85d4744b543af99f.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n password_hash AS \"password_hash: PasswordHash\",\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 avatar_size\n FROM app_user WHERE id = $1", "describe": { "columns": [ { @@ -27,12 +27,12 @@ }, { "ordinal": 2, - "name": "password_hash: PasswordHash", - "type_info": "Text", + "name": "person: PersonId", + "type_info": "Uuid", "origin": { "Table": { "table": "app_user", - "name": "password_hash" + "name": "person" } } }, @@ -199,7 +199,7 @@ "nullable": [ false, false, - false, + true, false, true, true, @@ -216,5 +216,5 @@ true ] }, - "hash": "f51d8ec191322860edab5b5691eb75608b7a97611865c7c60835b671620d341d" + "hash": "58e602261d1ddb31b9b0d25cb87f46934b0c584727551c8f85d4744b543af99f" } diff --git a/.sqlx/query-978ee2d572d4c605bc6efc79619a592706dab1a321d6a6afc02705624be5a9d2.json b/.sqlx/query-5c49c6a3de866f7db70e13ce592b877972ba1729c8db31202abe0ece0337114b.json similarity index 81% rename from .sqlx/query-978ee2d572d4c605bc6efc79619a592706dab1a321d6a6afc02705624be5a9d2.json rename to .sqlx/query-5c49c6a3de866f7db70e13ce592b877972ba1729c8db31202abe0ece0337114b.json index 13e7a0f..ff8d6cc 100644 --- a/.sqlx/query-978ee2d572d4c605bc6efc79619a592706dab1a321d6a6afc02705624be5a9d2.json +++ b/.sqlx/query-5c49c6a3de866f7db70e13ce592b877972ba1729c8db31202abe0ece0337114b.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT class AS \"class: ClassGroupId\", course AS \"course: CourseId\"\n FROM class_course\n WHERE source = $1 AND course <> ALL($2)", + "query": "SELECT class AS \"class: ClassGroupId\", course AS \"course: CourseId\"\n FROM class_course\n WHERE source = (SELECT id FROM class_blueprint WHERE grade = $1)\n AND course <> ALL($2)", "describe": { "columns": [ { @@ -37,5 +37,5 @@ false ] }, - "hash": "978ee2d572d4c605bc6efc79619a592706dab1a321d6a6afc02705624be5a9d2" + "hash": "5c49c6a3de866f7db70e13ce592b877972ba1729c8db31202abe0ece0337114b" } diff --git a/.sqlx/query-640eda8540ee9ff418c99a67bb6744b6feff7ee0279025b7c2bd6bc457fc6890.json b/.sqlx/query-640eda8540ee9ff418c99a67bb6744b6feff7ee0279025b7c2bd6bc457fc6890.json new file mode 100644 index 0000000..3921ae0 --- /dev/null +++ b/.sqlx/query-640eda8540ee9ff418c99a67bb6744b6feff7ee0279025b7c2bd6bc457fc6890.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id FROM solution WHERE id = $1 FOR UPDATE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "solution", + "name": "id" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "640eda8540ee9ff418c99a67bb6744b6feff7ee0279025b7c2bd6bc457fc6890" +} diff --git a/.sqlx/query-714830734d9e787ce33c15e0027e83043ee456b16d6f4f856c3af00a16e977f3.json b/.sqlx/query-714830734d9e787ce33c15e0027e83043ee456b16d6f4f856c3af00a16e977f3.json new file mode 100644 index 0000000..0542ec1 --- /dev/null +++ b/.sqlx/query-714830734d9e787ce33c15e0027e83043ee456b16d6f4f856c3af00a16e977f3.json @@ -0,0 +1,64 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT solution AS \"solution: SolutionId\", file,\n content_type AS \"content_type: FileContentType\", size\n FROM solution_image WHERE solution = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "solution: SolutionId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "solution_image", + "name": "solution" + } + } + }, + { + "ordinal": 1, + "name": "file", + "type_info": "Text", + "origin": { + "Table": { + "table": "solution_image", + "name": "file" + } + } + }, + { + "ordinal": 2, + "name": "content_type: FileContentType", + "type_info": "Text", + "origin": { + "Table": { + "table": "solution_image", + "name": "content_type" + } + } + }, + { + "ordinal": 3, + "name": "size", + "type_info": "Int8", + "origin": { + "Table": { + "table": "solution_image", + "name": "size" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + false, + false, + false + ] + }, + "hash": "714830734d9e787ce33c15e0027e83043ee456b16d6f4f856c3af00a16e977f3" +} diff --git a/.sqlx/query-be50288b93c89d7af01260c224d618b4f0503e6bc9ffe98a260d37781b4ffafe.json b/.sqlx/query-71d04899eb9154c003e684424ff74f05dafe0fd7b11d51f9c572cee6591a9229.json similarity index 65% rename from .sqlx/query-be50288b93c89d7af01260c224d618b4f0503e6bc9ffe98a260d37781b4ffafe.json rename to .sqlx/query-71d04899eb9154c003e684424ff74f05dafe0fd7b11d51f9c572cee6591a9229.json index 0f4f474..0f60123 100644 --- a/.sqlx/query-be50288b93c89d7af01260c224d618b4f0503e6bc9ffe98a260d37781b4ffafe.json +++ b/.sqlx/query-71d04899eb9154c003e684424ff74f05dafe0fd7b11d51f9c572cee6591a9229.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: PoolQuestionId\", asker AS \"asker: UserId\",\n title AS \"title: PoolQuestionTitle\", body AS \"body: PoolQuestionBody\",\n status, asked_at AS \"asked_at: Timestamp\",\n approved_by AS \"approved_by: UserId\", image_file,\n image_content_type AS \"image_content_type: FileContentType\",\n image_size\n FROM pool_question\n WHERE status = $1 OR asker = $2\n ORDER BY asked_at DESC, id DESC", + "query": "SELECT id AS \"id: PoolQuestionId\", asker AS \"asker: UserId\",\n title AS \"title: PoolQuestionTitle\", body AS \"body: PoolQuestionBody\",\n status, asked_at AS \"asked_at: Timestamp\",\n approved_by AS \"approved_by: UserId\"\n FROM pool_question WHERE id = $1", "describe": { "columns": [ { @@ -79,44 +79,10 @@ "name": "approved_by" } } - }, - { - "ordinal": 7, - "name": "image_file", - "type_info": "Text", - "origin": { - "Table": { - "table": "pool_question", - "name": "image_file" - } - } - }, - { - "ordinal": 8, - "name": "image_content_type: FileContentType", - "type_info": "Text", - "origin": { - "Table": { - "table": "pool_question", - "name": "image_content_type" - } - } - }, - { - "ordinal": 9, - "name": "image_size", - "type_info": "Int8", - "origin": { - "Table": { - "table": "pool_question", - "name": "image_size" - } - } } ], "parameters": { "Left": [ - "Text", "Uuid" ] }, @@ -127,11 +93,8 @@ false, false, false, - true, - true, - true, true ] }, - "hash": "be50288b93c89d7af01260c224d618b4f0503e6bc9ffe98a260d37781b4ffafe" + "hash": "71d04899eb9154c003e684424ff74f05dafe0fd7b11d51f9c572cee6591a9229" } diff --git a/.sqlx/query-737f3d886474291e0875e7bd66d7aef4d7a718a6b900cf55725811cc0193c63b.json b/.sqlx/query-737f3d886474291e0875e7bd66d7aef4d7a718a6b900cf55725811cc0193c63b.json deleted file mode 100644 index ea549fd..0000000 --- a/.sqlx/query-737f3d886474291e0875e7bd66d7aef4d7a718a6b900cf55725811cc0193c63b.json +++ /dev/null @@ -1,112 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: SolutionId\", question AS \"question: PoolQuestionId\",\n author AS \"author: UserId\", body AS \"body: SolutionBody\",\n offered_at AS \"offered_at: Timestamp\", image_file,\n image_content_type AS \"image_content_type: FileContentType\",\n image_size\n FROM solution WHERE id = $1 FOR UPDATE", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "id: SolutionId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "solution", - "name": "id" - } - } - }, - { - "ordinal": 1, - "name": "question: PoolQuestionId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "solution", - "name": "question" - } - } - }, - { - "ordinal": 2, - "name": "author: UserId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "solution", - "name": "author" - } - } - }, - { - "ordinal": 3, - "name": "body: SolutionBody", - "type_info": "Text", - "origin": { - "Table": { - "table": "solution", - "name": "body" - } - } - }, - { - "ordinal": 4, - "name": "offered_at: Timestamp", - "type_info": "Int8", - "origin": { - "Table": { - "table": "solution", - "name": "offered_at" - } - } - }, - { - "ordinal": 5, - "name": "image_file", - "type_info": "Text", - "origin": { - "Table": { - "table": "solution", - "name": "image_file" - } - } - }, - { - "ordinal": 6, - "name": "image_content_type: FileContentType", - "type_info": "Text", - "origin": { - "Table": { - "table": "solution", - "name": "image_content_type" - } - } - }, - { - "ordinal": 7, - "name": "image_size", - "type_info": "Int8", - "origin": { - "Table": { - "table": "solution", - "name": "image_size" - } - } - } - ], - "parameters": { - "Left": [ - "Uuid" - ] - }, - "nullable": [ - false, - false, - false, - false, - false, - true, - true, - true - ] - }, - "hash": "737f3d886474291e0875e7bd66d7aef4d7a718a6b900cf55725811cc0193c63b" -} diff --git a/.sqlx/query-7ef42e6925a0f1f65338d486da231542f6b2e0ea1ea0deb33a56e610e52a48ad.json b/.sqlx/query-7ef42e6925a0f1f65338d486da231542f6b2e0ea1ea0deb33a56e610e52a48ad.json new file mode 100644 index 0000000..e88b7b1 --- /dev/null +++ b/.sqlx/query-7ef42e6925a0f1f65338d486da231542f6b2e0ea1ea0deb33a56e610e52a48ad.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT file FROM pool_question_image WHERE question = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "file", + "type_info": "Text", + "origin": { + "Table": { + "table": "pool_question_image", + "name": "file" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "7ef42e6925a0f1f65338d486da231542f6b2e0ea1ea0deb33a56e610e52a48ad" +} diff --git a/.sqlx/query-e0b4d2b3044ea3789088b96d5e94a26ddb6e2cf9a8c4975add584de027fd6129.json b/.sqlx/query-81a7b9416011e6f61c2723adbc62c4499ac910c7d1228afb0ccfd1f28b02dc11.json similarity index 79% rename from .sqlx/query-e0b4d2b3044ea3789088b96d5e94a26ddb6e2cf9a8c4975add584de027fd6129.json rename to .sqlx/query-81a7b9416011e6f61c2723adbc62c4499ac910c7d1228afb0ccfd1f28b02dc11.json index f6d73d5..e4c3eb1 100644 --- a/.sqlx/query-e0b4d2b3044ea3789088b96d5e94a26ddb6e2cf9a8c4975add584de027fd6129.json +++ b/.sqlx/query-81a7b9416011e6f61c2723adbc62c4499ac910c7d1228afb0ccfd1f28b02dc11.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n password_hash AS \"password_hash: PasswordHash\",\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 avatar_size\n FROM app_user WHERE role = $1 ORDER BY id DESC", "describe": { "columns": [ { @@ -27,12 +27,12 @@ }, { "ordinal": 2, - "name": "password_hash: PasswordHash", - "type_info": "Text", + "name": "person: PersonId", + "type_info": "Uuid", "origin": { "Table": { "table": "app_user", - "name": "password_hash" + "name": "person" } } }, @@ -199,7 +199,7 @@ "nullable": [ false, false, - false, + true, false, true, true, @@ -216,5 +216,5 @@ true ] }, - "hash": "e0b4d2b3044ea3789088b96d5e94a26ddb6e2cf9a8c4975add584de027fd6129" + "hash": "81a7b9416011e6f61c2723adbc62c4499ac910c7d1228afb0ccfd1f28b02dc11" } diff --git a/.sqlx/query-c3749cd58f34075bdd4568e519d212b3ead4691ab73272d0d1eae00b126d30f6.json b/.sqlx/query-8752532672cac328e5a5a18d0cbd3d372f285cabee06be0a798fb477b5a98787.json similarity index 69% rename from .sqlx/query-c3749cd58f34075bdd4568e519d212b3ead4691ab73272d0d1eae00b126d30f6.json rename to .sqlx/query-8752532672cac328e5a5a18d0cbd3d372f285cabee06be0a798fb477b5a98787.json index 70e1ec3..5159c5b 100644 --- a/.sqlx/query-c3749cd58f34075bdd4568e519d212b3ead4691ab73272d0d1eae00b126d30f6.json +++ b/.sqlx/query-8752532672cac328e5a5a18d0cbd3d372f285cabee06be0a798fb477b5a98787.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE pool_question SET status = $2, approved_by = $3\n WHERE id = $1 AND status = $4\n RETURNING id AS \"id: PoolQuestionId\", asker AS \"asker: UserId\",\n title AS \"title: PoolQuestionTitle\", body AS \"body: PoolQuestionBody\",\n status, asked_at AS \"asked_at: Timestamp\",\n approved_by AS \"approved_by: UserId\", image_file,\n image_content_type AS \"image_content_type: FileContentType\",\n image_size", + "query": "UPDATE pool_question SET status = $2, approved_by = $3\n WHERE id = $1 AND status = $4\n RETURNING id AS \"id: PoolQuestionId\", asker AS \"asker: UserId\",\n title AS \"title: PoolQuestionTitle\", body AS \"body: PoolQuestionBody\",\n status, asked_at AS \"asked_at: Timestamp\",\n approved_by AS \"approved_by: UserId\"", "describe": { "columns": [ { @@ -79,39 +79,6 @@ "name": "approved_by" } } - }, - { - "ordinal": 7, - "name": "image_file", - "type_info": "Text", - "origin": { - "Table": { - "table": "pool_question", - "name": "image_file" - } - } - }, - { - "ordinal": 8, - "name": "image_content_type: FileContentType", - "type_info": "Text", - "origin": { - "Table": { - "table": "pool_question", - "name": "image_content_type" - } - } - }, - { - "ordinal": 9, - "name": "image_size", - "type_info": "Int8", - "origin": { - "Table": { - "table": "pool_question", - "name": "image_size" - } - } } ], "parameters": { @@ -129,11 +96,8 @@ false, false, false, - true, - true, - true, true ] }, - "hash": "c3749cd58f34075bdd4568e519d212b3ead4691ab73272d0d1eae00b126d30f6" + "hash": "8752532672cac328e5a5a18d0cbd3d372f285cabee06be0a798fb477b5a98787" } diff --git a/.sqlx/query-8bef59e3c15a1c19a23800bffe0dd2e43afa3a07509c593ac01828a9d511dcb3.json b/.sqlx/query-8bef59e3c15a1c19a23800bffe0dd2e43afa3a07509c593ac01828a9d511dcb3.json new file mode 100644 index 0000000..d18c368 --- /dev/null +++ b/.sqlx/query-8bef59e3c15a1c19a23800bffe0dd2e43afa3a07509c593ac01828a9d511dcb3.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM solution_image si\n USING solution s\n WHERE si.solution = s.id AND s.question = $1\n RETURNING si.file", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "file", + "type_info": "Text", + "origin": { + "Table": { + "table": "solution_image", + "name": "file" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "8bef59e3c15a1c19a23800bffe0dd2e43afa3a07509c593ac01828a9d511dcb3" +} diff --git a/.sqlx/query-8c457fff4a76cedba9338135a894713e2609cb8aed0e963ba491118d3aebe0a3.json b/.sqlx/query-8c457fff4a76cedba9338135a894713e2609cb8aed0e963ba491118d3aebe0a3.json new file mode 100644 index 0000000..177d57d --- /dev/null +++ b/.sqlx/query-8c457fff4a76cedba9338135a894713e2609cb8aed0e963ba491118d3aebe0a3.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO person_school (person, school, created_at) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Text", + "Int8" + ] + }, + "nullable": [] + }, + "hash": "8c457fff4a76cedba9338135a894713e2609cb8aed0e963ba491118d3aebe0a3" +} diff --git a/.sqlx/query-cbfa89d17e1e85a80d7d966b8a016241636a48ce16f69fb3c7a60ea0daeeae18.json b/.sqlx/query-97201bc98edb694a2e07d8da4fd91718e519bfe092a9cdb735d65f654da2f58d.json similarity index 70% rename from .sqlx/query-cbfa89d17e1e85a80d7d966b8a016241636a48ce16f69fb3c7a60ea0daeeae18.json rename to .sqlx/query-97201bc98edb694a2e07d8da4fd91718e519bfe092a9cdb735d65f654da2f58d.json index 6c81f31..417b36d 100644 --- a/.sqlx/query-cbfa89d17e1e85a80d7d966b8a016241636a48ce16f69fb3c7a60ea0daeeae18.json +++ b/.sqlx/query-97201bc98edb694a2e07d8da4fd91718e519bfe092a9cdb735d65f654da2f58d.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO session_attendance (session, app_user, course, status, marked_by)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (session, app_user) DO UPDATE\n SET status = EXCLUDED.status, marked_by = EXCLUDED.marked_by\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, 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\"", "describe": { "columns": [ { @@ -65,7 +65,8 @@ "Uuid", "Uuid", "Text", - "Uuid" + "Uuid", + "Int8" ] }, "nullable": [ @@ -76,5 +77,5 @@ false ] }, - "hash": "cbfa89d17e1e85a80d7d966b8a016241636a48ce16f69fb3c7a60ea0daeeae18" + "hash": "97201bc98edb694a2e07d8da4fd91718e519bfe092a9cdb735d65f654da2f58d" } diff --git a/.sqlx/query-d55fea5f3a7984940247abf1f5aa70ab377956b5bd73eea3f052beda34c330d2.json b/.sqlx/query-abfadabb2800fe7d24a29c2fefb9d53342ad156dd1ec856a31e61cd84ab14fc2.json similarity index 63% rename from .sqlx/query-d55fea5f3a7984940247abf1f5aa70ab377956b5bd73eea3f052beda34c330d2.json rename to .sqlx/query-abfadabb2800fe7d24a29c2fefb9d53342ad156dd1ec856a31e61cd84ab14fc2.json index c9f52fe..9be426a 100644 --- a/.sqlx/query-d55fea5f3a7984940247abf1f5aa70ab377956b5bd73eea3f052beda34c330d2.json +++ b/.sqlx/query-abfadabb2800fe7d24a29c2fefb9d53342ad156dd1ec856a31e61cd84ab14fc2.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "DELETE FROM pool_question WHERE id = $1\n RETURNING id AS \"id: PoolQuestionId\", asker AS \"asker: UserId\",\n title AS \"title: PoolQuestionTitle\", body AS \"body: PoolQuestionBody\",\n status, asked_at AS \"asked_at: Timestamp\",\n approved_by AS \"approved_by: UserId\", image_file,\n image_content_type AS \"image_content_type: FileContentType\",\n image_size", + "query": "DELETE FROM pool_question WHERE id = $1\n RETURNING id AS \"id: PoolQuestionId\", asker AS \"asker: UserId\",\n title AS \"title: PoolQuestionTitle\", body AS \"body: PoolQuestionBody\",\n status, asked_at AS \"asked_at: Timestamp\",\n approved_by AS \"approved_by: UserId\"", "describe": { "columns": [ { @@ -79,39 +79,6 @@ "name": "approved_by" } } - }, - { - "ordinal": 7, - "name": "image_file", - "type_info": "Text", - "origin": { - "Table": { - "table": "pool_question", - "name": "image_file" - } - } - }, - { - "ordinal": 8, - "name": "image_content_type: FileContentType", - "type_info": "Text", - "origin": { - "Table": { - "table": "pool_question", - "name": "image_content_type" - } - } - }, - { - "ordinal": 9, - "name": "image_size", - "type_info": "Int8", - "origin": { - "Table": { - "table": "pool_question", - "name": "image_size" - } - } } ], "parameters": { @@ -126,11 +93,8 @@ false, false, false, - true, - true, - true, true ] }, - "hash": "d55fea5f3a7984940247abf1f5aa70ab377956b5bd73eea3f052beda34c330d2" + "hash": "abfadabb2800fe7d24a29c2fefb9d53342ad156dd1ec856a31e61cd84ab14fc2" } diff --git a/.sqlx/query-b13fbe46118621c9232dad317f012454024d0587e63d010f4f4e9c837b54ea46.json b/.sqlx/query-b13fbe46118621c9232dad317f012454024d0587e63d010f4f4e9c837b54ea46.json new file mode 100644 index 0000000..7db84cd --- /dev/null +++ b/.sqlx/query-b13fbe46118621c9232dad317f012454024d0587e63d010f4f4e9c837b54ea46.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM pool_question_image WHERE question = $1 RETURNING file", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "file", + "type_info": "Text", + "origin": { + "Table": { + "table": "pool_question_image", + "name": "file" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "b13fbe46118621c9232dad317f012454024d0587e63d010f4f4e9c837b54ea46" +} diff --git a/.sqlx/query-b21b7cead2c7a5737594f65d926b19d442328c17626b2a9766a48a3fba108de3.json b/.sqlx/query-b21b7cead2c7a5737594f65d926b19d442328c17626b2a9766a48a3fba108de3.json new file mode 100644 index 0000000..742bbca --- /dev/null +++ b/.sqlx/query-b21b7cead2c7a5737594f65d926b19d442328c17626b2a9766a48a3fba108de3.json @@ -0,0 +1,17 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO solution_image (solution, file, content_type, size)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (solution) DO UPDATE\n SET file = EXCLUDED.file, content_type = EXCLUDED.content_type,\n size = EXCLUDED.size", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Text", + "Text", + "Int8" + ] + }, + "nullable": [] + }, + "hash": "b21b7cead2c7a5737594f65d926b19d442328c17626b2a9766a48a3fba108de3" +} diff --git a/.sqlx/query-98f14d5a29c39911636d47058ce39fd2e48177276cf04ef529625326b414a1ca.json b/.sqlx/query-b2bccc168bdfc5b3fb5ae5d0f0164689877cb542d7a57e7bcb34e24f619122ca.json similarity index 74% rename from .sqlx/query-98f14d5a29c39911636d47058ce39fd2e48177276cf04ef529625326b414a1ca.json rename to .sqlx/query-b2bccc168bdfc5b3fb5ae5d0f0164689877cb542d7a57e7bcb34e24f619122ca.json index 40ebce0..9dcbe4d 100644 --- a/.sqlx/query-98f14d5a29c39911636d47058ce39fd2e48177276cf04ef529625326b414a1ca.json +++ b/.sqlx/query-b2bccc168bdfc5b3fb5ae5d0f0164689877cb542d7a57e7bcb34e24f619122ca.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO attendance (event, app_user, status, marked_by)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (event, app_user) DO UPDATE SET status = $3, marked_by = $4\n RETURNING event AS \"event: EventId\", app_user AS \"user: UserId\", status AS \"status: AttendanceStatus\", marked_by AS \"marked_by: UserId\"", + "query": "INSERT INTO attendance (event, app_user, status, marked_by, marked_at)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (event, app_user) DO UPDATE SET status = $3, marked_by = $4, marked_at = $5\n RETURNING event AS \"event: EventId\", app_user AS \"user: UserId\", status AS \"status: AttendanceStatus\", marked_by AS \"marked_by: UserId\"", "describe": { "columns": [ { @@ -53,7 +53,8 @@ "Uuid", "Uuid", "Text", - "Uuid" + "Uuid", + "Int8" ] }, "nullable": [ @@ -63,5 +64,5 @@ false ] }, - "hash": "98f14d5a29c39911636d47058ce39fd2e48177276cf04ef529625326b414a1ca" + "hash": "b2bccc168bdfc5b3fb5ae5d0f0164689877cb542d7a57e7bcb34e24f619122ca" } diff --git a/.sqlx/query-b38dc08f857b6b4d513ab833a68c4f6f35d0883f920a16e133848377032f8ec7.json b/.sqlx/query-b38dc08f857b6b4d513ab833a68c4f6f35d0883f920a16e133848377032f8ec7.json deleted file mode 100644 index b79f408..0000000 --- a/.sqlx/query-b38dc08f857b6b4d513ab833a68c4f6f35d0883f920a16e133848377032f8ec7.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE solution\n SET image_file = $2, image_content_type = $3, image_size = $4\n WHERE id = $1", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Uuid", - "Text", - "Text", - "Int8" - ] - }, - "nullable": [] - }, - "hash": "b38dc08f857b6b4d513ab833a68c4f6f35d0883f920a16e133848377032f8ec7" -} diff --git a/.sqlx/query-b456d14c2d2995e199dd8469982675d5693328ba0bf54d95f392587025c044a3.json b/.sqlx/query-b456d14c2d2995e199dd8469982675d5693328ba0bf54d95f392587025c044a3.json deleted file mode 100644 index 370376f..0000000 --- a/.sqlx/query-b456d14c2d2995e199dd8469982675d5693328ba0bf54d95f392587025c044a3.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO person (id, username, password_hash) VALUES ($1, $2, $3)", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Uuid", - "Text", - "Text" - ] - }, - "nullable": [] - }, - "hash": "b456d14c2d2995e199dd8469982675d5693328ba0bf54d95f392587025c044a3" -} diff --git a/.sqlx/query-b8a5a3348368cdff8471feda27935f12d583776ef91a10a879fc52b5ae35248a.json b/.sqlx/query-b8a5a3348368cdff8471feda27935f12d583776ef91a10a879fc52b5ae35248a.json new file mode 100644 index 0000000..b8aa039 --- /dev/null +++ b/.sqlx/query-b8a5a3348368cdff8471feda27935f12d583776ef91a10a879fc52b5ae35248a.json @@ -0,0 +1,64 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT question AS \"question: PoolQuestionId\", file,\n content_type AS \"content_type: FileContentType\", size\n FROM pool_question_image WHERE question = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "question: PoolQuestionId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "pool_question_image", + "name": "question" + } + } + }, + { + "ordinal": 1, + "name": "file", + "type_info": "Text", + "origin": { + "Table": { + "table": "pool_question_image", + "name": "file" + } + } + }, + { + "ordinal": 2, + "name": "content_type: FileContentType", + "type_info": "Text", + "origin": { + "Table": { + "table": "pool_question_image", + "name": "content_type" + } + } + }, + { + "ordinal": 3, + "name": "size", + "type_info": "Int8", + "origin": { + "Table": { + "table": "pool_question_image", + "name": "size" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + false, + false, + false + ] + }, + "hash": "b8a5a3348368cdff8471feda27935f12d583776ef91a10a879fc52b5ae35248a" +} diff --git a/.sqlx/query-b8cd6149b5f42e615c31018d2fdf306f157f5275587ae57d1e5146c9a76a51d3.json b/.sqlx/query-b8cd6149b5f42e615c31018d2fdf306f157f5275587ae57d1e5146c9a76a51d3.json new file mode 100644 index 0000000..20cbda6 --- /dev/null +++ b/.sqlx/query-b8cd6149b5f42e615c31018d2fdf306f157f5275587ae57d1e5146c9a76a51d3.json @@ -0,0 +1,17 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO class_blueprint (id, grade, courses, creator)\n VALUES ($1, $2, $3, $4)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Text", + "UuidArray", + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "b8cd6149b5f42e615c31018d2fdf306f157f5275587ae57d1e5146c9a76a51d3" +} diff --git a/.sqlx/query-b974949e3de075232f1220b8daec3799995ce55fd9f1097a7989c9ac466bccd2.json b/.sqlx/query-b974949e3de075232f1220b8daec3799995ce55fd9f1097a7989c9ac466bccd2.json deleted file mode 100644 index 1c8a20b..0000000 --- a/.sqlx/query-b974949e3de075232f1220b8daec3799995ce55fd9f1097a7989c9ac466bccd2.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE pool_question\n SET image_file = NULL, image_content_type = NULL, image_size = NULL\n WHERE id = $1 AND status = $2", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Uuid", - "Text" - ] - }, - "nullable": [] - }, - "hash": "b974949e3de075232f1220b8daec3799995ce55fd9f1097a7989c9ac466bccd2" -} diff --git a/.sqlx/query-b98d8909cb9032074d2ed751ed8196d28b55994655cab271d7660b050a37724d.json b/.sqlx/query-b98d8909cb9032074d2ed751ed8196d28b55994655cab271d7660b050a37724d.json deleted file mode 100644 index 6caaaba..0000000 --- a/.sqlx/query-b98d8909cb9032074d2ed751ed8196d28b55994655cab271d7660b050a37724d.json +++ /dev/null @@ -1,136 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: PoolQuestionId\", asker AS \"asker: UserId\",\n title AS \"title: PoolQuestionTitle\", body AS \"body: PoolQuestionBody\",\n status, asked_at AS \"asked_at: Timestamp\",\n approved_by AS \"approved_by: UserId\", image_file,\n image_content_type AS \"image_content_type: FileContentType\",\n image_size\n FROM pool_question WHERE id = $1 FOR UPDATE", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "id: PoolQuestionId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "pool_question", - "name": "id" - } - } - }, - { - "ordinal": 1, - "name": "asker: UserId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "pool_question", - "name": "asker" - } - } - }, - { - "ordinal": 2, - "name": "title: PoolQuestionTitle", - "type_info": "Text", - "origin": { - "Table": { - "table": "pool_question", - "name": "title" - } - } - }, - { - "ordinal": 3, - "name": "body: PoolQuestionBody", - "type_info": "Text", - "origin": { - "Table": { - "table": "pool_question", - "name": "body" - } - } - }, - { - "ordinal": 4, - "name": "status", - "type_info": "Text", - "origin": { - "Table": { - "table": "pool_question", - "name": "status" - } - } - }, - { - "ordinal": 5, - "name": "asked_at: Timestamp", - "type_info": "Int8", - "origin": { - "Table": { - "table": "pool_question", - "name": "asked_at" - } - } - }, - { - "ordinal": 6, - "name": "approved_by: UserId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "pool_question", - "name": "approved_by" - } - } - }, - { - "ordinal": 7, - "name": "image_file", - "type_info": "Text", - "origin": { - "Table": { - "table": "pool_question", - "name": "image_file" - } - } - }, - { - "ordinal": 8, - "name": "image_content_type: FileContentType", - "type_info": "Text", - "origin": { - "Table": { - "table": "pool_question", - "name": "image_content_type" - } - } - }, - { - "ordinal": 9, - "name": "image_size", - "type_info": "Int8", - "origin": { - "Table": { - "table": "pool_question", - "name": "image_size" - } - } - } - ], - "parameters": { - "Left": [ - "Uuid" - ] - }, - "nullable": [ - false, - false, - false, - false, - false, - false, - true, - true, - true, - true - ] - }, - "hash": "b98d8909cb9032074d2ed751ed8196d28b55994655cab271d7660b050a37724d" -} diff --git a/.sqlx/query-c7a7010a5c92b584dfb05e486525b486f6789eacf8b91ee91ba6bfc41e28b224.json b/.sqlx/query-c7a7010a5c92b584dfb05e486525b486f6789eacf8b91ee91ba6bfc41e28b224.json new file mode 100644 index 0000000..936e46a --- /dev/null +++ b/.sqlx/query-c7a7010a5c92b584dfb05e486525b486f6789eacf8b91ee91ba6bfc41e28b224.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id FROM class_blueprint WHERE grade = $1 FOR KEY SHARE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_blueprint", + "name": "id" + } + } + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false + ] + }, + "hash": "c7a7010a5c92b584dfb05e486525b486f6789eacf8b91ee91ba6bfc41e28b224" +} diff --git a/.sqlx/query-99e79710dd2c15c90fdcbdadfa02b4f794bae5b308c904d4c1e21effdc10fd19.json b/.sqlx/query-c8ff6de29d2a6825321c3de628a7d77fb6d3cfd2d74053304af55946ddeb5197.json similarity index 62% rename from .sqlx/query-99e79710dd2c15c90fdcbdadfa02b4f794bae5b308c904d4c1e21effdc10fd19.json rename to .sqlx/query-c8ff6de29d2a6825321c3de628a7d77fb6d3cfd2d74053304af55946ddeb5197.json index 43d88c2..08ed780 100644 --- a/.sqlx/query-99e79710dd2c15c90fdcbdadfa02b4f794bae5b308c904d4c1e21effdc10fd19.json +++ b/.sqlx/query-c8ff6de29d2a6825321c3de628a7d77fb6d3cfd2d74053304af55946ddeb5197.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE solution SET body = $2 WHERE id = $1\n RETURNING id AS \"id: SolutionId\", question AS \"question: PoolQuestionId\",\n author AS \"author: UserId\", body AS \"body: SolutionBody\",\n offered_at AS \"offered_at: Timestamp\", image_file,\n image_content_type AS \"image_content_type: FileContentType\",\n image_size", + "query": "UPDATE solution SET body = $2 WHERE id = $1\n RETURNING id AS \"id: SolutionId\", question AS \"question: PoolQuestionId\",\n author AS \"author: UserId\", body AS \"body: SolutionBody\",\n offered_at AS \"offered_at: Timestamp\"", "describe": { "columns": [ { @@ -57,39 +57,6 @@ "name": "offered_at" } } - }, - { - "ordinal": 5, - "name": "image_file", - "type_info": "Text", - "origin": { - "Table": { - "table": "solution", - "name": "image_file" - } - } - }, - { - "ordinal": 6, - "name": "image_content_type: FileContentType", - "type_info": "Text", - "origin": { - "Table": { - "table": "solution", - "name": "image_content_type" - } - } - }, - { - "ordinal": 7, - "name": "image_size", - "type_info": "Int8", - "origin": { - "Table": { - "table": "solution", - "name": "image_size" - } - } } ], "parameters": { @@ -103,11 +70,8 @@ false, false, false, - false, - true, - true, - true + false ] }, - "hash": "99e79710dd2c15c90fdcbdadfa02b4f794bae5b308c904d4c1e21effdc10fd19" + "hash": "c8ff6de29d2a6825321c3de628a7d77fb6d3cfd2d74053304af55946ddeb5197" } diff --git a/.sqlx/query-adf2538573b95fb3dd6138ee45469e4d1308caf090e0079b993cd350a6227325.json b/.sqlx/query-cdf70b71ea45a12649a5586c9ef1185cf737b2284fc7e4b22cc15ca4470d62d0.json similarity index 52% rename from .sqlx/query-adf2538573b95fb3dd6138ee45469e4d1308caf090e0079b993cd350a6227325.json rename to .sqlx/query-cdf70b71ea45a12649a5586c9ef1185cf737b2284fc7e4b22cc15ca4470d62d0.json index 69e8681..2bf4601 100644 --- a/.sqlx/query-adf2538573b95fb3dd6138ee45469e4d1308caf090e0079b993cd350a6227325.json +++ b/.sqlx/query-cdf70b71ea45a12649a5586c9ef1185cf737b2284fc7e4b22cc15ca4470d62d0.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "DELETE FROM solution WHERE id = $1\n RETURNING id AS \"id: SolutionId\", question AS \"question: PoolQuestionId\",\n author AS \"author: UserId\", body AS \"body: SolutionBody\",\n offered_at AS \"offered_at: Timestamp\", image_file,\n image_content_type AS \"image_content_type: FileContentType\",\n image_size", + "query": "DELETE FROM solution WHERE id = $1\n RETURNING id AS \"id: SolutionId\", question AS \"question: PoolQuestionId\",\n author AS \"author: UserId\", body AS \"body: SolutionBody\",\n offered_at AS \"offered_at: Timestamp\"", "describe": { "columns": [ { @@ -57,39 +57,6 @@ "name": "offered_at" } } - }, - { - "ordinal": 5, - "name": "image_file", - "type_info": "Text", - "origin": { - "Table": { - "table": "solution", - "name": "image_file" - } - } - }, - { - "ordinal": 6, - "name": "image_content_type: FileContentType", - "type_info": "Text", - "origin": { - "Table": { - "table": "solution", - "name": "image_content_type" - } - } - }, - { - "ordinal": 7, - "name": "image_size", - "type_info": "Int8", - "origin": { - "Table": { - "table": "solution", - "name": "image_size" - } - } } ], "parameters": { @@ -102,11 +69,8 @@ false, false, false, - false, - true, - true, - true + false ] }, - "hash": "adf2538573b95fb3dd6138ee45469e4d1308caf090e0079b993cd350a6227325" + "hash": "cdf70b71ea45a12649a5586c9ef1185cf737b2284fc7e4b22cc15ca4470d62d0" } diff --git a/.sqlx/query-8976db6b51d0e2019c6ecda3ada05fbbb8270044587c86a50396091e7ef542cd.json b/.sqlx/query-d9dafaf7b0734e61a05c51caa2da71d7bfa5a6c70a05f03d431bfc6d956e73bd.json similarity index 66% rename from .sqlx/query-8976db6b51d0e2019c6ecda3ada05fbbb8270044587c86a50396091e7ef542cd.json rename to .sqlx/query-d9dafaf7b0734e61a05c51caa2da71d7bfa5a6c70a05f03d431bfc6d956e73bd.json index 8e1aa10..c520be3 100644 --- a/.sqlx/query-8976db6b51d0e2019c6ecda3ada05fbbb8270044587c86a50396091e7ef542cd.json +++ b/.sqlx/query-d9dafaf7b0734e61a05c51caa2da71d7bfa5a6c70a05f03d431bfc6d956e73bd.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: PoolQuestionId\", asker AS \"asker: UserId\",\n title AS \"title: PoolQuestionTitle\", body AS \"body: PoolQuestionBody\",\n status, asked_at AS \"asked_at: Timestamp\",\n approved_by AS \"approved_by: UserId\", image_file,\n image_content_type AS \"image_content_type: FileContentType\",\n image_size\n FROM pool_question ORDER BY asked_at DESC, id DESC", + "query": "SELECT id AS \"id: PoolQuestionId\", asker AS \"asker: UserId\",\n title AS \"title: PoolQuestionTitle\", body AS \"body: PoolQuestionBody\",\n status, asked_at AS \"asked_at: Timestamp\",\n approved_by AS \"approved_by: UserId\"\n FROM pool_question ORDER BY asked_at DESC, id DESC", "describe": { "columns": [ { @@ -79,39 +79,6 @@ "name": "approved_by" } } - }, - { - "ordinal": 7, - "name": "image_file", - "type_info": "Text", - "origin": { - "Table": { - "table": "pool_question", - "name": "image_file" - } - } - }, - { - "ordinal": 8, - "name": "image_content_type: FileContentType", - "type_info": "Text", - "origin": { - "Table": { - "table": "pool_question", - "name": "image_content_type" - } - } - }, - { - "ordinal": 9, - "name": "image_size", - "type_info": "Int8", - "origin": { - "Table": { - "table": "pool_question", - "name": "image_size" - } - } } ], "parameters": { @@ -124,11 +91,8 @@ false, false, false, - true, - true, - true, true ] }, - "hash": "8976db6b51d0e2019c6ecda3ada05fbbb8270044587c86a50396091e7ef542cd" + "hash": "d9dafaf7b0734e61a05c51caa2da71d7bfa5a6c70a05f03d431bfc6d956e73bd" } diff --git a/.sqlx/query-db1585206cb88ca4a02b4f73b23e10ea7f51bf6c77bca5217040e11f0cf87239.json b/.sqlx/query-db1585206cb88ca4a02b4f73b23e10ea7f51bf6c77bca5217040e11f0cf87239.json deleted file mode 100644 index 6d2e331..0000000 --- a/.sqlx/query-db1585206cb88ca4a02b4f73b23e10ea7f51bf6c77bca5217040e11f0cf87239.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE pool_question\n SET image_file = $2, image_content_type = $3, image_size = $4\n WHERE id = $1 AND status = $5", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Uuid", - "Text", - "Text", - "Int8", - "Text" - ] - }, - "nullable": [] - }, - "hash": "db1585206cb88ca4a02b4f73b23e10ea7f51bf6c77bca5217040e11f0cf87239" -} diff --git a/.sqlx/query-bf12836a8da8bc01c3eb4ac728568f5777f33a4a250137dfd3b3ba0087741779.json b/.sqlx/query-df7311334c93314352406e1097530e602a575930baf28e91933d9fa9adf7a2ed.json similarity index 59% rename from .sqlx/query-bf12836a8da8bc01c3eb4ac728568f5777f33a4a250137dfd3b3ba0087741779.json rename to .sqlx/query-df7311334c93314352406e1097530e602a575930baf28e91933d9fa9adf7a2ed.json index 987cde9..0b46033 100644 --- a/.sqlx/query-bf12836a8da8bc01c3eb4ac728568f5777f33a4a250137dfd3b3ba0087741779.json +++ b/.sqlx/query-df7311334c93314352406e1097530e602a575930baf28e91933d9fa9adf7a2ed.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO enrollment (course, app_user, enrolled_by, source)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (course, app_user) DO NOTHING\n RETURNING 1 AS \"one\"", + "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\"", "describe": { "columns": [ { @@ -15,12 +15,13 @@ "Uuid", "Uuid", "Uuid", - "Uuid" + "Uuid", + "Int8" ] }, "nullable": [ null ] }, - "hash": "bf12836a8da8bc01c3eb4ac728568f5777f33a4a250137dfd3b3ba0087741779" + "hash": "df7311334c93314352406e1097530e602a575930baf28e91933d9fa9adf7a2ed" } diff --git a/.sqlx/query-46d41617a9a790c57a22c0c5dc3f1d8ff8efa70693c4ea8a67d9980f365499ae.json b/.sqlx/query-e7049ca4ddf6a6103dbecabe61f56992e9e2105e5c2de3b148d5533e4ffc8989.json similarity index 78% rename from .sqlx/query-46d41617a9a790c57a22c0c5dc3f1d8ff8efa70693c4ea8a67d9980f365499ae.json rename to .sqlx/query-e7049ca4ddf6a6103dbecabe61f56992e9e2105e5c2de3b148d5533e4ffc8989.json index 425f963..d198823 100644 --- a/.sqlx/query-46d41617a9a790c57a22c0c5dc3f1d8ff8efa70693c4ea8a67d9980f365499ae.json +++ b/.sqlx/query-e7049ca4ddf6a6103dbecabe61f56992e9e2105e5c2de3b148d5533e4ffc8989.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n password_hash AS \"password_hash: PasswordHash\",\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 avatar_size\n FROM app_user WHERE id = $1 FOR UPDATE", "describe": { "columns": [ { @@ -27,12 +27,12 @@ }, { "ordinal": 2, - "name": "password_hash: PasswordHash", - "type_info": "Text", + "name": "person: PersonId", + "type_info": "Uuid", "origin": { "Table": { "table": "app_user", - "name": "password_hash" + "name": "person" } } }, @@ -199,7 +199,7 @@ "nullable": [ false, false, - false, + true, false, true, true, @@ -216,5 +216,5 @@ true ] }, - "hash": "46d41617a9a790c57a22c0c5dc3f1d8ff8efa70693c4ea8a67d9980f365499ae" + "hash": "e7049ca4ddf6a6103dbecabe61f56992e9e2105e5c2de3b148d5533e4ffc8989" } diff --git a/.sqlx/query-e8a08dbbc2d58b7fd391beea26491ac2c61ac38d35a6805cc95dc2f370822b07.json b/.sqlx/query-e8a08dbbc2d58b7fd391beea26491ac2c61ac38d35a6805cc95dc2f370822b07.json index ce85f06..478d43b 100644 --- a/.sqlx/query-e8a08dbbc2d58b7fd391beea26491ac2c61ac38d35a6805cc95dc2f370822b07.json +++ b/.sqlx/query-e8a08dbbc2d58b7fd391beea26491ac2c61ac38d35a6805cc95dc2f370822b07.json @@ -17,7 +17,7 @@ "Uuid", "Uuid", "Int8", - "Text" + "Uuid" ] }, "nullable": [ diff --git a/.sqlx/query-4dc841ae1b0ad493eb2b63a421ac3dc3e6026d28ac871a0d459a8422cbfd1c65.json b/.sqlx/query-ec3f4c095d63d334a5c0af6ec8c73be375b10814ddef44ace4fca2919dadc8b1.json similarity index 57% rename from .sqlx/query-4dc841ae1b0ad493eb2b63a421ac3dc3e6026d28ac871a0d459a8422cbfd1c65.json rename to .sqlx/query-ec3f4c095d63d334a5c0af6ec8c73be375b10814ddef44ace4fca2919dadc8b1.json index a0aade2..15f70f2 100644 --- a/.sqlx/query-4dc841ae1b0ad493eb2b63a421ac3dc3e6026d28ac871a0d459a8422cbfd1c65.json +++ b/.sqlx/query-ec3f4c095d63d334a5c0af6ec8c73be375b10814ddef44ace4fca2919dadc8b1.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "DELETE FROM solution WHERE question = $1\n RETURNING id AS \"id: SolutionId\", question AS \"question: PoolQuestionId\",\n author AS \"author: UserId\", body AS \"body: SolutionBody\",\n offered_at AS \"offered_at: Timestamp\", image_file,\n image_content_type AS \"image_content_type: FileContentType\",\n image_size", + "query": "DELETE FROM solution WHERE question = $1\n RETURNING id AS \"id: SolutionId\", question AS \"question: PoolQuestionId\",\n author AS \"author: UserId\", body AS \"body: SolutionBody\",\n offered_at AS \"offered_at: Timestamp\"", "describe": { "columns": [ { @@ -57,39 +57,6 @@ "name": "offered_at" } } - }, - { - "ordinal": 5, - "name": "image_file", - "type_info": "Text", - "origin": { - "Table": { - "table": "solution", - "name": "image_file" - } - } - }, - { - "ordinal": 6, - "name": "image_content_type: FileContentType", - "type_info": "Text", - "origin": { - "Table": { - "table": "solution", - "name": "image_content_type" - } - } - }, - { - "ordinal": 7, - "name": "image_size", - "type_info": "Int8", - "origin": { - "Table": { - "table": "solution", - "name": "image_size" - } - } } ], "parameters": { @@ -102,11 +69,8 @@ false, false, false, - false, - true, - true, - true + false ] }, - "hash": "4dc841ae1b0ad493eb2b63a421ac3dc3e6026d28ac871a0d459a8422cbfd1c65" + "hash": "ec3f4c095d63d334a5c0af6ec8c73be375b10814ddef44ace4fca2919dadc8b1" } diff --git a/.sqlx/query-ef02dcc7b39f93369deac9ba8bf0f5875142ea52b528f737165ac0ae7dcb606a.json b/.sqlx/query-ef02dcc7b39f93369deac9ba8bf0f5875142ea52b528f737165ac0ae7dcb606a.json deleted file mode 100644 index e2fc0f6..0000000 --- a/.sqlx/query-ef02dcc7b39f93369deac9ba8bf0f5875142ea52b528f737165ac0ae7dcb606a.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO class_blueprint (grade, courses, creator)\n VALUES ($1, $2, $3)", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Text", - "UuidArray", - "Uuid" - ] - }, - "nullable": [] - }, - "hash": "ef02dcc7b39f93369deac9ba8bf0f5875142ea52b528f737165ac0ae7dcb606a" -} diff --git a/.sqlx/query-f030e7990981531cedf902ef0af1545a25eed85156ad89da42de5792d4a9d4a5.json b/.sqlx/query-f030e7990981531cedf902ef0af1545a25eed85156ad89da42de5792d4a9d4a5.json deleted file mode 100644 index 8c0fc8f..0000000 --- a/.sqlx/query-f030e7990981531cedf902ef0af1545a25eed85156ad89da42de5792d4a9d4a5.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO builder (id, username, password_hash) VALUES ($1, $2, $3)", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Uuid", - "Text", - "Text" - ] - }, - "nullable": [] - }, - "hash": "f030e7990981531cedf902ef0af1545a25eed85156ad89da42de5792d4a9d4a5" -} diff --git a/.sqlx/query-f033efcb08101eb7c3873abe1b079ccb175dc1dcacf75910ad9aa45d23210583.json b/.sqlx/query-f033efcb08101eb7c3873abe1b079ccb175dc1dcacf75910ad9aa45d23210583.json new file mode 100644 index 0000000..12a89d5 --- /dev/null +++ b/.sqlx/query-f033efcb08101eb7c3873abe1b079ccb175dc1dcacf75910ad9aa45d23210583.json @@ -0,0 +1,17 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO builder (id, username, password_hash, created_at) VALUES ($1, $2, $3, $4)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Text", + "Text", + "Int8" + ] + }, + "nullable": [] + }, + "hash": "f033efcb08101eb7c3873abe1b079ccb175dc1dcacf75910ad9aa45d23210583" +} diff --git a/.sqlx/query-1b109ac4162684c4444aac1b25716ca51fbcfeaee5adc3d8ab8216a2b1ae22b9.json b/.sqlx/query-f64594c9dd40fc944bcc77ae1bf62adc1a6d90c8cf53d4807dfa4db26d4faf41.json similarity index 80% rename from .sqlx/query-1b109ac4162684c4444aac1b25716ca51fbcfeaee5adc3d8ab8216a2b1ae22b9.json rename to .sqlx/query-f64594c9dd40fc944bcc77ae1bf62adc1a6d90c8cf53d4807dfa4db26d4faf41.json index 78b72ad..534e8ba 100644 --- a/.sqlx/query-1b109ac4162684c4444aac1b25716ca51fbcfeaee5adc3d8ab8216a2b1ae22b9.json +++ b/.sqlx/query-f64594c9dd40fc944bcc77ae1bf62adc1a6d90c8cf53d4807dfa4db26d4faf41.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 password_hash AS \"password_hash: PasswordHash\",\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 avatar_size", "describe": { "columns": [ { @@ -27,12 +27,12 @@ }, { "ordinal": 2, - "name": "password_hash: PasswordHash", - "type_info": "Text", + "name": "person: PersonId", + "type_info": "Uuid", "origin": { "Table": { "table": "app_user", - "name": "password_hash" + "name": "person" } } }, @@ -200,7 +200,7 @@ "nullable": [ false, false, - false, + true, false, true, true, @@ -217,5 +217,5 @@ true ] }, - "hash": "1b109ac4162684c4444aac1b25716ca51fbcfeaee5adc3d8ab8216a2b1ae22b9" + "hash": "f64594c9dd40fc944bcc77ae1bf62adc1a6d90c8cf53d4807dfa4db26d4faf41" } diff --git a/.sqlx/query-168ce1cc3188b7e1ede75b8f783562f54c39ead09a8e41dc8d8ded3e1fcccef3.json b/.sqlx/query-fcce69f1324abd0a60651f5f0bc3f0bcfbdf42be5b2f34f79a40d3c741055135.json similarity index 77% rename from .sqlx/query-168ce1cc3188b7e1ede75b8f783562f54c39ead09a8e41dc8d8ded3e1fcccef3.json rename to .sqlx/query-fcce69f1324abd0a60651f5f0bc3f0bcfbdf42be5b2f34f79a40d3c741055135.json index 8cba855..99c99ea 100644 --- a/.sqlx/query-168ce1cc3188b7e1ede75b8f783562f54c39ead09a8e41dc8d8ded3e1fcccef3.json +++ b/.sqlx/query-fcce69f1324abd0a60651f5f0bc3f0bcfbdf42be5b2f34f79a40d3c741055135.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO app_user (id, username, password_hash, role)\n VALUES ($1, $2, $3, $4)\n RETURNING id AS \"id: UserId\",\n username AS \"username: Username\",\n password_hash AS \"password_hash: PasswordHash\",\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 avatar_size", "describe": { "columns": [ { @@ -27,12 +27,12 @@ }, { "ordinal": 2, - "name": "password_hash: PasswordHash", - "type_info": "Text", + "name": "person: PersonId", + "type_info": "Uuid", "origin": { "Table": { "table": "app_user", - "name": "password_hash" + "name": "person" } } }, @@ -195,14 +195,15 @@ "Left": [ "Uuid", "Text", + "Uuid", "Text", - "Text" + "Int8" ] }, "nullable": [ false, false, - false, + true, false, true, true, @@ -219,5 +220,5 @@ true ] }, - "hash": "168ce1cc3188b7e1ede75b8f783562f54c39ead09a8e41dc8d8ded3e1fcccef3" + "hash": "fcce69f1324abd0a60651f5f0bc3f0bcfbdf42be5b2f34f79a40d3c741055135" } diff --git a/migrations/control/20260912000001_control.sql b/migrations/control/20260912000001_control.sql index 79fb5a3..cbc8400 100644 --- a/migrations/control/20260912000001_control.sql +++ b/migrations/control/20260912000001_control.sql @@ -23,9 +23,12 @@ -- `tier:client:window` key, so the PK is TEXT. CREATE TABLE school ( + -- Immutable: a rename is blocked by the school_slug primary key below and + -- by the per-school database name ({control}_school_{slug}) minted from + -- it — a slug change would orphan the database. slug TEXT NOT NULL, name TEXT NOT NULL, - status TEXT NOT NULL CHECK (status IN ('active', 'suspended')), + status TEXT NOT NULL CONSTRAINT school_status CHECK (status IN ('active', 'suspended')), created_at BIGINT NOT NULL, -- Which product modules this school has bought; names bound from -- Module::ALL at write time, never spelled here. @@ -37,6 +40,7 @@ CREATE TABLE builder ( id uuid PRIMARY KEY, username TEXT NOT NULL, password_hash TEXT NOT NULL, + created_at BIGINT NOT NULL, CONSTRAINT builder_username UNIQUE (username) ); diff --git a/migrations/control/20260913000001_person.sql b/migrations/control/20260913000001_person.sql index 376f781..47054bb 100644 --- a/migrations/control/20260913000001_person.sql +++ b/migrations/control/20260913000001_person.sql @@ -19,6 +19,7 @@ CREATE TABLE person ( id uuid PRIMARY KEY, username TEXT NOT NULL, password_hash TEXT NOT NULL, + created_at BIGINT NOT NULL, -- Globally unique: the same username in two school databases is one and -- the same person, copied into each school's `app_user`. CONSTRAINT person_username UNIQUE (username) @@ -27,6 +28,7 @@ CREATE TABLE person ( CREATE TABLE person_school ( person uuid NOT NULL REFERENCES person(id) ON DELETE NO ACTION, school TEXT NOT NULL REFERENCES school(slug) ON DELETE NO ACTION, + created_at BIGINT NOT NULL, CONSTRAINT person_school_person_school PRIMARY KEY (person, school) ); @@ -40,3 +42,5 @@ CREATE TABLE person_session ( ); CREATE INDEX person_session_expires ON person_session (expires_at); + +CREATE INDEX person_session_person ON person_session (person); diff --git a/migrations/school/20260912000001_identity.sql b/migrations/school/20260912000001_identity.sql index 2dffc3b..50d65b2 100644 --- a/migrations/school/20260912000001_identity.sql +++ b/migrations/school/20260912000001_identity.sql @@ -33,10 +33,14 @@ -- statuses / exam kinds are school-configurable at runtime, which a DDL -- CHECK could not survive. +-- The school-side identity row. The password hash is NOT here: the credential +-- lives on the control database's `person` row, and `app_user.person` is the +-- join key to it (uuid, no FK — the two halves are separate databases). The +-- `username` copy stays for display and for the school-scoped unique name. CREATE TABLE app_user ( id uuid PRIMARY KEY, username TEXT NOT NULL, - password_hash TEXT NOT NULL, + person uuid NULL, role TEXT NOT NULL DEFAULT 'student' CHECK (role IN ('ai', 'parent', 'student', 'teacher', 'manager', 'admin')), name TEXT NULL, @@ -74,9 +78,15 @@ CREATE TABLE app_user ( study_streak_last_day BIGINT NULL, pomodoro_counted_today BIGINT NOT NULL DEFAULT 0, pomodoro_counted_day BIGINT NULL, + created_at BIGINT NOT NULL, CONSTRAINT app_user_username UNIQUE (username) ); +-- At most one school identity per person: the join key is 1:1. Partial +-- because a school row minted before its person was known (boot seed order) +-- legally reads NULL. +CREATE UNIQUE INDEX app_user_person ON app_user (person) WHERE person IS NOT NULL; + CREATE TABLE user_session ( id uuid PRIMARY KEY, app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, diff --git a/migrations/school/20260912000002_courses.sql b/migrations/school/20260912000002_courses.sql index a8f0b47..1bfae7a 100644 --- a/migrations/school/20260912000002_courses.sql +++ b/migrations/school/20260912000002_courses.sql @@ -22,7 +22,22 @@ CREATE TABLE term ( course_count BIGINT NOT NULL DEFAULT 0, class_count BIGINT NOT NULL DEFAULT 0 ); - +-- A term is dropped, not cascaded: the nullable `term` FKs on course and +-- class_group (ON DELETE NO ACTION) must be cleared to NULL first — a delete +-- with a reference still standing is a 23503, not a sweep. The stored +-- course_count/class_count are the pre-flight counters that refuse the drop +-- before the FKs get the chance. + +-- db::course::delete sweeps every child in ONE transaction — a crash between +-- statements must orphan nothing — so the guard is the course row itself: +-- locked FOR UPDATE and refused while its enrollment_count is non-zero. The +-- child order is the FK-safest one: exam results/attempts/answers/images and +-- questions, homework files/submissions/results, rag output, note files and +-- notes, class_course links (each class gets its class_course_count back and +-- every blueprint drops the id from its list), session_attendance and +-- course_session, enrollment (each seat given back), then the exam, homework +-- and subject rows themselves. Bank questions keep their templates; only +-- their subject/source_exam links are cleared. CREATE TABLE course ( id uuid PRIMARY KEY, creator uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, @@ -106,10 +121,10 @@ CREATE TABLE session_attendance ( course uuid NOT NULL REFERENCES 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_session ON session_attendance (session); CREATE INDEX session_attendance_user ON session_attendance (app_user); CREATE INDEX session_attendance_course ON session_attendance (course); @@ -126,12 +141,17 @@ CREATE TABLE class_group ( CREATE INDEX class_group_grade ON class_group (grade); --- A grade's course template. The grade label IS the record key in Surreal, so --- the PK here is TEXT on grade itself (no id column, no uuid). +-- A grade's course template. The grade label is the identity the whole API +-- speaks and it stays UNIQUE, but the row carries a surrogate uuid PK: it is +-- what class_course.source references, and a delete-and-recreate of the same +-- grade mints a new id, so links tagged by the old one were swept by that +-- delete instead of being adopted by the new blueprint (a TEXT grade tag +-- made the two indistinguishable). CREATE TABLE class_blueprint ( - grade TEXT PRIMARY KEY, - courses uuid[] NOT NULL DEFAULT '{}', - creator uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION + id uuid PRIMARY KEY, + grade TEXT NOT NULL CONSTRAINT class_blueprint_grade_key UNIQUE, + courses uuid[] NOT NULL DEFAULT '{}', + creator uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION ); CREATE TABLE class_member ( @@ -143,7 +163,6 @@ CREATE TABLE class_member ( CONSTRAINT class_member_class_user PRIMARY KEY (class, app_user) ); -CREATE INDEX class_member_class ON class_member (class); CREATE INDEX class_member_user ON class_member (app_user); CREATE TABLE class_course ( @@ -153,17 +172,17 @@ CREATE TABLE class_course ( attached_at BIGINT NULL, -- The blueprint that attached this course; NULL = attached by hand, which -- keeps a hand-attached course unreachable by every blueprint sweep. - source TEXT NULL REFERENCES class_blueprint(grade) ON DELETE NO ACTION, + source uuid NULL REFERENCES class_blueprint(id) ON DELETE NO ACTION, CONSTRAINT class_course_class_course PRIMARY KEY (class, course) ); -CREATE INDEX class_course_class ON class_course (class); CREATE INDEX class_course_course ON class_course (course); CREATE TABLE enrollment ( course uuid NOT NULL REFERENCES 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, + created_at BIGINT NOT NULL, -- The class that pumped this row; NULL when a human placed the student. source uuid NULL REFERENCES class_group(id) ON DELETE NO ACTION, CONSTRAINT enrollment_course_user PRIMARY KEY (course, app_user) @@ -193,6 +212,7 @@ CREATE TABLE attendance ( app_user uuid NOT NULL REFERENCES app_user(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 attendance_event_user PRIMARY KEY (event, app_user) ); @@ -202,6 +222,7 @@ CREATE TABLE registration ( event uuid NOT NULL REFERENCES event(id) ON DELETE NO ACTION, app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, registered_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + created_at BIGINT NOT NULL, CONSTRAINT registration_event_user PRIMARY KEY (event, app_user) ); diff --git a/migrations/school/20260912000003_exams.sql b/migrations/school/20260912000003_exams.sql index 5a484ce..f3285fd 100644 --- a/migrations/school/20260912000003_exams.sql +++ b/migrations/school/20260912000003_exams.sql @@ -67,7 +67,11 @@ CREATE TABLE exam_question ( -- question was inserted from, banked_as = the template most recently -- minted by saving it into the bank. from_bank uuid NULL REFERENCES bank_question(id) ON DELETE NO ACTION, - banked_as uuid NULL REFERENCES bank_question(id) ON DELETE NO ACTION + banked_as uuid NULL REFERENCES bank_question(id) ON DELETE NO ACTION, + -- The composite target of every (exam, question) foreign key below: an + -- answer or image pair can only name a question that belongs to that + -- exam, so the two columns can never disagree about the owner. + CONSTRAINT exam_question_id_exam UNIQUE (id, exam) ); CREATE INDEX exam_question_exam ON exam_question (exam); @@ -87,8 +91,8 @@ CREATE TABLE bank_question_image ( ); CREATE TABLE question_image ( - exam uuid NOT NULL REFERENCES exam(id) ON DELETE NO ACTION, - question uuid NOT NULL REFERENCES exam_question(id) ON DELETE NO ACTION, + exam uuid NOT NULL, + question uuid NOT NULL, -- NULL = the question's own illustration; otherwise the choice's id. A -- (question, slot) pair holds at most one picture, and a question holds -- at most one illustration — NULLS NOT DISTINCT is what makes the NULL @@ -97,7 +101,11 @@ CREATE TABLE question_image ( 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_question_slot UNIQUE NULLS NOT DISTINCT (question, slot), + -- One composite key instead of the old two single-column ones: the pair + -- must resolve to one exam_question row, not two that could disagree. + 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); @@ -113,31 +121,33 @@ CREATE TABLE exam_attempt ( CONSTRAINT exam_attempt_exam_user_seq PRIMARY KEY (exam, app_user, seq) ); -CREATE INDEX exam_attempt_exam ON exam_attempt (exam); CREATE TABLE exam_answer ( - exam uuid NOT NULL REFERENCES exam(id) ON DELETE NO ACTION, - question uuid NOT NULL REFERENCES exam_question(id) ON DELETE NO ACTION, + 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_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 INDEX exam_answer_exam ON exam_answer (exam); CREATE TABLE answer_image ( - exam uuid NOT NULL REFERENCES exam(id) ON DELETE NO ACTION, - question uuid NOT NULL REFERENCES exam_question(id) ON DELETE NO ACTION, + 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_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); @@ -148,6 +158,9 @@ CREATE TABLE exam_result ( 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, + -- When this mark was written (now-millis, stamped by the grader's own + -- transaction); a regrade of the sitting overwrites it. + graded_at BIGINT NOT NULL, seq BIGINT NOT NULL DEFAULT 1, CONSTRAINT exam_result_exam_user_seq PRIMARY KEY (exam, app_user, seq) ); @@ -159,10 +172,7 @@ CREATE TABLE pool_question ( body TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', asked_at BIGINT NOT NULL, - approved_by uuid NULL REFERENCES app_user(id) ON DELETE NO ACTION, - image_file TEXT NULL, - image_content_type TEXT NULL, - image_size BIGINT NULL + approved_by uuid NULL REFERENCES app_user(id) ON DELETE NO ACTION ); CREATE INDEX pool_question_status ON pool_question (status); @@ -173,14 +183,31 @@ CREATE TABLE solution ( question uuid NOT NULL REFERENCES pool_question(id) ON DELETE NO ACTION, author uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, body TEXT NOT NULL, - offered_at BIGINT NOT NULL, - image_file TEXT NULL, - image_content_type TEXT NULL, - image_size BIGINT NULL + offered_at BIGINT NOT NULL ); CREATE INDEX solution_question ON solution (question); +-- The pool photos, one row per question/solution — the single-slot spelling +-- of question_image's child-table shape: the parent rows carry no image +-- columns, the metadata lives here, and the bytes live on disk under the +-- `file` name. The primary key IS the "one image" rule; a replace is a +-- plain upsert. +CREATE TABLE pool_question_image ( + question uuid PRIMARY KEY REFERENCES pool_question(id) ON DELETE NO ACTION, + file TEXT NOT NULL, + content_type TEXT NOT NULL, + size BIGINT NOT NULL +); + +CREATE TABLE solution_image ( + solution uuid PRIMARY KEY REFERENCES solution(id) ON DELETE NO ACTION, + file TEXT NOT NULL, + content_type TEXT NOT NULL, + size BIGINT NOT NULL +); + + CREATE TABLE homework ( id uuid PRIMARY KEY, course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION, @@ -222,6 +249,8 @@ CREATE TABLE homework_submission ( -- The on-time verdict credited at the first hand-in, never re-judged. counted_on_time BOOLEAN NULL, -- The grade that froze this submission; NULL while it is still open. + -- NO ACTION orders the deletes: this row must be removed before the + -- homework_result it points at. graded_by_result uuid NULL REFERENCES homework_result(id) ON DELETE NO ACTION, -- Same deterministic pair as homework_result: one submission per -- (homework, user) by construction. diff --git a/migrations/school/20260912000004_food_appointments_fees.sql b/migrations/school/20260912000004_food_appointments_fees.sql index 5edc0c0..87ee8cd 100644 --- a/migrations/school/20260912000004_food_appointments_fees.sql +++ b/migrations/school/20260912000004_food_appointments_fees.sql @@ -66,7 +66,10 @@ CREATE INDEX appointment_status ON appointment (status); -- A published menu per day+slot. `date` is a calendar day as YYYY-MM-DD -- text (an equality key, not a timestamp); `slot` is snapshotted text, so --- retiring a slot in settings never rewrites a past menu. +-- retiring a slot in settings never rewrites a past menu. Deleting a menu +-- sweeps its menu_dish and meal_attendance rows (the children go first — +-- both FKs are NO ACTION) and never meal_booking: those rows carry no FK +-- and survive the delete, auditable against the ledger lines they charged. CREATE TABLE menu ( -- The {date}_{slot} derived key — it IS the URL segment — with the two -- components kept as their own columns (the unique pair keeps the old @@ -130,7 +133,6 @@ CREATE TABLE meal_booking ( CONSTRAINT meal_booking_menu_student PRIMARY KEY (menu, student) ); -CREATE INDEX meal_booking_menu ON meal_booking (menu); CREATE INDEX meal_booking_student ON meal_booking (student); CREATE TABLE meal_attendance ( diff --git a/src/constant.rs b/src/constant.rs index 39b498c..1482754 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -864,7 +864,9 @@ pub const SETTINGS_TABLE: &str = "settings"; pub const TERM_TABLE: &str = "term"; pub const SUBJECT_TABLE: &str = "subject"; pub const POOL_QUESTION_TABLE: &str = "pool_question"; +pub const POOL_QUESTION_IMAGE_TABLE: &str = "pool_question_image"; pub const SOLUTION_TABLE: &str = "solution"; +pub const SOLUTION_IMAGE_TABLE: &str = "solution_image"; pub const HOMEWORK_TABLE: &str = "homework"; pub const HOMEWORK_SUBMISSION_TABLE: &str = "homework_submission"; pub const HOMEWORK_FILE_TABLE: &str = "homework_file"; diff --git a/src/db/answer_image.rs b/src/db/answer_image.rs index 1c45e3c..736a896 100644 --- a/src/db/answer_image.rs +++ b/src/db/answer_image.rs @@ -243,7 +243,7 @@ mod tests { /// foreign key now. async fn a_student(db: &Database) -> UserId { let user = UserId::from_key("019732e3-7b00-7000-8000-00000000a11a"); - sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, 'a11a', 'x')") + sqlx::query("INSERT INTO app_user (id, username, created_at) VALUES ($1, 'a11a', 0)") .bind(user.uuid()) .execute(db) .await @@ -327,7 +327,7 @@ mod tests { // Another student's drawing for the same question/sitting is its own row. let other = UserId::generate(); - sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, 'b22b', 'x')") + sqlx::query("INSERT INTO app_user (id, username, created_at) VALUES ($1, 'b22b', 0)") .bind(other.uuid()) .execute(&db) .await diff --git a/src/db/attendance.rs b/src/db/attendance.rs index 8578a67..1ed23fe 100644 --- a/src/db/attendance.rs +++ b/src/db/attendance.rs @@ -7,6 +7,7 @@ use crate::database::{Database, tx_with_retry}; use crate::db::page::PagedList; use crate::domain::attendance::{Attendance, AttendanceStatus}; use crate::domain::event::EventId; +use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; use sqlx::query_as; @@ -53,15 +54,16 @@ pub async fn mark( } let row = query_as!( Attendance, - "INSERT INTO attendance (event, app_user, status, marked_by) - VALUES ($1, $2, $3, $4) - ON CONFLICT (event, app_user) DO UPDATE SET status = $3, marked_by = $4 + "INSERT INTO attendance (event, app_user, status, marked_by, marked_at) + VALUES ($1, $2, $3, $4, $5) + ON CONFLICT (event, app_user) DO UPDATE SET status = $3, marked_by = $4, marked_at = $5 RETURNING event AS \"event: EventId\", app_user AS \"user: UserId\", \ status AS \"status: AttendanceStatus\", marked_by AS \"marked_by: UserId\"", event.uuid(), user.uuid(), status.as_str(), - marked_by.uuid() + marked_by.uuid(), + Timestamp::now().as_millis(), ) .fetch_one(&mut *tx) .await?; @@ -148,8 +150,8 @@ mod tests { async fn a_person(db: &Database, label: &str) -> UserId { let user = UserId::generate(); sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, $2, 'x', 'teacher')", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, 'teacher')", ) .bind(user.uuid()) .bind(format!("{label}-{}", &user.key()[30..])) diff --git a/src/db/badge.rs b/src/db/badge.rs index 901952b..495e9f9 100644 --- a/src/db/badge.rs +++ b/src/db/badge.rs @@ -125,20 +125,12 @@ mod tests { use super::*; use crate::constant::BADGE_AWARD_TABLE; use crate::database::init_test_db; - use crate::domain::user::{Password, Username}; + use crate::domain::user::Username; async fn a_user(username: &str, db: &Database) -> crate::domain::user::User { - crate::db::user::create( - db, - Username::try_new(username).unwrap(), - Password::try_new("secret1") - .unwrap() - .hash_async() - .await - .unwrap(), - ) - .await - .unwrap() + crate::db::user::create(db, Username::try_new(username).unwrap(), None) + .await + .unwrap() } async fn count_awards(db: &Database, user: &UserId) -> i64 { diff --git a/src/db/bank_question.rs b/src/db/bank_question.rs index 7f50988..59b16d4 100644 --- a/src/db/bank_question.rs +++ b/src/db/bank_question.rs @@ -398,7 +398,7 @@ mod tests { /// minted per call, so repeated calls are new people, not the same row. async fn a_person(db: &Database, label: &str) -> UserId { let user = UserId::generate(); - sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, $2, 'x')") + sqlx::query("INSERT INTO app_user (id, username, created_at) VALUES ($1, $2, 0)") .bind(user.uuid()) .bind(format!("{label}-{}", &user.key()[30..])) .execute(db) diff --git a/src/db/bank_question_image.rs b/src/db/bank_question_image.rs index df6ea8b..59426f3 100644 --- a/src/db/bank_question_image.rs +++ b/src/db/bank_question_image.rs @@ -196,8 +196,8 @@ mod tests { let id = BankQuestionId::generate(); let owner = crate::domain::user::UserId::generate(); sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, $2, 'x', 'teacher')", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, 'teacher')", ) .bind(owner.uuid()) .bind(format!("bqi-owner-{}", &owner.key()[30..])) diff --git a/src/db/builder.rs b/src/db/builder.rs index 0dae33f..b523dbb 100644 --- a/src/db/builder.rs +++ b/src/db/builder.rs @@ -46,10 +46,11 @@ pub async fn read(db: &Database, id: &BuilderId) -> Result, AppE /// constraint stands guard regardless. pub async fn create(db: &Database, builder: Builder) -> Result<(), AppError> { sqlx::query!( - "INSERT INTO builder (id, username, password_hash) VALUES ($1, $2, $3)", + "INSERT INTO builder (id, username, password_hash, created_at) VALUES ($1, $2, $3, $4)", builder.id.uuid(), builder.username.as_str(), builder.password_hash.as_str(), + Timestamp::now().as_millis(), ) .execute(db) .await?; diff --git a/src/db/chatbot_message.rs b/src/db/chatbot_message.rs index 63d4efe..357f819 100644 --- a/src/db/chatbot_message.rs +++ b/src/db/chatbot_message.rs @@ -324,8 +324,8 @@ mod tests { let user = UserId::from_key("019732e3-7b00-7000-8000-00000000cafe"); let thread = ChatbotThreadId::from_key("019732e3-7b00-7000-8000-00000000beef"); sqlx::query( - "INSERT INTO app_user (id, username, password_hash) \ - VALUES ($1, 'chat-fixture', 'x')", + "INSERT INTO app_user (id, username, created_at) \ + VALUES ($1, 'chat-fixture', 0)", ) .bind(user.uuid()) .execute(&db) diff --git a/src/db/chatbot_thread.rs b/src/db/chatbot_thread.rs index a95d366..2bef1b2 100644 --- a/src/db/chatbot_thread.rs +++ b/src/db/chatbot_thread.rs @@ -224,7 +224,7 @@ mod tests { async fn a_user_capped_at(threads: i64) -> (Database, crate::database::TestDatabases) { let (db, leases) = crate::database::init_test_db().await; - sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, 'u', 'x')") + sqlx::query("INSERT INTO app_user (id, username, created_at) VALUES ($1, 'u', 0)") .bind(UserId::from_key(U).uuid()) .execute(&db) .await diff --git a/src/db/class_blueprint.rs b/src/db/class_blueprint.rs index c3a0713..223bf8c 100644 --- a/src/db/class_blueprint.rs +++ b/src/db/class_blueprint.rs @@ -13,6 +13,7 @@ use crate::db::page::PagedList; use crate::domain::class_blueprint::{ClassBlueprint, ClassBlueprintId}; use crate::domain::class_group::{ClassGrade, ClassGroupId}; use crate::domain::course::CourseId; +use crate::domain::monotonic_id::next_uuid; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -67,9 +68,11 @@ fn no_such_course() -> AppError { } /// Write the blueprint's row. A second one for the same grade is a 409 the -/// store itself decides — the grade is the primary key, so the duplicate is -/// seen rather than raced (`23505` on `class_blueprint_pkey`, mapped right -/// here: a duplicate is a decision, never a retry). +/// store itself decides — the grade carries a UNIQUE constraint, so the +/// duplicate is seen rather than raced (`23505` on +/// `class_blueprint_grade_key`, mapped right here: a duplicate is a +/// decision, never a retry). The surrogate `id` is minted here and never +/// read back: the grade label stays the only identity the API speaks. pub async fn create( db: &Database, creator: &UserId, @@ -83,11 +86,13 @@ pub async fn create( creator: *creator, }; let creator = *creator; + let id = next_uuid(); tx_with_retry(db, false, async move |tx| { courses_alive(tx, &courses).await?; let inserted = sqlx::query!( - r#"INSERT INTO class_blueprint (grade, courses, creator) - VALUES ($1, $2, $3)"#, + r#"INSERT INTO class_blueprint (id, grade, courses, creator) + VALUES ($1, $2, $3, $4)"#, + id, grade as _, courses as _, creator as _ @@ -96,7 +101,7 @@ pub async fn create( .await; match inserted { Ok(_) => Ok(blueprint.clone()), - Err(e) if unique_violation(&e) == Some("class_blueprint_pkey") => Err( + Err(e) if unique_violation(&e) == Some("class_blueprint_grade_key") => Err( AppError::Conflict("a blueprint already exists for that grade"), ), Err(e) => Err(e.into()), @@ -315,6 +320,9 @@ pub async fn prune( /// it. The rows are read rather than derived from the classes at this grade: /// a class whose grade was edited after the pump still carries this /// blueprint's attachments, and only the tag can find it. +/// +/// The stored tag is the blueprint's surrogate uuid, not the grade label the +/// API speaks — the query translates the label to it. pub async fn sourced_links( db: &Database, id: &ClassBlueprintId, @@ -324,7 +332,8 @@ pub async fn sourced_links( let rows = sqlx::query!( r#"SELECT class AS "class: ClassGroupId", course AS "course: CourseId" FROM class_course - WHERE source = $1 AND course <> ALL($2)"#, + WHERE source = (SELECT id FROM class_blueprint WHERE grade = $1) + AND course <> ALL($2)"#, id as _, keep as _ ) diff --git a/src/db/class_course.rs b/src/db/class_course.rs index a19336c..1b492ec 100644 --- a/src/db/class_course.rs +++ b/src/db/class_course.rs @@ -49,8 +49,17 @@ pub async fn list_for_class( 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!("{CLASS_COURSE_TABLE} WHERE class = $1"), + format!( + "(SELECT cc.class, cc.course, cc.attached_by, cc.attached_at, \ + b.grade AS source \ + 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", ) .bind(class.uuid()) diff --git a/src/db/class_group.rs b/src/db/class_group.rs index 0bb3021..f7b9bb7 100644 --- a/src/db/class_group.rs +++ b/src/db/class_group.rs @@ -313,8 +313,8 @@ mod tests { // The username is unique: a second call for the same name must adopt // the existing row, not collide with it. sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, $2, 'x', 'teacher') ON CONFLICT DO NOTHING", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, 'teacher') ON CONFLICT DO NOTHING", ) .bind(UserId::generate().uuid()) .bind(username) diff --git a/src/db/class_member.rs b/src/db/class_member.rs index bba1c31..23c4071 100644 --- a/src/db/class_member.rs +++ b/src/db/class_member.rs @@ -62,8 +62,8 @@ pub(crate) mod tests { /// fixture actors are rows, not fabricated ids. pub(crate) async fn fixture_user(db: &Database, username: &str) -> UserId { sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, $2, 'x', 'student') ON CONFLICT DO NOTHING", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, 'student') ON CONFLICT DO NOTHING", ) .bind(crate::domain::user::UserId::generate().uuid()) .bind(username) diff --git a/src/db/class_pump.rs b/src/db/class_pump.rs index 192157a..feb6610 100644 --- a/src/db/class_pump.rs +++ b/src/db/class_pump.rs @@ -242,6 +242,10 @@ fn refusal_of(early: Early) -> Attached { /// is the weakest strength that blocks the delete, so two sourced attaches /// still run concurrently, exactly as they did under the old shared read /// lease. +/// +/// The same locked read resolves the surrogate `id` the link row will +/// store: the stored tag is that uuid, not the grade label the API +/// speaks, and it rides out of this gate to the insert below. /// 3. **Pivot** — the member axis takes the [`cap` role-claim /// recipe](crate::db::cap)'s `FOR NO KEY UPDATE` handshake on the user row: /// a role change away from `student` sweeps this membership, and demotion @@ -258,7 +262,7 @@ async fn early_verdicts( axis: Axis, pivot: Pivot<'_>, source: Option<&ClassBlueprintId>, -) -> Result, AppError> { +) -> 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"#, @@ -278,19 +282,23 @@ async fn early_verdicts( .is_some(), }; if held { - return Ok(Some(Early::Duplicate)); + return Ok((Some(Early::Duplicate), None)); } + // The lock and the resolution are one read: the stored `source` is the + // blueprint's surrogate uuid, and the row this read returns it from is + // the very row the KEY SHARE lock holds against the blueprint's delete. + let mut source_id = None; if let Some(source) = source { - let alive = sqlx::query_scalar!( - r#"SELECT 1 AS "one" FROM class_blueprint WHERE grade = $1 FOR KEY SHARE"#, + let locked = sqlx::query_scalar!( + r#"SELECT id FROM class_blueprint WHERE grade = $1 FOR KEY SHARE"#, source as _ ) .fetch_optional(&mut *tx) - .await? - .is_some(); - if !alive { - return Ok(Some(Early::SourceGone)); - } + .await?; + let Some(id) = locked else { + return Ok((Some(Early::SourceGone), None)); + }; + source_id = Some(id); } match pivot { Pivot::User(user) => { @@ -301,7 +309,7 @@ async fn early_verdicts( .fetch_optional(&mut *tx) .await?; if row.map(|row| row.role) != Some(Role::Student) { - return Ok(Some(Early::PivotGone)); + return Ok((Some(Early::PivotGone), None)); } } Pivot::Course(course) => { @@ -313,7 +321,7 @@ async fn early_verdicts( .await? .is_some(); if !alive { - return Ok(Some(Early::PivotGone)); + return Ok((Some(Early::PivotGone), None)); } } } @@ -339,7 +347,7 @@ async fn early_verdicts( .await? .is_some(), }; - Ok(over.then_some(Early::Overloaded)) + Ok((over.then_some(Early::Overloaded), source_id)) } /// Write the member link and enroll the student into every course the class is @@ -368,9 +376,9 @@ pub(crate) async fn add_member( let class = class.clone(); let (user, by) = (*user, *by); let outcome = tx_with_retry(db, false, async move |tx| { - if let Some(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)); } // The claim and the link are one statement (the cap recipe's CTE): the @@ -463,15 +471,15 @@ pub(crate) async fn attach_course( let by = *by; let source = source.cloned(); let outcome = tx_with_retry(db, false, async move |tx| { - if let Some(early) = early_verdicts( + let (early, source_id) = early_verdicts( tx, &class, Axis::Course, Pivot::Course(&course), source.as_ref(), ) - .await? - { + .await?; + if let Some(early) = early { return Ok(refusal_of(early)); } let inserted = match sqlx::query_scalar!( @@ -487,7 +495,7 @@ pub(crate) async fn attach_course( course as _, by as _, attached_at as _, - source as _ + source_id, ) .fetch_optional(&mut *tx) .await @@ -577,6 +585,7 @@ async fn enroll_pairs( pairs: impl Iterator, by: &UserId, ) -> Result<(), AppError> { + let now = Timestamp::now(); for (course, user) in pairs { let held = sqlx::query_scalar!( r#"SELECT 1 AS "one" FROM enrollment WHERE course = $1 AND app_user = $2"#, @@ -610,14 +619,15 @@ async fn enroll_pairs( return Err(AppError::Internal(format!("{COURSE_FULL_MARK}{course}"))); } let wrote = sqlx::query_scalar!( - r#"INSERT INTO enrollment (course, app_user, enrolled_by, source) - VALUES ($1, $2, $3, $4) + r#"INSERT INTO enrollment (course, app_user, enrolled_by, source, created_at) + VALUES ($1, $2, $3, $4, $5) ON CONFLICT (course, app_user) DO NOTHING RETURNING 1 AS "one""#, course, user, by as _, - class as _ + class as _, + now.as_millis() ) .fetch_optional(&mut *tx) .await; @@ -757,7 +767,8 @@ pub(crate) async fn detach_course( let gone = match &source { Some(source) => { sqlx::query_scalar!( - r#"DELETE FROM class_course WHERE class = $1 AND course = $2 AND source = $3 + r#"DELETE FROM class_course WHERE class = $1 AND course = $2 + AND source = (SELECT id FROM class_blueprint WHERE grade = $3) RETURNING 1 AS "one""#, class as _, course as _, diff --git a/src/db/course.rs b/src/db/course.rs index 56eb036..3e3db5a 100644 --- a/src/db/course.rs +++ b/src/db/course.rs @@ -577,8 +577,8 @@ pub(crate) async fn a_test_course(db: &Database) -> CourseId { // repeated calls are new people, not the same one. let creator = UserId::generate(); sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, $2, 'x', 'teacher')", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, 'teacher')", ) .bind(creator.uuid()) .bind(format!("course-fixture-{}", &creator.key()[30..])) @@ -717,8 +717,8 @@ mod tests { async fn a_person(db: &Database, label: &str, role: &str) -> UserId { let user = UserId::generate(); sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, $2, 'x', $3)", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, $3)", ) .bind(user.uuid()) .bind(format!("{label}-{}", &user.key()[30..])) diff --git a/src/db/course_note_file.rs b/src/db/course_note_file.rs index 3a71a36..26c4ff9 100644 --- a/src/db/course_note_file.rs +++ b/src/db/course_note_file.rs @@ -168,7 +168,7 @@ mod tests { /// A real `app_user` row: authors and creators are foreign keys now. async fn a_person(db: &Database) -> crate::domain::user::UserId { let user = crate::domain::user::UserId::generate(); - sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, $2, 'x')") + sqlx::query("INSERT INTO app_user (id, username, created_at) VALUES ($1, $2, 0)") .bind(user.uuid()) .bind(format!("cnf-{}", &user.key()[30..])) .execute(db) diff --git a/src/db/course_session.rs b/src/db/course_session.rs index 9c3a113..03d1e89 100644 --- a/src/db/course_session.rs +++ b/src/db/course_session.rs @@ -180,8 +180,8 @@ mod tests { // The creator is a foreign key now: a real `app_user` row. let creator = UserId::generate(); sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, $2, 'x', 'teacher')", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, 'teacher')", ) .bind(creator.uuid()) .bind(format!("session-race-{}", &creator.key()[30..])) diff --git a/src/db/enrollment.rs b/src/db/enrollment.rs index f1e91ee..4119782 100644 --- a/src/db/enrollment.rs +++ b/src/db/enrollment.rs @@ -11,6 +11,7 @@ use crate::domain::class_group::ClassGroupId; use crate::domain::course::CourseId; use crate::domain::enrollment::Enrollment; use crate::domain::role::Role; +use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -62,6 +63,7 @@ pub async fn enroll( } let course_id = course.clone(); let (user_id, enrolled_by_id) = (*user, *enrolled_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. @@ -99,14 +101,15 @@ pub async fn enroll( WHERE id = $1 AND enrollment_count < COALESCE(capacity, $2) RETURNING 1) - INSERT INTO enrollment (course, app_user, enrolled_by, source) - SELECT $1, $3, $4, NULL WHERE EXISTS (SELECT 1 FROM seat) + 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, user_id.uuid(), enrolled_by_id.uuid(), + created_at as _, ) .fetch_optional(&mut *tx) .await?; @@ -274,8 +277,8 @@ mod tests { async fn a_person(db: &Database, label: &str, role: &str) -> UserId { let user = UserId::generate(); sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, $2, 'x', $3)", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, $3)", ) .bind(user.uuid()) .bind(format!("{label}-{}", &user.key()[30..])) @@ -301,8 +304,8 @@ mod tests { .bind({ let mgr = UserId::generate(); sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, 'enroll-fixture', 'x', 'manager')", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, 'enroll-fixture', 0, 'manager')", ) .bind(mgr.uuid()) .execute(&db) diff --git a/src/db/event.rs b/src/db/event.rs index c7f9f61..a30e350 100644 --- a/src/db/event.rs +++ b/src/db/event.rs @@ -296,8 +296,8 @@ mod tests { async fn a_person(db: &Database, label: &str) -> UserId { let user = UserId::generate(); sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, $2, 'x', 'teacher')", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, 'teacher')", ) .bind(user.uuid()) .bind(format!("{label}-{}", &user.key()[30..])) diff --git a/src/db/exam.rs b/src/db/exam.rs index d3f4cbd..61dab3f 100644 --- a/src/db/exam.rs +++ b/src/db/exam.rs @@ -486,8 +486,8 @@ pub(crate) async fn published_exam(db: &Database) -> Exam { // The creator is a foreign key now: a real `app_user` row, minted per call. let creator = UserId::generate(); sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, $2, 'x', 'teacher')", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, 'teacher')", ) .bind(creator.uuid()) .bind(format!("exam-fixture-{}", &creator.key()[30..])) @@ -544,8 +544,8 @@ mod tests { .to_vec(); let creator = UserId::generate(); sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, $2, 'x', 'teacher')", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, 'teacher')", ) .bind(creator.uuid()) .bind(format!("orphan-race-{}", &creator.key()[30..])) @@ -578,8 +578,8 @@ mod tests { async fn a_person(db: &Database, label: &str, role: &str) -> UserId { let user = UserId::generate(); sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, $2, 'x', $3)", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, $3)", ) .bind(user.uuid()) .bind(format!("{label}-{}", &user.key()[30..])) diff --git a/src/db/exam_answer.rs b/src/db/exam_answer.rs index c4b1c66..8f1e45d 100644 --- a/src/db/exam_answer.rs +++ b/src/db/exam_answer.rs @@ -302,8 +302,8 @@ mod tests { // The student is a foreign key now: a real row under the fixture's // fixed key. sqlx::query( - "INSERT INTO app_user (id, username, password_hash) \ - VALUES ($1, 'aaaa-fixture', 'x')", + "INSERT INTO app_user (id, username, created_at) \ + VALUES ($1, 'aaaa-fixture', 0)", ) .bind(student().uuid()) .execute(&db) diff --git a/src/db/exam_attempt.rs b/src/db/exam_attempt.rs index e147ad8..564cc6f 100644 --- a/src/db/exam_attempt.rs +++ b/src/db/exam_attempt.rs @@ -393,8 +393,8 @@ mod tests { // The creator is a foreign key now: a real `app_user` row under the // fixture's fixed key. sqlx::query( - "INSERT INTO app_user (id, username, password_hash) \ - VALUES ($1, 'acdc-fixture', 'x') ON CONFLICT DO NOTHING", + "INSERT INTO app_user (id, username, created_at) \ + VALUES ($1, 'acdc-fixture', 0) ON CONFLICT DO NOTHING", ) .bind(creator.uuid()) .execute(db) @@ -460,15 +460,10 @@ mod tests { /// A real user row: the sitting counter lives on it, and the claim that /// rides the attempt's create has nothing to write to without one. async fn student(db: &Database) -> UserId { - let hash = crate::domain::user::Password::try_new("secret1") - .unwrap() - .hash_async() - .await - .unwrap(); *crate::db::user::create( db, crate::domain::user::Username::try_new("ogrenci").unwrap(), - hash, + None, ) .await .unwrap() diff --git a/src/db/exam_question.rs b/src/db/exam_question.rs index 6142591..1df9c55 100644 --- a/src/db/exam_question.rs +++ b/src/db/exam_question.rs @@ -450,8 +450,8 @@ mod tests { // the fixture's fixed key. let creator = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); sqlx::query( - "INSERT INTO app_user (id, username, password_hash) \ - VALUES ($1, 'acdc-fixture', 'x')", + "INSERT INTO app_user (id, username, created_at) \ + VALUES ($1, 'acdc-fixture', 0)", ) .bind(creator.uuid()) .execute(db) @@ -547,15 +547,10 @@ mod tests { // A real user row: starting a sitting moves that student's badge // counter in the same transaction, and an `UPDATE` has nothing to // write to without one. - let hash = crate::domain::user::Password::try_new("secret1") - .unwrap() - .hash_async() - .await - .unwrap(); let student = crate::db::user::create( &db, crate::domain::user::Username::try_new("ogrenci").unwrap(), - hash, + None, ) .await .unwrap(); diff --git a/src/db/exam_result.rs b/src/db/exam_result.rs index 5732086..7658774 100644 --- a/src/db/exam_result.rs +++ b/src/db/exam_result.rs @@ -11,6 +11,7 @@ use crate::domain::exam::ExamId; use crate::domain::exam_result::{ ExamResult, Mark, draft_error, latest_per_pair, retired_kind_error, }; +use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; @@ -180,10 +181,11 @@ pub async fn grade( } let written = sqlx::query_as!( ExamResult, - r#"INSERT INTO exam_result (exam, app_user, seq, mark, graded_by) - VALUES ($1, $2, $3, $4, $5) + r#"INSERT INTO exam_result (exam, app_user, seq, mark, graded_by, graded_at) + VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (exam, app_user, seq) DO UPDATE - SET mark = EXCLUDED.mark, graded_by = EXCLUDED.graded_by + SET mark = EXCLUDED.mark, graded_by = EXCLUDED.graded_by, + graded_at = EXCLUDED.graded_at RETURNING exam AS "exam: ExamId", app_user AS "user: UserId", seq, mark AS "mark: Mark", graded_by AS "graded_by: UserId""#, exam.uuid(), @@ -191,6 +193,7 @@ pub async fn grade( seq, mark.as_i64(), graded_by.uuid(), + Timestamp::now().as_millis(), ) .fetch_one(&mut *conn) .await?; @@ -518,8 +521,8 @@ mod tests { // too (the teacher idempotently — [`the_two_people`] re-runs it). let teacher = UserId::from_key(TEACHER); sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, 't', 'x', 'teacher') ON CONFLICT (id) DO NOTHING", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, 't', 0, 'teacher') ON CONFLICT (id) DO NOTHING", ) .bind(teacher.uuid()) .execute(db) @@ -622,8 +625,8 @@ mod tests { async fn the_two_people(db: &Database) { for (role, key) in [("teacher", TEACHER), ("student", STUDENT)] { sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, $2, 'x', $3) ON CONFLICT (id) DO NOTHING", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, $3) ON CONFLICT (id) DO NOTHING", ) .bind(UserId::from_key(key).uuid()) .bind(key) diff --git a/src/db/homework.rs b/src/db/homework.rs index 1caa16d..b23630d 100644 --- a/src/db/homework.rs +++ b/src/db/homework.rs @@ -537,8 +537,8 @@ mod tests { // (the subject's own fixture path mints one) and a real teacher. let teacher = UserId::generate(); sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, $2, 'x', 'teacher')", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, 'teacher')", ) .bind(teacher.uuid()) .bind(format!("homework-fixture-{}", &teacher.key()[30..])) diff --git a/src/db/homework_file.rs b/src/db/homework_file.rs index 60e98ac..5dbb4ea 100644 --- a/src/db/homework_file.rs +++ b/src/db/homework_file.rs @@ -310,7 +310,7 @@ 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, password_hash, role) VALUES ($1, $2, 'x', 'student')") + 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) @@ -322,7 +322,7 @@ mod tests { /// 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, password_hash, role) VALUES ($1, $2, 'x', 'teacher')") + 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) diff --git a/src/db/homework_result.rs b/src/db/homework_result.rs index 56a7161..df63001 100644 --- a/src/db/homework_result.rs +++ b/src/db/homework_result.rs @@ -333,8 +333,8 @@ mod tests { async fn a_teacher(db: &Database) -> UserId { let user = UserId::generate(); sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, $2, 'x', 'teacher')", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, 'teacher')", ) .bind(user.uuid()) .bind(format!("t-{}", &user.key()[30..])) @@ -348,8 +348,8 @@ mod tests { async fn a_student(db: &Database) -> UserId { let user = UserId::generate(); sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, $2, 'x', 'student')", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, 'student')", ) .bind(user.uuid()) .bind(format!("s-{}", &user.key()[30..])) diff --git a/src/db/homework_submission.rs b/src/db/homework_submission.rs index aeb8910..fe300c6 100644 --- a/src/db/homework_submission.rs +++ b/src/db/homework_submission.rs @@ -419,8 +419,8 @@ mod tests { async fn a_teacher(db: &Database) -> UserId { let user = UserId::generate(); sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, $2, 'x', 'teacher')", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, 'teacher')", ) .bind(user.uuid()) .bind(format!("t-{}", &user.key()[30..])) @@ -439,15 +439,10 @@ mod tests { /// A real user row: the counters live on it, and an `UPDATE` has nothing to /// write to without one. async fn a_student(username: &str, db: &Database) -> UserId { - let hash = crate::domain::user::Password::try_new("secret1") - .unwrap() - .hash_async() - .await - .unwrap(); *crate::db::user::create( db, crate::domain::user::Username::try_new(username).unwrap(), - hash, + None, ) .await .unwrap() diff --git a/src/db/meal_booking.rs b/src/db/meal_booking.rs index c94b029..b622fdd 100644 --- a/src/db/meal_booking.rs +++ b/src/db/meal_booking.rs @@ -412,8 +412,8 @@ mod tests { // The menu's creator is a foreign key now: a real `app_user` row. let creator = UserId::generate(); sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, $2, 'x', 'teacher')", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, 'teacher')", ) .bind(creator.uuid()) .bind(format!("menu-fixture-{}", &creator.key()[30..])) diff --git a/src/db/menu.rs b/src/db/menu.rs index 1474309..bb04a45 100644 --- a/src/db/menu.rs +++ b/src/db/menu.rs @@ -296,8 +296,8 @@ mod tests { async fn school() -> (Database, crate::database::TestDatabases) { let (db, leases) = init_test_db().await; sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, 'teacher', 'x', 'teacher')", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, 'teacher', 0, 'teacher')", ) .bind(UserId::from_key(TEACHER).uuid()) .execute(&db) diff --git a/src/db/mod.rs b/src/db/mod.rs index d820017..feb8f7c 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -50,6 +50,7 @@ pub mod person; pub mod payment_ledger; pub mod pomodoro; pub mod pool_question; +pub mod pool_question_image; pub mod profile; pub mod question_image; pub mod rag_output; @@ -58,6 +59,7 @@ pub mod session; pub mod session_attendance; pub mod settings; pub mod solution; +pub mod solution_image; pub mod subject; pub mod term; pub mod user; diff --git a/src/db/note_file.rs b/src/db/note_file.rs index b87dcec..289a9b8 100644 --- a/src/db/note_file.rs +++ b/src/db/note_file.rs @@ -123,7 +123,7 @@ mod tests { /// A real `app_user` row: the note's owner is a foreign key now. async fn a_person(db: &Database) -> crate::domain::user::UserId { let user = crate::domain::user::UserId::generate(); - sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, $2, 'x')") + sqlx::query("INSERT INTO app_user (id, username, created_at) VALUES ($1, $2, 0)") .bind(user.uuid()) .bind(format!("nf-{}", &user.key()[30..])) .execute(db) diff --git a/src/db/person.rs b/src/db/person.rs index 0d7296f..f14dec3 100644 --- a/src/db/person.rs +++ b/src/db/person.rs @@ -18,10 +18,11 @@ use crate::tenant::{SchoolStatus, Slug}; /// of a race gets the same `Conflict` a sequential duplicate would. pub async fn create(db: &Database, person: Person) -> Result<(), AppError> { match sqlx::query!( - "INSERT INTO person (id, username, password_hash) VALUES ($1, $2, $3)", + "INSERT INTO person (id, username, password_hash, created_at) VALUES ($1, $2, $3, $4)", person.id.uuid(), person.username.as_str(), person.password_hash.as_str(), + Timestamp::now().as_millis(), ) .execute(db) .await @@ -112,9 +113,10 @@ pub async fn membership_of( /// repeated join is a no-op, not an error. pub async fn add_membership(db: &Database, person: &PersonId, slug: &Slug) -> Result<(), AppError> { sqlx::query!( - "INSERT INTO person_school (person, school) VALUES ($1, $2) ON CONFLICT DO NOTHING", + "INSERT INTO person_school (person, school, created_at) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING", person.uuid(), - slug.as_str() + slug.as_str(), + Timestamp::now().as_millis() ) .execute(db) .await?; @@ -193,9 +195,8 @@ pub async fn delete_sessions_by_person(db: &Database, person: &PersonId) -> Resu Ok(()) } -/// Move the person credential — the one login reads. The school-side -/// `app_user` copy is rewritten separately by the same caller, so the two -/// stay in step. +/// Move the person credential — the one login reads. The school-side row +/// carries no password at all, so this is the whole credential move. pub async fn set_password_hash( db: &Database, username: &Username, diff --git a/src/db/pomodoro.rs b/src/db/pomodoro.rs index e36c0b8..8acebb8 100644 --- a/src/db/pomodoro.rs +++ b/src/db/pomodoro.rs @@ -244,7 +244,7 @@ mod tests { /// nothing. The tests above need no row — they read only the stint log. async fn a_user(db: &Database) -> UserId { let user = UserId::generate(); - sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, $2, 'x')") + sqlx::query("INSERT INTO app_user (id, username, created_at) VALUES ($1, $2, 0)") .bind(user.uuid()) .bind(format!("u{}", &user.key()[30..])) .execute(db) diff --git a/src/db/pool_question.rs b/src/db/pool_question.rs index 531f1a4..a2edccf 100644 --- a/src/db/pool_question.rs +++ b/src/db/pool_question.rs @@ -23,9 +23,7 @@ pub async fn insert(db: &Database, question: PoolQuestion) -> Result Result Result, AppError> { r#"SELECT id AS "id: PoolQuestionId", asker AS "asker: UserId", title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody", status, asked_at AS "asked_at: Timestamp", - approved_by AS "approved_by: UserId", image_file, - image_content_type AS "image_content_type: FileContentType", - image_size + approved_by AS "approved_by: UserId" FROM pool_question ORDER BY asked_at DESC, id DESC"#, ) .fetch_all(db) @@ -81,9 +75,7 @@ pub async fn list_visible_to(db: &Database, user: &UserId) -> Result Result, AppError> { +) -> Result>, AppError> { let id = *id; let file = file.to_owned(); let content_type = content_type.clone(); tx_with_retry(db, false, async move |tx| { - let before = sqlx::query_as!( - PoolQuestion, - r#"SELECT id AS "id: PoolQuestionId", asker AS "asker: UserId", - title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody", - status, asked_at AS "asked_at: Timestamp", - approved_by AS "approved_by: UserId", image_file, - image_content_type AS "image_content_type: FileContentType", - image_size - FROM pool_question WHERE id = $1 FOR UPDATE"#, + let before = sqlx::query!( + r#"SELECT status FROM pool_question WHERE id = $1 FOR UPDATE"#, id.uuid() ) .fetch_optional(&mut *tx) @@ -213,43 +203,45 @@ pub async fn set_image( let Some(before) = before else { return Ok(None); }; - let written = sqlx::query!( - r#"UPDATE pool_question - SET image_file = $2, image_content_type = $3, image_size = $4 - WHERE id = $1 AND status = $5"#, + if before.status != STATUS_PENDING { + return Ok(None); + } + let replaced = sqlx::query_scalar!( + r#"SELECT file FROM pool_question_image WHERE question = $1"#, + id.uuid() + ) + .fetch_optional(&mut *tx) + .await?; + sqlx::query!( + r#"INSERT INTO pool_question_image (question, file, content_type, size) + VALUES ($1, $2, $3, $4) + ON CONFLICT (question) DO UPDATE + SET file = EXCLUDED.file, content_type = EXCLUDED.content_type, + size = EXCLUDED.size"#, id.uuid(), file, content_type.as_str(), size, - STATUS_PENDING, ) .execute(&mut *tx) .await?; - if written.rows_affected() == 0 { - return Ok(None); - } - Ok(Some(before)) + Ok(Some(replaced)) }) .await } -/// Detach the question's image (pending only, like `set_image`). Returns -/// the *before* row — its `image_file` is the blob the caller must remove. +/// Detach the question's image (pending only, like [`set_image`]). +/// `Ok(None)` = the question is gone or no longer pending; +/// `Ok(Some(detached))` names the blob the caller removes — `None` inside +/// when the question carried no image (the route answers that 404). pub async fn clear_image( db: &Database, id: &PoolQuestionId, -) -> Result, AppError> { +) -> Result>, AppError> { let id = *id; tx_with_retry(db, false, async move |tx| { - let before = sqlx::query_as!( - PoolQuestion, - r#"SELECT id AS "id: PoolQuestionId", asker AS "asker: UserId", - title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody", - status, asked_at AS "asked_at: Timestamp", - approved_by AS "approved_by: UserId", image_file, - image_content_type AS "image_content_type: FileContentType", - image_size - FROM pool_question WHERE id = $1 FOR UPDATE"#, + let before = sqlx::query!( + r#"SELECT status FROM pool_question WHERE id = $1 FOR UPDATE"#, id.uuid() ) .fetch_optional(&mut *tx) @@ -257,66 +249,90 @@ pub async fn clear_image( let Some(before) = before else { return Ok(None); }; - let written = sqlx::query!( - r#"UPDATE pool_question - SET image_file = NULL, image_content_type = NULL, image_size = NULL - WHERE id = $1 AND status = $2"#, - id.uuid(), - STATUS_PENDING, - ) - .execute(&mut *tx) - .await?; - if written.rows_affected() == 0 { + if before.status != STATUS_PENDING { return Ok(None); } - Ok(Some(before)) + let detached = sqlx::query_scalar!( + r#"DELETE FROM pool_question_image WHERE question = $1 RETURNING file"#, + id.uuid() + ) + .fetch_optional(&mut *tx) + .await?; + Ok(Some(detached)) }) .await } -/// Delete the question and its solutions in one transaction, returning -/// the removed rows — the question's *and* the swept solutions' — so the -/// caller can take every image blob off disk (solutions carry photos too, -/// and a row-only sweep would strand theirs forever). +/// What [`delete`] took with the question: the rows ride back for their +/// ids, and `image_files` is the caller's disk-GC list — the question's +/// photo and every swept solution's. +pub struct Deleted { + pub question: PoolQuestion, + pub solutions: Vec, + pub image_files: Vec, +} + +/// Delete the question and its solutions in one transaction, returning the +/// removed rows plus every image blob key the two kinds of rows named, so +/// the caller can take every blob off disk (solutions carry photos too, and +/// a row-only sweep would strand theirs forever). /// /// Children before the parent, so the foreign keys never refuse the parent -/// delete. `cascade = true` because a solution offer committing inside this -/// window makes the parent delete answer 23503 — a mid-cascade race the -/// retry loop re-runs, sweeping the latecomer with it. That foreign key is -/// also what keeps a solution from outliving its question on the insert -/// side, so the old existence-move transaction is simply gone. -pub async fn delete( - db: &Database, - id: &PoolQuestionId, -) -> Result)>, AppError> { +/// delete — the photo rows first (they name their parents), then the +/// solutions, then the question. `cascade = true` because a solution offer +/// committing inside this window makes the parent delete answer 23503 — a +/// mid-cascade race the retry loop re-runs, sweeping the latecomer with it. +/// That foreign key is also what keeps a solution from outliving its +/// question on the insert side, so the old existence-move transaction is +/// simply gone. +pub async fn delete(db: &Database, id: &PoolQuestionId) -> Result, AppError> { let id = *id; tx_with_retry(db, true, async move |tx| { + let solution_files = sqlx::query_scalar!( + r#"DELETE FROM solution_image si + USING solution s + WHERE si.solution = s.id AND s.question = $1 + RETURNING si.file"#, + id.uuid() + ) + .fetch_all(&mut *tx) + .await?; let solutions = sqlx::query_as!( Solution, r#"DELETE FROM solution WHERE question = $1 RETURNING id AS "id: SolutionId", question AS "question: PoolQuestionId", - author AS "author: UserId", body AS "body: SolutionBody", - offered_at AS "offered_at: Timestamp", image_file, - image_content_type AS "image_content_type: FileContentType", - image_size"#, + author AS "author: UserId", body AS "body: SolutionBody", + offered_at AS "offered_at: Timestamp""#, id.uuid() ) .fetch_all(&mut *tx) .await?; + let question_file = sqlx::query_scalar!( + r#"DELETE FROM pool_question_image WHERE question = $1 RETURNING file"#, + id.uuid() + ) + .fetch_optional(&mut *tx) + .await?; let question = sqlx::query_as!( PoolQuestion, r#"DELETE FROM pool_question WHERE id = $1 RETURNING id AS "id: PoolQuestionId", asker AS "asker: UserId", - title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody", - status, asked_at AS "asked_at: Timestamp", - approved_by AS "approved_by: UserId", image_file, - image_content_type AS "image_content_type: FileContentType", - image_size"#, + title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody", + status, asked_at AS "asked_at: Timestamp", + approved_by AS "approved_by: UserId""#, id.uuid() ) .fetch_optional(&mut *tx) .await?; - Ok(question.map(|question| (question, solutions))) + Ok(question.map(|question| { + let mut image_files = solution_files; + image_files.extend(question_file); + Deleted { + question, + solutions, + image_files, + } + })) }) .await } @@ -332,7 +348,7 @@ mod tests { /// the question, and the counters are plain `NOT NULL DEFAULT 0` columns. async fn a_user(db: &Database) -> UserId { let user = UserId::generate(); - sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, $2, 'x')") + sqlx::query("INSERT INTO app_user (id, username, created_at) VALUES ($1, $2, 0)") .bind(user.uuid()) .bind(format!("u{}", &user.key()[30..])) .execute(db) @@ -483,31 +499,32 @@ mod tests { let png = FileContentType::try_new("image/png").unwrap(); let q = insert(&db, question(&asker)).await.unwrap(); - let before = set_image(&db, q.get_id(), "blob_a", &png, 3) + let replaced = set_image(&db, q.get_id(), "blob_a", &png, 3) .await .unwrap() .unwrap(); - assert!(before.get_image_file().is_none()); + assert!(replaced.is_none()); // A replace reports the old blob for cleanup. - let before = set_image(&db, q.get_id(), "blob_b", &png, 5) + let replaced = set_image(&db, q.get_id(), "blob_b", &png, 5) .await .unwrap() .unwrap(); - assert_eq!(before.get_image_file(), Some("blob_a")); - let stored = read(&db, q.get_id()).await.unwrap().unwrap(); - assert_eq!(stored.get_image_file(), Some("blob_b")); - assert_eq!(stored.get_image_size(), Some(5)); - - // Clearing reports the detached blob and empties the fields. - let before = clear_image(&db, q.get_id()).await.unwrap().unwrap(); - assert_eq!(before.get_image_file(), Some("blob_b")); + assert_eq!(replaced.as_deref(), Some("blob_a")); + let stored = crate::db::pool_question_image::read(&db, q.get_id()) + .await + .unwrap() + .unwrap(); + assert_eq!(stored.get_file(), "blob_b"); + assert_eq!(stored.get_size(), 5); + + // Clearing reports the detached blob and drops the row. + let detached = clear_image(&db, q.get_id()).await.unwrap().unwrap(); + assert_eq!(detached.as_deref(), Some("blob_b")); assert!( - read(&db, q.get_id()) + crate::db::pool_question_image::read(&db, q.get_id()) .await .unwrap() - .unwrap() - .get_image_file() .is_none() ); @@ -527,6 +544,7 @@ mod tests { let (db, _leases) = database::init_test_db().await; let asker = a_user(&db).await; let helper = a_user(&db).await; + let png = FileContentType::try_new("image/png").unwrap(); let q = insert(&db, question(&asker)).await.unwrap(); let offered = crate::db::solution::insert( @@ -539,13 +557,26 @@ mod tests { ) .await .unwrap(); + // Photos on both rows: their blob names must ride out with the + // delete, or the files strand on disk forever. + set_image(&db, q.get_id(), "q_blob", &png, 1) + .await + .unwrap() + .unwrap(); + crate::db::solution::set_image(&db, offered.get_id(), "s_blob", &png, 2) + .await + .unwrap() + .unwrap(); // The swept solutions ride back with the question so the caller can - // take their image blobs off disk. - let (removed, swept) = delete(&db, q.get_id()).await.unwrap().unwrap(); - assert_eq!(removed.get_id(), q.get_id()); - assert_eq!(swept.len(), 1); - assert_eq!(swept[0].get_id(), offered.get_id()); + // take every image blob off disk. + let removed = delete(&db, q.get_id()).await.unwrap().unwrap(); + assert_eq!(removed.question.get_id(), q.get_id()); + assert_eq!(removed.solutions.len(), 1); + assert_eq!(removed.solutions[0].get_id(), offered.get_id()); + assert_eq!(removed.image_files.len(), 2); + assert!(removed.image_files.contains(&"q_blob".to_string())); + assert!(removed.image_files.contains(&"s_blob".to_string())); assert!(read(&db, q.get_id()).await.unwrap().is_none()); assert!( crate::db::solution::list_for(&db, q.get_id(), None, 0) diff --git a/src/db/pool_question_image.rs b/src/db/pool_question_image.rs new file mode 100644 index 0000000..ef74c46 --- /dev/null +++ b/src/db/pool_question_image.rs @@ -0,0 +1,53 @@ +//! The `pool_question_image` table: the reads behind the pool photo +//! endpoints. One row per question at most (`question` is the primary key); +//! the writes ride the question's own guarded transactions in +//! [`crate::db::pool_question`] (`set_image`/`clear_image`/`delete`), where +//! the pending-freeze discipline and the replaced-blob accounting live. The +//! row's pure half lives in [`crate::domain::pool_question_image`]; the blob +//! bytes stay the web layer's. + +use crate::database::Database; +use crate::domain::note_file::FileContentType; +use crate::domain::pool_question::PoolQuestionId; +use crate::domain::pool_question_image::PoolQuestionImage; +use crate::error::AppError; + +/// The question's photo row, if it carries one — the blob-serving read. +pub async fn read( + db: &Database, + question: &PoolQuestionId, +) -> Result, AppError> { + let row = sqlx::query_as!( + PoolQuestionImage, + r#"SELECT question AS "question: PoolQuestionId", file, + content_type AS "content_type: FileContentType", size + FROM pool_question_image WHERE question = $1"#, + question.uuid() + ) + .fetch_optional(db) + .await?; + Ok(row) +} + +/// The photo rows of several questions in one query — for bucketing onto a +/// listing's *page* (one image per question at most, so a page of `n` +/// questions reads at most `n` rows). +pub async fn list_for_questions( + db: &Database, + questions: &[&PoolQuestionId], +) -> Result, AppError> { + if questions.is_empty() { + return Ok(Vec::new()); + } + let ids: Vec = questions.iter().map(|q| q.uuid()).collect(); + let rows = sqlx::query_as!( + PoolQuestionImage, + r#"SELECT question AS "question: PoolQuestionId", file, + content_type AS "content_type: FileContentType", size + FROM pool_question_image WHERE question = ANY($1)"#, + &ids + ) + .fetch_all(db) + .await?; + Ok(rows) +} diff --git a/src/db/profile.rs b/src/db/profile.rs index f7af010..5a3d2a9 100644 --- a/src/db/profile.rs +++ b/src/db/profile.rs @@ -79,20 +79,12 @@ pub async fn load( mod tests { use super::*; use crate::database::init_test_db; - use crate::domain::user::{Password, Username}; + use crate::domain::user::Username; async fn a_user(username: &str, db: &Database) -> crate::domain::user::User { - crate::db::user::create( - db, - Username::try_new(username).unwrap(), - Password::try_new("secret1") - .unwrap() - .hash_async() - .await - .unwrap(), - ) - .await - .unwrap() + crate::db::user::create(db, Username::try_new(username).unwrap(), None) + .await + .unwrap() } #[tokio::test] diff --git a/src/db/rag_output.rs b/src/db/rag_output.rs index 94666a5..27d5e42 100644 --- a/src/db/rag_output.rs +++ b/src/db/rag_output.rs @@ -168,7 +168,7 @@ mod tests { /// A real `app_user` row: the course's creator is a foreign key now. async fn a_person(db: &Database) -> crate::domain::user::UserId { let user = crate::domain::user::UserId::generate(); - sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, $2, 'x')") + sqlx::query("INSERT INTO app_user (id, username, created_at) VALUES ($1, $2, 0)") .bind(user.uuid()) .bind(format!("rag-{}", &user.key()[30..])) .execute(db) diff --git a/src/db/registration.rs b/src/db/registration.rs index 7fef616..244961d 100644 --- a/src/db/registration.rs +++ b/src/db/registration.rs @@ -7,6 +7,7 @@ use crate::database::{Database, tx_with_retry, unique_violation}; use crate::db::cap::Claimed; use crate::domain::event::EventId; use crate::domain::registration::Registration; +use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; use sqlx::query_as; @@ -67,6 +68,7 @@ pub(crate) async fn claim_seat( user: &UserId, registered_by: &UserId, ) -> Result, AppError> { + let created_at = Timestamp::now().as_millis(); match query_as!( Registration, "WITH person AS ( @@ -83,13 +85,14 @@ pub(crate) async fn claim_seat( AND (audience_capacity IS NULL OR registration_count < audience_capacity) AND EXISTS (SELECT 1 FROM person) RETURNING 1) - INSERT INTO registration (event, app_user, registered_by) - SELECT $1, $2, $3 + INSERT INTO registration (event, app_user, registered_by, created_at) + SELECT $1, $2, $3, $4 WHERE EXISTS (SELECT 1 FROM seat) RETURNING event AS \"event: EventId\", app_user AS \"user: UserId\", registered_by AS \"registered_by: UserId\"", event.uuid(), user.uuid(), - registered_by.uuid() + registered_by.uuid(), + created_at, ) .fetch_optional(db) .await diff --git a/src/db/session.rs b/src/db/session.rs index 739398c..cc0c8c6 100644 --- a/src/db/session.rs +++ b/src/db/session.rs @@ -92,8 +92,8 @@ mod tests { // under the fixture's fixed key, then two rows either side of `now`. let user = UserId::from_key("019732e3-7b00-7000-8000-00000000cab0"); sqlx::query( - "INSERT INTO app_user (id, username, password_hash) \ - VALUES ($1, 'purge-fixture', 'x')", + "INSERT INTO app_user (id, username, created_at) \ + VALUES ($1, 'purge-fixture', 0)", ) .bind(user.uuid()) .execute(&db) diff --git a/src/db/session_attendance.rs b/src/db/session_attendance.rs index 8ac456b..700d333 100644 --- a/src/db/session_attendance.rs +++ b/src/db/session_attendance.rs @@ -130,10 +130,11 @@ 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) - VALUES ($1, $2, $3, $4, $5) + r#"INSERT INTO session_attendance (session, app_user, 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 + 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", marked_by AS "marked_by: UserId""#, @@ -142,6 +143,7 @@ pub async fn mark( session.course.uuid(), status.as_str(), marked_by.uuid(), + now.as_millis(), ) .fetch_one(&mut *tx) .await?; @@ -311,8 +313,8 @@ mod tests { // keeps repeated calls (same label, new person) collision-free. let user = UserId::generate(); sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, $2, 'x', $3)", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, $3)", ) .bind(user.uuid()) .bind(format!("{key}-{}", &user.key()[30..])) diff --git a/src/db/solution.rs b/src/db/solution.rs index d6cb088..1f566fc 100644 --- a/src/db/solution.rs +++ b/src/db/solution.rs @@ -33,9 +33,7 @@ pub async fn insert(db: &Database, solution: Solution) -> Result Result, AppError> { +) -> Result>, AppError> { // Owned captures (`Send` rule of `tx_with_retry` closures). let id = *id; let file = file.to_owned(); let content_type = content_type.clone(); tx_with_retry(db, false, async move |tx| { - let before = sqlx::query_as!( - Solution, - r#"SELECT id AS "id: SolutionId", question AS "question: PoolQuestionId", - author AS "author: UserId", body AS "body: SolutionBody", - offered_at AS "offered_at: Timestamp", image_file, - image_content_type AS "image_content_type: FileContentType", - image_size - FROM solution WHERE id = $1 FOR UPDATE"#, + let before = sqlx::query!( + r#"SELECT id FROM solution WHERE id = $1 FOR UPDATE"#, id.uuid() ) .fetch_optional(&mut *tx) .await?; - let Some(before) = before else { + if before.is_none() { return Ok(None); - }; + } + let replaced = sqlx::query_scalar!( + r#"SELECT file FROM solution_image WHERE solution = $1"#, + id.uuid() + ) + .fetch_optional(&mut *tx) + .await?; sqlx::query!( - r#"UPDATE solution - SET image_file = $2, image_content_type = $3, image_size = $4 - WHERE id = $1"#, + r#"INSERT INTO solution_image (solution, file, content_type, size) + VALUES ($1, $2, $3, $4) + ON CONFLICT (solution) DO UPDATE + SET file = EXCLUDED.file, content_type = EXCLUDED.content_type, + size = EXCLUDED.size"#, id.uuid(), - file.as_str(), + file, content_type.as_str(), size, ) .execute(&mut *tx) .await?; - Ok(Some(before)) + Ok(Some(replaced)) }) .await } -/// Detach the solution's image. Returns the *before* row — its -/// `image_file` is the blob the caller must remove. -pub async fn clear_image(db: &Database, id: &SolutionId) -> Result, AppError> { +/// Detach the solution's image. `Ok(None)` = the row was deleted mid-flight; +/// `Ok(Some(detached))` names the blob the caller removes — `None` inside +/// when the solution carried no image (the route answers that 404). +pub async fn clear_image( + db: &Database, + id: &SolutionId, +) -> Result>, AppError> { // Owned capture (`Send` rule of `tx_with_retry` closures). let id = *id; tx_with_retry(db, false, async move |tx| { - let before = sqlx::query_as!( - Solution, - r#"SELECT id AS "id: SolutionId", question AS "question: PoolQuestionId", - author AS "author: UserId", body AS "body: SolutionBody", - offered_at AS "offered_at: Timestamp", image_file, - image_content_type AS "image_content_type: FileContentType", - image_size - FROM solution WHERE id = $1 FOR UPDATE"#, + let before = sqlx::query!( + r#"SELECT id FROM solution WHERE id = $1 FOR UPDATE"#, id.uuid() ) .fetch_optional(&mut *tx) .await?; - let Some(before) = before else { + if before.is_none() { return Ok(None); - }; - sqlx::query!( - r#"UPDATE solution - SET image_file = NULL, image_content_type = NULL, image_size = NULL - WHERE id = $1"#, - id.uuid(), + } + let detached = sqlx::query_scalar!( + r#"DELETE FROM solution_image WHERE solution = $1 RETURNING file"#, + id.uuid() ) - .execute(&mut *tx) + .fetch_optional(&mut *tx) .await?; - Ok(Some(before)) + Ok(Some(detached)) }) .await } -pub async fn delete(db: &Database, solution: Solution) -> Result { - let deleted = sqlx::query_as!( - Solution, - r#"DELETE FROM solution WHERE id = $1 - RETURNING id AS "id: SolutionId", question AS "question: PoolQuestionId", - author AS "author: UserId", body AS "body: SolutionBody", - offered_at AS "offered_at: Timestamp", image_file, - image_content_type AS "image_content_type: FileContentType", - image_size"#, - solution.id.uuid() - ) - .fetch_optional(db) - .await?; - deleted.ok_or(AppError::NotFound) +/// Delete a solution, returning the row plus the blob name of the photo it +/// carried (the caller's disk-GC list — one entry at most). The photo row +/// goes first: its foreign key is `NO ACTION`, so it cannot outlive being +/// pointed at, and its file name is read on the way out, under the same +/// transaction — a photo uploaded by a racing `set_image` loses the row +/// lock to this delete and comes back as the caller's orphan. +pub async fn delete( + db: &Database, + solution: Solution, +) -> Result)>, AppError> { + // Owned capture (`Send` rule of `tx_with_retry` closures). + let id = *solution.get_id(); + tx_with_retry(db, false, async move |tx| { + let image = sqlx::query_scalar!( + r#"DELETE FROM solution_image WHERE solution = $1 RETURNING file"#, + id.uuid() + ) + .fetch_optional(&mut *tx) + .await?; + let deleted = sqlx::query_as!( + Solution, + r#"DELETE FROM solution WHERE id = $1 + RETURNING id AS "id: SolutionId", question AS "question: PoolQuestionId", + author AS "author: UserId", body AS "body: SolutionBody", + offered_at AS "offered_at: Timestamp""#, + id.uuid() + ) + .fetch_optional(&mut *tx) + .await?; + Ok(deleted.map(|deleted| (deleted, image))) + }) + .await } #[cfg(test)] @@ -264,8 +278,8 @@ mod tests { async fn a_person(db: &Database, label: &str) -> UserId { let user = UserId::generate(); sqlx::query( - "INSERT INTO app_user (id, username, password_hash) \ - VALUES ($1, $2, 'x')", + "INSERT INTO app_user (id, username, created_at) \ + VALUES ($1, $2, 0)", ) .bind(user.uuid()) .bind(format!("{label}-{}", &user.key()[30..])) @@ -345,7 +359,10 @@ mod tests { .is_none() ); - delete(&db, first).await.unwrap(); + let first_id = *first.get_id(); + let (deleted, image) = delete(&db, first).await.unwrap().unwrap(); + assert_eq!(deleted.get_id(), &first_id); + assert!(image.is_none()); assert_eq!( list_for(&db, &question_a, None, 0).await.unwrap().0.len(), 1 @@ -370,40 +387,39 @@ mod tests { .await .unwrap(); - let before = set_image(&db, solution.get_id(), "blob_a", &png, 3) + let replaced = set_image(&db, solution.get_id(), "blob_a", &png, 3) .await .unwrap() .unwrap(); - assert!(before.get_image_file().is_none()); + assert!(replaced.is_none()); // A replace reports the old blob for cleanup. - let before = set_image(&db, solution.get_id(), "blob_b", &png, 5) + let replaced = set_image(&db, solution.get_id(), "blob_b", &png, 5) .await .unwrap() .unwrap(); - assert_eq!(before.get_image_file(), Some("blob_a")); - let stored = read_for(&db, solution.get_id(), &question) + assert_eq!(replaced.as_deref(), Some("blob_a")); + let stored = crate::db::solution_image::read(&db, solution.get_id()) .await .unwrap() .unwrap(); - assert_eq!(stored.get_image_file(), Some("blob_b")); - assert_eq!(stored.get_image_size(), Some(5)); + assert_eq!(stored.get_file(), "blob_b"); + assert_eq!(stored.get_size(), 5); - // Clearing reports the detached blob and empties the fields. - let before = clear_image(&db, solution.get_id()).await.unwrap().unwrap(); - assert_eq!(before.get_image_file(), Some("blob_b")); + // Clearing reports the detached blob and drops the row. + let detached = clear_image(&db, solution.get_id()).await.unwrap().unwrap(); + assert_eq!(detached.as_deref(), Some("blob_b")); assert!( - read_for(&db, solution.get_id(), &question) + crate::db::solution_image::read(&db, solution.get_id()) .await .unwrap() - .unwrap() - .get_image_file() .is_none() ); // A row deleted mid-flight surfaces as None, not an error. - let deleted = delete(&db, solution.clone()).await.unwrap(); + let (deleted, image) = delete(&db, solution.clone()).await.unwrap().unwrap(); assert_eq!(deleted.get_id(), solution.get_id()); + assert!(image.is_none()); assert!( set_image(&db, solution.get_id(), "blob_c", &png, 7) .await @@ -473,9 +489,7 @@ mod tests { } } - let counts = counts_for(&db, &[two, one, none]) - .await - .unwrap(); + let counts = counts_for(&db, &[two, one, none]).await.unwrap(); assert_eq!(counts.get(two.key().as_str()), Some(&2)); assert_eq!(counts.get(one.key().as_str()), Some(&1)); // No solutions = no entry; the caller reads the miss as zero. diff --git a/src/db/solution_image.rs b/src/db/solution_image.rs new file mode 100644 index 0000000..3e75419 --- /dev/null +++ b/src/db/solution_image.rs @@ -0,0 +1,49 @@ +//! The `solution_image` table: the reads behind the solution photo +//! endpoints. One row per solution at most (`solution` is the primary key); +//! the writes ride the solution's own transactions in +//! [`crate::db::solution`] (`set_image`/`clear_image`/`delete`), where the +//! replaced-blob accounting lives. The row's pure half lives in +//! [`crate::domain::solution_image`]; the blob bytes stay the web layer's. + +use crate::database::Database; +use crate::domain::note_file::FileContentType; +use crate::domain::solution::SolutionId; +use crate::domain::solution_image::SolutionImage; +use crate::error::AppError; + +/// The solution's photo row, if it carries one — the blob-serving read. +pub async fn read(db: &Database, solution: &SolutionId) -> Result, AppError> { + let row = sqlx::query_as!( + SolutionImage, + r#"SELECT solution AS "solution: SolutionId", file, + content_type AS "content_type: FileContentType", size + FROM solution_image WHERE solution = $1"#, + solution.uuid() + ) + .fetch_optional(db) + .await?; + Ok(row) +} + +/// The photo rows of several solutions in one query — for bucketing onto a +/// listing's *page* (one image per solution at most, so a page of `n` +/// solutions reads at most `n` rows). +pub async fn list_for_solutions( + db: &Database, + solutions: &[&SolutionId], +) -> Result, AppError> { + if solutions.is_empty() { + return Ok(Vec::new()); + } + let ids: Vec = solutions.iter().map(|s| s.uuid()).collect(); + let rows = sqlx::query_as!( + SolutionImage, + r#"SELECT solution AS "solution: SolutionId", file, + content_type AS "content_type: FileContentType", size + FROM solution_image WHERE solution = ANY($1)"#, + &ids + ) + .fetch_all(db) + .await?; + Ok(rows) +} diff --git a/src/db/term.rs b/src/db/term.rs index 39479db..b130ed0 100644 --- a/src/db/term.rs +++ b/src/db/term.rs @@ -274,8 +274,8 @@ mod tests { // every create in every round. let teacher = UserId::generate(); sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, $2, 'x', 'teacher')", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, 'teacher')", ) .bind(teacher.uuid()) .bind(format!("term-race-{}", &teacher.key()[30..])) diff --git a/src/db/user.rs b/src/db/user.rs index c97130c..66bd04b 100644 --- a/src/db/user.rs +++ b/src/db/user.rs @@ -13,23 +13,27 @@ use crate::db::field_update::FieldUpdate; use crate::db::page::{PagedList, Param}; use crate::domain::board::{Board, BoardId, BoardTitle}; use crate::domain::note_file::FileContentType; +use crate::domain::person::PersonId; use crate::domain::preferences::{Language, PaletteColor, Theme}; use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone}; use crate::domain::role::Role; use crate::domain::text_fold::{search_fold, search_fold_sql}; use crate::domain::timestamp::Timestamp; -use crate::domain::user::{PasswordHash, User, UserId, Username}; +use crate::domain::user::{User, UserId, Username}; use crate::error::AppError; -/// Register a new account. New users always start as [`Role::Student`]; -/// elevation is a separate, admin-only action +/// Register a new school account for the control-plane `person` whose +/// credential login verifies — `person` is the join key, `None` only where the +/// caller cannot know it yet (tests, the boot seed's row-first order — see +/// [`crate::service::user::ensure_admin`]). New users always start as +/// [`Role::Student`]; elevation is a separate, admin-only action /// (see [`crate::service::user::set_role`]). pub async fn create( db: &Database, username: Username, - password_hash: PasswordHash, + person: Option, ) -> Result { - create_with_role(db, username, password_hash, Role::Student).await + create_with_role(db, username, person, Role::Student).await } /// The one row-minting path. `role` is written *with* the row rather than @@ -44,20 +48,23 @@ pub async fn create( /// the constraint a racing insert had violated; here the violated /// constraint's name answers directly (`app_user_username`), and the loser /// of a race gets the same 409 the sequential duplicate always got. +/// +/// The row carries its `created_at` mint stamp and, when the caller knows it, +/// the `person` id the credential lives on. pub async fn create_with_role( db: &Database, username: Username, - password_hash: PasswordHash, + person: Option, role: Role, ) -> Result { let id = UserId::generate(); match sqlx::query_as!( User, - r#"INSERT INTO app_user (id, username, password_hash, role) - VALUES ($1, $2, $3, $4) + r#"INSERT INTO app_user (id, username, person, role, created_at) + VALUES ($1, $2, $3, $4, $5) RETURNING id AS "id: UserId", username AS "username: Username", - password_hash AS "password_hash: PasswordHash", + person AS "person: PersonId", role AS "role: Role", name AS "name: PersonName", surname AS "surname: PersonName", @@ -74,13 +81,20 @@ pub async fn create_with_role( avatar_size"#, id.uuid(), username.as_str(), - password_hash.as_str(), + person.as_ref().map(PersonId::uuid), role.as_str(), + Timestamp::now().as_millis(), ) .fetch_one(db) .await { - Ok(user) => Ok(user), + Ok(user) => { + debug_assert_eq!( + user.get_person().map(PersonId::uuid), + person.as_ref().map(PersonId::uuid) + ); + Ok(user) + } Err(err) if crate::database::unique_violation(&err) == Some("app_user_username") => { Err(AppError::Conflict("username already taken")) } @@ -93,7 +107,7 @@ pub async fn read(db: &Database, id: &UserId) -> Result, AppError> User, r#"SELECT id AS "id: UserId", username AS "username: Username", - password_hash AS "password_hash: PasswordHash", + person AS "person: PersonId", role AS "role: Role", name AS "name: PersonName", surname AS "surname: PersonName", @@ -137,7 +151,7 @@ pub async fn list_by_ids(db: &Database, ids: &[UserId]) -> Result, App User, r#"SELECT id AS "id: UserId", username AS "username: Username", - password_hash AS "password_hash: PasswordHash", + person AS "person: PersonId", role AS "role: Role", name AS "name: PersonName", surname AS "surname: PersonName", @@ -168,7 +182,7 @@ pub async fn list_by_role(db: &Database, role: Role) -> Result, AppErr User, r#"SELECT id AS "id: UserId", username AS "username: Username", - password_hash AS "password_hash: PasswordHash", + person AS "person: PersonId", role AS "role: Role", name AS "name: PersonName", surname AS "surname: PersonName", @@ -389,7 +403,7 @@ pub async fn set_role_cascade( WHERE role = 'admin' AND id <> $1) = 0) RETURNING id AS "id: UserId", username AS "username: Username", - password_hash AS "password_hash: PasswordHash", + person AS "person: PersonId", role AS "role: Role", name AS "name: PersonName", surname AS "surname: PersonName", @@ -622,13 +636,38 @@ pub async fn set_profile( value.map(|inner| Param::OptText(inner.map(str::to_string))) } FieldUpdate::new("app_user", id.uuid()) - .set("name", text(name.as_ref().map(|n| n.as_ref().map(|x| x.as_str())))) - .set("surname", text(surname.as_ref().map(|n| n.as_ref().map(|x| x.as_str())))) - .set("email", text(email.as_ref().map(|n| n.as_ref().map(|x| x.as_str())))) - .set("phone", text(phone.as_ref().map(|n| n.as_ref().map(|x| x.as_str())))) - .set("birth_date", text(birth_date.as_ref().map(|n| n.as_ref().map(|x| x.as_str())))) - .set("display_name", text(display_name.as_ref().map(|n| n.as_ref().map(|x| x.as_str())))) - .set("bio", text(bio.as_ref().map(|n| n.as_ref().map(|x| x.as_str())))) + .set( + "name", + text(name.as_ref().map(|n| n.as_ref().map(|x| x.as_str()))), + ) + .set( + "surname", + text(surname.as_ref().map(|n| n.as_ref().map(|x| x.as_str()))), + ) + .set( + "email", + text(email.as_ref().map(|n| n.as_ref().map(|x| x.as_str()))), + ) + .set( + "phone", + text(phone.as_ref().map(|n| n.as_ref().map(|x| x.as_str()))), + ) + .set( + "birth_date", + text(birth_date.as_ref().map(|n| n.as_ref().map(|x| x.as_str()))), + ) + .set( + "display_name", + text( + display_name + .as_ref() + .map(|n| n.as_ref().map(|x| x.as_str())), + ), + ) + .set( + "bio", + text(bio.as_ref().map(|n| n.as_ref().map(|x| x.as_str()))), + ) .run(db) .await } @@ -662,7 +701,7 @@ pub async fn set_avatar( User, r#"SELECT id AS "id: UserId", username AS "username: Username", - password_hash AS "password_hash: PasswordHash", + person AS "person: PersonId", role AS "role: Role", name AS "name: PersonName", surname AS "surname: PersonName", @@ -710,7 +749,7 @@ pub async fn clear_avatar(db: &Database, id: &UserId) -> Result, Ap User, r#"SELECT id AS "id: UserId", username AS "username: Username", - password_hash AS "password_hash: PasswordHash", + person AS "person: PersonId", role AS "role: Role", name AS "name: PersonName", surname AS "surname: PersonName", @@ -746,44 +785,6 @@ pub async fn clear_avatar(db: &Database, id: &UserId) -> Result, Ap .await } -/// Replace a user's password hash — the builder's admin-password reset -/// (`POST /schools/{slug}/admin-password`). Only the credential is -/// rewritten; revoking the sessions minted under the old one is the -/// caller's second half ([`crate::db::session::delete_by_user`]), because a -/// reset that leaves a stolen cookie working resets nothing. -pub async fn set_password_hash( - db: &Database, - id: &UserId, - password_hash: PasswordHash, -) -> Result, AppError> { - let user = sqlx::query_as!( - User, - r#"UPDATE app_user SET password_hash = $2 WHERE id = $1 - RETURNING id AS "id: UserId", - username AS "username: Username", - password_hash AS "password_hash: PasswordHash", - role AS "role: Role", - name AS "name: PersonName", - surname AS "surname: PersonName", - email AS "email: Email", - phone AS "phone: Phone", - birth_date AS "birth_date: BirthDate", - theme AS "theme: Theme", - language AS "language: Language", - palette_color AS "palette_color: PaletteColor", - display_name AS "display_name: DisplayName", - bio AS "bio: Bio", - avatar_file, - avatar_content_type AS "avatar_content_type: FileContentType", - avatar_size"#, - id.uuid(), - password_hash.as_str(), - ) - .fetch_optional(db) - .await?; - Ok(user) -} - /// Write the UI-preference fields the request actually carried. Same /// contract as [`set_profile`]: `None` = omitted (not written), /// `Some(None)` = cleared back to "never chose", `Some(Some(v))` = set. @@ -810,7 +811,7 @@ pub async fn find_by_username(db: &Database, username: &str) -> Result Result FileContentType { FileContentType::try_new("image/png").unwrap() } async fn a_user(username: &str, db: &Database) -> User { - create( - db, - Username::try_new(username).unwrap(), - Password::try_new("secret1") - .unwrap() - .hash_async() - .await - .unwrap(), - ) - .await - .unwrap() + create(db, Username::try_new(username).unwrap(), None) + .await + .unwrap() } #[tokio::test] diff --git a/src/db/work_entry.rs b/src/db/work_entry.rs index f55ae7a..cf548b8 100644 --- a/src/db/work_entry.rs +++ b/src/db/work_entry.rs @@ -204,8 +204,8 @@ mod tests { // The stint's owner is a foreign key now: a real `app_user` row. let user = UserId::generate(); sqlx::query( - "INSERT INTO app_user (id, username, password_hash) \ - VALUES ($1, 'work-fixture', 'x')", + "INSERT INTO app_user (id, username, created_at) \ + VALUES ($1, 'work-fixture', 0)", ) .bind(user.uuid()) .execute(&db) diff --git a/src/domain/mod.rs b/src/domain/mod.rs index fdb74c3..88ecd6d 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -52,6 +52,7 @@ pub mod parent_link; pub mod payment_ledger; pub mod pomodoro; pub mod pool_question; +pub mod pool_question_image; pub mod preferences; pub mod profile; pub mod question_image; @@ -63,6 +64,7 @@ pub mod session; pub mod session_attendance; pub mod settings; pub mod solution; +pub mod solution_image; pub mod subject; pub mod term; pub mod text_fold; diff --git a/src/domain/pool_question.rs b/src/domain/pool_question.rs index 36aa5f7..c603931 100644 --- a/src/domain/pool_question.rs +++ b/src/domain/pool_question.rs @@ -4,11 +4,13 @@ //! the whole school for everyone to read and offer solutions on. Approved //! content is frozen — edits after approval would bypass moderation — so the //! only post-approval change is deletion (asker or teacher+), which takes the -//! question's solutions with it. An optional photo of the problem rides on -//! the row as metadata (`image_*`); the bytes live on disk under -//! [`crate::config::Config::files_path`] in a file named by `image_file` — a -//! fresh server-generated id per upload. The web layer owns the blob I/O; -//! the queries live in [`crate::db::pool_question`], the workflows in +//! question's solutions with it. An optional photo of the problem is its own +//! row in `pool_question_image` — the child-table shape of +//! [`crate::domain::question_image`] with a single (implicit) slot — and the +//! bytes live on disk under [`crate::config::Config::files_path`] in a file +//! named by that row's `file` — a fresh server-generated id per upload. The +//! web layer owns the blob I/O; the queries live in +//! [`crate::db::pool_question`], the workflows in //! [`crate::service::pool_question`]. use uuid::Uuid; @@ -17,7 +19,6 @@ use crate::constant::{ MAX_POOL_QUESTION_BODY_LEN, MAX_POOL_QUESTION_TITLE_LEN, STATUS_APPROVED, STATUS_PENDING, }; use crate::domain::monotonic_id::next_uuid; -use crate::domain::note_file::FileContentType; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::ValidationError; @@ -97,11 +98,6 @@ pub struct PoolQuestion { pub(crate) status: String, pub(crate) asked_at: Timestamp, pub(crate) approved_by: Option, - /// The photo's on-disk blob name — a fresh server-generated id every - /// upload; `None` when the question carries no image. - pub(crate) image_file: Option, - pub(crate) image_content_type: Option, - pub(crate) image_size: Option, } impl PoolQuestion { @@ -114,9 +110,6 @@ impl PoolQuestion { status: STATUS_PENDING.to_string(), asked_at: Timestamp::now(), approved_by: None, - image_file: None, - image_content_type: None, - image_size: None, } } @@ -151,16 +144,5 @@ impl PoolQuestion { pub fn get_approved_by(&self) -> Option<&UserId> { self.approved_by.as_ref() } - - pub fn get_image_file(&self) -> Option<&str> { - self.image_file.as_deref() - } - - pub fn get_image_content_type(&self) -> Option<&FileContentType> { - self.image_content_type.as_ref() - } - - pub fn get_image_size(&self) -> Option { - self.image_size - } } + diff --git a/src/domain/pool_question_image.rs b/src/domain/pool_question_image.rs new file mode 100644 index 0000000..e4f3248 --- /dev/null +++ b/src/domain/pool_question_image.rs @@ -0,0 +1,42 @@ +//! The photo of a pool question — one optional image row per question, the +//! single-slot spelling of [`crate::domain::question_image`]'s child-table +//! shape. The row carries metadata only; the bytes live on disk under +//! [`crate::config::Config::files_path`] in a file named by `file` — a fresh +//! server-generated id per upload, so a replace never overwrites bytes in +//! place. The question row itself carries no image columns; the child row is +//! the whole photo. The writes ride the parent's own transactions in +//! [`crate::db::pool_question`] (pending-only, like every content write); +//! the reads live in [`crate::db::pool_question_image`]; the web layer owns +//! the blob I/O and its ordering (new blob before row, row before old blob). + +use crate::domain::note_file::FileContentType; +use crate::domain::pool_question::PoolQuestionId; + +/// One question's photo row. `question` is the primary key — one image per +/// question by construction, and a replace is a plain upsert. +#[derive(Debug, Clone, sqlx::FromRow)] +pub struct PoolQuestionImage { + pub(crate) question: PoolQuestionId, + /// The blob's on-disk name — a fresh server-generated id every upload. + pub(crate) file: String, + pub(crate) content_type: FileContentType, + pub(crate) size: i64, +} + +impl PoolQuestionImage { + pub fn get_question(&self) -> &PoolQuestionId { + &self.question + } + + pub fn get_file(&self) -> &str { + &self.file + } + + pub fn get_content_type(&self) -> &FileContentType { + &self.content_type + } + + pub fn get_size(&self) -> i64 { + self.size + } +} diff --git a/src/domain/solution.rs b/src/domain/solution.rs index a24152e..6d84d86 100644 --- a/src/domain/solution.rs +++ b/src/domain/solution.rs @@ -2,7 +2,6 @@ use uuid::Uuid; use crate::constant::MAX_SOLUTION_BODY_LEN; use crate::domain::monotonic_id::next_uuid; -use crate::domain::note_file::FileContentType; use crate::domain::pool_question::PoolQuestionId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; @@ -66,11 +65,6 @@ pub struct Solution { pub(crate) author: UserId, pub(crate) body: SolutionBody, pub(crate) offered_at: Timestamp, - /// The photo's on-disk blob name — a fresh server-generated id every - /// upload; `None` when the solution carries no image. - pub(crate) image_file: Option, - pub(crate) image_content_type: Option, - pub(crate) image_size: Option, } impl Solution { @@ -81,9 +75,6 @@ impl Solution { author: *author, body, offered_at: Timestamp::now(), - image_file: None, - image_content_type: None, - image_size: None, } } @@ -107,17 +98,6 @@ impl Solution { self.offered_at } - pub fn get_image_file(&self) -> Option<&str> { - self.image_file.as_deref() - } - - pub fn get_image_content_type(&self) -> Option<&FileContentType> { - self.image_content_type.as_ref() - } - - pub fn get_image_size(&self) -> Option { - self.image_size - } } #[cfg(test)] diff --git a/src/domain/solution_image.rs b/src/domain/solution_image.rs new file mode 100644 index 0000000..23b192a --- /dev/null +++ b/src/domain/solution_image.rs @@ -0,0 +1,42 @@ +//! The photo of an offered solution — one optional image row per solution, +//! the single-slot spelling of [`crate::domain::question_image`]'s +//! child-table shape. The row carries metadata only; the bytes live on disk +//! under [`crate::config::Config::files_path`] in a file named by `file` — a +//! fresh server-generated id per upload, so a replace never overwrites bytes +//! in place. The solution row itself carries no image columns; the child row +//! is the whole photo. The writes ride the parent's own transactions in +//! [`crate::db::solution`] (unconditional — solutions are unmoderated); the +//! reads live in [`crate::db::solution_image`]; the web layer owns the blob +//! I/O and its ordering (new blob before row, row before old blob). + +use crate::domain::note_file::FileContentType; +use crate::domain::solution::SolutionId; + +/// One solution's photo row. `solution` is the primary key — one image per +/// solution by construction, and a replace is a plain upsert. +#[derive(Debug, Clone, sqlx::FromRow)] +pub struct SolutionImage { + pub(crate) solution: SolutionId, + /// The blob's on-disk name — a fresh server-generated id every upload. + pub(crate) file: String, + pub(crate) content_type: FileContentType, + pub(crate) size: i64, +} + +impl SolutionImage { + pub fn get_solution(&self) -> &SolutionId { + &self.solution + } + + pub fn get_file(&self) -> &str { + &self.file + } + + pub fn get_content_type(&self) -> &FileContentType { + &self.content_type + } + + pub fn get_size(&self) -> i64 { + self.size + } +} diff --git a/src/domain/user.rs b/src/domain/user.rs index 28934fb..9fead91 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -12,6 +12,7 @@ use uuid::Uuid; use crate::constant::{AI_PRINCIPAL_KEY, DECOY_PASSWORD}; use crate::domain::monotonic_id::next_uuid; use crate::domain::note_file::FileContentType; +use crate::domain::person::PersonId; use crate::domain::preferences::{Language, PaletteColor, Theme}; use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone}; use crate::domain::role::Role; @@ -103,7 +104,9 @@ impl Password { fn hash(&self) -> Result { // password-hash 0.6 generates the salt internally (its own CSPRNG); // the explicit SaltString step is gone. - let hash = Argon2::default().hash_password(self.0.as_bytes())?.to_string(); + let hash = Argon2::default() + .hash_password(self.0.as_bytes())? + .to_string(); Ok(PasswordHash(hash)) } @@ -204,7 +207,10 @@ impl PasswordHash { pub struct User { pub(crate) id: UserId, pub(crate) username: Username, - pub(crate) password_hash: PasswordHash, + /// The control-plane person this school row belongs to — the join key to + /// the credential. No FK: the two halves are separate databases. `None` + /// on rows minted before their person was known (boot seed order, tests). + pub(crate) person: Option, pub(crate) role: Role, // Personal info, identical for every role. All optional: accounts are // created from bare credentials and filled in later, and rows from before @@ -237,14 +243,14 @@ impl User { /// /// Never written to the database, and never read back from one: the id is /// the nil UUID, which no minted id (always a v7) can ever equal. Every - /// other field is inert — the empty password hash parses as no argon2 hash, - /// so it verifies against nothing, and [`Role::Ai`] clears no `at_least` - /// bar and fails every exact `== Role::Student` / `== Role::Parent` gate. + /// other field is inert — `person` is `None`, and [`Role::Ai`] clears no + /// `at_least` bar and fails every exact `== Role::Student` / + /// `== Role::Parent` gate. pub(crate) fn ai_principal() -> User { User { id: UserId(Uuid::nil()), username: Username(AI_PRINCIPAL_KEY.to_string()), - password_hash: PasswordHash(String::new()), + person: None, role: Role::Ai, name: None, surname: None, @@ -269,9 +275,8 @@ impl User { pub fn get_username(&self) -> &Username { &self.username } - - pub fn get_password_hash(&self) -> &PasswordHash { - &self.password_hash + pub fn get_person(&self) -> Option<&PersonId> { + self.person.as_ref() } pub fn get_role(&self) -> Role { @@ -329,7 +334,6 @@ impl User { pub fn get_avatar_size(&self) -> Option { self.avatar_size } - } #[cfg(test)] diff --git a/src/service/appointment.rs b/src/service/appointment.rs index 4bf7c15..17bff10 100644 --- a/src/service/appointment.rs +++ b/src/service/appointment.rs @@ -405,8 +405,8 @@ mod tests { async fn a_person(db: &Database, label: &str, role: &str) -> UserId { let user = UserId::generate(); sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, $2, 'x', $3)", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, $3)", ) .bind(user.uuid()) .bind(format!("{label}-{}", &user.key()[30..])) diff --git a/src/service/appointment_slot.rs b/src/service/appointment_slot.rs index 5424366..81c34e7 100644 --- a/src/service/appointment_slot.rs +++ b/src/service/appointment_slot.rs @@ -211,8 +211,8 @@ mod tests { async fn a_person(db: &Database, label: &str, role: &str) -> UserId { let user = UserId::generate(); sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, $2, 'x', $3)", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, $3)", ) .bind(user.uuid()) .bind(format!("{label}-{}", &user.key()[30..])) diff --git a/src/service/class_member.rs b/src/service/class_member.rs index 566bac3..55c5dc9 100644 --- a/src/service/class_member.rs +++ b/src/service/class_member.rs @@ -353,15 +353,10 @@ mod tests { let (db, _leases) = crate::database::init_test_db().await; let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; // A real row, because the sweep now rides on the role write. - let hash = crate::domain::user::Password::try_new("secret1") - .unwrap() - .hash_async() - .await - .unwrap(); let account = crate::db::user::create( &db, crate::domain::user::Username::try_new("ogrenci").unwrap(), - hash, + None, ) .await .unwrap(); diff --git a/src/service/exam_attempt.rs b/src/service/exam_attempt.rs index 7f4268c..f8be752 100644 --- a/src/service/exam_attempt.rs +++ b/src/service/exam_attempt.rs @@ -446,8 +446,8 @@ mod tests { // The creator is a foreign key now: a real `app_user` row under the // fixture's fixed key. sqlx::query( - "INSERT INTO app_user (id, username, password_hash) \ - VALUES ($1, 'acdc-fixture', 'x') ON CONFLICT DO NOTHING", + "INSERT INTO app_user (id, username, created_at) \ + VALUES ($1, 'acdc-fixture', 0) ON CONFLICT DO NOTHING", ) .bind(creator.uuid()) .execute(db) @@ -513,15 +513,10 @@ mod tests { /// A real user row: the sitting counter lives on it, and the claim that /// rides the attempt's create has nothing to write to without one. async fn student(db: &Database) -> UserId { - let hash = crate::domain::user::Password::try_new("secret1") - .unwrap() - .hash_async() - .await - .unwrap(); *crate::db::user::create( db, crate::domain::user::Username::try_new("ogrenci").unwrap(), - hash, + None, ) .await .unwrap() diff --git a/src/service/fee_plan_assignment.rs b/src/service/fee_plan_assignment.rs index 3267852..721ec37 100644 --- a/src/service/fee_plan_assignment.rs +++ b/src/service/fee_plan_assignment.rs @@ -221,8 +221,8 @@ mod tests { async fn a_person(db: &Database, label: &str, role: &str) -> UserId { let user = UserId::generate(); sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, $2, 'x', $3)", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, $3)", ) .bind(user.uuid()) .bind(format!("{label}-{}", &user.key()[30..])) diff --git a/src/service/meal_booking.rs b/src/service/meal_booking.rs index 50c1e77..8997122 100644 --- a/src/service/meal_booking.rs +++ b/src/service/meal_booking.rs @@ -314,8 +314,8 @@ mod tests { // The menu's creator is a foreign key now: a real `app_user` row. let creator = UserId::generate(); sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, $2, 'x', 'teacher')", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, 'teacher')", ) .bind(creator.uuid()) .bind(format!("menu-fixture-{}", &creator.key()[30..])) diff --git a/src/service/mod.rs b/src/service/mod.rs index 8f19a7e..431f98a 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -46,6 +46,7 @@ pub mod payment_ledger; pub mod person; pub mod pomodoro; pub mod pool_question; +pub mod pool_question_image; pub mod profile; pub mod question_image; pub mod rag_output; @@ -54,6 +55,7 @@ pub mod session; pub mod session_attendance; pub mod settings; pub mod solution; +pub mod solution_image; pub mod subject; pub mod term; pub mod user; diff --git a/src/service/person.rs b/src/service/person.rs index 3862944..bb4ccf4 100644 --- a/src/service/person.rs +++ b/src/service/person.rs @@ -100,9 +100,8 @@ pub async fn delete_sessions_by_person( person::delete_sessions_by_person(control, person).await } -/// The school-user password writes mirror the person credential: login reads -/// `person.password_hash` and nothing else, so a reset that moved only the -/// school row would reset nothing. +/// Move the credential — the one login reads. The school-side row carries no +/// password at all, so this is the whole credential move. pub async fn set_password_hash( control: &Database, username: &Username, diff --git a/src/service/pool_question.rs b/src/service/pool_question.rs index c333fac..d918545 100644 --- a/src/service/pool_question.rs +++ b/src/service/pool_question.rs @@ -1,14 +1,14 @@ //! Pool-question funnels: ask, the two listings, the approve with its //! 409-vs-404 split, the pending-only image writes, and the delete whose -//! swept solutions ride back for the web layer's blob cleanup. The queries -//! and their transactions live in [`crate::db::pool_question`]; the pure -//! entity and newtypes in [`crate::domain::pool_question`]. +//! swept solutions and collected image blob keys ride back for the web +//! layer's blob cleanup. The queries and their transactions live in +//! [`crate::db::pool_question`]; the pure entity and newtypes in +//! [`crate::domain::pool_question`]. use crate::database::Database; use crate::db::pool_question; use crate::domain::note_file::FileContentType; use crate::domain::pool_question::{PoolQuestion, PoolQuestionId}; -use crate::domain::solution::Solution; use crate::domain::user::UserId; use crate::error::AppError; @@ -56,31 +56,34 @@ pub async fn approve( /// Point the question at a freshly written image blob; `None` means the /// question was approved or deleted mid-upload (the fresh blob is the -/// caller's orphan to take back off disk). +/// caller's orphan to take back off disk). `Some(replaced)` names the blob +/// this upload displaced — the caller's to remove. pub async fn set_image( db: &Database, id: &PoolQuestionId, file: &str, content_type: &FileContentType, size: i64, -) -> Result, AppError> { +) -> Result>, AppError> { pool_question::set_image(db, id, file, content_type, size).await } /// Detach the question's image (pending only, like [`set_image`]); `None` -/// means the question is no longer pending. +/// means the question is no longer pending. `Some(detached)` names the +/// removed blob — `None` inside when there was no image. pub async fn clear_image( db: &Database, id: &PoolQuestionId, -) -> Result, AppError> { +) -> Result>, AppError> { pool_question::clear_image(db, id).await } -/// Delete the question and cascade its solutions; the removed rows come back -/// so the web layer can take every image blob off disk. +/// Delete the question and cascade its solutions; the removed rows and the +/// image blob keys they named come back so the web layer can take every +/// blob off disk. pub async fn delete( db: &Database, id: &PoolQuestionId, -) -> Result)>, AppError> { +) -> Result, AppError> { pool_question::delete(db, id).await } diff --git a/src/service/pool_question_image.rs b/src/service/pool_question_image.rs new file mode 100644 index 0000000..5e08b8c --- /dev/null +++ b/src/service/pool_question_image.rs @@ -0,0 +1,26 @@ +//! Pool-question-photo funnels: the read doors the web layer takes for the +//! blob endpoints and the page bucketing. The writes do not pass through +//! here — they are the question's own guarded transactions in +//! [`crate::service::pool_question`] (`set_image`/`clear_image`/`delete`). + +use crate::database::Database; +use crate::db; +use crate::domain::pool_question::PoolQuestionId; +use crate::domain::pool_question_image::PoolQuestionImage; +use crate::error::AppError; + +/// The question's photo row, if any. +pub async fn read( + db: &Database, + question: &PoolQuestionId, +) -> Result, AppError> { + db::pool_question_image::read(db, question).await +} + +/// The photo rows of a page of questions, in one query. +pub async fn list_for_questions( + db: &Database, + questions: &[&PoolQuestionId], +) -> Result, AppError> { + db::pool_question_image::list_for_questions(db, questions).await +} diff --git a/src/service/solution.rs b/src/service/solution.rs index 61074c3..a426abb 100644 --- a/src/service/solution.rs +++ b/src/service/solution.rs @@ -57,24 +57,35 @@ pub async fn set_body( solution::set_body(db, id, body).await } -/// Point the solution at a freshly written image blob; the *before* row names -/// the replaced blob the caller must remove. +/// Point the solution at a freshly written image blob; `None` means the row +/// was deleted mid-flight (the fresh blob is the caller's orphan to take +/// back off disk). `Some(replaced)` names the blob this upload displaced — +/// the caller's to remove. pub async fn set_image( db: &Database, id: &SolutionId, file: &str, content_type: &FileContentType, size: i64, -) -> Result, AppError> { +) -> Result>, AppError> { solution::set_image(db, id, file, content_type, size).await } -/// Detach the solution's image; the *before* row names the blob the caller -/// must remove. -pub async fn clear_image(db: &Database, id: &SolutionId) -> Result, AppError> { +/// Detach the solution's image; `None` means the row was deleted mid-flight. +/// `Some(detached)` names the removed blob — `None` inside when there was no +/// image. +pub async fn clear_image( + db: &Database, + id: &SolutionId, +) -> Result>, AppError> { solution::clear_image(db, id).await } -pub async fn delete(db: &Database, target: Solution) -> Result { +/// Delete a solution; the pair carries the row and the blob name of the +/// photo it carried (the caller's disk-GC list). `None` = already gone. +pub async fn delete( + db: &Database, + target: Solution, +) -> Result)>, AppError> { solution::delete(db, target).await } diff --git a/src/service/solution_image.rs b/src/service/solution_image.rs new file mode 100644 index 0000000..4c125b6 --- /dev/null +++ b/src/service/solution_image.rs @@ -0,0 +1,23 @@ +//! Solution-photo funnels: the read doors the web layer takes for the blob +//! endpoints and the page bucketing. The writes do not pass through here — +//! they are the solution's own transactions in +//! [`crate::service::solution`] (`set_image`/`clear_image`/`delete`). + +use crate::database::Database; +use crate::db; +use crate::domain::solution::SolutionId; +use crate::domain::solution_image::SolutionImage; +use crate::error::AppError; + +/// The solution's photo row, if any. +pub async fn read(db: &Database, solution: &SolutionId) -> Result, AppError> { + db::solution_image::read(db, solution).await +} + +/// The photo rows of a page of solutions, in one query. +pub async fn list_for_solutions( + db: &Database, + solutions: &[&SolutionId], +) -> Result, AppError> { + db::solution_image::list_for_solutions(db, solutions).await +} diff --git a/src/service/user.rs b/src/service/user.rs index 6fed346..b7ef762 100644 --- a/src/service/user.rs +++ b/src/service/user.rs @@ -8,10 +8,11 @@ use crate::tenant::{Slug, Tenants}; use crate::db::user; use crate::domain::board::Board; use crate::domain::note_file::FileContentType; +use crate::domain::person::PersonId; use crate::domain::preferences::{Language, PaletteColor, Theme}; use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone}; use crate::domain::role::Role; -use crate::domain::user::{Password, PasswordHash, User, UserId, Username}; +use crate::domain::user::{Password, User, UserId, Username}; use crate::error::AppError; /// Idempotent startup seed: guarantee an admin account with this username. @@ -27,6 +28,19 @@ pub async fn ensure_admin( password: Password, ) -> Result<(), AppError> { let db = tenants.get(slug).await?; + // The person half runs first, so the school row can carry the person id + // it is the join key to. Login reads the control-plane credential, so the + // seeded admin needs their `person` row and the membership too. Both + // writes are idempotent (create-or-load never re-keys an existing + // person's password; the membership insert is `ON CONFLICT DO NOTHING`), + // so every boot re-runs them — and a school whose seed predates the + // person half heals on the next boot instead of stranding an admin who + // cannot log in. + let password_hash = password.hash_async().await?; + let person = + crate::service::person::create_or_load(tenants.control(), username.clone(), password_hash) + .await?; + crate::service::person::link_school(tenants.control(), person.get_id(), slug).await?; match user::find_by_username(&db, username.as_str()).await? { Some(user) if user.role == Role::Admin => {} Some(_) => { @@ -36,37 +50,20 @@ pub async fn ensure_admin( ); return Ok(()); } + // One statement, admin from birth. Never create-then-promote: + // an interruption between those two writes leaves a student row + // holding ADMIN_USERNAME, which the `Some(_)` arm above then + // refuses to promote — forever, on every subsequent boot. There + // is no marker that could tell such a row apart from a stranger + // who registered the name first, so the hole cannot be healed + // later; it has to be impossible to open. None => { - // One statement, admin from birth. Never create-then-promote: - // an interruption between those two writes leaves a student row - // holding ADMIN_USERNAME, which the `Some(_)` arm above then - // refuses to promote — forever, on every subsequent boot. There - // is no marker that could tell such a row apart from a stranger - // who registered the name first, so the hole cannot be healed - // later; it has to be impossible to open. - user::create_with_role( - &db, - username.clone(), - password.hash_async().await?, - Role::Admin, - ) - .await?; + user::create_with_role(&db, username, Some(*person.get_id()), Role::Admin).await?; // No `username` field: with OTLP on every event is exported as a // log record, so an account name here leaves the process. tracing::info!("seeded the admin account named by ADMIN_USERNAME"); } } - // The person half: login reads the control-plane credential, so the - // seeded admin needs their `person` row and the membership too. Both - // writes are idempotent (create-or-load never re-keys an existing - // person's password; the membership insert is `ON CONFLICT DO NOTHING`), - // so every boot re-runs them — and a school whose seed predates the - // person half heals on the next boot instead of stranding an admin who - // cannot log in. - let password_hash = password.hash_async().await?; - let person = - crate::service::person::create_or_load(tenants.control(), username, password_hash).await?; - crate::service::person::link_school(tenants.control(), person.get_id(), slug).await?; Ok(()) } @@ -101,15 +98,15 @@ pub async fn set_role( user::set_role_cascade(db, target, role).await } -/// Register a new account — the web layer's row mint. New users always start -/// as [`Role::Student`]; elevation is a separate, admin-only action -/// (see [`set_role`]). +/// Register a new school account for `person` — the web layer's row mint. +/// New users always start as [`Role::Student`]; elevation is a separate, +/// admin-only action (see [`set_role`]). pub async fn create( db: &Database, username: Username, - password_hash: PasswordHash, + person: Option, ) -> Result { - user::create(db, username, password_hash).await + user::create(db, username, person).await } /// Mint a row holding `role` outright — the school-creation path, whose @@ -117,10 +114,10 @@ pub async fn create( pub async fn create_with_role( db: &Database, username: Username, - password_hash: PasswordHash, + person: Option, role: Role, ) -> Result { - user::create_with_role(db, username, password_hash, role).await + user::create_with_role(db, username, person, role).await } /// One user row, for callers that only inspect it — the web layer's reads go @@ -207,15 +204,6 @@ pub async fn clear_avatar(db: &Database, id: &UserId) -> Result, Ap user::clear_avatar(db, id).await } -/// Rewrite the credential — the admin-password reset's store half. -pub async fn set_password_hash( - db: &Database, - id: &UserId, - password_hash: PasswordHash, -) -> Result, AppError> { - user::set_password_hash(db, id, password_hash).await -} - /// Persist the UI-preference fields a PATCH carried. pub async fn set_preferences( db: &Database, @@ -231,20 +219,11 @@ pub async fn set_preferences( mod tests { use super::*; use crate::database::{Database, init_test_db}; - use crate::domain::user::Password; async fn a_user(username: &str, db: &Database) -> User { - user::create( - db, - Username::try_new(username).unwrap(), - Password::try_new("secret1") - .unwrap() - .hash_async() - .await - .unwrap(), - ) - .await - .unwrap() + user::create(db, Username::try_new(username).unwrap(), None) + .await + .unwrap() } /// The board result slot is an *index* into a batch whose length depends on diff --git a/src/web/appointments.rs b/src/web/appointments.rs index 0da2e0b..38b4dd1 100644 --- a/src/web/appointments.rs +++ b/src/web/appointments.rs @@ -902,16 +902,11 @@ async fn ensure_requester( mod tests { use super::*; use crate::database::init_test_db; - use crate::domain::user::{Password, Username}; + use crate::domain::user::Username; /// A user at `role`, minted through the real create path. async fn user(username: &str, role: Role, db: &Database) -> User { - let hash = Password::try_new("secret1") - .unwrap() - .hash_async() - .await - .unwrap(); - let user = crate::service::user::create(db, Username::try_new(username).unwrap(), hash) + let user = crate::service::user::create(db, Username::try_new(username).unwrap(), None) .await .unwrap(); crate::service::user::set_role(db, user.get_id(), role).await.unwrap().0 diff --git a/src/web/auth.rs b/src/web/auth.rs index 5e4aaec..eb6887b 100644 --- a/src/web/auth.rs +++ b/src/web/auth.rs @@ -200,7 +200,7 @@ async fn register( // each half is idempotent and a retry after a torn pair completes // it). A taken school username means the person is already a member // — the same 201. - match service::user::create(&db, username, password_hash).await { + match service::user::create(&db, username, Some(*person.get_id())).await { Ok(_) => {} Err(AppError::Conflict(_)) => { tracing::info!("register: school username already taken, answering 201"); diff --git a/src/web/bank_questions.rs b/src/web/bank_questions.rs index 566504d..872d0c7 100644 --- a/src/web/bank_questions.rs +++ b/src/web/bank_questions.rs @@ -923,16 +923,11 @@ mod tests { use super::*; use crate::database::{Database, init_test_db}; use crate::domain::role::Role; - use crate::domain::user::{Password, Username}; + use crate::domain::user::Username; /// A user at `role`, minted through the real create path. async fn user(username: &str, role: Role, db: &Database) -> User { - let hash = Password::try_new("secret1") - .unwrap() - .hash_async() - .await - .unwrap(); - let user = crate::service::user::create(db, Username::try_new(username).unwrap(), hash) + let user = crate::service::user::create(db, Username::try_new(username).unwrap(), None) .await .unwrap(); crate::service::user::set_role(db, user.get_id(), role) diff --git a/src/web/board_ws.rs b/src/web/board_ws.rs index 128fa83..ce54d02 100644 --- a/src/web/board_ws.rs +++ b/src/web/board_ws.rs @@ -672,24 +672,15 @@ mod tests { #[tokio::test] async fn a_demotion_bars_the_open_socket_from_every_write() { use crate::domain::board::BoardTitle; - use crate::domain::user::{Password, Username}; + use crate::domain::user::Username; let (db, _leases) = crate::database::init_test_db().await; - let password = Password::try_new("secret1").unwrap(); - let creator = crate::service::user::create( - &db, - Username::try_new("ogretmen").unwrap(), - password.hash_async().await.unwrap(), - ) - .await - .unwrap(); - let mate = crate::service::user::create( - &db, - Username::try_new("ogrenci").unwrap(), - password.hash_async().await.unwrap(), - ) - .await - .unwrap(); + let creator = crate::service::user::create(&db, Username::try_new("ogretmen").unwrap(), None) + .await + .unwrap(); + let mate = crate::service::user::create(&db, Username::try_new("ogrenci").unwrap(), None) + .await + .unwrap(); let mate_id = *mate.get_id(); let board = board::create( &db, diff --git a/src/web/builder.rs b/src/web/builder.rs index 2f67cbc..40c38b7 100644 --- a/src/web/builder.rs +++ b/src/web/builder.rs @@ -371,7 +371,8 @@ async fn create_school( let db = st.tenants.create(&slug, &name, modules).await?; let seeded = async { - crate::service::user::create_with_role(&db, username, password_hash, Role::Admin).await?; + crate::service::user::create_with_role(&db, username, Some(*person.get_id()), Role::Admin) + .await?; // The admin's person gets the membership the school row answers for — // idempotent, so a retried create after a torn pair completes it. service::person::link_school(&st.db, person.get_id(), &slug).await?; @@ -774,12 +775,8 @@ async fn reset_admin_password( let user = school_admin(&req.username, &db).await?; let password_hash = Password::try_new(&req.password)?.hash_async().await?; - crate::service::user::set_password_hash(&db, user.get_id(), password_hash.clone()) - .await? - .ok_or(AppError::NotFound)?; - // The person credential is the one login reads; the school row's copy - // exists so school-side queries keep compiling. Both move together, or a - // reset would leave the old password working everywhere. + // The credential is the control person's — the one login reads. The + // school row carries no password at all. service::person::set_password_hash(&st.db, user.get_username(), &password_hash).await?; // The other half: the new password means nothing while a cookie minted // under the old one still authenticates — school sessions *and* any diff --git a/src/web/chatbot.rs b/src/web/chatbot.rs index bbd0031..2e82864 100644 --- a/src/web/chatbot.rs +++ b/src/web/chatbot.rs @@ -907,8 +907,8 @@ mod tests { let user = UserId::from_key("019732e3-7b00-7000-8000-00000000cafe"); let thread = ChatbotThreadId::from_key("019732e3-7b00-7000-8000-00000000beef"); sqlx::query( - "INSERT INTO app_user (id, username, password_hash) \ - VALUES ($1, 'chat-web-fixture', 'x')", + "INSERT INTO app_user (id, username, created_at) \ + VALUES ($1, 'chat-web-fixture', 0)", ) .bind(user.uuid()) .execute(&db) diff --git a/src/web/classes.rs b/src/web/classes.rs index 7a639bd..45b3bc5 100644 --- a/src/web/classes.rs +++ b/src/web/classes.rs @@ -1494,24 +1494,16 @@ mod tests { #[tokio::test] async fn an_empty_teacher_is_no_teacher_and_a_student_is_never_one() { use crate::domain::role::Role; - use crate::domain::user::{Password, Username}; + use crate::domain::user::Username; let (db, _leases) = crate::database::init_test_db().await; assert!(teacher_or_none(None, &db).await.unwrap().is_none()); assert!(teacher_or_none(Some(""), &db).await.unwrap().is_none()); let make = async |name: &str, role: Role| { - let user = crate::service::user::create( - &db, - Username::try_new(name).unwrap(), - Password::try_new("secret1") - .unwrap() - .hash_async() - .await - .unwrap(), - ) - .await - .unwrap(); + let user = crate::service::user::create(&db, Username::try_new(name).unwrap(), None) + .await + .unwrap(); crate::service::user::set_role(&db, user.get_id(), role) .await .unwrap() diff --git a/src/web/courses.rs b/src/web/courses.rs index 15d0775..d68515a 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -1283,16 +1283,11 @@ async fn list_course_sessions( mod tests { use super::*; use crate::database::init_test_db; - use crate::domain::user::{Password, Username}; + use crate::domain::user::Username; /// A user at `role`, minted through the real create path. async fn user(username: &str, role: Role, db: &Database) -> User { - let hash = Password::try_new("secret1") - .unwrap() - .hash_async() - .await - .unwrap(); - let user = crate::service::user::create(db, Username::try_new(username).unwrap(), hash) + let user = crate::service::user::create(db, Username::try_new(username).unwrap(), None) .await .unwrap(); crate::service::user::set_role(db, user.get_id(), role) diff --git a/src/web/events.rs b/src/web/events.rs index 863f14e..ac6c602 100644 --- a/src/web/events.rs +++ b/src/web/events.rs @@ -913,16 +913,11 @@ async fn unregister( mod tests { use super::*; use crate::database::init_test_db; - use crate::domain::user::{Password, Username}; + use crate::domain::user::Username; /// A user at `role`, minted through the real create path. async fn user(username: &str, role: Role, db: &Database) -> User { - let hash = Password::try_new("secret1") - .unwrap() - .hash_async() - .await - .unwrap(); - let user = crate::service::user::create(db, Username::try_new(username).unwrap(), hash) + let user = crate::service::user::create(db, Username::try_new(username).unwrap(), None) .await .unwrap(); crate::service::user::set_role(db, user.get_id(), role) diff --git a/src/web/mod.rs b/src/web/mod.rs index 88d762a..03adf55 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -378,21 +378,13 @@ mod tests { async fn undo_if_demoted_repairs_both_assignments_or_neither() { use crate::domain::class_group::ClassName; use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; - use crate::domain::user::{Password, Username}; + use crate::domain::user::Username; let (db, _leases) = crate::database::init_test_db().await; let office = crate::db::class_member::tests::fixture_user(&db, "office").await; - let teacher = crate::service::user::create( - &db, - Username::try_new("ada").unwrap(), - Password::try_new("secret1") - .unwrap() - .hash_async() - .await - .unwrap(), - ) - .await - .unwrap(); + let teacher = crate::service::user::create(&db, Username::try_new("ada").unwrap(), None) + .await + .unwrap(); crate::service::user::set_role(&db, teacher.get_id(), Role::Teacher) .await .unwrap(); diff --git a/src/web/questions.rs b/src/web/questions.rs index 29a0873..b95e7b0 100644 --- a/src/web/questions.rs +++ b/src/web/questions.rs @@ -8,7 +8,8 @@ //! opposite: unmoderated, so their author may edit the body and attach, //! replace, or drop one photo at any time — moderation there is delete-only. -use crate::web::tenant_state::State; +use std::collections::HashMap; + use axum::Json; use axum::extract::{DefaultBodyLimit, Multipart, Path, Query}; use axum::http::StatusCode; @@ -22,13 +23,18 @@ use crate::constant::{MAX_MAX_FILE_BYTES, POOL_QUESTION_STATUSES, UPLOAD_BODY_OV use crate::domain::pool_question::{ PoolQuestion, PoolQuestionBody, PoolQuestionId, PoolQuestionTitle, }; +use crate::domain::pool_question_image::PoolQuestionImage; use crate::domain::role::Role; use crate::domain::solution::{Solution, SolutionBody, SolutionId}; +use crate::domain::solution_image::SolutionImage; use crate::domain::user::User; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::service::pool_question; +use crate::service::pool_question_image; use crate::service::solution; +use crate::service::solution_image; use crate::state::AppState; +use crate::web::tenant_state::State; use super::{ CurrentUser, Page, PageParams, PersonRef, RequireStudent, RequireTeacher, UploadFileForm, @@ -157,6 +163,7 @@ impl PoolQuestionResponse { question: &PoolQuestion, people: &std::collections::HashMap, solution_count: i64, + image: Option<&PoolQuestionImage>, ) -> Self { Self { id: question.get_id().key().to_string(), @@ -168,12 +175,10 @@ impl PoolQuestionResponse { approved_by: question .get_approved_by() .map(|approver| PersonRef::resolve(people, approver)), - image: question - .get_image_content_type() - .map(|content_type| PoolImageMeta { - content_type: content_type.as_str().to_string(), - size: question.get_image_size().unwrap_or(0), - }), + image: image.map(|image| PoolImageMeta { + content_type: image.get_content_type().as_str().to_string(), + size: image.get_size(), + }), solution_count, } } @@ -196,19 +201,21 @@ struct SolutionResponse { } impl SolutionResponse { - fn new(solution: &Solution, people: &std::collections::HashMap) -> Self { + fn new( + solution: &Solution, + people: &std::collections::HashMap, + image: Option<&SolutionImage>, + ) -> Self { Self { id: solution.get_id().key().to_string(), question: solution.get_question().key().to_string(), author: PersonRef::resolve(people, solution.get_author()), body: solution.get_body().as_str().to_string(), offered_at: solution.get_offered_at().as_millis(), - image: solution - .get_image_content_type() - .map(|content_type| PoolImageMeta { - content_type: content_type.as_str().to_string(), - size: solution.get_image_size().unwrap_or(0), - }), + image: image.map(|image| PoolImageMeta { + content_type: image.get_content_type().as_str().to_string(), + size: image.get_size(), + }), } } } @@ -229,11 +236,19 @@ async fn question_responses( .map(|question| *question.get_id()) .collect(); let counts = solution::counts_for(&st.db, &question_ids).await?; + // The photos bucket onto the page in one query, exactly like the + // solution tallies — never an image read per row. + let image_refs: Vec<&PoolQuestionId> = questions.iter().map(|q| q.get_id()).collect(); + let mut images: HashMap = HashMap::new(); + for image in pool_question_image::list_for_questions(&st.db, &image_refs).await? { + images.insert(image.get_question().key(), image); + } Ok(questions .iter() .map(|question| { let count = counts.get(&question.get_id().key()).copied().unwrap_or(0); - PoolQuestionResponse::new(question, &people, count) + let image = images.get(question.get_id().key().as_str()); + PoolQuestionResponse::new(question, &people, count, image) }) .collect()) } @@ -426,19 +441,14 @@ async fn delete_question( "only the asker or a teacher+ may delete a question", )); } - let (removed, swept) = pool_question::delete(&st.db, question.get_id()) + let removed = pool_question::delete(&st.db, question.get_id()) .await? .ok_or(AppError::NotFound)?; - // Rows went first (in one transaction); now every blob they pointed at — - // the question's photo and each swept solution's — comes off disk. - if let Some(file) = removed.get_image_file() { + // Rows went first (in one transaction); now every blob they named — the + // question's photo and each swept solution's — comes off disk. + for file in &removed.image_files { remove_blob(&st.files_path, file).await; } - for solution in &swept { - if let Some(file) = solution.get_image_file() { - remove_blob(&st.files_path, file).await; - } - } Ok(StatusCode::NO_CONTENT) } @@ -489,7 +499,7 @@ async fn upload_image( { // The guarded UPDATE found the question still pending: point-of-truth // write done; the replaced blob (if any) comes off disk. - Some(before) => Ok(((), before.get_image_file().map(str::to_string))), + Some(replaced) => Ok(((), replaced)), // Approved or deleted mid-upload — the fresh blob is an orphan. None => Err(AppError::Conflict("the question is no longer pending")), } @@ -526,11 +536,12 @@ async fn get_image( ) -> Result { let question = question_or_404(&st, &id).await?; ensure_visible(&question, &user)?; - match (question.get_image_file(), question.get_image_content_type()) { - (Some(file), Some(content_type)) => { - serve_inline_blob(&st.files_path, file, content_type).await + let image = pool_question_image::read(&st.db, question.get_id()).await?; + match image { + Some(image) => { + serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await } - _ => Err(AppError::NotFound), + None => Err(AppError::NotFound), } } @@ -557,16 +568,17 @@ async fn delete_image( ) -> Result { let question = question_or_404(&st, &id).await?; ensure_asker_editable(&question, &user)?; - if question.get_image_file().is_none() { - return Err(AppError::NotFound); - } - let before = pool_question::clear_image(&st.db, question.get_id()) - .await? - .ok_or(AppError::Conflict("the question is no longer pending"))?; - if let Some(file) = before.get_image_file() { - remove_blob(&st.files_path, file).await; + match pool_question::clear_image(&st.db, question.get_id()).await? { + // Detached: the blob comes off disk. + Some(Some(file)) => { + remove_blob(&st.files_path, &file).await; + Ok(StatusCode::NO_CONTENT) + } + // Still pending, but there was no image to remove. + Some(None) => Err(AppError::NotFound), + // Approved or deleted mid-flight — content is frozen or gone. + None => Err(AppError::Conflict("the question is no longer pending")), } - Ok(StatusCode::NO_CONTENT) } // ---- solutions -------------------------------------------------------------- @@ -647,7 +659,7 @@ async fn offer_solution( let people = person_map([*user.get_id()], &st.db).await?; Ok(( StatusCode::CREATED, - Json(SolutionResponse::new(&solution, &people)), + Json(SolutionResponse::new(&solution, &people, None)), )) } @@ -678,14 +690,18 @@ async fn list_solutions( ensure_visible(&question, &user)?; let (solutions, total) = solution::list_for(&st.db, question.get_id(), limit, offset).await?; let slice = solutions.as_slice(); - let people = person_map( - slice.iter().map(|solution| *solution.get_author()), - &st.db, - ) - .await?; + let people = person_map(slice.iter().map(|solution| *solution.get_author()), &st.db).await?; + let solution_refs: Vec<&SolutionId> = slice.iter().map(|s| s.get_id()).collect(); + let mut images: HashMap = HashMap::new(); + for image in solution_image::list_for_solutions(&st.db, &solution_refs).await? { + images.insert(image.get_solution().key(), image); + } let items = slice .iter() - .map(|solution| SolutionResponse::new(solution, &people)) + .map(|solution| { + let image = images.get(solution.get_id().key().as_str()); + SolutionResponse::new(solution, &people, image) + }) .collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -721,9 +737,11 @@ async fn delete_solution( } // Row first, blob after — a crash in between strands at worst an // unreachable file. - let deleted = solution::delete(&st.db, solution).await?; - if let Some(file) = deleted.get_image_file() { - remove_blob(&st.files_path, file).await; + let (_, image) = solution::delete(&st.db, solution) + .await? + .ok_or(AppError::NotFound)?; + if let Some(file) = image { + remove_blob(&st.files_path, &file).await; } Ok(StatusCode::NO_CONTENT) } @@ -764,7 +782,12 @@ async fn edit_solution( .await? .ok_or(AppError::NotFound)?; let people = person_map([*user.get_id()], &st.db).await?; - Ok(Json(SolutionResponse::new(&updated, &people))) + let image = solution_image::read(&st.db, updated.get_id()).await?; + Ok(Json(SolutionResponse::new( + &updated, + &people, + image.as_ref(), + ))) } // ---- the solution's photo --------------------------------------------------- @@ -814,7 +837,7 @@ async fn upload_solution_image( .await? { // Row write done; the replaced blob (if any) comes off disk. - Some(before) => Ok(((), before.get_image_file().map(str::to_string))), + Some(replaced) => Ok(((), replaced)), // Deleted mid-upload — the fresh blob is an orphan. None => Err(AppError::NotFound), } @@ -854,11 +877,12 @@ async fn get_solution_image( Path((id, sid)): Path<(String, String)>, ) -> Result { let solution = visible_solution(&st, &user, &id, &sid).await?; - match (solution.get_image_file(), solution.get_image_content_type()) { - (Some(file), Some(content_type)) => { - serve_inline_blob(&st.files_path, file, content_type).await + let image = solution_image::read(&st.db, solution.get_id()).await?; + match image { + Some(image) => { + serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await } - _ => Err(AppError::NotFound), + None => Err(AppError::NotFound), } } @@ -886,14 +910,13 @@ async fn delete_solution_image( Path((id, sid)): Path<(String, String)>, ) -> Result { let solution = author_solution(&st, &user, &id, &sid).await?; - if solution.get_image_file().is_none() { - return Err(AppError::NotFound); - } - let before = solution::clear_image(&st.db, solution.get_id()) - .await? - .ok_or(AppError::NotFound)?; - if let Some(file) = before.get_image_file() { - remove_blob(&st.files_path, file).await; + match solution::clear_image(&st.db, solution.get_id()).await? { + // Detached: the blob comes off disk. + Some(Some(file)) => { + remove_blob(&st.files_path, &file).await; + Ok(StatusCode::NO_CONTENT) + } + // Gone, or there was no image to remove. + _ => Err(AppError::NotFound), } - Ok(StatusCode::NO_CONTENT) } diff --git a/src/web/tenant_state.rs b/src/web/tenant_state.rs index 17df3e4..c7ad8c6 100644 --- a/src/web/tenant_state.rs +++ b/src/web/tenant_state.rs @@ -203,17 +203,9 @@ mod tests { .await .expect("the demo school"); - let user = crate::service::user::create( - &school, - Username::try_new("ada").unwrap(), - Password::try_new("secret1") - .unwrap() - .hash_async() - .await - .unwrap(), - ) - .await - .unwrap(); + let user = crate::service::user::create(&school, Username::try_new("ada").unwrap(), None) + .await + .unwrap(); let session = session::create(&school, user.get_id()).await.unwrap(); let school_cookie = format!("session={DEMO_SLUG}.{}", session.token().as_str()); diff --git a/tests/builder_api.rs b/tests/builder_api.rs index 0917026..6882ae7 100644 --- a/tests/builder_api.rs +++ b/tests/builder_api.rs @@ -425,17 +425,9 @@ async fn resetting_an_admin_password_revokes_the_old_credential_and_its_sessions .get(&hezarfen_backend::tenant::Slug::try_new("gamma").unwrap()) .await .unwrap(); - hezarfen_backend::db::user::create( - &gamma_db, - Username::try_new("veli").unwrap(), - Password::try_new("secret1") - .unwrap() - .hash_async() - .await - .unwrap(), - ) - .await - .unwrap(); + hezarfen_backend::db::user::create(&gamma_db, Username::try_new("veli").unwrap(), None) + .await + .unwrap(); assert_eq!( send( &app, diff --git a/tests/regress_classes.rs b/tests/regress_classes.rs index 768911b..25c687d 100644 --- a/tests/regress_classes.rs +++ b/tests/regress_classes.rs @@ -35,8 +35,8 @@ async fn rows(sql: &'static str, db: &Database) -> i64 { /// hash is a stub. async fn fixture_user(db: &Database, username: &str) -> UserId { sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, $2, 'x', 'student') ON CONFLICT DO NOTHING", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, 'student') ON CONFLICT DO NOTHING", ) .bind(UserId::generate().uuid()) .bind(username) diff --git a/tests/regress_course_child_orphans.rs b/tests/regress_course_child_orphans.rs index 6b149b2..1c83612 100644 --- a/tests/regress_course_child_orphans.rs +++ b/tests/regress_course_child_orphans.rs @@ -60,8 +60,8 @@ async fn teacher(db: &Database) -> UserId { // Creator columns are foreign keys now, so the fixture teacher is a row, // not a fabricated id. It never logs in, so the hash is a stub. sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, 'doktor', 'x', 'teacher') ON CONFLICT DO NOTHING", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, 'doktor', 0, 'teacher') ON CONFLICT DO NOTHING", ) .bind(UserId::generate().uuid()) .execute(db) diff --git a/tests/regress_payments.rs b/tests/regress_payments.rs index 2f27ff7..6da3e6f 100644 --- a/tests/regress_payments.rs +++ b/tests/regress_payments.rs @@ -61,8 +61,8 @@ async fn ledger(app: &axum::Router, mgr: &str, student: &str) -> Vec { /// hash is a stub. async fn fixture_user(db: &Database, username: &str) -> UserId { sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, $2, 'x', 'student') ON CONFLICT DO NOTHING", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, 'student') ON CONFLICT DO NOTHING", ) .bind(UserId::generate().uuid()) .bind(username) diff --git a/tests/regress_role_sweep.rs b/tests/regress_role_sweep.rs index 0035abb..1ff610b 100644 --- a/tests/regress_role_sweep.rs +++ b/tests/regress_role_sweep.rs @@ -61,8 +61,8 @@ async fn counter(column: &str, table: &str, db: &Database) -> i64 { /// whichever call minted it. These actors never log in, so the hash is a stub. async fn fixture_actor(db: &Database, username: &str) -> UserId { sqlx::query( - "INSERT INTO app_user (id, username, password_hash, role) \ - VALUES ($1, $2, 'x', 'student') ON CONFLICT DO NOTHING", + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, 'student') ON CONFLICT DO NOTHING", ) .bind(UserId::generate().uuid()) .bind(username)