From 57fad2c07b2395b558338e2c6a912aa9a736aa69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 14 Sep 2026 14:41:50 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20compose-stack=20deploy=20pl?= =?UTF-8?q?us=20in-tree=20schema=20work?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Production deploy is podman compose (postgres + backend + openobserve) instead of a systemd binary. CI stays a throwaway postgres sidecar. Operator credentials live in ~/hezarfen_backend/hezarfen_backend.env (0600); the deploy never writes that file. Also lands the working-tree schema/junction and .sqlx updates that were already sitting next to this change. --- .github/workflows/main.yml | 324 ++++++++++------ ...c98da0c49fac2b2f178ec9a521f6b070aca70.json | 14 + ...87840bfde048747904ead52da7a2a6961f9a2.json | 15 - ...074eb43d881555a2d278f30abf5ef6b4cef54.json | 14 + ...50ff42e92738d5bf32d42b3471178a0439d7b.json | 136 ------- ...8cd309907f23262685f8b3b267399f06ff730.json | 16 + ...824bacb3b971bb88a99db0fbeb148045048d.json} | 19 +- ...b0d075c1d724f9f0b05890953e52cbe4f08e3.json | 14 + ...144f303f578b1048bf96689e513848eca9185.json | 40 ++ ...a27ef52f014385003a3b5c3c1fae1768de6b.json} | 15 +- ...c9970bcc3aea1a65bb486f4510803f4d0019.json} | 24 +- ...86650a361821b38809f8cc2c8b28a01952c83.json | 14 - ...c0c46b1e0aa1efe82ea16208b41b253de74d9.json | 15 + ...511e77c81d4e7efe639591f7db00efaca2f54.json | 15 + ...3f70b916a6273b29e768e303d612a29609fb1.json | 15 + ...3cb74660d9bbddaa7fc876d2230184f3430c.json} | 15 +- ...891866199a2dd3d3c822cccc471061d842c71.json | 155 -------- ...c9f44414871c3bca6f106e33eea0aaf7ba82e.json | 28 ++ ...4810dd0a8bfb1290a626ae40f31ca469a632.json} | 24 +- ...4e7bf1fb475a7aefa88b9ce817ee05ad8582.json} | 15 +- ...4f0a47d8f3231e8fdfe3dfe60ae82eacf532.json} | 18 +- ...203c9eea7308e773738dfd905a9eb131dcb2.json} | 4 +- ...a0dc99b92d06993df0e078263d773feb3fff1.json | 2 +- ...428bdccf4e2d95f2499d9feb46ff6238f51d.json} | 4 +- ...649c8707018d8af8f511c04310aa2357d8a4b.json | 15 + ...1e68d2e630763fc4732795891e4243e5e0eea.json | 15 + ...68dc81304180cd047d1ae2b65951528e1d4b1.json | 14 + ...a6cc355fa9ce81fc609ad25450d2a1d8cf555.json | 18 + ...80b6974dff0cb59238f7ab0e1b51a389e6b1.json} | 4 +- ...736c7f8df98bf1a17083a72371155b0b553d.json} | 27 +- ...d2985cdd8768d31b752c235d4d5bbc2549d1.json} | 18 +- ...56f471b95a2e0c99a880e428f5550abc05695.json | 14 + ...43ea62604494f00d597051e46eba1ae56625d.json | 12 + ...a672b6ecd3a55bebac6efa1ade9a7620b564a.json | 14 + ...2062f7c591143cdb056bf5a250235bbb12609.json | 14 + ...bc35b300037ef875d14026eaa226d3e543ef9.json | 14 + ...71b205edd9f9550412eeba7f22e16a16971f2.json | 113 ------ ...0fe0412bbf6be669731377fa8bf033f5cc072.json | 14 + ...6717830c3ca1ff9954c376d6c9c674ff4b5b.json} | 15 +- ...3229d4ba5108df18938a8629ecfb70725b5ff.json | 40 ++ ...d93332990a094273f6ac2adb05bf94397010f.json | 14 - ...70c13768fb537393c70e006466df156a319a2.json | 105 ++++++ ...2709ac1102fcafffd227c1fa1dc4e36a944af.json | 28 ++ ...d195587319a4ab757166a046b394e86938a5.json} | 5 +- ...fae53259b9db0048d350758a546836021e3c.json} | 22 +- ...74aca9089ae24b9d87521a134267f4f76caa.json} | 7 +- ...0d7b7d17420cdc12bd26939b3eca27088d275.json | 14 + ...19918a413158e9446b39fe5b69da534810e60.json | 15 - ...7e573b36ded45dc3f8050b95ea6823ae3177a.json | 14 + ...dd9ad20d54e788a7af2e04e50658bcc1c45c.json} | 15 +- ...486869381275626163e8bd75e928188875b1.json} | 24 +- ...729e250ce149537408ac7b0124b3d33582980.json | 14 - ...5198f1bf92d9a7b4984b227849771bec8699.json} | 4 +- ...2d0c176065c36a5ba34a1757c9f3cef17d15f.json | 132 +++++++ ...91d188bfff40e5e1e0af2789e92ca110c71f.json} | 24 +- ...bb8a71f134255f4f9283bbde0e90537c6501.json} | 15 +- ...9108aabe3ddb6dc9522530787d3fa632b595.json} | 4 +- ...1610a2d9f88eee804fad8c4936cd23e4770d3.json | 14 + ...381d01bd34a4f4a6559c362499376a0518bfd.json | 12 + ...9e8fb9c8d3bffb022d47939e9ee0269eb764a.json | 15 + ...c45fafa1e717db6630c7e3fde77816d9e3a7.json} | 4 +- ...eed4cc0cbc04fc93ff05b33e6c70a91116e2.json} | 10 +- ...42314670484e5eacfdcf9b4fec3ed887b6b0d.json | 15 + ...46978aa69cbda3bd53e1c79157f840edf1443.json | 107 ------ ...a4db6a284b2f95e0fe8a69bbec9117f5d0a0.json} | 4 +- ...b5eb01f3868fd3d98bd29a9efc85a80176e95.json | 18 + ...31da05a618a6ab0e628482399affad99261c8.json | 137 +++++++ ...f349fb341315f8899c7c61cd669916f292609.json | 105 ------ ...af732f6ab3b158fad47d4daab3c52426e9564.json | 120 ------ ...abc72dc0058951a26855a52cc688e21e21685.json | 15 + ...fc868d6fb3c91a7ba9ae5b553dfb48be9353.json} | 4 +- ...8cc313f9c8ddd2afd3a9728462819f5db30dd.json | 14 + ...42a877dfac056dea7b17e702bdea174b0993a.json | 15 + ...d18a7b8397112582a9d8a0c386491e1c2bfad.json | 15 + ...6b36c168cb3c9ddbf00ebb402e8598b995f13.json | 14 + ...660d9b628c5529195edfbe634c2c21818a345.json | 28 ++ ...88a7365573ea7f566f9ff3f625e6a034d181c.json | 14 + ...337dfa6d93ddd6e5909c4fd6950e2e468ad6e.json | 138 ------- ...c803494d402b4611dbfb646d8973af96896a.json} | 15 +- ...47c918f564d0022954a7efc0e98dc8d03df4.json} | 15 +- ...f306f157f5275587ae57d1e5146c9a76a51d3.json | 17 - ...2bee96cd9acec380c29c4006c9d68f5becd57.json | 40 ++ ...a7798ced19472830ac9421f024eb43c784318.json | 15 + ...e76093cdd89e6173043354ee6ee66e7c2a518.json | 113 ------ ...ec7eab955fb80167fec8768a381cd012f4b5.json} | 22 +- ...4dd17acb47f65cca634b739f9ff6cd0a6894.json} | 4 +- ...85f8c0d229a7a83b23fb3ba02c1e6b675fe6.json} | 22 +- ...bb80ed92b3f86eef355cc301bcb1178d3ca4d.json | 137 ------- ...88979bc2758176b486ac554a763653e04c718.json | 24 ++ ...1ab4392ea31250f0c00db33e0864a33dfde42.json | 14 + ...ae1a44da4173d3d7e10b6e2e3dddad51d952e.json | 15 + ...285a17bd52337a3b586b99deb4bfc5250bbe5.json | 28 ++ ...9396b9a134f3b85a727c8fb08b01c9fa1fd6b.json | 20 + ...7688b2d1a239f0604d945885c1c3a09b305b4.json | 21 ++ ...8e33b7c575b5510df2bf6547c818481be5eaa.json | 15 + ...49cd7f9e911516b7615c36e1dfe07959ff51c.json | 145 -------- ...236148b27134bbec41d9084704143e35d90ea.json | 14 + ...fa97a212a9111135b4ca576962cc64267757.json} | 15 +- ...9d13f43f251bc7276d1a6b6fe249920677ad.json} | 4 +- ...97b1f4786e15116846e0288035e6ef1ca091.json} | 4 +- ...2942bc8828d833df5fe56e8201b2aa8cae80c.json | 15 + ...202947538687c018b94967578f68be3358864.json | 14 + ...82392ba1739904fcb1d40006e34c78d4afa9.json} | 4 +- ...bbb68a2b726f7a1c98068d506d51aa52785e.json} | 24 +- ...2e425f8a349b2715ae2062fdda16d1c86d00.json} | 15 +- ...0ce84a117296bdf0c18e643293bb0b1e153e.json} | 15 +- README.md | 90 ++++- compose.yaml | 95 ++--- deploy/Containerfile.runtime | 37 ++ deploy/backup-postgres.sh | 26 ++ deploy/hezarfen-compose.service | 47 +++ deploy/hezarfen.service | 41 -- deploy/hezarfen_backend.env.example | 67 ++++ migrations/control/20260912000001_control.sql | 29 +- migrations/control/20260913000001_person.sql | 4 +- migrations/school/20260912000001_identity.sql | 38 +- migrations/school/20260912000002_courses.sql | 55 ++- migrations/school/20260912000003_exams.sql | 14 +- .../20260912000004_food_appointments_fees.sql | 24 +- src/database.rs | 30 +- src/db/board.rs | 251 ++++++++----- src/db/board_stroke.rs | 4 +- src/db/class_blueprint.rs | 303 +++++++++++---- src/db/course.rs | 308 +++++++++------ src/db/course_note.rs | 9 + src/db/dietary_profile.rs | 96 +++-- src/db/homework.rs | 288 ++++++++++---- src/db/homework_submission.rs | 6 +- src/db/menu.rs | 12 +- src/db/menu_dish.rs | 108 ++++-- src/db/note.rs | 9 + src/db/person.rs | 21 +- src/db/rag_output.rs | 295 +++++++++++---- src/db/settings.rs | 351 +++++++++++------- src/db/user.rs | 48 ++- src/domain/class_blueprint.rs | 13 +- src/domain/course.rs | 8 +- src/domain/dietary_profile.rs | 3 +- src/domain/homework.rs | 11 +- src/domain/menu_dish.rs | 5 +- src/domain/rag_output.rs | 15 +- src/service/board.rs | 10 +- src/service/class_blueprint.rs | 20 +- src/service/course.rs | 9 +- src/service/rag_output.rs | 6 +- src/tenant.rs | 313 ++++++++++------ src/web/builder.rs | 18 +- src/web/course_notes.rs | 33 +- tests/ai_bridge.rs | 7 +- tests/ai_protocol.rs | 1 + tests/builder_api.rs | 14 +- tests/common/mod.rs | 1 + tests/integration.rs | 48 ++- tests/persistence.rs | 100 ++--- tests/regress_blueprints.rs | 69 ++-- tests/regress_classes.rs | 2 +- 156 files changed, 3966 insertions(+), 2842 deletions(-) create mode 100644 .sqlx/query-000fbca60257b293277232cb808c98da0c49fac2b2f178ec9a521f6b070aca70.json delete mode 100644 .sqlx/query-0345094de481bdd86f0ac699bc987840bfde048747904ead52da7a2a6961f9a2.json create mode 100644 .sqlx/query-03c775aaaa23fc44b29fe4a4d64074eb43d881555a2d278f30abf5ef6b4cef54.json delete mode 100644 .sqlx/query-095bbc7dc251d30a4ae7bfaf71d50ff42e92738d5bf32d42b3471178a0439d7b.json create mode 100644 .sqlx/query-13a9d4d1e07a6bd0ab6bcd5d0798cd309907f23262685f8b3b267399f06ff730.json rename .sqlx/{query-8c4b65a9c0a081238e9f3d154ee1e2cef90809aa9c81ba4a2109ffaf8caf4170.json => query-171dde095199b0d28722a55df522824bacb3b971bb88a99db0fbeb148045048d.json} (63%) create mode 100644 .sqlx/query-1849fc54c3514fc57c3ad18cc02b0d075c1d724f9f0b05890953e52cbe4f08e3.json create mode 100644 .sqlx/query-1ab734e07505d4c74ae50901fb3144f303f578b1048bf96689e513848eca9185.json rename .sqlx/{query-0c551290ec429e8663d0cd33e307b195d00ed6a90dbd095f9066c87ec9cec8b3.json => query-1c45fc4d105c7dc58a1145c9921fa27ef52f014385003a3b5c3c1fae1768de6b.json} (79%) rename .sqlx/{query-5e5f34152d7edc6330e583d24ae75d9d3486569a45b1dd375f7298e542e410a6.json => query-1f177f50cbca268c6586d099964dc9970bcc3aea1a65bb486f4510803f4d0019.json} (74%) delete mode 100644 .sqlx/query-25e11c52a36dd51246aaa35fb7b86650a361821b38809f8cc2c8b28a01952c83.json create mode 100644 .sqlx/query-26379a9428e3236693332d0c236c0c46b1e0aa1efe82ea16208b41b253de74d9.json create mode 100644 .sqlx/query-27a509ab3a8873474dffaa26b61511e77c81d4e7efe639591f7db00efaca2f54.json create mode 100644 .sqlx/query-27dd38ebf96a18059c72db4b6b23f70b916a6273b29e768e303d612a29609fb1.json rename .sqlx/{query-0a2e0d2d5ca8d25286d988af36998657122706c2873ed4ed1b499f262a4c78d9.json => query-284241b54bd6674d3d77a88d5cb63cb74660d9bbddaa7fc876d2230184f3430c.json} (80%) delete mode 100644 .sqlx/query-290550b5ce584441f5343802004891866199a2dd3d3c822cccc471061d842c71.json create mode 100644 .sqlx/query-2a15712642955d8e832f14d5173c9f44414871c3bca6f106e33eea0aaf7ba82e.json rename .sqlx/{query-aeb5df78c83af8be112917b0cf0b034e94d2b305db968ffaae53785a3af93dab.json => query-2ab51ad375937884da43590de2ca4810dd0a8bfb1290a626ae40f31ca469a632.json} (75%) rename .sqlx/{query-f6ab1a10c0ebdc295fe7ea726b189838548d9535470d0eafce7c8911d71015d7.json => query-2c4a5e96ccd5b0b27c2c99846f574e7bf1fb475a7aefa88b9ce817ee05ad8582.json} (79%) rename .sqlx/{query-f0d305ba65359dea4a9d7b4a0577ae43db1c7ef01adc22450f75c0cd37c0d950.json => query-321f0103b33607cbfda238c631fc4f0a47d8f3231e8fdfe3dfe60ae82eacf532.json} (72%) rename .sqlx/{query-99469fccd450e6d9fae93713e93936de6a95cefbdefaae798d88c8cda1da9fc6.json => query-329a782baf49baadc80e6c3a233f203c9eea7308e773738dfd905a9eb131dcb2.json} (53%) rename .sqlx/{query-13d7f63724ed14449a9d6bfd3735072ce7eded7b6e5c40c33fc6140ae8747ec0.json => query-33937eda61e33ee52f82bf7e6338428bdccf4e2d95f2499d9feb46ff6238f51d.json} (86%) create mode 100644 .sqlx/query-3a2e8db644faec7cc2aab62aba2649c8707018d8af8f511c04310aa2357d8a4b.json create mode 100644 .sqlx/query-3c78ef010f90748dd6f60c086761e68d2e630763fc4732795891e4243e5e0eea.json create mode 100644 .sqlx/query-3d1db83ef8c406a80281be9cfc968dc81304180cd047d1ae2b65951528e1d4b1.json create mode 100644 .sqlx/query-3e68616aab7908522dcb7aef662a6cc355fa9ce81fc609ad25450d2a1d8cf555.json rename .sqlx/{query-258c27c5e706ee3493229f3aacace4fa9ae874106c106a768b087e09f2234dcd.json => query-3f35044808071da4e1275f141b5f80b6974dff0cb59238f7ab0e1b51a389e6b1.json} (84%) rename .sqlx/{query-685fff635ecc5f67628da31ddcc229a97ac0ee9dbb5d8c73732e921e0613a1b0.json => query-4033f72b27577d747740c96aa418736c7f8df98bf1a17083a72371155b0b553d.json} (69%) rename .sqlx/{query-8890b0928a86ed9b08e5803dc4fd3dca14b305482d4614abbbd19f982c9fd732.json => query-40b8fe75dcbef4923d4d7f774d4cd2985cdd8768d31b752c235d4d5bbc2549d1.json} (65%) create mode 100644 .sqlx/query-425c4b69c806d2f70999dea4dfd56f471b95a2e0c99a880e428f5550abc05695.json create mode 100644 .sqlx/query-42dcb34cc907c4d361d0950c3a843ea62604494f00d597051e46eba1ae56625d.json create mode 100644 .sqlx/query-43d5cd5b3c47c16859989d22ad3a672b6ecd3a55bebac6efa1ade9a7620b564a.json create mode 100644 .sqlx/query-4a7ac53dc8e09c518c8f2cf1a992062f7c591143cdb056bf5a250235bbb12609.json create mode 100644 .sqlx/query-4ade3a1620e48bd3d8bdd32450abc35b300037ef875d14026eaa226d3e543ef9.json delete mode 100644 .sqlx/query-4caddc18b673f2dfff6b63b51b271b205edd9f9550412eeba7f22e16a16971f2.json create mode 100644 .sqlx/query-4ef82265de6a27ab50351320b610fe0412bbf6be669731377fa8bf033f5cc072.json rename .sqlx/{query-092ffc9c8c3d159f1792968df3591104dcd0e08206d94a092646c0cea5aff32a.json => query-5258fa19ca184606b7078160ecbc6717830c3ca1ff9954c376d6c9c674ff4b5b.json} (63%) create mode 100644 .sqlx/query-532d2d0011fe140007ad8f56fa63229d4ba5108df18938a8629ecfb70725b5ff.json delete mode 100644 .sqlx/query-54a4303671c7acb834b45dabd55d93332990a094273f6ac2adb05bf94397010f.json create mode 100644 .sqlx/query-553487a166d9b3d9c0e3d4c7a5270c13768fb537393c70e006466df156a319a2.json create mode 100644 .sqlx/query-57a63446535fbaf09ea123221182709ac1102fcafffd227c1fa1dc4e36a944af.json rename .sqlx/{query-a70bfbf0b8ea81aab2f5b907a40ed1a4236cff0484bf3bc652e24133407283e5.json => query-59e72e6dab4c94b31994810b4bf1d195587319a4ab757166a046b394e86938a5.json} (68%) rename .sqlx/{query-bac093371039a68fb29a6739b77ad3e835ae128d3c7f0a712793da3cbdd9d429.json => query-5d88e06f2106d13aa6bc807c6c7dfae53259b9db0048d350758a546836021e3c.json} (55%) rename .sqlx/{query-97e71a885347d2ee6ee809e3608825b108349bb0dde0046d5817dfcc56d6a583.json => query-60dc8924b722dbdeafa1686248b574aca9089ae24b9d87521a134267f4f76caa.json} (73%) create mode 100644 .sqlx/query-61c84c00d51c17a737b8358ac320d7b7d17420cdc12bd26939b3eca27088d275.json delete mode 100644 .sqlx/query-633c525f787d9597ef6d6e5ca7019918a413158e9446b39fe5b69da534810e60.json create mode 100644 .sqlx/query-63bdf7314ccc48750af75af20167e573b36ded45dc3f8050b95ea6823ae3177a.json rename .sqlx/{query-42ec2891956481a4fb70b81cc230621f4481f2fc57e10e3680043fb83c850c66.json => query-63e9be4296079ff969f4a3e464e6dd9ad20d54e788a7af2e04e50658bcc1c45c.json} (79%) rename .sqlx/{query-07f5872671b049dca356394ea98c9840bf57fd5e586b4ff36ffabb988a8423c5.json => query-6907da40c5b42ea56fb9c257cd9b486869381275626163e8bd75e928188875b1.json} (75%) delete mode 100644 .sqlx/query-69308bfda3e686112dfaa6493e2729e250ce149537408ac7b0124b3d33582980.json rename .sqlx/{query-96175480de70dd3d01e7b9d4a5edd779f04ace47d43143e0e1ed353c3a8ce3fc.json => query-6c518ef0581ca1549988917c39135198f1bf92d9a7b4984b227849771bec8699.json} (85%) create mode 100644 .sqlx/query-6ce14f236c940b29b7107569aed2d0c176065c36a5ba34a1757c9f3cef17d15f.json rename .sqlx/{query-5942f054f1c660ec1eaf894afdf37c2ed8aa3ec0dfecf243b26193210619377f.json => query-6ce455efe2f18ee3bf4a217db31b91d188bfff40e5e1e0af2789e92ca110c71f.json} (74%) rename .sqlx/{query-3dbbe1738727b434a5bf46e535e16b293dc59a120c861b79ab3166cf0a0e27df.json => query-6fcc2a42e243df55569ca080ec3cbb8a71f134255f4f9283bbde0e90537c6501.json} (81%) rename .sqlx/{query-3b8dd2053a8627a7e965b5aabb4640b02fbf9653ac9da6af47e5d0732e611a29.json => query-72cd9aa43384131ba5489ac5b79e9108aabe3ddb6dc9522530787d3fa632b595.json} (86%) create mode 100644 .sqlx/query-743dc724aee85af2244e80c69a71610a2d9f88eee804fad8c4936cd23e4770d3.json create mode 100644 .sqlx/query-771928c37367daef7caef3a0faa381d01bd34a4f4a6559c362499376a0518bfd.json create mode 100644 .sqlx/query-800bb78fa5b427d8ccb72cf3ba69e8fb9c8d3bffb022d47939e9ee0269eb764a.json rename .sqlx/{query-c9176c3fd78effbb5626b81d72d2f9d02c841a21271501ed5d27f64c8b08fbad.json => query-8cfb7acdfe6bb096f83920c104c8c45fafa1e717db6630c7e3fde77816d9e3a7.json} (85%) rename .sqlx/{query-befcf1a2da3632684bcc6d741540c05719315260192d47a8cd50c1d45eb32e8d.json => query-8d7ae20c108d3c74fd9d841f7b36eed4cc0cbc04fc93ff05b33e6c70a91116e2.json} (51%) create mode 100644 .sqlx/query-8e4568e7dfb68793acc1aa2a9c142314670484e5eacfdcf9b4fec3ed887b6b0d.json delete mode 100644 .sqlx/query-8e687f07237ef09a151a945cd4046978aa69cbda3bd53e1c79157f840edf1443.json rename .sqlx/{query-409b3b702b6cd4ad4dcd34f5330d20b16f3093821553a6af4f55a53cc4c69fb7.json => query-90ca4d8c108622034298f4da1ac3a4db6a284b2f95e0fe8a69bbec9117f5d0a0.json} (87%) create mode 100644 .sqlx/query-915d3bcbbe66341824b280bde6cb5eb01f3868fd3d98bd29a9efc85a80176e95.json create mode 100644 .sqlx/query-935e0ed64846d8c1ad7e317725d31da05a618a6ab0e628482399affad99261c8.json delete mode 100644 .sqlx/query-93c7d6a0aa9805cda59508aa0baf349fb341315f8899c7c61cd669916f292609.json delete mode 100644 .sqlx/query-94bc804bff53b231870f54a09eaaf732f6ab3b158fad47d4daab3c52426e9564.json create mode 100644 .sqlx/query-9d2466aa569f86333f3eb28871eabc72dc0058951a26855a52cc688e21e21685.json rename .sqlx/{query-ea0e9333278dc82972ebfc2aa5efee079814899bebf6c2a495a47e6fdc0b5834.json => query-9d9cce760c2a87090f4b3cf5da4afc868d6fb3c91a7ba9ae5b553dfb48be9353.json} (87%) create mode 100644 .sqlx/query-9e64583ead1738639a6fdc7e6158cc313f9c8ddd2afd3a9728462819f5db30dd.json create mode 100644 .sqlx/query-9e70ed1446d7ca45b78aa8dfb9842a877dfac056dea7b17e702bdea174b0993a.json create mode 100644 .sqlx/query-a48289705d949851428efdaa1cdd18a7b8397112582a9d8a0c386491e1c2bfad.json create mode 100644 .sqlx/query-a659d3ffcdac1279b32d1d0673a6b36c168cb3c9ddbf00ebb402e8598b995f13.json create mode 100644 .sqlx/query-a6baebb365f43380e7bf289cc9a660d9b628c5529195edfbe634c2c21818a345.json create mode 100644 .sqlx/query-a8f1d82b2d0a543ea09ea62f8bb88a7365573ea7f566f9ff3f625e6a034d181c.json delete mode 100644 .sqlx/query-aee5be56a586cd5424cbc0532b4337dfa6d93ddd6e5909c4fd6950e2e468ad6e.json rename .sqlx/{query-123a9c9b6be7c9bed57fb3c22ac699108abd335fa898d098652bc0f16541cab4.json => query-b0b72a673261825bb0103bef5882c803494d402b4611dbfb646d8973af96896a.json} (73%) rename .sqlx/{query-74d97285fdc1081f2efdca29cbfc9a4832c0ae927e24be87f216855fe631e40c.json => query-b63d7258825b3b578664bd4e8f1347c918f564d0022954a7efc0e98dc8d03df4.json} (75%) delete mode 100644 .sqlx/query-b8cd6149b5f42e615c31018d2fdf306f157f5275587ae57d1e5146c9a76a51d3.json create mode 100644 .sqlx/query-bd7a06a5112f3a1489d0f3800e42bee96cd9acec380c29c4006c9d68f5becd57.json create mode 100644 .sqlx/query-bdfda68f7d0dedef148b54d5911a7798ced19472830ac9421f024eb43c784318.json delete mode 100644 .sqlx/query-be12adc83910edf8922a2b22308e76093cdd89e6173043354ee6ee66e7c2a518.json rename .sqlx/{query-5faf6a7b5f0ae1ff707c72f2a8985e65d83dcd7a4cad37c752908c361a460d86.json => query-c1bac901f8e1b2a8ee9aa2aa15e4ec7eab955fb80167fec8768a381cd012f4b5.json} (55%) rename .sqlx/{query-866efd5fe0b7f2b4524f747d9ef26100e13c48d4cb35d390d29c327180681c60.json => query-c3232a6de8535065f4fc7e1a19494dd17acb47f65cca634b739f9ff6cd0a6894.json} (52%) rename .sqlx/{query-b364954dae05a5a23861686a2f9b9ce478f5ee272d09c11e288d335d05f43fd8.json => query-c41fb6b0ecd0a378198552f4c36085f8c0d229a7a83b23fb3ba02c1e6b675fe6.json} (56%) delete mode 100644 .sqlx/query-c79d72b0f40ff99077904b1d479bb80ed92b3f86eef355cc301bcb1178d3ca4d.json create mode 100644 .sqlx/query-c853378f65634bdb7e00a372fa188979bc2758176b486ac554a763653e04c718.json create mode 100644 .sqlx/query-c95bf5c2dfe3ef6919ddb41983f1ab4392ea31250f0c00db33e0864a33dfde42.json create mode 100644 .sqlx/query-cb8b95b85f0f40ad61f2135d211ae1a44da4173d3d7e10b6e2e3dddad51d952e.json create mode 100644 .sqlx/query-cbf6dd44326403b41940e572a66285a17bd52337a3b586b99deb4bfc5250bbe5.json create mode 100644 .sqlx/query-cdd48454144e721a0c3bab8b0859396b9a134f3b85a727c8fb08b01c9fa1fd6b.json create mode 100644 .sqlx/query-cf84beaac0eb97a92e8a2fde1cc7688b2d1a239f0604d945885c1c3a09b305b4.json create mode 100644 .sqlx/query-cfd796a16bdfb74c118bd76c0558e33b7c575b5510df2bf6547c818481be5eaa.json delete mode 100644 .sqlx/query-da48c3255d2e13ec4031617c4e549cd7f9e911516b7615c36e1dfe07959ff51c.json create mode 100644 .sqlx/query-df8f0dba6da244501e34e5f0108236148b27134bbec41d9084704143e35d90ea.json rename .sqlx/{query-9ebc278fccb979dbd426a4a24b7ab5261e0c26c29786b1abc23c03d76c27e7a9.json => query-e468a344c54e212f2ad3d4159206fa97a212a9111135b4ca576962cc64267757.json} (80%) rename .sqlx/{query-8c457fff4a76cedba9338135a894713e2609cb8aed0e963ba491118d3aebe0a3.json => query-ede2ad9dfbe1e9e069bd8912acb49d13f43f251bc7276d1a6b6fe249920677ad.json} (58%) rename .sqlx/{query-1604ab0a5b6f69c82c52fbdd8a4a54422aaacfa006d1a05d5ea37ed20baa355f.json => query-f19d64790b8c145113b680276ff897b1f4786e15116846e0288035e6ef1ca091.json} (77%) create mode 100644 .sqlx/query-f3d94b7ff35a9dfabb0459303432942bc8828d833df5fe56e8201b2aa8cae80c.json create mode 100644 .sqlx/query-f5de8fdcec4e2b21ebb8fbfbd12202947538687c018b94967578f68be3358864.json rename .sqlx/{query-d33066aa6a8214a7ceb38922c1fa0ad45fcb45e4a4cebbc26efbcf8c31691517.json => query-f7d2187dc89a2bba3b521b0ea67282392ba1739904fcb1d40006e34c78d4afa9.json} (85%) rename .sqlx/{query-8a2042be8e7358d9c9f9f8a906ff113f71fa4ac519aec8519ee6b40bc51f694d.json => query-fb46d17a76c6111308068c735184bbb68a2b726f7a1c98068d506d51aa52785e.json} (68%) rename .sqlx/{query-1f1dc2c17f96a49d8ae036569ba1d67db0558b58f0c2a463d54ad923254fba8c.json => query-fd31503ac762b761089f28233e0b2e425f8a349b2715ae2062fdda16d1c86d00.json} (69%) rename .sqlx/{query-fe740c4ecd33f9510af45852fdbb70712754d6d6095b27404cb77dc106774341.json => query-fe26461b2872573cafe05ba8d0b70ce84a117296bdf0c18e643293bb0b1e153e.json} (78%) create mode 100644 deploy/Containerfile.runtime create mode 100755 deploy/backup-postgres.sh create mode 100644 deploy/hezarfen-compose.service delete mode 100644 deploy/hezarfen.service create mode 100644 deploy/hezarfen_backend.env.example diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index d622654..806388f 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -1,30 +1,39 @@ -# VPS deploy, im-style, split into two jobs so failure recovery is cheap: +# VPS deploy, compose-style, split into two jobs so failure recovery is cheap: # # Build and test — Postgres sidecar, clippy, the whole suite, the release -# build; uploads the staged release as the run's artifact. -# Deploy — SSH release-dir swap + systemd user-unit restart, -# /health gated on THIS build's process, rollback on -# failure, independent after-the-fact verify. +# build; packs the stripped binary + migrations into the +# runtime image (deploy/Containerfile.runtime) and +# uploads the image tarball + compose files as the run's +# artifact. +# Deploy — SSH: podman load the image, point the deploy-owned +# stack.env's HEZARFEN_TAG at it, install compose.yaml + +# the hezarfen-compose user unit + the backup script, +# restart the stack, /health-gated rollback to the +# previous tag, independent after-the-fact verify. # # The split is the recovery story, not ceremony: # * "Re-run failed jobs" on a run whose Deploy step failed re-runs ONLY the -# ~1-minute deploy job — the built release is still in the run's artifact. +# ~1-minute deploy job — the built image is still in the run's artifact. # * workflow_dispatch (the manual door: Actions tab → Run workflow on main, # or `gh workflow run main.yml --ref main`) deploys WITHOUT the suite: it # takes the newest artifact a green Build-and-test produced — which can # lag HEAD while a push is mid-CI, and that is the point: redeploy the -# known-good release, e.g. after a server-side fix (env file, proxy, +# known-good image, e.g. after a server-side fix (env file, proxy, # database). For env-only changes a plain -# `ssh 'systemctl --user restart hezarfen'` needs no workflow at -# all: the process reads its env at boot. +# `ssh 'systemctl --user restart hezarfen-compose'` needs no +# workflow at all: the stack re-reads its env files on the next +# `podman compose up`. # # One-time prerequisites, outside the workflow's reach: -# * the repo secrets SSH_PRIVATE_KEY / SSH_HOST / SSH_USER (im's values -# work if this deploys as the same user); +# * the repo secrets SSH_PRIVATE_KEY / SSH_HOST / SSH_USER; # * `loginctl enable-linger ` on the server unless the deploy user -# already has it (im's does) — user units need a running user manager; -# * a Postgres the backend can reach, and ~/hezarfen_backend/hezarfen_backend.env (0600) -# with at least DATABASE_URL — see deploy/hezarfen.service for the keys. +# already has it — user units need a running user manager; +# * podman plus a compose provider on the server (the deploy checks for +# both and fails with a one-line install hint); +# * the operator's ~/hezarfen_backend/hezarfen_backend.env (0600), written +# once by hand from deploy/hezarfen_backend.env.example — at minimum the +# POSTGRES_PASSWORD and BUILDER_PASSWORD lines. The deploy never +# creates or overwrites it. name: VPS deploy @@ -35,30 +44,34 @@ on: # The manual redeploy door — see the header comment for how and why. workflow_dispatch: -# One deploy at a time: the deploy swaps a release directory and restarts one -# service; two of them racing would leave the binary and the running process -# from different builds. A dispatched redeploy queues behind any in-flight -# push deploy rather than racing it. +# One deploy at a time: the deploy reloads one compose stack; two of them +# racing would interleave container recreations and could leave the served +# image and the tag files from different builds. A dispatched redeploy +# queues behind any in-flight push deploy rather than racing it. concurrency: group: deploy cancel-in-progress: false env: - # A gnu binary links against the runner's glibc, so the runner is pinned - # (see runs-on below) to the same 24.04 the server runs; the day either - # side moves, the pin is what forces a conscious decision rather than a - # broken deploy. In exchange: no cross-toolchain, and the linker is - # rustc's default bundled lld. + # A gnu binary links against the toolchain's glibc, so the runner is + # pinned (see runs-on below) to 24.04, and the runtime image is + # debian:trixie-slim: move either side without thinking and the binary + # stops loading inside the container. The pin is what forces a conscious + # decision rather than a broken deploy. In exchange: no cross-toolchain, + # and the linker is rustc's default bundled lld. TARGET: x86_64-unknown-linux-gnu - # The systemd user unit that owns the process. See deploy/hezarfen.service. - SERVICE: hezarfen + # The systemd user unit that wraps `podman compose`. See + # deploy/hezarfen-compose.service. + SERVICE: hezarfen-compose # The deploy lives in this subdirectory of the SSH user's home. The home # itself is resolved on the server ($HOME), so switching the deploy user # moves the path with it — a baked-in absolute path once kept pointing at # the previous user's home and failed the deploy on permissions. DEPLOY_SUBDIR: hezarfen_backend - # The unit reads its secrets from this file on the server; the deploy - # never writes it, only checks it exists and holds DATABASE_URL. + # Compose interpolates its secrets from this file on the server (passed + # as --env-file, and to the backend container as env_file). The deploy + # never writes it, only checks it exists and carries the + # POSTGRES_PASSWORD / BUILDER_PASSWORD lines prod must not run without. ENV_FILE_NAME: hezarfen_backend.env # The Postgres the test suite mints its per-test databases on. Credentials # and port match the harness default (HEZARFEN_TEST_DATABASE_URL), so the @@ -77,9 +90,9 @@ jobs: # Pushes only: a manual redeploy reuses the newest green artifact # instead of paying the suite again. if: github.event_name == 'push' - # Pinned, not `latest`: ubuntu-latest floating to the next LTS would - # one day ship a glibc newer than the server's, and the gnu binary - # would stop running there. See the TARGET comment above. + # Pinned, not `latest`: the gnu build links the runner's glibc and the + # runtime image is debian:trixie-slim — float either side carelessly + # and the binary stops loading. See the TARGET comment above. runs-on: ubuntu-24.04 env: # The 41 test binaries each link the full tonic/otlp/axum/sqlx stack; @@ -155,12 +168,36 @@ jobs: cp "target/$TARGET/release/hezarfen_backend" stage/hezarfen_backend # The migrators resolve `migrations/` beside the binary when the # compile-time checkout path is absent (see migrations_path), so - # the schema ships with the release it belongs to. + # the schema ships inside the image, next to /app/hezarfen_backend. cp -r migrations stage/migrations - cp deploy/hezarfen.service stage/hezarfen.service strip stage/hezarfen_backend ls -l stage + - name: Build the runtime image + run: | + set -euo pipefail + # Pack the already-built, already-stripped gnu binary into the + # runtime image. Never build from source here: a second rust + # compile blows the runner's disk. + docker build -f deploy/Containerfile.runtime -t localhost/hezarfen-backend:$GITHUB_SHA stage/ + docker save localhost/hezarfen-backend:$GITHUB_SHA | gzip > stage/hezarfen-backend.tar.gz + + - name: Stage the compose bundle + run: | + set -euo pipefail + cp compose.yaml deploy/hezarfen-compose.service deploy/backup-postgres.sh stage/ + echo -n "$GITHUB_SHA" > stage/tag + # Everything the deploy installs on the server must be here; a + # missing piece fails here, on the runner, not mid-deploy on the + # VPS. The raw binary and migrations may linger as docker build + # context — they are no longer load-bearing. + test -f stage/hezarfen-backend.tar.gz + test -f stage/compose.yaml + test -f stage/hezarfen-compose.service + test -f stage/backup-postgres.sh + test -f stage/tag + ls -l stage + # The deploy job (and, later, a manual redeploy) consumes this. 30 # days is also the dispatch door's reach-back window: an older green # build's artifact is gone, and the redeploy fails loudly instead of @@ -226,12 +263,16 @@ jobs: run-id: ${{ env.run_id }} github-token: ${{ github.token }} + # The dispatch path downloads a possibly-days-old artifact; re-check + # the bundle is whole before pointing any of it at the server. - name: Check the release is complete run: | set -euo pipefail - test -f stage/hezarfen_backend - test -d stage/migrations/control - test -f stage/hezarfen.service + test -f stage/hezarfen-backend.tar.gz + test -f stage/compose.yaml + test -f stage/hezarfen-compose.service + test -f stage/backup-postgres.sh + test -f stage/tag - name: Install SSH keys run: | @@ -260,19 +301,19 @@ jobs: ;; esac deploy_path=$HOME/$1 - # The deploy path is the service's working tree: hezarfen_backend.env and - # data/ live there and are never touched from here. Only 'current' - # is replaced. + # The deploy path holds the operator's hezarfen_backend.env, the + # compose files and the tag files; nothing in it is deleted + # wholesale, ever. mkdir -p -- "$deploy_path" - rm -rf -- "$deploy_path/current.new" - mkdir -p -- "$deploy_path/current.new" REMOTE - # stdin carries the tarball, so the script cannot; the extraction + # stdin carries the bundle, so the script cannot; the extraction # still goes through bash -c because the login shell is not bash - # and would not expand $HOME. - tar -C stage -czf - . | ssh "$ssh_target" "bash -c 'exec tar -xzf - -C \"\$HOME/\$1/current.new\"' -- '$DEPLOY_SUBDIR'" + # and would not expand $HOME. Only the five deploy files ship — + # the raw binary and migrations stay on the runner (they were + # docker build context, nothing more). + tar -C stage -czf - hezarfen-backend.tar.gz compose.yaml hezarfen-compose.service backup-postgres.sh tag | ssh "$ssh_target" "bash -c 'exec tar -xzf - -C \"\$HOME/\$1\"' -- '$DEPLOY_SUBDIR'" - - name: Swap and restart + - name: Load the image and restart the stack run: | set -euo pipefail ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}" @@ -285,72 +326,139 @@ jobs: service=$2 env_file=$deploy_path/$3 export XDG_RUNTIME_DIR=/run/user/$(id -u) + # compose.yaml is resolved from the working directory: the unit's + # ExecStart carries WorkingDirectory, but the rollback compose up + # and a first-deploy down run from right here. + cd -- "$deploy_path" + # Read before anything moves: the env file is the operator's, on - # the server, written once (see deploy/hezarfen.service for the - # keys). A missing file or a missing DATABASE_URL is a failure to - # stop on, not one to roll back from. + # the server, written once by hand (see + # deploy/hezarfen_backend.env.example for the keys). The deploy + # never creates or overwrites it. The password and OpenObserve lines + # are load-bearing: without them compose would silently run the stack + # on its laptop defaults. if [ ! -f "$env_file" ]; then - echo "missing $env_file — create it (0600) with at least DATABASE_URL; see deploy/hezarfen.service" >&2 + echo "missing $env_file — create it (0600) from deploy/hezarfen_backend.env.example" >&2 exit 1 fi chmod 0600 -- "$env_file" - if ! grep -q '^DATABASE_URL=' "$env_file"; then - echo "no DATABASE_URL in $env_file" >&2 + for key in POSTGRES_PASSWORD BUILDER_PASSWORD ZO_ROOT_USER_EMAIL ZO_ROOT_USER_PASSWORD; do + grep -Eq "^${key}=.+" "$env_file" || { + echo "no non-empty ${key}= line in $env_file — prod must not run on the compose defaults" >&2 + exit 1 + } + done + + # Rootless podman plus a compose provider; fail with the fix, not + # a bare command-not-found three steps in. + command -v podman >/dev/null || { + echo "podman not found — install podman and a compose provider (e.g. dnf install podman podman-compose)" >&2 exit 1 + } + podman compose version >/dev/null 2>&1 || { + echo "'podman compose' unavailable — install a compose provider (podman-compose or docker-compose)" >&2 + exit 1 + } + + # Load THIS build's image and read the tag the build stamped into + # it (build time and deploy time must agree on what is shipping). + gunzip -c "$deploy_path/hezarfen-backend.tar.gz" | podman load + tag=$(cat -- "$deploy_path/tag") + + # Tag rotation: previous_tag is the rollback target (absent on a + # first deploy); current_tag records what should now be running. + if [ -f "$deploy_path/current_tag" ]; then + cp -- "$deploy_path/current_tag" "$deploy_path/previous_tag" fi - # The unit defaults to 7656; the env file may override. - port=$(sed -n 's/^PORT=\([0-9][0-9]*\)$/\1/p' "$env_file" | tail -n1) - port=${port:-7656} - mkdir -p -- "$deploy_path/data/files" - chmod +x -- "$deploy_path/current.new/hezarfen_backend" - rm -rf -- "$deploy_path/current.previous" - if [ -e "$deploy_path/current" ]; then - mv -- "$deploy_path/current" "$deploy_path/current.previous" - fi - mv -- "$deploy_path/current.new" "$deploy_path/current" + printf '%s\n' "$tag" > "$deploy_path/current_tag" + + # stack.env is deploy-owned (unlike the secrets file): it carries + # only the image tag, and --env-file order makes it win over the + # operator's file for HEZARFEN_TAG. + printf 'HEZARFEN_TAG=%s\n' "$tag" > "$deploy_path/stack.env" + + # The freshly extracted bundle: compose file and unit are + # world-readable, the backup script is run by hand or a timer. + chmod 0644 -- "$deploy_path/compose.yaml" "$deploy_path/hezarfen-compose.service" + chmod 0755 -- "$deploy_path/backup-postgres.sh" + # The image tarball was only a transport; the image is loaded into + # podman's storage now. + rm -f -- "$deploy_path/hezarfen-backend.tar.gz" + + compose_up() { + podman compose --env-file "$env_file" --env-file "$deploy_path/stack.env" up -d --no-build + } + rollback() { + if [ -f "$deploy_path/previous_tag" ]; then + prev=$(cat -- "$deploy_path/previous_tag") + printf 'HEZARFEN_TAG=%s\n' "$prev" > "$deploy_path/stack.env" + printf '%s\n' "$prev" > "$deploy_path/current_tag" + compose_up + echo "rolled back to $prev" >&2 + else + # First deploy: nothing to roll back to, so stop the + # half-brought-up stack. Plain down — the volumes hold the + # operator's data and postgres's first-boot password. + podman compose --env-file "$env_file" --env-file "$deploy_path/stack.env" down + echo 'first deploy failed; stack stopped, volumes kept' >&2 + fi + } + # The unit ships with the release: a freshly provisioned box has # no unit until the first deploy writes it, and a changed unit - # lands with the code that needs it. Enabling is idempotent. + # lands with the compose file that needs it. mkdir -p -- "$HOME/.config/systemd/user" - install -m 644 -- "$deploy_path/current/hezarfen.service" "$HOME/.config/systemd/user/$service.service" + install -m 0644 -- "$deploy_path/hezarfen-compose.service" "$HOME/.config/systemd/user/$service.service" systemctl --user daemon-reload + # Retire the binary-era unit: disable it (absent on fresh boxes) + # and drop its unit file so it can never come back at boot. + systemctl --user disable --now hezarfen.service 2>/dev/null || true; rm -f -- "$HOME/.config/systemd/user/hezarfen.service" + + # The unit is a oneshot with RemainAfterExit, so `start` on the + # active (exited) unit would be a no-op — every deploy restarts + # to re-run ExecStart. A failed restart (bad interpolation, a + # provider hiccup) must still reach the health gate below: it + # decides between rollback and success. systemctl --user enable -- "$service" - systemctl --user restart "$service" - # The unit is Type=simple, so a restart returns before the new - # process has bound its port — and before an old one has let go - # of it. Wait for the health route rather than a clock: /health + systemctl --user restart "$service" || true + + # The oneshot returns before the containers have bound their + # ports. Wait for the health route rather than a clock: /health # answers 503 (curl -f fails) while the database is unreachable, - # so a 200 here already means status "ok". - rollback() { - rm -rf -- "$deploy_path/current" - mv -- "$deploy_path/current.previous" "$deploy_path/current" - systemctl --user restart "$service" - } - for _ in $(seq 1 30); do - served=$(curl -fsS "http://127.0.0.1:$port/health" 2>/dev/null) || { sleep 1; continue; } - # A stale process from an older deploy can answer too, so the - # running binary must be THIS release's, or it rolls back. - pid=$(systemctl --user show -p MainPID --value "$service") - exe=$(readlink "/proc/$pid/exe") - case "$exe" in - "$deploy_path/current/hezarfen_backend") ;; - *) - echo "/health answered, but the process is '$exe' — not this release; rolling back" >&2 - rollback - exit 1 - ;; + # so a 200 whose body says "status":"ok" means the new stack is + # truly serving. 90 attempts, not 30: a first deploy also pulls + # the postgres and observability base images. + health_ok=0 + for _ in $(seq 1 90); do + served=$(curl -fsS http://127.0.0.1:7656/health 2>/dev/null) || true + case "$served" in + *'"status":"ok"'*) health_ok=1; break ;; esac - echo 'hezarfen is up' - rm -rf -- "$deploy_path/current.previous" - exit 0 + sleep 1 done - echo 'hezarfen did not answer /health; rolling back' >&2 - rollback - exit 1 + if [ "$health_ok" -ne 1 ]; then + echo '/health never said "status":"ok"; rolling back' >&2 + rollback + exit 1 + fi + + # A stale stack from an older deploy can answer too, so the + # running container must be THIS build's image, or it rolls back. + image=$(podman inspect -f '{{.Config.Image}}' hezarfen-backend) + case "$image" in + *"$tag"*) ;; + *) + echo "/health answered, but the container runs '$image' — not this build ($tag); rolling back" >&2 + rollback + exit 1 + ;; + esac + echo 'hezarfen-compose is up' REMOTE - # The independent after-the-fact check: the process answering must - # still be this release's, and the validation contract must be served. + # The independent after-the-fact check: the container answering must + # still be the current tag's, and the validation contract must be + # served. - name: Verify the served API run: | set -euo pipefail @@ -358,22 +466,26 @@ jobs: # One remote script, im-style: mixing runner-side and server-side # variables in nested ssh quoting once shipped a check that failed # on a healthy deploy. Everything happens inside the heredoc. - ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR' '$SERVICE' '$ENV_FILE_NAME'" <<'REMOTE' + ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR'" <<'REMOTE' set -euo pipefail deploy_path=$HOME/$1 - service=$2 - env_file=$deploy_path/$3 export XDG_RUNTIME_DIR=/run/user/$(id -u) - port=$(sed -n 's/^PORT=\([0-9][0-9]*\)$/\1/p' "$env_file" | tail -n1) - port=${port:-7656} - pid=$(systemctl --user show -p MainPID --value "$service") - exe=$(readlink "/proc/$pid/exe") - [ "$exe" = "$deploy_path/current/hezarfen_backend" ] || { - echo "serving '$exe', not the current release" >&2 - exit 1 - } - curl -fsS "http://127.0.0.1:$port/health" | grep -q '"status":"ok"' - curl -fsS -o /dev/null "http://127.0.0.1:$port/limits" + cd -- "$deploy_path" + tag=$(cat -- "$deploy_path/current_tag") + image=$(podman inspect -f '{{.Config.Image}}' hezarfen-backend) + case "$image" in + *"$tag"*) ;; + *) + echo "container runs '$image', not the current tag '$tag'" >&2 + exit 1 + ;; + esac + served=$(curl -fsS http://127.0.0.1:7656/health) || { echo '/health failed' >&2; exit 1; } + case "$served" in + *'"status":"ok"'*) ;; + *) echo '/health did not report "status":"ok"' >&2; exit 1 ;; + esac + curl -fsS -o /dev/null http://127.0.0.1:7656/limits echo 'health ok, limits served' REMOTE diff --git a/.sqlx/query-000fbca60257b293277232cb808c98da0c49fac2b2f178ec9a521f6b070aca70.json b/.sqlx/query-000fbca60257b293277232cb808c98da0c49fac2b2f178ec9a521f6b070aca70.json new file mode 100644 index 0000000..8dc4f65 --- /dev/null +++ b/.sqlx/query-000fbca60257b293277232cb808c98da0c49fac2b2f178ec9a521f6b070aca70.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM rag_output_source WHERE output = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "000fbca60257b293277232cb808c98da0c49fac2b2f178ec9a521f6b070aca70" +} diff --git a/.sqlx/query-0345094de481bdd86f0ac699bc987840bfde048747904ead52da7a2a6961f9a2.json b/.sqlx/query-0345094de481bdd86f0ac699bc987840bfde048747904ead52da7a2a6961f9a2.json deleted file mode 100644 index ae95b46..0000000 --- a/.sqlx/query-0345094de481bdd86f0ac699bc987840bfde048747904ead52da7a2a6961f9a2.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE class_blueprint SET courses = array_remove(courses, $2) WHERE grade = $1", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Text", - "Uuid" - ] - }, - "nullable": [] - }, - "hash": "0345094de481bdd86f0ac699bc987840bfde048747904ead52da7a2a6961f9a2" -} diff --git a/.sqlx/query-03c775aaaa23fc44b29fe4a4d64074eb43d881555a2d278f30abf5ef6b4cef54.json b/.sqlx/query-03c775aaaa23fc44b29fe4a4d64074eb43d881555a2d278f30abf5ef6b4cef54.json new file mode 100644 index 0000000..2422dbb --- /dev/null +++ b/.sqlx/query-03c775aaaa23fc44b29fe4a4d64074eb43d881555a2d278f30abf5ef6b4cef54.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO settings_attendance_status (settings, status)\n SELECT 'school', t.status FROM unnest($1::text[]) AS t(status)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "TextArray" + ] + }, + "nullable": [] + }, + "hash": "03c775aaaa23fc44b29fe4a4d64074eb43d881555a2d278f30abf5ef6b4cef54" +} diff --git a/.sqlx/query-095bbc7dc251d30a4ae7bfaf71d50ff42e92738d5bf32d42b3471178a0439d7b.json b/.sqlx/query-095bbc7dc251d30a4ae7bfaf71d50ff42e92738d5bf32d42b3471178a0439d7b.json deleted file mode 100644 index 010a546..0000000 --- a/.sqlx/query-095bbc7dc251d30a4ae7bfaf71d50ff42e92738d5bf32d42b3471178a0439d7b.json +++ /dev/null @@ -1,136 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE board\n SET participants = array_remove(participants, $1)\n WHERE $1 = ANY(participants) OR creator = $1\n RETURNING id AS \"id: BoardId\",\n creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n participants AS \"participants: Vec\",\n locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\",\n epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "id: BoardId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "board", - "name": "id" - } - } - }, - { - "ordinal": 1, - "name": "creator: UserId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "board", - "name": "creator" - } - } - }, - { - "ordinal": 2, - "name": "title: BoardTitle", - "type_info": "Text", - "origin": { - "Table": { - "table": "board", - "name": "title" - } - } - }, - { - "ordinal": 3, - "name": "participants: Vec", - "type_info": "UuidArray", - "origin": { - "Table": { - "table": "board", - "name": "participants" - } - } - }, - { - "ordinal": 4, - "name": "locked", - "type_info": "Bool", - "origin": { - "Table": { - "table": "board", - "name": "locked" - } - } - }, - { - "ordinal": 5, - "name": "locked_by: UserId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "board", - "name": "locked_by" - } - } - }, - { - "ordinal": 6, - "name": "locked_at: Timestamp", - "type_info": "Int8", - "origin": { - "Table": { - "table": "board", - "name": "locked_at" - } - } - }, - { - "ordinal": 7, - "name": "epoch", - "type_info": "Int8", - "origin": { - "Table": { - "table": "board", - "name": "epoch" - } - } - }, - { - "ordinal": 8, - "name": "closed_at: Timestamp", - "type_info": "Int8", - "origin": { - "Table": { - "table": "board", - "name": "closed_at" - } - } - }, - { - "ordinal": 9, - "name": "created_at: Timestamp", - "type_info": "Int8", - "origin": { - "Table": { - "table": "board", - "name": "created_at" - } - } - } - ], - "parameters": { - "Left": [ - "Uuid" - ] - }, - "nullable": [ - false, - false, - false, - false, - false, - true, - true, - false, - true, - false - ] - }, - "hash": "095bbc7dc251d30a4ae7bfaf71d50ff42e92738d5bf32d42b3471178a0439d7b" -} diff --git a/.sqlx/query-13a9d4d1e07a6bd0ab6bcd5d0798cd309907f23262685f8b3b267399f06ff730.json b/.sqlx/query-13a9d4d1e07a6bd0ab6bcd5d0798cd309907f23262685f8b3b267399f06ff730.json new file mode 100644 index 0000000..b16a72b --- /dev/null +++ b/.sqlx/query-13a9d4d1e07a6bd0ab6bcd5d0798cd309907f23262685f8b3b267399f06ff730.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO class_blueprint (id, grade, creator)\n VALUES ($1, $2, $3)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Text", + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "13a9d4d1e07a6bd0ab6bcd5d0798cd309907f23262685f8b3b267399f06ff730" +} diff --git a/.sqlx/query-8c4b65a9c0a081238e9f3d154ee1e2cef90809aa9c81ba4a2109ffaf8caf4170.json b/.sqlx/query-171dde095199b0d28722a55df522824bacb3b971bb88a99db0fbeb148045048d.json similarity index 63% rename from .sqlx/query-8c4b65a9c0a081238e9f3d154ee1e2cef90809aa9c81ba4a2109ffaf8caf4170.json rename to .sqlx/query-171dde095199b0d28722a55df522824bacb3b971bb88a99db0fbeb148045048d.json index fe60af8..06610ad 100644 --- a/.sqlx/query-8c4b65a9c0a081238e9f3d154ee1e2cef90809aa9c81ba4a2109ffaf8caf4170.json +++ b/.sqlx/query-171dde095199b0d28722a55df522824bacb3b971bb88a99db0fbeb148045048d.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO rag_output (id, course_note, course, sources, payload, generated_at)\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING id AS \"id: RagOutputId\", course_note AS \"course_note: CourseNoteId\",\n course AS \"course: CourseId\",\n sources AS \"sources: Vec\",\n payload AS \"payload: Json\",\n generated_at AS \"generated_at: Timestamp\"", + "query": "INSERT INTO rag_output (id, course_note, course, payload, generated_at)\n VALUES ($1, $2, $3, $4, $5)\n RETURNING id AS \"id: RagOutputId\", course_note AS \"course_note: CourseNoteId\",\n course AS \"course: CourseId\",\n payload AS \"payload: Json\",\n generated_at AS \"generated_at: Timestamp\"", "describe": { "columns": [ { @@ -38,17 +38,6 @@ }, { "ordinal": 3, - "name": "sources: Vec", - "type_info": "UuidArray", - "origin": { - "Table": { - "table": "rag_output", - "name": "sources" - } - } - }, - { - "ordinal": 4, "name": "payload: Json", "type_info": "Jsonb", "origin": { @@ -59,7 +48,7 @@ } }, { - "ordinal": 5, + "ordinal": 4, "name": "generated_at: Timestamp", "type_info": "Int8", "origin": { @@ -75,7 +64,6 @@ "Uuid", "Uuid", "Uuid", - "UuidArray", "Jsonb", "Int8" ] @@ -85,9 +73,8 @@ false, false, false, - false, false ] }, - "hash": "8c4b65a9c0a081238e9f3d154ee1e2cef90809aa9c81ba4a2109ffaf8caf4170" + "hash": "171dde095199b0d28722a55df522824bacb3b971bb88a99db0fbeb148045048d" } diff --git a/.sqlx/query-1849fc54c3514fc57c3ad18cc02b0d075c1d724f9f0b05890953e52cbe4f08e3.json b/.sqlx/query-1849fc54c3514fc57c3ad18cc02b0d075c1d724f9f0b05890953e52cbe4f08e3.json new file mode 100644 index 0000000..ab6c184 --- /dev/null +++ b/.sqlx/query-1849fc54c3514fc57c3ad18cc02b0d075c1d724f9f0b05890953e52cbe4f08e3.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM rag_output_source WHERE output IN\n (SELECT id FROM rag_output WHERE course_note = $1)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "1849fc54c3514fc57c3ad18cc02b0d075c1d724f9f0b05890953e52cbe4f08e3" +} diff --git a/.sqlx/query-1ab734e07505d4c74ae50901fb3144f303f578b1048bf96689e513848eca9185.json b/.sqlx/query-1ab734e07505d4c74ae50901fb3144f303f578b1048bf96689e513848eca9185.json new file mode 100644 index 0000000..eb7a4d3 --- /dev/null +++ b/.sqlx/query-1ab734e07505d4c74ae50901fb3144f303f578b1048bf96689e513848eca9185.json @@ -0,0 +1,40 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT course AS \"course: CourseId\", teacher AS \"teacher: UserId\"\n FROM course_teacher WHERE course = ANY($1)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "course: CourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_teacher", + "name": "course" + } + } + }, + { + "ordinal": 1, + "name": "teacher: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_teacher", + "name": "teacher" + } + } + } + ], + "parameters": { + "Left": [ + "UuidArray" + ] + }, + "nullable": [ + false, + false + ] + }, + "hash": "1ab734e07505d4c74ae50901fb3144f303f578b1048bf96689e513848eca9185" +} diff --git a/.sqlx/query-0c551290ec429e8663d0cd33e307b195d00ed6a90dbd095f9066c87ec9cec8b3.json b/.sqlx/query-1c45fc4d105c7dc58a1145c9921fa27ef52f014385003a3b5c3c1fae1768de6b.json similarity index 79% rename from .sqlx/query-0c551290ec429e8663d0cd33e307b195d00ed6a90dbd095f9066c87ec9cec8b3.json rename to .sqlx/query-1c45fc4d105c7dc58a1145c9921fa27ef52f014385003a3b5c3c1fae1768de6b.json index 171fe5d..87cfd42 100644 --- a/.sqlx/query-0c551290ec429e8663d0cd33e307b195d00ed6a90dbd095f9066c87ec9cec8b3.json +++ b/.sqlx/query-1c45fc4d105c7dc58a1145c9921fa27ef52f014385003a3b5c3c1fae1768de6b.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", tags AS \"tags: DishTags\", created_at AS \"created_at: Timestamp\"\n FROM menu_dish WHERE menu = ANY($1) ORDER BY id ASC", + "query": "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\",\n COALESCE((SELECT array_agg(t.tag ORDER BY t.ord) FROM menu_dish_tag t WHERE t.dish = menu_dish.id), '{}'::text[]) AS \"tags!: DishTags\",\n created_at AS \"created_at: Timestamp\"\n FROM menu_dish WHERE menu = ANY($1) ORDER BY id ASC", "describe": { "columns": [ { @@ -60,14 +60,9 @@ }, { "ordinal": 5, - "name": "tags: DishTags", + "name": "tags!: DishTags", "type_info": "TextArray", - "origin": { - "Table": { - "table": "menu_dish", - "name": "tags" - } - } + "origin": "Expression" }, { "ordinal": 6, @@ -92,9 +87,9 @@ false, true, false, - false, + null, false ] }, - "hash": "0c551290ec429e8663d0cd33e307b195d00ed6a90dbd095f9066c87ec9cec8b3" + "hash": "1c45fc4d105c7dc58a1145c9921fa27ef52f014385003a3b5c3c1fae1768de6b" } diff --git a/.sqlx/query-5e5f34152d7edc6330e583d24ae75d9d3486569a45b1dd375f7298e542e410a6.json b/.sqlx/query-1f177f50cbca268c6586d099964dc9970bcc3aea1a65bb486f4510803f4d0019.json similarity index 74% rename from .sqlx/query-5e5f34152d7edc6330e583d24ae75d9d3486569a45b1dd375f7298e542e410a6.json rename to .sqlx/query-1f177f50cbca268c6586d099964dc9970bcc3aea1a65bb486f4510803f4d0019.json index 804be45..271dabe 100644 --- a/.sqlx/query-5e5f34152d7edc6330e583d24ae75d9d3486569a45b1dd375f7298e542e410a6.json +++ b/.sqlx/query-1f177f50cbca268c6586d099964dc9970bcc3aea1a65bb486f4510803f4d0019.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n teachers AS \"teachers: Vec\", title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity\n FROM course ORDER BY id DESC", + "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity\n FROM course ORDER BY id DESC", "describe": { "columns": [ { @@ -27,17 +27,6 @@ }, { "ordinal": 2, - "name": "teachers: Vec", - "type_info": "UuidArray", - "origin": { - "Table": { - "table": "course", - "name": "teachers" - } - } - }, - { - "ordinal": 3, "name": "title: CourseTitle", "type_info": "Text", "origin": { @@ -48,7 +37,7 @@ } }, { - "ordinal": 4, + "ordinal": 3, "name": "description: CourseDescription", "type_info": "Text", "origin": { @@ -59,7 +48,7 @@ } }, { - "ordinal": 5, + "ordinal": 4, "name": "kind: CourseKind", "type_info": "Text", "origin": { @@ -70,7 +59,7 @@ } }, { - "ordinal": 6, + "ordinal": 5, "name": "term: TermId", "type_info": "Uuid", "origin": { @@ -81,7 +70,7 @@ } }, { - "ordinal": 7, + "ordinal": 6, "name": "capacity", "type_info": "Int8", "origin": { @@ -101,10 +90,9 @@ false, false, false, - false, true, true ] }, - "hash": "5e5f34152d7edc6330e583d24ae75d9d3486569a45b1dd375f7298e542e410a6" + "hash": "1f177f50cbca268c6586d099964dc9970bcc3aea1a65bb486f4510803f4d0019" } diff --git a/.sqlx/query-25e11c52a36dd51246aaa35fb7b86650a361821b38809f8cc2c8b28a01952c83.json b/.sqlx/query-25e11c52a36dd51246aaa35fb7b86650a361821b38809f8cc2c8b28a01952c83.json deleted file mode 100644 index 7d607a9..0000000 --- a/.sqlx/query-25e11c52a36dd51246aaa35fb7b86650a361821b38809f8cc2c8b28a01952c83.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE class_blueprint SET courses = array_remove(courses, $1)\n WHERE $1 = ANY(courses)", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Uuid" - ] - }, - "nullable": [] - }, - "hash": "25e11c52a36dd51246aaa35fb7b86650a361821b38809f8cc2c8b28a01952c83" -} diff --git a/.sqlx/query-26379a9428e3236693332d0c236c0c46b1e0aa1efe82ea16208b41b253de74d9.json b/.sqlx/query-26379a9428e3236693332d0c236c0c46b1e0aa1efe82ea16208b41b253de74d9.json new file mode 100644 index 0000000..583fe54 --- /dev/null +++ b/.sqlx/query-26379a9428e3236693332d0c236c0c46b1e0aa1efe82ea16208b41b253de74d9.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM rag_output_source WHERE output IN\n (SELECT id FROM rag_output WHERE course_note = $1 AND id < $2)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "26379a9428e3236693332d0c236c0c46b1e0aa1efe82ea16208b41b253de74d9" +} diff --git a/.sqlx/query-27a509ab3a8873474dffaa26b61511e77c81d4e7efe639591f7db00efaca2f54.json b/.sqlx/query-27a509ab3a8873474dffaa26b61511e77c81d4e7efe639591f7db00efaca2f54.json new file mode 100644 index 0000000..de0f7fc --- /dev/null +++ b/.sqlx/query-27a509ab3a8873474dffaa26b61511e77c81d4e7efe639591f7db00efaca2f54.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO rag_output_source (output, source)\n SELECT $1, s FROM unnest($2::uuid[]) AS t(s)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "UuidArray" + ] + }, + "nullable": [] + }, + "hash": "27a509ab3a8873474dffaa26b61511e77c81d4e7efe639591f7db00efaca2f54" +} diff --git a/.sqlx/query-27dd38ebf96a18059c72db4b6b23f70b916a6273b29e768e303d612a29609fb1.json b/.sqlx/query-27dd38ebf96a18059c72db4b6b23f70b916a6273b29e768e303d612a29609fb1.json new file mode 100644 index 0000000..aa0c7a0 --- /dev/null +++ b/.sqlx/query-27dd38ebf96a18059c72db4b6b23f70b916a6273b29e768e303d612a29609fb1.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM course_teacher WHERE course = $1 AND teacher = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "27dd38ebf96a18059c72db4b6b23f70b916a6273b29e768e303d612a29609fb1" +} diff --git a/.sqlx/query-0a2e0d2d5ca8d25286d988af36998657122706c2873ed4ed1b499f262a4c78d9.json b/.sqlx/query-284241b54bd6674d3d77a88d5cb63cb74660d9bbddaa7fc876d2230184f3430c.json similarity index 80% rename from .sqlx/query-0a2e0d2d5ca8d25286d988af36998657122706c2873ed4ed1b499f262a4c78d9.json rename to .sqlx/query-284241b54bd6674d3d77a88d5cb63cb74660d9bbddaa7fc876d2230184f3430c.json index 31e32fd..dcf00e8 100644 --- a/.sqlx/query-0a2e0d2d5ca8d25286d988af36998657122706c2873ed4ed1b499f262a4c78d9.json +++ b/.sqlx/query-284241b54bd6674d3d77a88d5cb63cb74660d9bbddaa7fc876d2230184f3430c.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE board SET locked = $2, locked_by = $3, locked_at = $4 WHERE id = $1\n RETURNING id AS \"id: BoardId\", creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n participants AS \"participants: Vec\", locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\", epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"", + "query": "UPDATE board SET locked = $2, locked_by = $3, locked_at = $4 WHERE id = $1\n RETURNING id AS \"id: BoardId\", creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n ARRAY(SELECT p.participant FROM board_participant p\n WHERE p.board = board.id ORDER BY p.participant)\n AS \"participants!: Vec\", locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\", epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"", "describe": { "columns": [ { @@ -38,14 +38,9 @@ }, { "ordinal": 3, - "name": "participants: Vec", + "name": "participants!: Vec", "type_info": "UuidArray", - "origin": { - "Table": { - "table": "board", - "name": "participants" - } - } + "origin": "Expression" }, { "ordinal": 4, @@ -126,7 +121,7 @@ false, false, false, - false, + null, false, true, true, @@ -135,5 +130,5 @@ false ] }, - "hash": "0a2e0d2d5ca8d25286d988af36998657122706c2873ed4ed1b499f262a4c78d9" + "hash": "284241b54bd6674d3d77a88d5cb63cb74660d9bbddaa7fc876d2230184f3430c" } diff --git a/.sqlx/query-290550b5ce584441f5343802004891866199a2dd3d3c822cccc471061d842c71.json b/.sqlx/query-290550b5ce584441f5343802004891866199a2dd3d3c822cccc471061d842c71.json deleted file mode 100644 index 900c5ec..0000000 --- a/.sqlx/query-290550b5ce584441f5343802004891866199a2dd3d3c822cccc471061d842c71.json +++ /dev/null @@ -1,155 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO settings (id, exam_kinds, attendance_statuses, grade_bands,\n max_file_bytes, chatbot_history_turns,\n max_chatbot_message_len, max_chatbot_threads,\n meal_slots, dietary_tags, meal_cancel_cutoff_minutes)\n VALUES ('school', $1, $2, $3, $4, $5, $6, $7, $8, $9, $10)\n ON CONFLICT (id) DO UPDATE SET\n exam_kinds = $1,\n attendance_statuses = $2,\n grade_bands = $3,\n max_file_bytes = $4,\n chatbot_history_turns = $5,\n max_chatbot_message_len = $6,\n max_chatbot_threads = $7,\n meal_slots = $8,\n dietary_tags = $9,\n meal_cancel_cutoff_minutes = $10\n WHERE settings.exam_kinds IS NOT DISTINCT FROM $11\n AND settings.attendance_statuses IS NOT DISTINCT FROM $12\n AND settings.grade_bands IS NOT DISTINCT FROM $13\n AND settings.max_file_bytes IS NOT DISTINCT FROM $14\n AND settings.chatbot_history_turns IS NOT DISTINCT FROM $15\n AND settings.max_chatbot_message_len IS NOT DISTINCT FROM $16\n AND settings.max_chatbot_threads IS NOT DISTINCT FROM $17\n AND settings.meal_slots IS NOT DISTINCT FROM $18\n AND settings.dietary_tags IS NOT DISTINCT FROM $19\n AND settings.meal_cancel_cutoff_minutes IS NOT DISTINCT FROM $20\n RETURNING\n exam_kinds AS \"exam_kinds: Json>\",\n attendance_statuses,\n grade_bands AS \"grade_bands: Json>\",\n max_file_bytes,\n chatbot_history_turns,\n max_chatbot_message_len,\n max_chatbot_threads,\n meal_slots AS \"meal_slots: Json>\",\n dietary_tags,\n meal_cancel_cutoff_minutes", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "exam_kinds: Json>", - "type_info": "Jsonb", - "origin": { - "Table": { - "table": "settings", - "name": "exam_kinds" - } - } - }, - { - "ordinal": 1, - "name": "attendance_statuses", - "type_info": "TextArray", - "origin": { - "Table": { - "table": "settings", - "name": "attendance_statuses" - } - } - }, - { - "ordinal": 2, - "name": "grade_bands: Json>", - "type_info": "Jsonb", - "origin": { - "Table": { - "table": "settings", - "name": "grade_bands" - } - } - }, - { - "ordinal": 3, - "name": "max_file_bytes", - "type_info": "Int8", - "origin": { - "Table": { - "table": "settings", - "name": "max_file_bytes" - } - } - }, - { - "ordinal": 4, - "name": "chatbot_history_turns", - "type_info": "Int8", - "origin": { - "Table": { - "table": "settings", - "name": "chatbot_history_turns" - } - } - }, - { - "ordinal": 5, - "name": "max_chatbot_message_len", - "type_info": "Int8", - "origin": { - "Table": { - "table": "settings", - "name": "max_chatbot_message_len" - } - } - }, - { - "ordinal": 6, - "name": "max_chatbot_threads", - "type_info": "Int8", - "origin": { - "Table": { - "table": "settings", - "name": "max_chatbot_threads" - } - } - }, - { - "ordinal": 7, - "name": "meal_slots: Json>", - "type_info": "Jsonb", - "origin": { - "Table": { - "table": "settings", - "name": "meal_slots" - } - } - }, - { - "ordinal": 8, - "name": "dietary_tags", - "type_info": "TextArray", - "origin": { - "Table": { - "table": "settings", - "name": "dietary_tags" - } - } - }, - { - "ordinal": 9, - "name": "meal_cancel_cutoff_minutes", - "type_info": "Int8", - "origin": { - "Table": { - "table": "settings", - "name": "meal_cancel_cutoff_minutes" - } - } - } - ], - "parameters": { - "Left": [ - "Jsonb", - "TextArray", - "Jsonb", - "Int8", - "Int8", - "Int8", - "Int8", - "Jsonb", - "TextArray", - "Int8", - "Jsonb", - "TextArray", - "Jsonb", - "Int8", - "Int8", - "Int8", - "Int8", - "Jsonb", - "TextArray", - "Int8" - ] - }, - "nullable": [ - false, - false, - false, - true, - true, - true, - true, - true, - true, - true - ] - }, - "hash": "290550b5ce584441f5343802004891866199a2dd3d3c822cccc471061d842c71" -} diff --git a/.sqlx/query-2a15712642955d8e832f14d5173c9f44414871c3bca6f106e33eea0aaf7ba82e.json b/.sqlx/query-2a15712642955d8e832f14d5173c9f44414871c3bca6f106e33eea0aaf7ba82e.json new file mode 100644 index 0000000..2fe2356 --- /dev/null +++ b/.sqlx/query-2a15712642955d8e832f14d5173c9f44414871c3bca6f106e33eea0aaf7ba82e.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM board_participant WHERE participant = $1 RETURNING board", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "board", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "board_participant", + "name": "board" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "2a15712642955d8e832f14d5173c9f44414871c3bca6f106e33eea0aaf7ba82e" +} diff --git a/.sqlx/query-aeb5df78c83af8be112917b0cf0b034e94d2b305db968ffaae53785a3af93dab.json b/.sqlx/query-2ab51ad375937884da43590de2ca4810dd0a8bfb1290a626ae40f31ca469a632.json similarity index 75% rename from .sqlx/query-aeb5df78c83af8be112917b0cf0b034e94d2b305db968ffaae53785a3af93dab.json rename to .sqlx/query-2ab51ad375937884da43590de2ca4810dd0a8bfb1290a626ae40f31ca469a632.json index eba2bba..caf3499 100644 --- a/.sqlx/query-aeb5df78c83af8be112917b0cf0b034e94d2b305db968ffaae53785a3af93dab.json +++ b/.sqlx/query-2ab51ad375937884da43590de2ca4810dd0a8bfb1290a626ae40f31ca469a632.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n teachers AS \"teachers: Vec\", title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity\n FROM course WHERE id = ANY($1)", + "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity\n FROM course WHERE id = ANY($1)", "describe": { "columns": [ { @@ -27,17 +27,6 @@ }, { "ordinal": 2, - "name": "teachers: Vec", - "type_info": "UuidArray", - "origin": { - "Table": { - "table": "course", - "name": "teachers" - } - } - }, - { - "ordinal": 3, "name": "title: CourseTitle", "type_info": "Text", "origin": { @@ -48,7 +37,7 @@ } }, { - "ordinal": 4, + "ordinal": 3, "name": "description: CourseDescription", "type_info": "Text", "origin": { @@ -59,7 +48,7 @@ } }, { - "ordinal": 5, + "ordinal": 4, "name": "kind: CourseKind", "type_info": "Text", "origin": { @@ -70,7 +59,7 @@ } }, { - "ordinal": 6, + "ordinal": 5, "name": "term: TermId", "type_info": "Uuid", "origin": { @@ -81,7 +70,7 @@ } }, { - "ordinal": 7, + "ordinal": 6, "name": "capacity", "type_info": "Int8", "origin": { @@ -103,10 +92,9 @@ false, false, false, - false, true, true ] }, - "hash": "aeb5df78c83af8be112917b0cf0b034e94d2b305db968ffaae53785a3af93dab" + "hash": "2ab51ad375937884da43590de2ca4810dd0a8bfb1290a626ae40f31ca469a632" } diff --git a/.sqlx/query-f6ab1a10c0ebdc295fe7ea726b189838548d9535470d0eafce7c8911d71015d7.json b/.sqlx/query-2c4a5e96ccd5b0b27c2c99846f574e7bf1fb475a7aefa88b9ce817ee05ad8582.json similarity index 79% rename from .sqlx/query-f6ab1a10c0ebdc295fe7ea726b189838548d9535470d0eafce7c8911d71015d7.json rename to .sqlx/query-2c4a5e96ccd5b0b27c2c99846f574e7bf1fb475a7aefa88b9ce817ee05ad8582.json index 98a6d87..56640ef 100644 --- a/.sqlx/query-f6ab1a10c0ebdc295fe7ea726b189838548d9535470d0eafce7c8911d71015d7.json +++ b/.sqlx/query-2c4a5e96ccd5b0b27c2c99846f574e7bf1fb475a7aefa88b9ce817ee05ad8582.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "DELETE FROM board WHERE id = $1\n RETURNING id AS \"id: BoardId\", creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n participants AS \"participants: Vec\", locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\", epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"", + "query": "DELETE FROM board WHERE id = $1\n RETURNING id AS \"id: BoardId\", creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n ARRAY(SELECT p.participant FROM board_participant p\n WHERE p.board = board.id ORDER BY p.participant)\n AS \"participants!: Vec\", locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\", epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"", "describe": { "columns": [ { @@ -38,14 +38,9 @@ }, { "ordinal": 3, - "name": "participants: Vec", + "name": "participants!: Vec", "type_info": "UuidArray", - "origin": { - "Table": { - "table": "board", - "name": "participants" - } - } + "origin": "Expression" }, { "ordinal": 4, @@ -123,7 +118,7 @@ false, false, false, - false, + null, false, true, true, @@ -132,5 +127,5 @@ false ] }, - "hash": "f6ab1a10c0ebdc295fe7ea726b189838548d9535470d0eafce7c8911d71015d7" + "hash": "2c4a5e96ccd5b0b27c2c99846f574e7bf1fb475a7aefa88b9ce817ee05ad8582" } diff --git a/.sqlx/query-f0d305ba65359dea4a9d7b4a0577ae43db1c7ef01adc22450f75c0cd37c0d950.json b/.sqlx/query-321f0103b33607cbfda238c631fc4f0a47d8f3231e8fdfe3dfe60ae82eacf532.json similarity index 72% rename from .sqlx/query-f0d305ba65359dea4a9d7b4a0577ae43db1c7ef01adc22450f75c0cd37c0d950.json rename to .sqlx/query-321f0103b33607cbfda238c631fc4f0a47d8f3231e8fdfe3dfe60ae82eacf532.json index 489c55f..f5c56a0 100644 --- a/.sqlx/query-f0d305ba65359dea4a9d7b4a0577ae43db1c7ef01adc22450f75c0cd37c0d950.json +++ b/.sqlx/query-321f0103b33607cbfda238c631fc4f0a47d8f3231e8fdfe3dfe60ae82eacf532.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: RagOutputId\", course_note AS \"course_note: CourseNoteId\",\n course AS \"course: CourseId\",\n sources AS \"sources: Vec\",\n payload AS \"payload: Json\",\n generated_at AS \"generated_at: Timestamp\"\n FROM rag_output WHERE id = $1", + "query": "SELECT id AS \"id: RagOutputId\", course_note AS \"course_note: CourseNoteId\",\n course AS \"course: CourseId\",\n payload AS \"payload: Json\",\n generated_at AS \"generated_at: Timestamp\"\n FROM rag_output WHERE id = $1", "describe": { "columns": [ { @@ -38,17 +38,6 @@ }, { "ordinal": 3, - "name": "sources: Vec", - "type_info": "UuidArray", - "origin": { - "Table": { - "table": "rag_output", - "name": "sources" - } - } - }, - { - "ordinal": 4, "name": "payload: Json", "type_info": "Jsonb", "origin": { @@ -59,7 +48,7 @@ } }, { - "ordinal": 5, + "ordinal": 4, "name": "generated_at: Timestamp", "type_info": "Int8", "origin": { @@ -80,9 +69,8 @@ false, false, false, - false, false ] }, - "hash": "f0d305ba65359dea4a9d7b4a0577ae43db1c7ef01adc22450f75c0cd37c0d950" + "hash": "321f0103b33607cbfda238c631fc4f0a47d8f3231e8fdfe3dfe60ae82eacf532" } diff --git a/.sqlx/query-99469fccd450e6d9fae93713e93936de6a95cefbdefaae798d88c8cda1da9fc6.json b/.sqlx/query-329a782baf49baadc80e6c3a233f203c9eea7308e773738dfd905a9eb131dcb2.json similarity index 53% rename from .sqlx/query-99469fccd450e6d9fae93713e93936de6a95cefbdefaae798d88c8cda1da9fc6.json rename to .sqlx/query-329a782baf49baadc80e6c3a233f203c9eea7308e773738dfd905a9eb131dcb2.json index bfa7298..023071f 100644 --- a/.sqlx/query-99469fccd450e6d9fae93713e93936de6a95cefbdefaae798d88c8cda1da9fc6.json +++ b/.sqlx/query-329a782baf49baadc80e6c3a233f203c9eea7308e773738dfd905a9eb131dcb2.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "DELETE FROM rag_output WHERE $1 = ANY(sources)", + "query": "DELETE FROM course_teacher WHERE course = $1", "describe": { "columns": [], "parameters": { @@ -10,5 +10,5 @@ }, "nullable": [] }, - "hash": "99469fccd450e6d9fae93713e93936de6a95cefbdefaae798d88c8cda1da9fc6" + "hash": "329a782baf49baadc80e6c3a233f203c9eea7308e773738dfd905a9eb131dcb2" } diff --git a/.sqlx/query-32cf492f2994793969ed61eb7f2a0dc99b92d06993df0e078263d773feb3fff1.json b/.sqlx/query-32cf492f2994793969ed61eb7f2a0dc99b92d06993df0e078263d773feb3fff1.json index 2af49ed..2871290 100644 --- a/.sqlx/query-32cf492f2994793969ed61eb7f2a0dc99b92d06993df0e078263d773feb3fff1.json +++ b/.sqlx/query-32cf492f2994793969ed61eb7f2a0dc99b92d06993df0e078263d773feb3fff1.json @@ -5,7 +5,7 @@ "columns": [], "parameters": { "Left": [ - "Text" + "Uuid" ] }, "nullable": [] diff --git a/.sqlx/query-13d7f63724ed14449a9d6bfd3735072ce7eded7b6e5c40c33fc6140ae8747ec0.json b/.sqlx/query-33937eda61e33ee52f82bf7e6338428bdccf4e2d95f2499d9feb46ff6238f51d.json similarity index 86% rename from .sqlx/query-13d7f63724ed14449a9d6bfd3735072ce7eded7b6e5c40c33fc6140ae8747ec0.json rename to .sqlx/query-33937eda61e33ee52f82bf7e6338428bdccf4e2d95f2499d9feb46ff6238f51d.json index d48d89d..c057865 100644 --- a/.sqlx/query-13d7f63724ed14449a9d6bfd3735072ce7eded7b6e5c40c33fc6140ae8747ec0.json +++ b/.sqlx/query-33937eda61e33ee52f82bf7e6338428bdccf4e2d95f2499d9feb46ff6238f51d.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "DELETE FROM homework WHERE id = $1\n RETURNING id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END\n AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"", + "query": "DELETE FROM homework WHERE id = $1\n RETURNING id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"", "describe": { "columns": [ { @@ -115,5 +115,5 @@ false ] }, - "hash": "13d7f63724ed14449a9d6bfd3735072ce7eded7b6e5c40c33fc6140ae8747ec0" + "hash": "33937eda61e33ee52f82bf7e6338428bdccf4e2d95f2499d9feb46ff6238f51d" } diff --git a/.sqlx/query-3a2e8db644faec7cc2aab62aba2649c8707018d8af8f511c04310aa2357d8a4b.json b/.sqlx/query-3a2e8db644faec7cc2aab62aba2649c8707018d8af8f511c04310aa2357d8a4b.json new file mode 100644 index 0000000..9c072a1 --- /dev/null +++ b/.sqlx/query-3a2e8db644faec7cc2aab62aba2649c8707018d8af8f511c04310aa2357d8a4b.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO menu_dish_tag (dish, tag, ord)\n SELECT $1, tag, ord FROM unnest($2::text[]) WITH ORDINALITY AS t(tag, ord)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "TextArray" + ] + }, + "nullable": [] + }, + "hash": "3a2e8db644faec7cc2aab62aba2649c8707018d8af8f511c04310aa2357d8a4b" +} diff --git a/.sqlx/query-3c78ef010f90748dd6f60c086761e68d2e630763fc4732795891e4243e5e0eea.json b/.sqlx/query-3c78ef010f90748dd6f60c086761e68d2e630763fc4732795891e4243e5e0eea.json new file mode 100644 index 0000000..047f19b --- /dev/null +++ b/.sqlx/query-3c78ef010f90748dd6f60c086761e68d2e630763fc4732795891e4243e5e0eea.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM blueprint_course\n WHERE blueprint = $1 AND NOT (course = ANY($2))", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "UuidArray" + ] + }, + "nullable": [] + }, + "hash": "3c78ef010f90748dd6f60c086761e68d2e630763fc4732795891e4243e5e0eea" +} diff --git a/.sqlx/query-3d1db83ef8c406a80281be9cfc968dc81304180cd047d1ae2b65951528e1d4b1.json b/.sqlx/query-3d1db83ef8c406a80281be9cfc968dc81304180cd047d1ae2b65951528e1d4b1.json new file mode 100644 index 0000000..9d1c519 --- /dev/null +++ b/.sqlx/query-3d1db83ef8c406a80281be9cfc968dc81304180cd047d1ae2b65951528e1d4b1.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM blueprint_course WHERE course = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "3d1db83ef8c406a80281be9cfc968dc81304180cd047d1ae2b65951528e1d4b1" +} diff --git a/.sqlx/query-3e68616aab7908522dcb7aef662a6cc355fa9ce81fc609ad25450d2a1d8cf555.json b/.sqlx/query-3e68616aab7908522dcb7aef662a6cc355fa9ce81fc609ad25450d2a1d8cf555.json new file mode 100644 index 0000000..844d7c3 --- /dev/null +++ b/.sqlx/query-3e68616aab7908522dcb7aef662a6cc355fa9ce81fc609ad25450d2a1d8cf555.json @@ -0,0 +1,18 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO dietary_profile (student, note, updated_by, updated_at)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (student) DO UPDATE SET\n note = CASE WHEN $5 THEN $2 ELSE dietary_profile.note END,\n updated_by = $3,\n updated_at = $4", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Text", + "Uuid", + "Int8", + "Bool" + ] + }, + "nullable": [] + }, + "hash": "3e68616aab7908522dcb7aef662a6cc355fa9ce81fc609ad25450d2a1d8cf555" +} diff --git a/.sqlx/query-258c27c5e706ee3493229f3aacace4fa9ae874106c106a768b087e09f2234dcd.json b/.sqlx/query-3f35044808071da4e1275f141b5f80b6974dff0cb59238f7ab0e1b51a389e6b1.json similarity index 84% rename from .sqlx/query-258c27c5e706ee3493229f3aacace4fa9ae874106c106a768b087e09f2234dcd.json rename to .sqlx/query-3f35044808071da4e1275f141b5f80b6974dff0cb59238f7ab0e1b51a389e6b1.json index 36b0ed1..38ab6be 100644 --- a/.sqlx/query-258c27c5e706ee3493229f3aacace4fa9ae874106c106a768b087e09f2234dcd.json +++ b/.sqlx/query-3f35044808071da4e1275f141b5f80b6974dff0cb59238f7ab0e1b51a389e6b1.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END\n AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE id = $1 FOR UPDATE", + "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE id = $1 FOR UPDATE", "describe": { "columns": [ { @@ -115,5 +115,5 @@ false ] }, - "hash": "258c27c5e706ee3493229f3aacace4fa9ae874106c106a768b087e09f2234dcd" + "hash": "3f35044808071da4e1275f141b5f80b6974dff0cb59238f7ab0e1b51a389e6b1" } diff --git a/.sqlx/query-685fff635ecc5f67628da31ddcc229a97ac0ee9dbb5d8c73732e921e0613a1b0.json b/.sqlx/query-4033f72b27577d747740c96aa418736c7f8df98bf1a17083a72371155b0b553d.json similarity index 69% rename from .sqlx/query-685fff635ecc5f67628da31ddcc229a97ac0ee9dbb5d8c73732e921e0613a1b0.json rename to .sqlx/query-4033f72b27577d747740c96aa418736c7f8df98bf1a17083a72371155b0b553d.json index 6a5be77..96be4bc 100644 --- a/.sqlx/query-685fff635ecc5f67628da31ddcc229a97ac0ee9dbb5d8c73732e921e0613a1b0.json +++ b/.sqlx/query-4033f72b27577d747740c96aa418736c7f8df98bf1a17083a72371155b0b553d.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO course (id, creator, teachers, title, description, kind, term, capacity)\n VALUES ($1, $2, $3, $4, $5, $6, NULL, $7)\n RETURNING id AS \"id: CourseId\", creator AS \"creator: UserId\",\n teachers AS \"teachers: Vec\", title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity", + "query": "WITH seat AS (\n UPDATE term\n SET course_count = course_count + 1\n WHERE id = $7 AND course_count < $8\n RETURNING 1)\n INSERT INTO course (id, creator, title, description, kind, term, capacity)\n SELECT $1, $2, $3, $4, $5, $7, $6 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity", "describe": { "columns": [ { @@ -27,17 +27,6 @@ }, { "ordinal": 2, - "name": "teachers: Vec", - "type_info": "UuidArray", - "origin": { - "Table": { - "table": "course", - "name": "teachers" - } - } - }, - { - "ordinal": 3, "name": "title: CourseTitle", "type_info": "Text", "origin": { @@ -48,7 +37,7 @@ } }, { - "ordinal": 4, + "ordinal": 3, "name": "description: CourseDescription", "type_info": "Text", "origin": { @@ -59,7 +48,7 @@ } }, { - "ordinal": 5, + "ordinal": 4, "name": "kind: CourseKind", "type_info": "Text", "origin": { @@ -70,7 +59,7 @@ } }, { - "ordinal": 6, + "ordinal": 5, "name": "term: TermId", "type_info": "Uuid", "origin": { @@ -81,7 +70,7 @@ } }, { - "ordinal": 7, + "ordinal": 6, "name": "capacity", "type_info": "Int8", "origin": { @@ -96,10 +85,11 @@ "Left": [ "Uuid", "Uuid", - "UuidArray", "Text", "Text", "Text", + "Int8", + "Uuid", "Int8" ] }, @@ -109,10 +99,9 @@ false, false, false, - false, true, true ] }, - "hash": "685fff635ecc5f67628da31ddcc229a97ac0ee9dbb5d8c73732e921e0613a1b0" + "hash": "4033f72b27577d747740c96aa418736c7f8df98bf1a17083a72371155b0b553d" } diff --git a/.sqlx/query-8890b0928a86ed9b08e5803dc4fd3dca14b305482d4614abbbd19f982c9fd732.json b/.sqlx/query-40b8fe75dcbef4923d4d7f774d4cd2985cdd8768d31b752c235d4d5bbc2549d1.json similarity index 65% rename from .sqlx/query-8890b0928a86ed9b08e5803dc4fd3dca14b305482d4614abbbd19f982c9fd732.json rename to .sqlx/query-40b8fe75dcbef4923d4d7f774d4cd2985cdd8768d31b752c235d4d5bbc2549d1.json index 8b9fd25..5eb374a 100644 --- a/.sqlx/query-8890b0928a86ed9b08e5803dc4fd3dca14b305482d4614abbbd19f982c9fd732.json +++ b/.sqlx/query-40b8fe75dcbef4923d4d7f774d4cd2985cdd8768d31b752c235d4d5bbc2549d1.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "DELETE FROM rag_output WHERE id = $1\n RETURNING id AS \"id: RagOutputId\", course_note AS \"course_note: CourseNoteId\",\n course AS \"course: CourseId\",\n sources AS \"sources: Vec\",\n payload AS \"payload: Json\",\n generated_at AS \"generated_at: Timestamp\"", + "query": "DELETE FROM rag_output WHERE id = $1\n RETURNING id AS \"id: RagOutputId\", course_note AS \"course_note: CourseNoteId\",\n course AS \"course: CourseId\",\n payload AS \"payload: Json\",\n generated_at AS \"generated_at: Timestamp\"", "describe": { "columns": [ { @@ -38,17 +38,6 @@ }, { "ordinal": 3, - "name": "sources: Vec", - "type_info": "UuidArray", - "origin": { - "Table": { - "table": "rag_output", - "name": "sources" - } - } - }, - { - "ordinal": 4, "name": "payload: Json", "type_info": "Jsonb", "origin": { @@ -59,7 +48,7 @@ } }, { - "ordinal": 5, + "ordinal": 4, "name": "generated_at: Timestamp", "type_info": "Int8", "origin": { @@ -80,9 +69,8 @@ false, false, false, - false, false ] }, - "hash": "8890b0928a86ed9b08e5803dc4fd3dca14b305482d4614abbbd19f982c9fd732" + "hash": "40b8fe75dcbef4923d4d7f774d4cd2985cdd8768d31b752c235d4d5bbc2549d1" } diff --git a/.sqlx/query-425c4b69c806d2f70999dea4dfd56f471b95a2e0c99a880e428f5550abc05695.json b/.sqlx/query-425c4b69c806d2f70999dea4dfd56f471b95a2e0c99a880e428f5550abc05695.json new file mode 100644 index 0000000..2803730 --- /dev/null +++ b/.sqlx/query-425c4b69c806d2f70999dea4dfd56f471b95a2e0c99a880e428f5550abc05695.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM course_teacher WHERE teacher = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "425c4b69c806d2f70999dea4dfd56f471b95a2e0c99a880e428f5550abc05695" +} diff --git a/.sqlx/query-42dcb34cc907c4d361d0950c3a843ea62604494f00d597051e46eba1ae56625d.json b/.sqlx/query-42dcb34cc907c4d361d0950c3a843ea62604494f00d597051e46eba1ae56625d.json new file mode 100644 index 0000000..bc72668 --- /dev/null +++ b/.sqlx/query-42dcb34cc907c4d361d0950c3a843ea62604494f00d597051e46eba1ae56625d.json @@ -0,0 +1,12 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM settings_attendance_status WHERE settings = 'school'", + "describe": { + "columns": [], + "parameters": { + "Left": [] + }, + "nullable": [] + }, + "hash": "42dcb34cc907c4d361d0950c3a843ea62604494f00d597051e46eba1ae56625d" +} diff --git a/.sqlx/query-43d5cd5b3c47c16859989d22ad3a672b6ecd3a55bebac6efa1ade9a7620b564a.json b/.sqlx/query-43d5cd5b3c47c16859989d22ad3a672b6ecd3a55bebac6efa1ade9a7620b564a.json new file mode 100644 index 0000000..b7c0d91 --- /dev/null +++ b/.sqlx/query-43d5cd5b3c47c16859989d22ad3a672b6ecd3a55bebac6efa1ade9a7620b564a.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM rag_output_source WHERE output IN (\n SELECT id FROM rag_output WHERE course = $1)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "43d5cd5b3c47c16859989d22ad3a672b6ecd3a55bebac6efa1ade9a7620b564a" +} diff --git a/.sqlx/query-4a7ac53dc8e09c518c8f2cf1a992062f7c591143cdb056bf5a250235bbb12609.json b/.sqlx/query-4a7ac53dc8e09c518c8f2cf1a992062f7c591143cdb056bf5a250235bbb12609.json new file mode 100644 index 0000000..322d74d --- /dev/null +++ b/.sqlx/query-4a7ac53dc8e09c518c8f2cf1a992062f7c591143cdb056bf5a250235bbb12609.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM homework_assignment WHERE homework = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "4a7ac53dc8e09c518c8f2cf1a992062f7c591143cdb056bf5a250235bbb12609" +} diff --git a/.sqlx/query-4ade3a1620e48bd3d8bdd32450abc35b300037ef875d14026eaa226d3e543ef9.json b/.sqlx/query-4ade3a1620e48bd3d8bdd32450abc35b300037ef875d14026eaa226d3e543ef9.json new file mode 100644 index 0000000..3b6372e --- /dev/null +++ b/.sqlx/query-4ade3a1620e48bd3d8bdd32450abc35b300037ef875d14026eaa226d3e543ef9.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM class_blueprint WHERE id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "4ade3a1620e48bd3d8bdd32450abc35b300037ef875d14026eaa226d3e543ef9" +} diff --git a/.sqlx/query-4caddc18b673f2dfff6b63b51b271b205edd9f9550412eeba7f22e16a16971f2.json b/.sqlx/query-4caddc18b673f2dfff6b63b51b271b205edd9f9550412eeba7f22e16a16971f2.json deleted file mode 100644 index a5311df..0000000 --- a/.sqlx/query-4caddc18b673f2dfff6b63b51b271b205edd9f9550412eeba7f22e16a16971f2.json +++ /dev/null @@ -1,113 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE course SET teachers = array_remove(teachers, $2)\n WHERE id = $1\n RETURNING id AS \"id: CourseId\", creator AS \"creator: UserId\",\n teachers AS \"teachers: Vec\", title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "id: CourseId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "course", - "name": "id" - } - } - }, - { - "ordinal": 1, - "name": "creator: UserId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "course", - "name": "creator" - } - } - }, - { - "ordinal": 2, - "name": "teachers: Vec", - "type_info": "UuidArray", - "origin": { - "Table": { - "table": "course", - "name": "teachers" - } - } - }, - { - "ordinal": 3, - "name": "title: CourseTitle", - "type_info": "Text", - "origin": { - "Table": { - "table": "course", - "name": "title" - } - } - }, - { - "ordinal": 4, - "name": "description: CourseDescription", - "type_info": "Text", - "origin": { - "Table": { - "table": "course", - "name": "description" - } - } - }, - { - "ordinal": 5, - "name": "kind: CourseKind", - "type_info": "Text", - "origin": { - "Table": { - "table": "course", - "name": "kind" - } - } - }, - { - "ordinal": 6, - "name": "term: TermId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "course", - "name": "term" - } - } - }, - { - "ordinal": 7, - "name": "capacity", - "type_info": "Int8", - "origin": { - "Table": { - "table": "course", - "name": "capacity" - } - } - } - ], - "parameters": { - "Left": [ - "Uuid", - "Uuid" - ] - }, - "nullable": [ - false, - false, - false, - false, - false, - false, - true, - true - ] - }, - "hash": "4caddc18b673f2dfff6b63b51b271b205edd9f9550412eeba7f22e16a16971f2" -} diff --git a/.sqlx/query-4ef82265de6a27ab50351320b610fe0412bbf6be669731377fa8bf033f5cc072.json b/.sqlx/query-4ef82265de6a27ab50351320b610fe0412bbf6be669731377fa8bf033f5cc072.json new file mode 100644 index 0000000..b7146e4 --- /dev/null +++ b/.sqlx/query-4ef82265de6a27ab50351320b610fe0412bbf6be669731377fa8bf033f5cc072.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM dietary_profile_tag WHERE student = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "4ef82265de6a27ab50351320b610fe0412bbf6be669731377fa8bf033f5cc072" +} diff --git a/.sqlx/query-092ffc9c8c3d159f1792968df3591104dcd0e08206d94a092646c0cea5aff32a.json b/.sqlx/query-5258fa19ca184606b7078160ecbc6717830c3ca1ff9954c376d6c9c674ff4b5b.json similarity index 63% rename from .sqlx/query-092ffc9c8c3d159f1792968df3591104dcd0e08206d94a092646c0cea5aff32a.json rename to .sqlx/query-5258fa19ca184606b7078160ecbc6717830c3ca1ff9954c376d6c9c674ff4b5b.json index 66584ce..5e94899 100644 --- a/.sqlx/query-092ffc9c8c3d159f1792968df3591104dcd0e08206d94a092646c0cea5aff32a.json +++ b/.sqlx/query-5258fa19ca184606b7078160ecbc6717830c3ca1ff9954c376d6c9c674ff4b5b.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "WITH seat AS (\n UPDATE app_user SET board_count = board_count + 1\n WHERE id = $1 AND board_count < $2\n RETURNING 1)\n INSERT INTO board (id, creator, title, participants, locked, locked_by, locked_at,\n epoch, closed_at, created_at)\n SELECT $3, $1, $4, $5, false, NULL, NULL, 0, NULL, $6\n WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING id AS \"id: BoardId\", creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n participants AS \"participants: Vec\", locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\", epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"", + "query": "WITH seat AS (\n UPDATE app_user SET board_count = board_count + 1\n WHERE id = $1 AND board_count < $2\n RETURNING 1),\n new_board AS (\n INSERT INTO board (id, creator, title, locked, locked_by, locked_at,\n epoch, closed_at, created_at)\n SELECT $3, $1, $4, false, NULL, NULL, 0, NULL, $6\n WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING id, creator, title, locked, locked_by, locked_at,\n epoch, closed_at, created_at),\n roster AS (\n INSERT INTO board_participant (board, participant)\n SELECT $3, t.x FROM unnest($5::uuid[]) AS t(x)\n WHERE EXISTS (SELECT 1 FROM new_board)\n RETURNING participant)\n SELECT nb.id AS \"id: BoardId\", nb.creator AS \"creator: UserId\",\n nb.title AS \"title: BoardTitle\",\n COALESCE((SELECT array_agg(r.participant ORDER BY r.participant)\n FROM roster r), '{}')\n AS \"participants!: Vec\",\n nb.locked, nb.locked_by AS \"locked_by: UserId\",\n nb.locked_at AS \"locked_at: Timestamp\", nb.epoch,\n nb.closed_at AS \"closed_at: Timestamp\",\n nb.created_at AS \"created_at: Timestamp\"\n FROM new_board nb", "describe": { "columns": [ { @@ -38,14 +38,9 @@ }, { "ordinal": 3, - "name": "participants: Vec", + "name": "participants!: Vec", "type_info": "UuidArray", - "origin": { - "Table": { - "table": "board", - "name": "participants" - } - } + "origin": "Expression" }, { "ordinal": 4, @@ -128,7 +123,7 @@ false, false, false, - false, + null, false, true, true, @@ -137,5 +132,5 @@ false ] }, - "hash": "092ffc9c8c3d159f1792968df3591104dcd0e08206d94a092646c0cea5aff32a" + "hash": "5258fa19ca184606b7078160ecbc6717830c3ca1ff9954c376d6c9c674ff4b5b" } diff --git a/.sqlx/query-532d2d0011fe140007ad8f56fa63229d4ba5108df18938a8629ecfb70725b5ff.json b/.sqlx/query-532d2d0011fe140007ad8f56fa63229d4ba5108df18938a8629ecfb70725b5ff.json new file mode 100644 index 0000000..af7484c --- /dev/null +++ b/.sqlx/query-532d2d0011fe140007ad8f56fa63229d4ba5108df18938a8629ecfb70725b5ff.json @@ -0,0 +1,40 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT output, source AS \"source: CourseNoteFileId\"\n FROM rag_output_source WHERE output = ANY($1) ORDER BY source", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "output", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "rag_output_source", + "name": "output" + } + } + }, + { + "ordinal": 1, + "name": "source: CourseNoteFileId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "rag_output_source", + "name": "source" + } + } + } + ], + "parameters": { + "Left": [ + "UuidArray" + ] + }, + "nullable": [ + false, + false + ] + }, + "hash": "532d2d0011fe140007ad8f56fa63229d4ba5108df18938a8629ecfb70725b5ff" +} diff --git a/.sqlx/query-54a4303671c7acb834b45dabd55d93332990a094273f6ac2adb05bf94397010f.json b/.sqlx/query-54a4303671c7acb834b45dabd55d93332990a094273f6ac2adb05bf94397010f.json deleted file mode 100644 index d8cfa33..0000000 --- a/.sqlx/query-54a4303671c7acb834b45dabd55d93332990a094273f6ac2adb05bf94397010f.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE course SET teachers = array_remove(teachers, $1)\n WHERE $1 = ANY(teachers)", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Uuid" - ] - }, - "nullable": [] - }, - "hash": "54a4303671c7acb834b45dabd55d93332990a094273f6ac2adb05bf94397010f" -} diff --git a/.sqlx/query-553487a166d9b3d9c0e3d4c7a5270c13768fb537393c70e006466df156a319a2.json b/.sqlx/query-553487a166d9b3d9c0e3d4c7a5270c13768fb537393c70e006466df156a319a2.json new file mode 100644 index 0000000..8995ab3 --- /dev/null +++ b/.sqlx/query-553487a166d9b3d9c0e3d4c7a5270c13768fb537393c70e006466df156a319a2.json @@ -0,0 +1,105 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO course (id, creator, title, description, kind, term, capacity)\n VALUES ($1, $2, $3, $4, $5, NULL, $6)\n RETURNING id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: CourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "creator: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course", + "name": "creator" + } + } + }, + { + "ordinal": 2, + "name": "title: CourseTitle", + "type_info": "Text", + "origin": { + "Table": { + "table": "course", + "name": "title" + } + } + }, + { + "ordinal": 3, + "name": "description: CourseDescription", + "type_info": "Text", + "origin": { + "Table": { + "table": "course", + "name": "description" + } + } + }, + { + "ordinal": 4, + "name": "kind: CourseKind", + "type_info": "Text", + "origin": { + "Table": { + "table": "course", + "name": "kind" + } + } + }, + { + "ordinal": 5, + "name": "term: TermId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course", + "name": "term" + } + } + }, + { + "ordinal": 6, + "name": "capacity", + "type_info": "Int8", + "origin": { + "Table": { + "table": "course", + "name": "capacity" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid", + "Uuid", + "Text", + "Text", + "Text", + "Int8" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + true, + true + ] + }, + "hash": "553487a166d9b3d9c0e3d4c7a5270c13768fb537393c70e006466df156a319a2" +} diff --git a/.sqlx/query-57a63446535fbaf09ea123221182709ac1102fcafffd227c1fa1dc4e36a944af.json b/.sqlx/query-57a63446535fbaf09ea123221182709ac1102fcafffd227c1fa1dc4e36a944af.json new file mode 100644 index 0000000..59b7638 --- /dev/null +++ b/.sqlx/query-57a63446535fbaf09ea123221182709ac1102fcafffd227c1fa1dc4e36a944af.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id FROM board WHERE id = $1 FOR NO KEY UPDATE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "board", + "name": "id" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "57a63446535fbaf09ea123221182709ac1102fcafffd227c1fa1dc4e36a944af" +} diff --git a/.sqlx/query-a70bfbf0b8ea81aab2f5b907a40ed1a4236cff0484bf3bc652e24133407283e5.json b/.sqlx/query-59e72e6dab4c94b31994810b4bf1d195587319a4ab757166a046b394e86938a5.json similarity index 68% rename from .sqlx/query-a70bfbf0b8ea81aab2f5b907a40ed1a4236cff0484bf3bc652e24133407283e5.json rename to .sqlx/query-59e72e6dab4c94b31994810b4bf1d195587319a4ab757166a046b394e86938a5.json index 7c61093..6ebb70d 100644 --- a/.sqlx/query-a70bfbf0b8ea81aab2f5b907a40ed1a4236cff0484bf3bc652e24133407283e5.json +++ b/.sqlx/query-59e72e6dab4c94b31994810b4bf1d195587319a4ab757166a046b394e86938a5.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "WITH seat AS (\n UPDATE subject SET homework_count = homework_count + 1\n WHERE id = $1\n RETURNING 1\n )\n INSERT INTO homework (id, course, subject, title, description, due_at, assigned, created_by, created_at)\n SELECT $2, $3, $1, $4, $5, $6, $7, $8, $9 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END\n AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"", + "query": "WITH seat AS (\n UPDATE subject SET homework_count = homework_count + 1\n WHERE id = $1\n RETURNING 1\n )\n INSERT INTO homework (id, course, subject, title, description, due_at, created_by, created_at)\n SELECT $2, $3, $1, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n NULL::uuid[] AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"", "describe": { "columns": [ { @@ -106,7 +106,6 @@ "Text", "Text", "Int8", - "UuidArray", "Uuid", "Int8" ] @@ -123,5 +122,5 @@ false ] }, - "hash": "a70bfbf0b8ea81aab2f5b907a40ed1a4236cff0484bf3bc652e24133407283e5" + "hash": "59e72e6dab4c94b31994810b4bf1d195587319a4ab757166a046b394e86938a5" } diff --git a/.sqlx/query-bac093371039a68fb29a6739b77ad3e835ae128d3c7f0a712793da3cbdd9d429.json b/.sqlx/query-5d88e06f2106d13aa6bc807c6c7dfae53259b9db0048d350758a546836021e3c.json similarity index 55% rename from .sqlx/query-bac093371039a68fb29a6739b77ad3e835ae128d3c7f0a712793da3cbdd9d429.json rename to .sqlx/query-5d88e06f2106d13aa6bc807c6c7dfae53259b9db0048d350758a546836021e3c.json index 46ae16a..929f610 100644 --- a/.sqlx/query-bac093371039a68fb29a6739b77ad3e835ae128d3c7f0a712793da3cbdd9d429.json +++ b/.sqlx/query-5d88e06f2106d13aa6bc807c6c7dfae53259b9db0048d350758a546836021e3c.json @@ -1,16 +1,16 @@ { "db_name": "PostgreSQL", - "query": "SELECT grade AS \"id: ClassBlueprintId\", grade AS \"grade: ClassGrade\",\n courses AS \"courses: Vec\", creator AS \"creator: UserId\"\n FROM class_blueprint WHERE grade = $1", + "query": "SELECT id AS \"key: uuid::Uuid\", grade AS \"grade: ClassGrade\",\n creator AS \"creator: UserId\"\n FROM class_blueprint WHERE grade = $1 FOR UPDATE", "describe": { "columns": [ { "ordinal": 0, - "name": "id: ClassBlueprintId", - "type_info": "Text", + "name": "key: uuid::Uuid", + "type_info": "Uuid", "origin": { "Table": { "table": "class_blueprint", - "name": "grade" + "name": "id" } } }, @@ -27,17 +27,6 @@ }, { "ordinal": 2, - "name": "courses: Vec", - "type_info": "UuidArray", - "origin": { - "Table": { - "table": "class_blueprint", - "name": "courses" - } - } - }, - { - "ordinal": 3, "name": "creator: UserId", "type_info": "Uuid", "origin": { @@ -54,11 +43,10 @@ ] }, "nullable": [ - false, false, false, false ] }, - "hash": "bac093371039a68fb29a6739b77ad3e835ae128d3c7f0a712793da3cbdd9d429" + "hash": "5d88e06f2106d13aa6bc807c6c7dfae53259b9db0048d350758a546836021e3c" } diff --git a/.sqlx/query-97e71a885347d2ee6ee809e3608825b108349bb0dde0046d5817dfcc56d6a583.json b/.sqlx/query-60dc8924b722dbdeafa1686248b574aca9089ae24b9d87521a134267f4f76caa.json similarity index 73% rename from .sqlx/query-97e71a885347d2ee6ee809e3608825b108349bb0dde0046d5817dfcc56d6a583.json rename to .sqlx/query-60dc8924b722dbdeafa1686248b574aca9089ae24b9d87521a134267f4f76caa.json index 73562ed..0ec1dca 100644 --- a/.sqlx/query-97e71a885347d2ee6ee809e3608825b108349bb0dde0046d5817dfcc56d6a583.json +++ b/.sqlx/query-60dc8924b722dbdeafa1686248b574aca9089ae24b9d87521a134267f4f76caa.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE homework SET subject = $2, title = $3, description = $4,\n due_at = $5, assigned = $6\n WHERE id = $1\n RETURNING id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END\n AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"", + "query": "UPDATE homework SET subject = $2, title = $3, description = $4,\n due_at = $5\n WHERE id = $1\n RETURNING id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"", "describe": { "columns": [ { @@ -104,8 +104,7 @@ "Uuid", "Text", "Text", - "Int8", - "UuidArray" + "Int8" ] }, "nullable": [ @@ -120,5 +119,5 @@ false ] }, - "hash": "97e71a885347d2ee6ee809e3608825b108349bb0dde0046d5817dfcc56d6a583" + "hash": "60dc8924b722dbdeafa1686248b574aca9089ae24b9d87521a134267f4f76caa" } diff --git a/.sqlx/query-61c84c00d51c17a737b8358ac320d7b7d17420cdc12bd26939b3eca27088d275.json b/.sqlx/query-61c84c00d51c17a737b8358ac320d7b7d17420cdc12bd26939b3eca27088d275.json new file mode 100644 index 0000000..077c691 --- /dev/null +++ b/.sqlx/query-61c84c00d51c17a737b8358ac320d7b7d17420cdc12bd26939b3eca27088d275.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM homework_assignment WHERE homework IN (\n SELECT id FROM homework WHERE course = $1)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "61c84c00d51c17a737b8358ac320d7b7d17420cdc12bd26939b3eca27088d275" +} diff --git a/.sqlx/query-633c525f787d9597ef6d6e5ca7019918a413158e9446b39fe5b69da534810e60.json b/.sqlx/query-633c525f787d9597ef6d6e5ca7019918a413158e9446b39fe5b69da534810e60.json deleted file mode 100644 index fe2e50a..0000000 --- a/.sqlx/query-633c525f787d9597ef6d6e5ca7019918a413158e9446b39fe5b69da534810e60.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "DELETE FROM class_blueprint WHERE grade = $1 AND courses = $2", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Text", - "UuidArray" - ] - }, - "nullable": [] - }, - "hash": "633c525f787d9597ef6d6e5ca7019918a413158e9446b39fe5b69da534810e60" -} diff --git a/.sqlx/query-63bdf7314ccc48750af75af20167e573b36ded45dc3f8050b95ea6823ae3177a.json b/.sqlx/query-63bdf7314ccc48750af75af20167e573b36ded45dc3f8050b95ea6823ae3177a.json new file mode 100644 index 0000000..a063699 --- /dev/null +++ b/.sqlx/query-63bdf7314ccc48750af75af20167e573b36ded45dc3f8050b95ea6823ae3177a.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM menu_dish_tag WHERE dish = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "63bdf7314ccc48750af75af20167e573b36ded45dc3f8050b95ea6823ae3177a" +} diff --git a/.sqlx/query-42ec2891956481a4fb70b81cc230621f4481f2fc57e10e3680043fb83c850c66.json b/.sqlx/query-63e9be4296079ff969f4a3e464e6dd9ad20d54e788a7af2e04e50658bcc1c45c.json similarity index 79% rename from .sqlx/query-42ec2891956481a4fb70b81cc230621f4481f2fc57e10e3680043fb83c850c66.json rename to .sqlx/query-63e9be4296079ff969f4a3e464e6dd9ad20d54e788a7af2e04e50658bcc1c45c.json index 48bbe49..aeab7f5 100644 --- a/.sqlx/query-42ec2891956481a4fb70b81cc230621f4481f2fc57e10e3680043fb83c850c66.json +++ b/.sqlx/query-63e9be4296079ff969f4a3e464e6dd9ad20d54e788a7af2e04e50658bcc1c45c.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", tags AS \"tags: DishTags\", created_at AS \"created_at: Timestamp\"\n FROM menu_dish WHERE id = $1", + "query": "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\",\n COALESCE((SELECT array_agg(t.tag ORDER BY t.ord) FROM menu_dish_tag t WHERE t.dish = menu_dish.id), '{}'::text[]) AS \"tags!: DishTags\",\n created_at AS \"created_at: Timestamp\"\n FROM menu_dish WHERE id = $1", "describe": { "columns": [ { @@ -60,14 +60,9 @@ }, { "ordinal": 5, - "name": "tags: DishTags", + "name": "tags!: DishTags", "type_info": "TextArray", - "origin": { - "Table": { - "table": "menu_dish", - "name": "tags" - } - } + "origin": "Expression" }, { "ordinal": 6, @@ -92,9 +87,9 @@ false, true, false, - false, + null, false ] }, - "hash": "42ec2891956481a4fb70b81cc230621f4481f2fc57e10e3680043fb83c850c66" + "hash": "63e9be4296079ff969f4a3e464e6dd9ad20d54e788a7af2e04e50658bcc1c45c" } diff --git a/.sqlx/query-07f5872671b049dca356394ea98c9840bf57fd5e586b4ff36ffabb988a8423c5.json b/.sqlx/query-6907da40c5b42ea56fb9c257cd9b486869381275626163e8bd75e928188875b1.json similarity index 75% rename from .sqlx/query-07f5872671b049dca356394ea98c9840bf57fd5e586b4ff36ffabb988a8423c5.json rename to .sqlx/query-6907da40c5b42ea56fb9c257cd9b486869381275626163e8bd75e928188875b1.json index aa1726e..1668a7e 100644 --- a/.sqlx/query-07f5872671b049dca356394ea98c9840bf57fd5e586b4ff36ffabb988a8423c5.json +++ b/.sqlx/query-6907da40c5b42ea56fb9c257cd9b486869381275626163e8bd75e928188875b1.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n teachers AS \"teachers: Vec\", title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity\n FROM course WHERE id = $1", + "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity\n FROM course WHERE id = $1", "describe": { "columns": [ { @@ -27,17 +27,6 @@ }, { "ordinal": 2, - "name": "teachers: Vec", - "type_info": "UuidArray", - "origin": { - "Table": { - "table": "course", - "name": "teachers" - } - } - }, - { - "ordinal": 3, "name": "title: CourseTitle", "type_info": "Text", "origin": { @@ -48,7 +37,7 @@ } }, { - "ordinal": 4, + "ordinal": 3, "name": "description: CourseDescription", "type_info": "Text", "origin": { @@ -59,7 +48,7 @@ } }, { - "ordinal": 5, + "ordinal": 4, "name": "kind: CourseKind", "type_info": "Text", "origin": { @@ -70,7 +59,7 @@ } }, { - "ordinal": 6, + "ordinal": 5, "name": "term: TermId", "type_info": "Uuid", "origin": { @@ -81,7 +70,7 @@ } }, { - "ordinal": 7, + "ordinal": 6, "name": "capacity", "type_info": "Int8", "origin": { @@ -103,10 +92,9 @@ false, false, false, - false, true, true ] }, - "hash": "07f5872671b049dca356394ea98c9840bf57fd5e586b4ff36ffabb988a8423c5" + "hash": "6907da40c5b42ea56fb9c257cd9b486869381275626163e8bd75e928188875b1" } diff --git a/.sqlx/query-69308bfda3e686112dfaa6493e2729e250ce149537408ac7b0124b3d33582980.json b/.sqlx/query-69308bfda3e686112dfaa6493e2729e250ce149537408ac7b0124b3d33582980.json deleted file mode 100644 index 3d1f612..0000000 --- a/.sqlx/query-69308bfda3e686112dfaa6493e2729e250ce149537408ac7b0124b3d33582980.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE course SET teachers = array_remove(teachers, $1) WHERE $1 = ANY(teachers)", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Uuid" - ] - }, - "nullable": [] - }, - "hash": "69308bfda3e686112dfaa6493e2729e250ce149537408ac7b0124b3d33582980" -} diff --git a/.sqlx/query-96175480de70dd3d01e7b9d4a5edd779f04ace47d43143e0e1ed353c3a8ce3fc.json b/.sqlx/query-6c518ef0581ca1549988917c39135198f1bf92d9a7b4984b227849771bec8699.json similarity index 85% rename from .sqlx/query-96175480de70dd3d01e7b9d4a5edd779f04ace47d43143e0e1ed353c3a8ce3fc.json rename to .sqlx/query-6c518ef0581ca1549988917c39135198f1bf92d9a7b4984b227849771bec8699.json index c7a09ad..b0df317 100644 --- a/.sqlx/query-96175480de70dd3d01e7b9d4a5edd779f04ace47d43143e0e1ed353c3a8ce3fc.json +++ b/.sqlx/query-6c518ef0581ca1549988917c39135198f1bf92d9a7b4984b227849771bec8699.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END\n AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework ORDER BY id DESC", + "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework ORDER BY id DESC", "describe": { "columns": [ { @@ -113,5 +113,5 @@ false ] }, - "hash": "96175480de70dd3d01e7b9d4a5edd779f04ace47d43143e0e1ed353c3a8ce3fc" + "hash": "6c518ef0581ca1549988917c39135198f1bf92d9a7b4984b227849771bec8699" } diff --git a/.sqlx/query-6ce14f236c940b29b7107569aed2d0c176065c36a5ba34a1757c9f3cef17d15f.json b/.sqlx/query-6ce14f236c940b29b7107569aed2d0c176065c36a5ba34a1757c9f3cef17d15f.json new file mode 100644 index 0000000..55efb93 --- /dev/null +++ b/.sqlx/query-6ce14f236c940b29b7107569aed2d0c176065c36a5ba34a1757c9f3cef17d15f.json @@ -0,0 +1,132 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT b.id AS \"id: BoardId\", b.creator AS \"creator: UserId\",\n b.title AS \"title: BoardTitle\",\n ARRAY(SELECT p.participant FROM board_participant p\n WHERE p.board = b.id ORDER BY p.participant)\n AS \"participants!: Vec\",\n b.locked, b.locked_by AS \"locked_by: UserId\",\n b.locked_at AS \"locked_at: Timestamp\", b.epoch,\n b.closed_at AS \"closed_at: Timestamp\",\n b.created_at AS \"created_at: Timestamp\"\n FROM board b\n WHERE b.id = ANY($1::uuid[]) OR b.creator = $2\n ORDER BY b.id", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: BoardId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "board", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "creator: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "board", + "name": "creator" + } + } + }, + { + "ordinal": 2, + "name": "title: BoardTitle", + "type_info": "Text", + "origin": { + "Table": { + "table": "board", + "name": "title" + } + } + }, + { + "ordinal": 3, + "name": "participants!: Vec", + "type_info": "UuidArray", + "origin": "Expression" + }, + { + "ordinal": 4, + "name": "locked", + "type_info": "Bool", + "origin": { + "Table": { + "table": "board", + "name": "locked" + } + } + }, + { + "ordinal": 5, + "name": "locked_by: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "board", + "name": "locked_by" + } + } + }, + { + "ordinal": 6, + "name": "locked_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "board", + "name": "locked_at" + } + } + }, + { + "ordinal": 7, + "name": "epoch", + "type_info": "Int8", + "origin": { + "Table": { + "table": "board", + "name": "epoch" + } + } + }, + { + "ordinal": 8, + "name": "closed_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "board", + "name": "closed_at" + } + } + }, + { + "ordinal": 9, + "name": "created_at: Timestamp", + "type_info": "Int8", + "origin": { + "Table": { + "table": "board", + "name": "created_at" + } + } + } + ], + "parameters": { + "Left": [ + "UuidArray", + "Uuid" + ] + }, + "nullable": [ + false, + false, + false, + null, + false, + true, + true, + false, + true, + false + ] + }, + "hash": "6ce14f236c940b29b7107569aed2d0c176065c36a5ba34a1757c9f3cef17d15f" +} diff --git a/.sqlx/query-5942f054f1c660ec1eaf894afdf37c2ed8aa3ec0dfecf243b26193210619377f.json b/.sqlx/query-6ce455efe2f18ee3bf4a217db31b91d188bfff40e5e1e0af2789e92ca110c71f.json similarity index 74% rename from .sqlx/query-5942f054f1c660ec1eaf894afdf37c2ed8aa3ec0dfecf243b26193210619377f.json rename to .sqlx/query-6ce455efe2f18ee3bf4a217db31b91d188bfff40e5e1e0af2789e92ca110c71f.json index 750aed8..2fccff2 100644 --- a/.sqlx/query-5942f054f1c660ec1eaf894afdf37c2ed8aa3ec0dfecf243b26193210619377f.json +++ b/.sqlx/query-6ce455efe2f18ee3bf4a217db31b91d188bfff40e5e1e0af2789e92ca110c71f.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n teachers AS \"teachers: Vec\", title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity\n FROM course WHERE creator = $1 OR $2 = ANY(teachers) ORDER BY id DESC", + "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity\n FROM course WHERE creator = $1 OR id IN (\n SELECT course FROM course_teacher WHERE teacher = $2)\n ORDER BY id DESC", "describe": { "columns": [ { @@ -27,17 +27,6 @@ }, { "ordinal": 2, - "name": "teachers: Vec", - "type_info": "UuidArray", - "origin": { - "Table": { - "table": "course", - "name": "teachers" - } - } - }, - { - "ordinal": 3, "name": "title: CourseTitle", "type_info": "Text", "origin": { @@ -48,7 +37,7 @@ } }, { - "ordinal": 4, + "ordinal": 3, "name": "description: CourseDescription", "type_info": "Text", "origin": { @@ -59,7 +48,7 @@ } }, { - "ordinal": 5, + "ordinal": 4, "name": "kind: CourseKind", "type_info": "Text", "origin": { @@ -70,7 +59,7 @@ } }, { - "ordinal": 6, + "ordinal": 5, "name": "term: TermId", "type_info": "Uuid", "origin": { @@ -81,7 +70,7 @@ } }, { - "ordinal": 7, + "ordinal": 6, "name": "capacity", "type_info": "Int8", "origin": { @@ -104,10 +93,9 @@ false, false, false, - false, true, true ] }, - "hash": "5942f054f1c660ec1eaf894afdf37c2ed8aa3ec0dfecf243b26193210619377f" + "hash": "6ce455efe2f18ee3bf4a217db31b91d188bfff40e5e1e0af2789e92ca110c71f" } diff --git a/.sqlx/query-3dbbe1738727b434a5bf46e535e16b293dc59a120c861b79ab3166cf0a0e27df.json b/.sqlx/query-6fcc2a42e243df55569ca080ec3cbb8a71f134255f4f9283bbde0e90537c6501.json similarity index 81% rename from .sqlx/query-3dbbe1738727b434a5bf46e535e16b293dc59a120c861b79ab3166cf0a0e27df.json rename to .sqlx/query-6fcc2a42e243df55569ca080ec3cbb8a71f134255f4f9283bbde0e90537c6501.json index 14d81b6..d91fd0c 100644 --- a/.sqlx/query-3dbbe1738727b434a5bf46e535e16b293dc59a120c861b79ab3166cf0a0e27df.json +++ b/.sqlx/query-6fcc2a42e243df55569ca080ec3cbb8a71f134255f4f9283bbde0e90537c6501.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE board SET title = $2 WHERE id = $1\n RETURNING id AS \"id: BoardId\", creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n participants AS \"participants: Vec\", locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\", epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"", + "query": "UPDATE board SET title = $2 WHERE id = $1\n RETURNING id AS \"id: BoardId\", creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n ARRAY(SELECT p.participant FROM board_participant p\n WHERE p.board = board.id ORDER BY p.participant)\n AS \"participants!: Vec\", locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\", epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"", "describe": { "columns": [ { @@ -38,14 +38,9 @@ }, { "ordinal": 3, - "name": "participants: Vec", + "name": "participants!: Vec", "type_info": "UuidArray", - "origin": { - "Table": { - "table": "board", - "name": "participants" - } - } + "origin": "Expression" }, { "ordinal": 4, @@ -124,7 +119,7 @@ false, false, false, - false, + null, false, true, true, @@ -133,5 +128,5 @@ false ] }, - "hash": "3dbbe1738727b434a5bf46e535e16b293dc59a120c861b79ab3166cf0a0e27df" + "hash": "6fcc2a42e243df55569ca080ec3cbb8a71f134255f4f9283bbde0e90537c6501" } diff --git a/.sqlx/query-3b8dd2053a8627a7e965b5aabb4640b02fbf9653ac9da6af47e5d0732e611a29.json b/.sqlx/query-72cd9aa43384131ba5489ac5b79e9108aabe3ddb6dc9522530787d3fa632b595.json similarity index 86% rename from .sqlx/query-3b8dd2053a8627a7e965b5aabb4640b02fbf9653ac9da6af47e5d0732e611a29.json rename to .sqlx/query-72cd9aa43384131ba5489ac5b79e9108aabe3ddb6dc9522530787d3fa632b595.json index 70710ab..d987869 100644 --- a/.sqlx/query-3b8dd2053a8627a7e965b5aabb4640b02fbf9653ac9da6af47e5d0732e611a29.json +++ b/.sqlx/query-72cd9aa43384131ba5489ac5b79e9108aabe3ddb6dc9522530787d3fa632b595.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END\n AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE course = $1 ORDER BY id DESC", + "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE id = $1", "describe": { "columns": [ { @@ -115,5 +115,5 @@ false ] }, - "hash": "3b8dd2053a8627a7e965b5aabb4640b02fbf9653ac9da6af47e5d0732e611a29" + "hash": "72cd9aa43384131ba5489ac5b79e9108aabe3ddb6dc9522530787d3fa632b595" } diff --git a/.sqlx/query-743dc724aee85af2244e80c69a71610a2d9f88eee804fad8c4936cd23e4770d3.json b/.sqlx/query-743dc724aee85af2244e80c69a71610a2d9f88eee804fad8c4936cd23e4770d3.json new file mode 100644 index 0000000..abd5ffb --- /dev/null +++ b/.sqlx/query-743dc724aee85af2244e80c69a71610a2d9f88eee804fad8c4936cd23e4770d3.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM blueprint_course WHERE blueprint = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "743dc724aee85af2244e80c69a71610a2d9f88eee804fad8c4936cd23e4770d3" +} diff --git a/.sqlx/query-771928c37367daef7caef3a0faa381d01bd34a4f4a6559c362499376a0518bfd.json b/.sqlx/query-771928c37367daef7caef3a0faa381d01bd34a4f4a6559c362499376a0518bfd.json new file mode 100644 index 0000000..5e700d3 --- /dev/null +++ b/.sqlx/query-771928c37367daef7caef3a0faa381d01bd34a4f4a6559c362499376a0518bfd.json @@ -0,0 +1,12 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM settings_dietary_tag WHERE settings = 'school'", + "describe": { + "columns": [], + "parameters": { + "Left": [] + }, + "nullable": [] + }, + "hash": "771928c37367daef7caef3a0faa381d01bd34a4f4a6559c362499376a0518bfd" +} diff --git a/.sqlx/query-800bb78fa5b427d8ccb72cf3ba69e8fb9c8d3bffb022d47939e9ee0269eb764a.json b/.sqlx/query-800bb78fa5b427d8ccb72cf3ba69e8fb9c8d3bffb022d47939e9ee0269eb764a.json new file mode 100644 index 0000000..1905c5e --- /dev/null +++ b/.sqlx/query-800bb78fa5b427d8ccb72cf3ba69e8fb9c8d3bffb022d47939e9ee0269eb764a.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO blueprint_course (blueprint, course)\n SELECT $1, x FROM unnest($2::uuid[]) AS t(x)\n ON CONFLICT DO NOTHING", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "UuidArray" + ] + }, + "nullable": [] + }, + "hash": "800bb78fa5b427d8ccb72cf3ba69e8fb9c8d3bffb022d47939e9ee0269eb764a" +} diff --git a/.sqlx/query-c9176c3fd78effbb5626b81d72d2f9d02c841a21271501ed5d27f64c8b08fbad.json b/.sqlx/query-8cfb7acdfe6bb096f83920c104c8c45fafa1e717db6630c7e3fde77816d9e3a7.json similarity index 85% rename from .sqlx/query-c9176c3fd78effbb5626b81d72d2f9d02c841a21271501ed5d27f64c8b08fbad.json rename to .sqlx/query-8cfb7acdfe6bb096f83920c104c8c45fafa1e717db6630c7e3fde77816d9e3a7.json index 56508f8..66f563a 100644 --- a/.sqlx/query-c9176c3fd78effbb5626b81d72d2f9d02c841a21271501ed5d27f64c8b08fbad.json +++ b/.sqlx/query-8cfb7acdfe6bb096f83920c104c8c45fafa1e717db6630c7e3fde77816d9e3a7.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END\n AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE course = ANY($1) ORDER BY id DESC", + "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE course = ANY($1) ORDER BY id DESC", "describe": { "columns": [ { @@ -115,5 +115,5 @@ false ] }, - "hash": "c9176c3fd78effbb5626b81d72d2f9d02c841a21271501ed5d27f64c8b08fbad" + "hash": "8cfb7acdfe6bb096f83920c104c8c45fafa1e717db6630c7e3fde77816d9e3a7" } diff --git a/.sqlx/query-befcf1a2da3632684bcc6d741540c05719315260192d47a8cd50c1d45eb32e8d.json b/.sqlx/query-8d7ae20c108d3c74fd9d841f7b36eed4cc0cbc04fc93ff05b33e6c70a91116e2.json similarity index 51% rename from .sqlx/query-befcf1a2da3632684bcc6d741540c05719315260192d47a8cd50c1d45eb32e8d.json rename to .sqlx/query-8d7ae20c108d3c74fd9d841f7b36eed4cc0cbc04fc93ff05b33e6c70a91116e2.json index ce2566d..040daef 100644 --- a/.sqlx/query-befcf1a2da3632684bcc6d741540c05719315260192d47a8cd50c1d45eb32e8d.json +++ b/.sqlx/query-8d7ae20c108d3c74fd9d841f7b36eed4cc0cbc04fc93ff05b33e6c70a91116e2.json @@ -1,16 +1,16 @@ { "db_name": "PostgreSQL", - "query": "SELECT courses AS \"courses: Vec\"\n FROM class_blueprint WHERE grade = $1 FOR UPDATE", + "query": "SELECT id AS \"key: uuid::Uuid\" FROM class_blueprint\n WHERE grade = $1 FOR UPDATE", "describe": { "columns": [ { "ordinal": 0, - "name": "courses: Vec", - "type_info": "UuidArray", + "name": "key: uuid::Uuid", + "type_info": "Uuid", "origin": { "Table": { "table": "class_blueprint", - "name": "courses" + "name": "id" } } } @@ -24,5 +24,5 @@ false ] }, - "hash": "befcf1a2da3632684bcc6d741540c05719315260192d47a8cd50c1d45eb32e8d" + "hash": "8d7ae20c108d3c74fd9d841f7b36eed4cc0cbc04fc93ff05b33e6c70a91116e2" } diff --git a/.sqlx/query-8e4568e7dfb68793acc1aa2a9c142314670484e5eacfdcf9b4fec3ed887b6b0d.json b/.sqlx/query-8e4568e7dfb68793acc1aa2a9c142314670484e5eacfdcf9b4fec3ed887b6b0d.json new file mode 100644 index 0000000..fc13484 --- /dev/null +++ b/.sqlx/query-8e4568e7dfb68793acc1aa2a9c142314670484e5eacfdcf9b4fec3ed887b6b0d.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO blueprint_course (blueprint, course)\n SELECT $1, x FROM unnest($2::uuid[]) AS t(x)\n ON CONFLICT DO NOTHING", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "UuidArray" + ] + }, + "nullable": [] + }, + "hash": "8e4568e7dfb68793acc1aa2a9c142314670484e5eacfdcf9b4fec3ed887b6b0d" +} diff --git a/.sqlx/query-8e687f07237ef09a151a945cd4046978aa69cbda3bd53e1c79157f840edf1443.json b/.sqlx/query-8e687f07237ef09a151a945cd4046978aa69cbda3bd53e1c79157f840edf1443.json deleted file mode 100644 index 5b895a2..0000000 --- a/.sqlx/query-8e687f07237ef09a151a945cd4046978aa69cbda3bd53e1c79157f840edf1443.json +++ /dev/null @@ -1,107 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO menu_dish (id, menu, name, description, price_minor, tags, created_at)\n SELECT $1, $2, $3, $4, $5, $6, $7\n WHERE (SELECT count(*) FROM menu_dish WHERE menu = $2) < $8\n RETURNING id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", tags AS \"tags: DishTags\", created_at AS \"created_at: Timestamp\"", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "id: MenuDishId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "menu_dish", - "name": "id" - } - } - }, - { - "ordinal": 1, - "name": "menu: MenuId", - "type_info": "Text", - "origin": { - "Table": { - "table": "menu_dish", - "name": "menu" - } - } - }, - { - "ordinal": 2, - "name": "name: DishName", - "type_info": "Text", - "origin": { - "Table": { - "table": "menu_dish", - "name": "name" - } - } - }, - { - "ordinal": 3, - "name": "description: DishDescription", - "type_info": "Text", - "origin": { - "Table": { - "table": "menu_dish", - "name": "description" - } - } - }, - { - "ordinal": 4, - "name": "price_minor: DishPrice", - "type_info": "Int8", - "origin": { - "Table": { - "table": "menu_dish", - "name": "price_minor" - } - } - }, - { - "ordinal": 5, - "name": "tags: DishTags", - "type_info": "TextArray", - "origin": { - "Table": { - "table": "menu_dish", - "name": "tags" - } - } - }, - { - "ordinal": 6, - "name": "created_at: Timestamp", - "type_info": "Int8", - "origin": { - "Table": { - "table": "menu_dish", - "name": "created_at" - } - } - } - ], - "parameters": { - "Left": [ - "Uuid", - "Text", - "Text", - "Text", - "Int8", - "TextArray", - "Int8", - "Int8" - ] - }, - "nullable": [ - false, - false, - false, - true, - false, - false, - false - ] - }, - "hash": "8e687f07237ef09a151a945cd4046978aa69cbda3bd53e1c79157f840edf1443" -} diff --git a/.sqlx/query-409b3b702b6cd4ad4dcd34f5330d20b16f3093821553a6af4f55a53cc4c69fb7.json b/.sqlx/query-90ca4d8c108622034298f4da1ac3a4db6a284b2f95e0fe8a69bbec9117f5d0a0.json similarity index 87% rename from .sqlx/query-409b3b702b6cd4ad4dcd34f5330d20b16f3093821553a6af4f55a53cc4c69fb7.json rename to .sqlx/query-90ca4d8c108622034298f4da1ac3a4db6a284b2f95e0fe8a69bbec9117f5d0a0.json index 71daafb..3349b7b 100644 --- a/.sqlx/query-409b3b702b6cd4ad4dcd34f5330d20b16f3093821553a6af4f55a53cc4c69fb7.json +++ b/.sqlx/query-90ca4d8c108622034298f4da1ac3a4db6a284b2f95e0fe8a69bbec9117f5d0a0.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT s.slug AS \"slug: Slug\",\n s.name,\n s.status AS \"status: SchoolStatus\"\n FROM person_school ps\n JOIN school s ON s.slug = ps.school\n WHERE ps.person = $1\n ORDER BY s.slug", + "query": "SELECT s.slug AS \"slug: Slug\",\n s.name,\n s.status AS \"status: SchoolStatus\"\n FROM person_school ps\n JOIN school s ON s.id = ps.school\n WHERE ps.person = $1\n ORDER BY s.slug", "describe": { "columns": [ { @@ -48,5 +48,5 @@ false ] }, - "hash": "409b3b702b6cd4ad4dcd34f5330d20b16f3093821553a6af4f55a53cc4c69fb7" + "hash": "90ca4d8c108622034298f4da1ac3a4db6a284b2f95e0fe8a69bbec9117f5d0a0" } diff --git a/.sqlx/query-915d3bcbbe66341824b280bde6cb5eb01f3868fd3d98bd29a9efc85a80176e95.json b/.sqlx/query-915d3bcbbe66341824b280bde6cb5eb01f3868fd3d98bd29a9efc85a80176e95.json new file mode 100644 index 0000000..721ab5c --- /dev/null +++ b/.sqlx/query-915d3bcbbe66341824b280bde6cb5eb01f3868fd3d98bd29a9efc85a80176e95.json @@ -0,0 +1,18 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE menu_dish SET\n name = COALESCE($2, name),\n description = CASE WHEN $3 THEN $4 ELSE description END,\n price_minor = COALESCE($5, price_minor)\n WHERE id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Text", + "Bool", + "Text", + "Int8" + ] + }, + "nullable": [] + }, + "hash": "915d3bcbbe66341824b280bde6cb5eb01f3868fd3d98bd29a9efc85a80176e95" +} diff --git a/.sqlx/query-935e0ed64846d8c1ad7e317725d31da05a618a6ab0e628482399affad99261c8.json b/.sqlx/query-935e0ed64846d8c1ad7e317725d31da05a618a6ab0e628482399affad99261c8.json new file mode 100644 index 0000000..51c973c --- /dev/null +++ b/.sqlx/query-935e0ed64846d8c1ad7e317725d31da05a618a6ab0e628482399affad99261c8.json @@ -0,0 +1,137 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH new_row AS (\n INSERT INTO settings (id, exam_kinds, grade_bands, max_file_bytes,\n chatbot_history_turns, max_chatbot_message_len,\n max_chatbot_threads, meal_slots,\n meal_cancel_cutoff_minutes)\n VALUES ('school', $1, $3, $4, $5, $6, $7, $8, $10)\n ON CONFLICT (id) DO UPDATE SET\n exam_kinds = $1,\n grade_bands = $3,\n max_file_bytes = $4,\n chatbot_history_turns = $5,\n max_chatbot_message_len = $6,\n max_chatbot_threads = $7,\n meal_slots = $8,\n meal_cancel_cutoff_minutes = $10\n WHERE settings.exam_kinds IS NOT DISTINCT FROM $1\n AND settings.grade_bands IS NOT DISTINCT FROM $3\n AND settings.max_file_bytes IS NOT DISTINCT FROM $4\n AND settings.chatbot_history_turns IS NOT DISTINCT FROM $5\n AND settings.max_chatbot_message_len IS NOT DISTINCT FROM $6\n AND settings.max_chatbot_threads IS NOT DISTINCT FROM $7\n AND settings.meal_slots IS NOT DISTINCT FROM $8\n AND settings.meal_cancel_cutoff_minutes IS NOT DISTINCT FROM $10\n AND COALESCE((SELECT array_agg(s.status ORDER BY s.status)\n FROM settings_attendance_status s\n WHERE s.settings = settings.id), '{}')\n IS NOT DISTINCT FROM $11::text[]\n AND (SELECT array_agg(t.tag ORDER BY t.tag)\n FROM settings_dietary_tag t\n WHERE t.settings = settings.id)\n IS NOT DISTINCT FROM $12::text[]\n RETURNING exam_kinds, grade_bands, max_file_bytes,\n chatbot_history_turns, max_chatbot_message_len,\n max_chatbot_threads, meal_slots, meal_cancel_cutoff_minutes),\n status_del AS (\n DELETE FROM settings_attendance_status\n WHERE settings = 'school' AND EXISTS (SELECT 1 FROM new_row)\n RETURNING 1),\n status_ins AS (\n INSERT INTO settings_attendance_status (settings, status)\n SELECT 'school', t.status FROM unnest($2::text[]) AS t(status)\n CROSS JOIN (SELECT count(*) AS deleted FROM status_del) d\n WHERE EXISTS (SELECT 1 FROM new_row)\n RETURNING status),\n tag_del AS (\n DELETE FROM settings_dietary_tag\n WHERE settings = 'school' AND EXISTS (SELECT 1 FROM new_row)\n RETURNING 1),\n tag_ins AS (\n INSERT INTO settings_dietary_tag (settings, tag)\n SELECT 'school', t.tag FROM unnest($9::text[]) AS t(tag)\n CROSS JOIN (SELECT count(*) AS deleted FROM tag_del) d\n WHERE EXISTS (SELECT 1 FROM new_row)\n RETURNING tag)\n SELECT r.exam_kinds AS \"exam_kinds: Json>\",\n COALESCE((SELECT array_agg(status ORDER BY status)\n FROM status_ins), '{}') AS \"attendance_statuses!: Vec\",\n r.grade_bands AS \"grade_bands: Json>\",\n r.max_file_bytes,\n r.chatbot_history_turns,\n r.max_chatbot_message_len,\n r.max_chatbot_threads,\n r.meal_slots AS \"meal_slots: Json>\",\n (SELECT array_agg(tag ORDER BY tag) FROM tag_ins) AS dietary_tags,\n r.meal_cancel_cutoff_minutes\n FROM new_row r", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "exam_kinds: Json>", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "settings", + "name": "exam_kinds" + } + } + }, + { + "ordinal": 1, + "name": "attendance_statuses!: Vec", + "type_info": "TextArray", + "origin": "Expression" + }, + { + "ordinal": 2, + "name": "grade_bands: Json>", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "settings", + "name": "grade_bands" + } + } + }, + { + "ordinal": 3, + "name": "max_file_bytes", + "type_info": "Int8", + "origin": { + "Table": { + "table": "settings", + "name": "max_file_bytes" + } + } + }, + { + "ordinal": 4, + "name": "chatbot_history_turns", + "type_info": "Int8", + "origin": { + "Table": { + "table": "settings", + "name": "chatbot_history_turns" + } + } + }, + { + "ordinal": 5, + "name": "max_chatbot_message_len", + "type_info": "Int8", + "origin": { + "Table": { + "table": "settings", + "name": "max_chatbot_message_len" + } + } + }, + { + "ordinal": 6, + "name": "max_chatbot_threads", + "type_info": "Int8", + "origin": { + "Table": { + "table": "settings", + "name": "max_chatbot_threads" + } + } + }, + { + "ordinal": 7, + "name": "meal_slots: Json>", + "type_info": "Jsonb", + "origin": { + "Table": { + "table": "settings", + "name": "meal_slots" + } + } + }, + { + "ordinal": 8, + "name": "dietary_tags", + "type_info": "TextArray", + "origin": "Expression" + }, + { + "ordinal": 9, + "name": "meal_cancel_cutoff_minutes", + "type_info": "Int8", + "origin": { + "Table": { + "table": "settings", + "name": "meal_cancel_cutoff_minutes" + } + } + } + ], + "parameters": { + "Left": [ + "Jsonb", + "TextArray", + "Jsonb", + "Int8", + "Int8", + "Int8", + "Int8", + "Jsonb", + "TextArray", + "Int8", + "TextArray", + "TextArray" + ] + }, + "nullable": [ + false, + null, + false, + true, + true, + true, + true, + true, + null, + true + ] + }, + "hash": "935e0ed64846d8c1ad7e317725d31da05a618a6ab0e628482399affad99261c8" +} diff --git a/.sqlx/query-93c7d6a0aa9805cda59508aa0baf349fb341315f8899c7c61cd669916f292609.json b/.sqlx/query-93c7d6a0aa9805cda59508aa0baf349fb341315f8899c7c61cd669916f292609.json deleted file mode 100644 index 51c981e..0000000 --- a/.sqlx/query-93c7d6a0aa9805cda59508aa0baf349fb341315f8899c7c61cd669916f292609.json +++ /dev/null @@ -1,105 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE menu_dish SET\n name = COALESCE($2, name),\n description = CASE WHEN $3 THEN $4 ELSE description END,\n price_minor = COALESCE($5, price_minor),\n tags = COALESCE($6, tags)\n WHERE id = $1\n RETURNING id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", tags AS \"tags: DishTags\", created_at AS \"created_at: Timestamp\"", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "id: MenuDishId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "menu_dish", - "name": "id" - } - } - }, - { - "ordinal": 1, - "name": "menu: MenuId", - "type_info": "Text", - "origin": { - "Table": { - "table": "menu_dish", - "name": "menu" - } - } - }, - { - "ordinal": 2, - "name": "name: DishName", - "type_info": "Text", - "origin": { - "Table": { - "table": "menu_dish", - "name": "name" - } - } - }, - { - "ordinal": 3, - "name": "description: DishDescription", - "type_info": "Text", - "origin": { - "Table": { - "table": "menu_dish", - "name": "description" - } - } - }, - { - "ordinal": 4, - "name": "price_minor: DishPrice", - "type_info": "Int8", - "origin": { - "Table": { - "table": "menu_dish", - "name": "price_minor" - } - } - }, - { - "ordinal": 5, - "name": "tags: DishTags", - "type_info": "TextArray", - "origin": { - "Table": { - "table": "menu_dish", - "name": "tags" - } - } - }, - { - "ordinal": 6, - "name": "created_at: Timestamp", - "type_info": "Int8", - "origin": { - "Table": { - "table": "menu_dish", - "name": "created_at" - } - } - } - ], - "parameters": { - "Left": [ - "Uuid", - "Text", - "Bool", - "Text", - "Int8", - "TextArray" - ] - }, - "nullable": [ - false, - false, - false, - true, - false, - false, - false - ] - }, - "hash": "93c7d6a0aa9805cda59508aa0baf349fb341315f8899c7c61cd669916f292609" -} diff --git a/.sqlx/query-94bc804bff53b231870f54a09eaaf732f6ab3b158fad47d4daab3c52426e9564.json b/.sqlx/query-94bc804bff53b231870f54a09eaaf732f6ab3b158fad47d4daab3c52426e9564.json deleted file mode 100644 index 3be00c1..0000000 --- a/.sqlx/query-94bc804bff53b231870f54a09eaaf732f6ab3b158fad47d4daab3c52426e9564.json +++ /dev/null @@ -1,120 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "WITH seat AS (\n UPDATE term\n SET course_count = course_count + 1\n WHERE id = $8 AND course_count < $9\n RETURNING 1)\n INSERT INTO course (id, creator, teachers, title, description, kind, term, capacity)\n SELECT $1, $2, $3, $4, $5, $6, $8, $7 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING id AS \"id: CourseId\", creator AS \"creator: UserId\",\n teachers AS \"teachers: Vec\", title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "id: CourseId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "course", - "name": "id" - } - } - }, - { - "ordinal": 1, - "name": "creator: UserId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "course", - "name": "creator" - } - } - }, - { - "ordinal": 2, - "name": "teachers: Vec", - "type_info": "UuidArray", - "origin": { - "Table": { - "table": "course", - "name": "teachers" - } - } - }, - { - "ordinal": 3, - "name": "title: CourseTitle", - "type_info": "Text", - "origin": { - "Table": { - "table": "course", - "name": "title" - } - } - }, - { - "ordinal": 4, - "name": "description: CourseDescription", - "type_info": "Text", - "origin": { - "Table": { - "table": "course", - "name": "description" - } - } - }, - { - "ordinal": 5, - "name": "kind: CourseKind", - "type_info": "Text", - "origin": { - "Table": { - "table": "course", - "name": "kind" - } - } - }, - { - "ordinal": 6, - "name": "term: TermId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "course", - "name": "term" - } - } - }, - { - "ordinal": 7, - "name": "capacity", - "type_info": "Int8", - "origin": { - "Table": { - "table": "course", - "name": "capacity" - } - } - } - ], - "parameters": { - "Left": [ - "Uuid", - "Uuid", - "UuidArray", - "Text", - "Text", - "Text", - "Int8", - "Uuid", - "Int8" - ] - }, - "nullable": [ - false, - false, - false, - false, - false, - false, - true, - true - ] - }, - "hash": "94bc804bff53b231870f54a09eaaf732f6ab3b158fad47d4daab3c52426e9564" -} diff --git a/.sqlx/query-9d2466aa569f86333f3eb28871eabc72dc0058951a26855a52cc688e21e21685.json b/.sqlx/query-9d2466aa569f86333f3eb28871eabc72dc0058951a26855a52cc688e21e21685.json new file mode 100644 index 0000000..56773d4 --- /dev/null +++ b/.sqlx/query-9d2466aa569f86333f3eb28871eabc72dc0058951a26855a52cc688e21e21685.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO menu_dish_tag (dish, tag, ord)\n SELECT $1, tag, ord FROM unnest($2::text[]) WITH ORDINALITY AS t(tag, ord)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "TextArray" + ] + }, + "nullable": [] + }, + "hash": "9d2466aa569f86333f3eb28871eabc72dc0058951a26855a52cc688e21e21685" +} diff --git a/.sqlx/query-ea0e9333278dc82972ebfc2aa5efee079814899bebf6c2a495a47e6fdc0b5834.json b/.sqlx/query-9d9cce760c2a87090f4b3cf5da4afc868d6fb3c91a7ba9ae5b553dfb48be9353.json similarity index 87% rename from .sqlx/query-ea0e9333278dc82972ebfc2aa5efee079814899bebf6c2a495a47e6fdc0b5834.json rename to .sqlx/query-9d9cce760c2a87090f4b3cf5da4afc868d6fb3c91a7ba9ae5b553dfb48be9353.json index 1e65b6e..4791939 100644 --- a/.sqlx/query-ea0e9333278dc82972ebfc2aa5efee079814899bebf6c2a495a47e6fdc0b5834.json +++ b/.sqlx/query-9d9cce760c2a87090f4b3cf5da4afc868d6fb3c91a7ba9ae5b553dfb48be9353.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT s.slug AS \"slug: Slug\",\n s.name,\n s.status AS \"status: SchoolStatus\"\n FROM person_school ps\n JOIN school s ON s.slug = ps.school\n WHERE ps.person = $1 AND ps.school = $2", + "query": "SELECT s.slug AS \"slug: Slug\",\n s.name,\n s.status AS \"status: SchoolStatus\"\n FROM person_school ps\n JOIN school s ON s.id = ps.school\n WHERE ps.person = $1 AND s.slug = $2", "describe": { "columns": [ { @@ -49,5 +49,5 @@ false ] }, - "hash": "ea0e9333278dc82972ebfc2aa5efee079814899bebf6c2a495a47e6fdc0b5834" + "hash": "9d9cce760c2a87090f4b3cf5da4afc868d6fb3c91a7ba9ae5b553dfb48be9353" } diff --git a/.sqlx/query-9e64583ead1738639a6fdc7e6158cc313f9c8ddd2afd3a9728462819f5db30dd.json b/.sqlx/query-9e64583ead1738639a6fdc7e6158cc313f9c8ddd2afd3a9728462819f5db30dd.json new file mode 100644 index 0000000..bb800fb --- /dev/null +++ b/.sqlx/query-9e64583ead1738639a6fdc7e6158cc313f9c8ddd2afd3a9728462819f5db30dd.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM menu_dish WHERE id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "9e64583ead1738639a6fdc7e6158cc313f9c8ddd2afd3a9728462819f5db30dd" +} diff --git a/.sqlx/query-9e70ed1446d7ca45b78aa8dfb9842a877dfac056dea7b17e702bdea174b0993a.json b/.sqlx/query-9e70ed1446d7ca45b78aa8dfb9842a877dfac056dea7b17e702bdea174b0993a.json new file mode 100644 index 0000000..967830d --- /dev/null +++ b/.sqlx/query-9e70ed1446d7ca45b78aa8dfb9842a877dfac056dea7b17e702bdea174b0993a.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO course_teacher (course, teacher)\n SELECT $1, $2 WHERE EXISTS (SELECT 1 FROM course WHERE id = $1)\n ON CONFLICT DO NOTHING", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "9e70ed1446d7ca45b78aa8dfb9842a877dfac056dea7b17e702bdea174b0993a" +} diff --git a/.sqlx/query-a48289705d949851428efdaa1cdd18a7b8397112582a9d8a0c386491e1c2bfad.json b/.sqlx/query-a48289705d949851428efdaa1cdd18a7b8397112582a9d8a0c386491e1c2bfad.json new file mode 100644 index 0000000..d06bd79 --- /dev/null +++ b/.sqlx/query-a48289705d949851428efdaa1cdd18a7b8397112582a9d8a0c386491e1c2bfad.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM blueprint_course\n WHERE course = $2\n AND blueprint = (SELECT id FROM class_blueprint WHERE grade = $1)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "a48289705d949851428efdaa1cdd18a7b8397112582a9d8a0c386491e1c2bfad" +} diff --git a/.sqlx/query-a659d3ffcdac1279b32d1d0673a6b36c168cb3c9ddbf00ebb402e8598b995f13.json b/.sqlx/query-a659d3ffcdac1279b32d1d0673a6b36c168cb3c9ddbf00ebb402e8598b995f13.json new file mode 100644 index 0000000..22e9adb --- /dev/null +++ b/.sqlx/query-a659d3ffcdac1279b32d1d0673a6b36c168cb3c9ddbf00ebb402e8598b995f13.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO settings_dietary_tag (settings, tag)\n SELECT 'school', t.tag FROM unnest($1::text[]) AS t(tag)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "TextArray" + ] + }, + "nullable": [] + }, + "hash": "a659d3ffcdac1279b32d1d0673a6b36c168cb3c9ddbf00ebb402e8598b995f13" +} diff --git a/.sqlx/query-a6baebb365f43380e7bf289cc9a660d9b628c5529195edfbe634c2c21818a345.json b/.sqlx/query-a6baebb365f43380e7bf289cc9a660d9b628c5529195edfbe634c2c21818a345.json new file mode 100644 index 0000000..81aabd4 --- /dev/null +++ b/.sqlx/query-a6baebb365f43380e7bf289cc9a660d9b628c5529195edfbe634c2c21818a345.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT course AS \"course: CourseId\" FROM blueprint_course\n WHERE blueprint = $1 ORDER BY course", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "course: CourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "blueprint_course", + "name": "course" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "a6baebb365f43380e7bf289cc9a660d9b628c5529195edfbe634c2c21818a345" +} diff --git a/.sqlx/query-a8f1d82b2d0a543ea09ea62f8bb88a7365573ea7f566f9ff3f625e6a034d181c.json b/.sqlx/query-a8f1d82b2d0a543ea09ea62f8bb88a7365573ea7f566f9ff3f625e6a034d181c.json new file mode 100644 index 0000000..f97016e --- /dev/null +++ b/.sqlx/query-a8f1d82b2d0a543ea09ea62f8bb88a7365573ea7f566f9ff3f625e6a034d181c.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM menu_dish_tag WHERE dish IN (SELECT id FROM menu_dish WHERE menu = $1)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [] + }, + "hash": "a8f1d82b2d0a543ea09ea62f8bb88a7365573ea7f566f9ff3f625e6a034d181c" +} diff --git a/.sqlx/query-aee5be56a586cd5424cbc0532b4337dfa6d93ddd6e5909c4fd6950e2e468ad6e.json b/.sqlx/query-aee5be56a586cd5424cbc0532b4337dfa6d93ddd6e5909c4fd6950e2e468ad6e.json deleted file mode 100644 index 3a4bda2..0000000 --- a/.sqlx/query-aee5be56a586cd5424cbc0532b4337dfa6d93ddd6e5909c4fd6950e2e468ad6e.json +++ /dev/null @@ -1,138 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE board\n SET participants = (SELECT coalesce(array_agg(DISTINCT x), '{}')\n FROM unnest(participants || $2::uuid[]) AS x)\n WHERE id = $1\n AND cardinality((SELECT coalesce(array_agg(DISTINCT x), '{}')\n FROM unnest(participants || $2::uuid[]) AS x)) <= $3\n RETURNING id AS \"id: BoardId\", creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n participants AS \"participants: Vec\", locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\", epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "id: BoardId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "board", - "name": "id" - } - } - }, - { - "ordinal": 1, - "name": "creator: UserId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "board", - "name": "creator" - } - } - }, - { - "ordinal": 2, - "name": "title: BoardTitle", - "type_info": "Text", - "origin": { - "Table": { - "table": "board", - "name": "title" - } - } - }, - { - "ordinal": 3, - "name": "participants: Vec", - "type_info": "UuidArray", - "origin": { - "Table": { - "table": "board", - "name": "participants" - } - } - }, - { - "ordinal": 4, - "name": "locked", - "type_info": "Bool", - "origin": { - "Table": { - "table": "board", - "name": "locked" - } - } - }, - { - "ordinal": 5, - "name": "locked_by: UserId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "board", - "name": "locked_by" - } - } - }, - { - "ordinal": 6, - "name": "locked_at: Timestamp", - "type_info": "Int8", - "origin": { - "Table": { - "table": "board", - "name": "locked_at" - } - } - }, - { - "ordinal": 7, - "name": "epoch", - "type_info": "Int8", - "origin": { - "Table": { - "table": "board", - "name": "epoch" - } - } - }, - { - "ordinal": 8, - "name": "closed_at: Timestamp", - "type_info": "Int8", - "origin": { - "Table": { - "table": "board", - "name": "closed_at" - } - } - }, - { - "ordinal": 9, - "name": "created_at: Timestamp", - "type_info": "Int8", - "origin": { - "Table": { - "table": "board", - "name": "created_at" - } - } - } - ], - "parameters": { - "Left": [ - "Uuid", - "UuidArray", - "Int4" - ] - }, - "nullable": [ - false, - false, - false, - false, - false, - true, - true, - false, - true, - false - ] - }, - "hash": "aee5be56a586cd5424cbc0532b4337dfa6d93ddd6e5909c4fd6950e2e468ad6e" -} diff --git a/.sqlx/query-123a9c9b6be7c9bed57fb3c22ac699108abd335fa898d098652bc0f16541cab4.json b/.sqlx/query-b0b72a673261825bb0103bef5882c803494d402b4611dbfb646d8973af96896a.json similarity index 73% rename from .sqlx/query-123a9c9b6be7c9bed57fb3c22ac699108abd335fa898d098652bc0f16541cab4.json rename to .sqlx/query-b0b72a673261825bb0103bef5882c803494d402b4611dbfb646d8973af96896a.json index 2464940..62ea889 100644 --- a/.sqlx/query-123a9c9b6be7c9bed57fb3c22ac699108abd335fa898d098652bc0f16541cab4.json +++ b/.sqlx/query-b0b72a673261825bb0103bef5882c803494d402b4611dbfb646d8973af96896a.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "DELETE FROM menu_dish WHERE id = $1\n RETURNING id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", tags AS \"tags: DishTags\", created_at AS \"created_at: Timestamp\"", + "query": "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\",\n COALESCE((SELECT array_agg(t.tag ORDER BY t.ord) FROM menu_dish_tag t WHERE t.dish = menu_dish.id), '{}'::text[]) AS \"tags!: DishTags\",\n created_at AS \"created_at: Timestamp\"\n FROM menu_dish WHERE id = $1", "describe": { "columns": [ { @@ -60,14 +60,9 @@ }, { "ordinal": 5, - "name": "tags: DishTags", + "name": "tags!: DishTags", "type_info": "TextArray", - "origin": { - "Table": { - "table": "menu_dish", - "name": "tags" - } - } + "origin": "Expression" }, { "ordinal": 6, @@ -92,9 +87,9 @@ false, true, false, - false, + null, false ] }, - "hash": "123a9c9b6be7c9bed57fb3c22ac699108abd335fa898d098652bc0f16541cab4" + "hash": "b0b72a673261825bb0103bef5882c803494d402b4611dbfb646d8973af96896a" } diff --git a/.sqlx/query-74d97285fdc1081f2efdca29cbfc9a4832c0ae927e24be87f216855fe631e40c.json b/.sqlx/query-b63d7258825b3b578664bd4e8f1347c918f564d0022954a7efc0e98dc8d03df4.json similarity index 75% rename from .sqlx/query-74d97285fdc1081f2efdca29cbfc9a4832c0ae927e24be87f216855fe631e40c.json rename to .sqlx/query-b63d7258825b3b578664bd4e8f1347c918f564d0022954a7efc0e98dc8d03df4.json index 967487d..211ea78 100644 --- a/.sqlx/query-74d97285fdc1081f2efdca29cbfc9a4832c0ae927e24be87f216855fe631e40c.json +++ b/.sqlx/query-b63d7258825b3b578664bd4e8f1347c918f564d0022954a7efc0e98dc8d03df4.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: BoardId\", creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n participants AS \"participants: Vec\", locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\", epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"\n FROM board WHERE id = $1", + "query": "SELECT b.id AS \"id: BoardId\", b.creator AS \"creator: UserId\",\n b.title AS \"title: BoardTitle\",\n ARRAY(SELECT p.participant FROM board_participant p\n WHERE p.board = b.id ORDER BY p.participant)\n AS \"participants!: Vec\",\n b.locked, b.locked_by AS \"locked_by: UserId\",\n b.locked_at AS \"locked_at: Timestamp\", b.epoch,\n b.closed_at AS \"closed_at: Timestamp\",\n b.created_at AS \"created_at: Timestamp\"\n FROM board b WHERE b.id = $1", "describe": { "columns": [ { @@ -38,14 +38,9 @@ }, { "ordinal": 3, - "name": "participants: Vec", + "name": "participants!: Vec", "type_info": "UuidArray", - "origin": { - "Table": { - "table": "board", - "name": "participants" - } - } + "origin": "Expression" }, { "ordinal": 4, @@ -123,7 +118,7 @@ false, false, false, - false, + null, false, true, true, @@ -132,5 +127,5 @@ false ] }, - "hash": "74d97285fdc1081f2efdca29cbfc9a4832c0ae927e24be87f216855fe631e40c" + "hash": "b63d7258825b3b578664bd4e8f1347c918f564d0022954a7efc0e98dc8d03df4" } diff --git a/.sqlx/query-b8cd6149b5f42e615c31018d2fdf306f157f5275587ae57d1e5146c9a76a51d3.json b/.sqlx/query-b8cd6149b5f42e615c31018d2fdf306f157f5275587ae57d1e5146c9a76a51d3.json deleted file mode 100644 index 20cbda6..0000000 --- a/.sqlx/query-b8cd6149b5f42e615c31018d2fdf306f157f5275587ae57d1e5146c9a76a51d3.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "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-bd7a06a5112f3a1489d0f3800e42bee96cd9acec380c29c4006c9d68f5becd57.json b/.sqlx/query-bd7a06a5112f3a1489d0f3800e42bee96cd9acec380c29c4006c9d68f5becd57.json new file mode 100644 index 0000000..eb93887 --- /dev/null +++ b/.sqlx/query-bd7a06a5112f3a1489d0f3800e42bee96cd9acec380c29c4006c9d68f5becd57.json @@ -0,0 +1,40 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT blueprint, course AS \"course: CourseId\" FROM blueprint_course\n WHERE blueprint = ANY($1) ORDER BY blueprint, course", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "blueprint", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "blueprint_course", + "name": "blueprint" + } + } + }, + { + "ordinal": 1, + "name": "course: CourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "blueprint_course", + "name": "course" + } + } + } + ], + "parameters": { + "Left": [ + "UuidArray" + ] + }, + "nullable": [ + false, + false + ] + }, + "hash": "bd7a06a5112f3a1489d0f3800e42bee96cd9acec380c29c4006c9d68f5becd57" +} diff --git a/.sqlx/query-bdfda68f7d0dedef148b54d5911a7798ced19472830ac9421f024eb43c784318.json b/.sqlx/query-bdfda68f7d0dedef148b54d5911a7798ced19472830ac9421f024eb43c784318.json new file mode 100644 index 0000000..267949c --- /dev/null +++ b/.sqlx/query-bdfda68f7d0dedef148b54d5911a7798ced19472830ac9421f024eb43c784318.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO dietary_profile_tag (student, tag, ord)\n SELECT $1, tag, ord FROM unnest($2::text[]) WITH ORDINALITY AS t(tag, ord)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "TextArray" + ] + }, + "nullable": [] + }, + "hash": "bdfda68f7d0dedef148b54d5911a7798ced19472830ac9421f024eb43c784318" +} diff --git a/.sqlx/query-be12adc83910edf8922a2b22308e76093cdd89e6173043354ee6ee66e7c2a518.json b/.sqlx/query-be12adc83910edf8922a2b22308e76093cdd89e6173043354ee6ee66e7c2a518.json deleted file mode 100644 index 2ec16ff..0000000 --- a/.sqlx/query-be12adc83910edf8922a2b22308e76093cdd89e6173043354ee6ee66e7c2a518.json +++ /dev/null @@ -1,113 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE course\n SET teachers = (SELECT array_agg(DISTINCT x)\n FROM unnest(course.teachers || $2::uuid) AS x)\n WHERE id = $1\n RETURNING id AS \"id: CourseId\", creator AS \"creator: UserId\",\n teachers AS \"teachers: Vec\", title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "id: CourseId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "course", - "name": "id" - } - } - }, - { - "ordinal": 1, - "name": "creator: UserId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "course", - "name": "creator" - } - } - }, - { - "ordinal": 2, - "name": "teachers: Vec", - "type_info": "UuidArray", - "origin": { - "Table": { - "table": "course", - "name": "teachers" - } - } - }, - { - "ordinal": 3, - "name": "title: CourseTitle", - "type_info": "Text", - "origin": { - "Table": { - "table": "course", - "name": "title" - } - } - }, - { - "ordinal": 4, - "name": "description: CourseDescription", - "type_info": "Text", - "origin": { - "Table": { - "table": "course", - "name": "description" - } - } - }, - { - "ordinal": 5, - "name": "kind: CourseKind", - "type_info": "Text", - "origin": { - "Table": { - "table": "course", - "name": "kind" - } - } - }, - { - "ordinal": 6, - "name": "term: TermId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "course", - "name": "term" - } - } - }, - { - "ordinal": 7, - "name": "capacity", - "type_info": "Int8", - "origin": { - "Table": { - "table": "course", - "name": "capacity" - } - } - } - ], - "parameters": { - "Left": [ - "Uuid", - "Uuid" - ] - }, - "nullable": [ - false, - false, - false, - false, - false, - false, - true, - true - ] - }, - "hash": "be12adc83910edf8922a2b22308e76093cdd89e6173043354ee6ee66e7c2a518" -} diff --git a/.sqlx/query-5faf6a7b5f0ae1ff707c72f2a8985e65d83dcd7a4cad37c752908c361a460d86.json b/.sqlx/query-c1bac901f8e1b2a8ee9aa2aa15e4ec7eab955fb80167fec8768a381cd012f4b5.json similarity index 55% rename from .sqlx/query-5faf6a7b5f0ae1ff707c72f2a8985e65d83dcd7a4cad37c752908c361a460d86.json rename to .sqlx/query-c1bac901f8e1b2a8ee9aa2aa15e4ec7eab955fb80167fec8768a381cd012f4b5.json index 62a807f..334fdf5 100644 --- a/.sqlx/query-5faf6a7b5f0ae1ff707c72f2a8985e65d83dcd7a4cad37c752908c361a460d86.json +++ b/.sqlx/query-c1bac901f8e1b2a8ee9aa2aa15e4ec7eab955fb80167fec8768a381cd012f4b5.json @@ -1,10 +1,21 @@ { "db_name": "PostgreSQL", - "query": "UPDATE class_blueprint SET courses = $2\n WHERE grade = $1 AND courses = $3\n RETURNING grade AS \"grade: ClassGrade\", creator AS \"creator: UserId\"", + "query": "SELECT id AS \"key: uuid::Uuid\", grade AS \"grade: ClassGrade\",\n creator AS \"creator: UserId\"\n FROM class_blueprint WHERE grade = $1", "describe": { "columns": [ { "ordinal": 0, + "name": "key: uuid::Uuid", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "class_blueprint", + "name": "id" + } + } + }, + { + "ordinal": 1, "name": "grade: ClassGrade", "type_info": "Text", "origin": { @@ -15,7 +26,7 @@ } }, { - "ordinal": 1, + "ordinal": 2, "name": "creator: UserId", "type_info": "Uuid", "origin": { @@ -28,15 +39,14 @@ ], "parameters": { "Left": [ - "Text", - "UuidArray", - "UuidArray" + "Text" ] }, "nullable": [ + false, false, false ] }, - "hash": "5faf6a7b5f0ae1ff707c72f2a8985e65d83dcd7a4cad37c752908c361a460d86" + "hash": "c1bac901f8e1b2a8ee9aa2aa15e4ec7eab955fb80167fec8768a381cd012f4b5" } diff --git a/.sqlx/query-866efd5fe0b7f2b4524f747d9ef26100e13c48d4cb35d390d29c327180681c60.json b/.sqlx/query-c3232a6de8535065f4fc7e1a19494dd17acb47f65cca634b739f9ff6cd0a6894.json similarity index 52% rename from .sqlx/query-866efd5fe0b7f2b4524f747d9ef26100e13c48d4cb35d390d29c327180681c60.json rename to .sqlx/query-c3232a6de8535065f4fc7e1a19494dd17acb47f65cca634b739f9ff6cd0a6894.json index b7e487c..6537407 100644 --- a/.sqlx/query-866efd5fe0b7f2b4524f747d9ef26100e13c48d4cb35d390d29c327180681c60.json +++ b/.sqlx/query-c3232a6de8535065f4fc7e1a19494dd17acb47f65cca634b739f9ff6cd0a6894.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT due_at AS \"due_at: Timestamp\" FROM homework\n WHERE id = $1 AND (cardinality(assigned) = 0 OR $2 = ANY(assigned))\n FOR UPDATE", + "query": "SELECT due_at AS \"due_at: Timestamp\" FROM homework\n WHERE id = $1\n AND (NOT EXISTS (SELECT 1 FROM homework_assignment a\n WHERE a.homework = homework.id)\n OR EXISTS (SELECT 1 FROM homework_assignment a\n WHERE a.homework = homework.id AND a.student = $2))\n FOR UPDATE", "describe": { "columns": [ { @@ -25,5 +25,5 @@ false ] }, - "hash": "866efd5fe0b7f2b4524f747d9ef26100e13c48d4cb35d390d29c327180681c60" + "hash": "c3232a6de8535065f4fc7e1a19494dd17acb47f65cca634b739f9ff6cd0a6894" } diff --git a/.sqlx/query-b364954dae05a5a23861686a2f9b9ce478f5ee272d09c11e288d335d05f43fd8.json b/.sqlx/query-c41fb6b0ecd0a378198552f4c36085f8c0d229a7a83b23fb3ba02c1e6b675fe6.json similarity index 56% rename from .sqlx/query-b364954dae05a5a23861686a2f9b9ce478f5ee272d09c11e288d335d05f43fd8.json rename to .sqlx/query-c41fb6b0ecd0a378198552f4c36085f8c0d229a7a83b23fb3ba02c1e6b675fe6.json index 15f886d..b96aab1 100644 --- a/.sqlx/query-b364954dae05a5a23861686a2f9b9ce478f5ee272d09c11e288d335d05f43fd8.json +++ b/.sqlx/query-c41fb6b0ecd0a378198552f4c36085f8c0d229a7a83b23fb3ba02c1e6b675fe6.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO dietary_profile (student, tags, note, updated_by, updated_at)\n VALUES ($1, COALESCE($2, '{}'::text[]), $3, $4, $5)\n ON CONFLICT (student) DO UPDATE SET\n tags = COALESCE($2, dietary_profile.tags),\n note = CASE WHEN $6 THEN $3 ELSE dietary_profile.note END,\n updated_by = $4,\n updated_at = $5\n RETURNING student AS \"student: UserId\", tags AS \"tags: DietaryTags\", note AS \"note: DietaryNote\", updated_by AS \"updated_by: UserId\", updated_at AS \"updated_at: Timestamp\"", + "query": "SELECT student AS \"student: UserId\",\n COALESCE((SELECT array_agg(t.tag ORDER BY t.ord) FROM dietary_profile_tag t WHERE t.student = dietary_profile.student), '{}'::text[]) AS \"tags!: DietaryTags\",\n note AS \"note: DietaryNote\", updated_by AS \"updated_by: UserId\", updated_at AS \"updated_at: Timestamp\"\n FROM dietary_profile WHERE student = $1", "describe": { "columns": [ { @@ -16,14 +16,9 @@ }, { "ordinal": 1, - "name": "tags: DietaryTags", + "name": "tags!: DietaryTags", "type_info": "TextArray", - "origin": { - "Table": { - "table": "dietary_profile", - "name": "tags" - } - } + "origin": "Expression" }, { "ordinal": 2, @@ -61,21 +56,16 @@ ], "parameters": { "Left": [ - "Uuid", - "TextArray", - "Text", - "Uuid", - "Int8", - "Bool" + "Uuid" ] }, "nullable": [ false, - false, + null, true, false, false ] }, - "hash": "b364954dae05a5a23861686a2f9b9ce478f5ee272d09c11e288d335d05f43fd8" + "hash": "c41fb6b0ecd0a378198552f4c36085f8c0d229a7a83b23fb3ba02c1e6b675fe6" } diff --git a/.sqlx/query-c79d72b0f40ff99077904b1d479bb80ed92b3f86eef355cc301bcb1178d3ca4d.json b/.sqlx/query-c79d72b0f40ff99077904b1d479bb80ed92b3f86eef355cc301bcb1178d3ca4d.json deleted file mode 100644 index 326867d..0000000 --- a/.sqlx/query-c79d72b0f40ff99077904b1d479bb80ed92b3f86eef355cc301bcb1178d3ca4d.json +++ /dev/null @@ -1,137 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE board SET participants = $2 WHERE id = $1\n RETURNING id AS \"id: BoardId\", creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n participants AS \"participants: Vec\", locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\", epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "id: BoardId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "board", - "name": "id" - } - } - }, - { - "ordinal": 1, - "name": "creator: UserId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "board", - "name": "creator" - } - } - }, - { - "ordinal": 2, - "name": "title: BoardTitle", - "type_info": "Text", - "origin": { - "Table": { - "table": "board", - "name": "title" - } - } - }, - { - "ordinal": 3, - "name": "participants: Vec", - "type_info": "UuidArray", - "origin": { - "Table": { - "table": "board", - "name": "participants" - } - } - }, - { - "ordinal": 4, - "name": "locked", - "type_info": "Bool", - "origin": { - "Table": { - "table": "board", - "name": "locked" - } - } - }, - { - "ordinal": 5, - "name": "locked_by: UserId", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "board", - "name": "locked_by" - } - } - }, - { - "ordinal": 6, - "name": "locked_at: Timestamp", - "type_info": "Int8", - "origin": { - "Table": { - "table": "board", - "name": "locked_at" - } - } - }, - { - "ordinal": 7, - "name": "epoch", - "type_info": "Int8", - "origin": { - "Table": { - "table": "board", - "name": "epoch" - } - } - }, - { - "ordinal": 8, - "name": "closed_at: Timestamp", - "type_info": "Int8", - "origin": { - "Table": { - "table": "board", - "name": "closed_at" - } - } - }, - { - "ordinal": 9, - "name": "created_at: Timestamp", - "type_info": "Int8", - "origin": { - "Table": { - "table": "board", - "name": "created_at" - } - } - } - ], - "parameters": { - "Left": [ - "Uuid", - "UuidArray" - ] - }, - "nullable": [ - false, - false, - false, - false, - false, - true, - true, - false, - true, - false - ] - }, - "hash": "c79d72b0f40ff99077904b1d479bb80ed92b3f86eef355cc301bcb1178d3ca4d" -} diff --git a/.sqlx/query-c853378f65634bdb7e00a372fa188979bc2758176b486ac554a763653e04c718.json b/.sqlx/query-c853378f65634bdb7e00a372fa188979bc2758176b486ac554a763653e04c718.json new file mode 100644 index 0000000..c412cac --- /dev/null +++ b/.sqlx/query-c853378f65634bdb7e00a372fa188979bc2758176b486ac554a763653e04c718.json @@ -0,0 +1,24 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT ((SELECT count(*) FROM board_participant WHERE board = $1)\n + (SELECT count(*) FROM unnest($2::uuid[]) AS t(x)\n WHERE NOT EXISTS (SELECT 1 FROM board_participant bp\n WHERE bp.board = $1 AND bp.participant = t.x)))\n AS \"filled!\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "filled!", + "type_info": "Int8", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Uuid", + "UuidArray" + ] + }, + "nullable": [ + null + ] + }, + "hash": "c853378f65634bdb7e00a372fa188979bc2758176b486ac554a763653e04c718" +} diff --git a/.sqlx/query-c95bf5c2dfe3ef6919ddb41983f1ab4392ea31250f0c00db33e0864a33dfde42.json b/.sqlx/query-c95bf5c2dfe3ef6919ddb41983f1ab4392ea31250f0c00db33e0864a33dfde42.json new file mode 100644 index 0000000..5fadb05 --- /dev/null +++ b/.sqlx/query-c95bf5c2dfe3ef6919ddb41983f1ab4392ea31250f0c00db33e0864a33dfde42.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM rag_output_source WHERE output IN\n (SELECT id FROM rag_output WHERE course_note = $1)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "c95bf5c2dfe3ef6919ddb41983f1ab4392ea31250f0c00db33e0864a33dfde42" +} diff --git a/.sqlx/query-cb8b95b85f0f40ad61f2135d211ae1a44da4173d3d7e10b6e2e3dddad51d952e.json b/.sqlx/query-cb8b95b85f0f40ad61f2135d211ae1a44da4173d3d7e10b6e2e3dddad51d952e.json new file mode 100644 index 0000000..39c6f64 --- /dev/null +++ b/.sqlx/query-cb8b95b85f0f40ad61f2135d211ae1a44da4173d3d7e10b6e2e3dddad51d952e.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO homework_assignment (homework, student)\n SELECT $2, s FROM unnest($1::uuid[]) AS t(s)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "UuidArray", + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "cb8b95b85f0f40ad61f2135d211ae1a44da4173d3d7e10b6e2e3dddad51d952e" +} diff --git a/.sqlx/query-cbf6dd44326403b41940e572a66285a17bd52337a3b586b99deb4bfc5250bbe5.json b/.sqlx/query-cbf6dd44326403b41940e572a66285a17bd52337a3b586b99deb4bfc5250bbe5.json new file mode 100644 index 0000000..0acb6a8 --- /dev/null +++ b/.sqlx/query-cbf6dd44326403b41940e572a66285a17bd52337a3b586b99deb4bfc5250bbe5.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT source AS \"source: CourseNoteFileId\"\n FROM rag_output_source WHERE output = $1 ORDER BY source", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "source: CourseNoteFileId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "rag_output_source", + "name": "source" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "cbf6dd44326403b41940e572a66285a17bd52337a3b586b99deb4bfc5250bbe5" +} diff --git a/.sqlx/query-cdd48454144e721a0c3bab8b0859396b9a134f3b85a727c8fb08b01c9fa1fd6b.json b/.sqlx/query-cdd48454144e721a0c3bab8b0859396b9a134f3b85a727c8fb08b01c9fa1fd6b.json new file mode 100644 index 0000000..0e8899e --- /dev/null +++ b/.sqlx/query-cdd48454144e721a0c3bab8b0859396b9a134f3b85a727c8fb08b01c9fa1fd6b.json @@ -0,0 +1,20 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO menu_dish (id, menu, name, description, price_minor, created_at)\n SELECT $1, $2, $3, $4, $5, $6\n WHERE (SELECT count(*) FROM menu_dish WHERE menu = $2) < $7", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Text", + "Text", + "Text", + "Int8", + "Int8", + "Int8" + ] + }, + "nullable": [] + }, + "hash": "cdd48454144e721a0c3bab8b0859396b9a134f3b85a727c8fb08b01c9fa1fd6b" +} diff --git a/.sqlx/query-cf84beaac0eb97a92e8a2fde1cc7688b2d1a239f0604d945885c1c3a09b305b4.json b/.sqlx/query-cf84beaac0eb97a92e8a2fde1cc7688b2d1a239f0604d945885c1c3a09b305b4.json new file mode 100644 index 0000000..f42da98 --- /dev/null +++ b/.sqlx/query-cf84beaac0eb97a92e8a2fde1cc7688b2d1a239f0604d945885c1c3a09b305b4.json @@ -0,0 +1,21 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO settings (id, exam_kinds, grade_bands, max_file_bytes,\n chatbot_history_turns, max_chatbot_message_len,\n max_chatbot_threads, meal_slots,\n meal_cancel_cutoff_minutes)\n VALUES ('school', $1, $2, $3, $4, $5, $6, $7, $8)\n ON CONFLICT (id) DO UPDATE SET\n exam_kinds = EXCLUDED.exam_kinds,\n grade_bands = EXCLUDED.grade_bands,\n max_file_bytes = EXCLUDED.max_file_bytes,\n chatbot_history_turns = EXCLUDED.chatbot_history_turns,\n max_chatbot_message_len = EXCLUDED.max_chatbot_message_len,\n max_chatbot_threads = EXCLUDED.max_chatbot_threads,\n meal_slots = EXCLUDED.meal_slots,\n meal_cancel_cutoff_minutes = EXCLUDED.meal_cancel_cutoff_minutes", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Jsonb", + "Jsonb", + "Int8", + "Int8", + "Int8", + "Int8", + "Jsonb", + "Int8" + ] + }, + "nullable": [] + }, + "hash": "cf84beaac0eb97a92e8a2fde1cc7688b2d1a239f0604d945885c1c3a09b305b4" +} diff --git a/.sqlx/query-cfd796a16bdfb74c118bd76c0558e33b7c575b5510df2bf6547c818481be5eaa.json b/.sqlx/query-cfd796a16bdfb74c118bd76c0558e33b7c575b5510df2bf6547c818481be5eaa.json new file mode 100644 index 0000000..cc29652 --- /dev/null +++ b/.sqlx/query-cfd796a16bdfb74c118bd76c0558e33b7c575b5510df2bf6547c818481be5eaa.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO board_participant (board, participant)\n SELECT $1, t.x FROM unnest($2::uuid[]) AS t(x)\n ON CONFLICT DO NOTHING", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "UuidArray" + ] + }, + "nullable": [] + }, + "hash": "cfd796a16bdfb74c118bd76c0558e33b7c575b5510df2bf6547c818481be5eaa" +} diff --git a/.sqlx/query-da48c3255d2e13ec4031617c4e549cd7f9e911516b7615c36e1dfe07959ff51c.json b/.sqlx/query-da48c3255d2e13ec4031617c4e549cd7f9e911516b7615c36e1dfe07959ff51c.json deleted file mode 100644 index f78a2ca..0000000 --- a/.sqlx/query-da48c3255d2e13ec4031617c4e549cd7f9e911516b7615c36e1dfe07959ff51c.json +++ /dev/null @@ -1,145 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO settings (id, exam_kinds, attendance_statuses, grade_bands,\n max_file_bytes, chatbot_history_turns,\n max_chatbot_message_len, max_chatbot_threads,\n meal_slots, dietary_tags, meal_cancel_cutoff_minutes)\n VALUES ('school', $1, $2, $3, $4, $5, $6, $7, $8, $9, $10)\n ON CONFLICT (id) DO UPDATE SET\n exam_kinds = EXCLUDED.exam_kinds,\n attendance_statuses = EXCLUDED.attendance_statuses,\n grade_bands = EXCLUDED.grade_bands,\n max_file_bytes = EXCLUDED.max_file_bytes,\n chatbot_history_turns = EXCLUDED.chatbot_history_turns,\n max_chatbot_message_len = EXCLUDED.max_chatbot_message_len,\n max_chatbot_threads = EXCLUDED.max_chatbot_threads,\n meal_slots = EXCLUDED.meal_slots,\n dietary_tags = EXCLUDED.dietary_tags,\n meal_cancel_cutoff_minutes = EXCLUDED.meal_cancel_cutoff_minutes\n RETURNING\n exam_kinds AS \"exam_kinds: Json>\",\n attendance_statuses,\n grade_bands AS \"grade_bands: Json>\",\n max_file_bytes,\n chatbot_history_turns,\n max_chatbot_message_len,\n max_chatbot_threads,\n meal_slots AS \"meal_slots: Json>\",\n dietary_tags,\n meal_cancel_cutoff_minutes", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "exam_kinds: Json>", - "type_info": "Jsonb", - "origin": { - "Table": { - "table": "settings", - "name": "exam_kinds" - } - } - }, - { - "ordinal": 1, - "name": "attendance_statuses", - "type_info": "TextArray", - "origin": { - "Table": { - "table": "settings", - "name": "attendance_statuses" - } - } - }, - { - "ordinal": 2, - "name": "grade_bands: Json>", - "type_info": "Jsonb", - "origin": { - "Table": { - "table": "settings", - "name": "grade_bands" - } - } - }, - { - "ordinal": 3, - "name": "max_file_bytes", - "type_info": "Int8", - "origin": { - "Table": { - "table": "settings", - "name": "max_file_bytes" - } - } - }, - { - "ordinal": 4, - "name": "chatbot_history_turns", - "type_info": "Int8", - "origin": { - "Table": { - "table": "settings", - "name": "chatbot_history_turns" - } - } - }, - { - "ordinal": 5, - "name": "max_chatbot_message_len", - "type_info": "Int8", - "origin": { - "Table": { - "table": "settings", - "name": "max_chatbot_message_len" - } - } - }, - { - "ordinal": 6, - "name": "max_chatbot_threads", - "type_info": "Int8", - "origin": { - "Table": { - "table": "settings", - "name": "max_chatbot_threads" - } - } - }, - { - "ordinal": 7, - "name": "meal_slots: Json>", - "type_info": "Jsonb", - "origin": { - "Table": { - "table": "settings", - "name": "meal_slots" - } - } - }, - { - "ordinal": 8, - "name": "dietary_tags", - "type_info": "TextArray", - "origin": { - "Table": { - "table": "settings", - "name": "dietary_tags" - } - } - }, - { - "ordinal": 9, - "name": "meal_cancel_cutoff_minutes", - "type_info": "Int8", - "origin": { - "Table": { - "table": "settings", - "name": "meal_cancel_cutoff_minutes" - } - } - } - ], - "parameters": { - "Left": [ - "Jsonb", - "TextArray", - "Jsonb", - "Int8", - "Int8", - "Int8", - "Int8", - "Jsonb", - "TextArray", - "Int8" - ] - }, - "nullable": [ - false, - false, - false, - true, - true, - true, - true, - true, - true, - true - ] - }, - "hash": "da48c3255d2e13ec4031617c4e549cd7f9e911516b7615c36e1dfe07959ff51c" -} diff --git a/.sqlx/query-df8f0dba6da244501e34e5f0108236148b27134bbec41d9084704143e35d90ea.json b/.sqlx/query-df8f0dba6da244501e34e5f0108236148b27134bbec41d9084704143e35d90ea.json new file mode 100644 index 0000000..8f868fb --- /dev/null +++ b/.sqlx/query-df8f0dba6da244501e34e5f0108236148b27134bbec41d9084704143e35d90ea.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM board_participant WHERE board = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "df8f0dba6da244501e34e5f0108236148b27134bbec41d9084704143e35d90ea" +} diff --git a/.sqlx/query-9ebc278fccb979dbd426a4a24b7ab5261e0c26c29786b1abc23c03d76c27e7a9.json b/.sqlx/query-e468a344c54e212f2ad3d4159206fa97a212a9111135b4ca576962cc64267757.json similarity index 80% rename from .sqlx/query-9ebc278fccb979dbd426a4a24b7ab5261e0c26c29786b1abc23c03d76c27e7a9.json rename to .sqlx/query-e468a344c54e212f2ad3d4159206fa97a212a9111135b4ca576962cc64267757.json index 3f3f99b..236a5fd 100644 --- a/.sqlx/query-9ebc278fccb979dbd426a4a24b7ab5261e0c26c29786b1abc23c03d76c27e7a9.json +++ b/.sqlx/query-e468a344c54e212f2ad3d4159206fa97a212a9111135b4ca576962cc64267757.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE board SET closed_at = $2 WHERE id = $1 AND closed_at IS NULL\n RETURNING id AS \"id: BoardId\", creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n participants AS \"participants: Vec\", locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\", epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"", + "query": "UPDATE board SET closed_at = $2 WHERE id = $1 AND closed_at IS NULL\n RETURNING id AS \"id: BoardId\", creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n ARRAY(SELECT p.participant FROM board_participant p\n WHERE p.board = board.id ORDER BY p.participant)\n AS \"participants!: Vec\", locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\", epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"", "describe": { "columns": [ { @@ -38,14 +38,9 @@ }, { "ordinal": 3, - "name": "participants: Vec", + "name": "participants!: Vec", "type_info": "UuidArray", - "origin": { - "Table": { - "table": "board", - "name": "participants" - } - } + "origin": "Expression" }, { "ordinal": 4, @@ -124,7 +119,7 @@ false, false, false, - false, + null, false, true, true, @@ -133,5 +128,5 @@ false ] }, - "hash": "9ebc278fccb979dbd426a4a24b7ab5261e0c26c29786b1abc23c03d76c27e7a9" + "hash": "e468a344c54e212f2ad3d4159206fa97a212a9111135b4ca576962cc64267757" } diff --git a/.sqlx/query-8c457fff4a76cedba9338135a894713e2609cb8aed0e963ba491118d3aebe0a3.json b/.sqlx/query-ede2ad9dfbe1e9e069bd8912acb49d13f43f251bc7276d1a6b6fe249920677ad.json similarity index 58% rename from .sqlx/query-8c457fff4a76cedba9338135a894713e2609cb8aed0e963ba491118d3aebe0a3.json rename to .sqlx/query-ede2ad9dfbe1e9e069bd8912acb49d13f43f251bc7276d1a6b6fe249920677ad.json index 177d57d..f2a6371 100644 --- a/.sqlx/query-8c457fff4a76cedba9338135a894713e2609cb8aed0e963ba491118d3aebe0a3.json +++ b/.sqlx/query-ede2ad9dfbe1e9e069bd8912acb49d13f43f251bc7276d1a6b6fe249920677ad.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO person_school (person, school, created_at) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING", + "query": "INSERT INTO person_school (person, school, created_at)\n SELECT $1, s.id, $3 FROM school s WHERE s.slug = $2\n ON CONFLICT DO NOTHING", "describe": { "columns": [], "parameters": { @@ -12,5 +12,5 @@ }, "nullable": [] }, - "hash": "8c457fff4a76cedba9338135a894713e2609cb8aed0e963ba491118d3aebe0a3" + "hash": "ede2ad9dfbe1e9e069bd8912acb49d13f43f251bc7276d1a6b6fe249920677ad" } diff --git a/.sqlx/query-1604ab0a5b6f69c82c52fbdd8a4a54422aaacfa006d1a05d5ea37ed20baa355f.json b/.sqlx/query-f19d64790b8c145113b680276ff897b1f4786e15116846e0288035e6ef1ca091.json similarity index 77% rename from .sqlx/query-1604ab0a5b6f69c82c52fbdd8a4a54422aaacfa006d1a05d5ea37ed20baa355f.json rename to .sqlx/query-f19d64790b8c145113b680276ff897b1f4786e15116846e0288035e6ef1ca091.json index d549475..dc76186 100644 --- a/.sqlx/query-1604ab0a5b6f69c82c52fbdd8a4a54422aaacfa006d1a05d5ea37ed20baa355f.json +++ b/.sqlx/query-f19d64790b8c145113b680276ff897b1f4786e15116846e0288035e6ef1ca091.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END\n AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework\n WHERE course = $1 AND (cardinality(assigned) = 0 OR $2 = ANY(assigned))\n ORDER BY id DESC", + "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework\n WHERE course = $1\n AND (NOT EXISTS (SELECT 1 FROM homework_assignment a\n WHERE a.homework = homework.id)\n OR EXISTS (SELECT 1 FROM homework_assignment a\n WHERE a.homework = homework.id AND a.student = $2))\n ORDER BY id DESC", "describe": { "columns": [ { @@ -116,5 +116,5 @@ false ] }, - "hash": "1604ab0a5b6f69c82c52fbdd8a4a54422aaacfa006d1a05d5ea37ed20baa355f" + "hash": "f19d64790b8c145113b680276ff897b1f4786e15116846e0288035e6ef1ca091" } diff --git a/.sqlx/query-f3d94b7ff35a9dfabb0459303432942bc8828d833df5fe56e8201b2aa8cae80c.json b/.sqlx/query-f3d94b7ff35a9dfabb0459303432942bc8828d833df5fe56e8201b2aa8cae80c.json new file mode 100644 index 0000000..248e408 --- /dev/null +++ b/.sqlx/query-f3d94b7ff35a9dfabb0459303432942bc8828d833df5fe56e8201b2aa8cae80c.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO homework_assignment (homework, student)\n SELECT $2, s FROM unnest($1::uuid[]) AS t(s)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "UuidArray", + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "f3d94b7ff35a9dfabb0459303432942bc8828d833df5fe56e8201b2aa8cae80c" +} diff --git a/.sqlx/query-f5de8fdcec4e2b21ebb8fbfbd12202947538687c018b94967578f68be3358864.json b/.sqlx/query-f5de8fdcec4e2b21ebb8fbfbd12202947538687c018b94967578f68be3358864.json new file mode 100644 index 0000000..62728fb --- /dev/null +++ b/.sqlx/query-f5de8fdcec4e2b21ebb8fbfbd12202947538687c018b94967578f68be3358864.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM rag_output_source WHERE source = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "f5de8fdcec4e2b21ebb8fbfbd12202947538687c018b94967578f68be3358864" +} diff --git a/.sqlx/query-d33066aa6a8214a7ceb38922c1fa0ad45fcb45e4a4cebbc26efbcf8c31691517.json b/.sqlx/query-f7d2187dc89a2bba3b521b0ea67282392ba1739904fcb1d40006e34c78d4afa9.json similarity index 85% rename from .sqlx/query-d33066aa6a8214a7ceb38922c1fa0ad45fcb45e4a4cebbc26efbcf8c31691517.json rename to .sqlx/query-f7d2187dc89a2bba3b521b0ea67282392ba1739904fcb1d40006e34c78d4afa9.json index 0aad7f1..475b902 100644 --- a/.sqlx/query-d33066aa6a8214a7ceb38922c1fa0ad45fcb45e4a4cebbc26efbcf8c31691517.json +++ b/.sqlx/query-f7d2187dc89a2bba3b521b0ea67282392ba1739904fcb1d40006e34c78d4afa9.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END\n AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE id = $1", + "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE course = $1 ORDER BY id DESC", "describe": { "columns": [ { @@ -115,5 +115,5 @@ false ] }, - "hash": "d33066aa6a8214a7ceb38922c1fa0ad45fcb45e4a4cebbc26efbcf8c31691517" + "hash": "f7d2187dc89a2bba3b521b0ea67282392ba1739904fcb1d40006e34c78d4afa9" } diff --git a/.sqlx/query-8a2042be8e7358d9c9f9f8a906ff113f71fa4ac519aec8519ee6b40bc51f694d.json b/.sqlx/query-fb46d17a76c6111308068c735184bbb68a2b726f7a1c98068d506d51aa52785e.json similarity index 68% rename from .sqlx/query-8a2042be8e7358d9c9f9f8a906ff113f71fa4ac519aec8519ee6b40bc51f694d.json rename to .sqlx/query-fb46d17a76c6111308068c735184bbb68a2b726f7a1c98068d506d51aa52785e.json index 4063b3a..20d9d01 100644 --- a/.sqlx/query-8a2042be8e7358d9c9f9f8a906ff113f71fa4ac519aec8519ee6b40bc51f694d.json +++ b/.sqlx/query-fb46d17a76c6111308068c735184bbb68a2b726f7a1c98068d506d51aa52785e.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT\n exam_kinds AS \"exam_kinds: Json>\",\n attendance_statuses,\n grade_bands AS \"grade_bands: Json>\",\n max_file_bytes,\n chatbot_history_turns,\n max_chatbot_message_len,\n max_chatbot_threads,\n meal_slots AS \"meal_slots: Json>\",\n dietary_tags,\n meal_cancel_cutoff_minutes\n FROM settings WHERE id = 'school'", + "query": "SELECT s.exam_kinds AS \"exam_kinds: Json>\",\n COALESCE((SELECT array_agg(t.status ORDER BY t.status)\n FROM settings_attendance_status t\n WHERE t.settings = s.id), '{}') AS \"attendance_statuses!: Vec\",\n s.grade_bands AS \"grade_bands: Json>\",\n s.max_file_bytes,\n s.chatbot_history_turns,\n s.max_chatbot_message_len,\n s.max_chatbot_threads,\n s.meal_slots AS \"meal_slots: Json>\",\n (SELECT array_agg(t.tag ORDER BY t.tag)\n FROM settings_dietary_tag t\n WHERE t.settings = s.id) AS dietary_tags,\n s.meal_cancel_cutoff_minutes\n FROM settings s WHERE s.id = 'school'", "describe": { "columns": [ { @@ -16,14 +16,9 @@ }, { "ordinal": 1, - "name": "attendance_statuses", + "name": "attendance_statuses!: Vec", "type_info": "TextArray", - "origin": { - "Table": { - "table": "settings", - "name": "attendance_statuses" - } - } + "origin": "Expression" }, { "ordinal": 2, @@ -95,12 +90,7 @@ "ordinal": 8, "name": "dietary_tags", "type_info": "TextArray", - "origin": { - "Table": { - "table": "settings", - "name": "dietary_tags" - } - } + "origin": "Expression" }, { "ordinal": 9, @@ -119,16 +109,16 @@ }, "nullable": [ false, + null, false, - false, - true, true, true, true, true, true, + null, true ] }, - "hash": "8a2042be8e7358d9c9f9f8a906ff113f71fa4ac519aec8519ee6b40bc51f694d" + "hash": "fb46d17a76c6111308068c735184bbb68a2b726f7a1c98068d506d51aa52785e" } diff --git a/.sqlx/query-1f1dc2c17f96a49d8ae036569ba1d67db0558b58f0c2a463d54ad923254fba8c.json b/.sqlx/query-fd31503ac762b761089f28233e0b2e425f8a349b2715ae2062fdda16d1c86d00.json similarity index 69% rename from .sqlx/query-1f1dc2c17f96a49d8ae036569ba1d67db0558b58f0c2a463d54ad923254fba8c.json rename to .sqlx/query-fd31503ac762b761089f28233e0b2e425f8a349b2715ae2062fdda16d1c86d00.json index c08a988..cbd2309 100644 --- a/.sqlx/query-1f1dc2c17f96a49d8ae036569ba1d67db0558b58f0c2a463d54ad923254fba8c.json +++ b/.sqlx/query-fd31503ac762b761089f28233e0b2e425f8a349b2715ae2062fdda16d1c86d00.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT student AS \"student: UserId\", tags AS \"tags: DietaryTags\", note AS \"note: DietaryNote\", updated_by AS \"updated_by: UserId\", updated_at AS \"updated_at: Timestamp\"\n FROM dietary_profile WHERE student = $1", + "query": "SELECT student AS \"student: UserId\",\n COALESCE((SELECT array_agg(t.tag ORDER BY t.ord) FROM dietary_profile_tag t WHERE t.student = dietary_profile.student), '{}'::text[]) AS \"tags!: DietaryTags\",\n note AS \"note: DietaryNote\", updated_by AS \"updated_by: UserId\", updated_at AS \"updated_at: Timestamp\"\n FROM dietary_profile WHERE student = $1", "describe": { "columns": [ { @@ -16,14 +16,9 @@ }, { "ordinal": 1, - "name": "tags: DietaryTags", + "name": "tags!: DietaryTags", "type_info": "TextArray", - "origin": { - "Table": { - "table": "dietary_profile", - "name": "tags" - } - } + "origin": "Expression" }, { "ordinal": 2, @@ -66,11 +61,11 @@ }, "nullable": [ false, - false, + null, true, false, false ] }, - "hash": "1f1dc2c17f96a49d8ae036569ba1d67db0558b58f0c2a463d54ad923254fba8c" + "hash": "fd31503ac762b761089f28233e0b2e425f8a349b2715ae2062fdda16d1c86d00" } diff --git a/.sqlx/query-fe740c4ecd33f9510af45852fdbb70712754d6d6095b27404cb77dc106774341.json b/.sqlx/query-fe26461b2872573cafe05ba8d0b70ce84a117296bdf0c18e643293bb0b1e153e.json similarity index 78% rename from .sqlx/query-fe740c4ecd33f9510af45852fdbb70712754d6d6095b27404cb77dc106774341.json rename to .sqlx/query-fe26461b2872573cafe05ba8d0b70ce84a117296bdf0c18e643293bb0b1e153e.json index 830f6e8..3404116 100644 --- a/.sqlx/query-fe740c4ecd33f9510af45852fdbb70712754d6d6095b27404cb77dc106774341.json +++ b/.sqlx/query-fe26461b2872573cafe05ba8d0b70ce84a117296bdf0c18e643293bb0b1e153e.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: BoardId\", creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n participants AS \"participants: Vec\", locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\", epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"\n FROM board WHERE id = $1 FOR UPDATE", + "query": "SELECT id AS \"id: BoardId\", creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n ARRAY(SELECT p.participant FROM board_participant p\n WHERE p.board = board.id ORDER BY p.participant)\n AS \"participants!: Vec\", locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\", epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"\n FROM board WHERE id = $1 FOR UPDATE", "describe": { "columns": [ { @@ -38,14 +38,9 @@ }, { "ordinal": 3, - "name": "participants: Vec", + "name": "participants!: Vec", "type_info": "UuidArray", - "origin": { - "Table": { - "table": "board", - "name": "participants" - } - } + "origin": "Expression" }, { "ordinal": 4, @@ -123,7 +118,7 @@ false, false, false, - false, + null, false, true, true, @@ -132,5 +127,5 @@ false ] }, - "hash": "fe740c4ecd33f9510af45852fdbb70712754d6d6095b27404cb77dc106774341" + "hash": "fe26461b2872573cafe05ba8d0b70ce84a117296bdf0c18e643293bb0b1e153e" } diff --git a/README.md b/README.md index fbcf99d..ca01a4c 100644 --- a/README.md +++ b/README.md @@ -242,14 +242,40 @@ so the build never touches a database — the macros read the committed `postgres:18-alpine` image, `max_connections=500` so the test suite's parallel control+school pools fit) and the backend, which waits for the database's healthcheck and connects over `DATABASE_URL` -(`postgres://hezarfen:hezarfen@postgres:5432/hezarfen_control`). Each has -its own named volume — `pgdata` holds the database, `hezarfen-data` the -uploaded note files (`/data/files`). `HOST` is forced to `0.0.0.0` inside the -container so the published port works. Production knobs (`COOKIE_SECURE`, -`CORS_ALLOWED_ORIGINS`, rate limits, `TRUST_PROXY`) are commented in -`compose.yaml` — uncomment as needed. Leaving `CORS_ALLOWED_ORIGINS` unset -means dev mirror mode without credentials; a cookie-using browser frontend -must be allowlisted explicitly. Works with `docker compose` too. +(`postgres://hezarfen:hezarfen@postgres:5432/hezarfen_control`). The backend +port is published on loopback only — `127.0.0.1:7656:7656` — so a server +deployment sits behind a reverse proxy and the API is never directly +reachable (`HOST` is forced to `0.0.0.0` inside the container so the publish +works). Each service has its own named volume: `pgdata` holds the database +— it is mounted at `/var/lib/postgresql`, which the postgres:18 image keeps +its cluster under (`/var/lib/postgresql/18/docker`), so the data really +lands in the volume — and `hezarfen-data` holds the +uploaded note files (`/data/files`). Production knobs (`COOKIE_SECURE`, +`CORS_ALLOWED_ORIGINS`, rate limits, `TRUST_PROXY`) reach the backend through +the env file (below), not through `compose.yaml`. Leaving +`CORS_ALLOWED_ORIGINS` unset means dev mirror mode without credentials; a +cookie-using browser frontend must be allowlisted explicitly. Works with +`docker compose` too. + +**Credentials live in three places and are never mixed.** CI's postgres +sidecar uses a throwaway `hezarfen`/`hezarfen` pair declared in the workflow +— no GitHub secrets involved. Local compose interpolates dev defaults +(`hezarfen`/`hezarfen` for postgres, `builder`/`builder123` for the builder +account, `admin@hezarfen.local` / `Hezarfen_dev1!` for OpenObserve), so the +`up` above works with zero extra files. Production is the operator's job: +ssh to the VPS, copy `deploy/hezarfen_backend.env.example` to +`$HOME/hezarfen_backend/hezarfen_backend.env`, `chmod 0600` it, and set the +real passwords — the deploy pipeline never creates, overwrites or uploads +that file, it only refuses to run unless the file exists at mode `0600` with +non-empty `POSTGRES_PASSWORD=`, `BUILDER_PASSWORD=`, `ZO_ROOT_USER_EMAIL=` and +`ZO_ROOT_USER_PASSWORD=` values (prod never silently falls back to the dev defaults). The first `podman compose up` bakes +`POSTGRES_PASSWORD` into the `pgdata` volume: changing the env file +afterwards does not re-key the database, so the real password must be in +place before that first up, and it must be URL-safe (no `@`, `:`, `/` — it +is interpolated into `DATABASE_URL`). The same file is the backend's +optional `env_file`, so extra keys it carries (`COOKIE_SECURE`, +`TRUST_PROXY`, `CORS_*`, `RATE_LIMIT_*`, `OTEL_*`) reach the container +without being listed in `environment:`. One more service is the telemetry sink: `openobserve`, a single Rust binary that stores logs, metrics and traces itself — no sidecar databases and no @@ -258,13 +284,38 @@ container socket. Its UI, search API and OTLP/HTTP ingest share http://127.0.0.1:5080 as the `ZO_ROOT_USER_EMAIL`/`ZO_ROOT_USER_PASSWORD` pair set on the service (`admin@hezarfen.local` / `Hezarfen_dev1!` for local dev — OpenObserve rejects a weaker password at boot). Retention is per stream in -days, defaulted globally to 90 by `ZO_COMPACT_DATA_RETENTION_DAYS`. Uncomment -the backend's `OTEL_EXPORTER_OTLP_ENDPOINT` (`http://openobserve:5081`) and +days, defaulted globally to 90 by `ZO_COMPACT_DATA_RETENTION_DAYS`. Traces, +metrics and logs start landing when the backend's environment carries +`OTEL_EXPORTER_OTLP_ENDPOINT` (`http://openobserve:5081`) and `OTEL_EXPORTER_OTLP_HEADERS` (`Authorization=Basic ` -plus `organization=default,stream-name=default`), and traces, metrics and logs -start landing; the commented OTLP/HTTP variant uses -`http://openobserve:5080/api/default` with `OTEL_EXPORTER_OTLP_PROTOCOL: -http/protobuf` instead. +plus `organization=default,stream-name=default`) — those keys belong in the +env file (production: `hezarfen_backend.env`; locally: an optional file of +the same name beside `compose.yaml`), never in `compose.yaml` itself, where +an empty OTEL value would switch export on and fail the boot. The OTLP/HTTP +variant (`http://openobserve:5080/api/default` with +`OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf`) is the alternative. + +Running a server means running its backups too. `./backup-postgres.sh` — +shipped with the deploy artifact and living next to `compose.yaml` on the VPS +— streams `pg_dumpall` out of the postgres container into +`backups/hezarfen-.sql.gz`, mode `0600`. `pg_dumpall` rather than +`pg_dump`, because every school is its own database and one dump has to cover +the control database and all of them. Restore with: + +```sh +gunzip -c backups/FILE.sql.gz | podman exec -i hezarfen-postgres psql -U hezarfen -d postgres +``` + +Deploying is GitHub Actions' job, not the server's: the workflow packs the +already-built binary and the migrations into a runtime image +(`deploy/Containerfile.runtime`), ships the image tarball together with +`compose.yaml`, the `hezarfen-compose.service` unit and the backup script as +an artifact, and the deploy job loads it on the VPS and starts the stack with +`podman compose up -d --no-build` — the image tag travels in a deploy-owned +`stack.env`, so a release never rewrites the operator's secrets file. The +operator's only manual step is writing the env file once (above). Reboots +heal themselves: the user session lingers (`loginctl enable-linger`) and the +`hezarfen-compose.service` user unit runs compose again at boot. The backend survives the database going away, at boot and at runtime. @@ -959,9 +1010,11 @@ if an older build already emptied a school's admin set): run UPDATE app_user SET role = 'admin' WHERE username = 'ada'; ``` -against the **school's** database (`{control}_school_{slug}`), not the -control one — e.g. `podman exec -it hezarfen-postgres psql -U hezarfen -d -hezarfen_control_school_demo` for the compose stack. +against the **school's** database (`{control}_school_{uuid hex}` — the hex of +the school's registry `id`, no dashes), not the control one. List the school +databases with `\l` — e.g. `podman exec -it hezarfen-postgres psql -U hezarfen +-d hezarfen_control -c "SELECT slug, id FROM school"` names each school and +its database suffix for the compose stack. ## Endpoints @@ -4866,7 +4919,8 @@ driven by a client that shares no code with the backend). Every suite runs against a **real** PostgreSQL, because production is real PostgreSQL. The harness (tests/common) mints each test a private pair of databases on one server — `heztest_<16 hex>` for the control side and its -`heztest_<…>_school_demo` school, template-cloned so a schema edit migrates +`heztest_<…>_school_` school (the school's registry id, clipped to +Postgres's 63-byte identifier cap), template-cloned so a schema edit migrates the shared template once — and drops them when the deployment's last handle dies; a janitor sweeps what a crashed run left behind. The server comes from `HEZARFEN_TEST_DATABASE_URL` (default: the compose stack's maintenance diff --git a/compose.yaml b/compose.yaml index 604572b..cf4a95b 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,3 +1,20 @@ +# The whole stack: postgres + backend + OpenObserve behind podman compose. +# +# Credentials live in three places, never mixed (see README): +# laptop the ${VAR:-default} interpolations below — `podman compose up` +# works with zero extra files +# CI the workflow's throwaway postgres sidecar (hezarfen/hezarfen) +# VPS prod ~/hezarfen_backend/hezarfen_backend.env (0600, written by hand +# from deploy/hezarfen_backend.env.example) +# +# Interpolation reads the --env-file arguments (hezarfen_backend.env first, +# deploy-owned stack.env second). The `env_file:` on the backend passes the +# same secrets file into the container so extra keys (OTEL_*, COOKIE_SECURE, +# TRUST_PROXY, CORS_*, RATE_LIMIT_*) reach it without being listed in +# `environment:`. `environment:` wins over `env_file`, which is why +# DATABASE_URL is always constructed here: a leftover DATABASE_URL in the env +# file cannot point the container at the host. + services: postgres: image: docker.io/library/postgres:18-alpine @@ -6,16 +23,21 @@ services: # (nextest runs ~a dozen concurrently), which exhausts the 100 default. command: ["postgres", "-c", "max_connections=500"] environment: - POSTGRES_USER: hezarfen - POSTGRES_PASSWORD: hezarfen - POSTGRES_DB: hezarfen_control + POSTGRES_USER: ${POSTGRES_USER:-hezarfen} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-hezarfen} + POSTGRES_DB: ${POSTGRES_DB:-hezarfen_control} ports: - "127.0.0.1:5432:5432" volumes: - - pgdata:/data + # postgres:18 declares VOLUME /var/lib/postgresql (PGDATA is + # /var/lib/postgresql/18/docker); mounting the parent keeps the whole + # data dir — including future major-version subdirs — in the volume. + - pgdata:/var/lib/postgresql restart: unless-stopped healthcheck: - test: ["CMD-SHELL", "pg_isready -U hezarfen -d hezarfen_control"] + # $$ keeps compose from interpolating; the shell inside the container + # expands the image's own POSTGRES_USER / POSTGRES_DB. + test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"] interval: 10s timeout: 5s retries: 5 @@ -25,52 +47,40 @@ services: build: context: . dockerfile: Containerfile - image: localhost/hezarfen-backend:latest + # HEZARFEN_TAG comes from the deploy-owned stack.env (--env-file), or the + # latest local build on a laptop. + image: localhost/hezarfen-backend:${HEZARFEN_TAG:-latest} container_name: hezarfen-backend ports: - - "7656:7656" + # Loopback only: terminate TLS on a reverse proxy in front of this. + - "127.0.0.1:7656:7656" # AI bridge (QUIC = UDP). Paired with AI_QUIC_ADDR below. - "8090:8090/udp" + env_file: + # Written once by the operator on the VPS (0600); absent on a laptop. + - path: hezarfen_backend.env + required: false environment: HOST: 0.0.0.0 PORT: "7656" # The control database: the school registry + the builder accounts. Each # school lives in a Postgres database of its own, named from its slug. - DATABASE_URL: postgres://hezarfen:hezarfen@postgres:5432/hezarfen_control + # Constructed from POSTGRES_* and always aimed at the compose postgres. + DATABASE_URL: postgres://${POSTGRES_USER:-hezarfen}:${POSTGRES_PASSWORD:-hezarfen}@postgres:5432/${POSTGRES_DB:-hezarfen_control} + # Hardcoded: must not pick up an old systemd host path from the env file. FILES_PATH: /data/files RUST_LOG: info,hezarfen_backend=debug # First-boot builder seed: the operator who creates and suspends schools, - # created once if the username doesn't exist yet. Local-dev credentials — - # change or remove before exposing this anywhere. - BUILDER_USERNAME: builder - BUILDER_PASSWORD: builder123 - # Production knobs — uncomment as needed (see .env.example for docs): - # COOKIE_SECURE: "true" - # CORS_ALLOWED_ORIGINS: https://app.example.com - # RATE_LIMIT_AUTH_PER_MINUTE: "10" - # RATE_LIMIT_API_PER_MINUTE: "300" - # TRUST_PROXY: "true" - # Telemetry — export traces, metrics and logs to OpenObserve over OTLP. - # The Authorization value is base64(":"); - # for the local-dev pair above that is the string below. gRPC carries the - # organization and the target stream as metadata headers. - # OTEL_EXPORTER_OTLP_ENDPOINT: http://openobserve:5081 - # OTEL_EXPORTER_OTLP_HEADERS: "Authorization=Basic YWRtaW5AaGV6YXJmZW4ubG9jYWw6SGV6YXJmZW5fZGV2MSE=,organization=default,stream-name=default" - # OTEL_SERVICE_NAME: hezarfen-backend - # OTLP/HTTP instead: the org goes in the path (the SDK appends - # /v1/{traces,metrics,logs}) and only Authorization is needed. - # OTEL_EXPORTER_OTLP_ENDPOINT: http://openobserve:5080/api/default - # OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf - # OTEL_EXPORTER_OTLP_HEADERS: "Authorization=Basic YWRtaW5AaGV6YXJmZW4ubG9jYWw6SGV6YXJmZW5fZGV2MSE=" + # created once if the username doesn't exist yet. + BUILDER_USERNAME: ${BUILDER_USERNAME:-builder} + BUILDER_PASSWORD: ${BUILDER_PASSWORD:-builder123} # AI bridge — the AI services dial IN over QUIC. Unset means off; a # bad address or a missing token fails the boot rather than leaving a # silently dead feature. Listening with no service connected is fine: # chat answers 503 until one registers `chat.reply`. - AI_QUIC_ADDR: 0.0.0.0:8090 - # Every service must present this to register. Local-dev value — change - # it before this is reachable from anywhere but your machine. - AI_SHARED_TOKEN: change-me - # AI_REQUEST_TIMEOUT_SECS: "30" + AI_QUIC_ADDR: ${AI_QUIC_ADDR:-0.0.0.0:8090} + # Every service must present this to register. + AI_SHARED_TOKEN: ${AI_SHARED_TOKEN:-change-me} volumes: - hezarfen-data:/data depends_on: @@ -88,18 +98,17 @@ services: # OpenObserve is the only telemetry sink (no Grafana/Jaeger/Loki): one Rust # binary, its own storage, no container socket and no sidecar databases. It # speaks OTLP itself — HTTP on 5080 (also the UI and the search API), gRPC on - # 5081. Both are published on loopback only. + # 5081. Both are published on loopback only. The backend exports to it only + # when OTEL_* keys are present in hezarfen_backend.env (see the example). openobserve: image: docker.io/openobserve/openobserve:v1.0.0-rc2 container_name: hezarfen-openobserve environment: - # First-boot root account, created once. Local-dev credentials, same - # status as the root/root above — change them before this is reachable - # from anywhere but your machine. OpenObserve enforces a password policy - # (8-128 chars, upper + lower + digit + special) and panics on boot - # otherwise, hence the shape of this one. - ZO_ROOT_USER_EMAIL: admin@hezarfen.local - ZO_ROOT_USER_PASSWORD: Hezarfen_dev1! + # First-boot root account, created once. OpenObserve enforces a password + # policy (8-128 chars, upper + lower + digit + special) and panics on + # boot otherwise. + ZO_ROOT_USER_EMAIL: ${ZO_ROOT_USER_EMAIL:-admin@hezarfen.local} + ZO_ROOT_USER_PASSWORD: ${ZO_ROOT_USER_PASSWORD:-Hezarfen_dev1!} ZO_DATA_DIR: /data # Retention is per stream in days; this is the global default applied to # streams that don't override it (upstream default is 3650). diff --git a/deploy/Containerfile.runtime b/deploy/Containerfile.runtime new file mode 100644 index 0000000..77fcb5f --- /dev/null +++ b/deploy/Containerfile.runtime @@ -0,0 +1,37 @@ +# CI-only runtime image: built from the gnu binary the workflow already +# compiled and stripped on ubuntu-24.04 — never from source here (a second +# rust compile blows the runner's disk; the source `Containerfile` stays for +# laptop `podman compose up --build`). +# +# Build context is stage/, populated by CI: +# docker build -f deploy/Containerfile.runtime \ +# -t localhost/hezarfen-backend:$GITHUB_SHA stage/ +# with stage/hezarfen_backend (the binary) and stage/migrations/. +FROM docker.io/library/debian:trixie-slim + +# curl answers the compose healthcheck; ca-certificates for TLS the backend +# may dial (OTLP endpoints, the AI bridge). +RUN apt-get update && \ + apt-get install -y --no-install-recommends curl ca-certificates && \ + rm -rf /var/lib/apt/lists/* && \ + useradd --system --uid 10001 hezarfen && \ + mkdir /data && chown hezarfen:hezarfen /data + +# Migrations MUST sit beside the binary at /app/hezarfen_backend: the CI +# runner's CARGO_MANIFEST_DIR does not exist in the image, so the app resolves +# the schema next to the executable (migrations_path in the source). +COPY hezarfen_backend /app/hezarfen_backend +COPY migrations /app/migrations + +WORKDIR /app +USER hezarfen + +# DATABASE_URL is deliberately not baked in: compose constructs it in +# `environment:` from POSTGRES_* (see compose.yaml), which also wins over the +# operator's env_file. +ENV HOST=0.0.0.0 \ + PORT=7656 + +EXPOSE 7656 + +ENTRYPOINT ["/app/hezarfen_backend"] diff --git a/deploy/backup-postgres.sh b/deploy/backup-postgres.sh new file mode 100755 index 0000000..41735b1 --- /dev/null +++ b/deploy/backup-postgres.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +# Dump every database in the hezarfen compose stack to backups/ next to this +# script. pg_dumpall is required (not pg_dump): each school is its own +# postgres database, and a control-only dump would lose them all. +# +# Keeps: backups/hezarfen-.sql.gz, mode 0600. +# Cron example (daily 04:20): +# 20 4 * * * $HOME/hezarfen_backend/backup-postgres.sh +# +# Restore (from ~/hezarfen_backend): +# gunzip -c backups/FILE.sql.gz | podman exec -i hezarfen-postgres psql -U hezarfen -d postgres +set -euo pipefail + +dir="$(cd "$(dirname "$0")" && pwd)" +mkdir -p "$dir/backups" + +# POSTGRES_USER lives in the env file beside this script (plain KEY=value +# lines, no quotes/export); default hezarfen. +user="$(awk -F= '/^POSTGRES_USER=/{print $2; exit}' "$dir/hezarfen_backend.env" 2>/dev/null || true)" +user="${user:-hezarfen}" + +out="$dir/backups/hezarfen-$(date -u +%Y%m%dT%H%M%SZ).sql.gz" +umask 077 +# pipefail (set above): a failed pg_dumpall must not leave a "good" empty dump. +podman exec hezarfen-postgres pg_dumpall -U "$user" | gzip > "$out" +echo "wrote $out ($(du -h "$out" | cut -f1))" diff --git a/deploy/hezarfen-compose.service b/deploy/hezarfen-compose.service new file mode 100644 index 0000000..9a6b0ea --- /dev/null +++ b/deploy/hezarfen-compose.service @@ -0,0 +1,47 @@ +# systemd USER unit running the whole stack via podman compose (replaces the +# old bare-binary unit). Files expected in %h/hezarfen_backend: +# compose.yaml from the deploy artifact +# hezarfen_backend.env 0600, written ONCE BY HAND from +# deploy/hezarfen_backend.env.example — the +# deploy never creates or overwrites it +# stack.env deploy-owned; carries HEZARFEN_TAG +# backup-postgres.sh from the deploy artifact (0755) +# +# Required hezarfen_backend.env keys (full docs in +# deploy/hezarfen_backend.env.example): +# POSTGRES_USER/PASSWORD/DB first-boot postgres credentials; +# POSTGRES_PASSWORD is baked into the pgdata +# volume on the FIRST up and must be URL-safe +# (no @ : / — it is interpolated into +# DATABASE_URL) +# BUILDER_USERNAME/PASSWORD first-boot operator seed +# COOKIE_SECURE true behind TLS +# TRUST_PROXY true behind the reverse proxy +# CORS_ALLOWED_ORIGINS the browser frontends' origins +# AI_QUIC_ADDR/AI_SHARED_TOKEN the QUIC AI bridge +# OTEL_* OTLP export to http://openobserve:5081 +# ZO_ROOT_USER_EMAIL/PASSWORD OpenObserve first-boot root account +# DEPLOY_ENV production +# +# Env-only restart (restart re-runs `compose up -d`, recreating containers +# whose environment changed): +# systemctl --user restart hezarfen-compose + +[Unit] +Description=Hezarfen backend compose stack (postgres + backend + openobserve) +After=network-online.target +Wants=network-online.target + +[Service] +Type=oneshot +RemainAfterExit=yes +WorkingDirectory=%h/hezarfen_backend +# Later --env-file wins for duplicate keys: the operator's secrets file +# first, the deploy-owned stack.env (HEZARFEN_TAG) second. +ExecStart=/usr/bin/podman compose --env-file %h/hezarfen_backend/hezarfen_backend.env --env-file %h/hezarfen_backend/stack.env up -d --no-build +# No -v: the pgdata/hezarfen-data/openobserve-data volumes must survive stop. +ExecStop=/usr/bin/podman compose down +TimeoutStartSec=180 + +[Install] +WantedBy=default.target diff --git a/deploy/hezarfen.service b/deploy/hezarfen.service deleted file mode 100644 index 8a20940..0000000 --- a/deploy/hezarfen.service +++ /dev/null @@ -1,41 +0,0 @@ -# The systemd user unit the deploy installs to ~/.config/systemd/user/ and -# restarts. The release layout: ~/hezarfen_backend/current/hezarfen_backend with -# migrations/ beside the binary (the app resolves the schema there when the -# compile-time checkout path is absent — see migrations_path in the source). -# -# ~/hezarfen_backend/hezarfen_backend.env (0600, written once by hand, never by the deploy) -# carries the deployment's own values and overrides the Environment= lines -# below: -# DATABASE_URL required — a Postgres with the control database -# (first boot creates the schema; each school is -# minted as its own database by the builder API) -# BUILDER_USERNAME/PASSWORD first-boot operator seed -# AI_QUIC_ADDR + AI_SHARED_TOKEN the AI bridge (UDP); unset = off -# COOKIE_SECURE=true behind TLS -# CORS_ALLOWED_ORIGINS a lone `*` reflects any origin with credentials -# ("anywhere, for now"); list the real origins -# once the frontends are known -# TRUST_PROXY=true client IPs from X-Forwarded-For behind a proxy -# -# The service binds loopback only by default — terminate TLS on a reverse -# proxy and forward to 127.0.0.1:7656. - -[Unit] -Description=Hezarfen backend (school management API) -After=network-online.target -Wants=network-online.target - -[Service] -Type=simple -ExecStart=%h/hezarfen_backend/current/hezarfen_backend -WorkingDirectory=%h/hezarfen_backend/current -Environment=HOST=127.0.0.1 -Environment=PORT=7656 -Environment=FILES_PATH=%h/hezarfen_backend/data/files -Environment=RUST_LOG=info,hezarfen_backend=debug -EnvironmentFile=%h/hezarfen_backend/hezarfen_backend.env -Restart=on-failure -RestartSec=2 - -[Install] -WantedBy=default.target diff --git a/deploy/hezarfen_backend.env.example b/deploy/hezarfen_backend.env.example new file mode 100644 index 0000000..63b3141 --- /dev/null +++ b/deploy/hezarfen_backend.env.example @@ -0,0 +1,67 @@ +# hezarfen_backend.env — production secrets for the podman compose stack. +# +# One-time setup ON THE VPS, by hand: +# mkdir -p ~/hezarfen_backend +# cp hezarfen_backend.env.example ~/hezarfen_backend/hezarfen_backend.env +# +# chmod 0600 ~/hezarfen_backend/hezarfen_backend.env +# +# The deploy NEVER creates, overwrites, or uploads this file — the operator +# owns it; compose only reads it (compose --env-file, plus env_file into the +# backend container). Plain KEY=value lines: no quotes, no `export`. +# +# POSTGRES_*/BUILDER_*/ZO_*/AI_* are ALSO compose interpolations (the stack +# file builds DATABASE_URL and the postgres/openobserve config from them). +# Every other key (COOKIE_SECURE, TRUST_PROXY, CORS_*, RATE_LIMIT_*, OTEL_*, +# DEPLOY_ENV) is passed into the backend container verbatim via env_file. + +# ── Postgres (first boot) ──────────────────────────────────────────────────── +# POSTGRES_PASSWORD is baked into the pgdata volume on the FIRST `compose up`; +# changing it here later does NOT re-key the database. Set the real password +# BEFORE the first production start. It is interpolated into DATABASE_URL, so +# it must be URL-safe: no `@`, `:`, or `/`. +POSTGRES_USER=hezarfen +POSTGRES_PASSWORD= +POSTGRES_DB=hezarfen_control + +# ── First-boot builder (operator) account ──────────────────────────────────── +# Seeded once on boot if the username doesn't exist; existing accounts are +# never promoted to builder or re-keyed (resolve conflicts by hand). +BUILDER_USERNAME=builder +BUILDER_PASSWORD= + +# ── HTTP posture ───────────────────────────────────────────────────────────── +# Session-cookie Secure flag: true (the stack sits behind a TLS reverse proxy). +COOKIE_SECURE=true +# Derive client IPs from X-Forwarded-For behind the reverse proxy: true. +TRUST_PROXY=true +# Browser origins allowed to send the credentialed session cookie, +# comma-separated. A lone `*` mirrors EVERY origin with credentials — list the +# real frontends once known. +CORS_ALLOWED_ORIGINS= + +# ── AI bridge (QUIC over UDP 8090) ─────────────────────────────────────────── +# Empty overrides the laptop compose default (0.0.0.0:8090 / change-me) and +# keeps the bridge off. Set BOTH to enable; address without token fails boot. +AI_QUIC_ADDR= +AI_SHARED_TOKEN= +# Per-request deadline; defaults to 30s. Anything above the 300s stale-answer +# horizon is clamped down at startup. +#AI_REQUEST_TIMEOUT_SECS=30 + +# ── Telemetry (OpenObserve over OTLP) ──────────────────────────────────────── +# Leave commented to keep export off (stdout logs only). Uncomment after +# ZO_ROOT_USER_* below are set; Authorization is +# base64(":"): +# printf '%s:%s' 'admin@example.com' 'PASSWORD' | base64 +#OTEL_EXPORTER_OTLP_ENDPOINT=http://openobserve:5081 +#OTEL_EXPORTER_OTLP_HEADERS=Authorization=Basic ,organization=default,stream-name=default +#OTEL_SERVICE_NAME=hezarfen-backend +# Names the deployment in every exported signal. +#DEPLOY_ENV=production + +# ── OpenObserve root account (first boot) ──────────────────────────────────── +# OpenObserve enforces a password policy — 8-128 chars, upper + lower + digit +# + special — and panics on boot otherwise. +ZO_ROOT_USER_EMAIL= +ZO_ROOT_USER_PASSWORD= diff --git a/migrations/control/20260912000001_control.sql b/migrations/control/20260912000001_control.sql index cbc8400..b2a5157 100644 --- a/migrations/control/20260912000001_control.sql +++ b/migrations/control/20260912000001_control.sql @@ -12,9 +12,10 @@ -- default); timestamps stay BIGINT unix-ms. All FKs are ON DELETE NO ACTION — -- cascades stay explicit application transactions. -- --- Renames (reserved words, never quoted): table `school` keeps its name (its --- Surreal record id WAS the slug, so slug is the PRIMARY KEY, constraint --- carrying the old index name school_slug). +-- Renames (reserved words, never quoted): table `school` keeps its name. Its +-- Surreal record id WAS the slug; the Postgres table instead carries an +-- app-minted uuid PRIMARY KEY (`id`) so the slug is a renameable label, with +-- the old PK index name `school_slug` kept as the UNIQUE constraint on slug. -- -- `rate_limit` exists ONLY here, not in the school schema: rate limiting is -- billed against the control handle before any cookie names a school (see the @@ -23,17 +24,25 @@ -- `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. + -- Surrogate identity, app-minted uuid v7 (no DB default): the per-school + -- database name is minted from it (see tenant::school_db_name), so a slug + -- rename — once offered — can never orphan a database. Immutable keys + -- belong to the uuid, never to the label. + id uuid PRIMARY KEY, slug TEXT NOT NULL, name TEXT NOT NULL, 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. - modules TEXT[] NOT NULL DEFAULT '{}', - CONSTRAINT school_slug PRIMARY KEY (slug) + CONSTRAINT school_slug UNIQUE (slug) +); + +-- One row per product module the school has bought; names bound from +-- Module::ALL at write time, never spelled here. The pair is the key: the +-- membership is the link, and a read joins it back onto the school row. +CREATE TABLE school_module ( + school uuid NOT NULL REFERENCES school(id) ON DELETE NO ACTION, + module TEXT NOT NULL, + PRIMARY KEY (school, module) ); CREATE TABLE builder ( diff --git a/migrations/control/20260913000001_person.sql b/migrations/control/20260913000001_person.sql index 47054bb..c41582d 100644 --- a/migrations/control/20260913000001_person.sql +++ b/migrations/control/20260913000001_person.sql @@ -27,7 +27,9 @@ 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, + -- Points at the school's uuid identity, not its slug: the slug is a + -- renameable label, and a membership must survive one. + school uuid NOT NULL REFERENCES school(id) ON DELETE NO ACTION, created_at BIGINT NOT NULL, CONSTRAINT person_school_person_school PRIMARY KEY (person, school) ); diff --git a/migrations/school/20260912000001_identity.sql b/migrations/school/20260912000001_identity.sql index 50d65b2..5d3bcd2 100644 --- a/migrations/school/20260912000001_identity.sql +++ b/migrations/school/20260912000001_identity.sql @@ -195,7 +195,6 @@ CREATE TABLE board ( id uuid PRIMARY KEY, creator uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, title TEXT NOT NULL, - participants uuid[] NOT NULL DEFAULT '{}', locked BOOLEAN NOT NULL DEFAULT false, locked_by uuid NULL REFERENCES app_user(id) ON DELETE NO ACTION, locked_at BIGINT NULL, @@ -207,9 +206,20 @@ CREATE TABLE board ( ); CREATE INDEX board_creator ON board (creator); --- The board list asks `creator = $u OR participants CONTAINS $u`; the GIN --- index covers the membership half ($1 = ANY(participants) at query sites). -CREATE INDEX board_participants ON board USING GIN (participants); + +-- The roster, one row per (board, invited user). The membership predicate +-- everywhere is `creator = $u OR EXISTS (… WHERE participant = $u)` over +-- this table; the participant-side index is what the board list, the +-- demotion strip in src/db/user.rs and the cap checks read through. Rows +-- carry no order: every reader sorts by participant, so the assembled +-- roster is deterministic. +CREATE TABLE board_participant ( + board uuid NOT NULL REFERENCES board(id) ON DELETE NO ACTION, + participant uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + CONSTRAINT board_participant_board_participant PRIMARY KEY (board, participant) +); + +CREATE INDEX board_participant_participant ON board_participant (participant); CREATE TABLE board_stroke ( id uuid PRIMARY KEY, @@ -256,20 +266,34 @@ CREATE INDEX chatbot_message_user ON chatbot_message (user_id); CREATE INDEX chatbot_message_status_created ON chatbot_message (status, created_at); CREATE TABLE settings ( - -- Singleton row: id = 'school'. id TEXT PRIMARY KEY, exam_kinds JSONB NOT NULL, - attendance_statuses TEXT[] NOT NULL, grade_bands JSONB NOT NULL, max_file_bytes BIGINT NULL, chatbot_history_turns BIGINT NULL, max_chatbot_message_len BIGINT NULL, max_chatbot_threads BIGINT NULL, meal_slots JSONB NULL, - dietary_tags TEXT[] NULL, meal_cancel_cutoff_minutes BIGINT NULL ); +-- The settings singleton's two vocabulary lists, one row per entry. They +-- replace TEXT[] columns; the compare-and-set guard in src/db/settings.rs +-- compares these row *sets*, so nothing here carries order — every reader +-- sorts, and an absent set (never configured) and an explicitly empty one +-- both read as zero rows. +CREATE TABLE settings_attendance_status ( + settings TEXT NOT NULL REFERENCES settings(id) ON DELETE NO ACTION, + status TEXT NOT NULL, + CONSTRAINT settings_attendance_status_settings_status PRIMARY KEY (settings, status) +); + +CREATE TABLE settings_dietary_tag ( + settings TEXT NOT NULL REFERENCES settings(id) ON DELETE NO ACTION, + tag TEXT NOT NULL, + CONSTRAINT settings_dietary_tag_settings_tag PRIMARY KEY (settings, tag) +); + -- Reference counters, one row per *name* the settings offer. Created by the -- first claim; an absent row reads as zero references, in service. CREATE TABLE kind_ref ( diff --git a/migrations/school/20260912000002_courses.sql b/migrations/school/20260912000002_courses.sql index 1bfae7a..5a3ac95 100644 --- a/migrations/school/20260912000002_courses.sql +++ b/migrations/school/20260912000002_courses.sql @@ -33,15 +33,14 @@ CREATE TABLE term ( -- 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 +-- notes, class_course links (each class gets its class_course_count back), +-- blueprint_course and course_teacher links, 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, - teachers uuid[] NOT NULL DEFAULT '{}', title TEXT NOT NULL, description TEXT NOT NULL, kind TEXT NOT NULL DEFAULT 'course', @@ -49,9 +48,20 @@ CREATE TABLE course ( capacity BIGINT NULL, enrollment_count BIGINT NOT NULL DEFAULT 0 ); --- No GIN on teachers, faithful to the Surreal schema: the teachers-membership --- read stays a scan, exactly as today (see src/db/course.rs — the Surreal --- per-element index form returned zero rows and was never defined). + +-- The staff a manager assigned to run a course. The old `teachers uuid[]` on +-- the course row is a junction now, like enrollment: membership is a row with +-- a foreign key, so an assigned user is a real reference (no dangling id a +-- demotion sweep or a delete can strand), the membership read is an index +-- lookup instead of an array scan, and "assigned to a course that is gone" is +-- unrepresentable rather than swept. +CREATE TABLE course_teacher ( + course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION, + teacher uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + CONSTRAINT course_teacher_course_teacher PRIMARY KEY (course, teacher) +); + +CREATE INDEX course_teacher_teacher ON course_teacher (teacher); CREATE TABLE subject ( id uuid PRIMARY KEY, @@ -91,15 +101,24 @@ CREATE TABLE rag_output ( id uuid PRIMARY KEY, course_note uuid NOT NULL REFERENCES course_note(id) ON DELETE NO ACTION, course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION, - sources uuid[] NOT NULL DEFAULT '{}', payload JSONB NOT NULL, generated_at BIGINT NOT NULL ); CREATE INDEX rag_output_note ON rag_output (course_note); --- The source cascade asks `sources CONTAINS $file`; the GIN index makes it a --- lookup instead of a scan. -CREATE INDEX rag_output_source ON rag_output USING GIN (sources); + +-- Citations: which course-note files an output was built from, as link rows +-- with real foreign keys rather than an array column. A file delete sweeps +-- the links that cite it before the file row goes, and deleting an output +-- sweeps its links before the output row does — `ON DELETE NO ACTION` makes +-- the refusal (23503) the backstop if a sweep is forgotten. +CREATE TABLE rag_output_source ( + output uuid NOT NULL REFERENCES rag_output(id) ON DELETE NO ACTION, + source uuid NOT NULL REFERENCES course_note_file(id) ON DELETE NO ACTION, + CONSTRAINT rag_output_source_output_source PRIMARY KEY (output, source) +); + +CREATE INDEX rag_output_source_source ON rag_output_source (source); CREATE TABLE course_session ( id uuid PRIMARY KEY, @@ -150,10 +169,24 @@ CREATE INDEX class_group_grade ON class_group (grade); CREATE TABLE class_blueprint ( 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 ); +-- A template's course list. The old `courses uuid[]` on the blueprint row is +-- a junction now, like the class_course links it pumps: a course in a +-- template is a foreign-keyed row, so the course delete's own cascade takes +-- the link out (no dangling id a prune had to chase), the compare-and-set +-- edits compare row sets, and the grade-with-no-sections case loses its dead +-- course for free. +CREATE TABLE blueprint_course ( + blueprint uuid NOT NULL REFERENCES class_blueprint(id) ON DELETE NO ACTION, + course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION, + CONSTRAINT blueprint_course_blueprint_course PRIMARY KEY (blueprint, course) +); + +-- The course delete's sweep strikes the link by course. +CREATE INDEX blueprint_course_course ON blueprint_course (course); + CREATE TABLE class_member ( class uuid NOT NULL REFERENCES class_group(id) ON DELETE NO ACTION, app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, diff --git a/migrations/school/20260912000003_exams.sql b/migrations/school/20260912000003_exams.sql index f3285fd..6bc549d 100644 --- a/migrations/school/20260912000003_exams.sql +++ b/migrations/school/20260912000003_exams.sql @@ -215,14 +215,24 @@ CREATE TABLE homework ( title TEXT NOT NULL, description TEXT NULL, due_at BIGINT NOT NULL, - -- NULL/empty means the whole course. - assigned uuid[] NOT NULL DEFAULT '{}', created_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, created_at BIGINT NOT NULL ); CREATE INDEX homework_course ON homework (course); +-- The audience of a homework: no rows = the whole course (whoever is enrolled +-- when they submit — later enrollees included); rows name the student subset, +-- a fixed snapshot taken at assign (or last PATCH) time. NO ACTION orders the +-- deletes: these rows go before the homework they scope. +CREATE TABLE homework_assignment ( + homework uuid NOT NULL REFERENCES homework(id) ON DELETE NO ACTION, + student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, + CONSTRAINT homework_assignment_homework_student PRIMARY KEY (homework, student) +); + +CREATE INDEX homework_assignment_student ON homework_assignment (student); + CREATE TABLE homework_result ( id uuid PRIMARY KEY, homework uuid NOT NULL REFERENCES homework(id) ON DELETE NO ACTION, diff --git a/migrations/school/20260912000004_food_appointments_fees.sql b/migrations/school/20260912000004_food_appointments_fees.sql index 87ee8cd..070a41a 100644 --- a/migrations/school/20260912000004_food_appointments_fees.sql +++ b/migrations/school/20260912000004_food_appointments_fees.sql @@ -95,21 +95,41 @@ CREATE TABLE menu_dish ( description TEXT NULL, -- Money is minor units (kuruş) as an integer, everywhere. Never decimal. price_minor BIGINT NOT NULL, - tags TEXT[] NOT NULL DEFAULT '{}', created_at BIGINT NOT NULL ); CREATE INDEX menu_dish_menu ON menu_dish (menu); +-- The dish's dietary tags, one row each (was a TEXT[] column). `ord` keeps +-- the order the kitchen gave the list in: a profile intersection reports +-- conflicts in dish-tag order. Deleting a dish sweeps these rows first — +-- the FK is NO ACTION. +CREATE TABLE menu_dish_tag ( + dish uuid NOT NULL REFERENCES menu_dish(id) ON DELETE NO ACTION, + tag TEXT NOT NULL, + ord SMALLINT NOT NULL, + CONSTRAINT menu_dish_tag_dish_tag PRIMARY KEY (dish, tag) +); + CREATE TABLE dietary_profile ( student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, - tags TEXT[] NOT NULL DEFAULT '{}', note TEXT NULL, updated_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, updated_at BIGINT NOT NULL, CONSTRAINT dietary_profile_student PRIMARY KEY (student) ); +-- The student's dietary tags, one row each (was a TEXT[] column): the same +-- vocabulary and the same `ord` order-preservation as menu_dish_tag. The +-- profile is the parent (no app_user FK of its own), so a tag exists only +-- while its profile row stands. +CREATE TABLE dietary_profile_tag ( + student uuid NOT NULL REFERENCES dietary_profile(student) ON DELETE NO ACTION, + tag TEXT NOT NULL, + ord SMALLINT NOT NULL, + CONSTRAINT dietary_profile_tag_student_tag PRIMARY KEY (student, tag) +); + -- A cancel flips `status` and stamps `cancelled_at`; the row stays so the -- freed seat is still auditable against the ledger line it charged. CREATE TABLE meal_booking ( diff --git a/src/database.rs b/src/database.rs index 80887de..86795ae 100644 --- a/src/database.rs +++ b/src/database.rs @@ -28,7 +28,7 @@ use crate::domain::timestamp::Timestamp; use crate::domain::user::{Password, Username}; use crate::error::AppError; use crate::module::ModuleSet; -use crate::tenant::{DEMO_SLUG, SchoolStatus, Slug, Tenants, school_db_name}; +use crate::tenant::{DEMO_SLUG, SchoolId, SchoolStatus, Tenants, school_db_name}; /// The shared database handle. /// @@ -134,9 +134,10 @@ pub(crate) async fn school_pool( /// A `CREATE DATABASE` / `DROP DATABASE` statement for a quoted identifier. /// The names passed here are the control database's name (from /// `DATABASE_URL`), the template's (`{control}_school_template`) or -/// [`crate::tenant::school_db_name`]'s output — never user input: the slug -/// charset is `[a-z0-9-]` and an embedded quote is doubled, so the statement -/// cannot be escaped from. That manual audit is what licenses the +/// [`crate::tenant::school_db_name`]'s output — never user input: the control +/// and template names come from configuration, the school name from a uuid's +/// hex (fixed `[0-9a-f]`), and an embedded quote is doubled besides, so the +/// statement cannot be escaped from. That manual audit is what licenses the /// `AssertSqlSafe` wrapper every caller applies (sqlx refuses non-literal /// query strings without it). pub(crate) fn create_database_sql(statement: &str, name: &str) -> String { @@ -451,7 +452,7 @@ fn builder_credentials(cfg: &Config) -> Result, App // // Every test run gets a **private pair of databases** on the compose Postgres: // a control database and the demo school's database, both named after one -// random suffix — `heztest_<16 hex>` and `heztest_<…>_school_demo` — so +// random suffix — `heztest_<16 hex>` and `heztest_<…>_school_` — so // nextest's parallel processes neither collide nor see each other's rows. The // school schema is not migrated per test: it is cloned from a shared template // database whose name carries a hash of `migrations/school`, so a schema edit @@ -612,9 +613,8 @@ pub async fn init_test_tenants() -> Tenants { .unwrap_or_else(|err| panic!("migrate the test control database {control_db}: {err}")); let template = ensure_test_template(&maintenance, &base).await; - - let demo = Slug::try_new(DEMO_SLUG).expect("the demo slug"); - let school_db = school_db_name(&control_db, &demo); + let demo_id = SchoolId::generate(); + let school_db = school_db_name(&control_db, demo_id.uuid()); create_database(&maintenance, &school_db, Some(&template)).await; lease.track(&school_db); let school = school_pool(&base, &school_db) @@ -625,24 +625,32 @@ pub async fn init_test_tenants() -> Tenants { // without the per-school migration its `bring_up` runs, which the // template clone has just replaced. sqlx::query( - "INSERT INTO school (slug, name, status, created_at, modules) + "INSERT INTO school (id, slug, name, status, created_at) VALUES ($1, $2, $3, $4, $5)", ) + .bind(demo_id.uuid()) .bind(DEMO_SLUG) .bind("Demo School") .bind(SchoolStatus::Active) .bind(Timestamp::now().as_millis()) - .bind(ModuleSet::all().names()) .execute(&control) .await .expect("register the test demo school"); + for module in ModuleSet::all().names() { + sqlx::query("INSERT INTO school_module (school, module) VALUES ($1, $2)") + .bind(demo_id.uuid()) + .bind(module) + .execute(&control) + .await + .expect("register the test demo school's modules"); + } Tenants::new_test_adopting( control, base.database(&control_db), control_db, lease, - [(demo, school)], + [(demo_id, school)], ) } diff --git a/src/db/board.rs b/src/db/board.rs index f7c3ef1..964faca 100644 --- a/src/db/board.rs +++ b/src/db/board.rs @@ -28,26 +28,40 @@ pub async fn create( closed_at: None, created_at: Timestamp::now(), }; - // The seat claim and the row are one statement (the `cap::claim_and_create` - // CTE, spelled out at its call site): a refused insert takes its own - // seat bump back, so the counter can never count a row that did not commit. + // The seat claim, the row and the roster are one statement (the + // `cap::claim_and_create` CTE, spelled out at its call site): a refused + // insert takes its own seat bump back, so the counter can never count a + // row that did not commit, and the roster can never trail the row. The + // `participants` array is aggregated from the roster CTE's RETURNING — + // the statement cannot see its own writes to `board_participant`. let saved = sqlx::query_as!( Board, r#"WITH seat AS ( UPDATE app_user SET board_count = board_count + 1 WHERE id = $1 AND board_count < $2 - RETURNING 1) - INSERT INTO board (id, creator, title, participants, locked, locked_by, locked_at, - epoch, closed_at, created_at) - SELECT $3, $1, $4, $5, false, NULL, NULL, 0, NULL, $6 - WHERE EXISTS (SELECT 1 FROM seat) - RETURNING id AS "id: BoardId", creator AS "creator: UserId", - title AS "title: BoardTitle", - participants AS "participants: Vec", locked, - locked_by AS "locked_by: UserId", - locked_at AS "locked_at: Timestamp", epoch, - closed_at AS "closed_at: Timestamp", - created_at AS "created_at: Timestamp""#, + RETURNING 1), + new_board AS ( + INSERT INTO board (id, creator, title, locked, locked_by, locked_at, + epoch, closed_at, created_at) + SELECT $3, $1, $4, false, NULL, NULL, 0, NULL, $6 + WHERE EXISTS (SELECT 1 FROM seat) + RETURNING id, creator, title, locked, locked_by, locked_at, + epoch, closed_at, created_at), + roster AS ( + INSERT INTO board_participant (board, participant) + SELECT $3, t.x FROM unnest($5::uuid[]) AS t(x) + WHERE EXISTS (SELECT 1 FROM new_board) + RETURNING participant) + SELECT nb.id AS "id: BoardId", nb.creator AS "creator: UserId", + nb.title AS "title: BoardTitle", + COALESCE((SELECT array_agg(r.participant ORDER BY r.participant) + FROM roster r), '{}') + AS "participants!: Vec", + nb.locked, nb.locked_by AS "locked_by: UserId", + nb.locked_at AS "locked_at: Timestamp", nb.epoch, + nb.closed_at AS "closed_at: Timestamp", + nb.created_at AS "created_at: Timestamp" + FROM new_board nb"#, board.creator.uuid(), MAX_BOARDS_PER_CREATOR, board.id.uuid(), @@ -77,17 +91,26 @@ pub async fn create( } } -pub async fn read(db: &Database, id: &BoardId) -> Result, AppError> { +/// The one board read: row columns plus the roster, re-assembled from +/// `board_participant` (the array column is gone). The junction keeps no +/// insertion order, so every reader sorts by participant and the wire list +/// is deterministic. +async fn read_row<'e, E>(db: E, id: &BoardId) -> Result, AppError> +where + E: sqlx::PgExecutor<'e>, +{ let board = sqlx::query_as!( Board, - r#"SELECT id AS "id: BoardId", creator AS "creator: UserId", - title AS "title: BoardTitle", - participants AS "participants: Vec", locked, - locked_by AS "locked_by: UserId", - locked_at AS "locked_at: Timestamp", epoch, - closed_at AS "closed_at: Timestamp", - created_at AS "created_at: Timestamp" - FROM board WHERE id = $1"#, + r#"SELECT b.id AS "id: BoardId", b.creator AS "creator: UserId", + b.title AS "title: BoardTitle", + ARRAY(SELECT p.participant FROM board_participant p + WHERE p.board = b.id ORDER BY p.participant) + AS "participants!: Vec", + b.locked, b.locked_by AS "locked_by: UserId", + b.locked_at AS "locked_at: Timestamp", b.epoch, + b.closed_at AS "closed_at: Timestamp", + b.created_at AS "created_at: Timestamp" + FROM board b WHERE b.id = $1"#, id.uuid() ) .fetch_optional(db) @@ -95,6 +118,10 @@ pub async fn read(db: &Database, id: &BoardId) -> Result, AppError Ok(board) } +pub async fn read(db: &Database, id: &BoardId) -> Result, AppError> { + read_row(db, id).await +} + /// Every board `user` may open: the ones they created and the ones they /// were invited to. Newest first — the ids are monotonic, so `id` is the /// creation order. @@ -111,12 +138,26 @@ pub async fn list_for_user( offset: i64, ) -> Result<(Vec, i64), AppError> { let open_clause = match open { - Some(true) => " AND closed_at IS NULL", - Some(false) => " AND closed_at IS NOT NULL", + Some(true) => " AND b.closed_at IS NULL", + Some(false) => " AND b.closed_at IS NOT NULL", None => "", }; + // `PagedList` wraps `from_where` in `SELECT * FROM (…)`, so the window + // is a whole derived table: the row columns plus the roster + // re-assembled from `board_participant`, and the membership half of the + // predicate as an `EXISTS` over it (the participant-side index covers + // it, as the GIN index once did). PagedList::new( - format!("board WHERE (creator = $1 OR $2 = ANY(participants)){open_clause}"), + format!( + "(SELECT b.id, b.creator, b.title, + ARRAY(SELECT p.participant FROM board_participant p + WHERE p.board = b.id ORDER BY p.participant) AS participants, + b.locked, b.locked_by, b.locked_at, b.epoch, b.closed_at, b.created_at + FROM board b + WHERE (b.creator = $1 + OR EXISTS (SELECT 1 FROM board_participant bp + WHERE bp.board = b.id AND bp.participant = $2)){open_clause})" + ), "ORDER BY id DESC", ) .bind(user.uuid()) @@ -125,33 +166,38 @@ pub async fn list_for_user( .await } -/// Re-invite. Field-scoped, like every write here: a stroke landing -/// concurrently is moving the counters this struct does not carry. +/// Re-invite: the creator-driven roster replace. The write is the +/// junction's — rows go in one transaction with the read-back, because the +/// old single `UPDATE` both wrote the array and returned the row; a read +/// issued apart from the write could answer a roster someone else had +/// replaced in between. pub async fn set_participants( db: &Database, board: &Board, participants: Vec, ) -> Result { let participants = checked_participants(participants)?; - let updated = sqlx::query_as!( - Board, - r#"UPDATE board SET participants = $2 WHERE id = $1 - RETURNING id AS "id: BoardId", creator AS "creator: UserId", - title AS "title: BoardTitle", - participants AS "participants: Vec", locked, - locked_by AS "locked_by: UserId", - locked_at AS "locked_at: Timestamp", epoch, - closed_at AS "closed_at: Timestamp", - created_at AS "created_at: Timestamp""#, - board.id.uuid(), - &participants - .iter() - .map(UserId::uuid) - .collect::>() - ) - .fetch_optional(db) - .await?; - one(updated) + let ids: Vec = participants.iter().map(UserId::uuid).collect(); + let id = board.id.clone(); + tx_with_retry(db, true, async move |tx| { + sqlx::query!("DELETE FROM board_participant WHERE board = $1", id.uuid()) + .execute(&mut *tx) + .await?; + sqlx::query!( + "INSERT INTO board_participant (board, participant) + SELECT $1, t.x FROM unnest($2::uuid[]) AS t(x) + ON CONFLICT DO NOTHING", + id.uuid(), + &ids, + ) + .execute(&mut *tx) + .await?; + // The read-back is under the write path's own transaction: None here + // means the board vanished between the caller's read and this tx, + // which is the same 404 the old `UPDATE … RETURNING` produced. + read_row(&mut *tx, &id).await?.ok_or(AppError::NotFound) + }) + .await } pub async fn set_title(db: &Database, board: &Board, title: BoardTitle) -> Result { @@ -160,7 +206,9 @@ pub async fn set_title(db: &Database, board: &Board, title: BoardTitle) -> Resul r#"UPDATE board SET title = $2 WHERE id = $1 RETURNING id AS "id: BoardId", creator AS "creator: UserId", title AS "title: BoardTitle", - participants AS "participants: Vec", locked, + ARRAY(SELECT p.participant FROM board_participant p + WHERE p.board = board.id ORDER BY p.participant) + AS "participants!: Vec", locked, locked_by AS "locked_by: UserId", locked_at AS "locked_at: Timestamp", epoch, closed_at AS "closed_at: Timestamp", @@ -187,7 +235,9 @@ pub async fn set_locked( r#"UPDATE board SET locked = $2, locked_by = $3, locked_at = $4 WHERE id = $1 RETURNING id AS "id: BoardId", creator AS "creator: UserId", title AS "title: BoardTitle", - participants AS "participants: Vec", locked, + ARRAY(SELECT p.participant FROM board_participant p + WHERE p.board = board.id ORDER BY p.participant) + AS "participants!: Vec", locked, locked_by AS "locked_by: UserId", locked_at AS "locked_at: Timestamp", epoch, closed_at AS "closed_at: Timestamp", @@ -202,13 +252,14 @@ pub async fn set_locked( one(updated) } -/// Union a bulk invite's resolved ids into the roster — the atomic-array -/// replacement for the old process-wide roster lock. The merge and the -/// participant cap are one guarded statement: `SET` and `WHERE` both read -/// the row version this `UPDATE` is acting on, so of two concurrent invites -/// each sees the other's committed roster and the cap refuses the second — -/// neither can drop the other's group, which is what the lock existed to -/// prevent. +/// Union a bulk invite's resolved ids into the roster — the atomic-union +/// replacement for the old process-wide roster lock. The merge is `INSERT +/// … ON CONFLICT DO NOTHING`, and the board row is locked (`FOR NO KEY +/// UPDATE`) before the cap counts: that lock is what the old guarded array +/// `UPDATE` got from its own row write, and it keeps the same property — +/// of two concurrent invites the second waits, counts against the first's +/// committed roster, and the cap refuses it — neither can drop the other's +/// group. /// /// `None` means the guard refused (or the board is gone): the roster was /// left exactly as it was, and the caller re-reads to pick the message. @@ -217,31 +268,46 @@ pub(crate) async fn invite_group( board: &BoardId, invited: Vec, ) -> Result, AppError> { - let updated = sqlx::query_as!( - Board, - r#"UPDATE board - SET participants = (SELECT coalesce(array_agg(DISTINCT x), '{}') - FROM unnest(participants || $2::uuid[]) AS x) - WHERE id = $1 - AND cardinality((SELECT coalesce(array_agg(DISTINCT x), '{}') - FROM unnest(participants || $2::uuid[]) AS x)) <= $3 - RETURNING id AS "id: BoardId", creator AS "creator: UserId", - title AS "title: BoardTitle", - participants AS "participants: Vec", locked, - locked_by AS "locked_by: UserId", - locked_at AS "locked_at: Timestamp", epoch, - closed_at AS "closed_at: Timestamp", - created_at AS "created_at: Timestamp""#, - board.uuid(), - &invited - .iter() - .map(UserId::uuid) - .collect::>(), - MAX_BOARD_PARTICIPANTS as i64 - ) - .fetch_optional(db) - .await?; - Ok(updated) + let invited: Vec = invited.iter().map(UserId::uuid).collect(); + let board = board.clone(); + tx_with_retry(db, true, async move |tx| { + // The serialization point; a vanished board refuses here, exactly + // like the old conditional `UPDATE` matching nothing. + let live = sqlx::query!( + "SELECT id FROM board WHERE id = $1 FOR NO KEY UPDATE", + board.uuid() + ) + .fetch_optional(&mut *tx) + .await?; + if live.is_none() { + return Ok(None); + } + let would_be: i64 = sqlx::query_scalar!( + r#"SELECT ((SELECT count(*) FROM board_participant WHERE board = $1) + + (SELECT count(*) FROM unnest($2::uuid[]) AS t(x) + WHERE NOT EXISTS (SELECT 1 FROM board_participant bp + WHERE bp.board = $1 AND bp.participant = t.x))) + AS "filled!""#, + board.uuid(), + &invited, + ) + .fetch_one(&mut *tx) + .await?; + if would_be > MAX_BOARD_PARTICIPANTS as i64 { + return Ok(None); + } + sqlx::query!( + "INSERT INTO board_participant (board, participant) + SELECT $1, t.x FROM unnest($2::uuid[]) AS t(x) + ON CONFLICT DO NOTHING", + board.uuid(), + &invited, + ) + .execute(&mut *tx) + .await?; + read_row(&mut *tx, &board).await + }) + .await } // The demotion sweep — stripping a user off every roster they are listed @@ -258,7 +324,9 @@ pub async fn close(db: &Database, board: &Board) -> Result { r#"UPDATE board SET closed_at = $2 WHERE id = $1 AND closed_at IS NULL RETURNING id AS "id: BoardId", creator AS "creator: UserId", title AS "title: BoardTitle", - participants AS "participants: Vec", locked, + ARRAY(SELECT p.participant FROM board_participant p + WHERE p.board = board.id ORDER BY p.participant) + AS "participants!: Vec", locked, locked_by AS "locked_by: UserId", locked_at AS "locked_at: Timestamp", epoch, closed_at AS "closed_at: Timestamp", @@ -280,12 +348,17 @@ pub async fn close(db: &Database, board: &Board) -> Result { /// transaction — a release issued afterwards can be lost, and the counter /// would then ratchet the creator's limit shut forever. /// -/// The stroke cascade rides in that same transaction: it is the one and -/// only legitimate delete of `board_stroke` rows (a clear deletes nothing), -/// and issued separately it could leave a board's whole history orphaned -/// under a record that no longer exists. +/// The roster and the stroke cascade ride in that same transaction: the FK +/// is NO ACTION, so the junction rows go before the board row they name, +/// and the stroke delete is the one and only legitimate delete of +/// `board_stroke` rows (a clear deletes nothing) — issued separately it +/// could leave a board's whole history orphaned under a record that no +/// longer exists. pub async fn delete(db: &Database, board: Board) -> Result { tx_with_retry(db, true, async move |conn| { + sqlx::query!("DELETE FROM board_participant WHERE board = $1", board.id.uuid()) + .execute(&mut *conn) + .await?; sqlx::query!("DELETE FROM board_stroke WHERE board = $1", board.id.uuid()) .execute(&mut *conn) .await?; @@ -294,7 +367,9 @@ pub async fn delete(db: &Database, board: Board) -> Result { r#"DELETE FROM board WHERE id = $1 RETURNING id AS "id: BoardId", creator AS "creator: UserId", title AS "title: BoardTitle", - participants AS "participants: Vec", locked, + ARRAY(SELECT p.participant FROM board_participant p + WHERE p.board = board.id ORDER BY p.participant) + AS "participants!: Vec", locked, locked_by AS "locked_by: UserId", locked_at AS "locked_at: Timestamp", epoch, closed_at AS "closed_at: Timestamp", diff --git a/src/db/board_stroke.rs b/src/db/board_stroke.rs index 6332b1e..d1a5089 100644 --- a/src/db/board_stroke.rs +++ b/src/db/board_stroke.rs @@ -176,7 +176,9 @@ pub async fn clear(db: &Database, board: &BoardId, by: &UserId) -> Result", locked, + ARRAY(SELECT p.participant FROM board_participant p + WHERE p.board = board.id ORDER BY p.participant) + AS "participants!: Vec", locked, locked_by AS "locked_by: UserId", locked_at AS "locked_at: Timestamp", epoch, closed_at AS "closed_at: Timestamp", diff --git a/src/db/class_blueprint.rs b/src/db/class_blueprint.rs index 223bf8c..de63fa5 100644 --- a/src/db/class_blueprint.rs +++ b/src/db/class_blueprint.rs @@ -6,6 +6,8 @@ use sqlx::postgres::PgConnection; +use std::collections::HashMap; + use crate::constant::CLASS_BLUEPRINT_TABLE; use crate::database::{Database, tx_with_retry, unique_violation}; use crate::db::class_pump; @@ -17,6 +19,86 @@ use crate::domain::monotonic_id::next_uuid; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; +/// The stored columns of one `class_blueprint` row. A template's course list +/// is *not* one of them — it lives across the `blueprint_course` junction and +/// is joined on in a batch after the read ([`with_courses`]), because the +/// paged list here reads whole rows (`SELECT *`), a shape no aggregate column +/// can ride. +#[derive(Debug, sqlx::FromRow)] +struct BlueprintRow { + /// The surrogate uuid primary key — the key the junction rows reference. + #[sqlx(rename = "id")] + key: uuid::Uuid, + grade: ClassGrade, + creator: UserId, +} + +impl BlueprintRow { + fn into_blueprint(self, courses: Vec) -> ClassBlueprint { + ClassBlueprint { + // The API identity is the grade label, which the key column also + // stores — the id *is* the grade. + id: ClassBlueprintId::for_grade(&self.grade), + grade: self.grade, + courses, + creator: self.creator, + } + } +} + +/// The stored course list of one blueprint, sorted by course. Every read goes +/// through this ordering, which is what makes the compare-and-set below a +/// plain vector comparison: both sides of it are junction reads. +async fn junction_courses<'e, E>( + executor: E, + blueprint: uuid::Uuid, +) -> Result, AppError> +where + E: sqlx::PgExecutor<'e>, +{ + let rows = sqlx::query!( + r#"SELECT course AS "course: CourseId" FROM blueprint_course + WHERE blueprint = $1 ORDER BY course"#, + blueprint, + ) + .fetch_all(executor) + .await?; + Ok(rows.into_iter().map(|row| row.course).collect()) +} + +/// Join the stored course lists onto a batch of blueprint rows, one junction +/// read for the lot. +async fn with_courses( + db: &Database, + rows: Vec, +) -> Result, AppError> { + if rows.is_empty() { + return Ok(Vec::new()); + } + let keys: Vec = rows.iter().map(|row| row.key).collect(); + let links = sqlx::query!( + r#"SELECT blueprint, course AS "course: CourseId" FROM blueprint_course + WHERE blueprint = ANY($1) ORDER BY blueprint, course"#, + &keys, + ) + .fetch_all(db) + .await?; + let mut by_blueprint: HashMap> = HashMap::new(); + for link in links { + by_blueprint + .entry(link.blueprint) + .or_default() + .push(link.course); + } + Ok(rows + .into_iter() + .map(|row| { + let courses = by_blueprint.remove(&row.key).unwrap_or_default(); + row.into_blueprint(courses) + }) + .collect()) +} + /// One `class_course` row, projected down to the pair that answers "does this /// section carry that course". `source` is deliberately not read: a link of any #[derive(Debug, sqlx::FromRow)] @@ -67,11 +149,12 @@ 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 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 +/// Write the blueprint's row — and its `blueprint_course` rows, in the same +/// transaction, under the same per-course proof ([`courses_alive`]). A second +/// blueprint for the same grade is a 409 the 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, @@ -90,17 +173,27 @@ pub async fn create( tx_with_retry(db, false, async move |tx| { courses_alive(tx, &courses).await?; let inserted = sqlx::query!( - r#"INSERT INTO class_blueprint (id, grade, courses, creator) - VALUES ($1, $2, $3, $4)"#, + r#"INSERT INTO class_blueprint (id, grade, creator) + VALUES ($1, $2, $3)"#, id, grade as _, - courses as _, creator as _ ) .execute(&mut *tx) .await; match inserted { - Ok(_) => Ok(blueprint.clone()), + Ok(_) => { + sqlx::query!( + r#"INSERT INTO blueprint_course (blueprint, course) + SELECT $1, x FROM unnest($2::uuid[]) AS t(x) + ON CONFLICT DO NOTHING"#, + id, + courses as _, + ) + .execute(&mut *tx) + .await?; + Ok(blueprint.clone()) + } Err(e) if unique_violation(&e) == Some("class_blueprint_grade_key") => Err( AppError::Conflict("a blueprint already exists for that grade"), ), @@ -114,20 +207,22 @@ pub async fn read( db: &Database, id: &ClassBlueprintId, ) -> Result, AppError> { - let row = sqlx::query!( - r#"SELECT grade AS "id: ClassBlueprintId", grade AS "grade: ClassGrade", - courses AS "courses: Vec", creator AS "creator: UserId" + let row = sqlx::query_as!( + BlueprintRow, + r#"SELECT id AS "key: uuid::Uuid", grade AS "grade: ClassGrade", + creator AS "creator: UserId" FROM class_blueprint WHERE grade = $1"#, id as _ ) .fetch_optional(db) .await?; - Ok(row.map(|row| ClassBlueprint { - id: row.id, - grade: row.grade, - courses: row.courses, - creator: row.creator, - })) + match row { + Some(row) => { + let courses = junction_courses(db, row.key).await?; + Ok(Some(row.into_blueprint(courses))) + } + None => Ok(None), + } } /// Every blueprint, by grade label — the id *is* the label, so this is the @@ -137,17 +232,26 @@ pub async fn list_all( limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - PagedList::new(CLASS_BLUEPRINT_TABLE, "ORDER BY grade ASC") - .run(limit, offset, db) - .await + let (rows, total) = PagedList::new(CLASS_BLUEPRINT_TABLE, "ORDER BY grade ASC") + .run::(limit, offset, db) + .await?; + Ok((with_courses(db, rows).await?, total)) } -/// Write the course list only while the stored row still carries the list +/// Write the course list only while the stored rows still answer to the list /// this caller read: two managers editing the same grade cannot have one's -/// list silently pump the other's diff. `None` means the conditional write -/// matched nothing — the row is gone, or its list moved since the caller read -/// it, and only the caller can tell those apart (the workflow re-reads and -/// answers a `409` or a `404`). +/// list silently pump the other's diff. `None` means the claim matched +/// nothing — the row is gone, or its list moved since the caller read it, and +/// only the caller can tell those apart (the workflow re-reads and answers a +/// `409` or a `404`). +/// +/// The write is a claim (`FOR UPDATE` on the row), a comparison (the stored +/// `blueprint_course` rows, read under that lock, against `held` — both +/// sorted the same way, so the comparison is a plain vector equality), then +/// the diff: rows `wanted` dropped are deleted, rows it added are inserted. +/// All of it rides one transaction, and the row lock it holds is the same +/// strength the blueprint delete takes, so a pump's `FOR KEY SHARE` claim on +/// this row waits out the whole write exactly as it waits out a delete. /// /// A template naming a course that is gone refuses inside the transaction /// with the pre-flight `400` ([`courses_alive`]). @@ -157,21 +261,49 @@ pub async fn set_courses_if_unchanged( held: Vec, wanted: Vec, ) -> Result, AppError> { - let id = id.clone(); + let grade = id.clone(); + let mut held = held; + held.sort_by_key(|course| course.uuid()); + let keys: Vec = wanted.iter().map(CourseId::uuid).collect(); tx_with_retry(db, false, async move |tx| { courses_alive(tx, &wanted).await?; - let updated = sqlx::query!( - r#"UPDATE class_blueprint SET courses = $2 - WHERE grade = $1 AND courses = $3 - RETURNING grade AS "grade: ClassGrade", creator AS "creator: UserId""#, - id as _, - wanted as _, - held as _ + let row = sqlx::query!( + r#"SELECT id AS "key: uuid::Uuid", grade AS "grade: ClassGrade", + creator AS "creator: UserId" + FROM class_blueprint WHERE grade = $1 FOR UPDATE"#, + grade.key(), ) .fetch_optional(&mut *tx) .await?; - Ok(updated.map(|row| ClassBlueprint { - id: id.clone(), + let Some(row) = row else { + return Ok(None); + }; + let stored = junction_courses(&mut *tx, row.key).await?; + if stored != held { + return Ok(None); + } + // The diff, from the list this caller stored: rows it dropped go, + // rows it added come (a duplicate in `wanted` is one row — the + // workflow deduplicates, and the key does the rest). + sqlx::query!( + r#"DELETE FROM blueprint_course + WHERE blueprint = $1 AND NOT (course = ANY($2))"#, + row.key, + &keys, + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + r#"INSERT INTO blueprint_course (blueprint, course) + SELECT $1, x FROM unnest($2::uuid[]) AS t(x) + ON CONFLICT DO NOTHING"#, + row.key, + &keys, + ) + .execute(&mut *tx) + .await?; + Ok(Some(ClassBlueprint { + id: ClassBlueprintId::for_grade(&row.grade), grade: row.grade, courses: wanted.clone(), creator: row.creator, @@ -180,10 +312,10 @@ pub async fn set_courses_if_unchanged( .await } -/// Delete the row, but only while it still carries the list this caller read -/// — the edit race answers the caller, not a silent delete of somebody -/// else's additions. `false` means the conditional delete matched nothing: -/// the row is gone, or its list moved since the caller read it, and only the +/// Delete the row — but only while its stored list is still the one this +/// caller read; the edit race answers the caller, not a silent delete of +/// somebody else's additions. `false` means the claim matched nothing: the +/// row is gone, or its list moved since the caller read it, and only the /// caller can tell those apart. /// /// The `DELETE` is also the whole of the serialization against the attaches @@ -196,32 +328,60 @@ pub async fn delete_if_unchanged( id: &ClassBlueprintId, held: Vec, ) -> Result { - let deleted = sqlx::query!( - r#"DELETE FROM class_blueprint WHERE grade = $1 AND courses = $2"#, - id as _, - held as _ - ) - .execute(db) - .await?; - Ok(deleted.rows_affected() > 0) + let grade = id.clone(); + tx_with_retry(db, false, async move |tx| { + delete_claimed(&mut *tx, &grade, &held).await + }) + .await } /// [`delete_if_unchanged`] inside the caller's transaction — the blueprint /// delete rides the row lock its claim took, so the sourced links are swept -/// while the window the claim opened is still closed. +/// while the window the claim opened is still closed. The claim and the +/// comparison re-run here: in the delete workflow's own transaction the +/// [`held_courses_for_update`] claim has already settled both, so they are a +/// formality; the standalone path above gets its whole CAS from this one +/// body. pub(crate) async fn delete_if_unchanged_in( tx: &mut sqlx::PgConnection, id: &ClassBlueprintId, held: &[CourseId], ) -> Result { - let deleted = sqlx::query!( - r#"DELETE FROM class_blueprint WHERE grade = $1 AND courses = $2"#, + delete_claimed(tx, id, held).await +} + +/// The delete's core: claim the row, compare the stored junction rows with +/// `held`, and take the junction rows before the blueprint row they +/// reference — the `NO ACTION` foreign key is checked the moment the final +/// `DELETE` runs. +async fn delete_claimed( + tx: &mut PgConnection, + id: &ClassBlueprintId, + held: &[CourseId], +) -> Result { + let row = sqlx::query!( + r#"SELECT id AS "key: uuid::Uuid" FROM class_blueprint + WHERE grade = $1 FOR UPDATE"#, id as _, - held as _ ) - .execute(&mut *tx) + .fetch_optional(&mut *tx) .await?; - Ok(deleted.rows_affected() > 0) + let Some(row) = row else { + return Ok(false); + }; + let mut held = held.to_vec(); + held.sort_by_key(|course| course.uuid()); + let stored = junction_courses(&mut *tx, row.key).await?; + if stored != held { + return Ok(false); + } + sqlx::query!(r#"DELETE FROM blueprint_course WHERE blueprint = $1"#, row.key) + .execute(&mut *tx) + .await?; + sqlx::query!(r#"DELETE FROM class_blueprint WHERE id = $1"#, row.key) + .execute(&mut *tx) + .await?; + Ok(true) } /// The stored course list of one blueprint, read `FOR UPDATE` — the claim @@ -234,13 +394,16 @@ pub(crate) async fn held_courses_for_update( id: &ClassBlueprintId, ) -> Result>, AppError> { let row = sqlx::query!( - r#"SELECT courses AS "courses: Vec" - FROM class_blueprint WHERE grade = $1 FOR UPDATE"#, - id as _ + r#"SELECT id AS "key: uuid::Uuid" FROM class_blueprint + WHERE grade = $1 FOR UPDATE"#, + id as _, ) .fetch_optional(&mut *tx) .await?; - Ok(row.map(|row| row.courses)) + match row { + Some(row) => Ok(Some(junction_courses(&mut *tx, row.key).await?)), + None => Ok(None), + } } /// Every `class_course` row held by any of `classes`, projected down to the @@ -265,15 +428,15 @@ pub async fn held_links(db: &Database, classes: Vec) -> Result Result<(), AppError> { sqlx::query!( - r#"UPDATE class_blueprint SET courses = array_remove(courses, $2) WHERE grade = $1"#, + r#"DELETE FROM blueprint_course + WHERE course = $2 + AND blueprint = (SELECT id FROM class_blueprint WHERE grade = $1)"#, id as _, - course as _ + course as _, ) .execute(db) .await?; diff --git a/src/db/course.rs b/src/db/course.rs index 3e3db5a..f0500af 100644 --- a/src/db/course.rs +++ b/src/db/course.rs @@ -12,6 +12,80 @@ use crate::domain::term::{self, TermId}; use crate::domain::user::UserId; use crate::error::AppError; +use std::collections::HashMap; + +/// The stored columns of a `course` row. The assigned teachers live across +/// the `course_teacher` junction, not on this row, so every read joins them +/// on in one batch afterwards ([`into_courses`]) — the two generic readers +/// below (the paged list and the field-scoped PATCH) both read whole rows +/// (`SELECT *` / `RETURNING *`), which is a shape no aggregate column can +/// ride. +#[derive(Debug, sqlx::FromRow)] +struct CourseRow { + id: CourseId, + creator: UserId, + title: CourseTitle, + description: CourseDescription, + kind: CourseKind, + term: Option, + capacity: Option, +} + +impl CourseRow { + fn into_course(self, teachers: Vec) -> Course { + Course { + id: self.id, + creator: self.creator, + teachers, + title: self.title, + description: self.description, + kind: self.kind, + term: self.term, + capacity: self.capacity, + } + } +} + +/// Assemble [`Course`]s (their assigned teachers included) out of row reads: +/// one `course_teacher` query for the whole batch, a course nobody is +/// assigned to reading an empty list. +async fn into_courses(db: &Database, rows: Vec) -> Result, AppError> { + if rows.is_empty() { + return Ok(Vec::new()); + } + let ids: Vec = rows.iter().map(|row| row.id.uuid()).collect(); + let links = sqlx::query!( + r#"SELECT course AS "course: CourseId", teacher AS "teacher: UserId" + FROM course_teacher WHERE course = ANY($1)"#, + &ids, + ) + .fetch_all(db) + .await?; + let mut by_course: HashMap> = HashMap::new(); + for link in links { + by_course + .entry(link.course.uuid()) + .or_default() + .push(link.teacher); + } + Ok(rows + .into_iter() + .map(|row| { + let teachers = by_course.remove(&row.id.uuid()).unwrap_or_default(); + row.into_course(teachers) + }) + .collect()) +} + +/// [`into_courses`] for a single row. +async fn one_course(db: &Database, row: CourseRow) -> Result { + let course = into_courses(db, vec![row]) + .await? + .pop() + .expect("one row in, one course out"); + Ok(course) +} + pub async fn create( db: &Database, creator: &UserId, @@ -24,16 +98,15 @@ pub async fn create( let id = CourseId::generate(); let Some(term) = term else { let created = sqlx::query_as!( - Course, - r#"INSERT INTO course (id, creator, teachers, title, description, kind, term, capacity) - VALUES ($1, $2, $3, $4, $5, $6, NULL, $7) + CourseRow, + r#"INSERT INTO course (id, creator, title, description, kind, term, capacity) + VALUES ($1, $2, $3, $4, $5, NULL, $6) RETURNING id AS "id: CourseId", creator AS "creator: UserId", - teachers AS "teachers: Vec", title AS "title: CourseTitle", + title AS "title: CourseTitle", description AS "description: CourseDescription", kind AS "kind: CourseKind", term AS "term: TermId", capacity"#, id.uuid(), creator.uuid(), - &Vec::::new(), title.as_str(), description.as_str(), kind.as_str(), @@ -41,7 +114,8 @@ pub async fn create( ) .fetch_one(db) .await?; - return Ok(created); + // A new course has no assigned teachers; the join reads an empty list. + return one_course(db, created).await; }; // Claim a reference on the term in the *same statement* as the row: the // claim is a conditional write on the term row, so it fails when the @@ -50,21 +124,20 @@ pub async fn create( // which a claim sent as its own query could (the count would strand and // the term be undeletable forever). let created = sqlx::query_as!( - Course, + CourseRow, r#"WITH seat AS ( UPDATE term SET course_count = course_count + 1 - WHERE id = $8 AND course_count < $9 + WHERE id = $7 AND course_count < $8 RETURNING 1) - INSERT INTO course (id, creator, teachers, title, description, kind, term, capacity) - SELECT $1, $2, $3, $4, $5, $6, $8, $7 WHERE EXISTS (SELECT 1 FROM seat) + INSERT INTO course (id, creator, title, description, kind, term, capacity) + SELECT $1, $2, $3, $4, $5, $7, $6 WHERE EXISTS (SELECT 1 FROM seat) RETURNING id AS "id: CourseId", creator AS "creator: UserId", - teachers AS "teachers: Vec", title AS "title: CourseTitle", + title AS "title: CourseTitle", description AS "description: CourseDescription", kind AS "kind: CourseKind", term AS "term: TermId", capacity"#, id.uuid(), creator.uuid(), - &Vec::::new(), title.as_str(), description.as_str(), kind.as_str(), @@ -75,7 +148,7 @@ pub async fn create( .fetch_one(db) .await; match created { - Ok(created) => Ok(created), + Ok(created) => one_course(db, created).await, // Uncapped, so "full" can only mean the conditional write matched no // term row at all — the existence check the pre-flight lookup makes. Err(sqlx::Error::RowNotFound) => Err(term::gone_error()), @@ -87,33 +160,40 @@ pub async fn create( } } -pub async fn read(db: &Database, id: &CourseId) -> Result, AppError> { - let course = sqlx::query_as!( - Course, +async fn read_row(db: &Database, id: &CourseId) -> Result, AppError> { + sqlx::query_as!( + CourseRow, r#"SELECT id AS "id: CourseId", creator AS "creator: UserId", - teachers AS "teachers: Vec", title AS "title: CourseTitle", + title AS "title: CourseTitle", description AS "description: CourseDescription", kind AS "kind: CourseKind", term AS "term: TermId", capacity FROM course WHERE id = $1"#, id.uuid(), ) .fetch_optional(db) - .await?; - Ok(course) + .await + .map_err(Into::into) +} + +pub async fn read(db: &Database, id: &CourseId) -> Result, AppError> { + match read_row(db, id).await? { + Some(row) => Ok(Some(one_course(db, row).await?)), + None => Ok(None), + } } pub async fn list_all(db: &Database) -> Result, AppError> { let rows = sqlx::query_as!( - Course, + CourseRow, r#"SELECT id AS "id: CourseId", creator AS "creator: UserId", - teachers AS "teachers: Vec", title AS "title: CourseTitle", + title AS "title: CourseTitle", description AS "description: CourseDescription", kind AS "kind: CourseKind", term AS "term: TermId", capacity FROM course ORDER BY id DESC"#, ) .fetch_all(db) .await?; - Ok(rows) + into_courses(db, rows).await } /// The courses `user` is enrolled in — the spine of `/courses/me` and the @@ -124,42 +204,39 @@ pub async fn list_enrolled( limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - PagedList::new( + let (rows, total) = PagedList::new( "course WHERE id IN (SELECT course FROM enrollment WHERE app_user = $1)", "ORDER BY id DESC", ) .bind(user.uuid()) - .run::(limit, offset, db) - .await + .run::(limit, offset, db) + .await?; + Ok((into_courses(db, rows).await?, total)) } /// The courses `user` runs — the ones they created plus the ones a manager /// assigned them to. A teacher's slice of the catalog. /// -/// corner-cut: unpaged full table scan, and it stays one — every profile -/// read of a teacher pays it, so the ceiling is the course table's size. -/// Under Postgres the `OR` halves could each use an index on `creator` / -/// `teachers` (a GIN), but the old per-element index the membership half -/// would have needed was *wrong*, not merely useless — `$usr IN teachers` -/// returned **no rows at all** with it, which is what the integration test -/// `assigned_teacher_manages_course_without_owning_it` catches. The upgrade -/// path is structural: a `course_teacher` link table indexed on `user`, the -/// shape `enrollment` already has, turning this into two index-backed -/// reads. No schema carries it yet, so the scan stays. +/// The assigned half reads `course_teacher` by its `teacher` index (the +/// shape `enrollment` already has) instead of an array membership test — +/// that test was the corner-cut here once, and the junction is exactly the +/// upgrade path the old comment called structural. pub async fn list_for_teacher(db: &Database, user: &UserId) -> Result, AppError> { let rows = sqlx::query_as!( - Course, + CourseRow, r#"SELECT id AS "id: CourseId", creator AS "creator: UserId", - teachers AS "teachers: Vec", title AS "title: CourseTitle", + title AS "title: CourseTitle", description AS "description: CourseDescription", kind AS "kind: CourseKind", term AS "term: TermId", capacity - FROM course WHERE creator = $1 OR $2 = ANY(teachers) ORDER BY id DESC"#, + FROM course WHERE creator = $1 OR id IN ( + SELECT course FROM course_teacher WHERE teacher = $2) + ORDER BY id DESC"#, user.uuid(), user.uuid(), ) .fetch_all(db) .await?; - Ok(rows) + into_courses(db, rows).await } /// Load every course behind `ids` (one query) — the join half of the @@ -170,9 +247,9 @@ pub async fn list_by_ids(db: &Database, ids: &[CourseId]) -> Result, } let keys: Vec = ids.iter().map(CourseId::uuid).collect(); let rows = sqlx::query_as!( - Course, + CourseRow, r#"SELECT id AS "id: CourseId", creator AS "creator: UserId", - teachers AS "teachers: Vec", title AS "title: CourseTitle", + title AS "title: CourseTitle", description AS "description: CourseDescription", kind AS "kind: CourseKind", term AS "term: TermId", capacity FROM course WHERE id = ANY($1)"#, @@ -180,19 +257,22 @@ pub async fn list_by_ids(db: &Database, ids: &[CourseId]) -> Result, ) .fetch_all(db) .await?; - Ok(rows) + into_courses(db, rows).await } -/// Request-scoped: `teachers` is written by [`assign_teacher`], -/// [`unassign_teacher`] and the demotion sweep, and nothing guards -/// the course row across the handler's read and this write (its `TERM_LOCK` -/// window guards the *term* it links, and the assign path takes no lock at -/// all) — so a field the request omitted (`None`) is not written at all. -/// Sending the snapshot's value back instead would revert a concurrent -/// edit of that field; scoping the `SET` alone does not stop that, the -/// values have to come from the request. `term` and `capacity` are -/// nullable, so they take the outer/inner `Option>`: `None` = -/// omitted (keep), `Some(None)` = clear. +/// Field-scoped: nothing guards the course row across the handler's read +/// and this write (its `TERM_LOCK` window guards the *term* it links, and +/// the assign path takes no lock at all) — so a field the request omitted +/// (`None`) is not written at all. Sending the snapshot's value back +/// instead would revert a concurrent edit of that field; scoping the `SET` +/// alone does not stop that, the values have to come from the request. +/// `term` and `capacity` are nullable, so they take the outer/inner +/// `Option>`: `None` = omitted (keep), `Some(None)` = clear. +/// +/// The assigned teachers are not fields of this row — they are +/// `course_teacher` rows, written only by [`assign_teacher`], +/// [`unassign_teacher`] and the demotion sweep — so a PATCH can neither +/// carry nor clobber them. pub async fn update( db: &Database, course: Course, @@ -208,7 +288,7 @@ pub async fn update( // without its count. A PATCH that carried no `term_id`, or re-stated the // link it already had, moves neither counter. let (claim, release) = term::ref_move(course.term.as_ref(), &term); - FieldUpdate::new(COURSE_TABLE, course.id.uuid()) + let row = FieldUpdate::new(COURSE_TABLE, course.id.uuid()) .set("title", title.map(|title| title.as_str().to_owned())) .set( "description", @@ -229,18 +309,17 @@ pub async fn update( release: release.map(|term| term.uuid()), refused: term::gone_error(), }) - .run::(db) - .await + .run::(db) + .await?; + // The teachers are joined on after the write, off the junction. + one_course(db, row).await } /// Assign `teacher` to run this course, or return the course untouched if -/// they already run it — assignment is idempotent, like enrollment. -/// Field-scoped, and the new list is folded server-side out of the *stored* -/// one: a course PATCH awaits a term lookup between its read and its write, -/// so a whole-row save from either side would revert the other. The -/// `array_agg(DISTINCT …)` keeps the assignment idempotent even when two -/// requests name the same teacher at once (the early return only sees a -/// stale row). +/// they already run it — assignment is idempotent, like enrollment: the +/// link is an `INSERT` whose `(course, teacher)` key answers a duplicate +/// with `DO NOTHING`, so two requests naming the same teacher at once land +/// one row (the early return only sees a stale snapshot). pub async fn assign_teacher( db: &Database, course: Course, @@ -249,22 +328,22 @@ pub async fn assign_teacher( if course.is_assigned(teacher) { return Ok(course); } - let updated = sqlx::query_as!( - Course, - r#"UPDATE course - SET teachers = (SELECT array_agg(DISTINCT x) - FROM unnest(course.teachers || $2::uuid) AS x) - WHERE id = $1 - RETURNING id AS "id: CourseId", creator AS "creator: UserId", - teachers AS "teachers: Vec", title AS "title: CourseTitle", - description AS "description: CourseDescription", - kind AS "kind: CourseKind", term AS "term: TermId", capacity"#, + // `WHERE EXISTS` keeps the insert a no-op when the course went between + // the caller's read and this write — the answer is the `NotFound` the + // fresh read below gives, not a foreign-key 500. + sqlx::query!( + r#"INSERT INTO course_teacher (course, teacher) + SELECT $1, $2 WHERE EXISTS (SELECT 1 FROM course WHERE id = $1) + ON CONFLICT DO NOTHING"#, course.id.uuid(), teacher.uuid(), ) - .fetch_optional(db) + .execute(db) .await?; - updated.ok_or(AppError::NotFound) + // Fresh read, like the `RETURNING` this replaced: the snapshot's + // teacher list can be stale (a concurrent assign). + let row = read_row(db, &course.id).await?.ok_or(AppError::NotFound)?; + one_course(db, row).await } /// Drop `teacher` from this course. `None` when they weren't assigned, so @@ -277,35 +356,26 @@ pub async fn unassign_teacher( if !course.is_assigned(teacher) { return Ok(None); } - // Same field-scoped story as [`assign_teacher`]; `array_remove` drops - // the one link off the stored list without touching the course's own - // text. - let updated = sqlx::query_as!( - Course, - r#"UPDATE course SET teachers = array_remove(teachers, $2) - WHERE id = $1 - RETURNING id AS "id: CourseId", creator AS "creator: UserId", - teachers AS "teachers: Vec", title AS "title: CourseTitle", - description AS "description: CourseDescription", - kind AS "kind: CourseKind", term AS "term: TermId", capacity"#, + let deleted = sqlx::query!( + r#"DELETE FROM course_teacher WHERE course = $1 AND teacher = $2"#, course.id.uuid(), teacher.uuid(), ) - .fetch_optional(db) + .execute(db) .await?; - Ok(updated) + if deleted.rows_affected() == 0 { + // Unassigned under the caller's feet — nothing was removed. + return Ok(None); + } + read(db, &course.id).await } /// Strip `user` from every course they were assigned to — the sweep for a /// user demoted below `teacher`, who may no longer run anything. pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), AppError> { - sqlx::query!( - r#"UPDATE course SET teachers = array_remove(teachers, $1) - WHERE $1 = ANY(teachers)"#, - user.uuid(), - ) - .execute(db) - .await?; + sqlx::query!(r#"DELETE FROM course_teacher WHERE teacher = $1"#, user.uuid(),) + .execute(db) + .await?; Ok(()) } @@ -330,15 +400,14 @@ pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), App /// ever visits that column) and at a dead subject the next `PATCH` /// omitting `subject_id` writes straight back. /// -/// The **grade blueprints** naming it are swept in that same transaction. -/// Nothing else can reach them — a blueprint holds its courses as a list on -/// its own row, not as link rows this cascade could delete — and an id left -/// behind is permanent rather than merely stale: the pump's own -/// [`crate::db::class_blueprint::prune`] fires only while walking a -/// section, so a grade with no sections can never drop one, and every -/// `PATCH` of that template is refused for naming a course that does not -/// exist, which is precisely the call documented as the repair. A dozen-row -/// table scanned unindexed, deliberately: a course delete is rare. +/// The **grade blueprints** naming it are swept in that same transaction — +/// their `blueprint_course` link rows are FK children now, deleted right +/// here like any other link, so a template stops naming a course the +/// instant that course goes (the old `teachers`-style array made the id a +/// permanent dangling value only the pump's [`crate::db::class_blueprint:: +/// prune`] could chase). The same transaction takes the course's +/// `course_teacher` assignment rows: an assigned teacher loses the course +/// with it. /// /// The **derived AI rows** (`rag_output` carries a denormalized `course` /// besides its note link) and the event **audience links** are FK children @@ -358,9 +427,9 @@ pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), App /// and question images before `exam_question`; `exam_question` before /// `exam`; homework files before submissions before results before /// `homework`; roll-call rows before `course_session`; note files and -/// rag rows before `course_note`; every one of them before the `course` -/// row itself, whose `NO ACTION` FKs are checked the moment the final -/// `DELETE` runs. +/// rag rows before `course_note`; `blueprint_course` and `course_teacher` +/// before the `course` row itself, whose `NO ACTION` FKs are checked the +/// moment the final `DELETE` runs. /// /// `false` = refused, nothing was written: someone is still enrolled. The /// guard locks the course row (`FOR UPDATE`) and reads its own @@ -470,7 +539,15 @@ pub async fn delete(db: &Database, course: Course) -> Result { ) .execute(&mut *tx) .await?; - // Derived AI rows for this course's notes. + // Derived AI rows for this course's notes — links before the rows + // (`ON DELETE NO ACTION`). + sqlx::query!( + r#"DELETE FROM rag_output_source WHERE output IN ( + SELECT id FROM rag_output WHERE course = $1)"#, + course.id.uuid(), + ) + .execute(&mut *tx) + .await?; sqlx::query!( r#"DELETE FROM rag_output WHERE course = $1"#, course.id.uuid() @@ -504,8 +581,14 @@ pub async fn delete(db: &Database, course: Course) -> Result { .execute(&mut *tx) .await?; sqlx::query!( - r#"UPDATE class_blueprint SET courses = array_remove(courses, $1) - WHERE $1 = ANY(courses)"#, + r#"DELETE FROM blueprint_course WHERE course = $1"#, + course.id.uuid(), + ) + .execute(&mut *tx) + .await?; + // The assignment links die with the course, before the row itself. + sqlx::query!( + r#"DELETE FROM course_teacher WHERE course = $1"#, course.id.uuid(), ) .execute(&mut *tx) @@ -549,6 +632,13 @@ pub async fn delete(db: &Database, course: Course) -> Result { sqlx::query!(r#"DELETE FROM exam WHERE course = $1"#, course.id.uuid()) .execute(&mut *tx) .await?; + sqlx::query!( + r#"DELETE FROM homework_assignment WHERE homework IN ( + SELECT id FROM homework WHERE course = $1)"#, + course.id.uuid(), + ) + .execute(&mut *tx) + .await?; sqlx::query!( r#"DELETE FROM homework WHERE course = $1"#, course.id.uuid() diff --git a/src/db/course_note.rs b/src/db/course_note.rs index b38dd0f..2241998 100644 --- a/src/db/course_note.rs +++ b/src/db/course_note.rs @@ -118,6 +118,15 @@ pub async fn delete( note: CourseNote, ) -> Result<(CourseNote, Vec), AppError> { tx_with_retry(db, true, async move |conn| { + // Links before rows: the outputs' citation links are their children + // (`ON DELETE NO ACTION`). + sqlx::query!( + "DELETE FROM rag_output_source WHERE output IN + (SELECT id FROM rag_output WHERE course_note = $1)", + note.id.uuid() + ) + .execute(&mut *conn) + .await?; sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.id.uuid()) .execute(&mut *conn) .await?; diff --git a/src/db/dietary_profile.rs b/src/db/dietary_profile.rs index f2fbf56..cd6b892 100644 --- a/src/db/dietary_profile.rs +++ b/src/db/dietary_profile.rs @@ -1,11 +1,12 @@ //! The `dietary_profile` table: one row per student (the primary key *is* //! the student), created on first write and afterwards patched -//! field-by-field — both by one `INSERT … ON CONFLICT DO UPDATE`. The -//! tag/note newtypes and the pure tag intersection live in +//! field-by-field — the row by one `INSERT … ON CONFLICT DO UPDATE`, the +//! tags by child rows in `dietary_profile_tag` replaced under the same +//! transaction. The tag/note newtypes and the pure tag intersection live in //! [`crate::domain::dietary_profile`]; the web layer reads through //! [`crate::service::dietary_profile`]. -use crate::database::Database; +use crate::database::{Database, tx_with_retry}; use crate::domain::dietary_profile::{DietaryNote, DietaryProfile, DietaryTags}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; @@ -16,7 +17,9 @@ use crate::error::AppError; pub async fn read(db: &Database, student: &UserId) -> Result, AppError> { let row = sqlx::query_as!( DietaryProfile, - "SELECT student AS \"student: UserId\", tags AS \"tags: DietaryTags\", note AS \"note: DietaryNote\", updated_by AS \"updated_by: UserId\", updated_at AS \"updated_at: Timestamp\" + "SELECT student AS \"student: UserId\", + COALESCE((SELECT array_agg(t.tag ORDER BY t.ord) FROM dietary_profile_tag t WHERE t.student = dietary_profile.student), '{}'::text[]) AS \"tags!: DietaryTags\", + note AS \"note: DietaryNote\", updated_by AS \"updated_by: UserId\", updated_at AS \"updated_at: Timestamp\" FROM dietary_profile WHERE student = $1", student.uuid(), ) @@ -38,14 +41,15 @@ pub async fn tags_of(db: &Database, student: &UserId) -> Result, App /// afterwards only the named fields move, because a whole-row save would /// also revert a concurrent edit of the other field. /// -/// Both paths are one statement: an absent `tags` keeps the stored list -/// (`COALESCE`), an absent `note` keeps the stored one, a `Some(None)` note -/// clears it and a `Some(Some)` overwrites it — the same three-way shape, -/// spelled with a "was the field on the request?" flag plus its nullable -/// value. A rival `PATCH` that created the row a moment ago turns this -/// call's `INSERT` into the `DO UPDATE` arm: a plain field write after all, -/// exactly as it would have been a moment later — without the error the old -/// store's create-then-patch pair had to catch. +/// The base row is one upsert — an absent `note` keeps the stored one, a +/// `Some(None)` clears it and a `Some(Some)` overwrites it (the same +/// three-way shape, spelled with a "was the field on the request?" flag +/// plus its nullable value) — and an absent `tags` leaves the stored tag +/// rows alone while a carried `tags` replaces the whole set, all under one +/// transaction. A rival `PATCH` that created the row a moment ago turns +/// this call's `INSERT` into the `DO UPDATE` arm: a plain field write +/// after all, exactly as it would have been a moment later — without the +/// error the old store's create-then-patch pair had to catch. pub async fn save( db: &Database, student: &UserId, @@ -53,24 +57,52 @@ pub async fn save( note: Option>, by: &UserId, ) -> Result { - let row = sqlx::query_as!( - DietaryProfile, - "INSERT INTO dietary_profile (student, tags, note, updated_by, updated_at) - VALUES ($1, COALESCE($2, '{}'::text[]), $3, $4, $5) - ON CONFLICT (student) DO UPDATE SET - tags = COALESCE($2, dietary_profile.tags), - note = CASE WHEN $6 THEN $3 ELSE dietary_profile.note END, - updated_by = $4, - updated_at = $5 - RETURNING student AS \"student: UserId\", tags AS \"tags: DietaryTags\", note AS \"note: DietaryNote\", updated_by AS \"updated_by: UserId\", updated_at AS \"updated_at: Timestamp\"", - student.uuid(), - tags.as_ref().map(|t| t.as_slice()), - note.as_ref().and_then(|n| n.as_ref()).map(|n| n.as_str()), - by.uuid(), - Timestamp::now().as_millis(), - note.is_some(), - ) - .fetch_one(db) - .await?; - Ok(row) + let student_key = student.uuid(); + let by_key = by.uuid(); + let now = Timestamp::now().as_millis(); + tx_with_retry(db, false, async move |tx| { + sqlx::query!( + "INSERT INTO dietary_profile (student, note, updated_by, updated_at) + VALUES ($1, $2, $3, $4) + ON CONFLICT (student) DO UPDATE SET + note = CASE WHEN $5 THEN $2 ELSE dietary_profile.note END, + updated_by = $3, + updated_at = $4", + student_key, + note.as_ref().and_then(|n| n.as_ref()).map(|n| n.as_str()), + by_key, + now, + note.is_some(), + ) + .execute(&mut *tx) + .await?; + if let Some(tags) = &tags { + sqlx::query!( + "DELETE FROM dietary_profile_tag WHERE student = $1", + student_key, + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + "INSERT INTO dietary_profile_tag (student, tag, ord) + SELECT $1, tag, ord FROM unnest($2::text[]) WITH ORDINALITY AS t(tag, ord)", + student_key, + tags.as_slice(), + ) + .execute(&mut *tx) + .await?; + } + let row = sqlx::query_as!( + DietaryProfile, + "SELECT student AS \"student: UserId\", + COALESCE((SELECT array_agg(t.tag ORDER BY t.ord) FROM dietary_profile_tag t WHERE t.student = dietary_profile.student), '{}'::text[]) AS \"tags!: DietaryTags\", + note AS \"note: DietaryNote\", updated_by AS \"updated_by: UserId\", updated_at AS \"updated_at: Timestamp\" + FROM dietary_profile WHERE student = $1", + student_key, + ) + .fetch_one(&mut *tx) + .await?; + Ok(row) + }) + .await } diff --git a/src/db/homework.rs b/src/db/homework.rs index b23630d..891f004 100644 --- a/src/db/homework.rs +++ b/src/db/homework.rs @@ -51,7 +51,9 @@ pub async fn create( // is the 400 the web layer's pre-flight check answers with. The subject // delete is refused while this counter is non-zero, so the two writers // contend on the subject row itself, and a crash cannot strand a claim - // that would make the subject undeletable forever. + // that would make the subject undeletable forever. The audience rows + // ride the same transaction: a subset homework never appears + // whole-course, not even for the instant of its create. let homework = Homework { id: HomeworkId::generate(), course: course.clone(), @@ -70,47 +72,86 @@ pub async fn create( .iter() .map(UserId::uuid) .collect(); - // The fresh v7 id cannot collide, so the pair-unique answer has no rival - // here; the mapping is kept for symmetry with the other claim sites. - let created = sqlx::query_as!( - Homework, - r#"WITH seat AS ( - UPDATE subject SET homework_count = homework_count + 1 - WHERE id = $1 - RETURNING 1 - ) - INSERT INTO homework (id, course, subject, title, description, due_at, assigned, created_by, created_at) - SELECT $2, $3, $1, $4, $5, $6, $7, $8, $9 WHERE EXISTS (SELECT 1 FROM seat) - RETURNING id AS "id: HomeworkId", - course AS "course: CourseId", - subject AS "subject: SubjectId", - title AS "title: HomeworkTitle", - description AS "description: HomeworkDescription", - due_at AS "due_at: Timestamp", - CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END - AS "assigned: Vec", - created_by AS "created_by: UserId", - created_at AS "created_at: Timestamp""#, - subject.uuid(), - homework.id.uuid(), - course.uuid(), - homework.title.as_str(), - homework.description.as_ref().map(HomeworkDescription::as_str), - homework.due_at.as_millis(), - &assigned_values, - homework.created_by.uuid(), - homework.created_at.as_millis(), - ) - .fetch_optional(db) - .await - .map_err(|err| { - if crate::database::unique_violation(&err).is_some() { - AppError::Internal("failed to create homework".into()) - } else { - AppError::from(err) + // The subset the caller passed is the truth — the store holds no roster + // column to read back; the whole-course case stays `None`. Cloned out + // here because the closure below consumes `homework`. + let assigned = homework.assigned.clone(); + // Owned BEFORE the closure. A reference parameter captured by the + // coroutine (`&CourseId`, `&SubjectId`) leaves that borrow in the + // statement future, and the `Send` proof at the `routes!` registration + // comes back "not general enough" over the higher-ranked connection + // lease — every tx_with_retry site captures only owned values. + let subject = *subject; + let course = course.clone(); + tx_with_retry(db, false, async move |tx| { + // And every bind is a precomputed value of this coroutine's own: a + // bind expression reading a capture inside the macro keeps that + // borrow alive across the await to the same `Send` end. + let subject_uuid = subject.uuid(); + let course_uuid = course.uuid(); + let homework_uuid = homework.id.uuid(); + let title = homework.title.clone(); + let description = homework.description.clone(); + let due_at_millis = homework.due_at.as_millis(); + let created_by_uuid = homework.created_by.uuid(); + let created_at_millis = homework.created_at.as_millis(); + let assigned_values = assigned_values.clone(); + let created = sqlx::query_as!( + Homework, + r#"WITH seat AS ( + UPDATE subject SET homework_count = homework_count + 1 + WHERE id = $1 + RETURNING 1 + ) + INSERT INTO homework (id, course, subject, title, description, due_at, created_by, created_at) + SELECT $2, $3, $1, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM seat) + RETURNING id AS "id: HomeworkId", + course AS "course: CourseId", + subject AS "subject: SubjectId", + title AS "title: HomeworkTitle", + description AS "description: HomeworkDescription", + due_at AS "due_at: Timestamp", + NULL::uuid[] AS "assigned: Vec", + created_by AS "created_by: UserId", + created_at AS "created_at: Timestamp""#, + subject_uuid, + homework_uuid, + course_uuid, + title.as_str(), + description.as_ref().map(HomeworkDescription::as_str), + due_at_millis, + created_by_uuid, + created_at_millis, + ) + .fetch_optional(&mut *tx) + .await + .map_err(|err| { + if crate::database::unique_violation(&err).is_some() { + AppError::Internal("failed to create homework".into()) + } else { + AppError::from(err) + } + })?; + // The audience subset, written beside the row it scopes: a refused + // create (subject gone) writes no audience either, and any other + // failure rolls the homework row back with its audience rows. + if created.is_some() && !assigned_values.is_empty() { + sqlx::query!( + "INSERT INTO homework_assignment (homework, student) + SELECT $2, s FROM unnest($1::uuid[]) AS t(s)", + &assigned_values, + homework_uuid + ) + .execute(&mut *tx) + .await?; } - })?; - created.ok_or_else(subject_gone) + created.ok_or_else(subject_gone) + }) + .await + .map(move |mut created| { + created.assigned = assigned; + created + }) } pub async fn read(db: &Database, id: &HomeworkId) -> Result, AppError> { @@ -122,8 +163,8 @@ pub async fn read(db: &Database, id: &HomeworkId) -> Result, Ap title AS "title: HomeworkTitle", description AS "description: HomeworkDescription", due_at AS "due_at: Timestamp", - CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END - AS "assigned: Vec", + (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a + WHERE a.homework = homework.id) AS "assigned: Vec", created_by AS "created_by: UserId", created_at AS "created_at: Timestamp" FROM homework WHERE id = $1"#, @@ -144,8 +185,8 @@ pub async fn list_for_course(db: &Database, course: &CourseId) -> Result", + (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a + WHERE a.homework = homework.id) AS "assigned: Vec", created_by AS "created_by: UserId", created_at AS "created_at: Timestamp" FROM homework WHERE course = $1 ORDER BY id DESC"#, @@ -166,8 +207,8 @@ pub async fn list_all(db: &Database) -> Result, AppError> { title AS "title: HomeworkTitle", description AS "description: HomeworkDescription", due_at AS "due_at: Timestamp", - CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END - AS "assigned: Vec", + (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a + WHERE a.homework = homework.id) AS "assigned: Vec", created_by AS "created_by: UserId", created_at AS "created_at: Timestamp" FROM homework ORDER BY id DESC"#, @@ -196,8 +237,8 @@ pub async fn list_for_courses( title AS "title: HomeworkTitle", description AS "description: HomeworkDescription", due_at AS "due_at: Timestamp", - CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END - AS "assigned: Vec", + (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a + WHERE a.homework = homework.id) AS "assigned: Vec", created_by AS "created_by: UserId", created_at AS "created_at: Timestamp" FROM homework WHERE course = ANY($1) ORDER BY id DESC"#, @@ -225,12 +266,16 @@ pub async fn list_for_user_in_course( title AS "title: HomeworkTitle", description AS "description: HomeworkDescription", due_at AS "due_at: Timestamp", - CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END - AS "assigned: Vec", + (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a + WHERE a.homework = homework.id) AS "assigned: Vec", created_by AS "created_by: UserId", created_at AS "created_at: Timestamp" FROM homework - WHERE course = $1 AND (cardinality(assigned) = 0 OR $2 = ANY(assigned)) + WHERE course = $1 + AND (NOT EXISTS (SELECT 1 FROM homework_assignment a + WHERE a.homework = homework.id) + OR EXISTS (SELECT 1 FROM homework_assignment a + WHERE a.homework = homework.id AND a.student = $2)) ORDER BY id DESC"#, course.uuid(), user.uuid() @@ -248,7 +293,8 @@ pub async fn list_for_user_in_course( /// and `created_at` are readonly and never appear in the write. /// /// `description` takes `Some(None)` to clear; `assigned` takes `Some(None)` -/// to widen back to the whole course (stored as `'{}'`, read back as `None`). +/// to widen back to the whole course (stored as no `homework_assignment` rows, +/// read back as `None`). /// The web layer has already re-checked a new `due_at` against now, a new /// `subject` against the course, and — inside the transaction here — the /// narrowing against the work that would be orphaned by it. @@ -277,8 +323,8 @@ pub async fn update( title AS "title: HomeworkTitle", description AS "description: HomeworkDescription", due_at AS "due_at: Timestamp", - CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END - AS "assigned: Vec", + (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a + WHERE a.homework = homework.id) AS "assigned: Vec", created_by AS "created_by: UserId", created_at AS "created_at: Timestamp" FROM homework WHERE id = $1 FOR UPDATE"#, @@ -331,6 +377,29 @@ pub async fn update( if subject.is_some() && current.subject != homework.subject { return Err(AppError::Conflict(STALE_MOVE)); } + // The carried `assigned` replaces the junction rows wholesale — + // delete-then-insert under the row lock, so the audience (or its + // absence, = whole course) is exactly what the request named. An + // uncarried `assigned` writes no rows, keeping the stored audience. + if let Some(resolved) = assigned.as_ref() { + sqlx::query!( + "DELETE FROM homework_assignment WHERE homework = $1", + homework.get_id().uuid() + ) + .execute(&mut *tx) + .await?; + let values: Vec = resolved.iter().flatten().map(UserId::uuid).collect(); + if !values.is_empty() { + sqlx::query!( + "INSERT INTO homework_assignment (homework, student) + SELECT $2, s FROM unnest($1::uuid[]) AS t(s)", + &values, + homework.get_id().uuid() + ) + .execute(&mut *tx) + .await?; + } + } // What the PATCH carried is written; what it did not carry keeps the // value just read under the lock. Under that lock this resolved @@ -345,22 +414,10 @@ pub async fn update( Some(Some(text)) => Some(text), }; let new_due_at = due_at.unwrap_or(current.due_at); - let new_assigned = match assigned.clone() { - None => current.assigned.clone(), - // Clear = the whole course, stored as `'{}'`. - Some(None) => None, - Some(Some(subset)) => Some(subset), - }; - let assigned_values: Vec = new_assigned - .as_deref() - .unwrap_or_default() - .iter() - .map(UserId::uuid) - .collect(); sqlx::query_as!( Homework, r#"UPDATE homework SET subject = $2, title = $3, description = $4, - due_at = $5, assigned = $6 + due_at = $5 WHERE id = $1 RETURNING id AS "id: HomeworkId", course AS "course: CourseId", @@ -368,8 +425,8 @@ pub async fn update( title AS "title: HomeworkTitle", description AS "description: HomeworkDescription", due_at AS "due_at: Timestamp", - CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END - AS "assigned: Vec", + (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a + WHERE a.homework = homework.id) AS "assigned: Vec", created_by AS "created_by: UserId", created_at AS "created_at: Timestamp""#, homework.get_id().uuid(), @@ -377,7 +434,6 @@ pub async fn update( new_title.as_str(), new_description.as_ref().map(HomeworkDescription::as_str), new_due_at.as_millis(), - &assigned_values, ) .fetch_optional(&mut *tx) .await? @@ -445,7 +501,8 @@ async fn ensure_no_orphans( /// vanished homework. The cascade runs children-first (every FK here is /// `ON DELETE NO ACTION`): files, then submissions — whose `graded_by_result` /// stamp points at a result row, so they must be gone before it — then the -/// results, then the homework. The submission file *blobs* are the web +/// results, the audience rows, then the homework. The submission file *blobs* +/// are the web /// layer's to unlink: their names are returned (collected inside the /// transaction, before the wipes — a file row inserted after an /// out-of-transaction collection would be deleted here while its key was @@ -485,6 +542,12 @@ pub async fn delete( ) .execute(&mut *tx) .await?; + sqlx::query!( + "DELETE FROM homework_assignment WHERE homework = $1", + homework.get_id().uuid() + ) + .execute(&mut *tx) + .await?; let deleted = sqlx::query_as!( Homework, r#"DELETE FROM homework WHERE id = $1 @@ -494,8 +557,8 @@ pub async fn delete( title AS "title: HomeworkTitle", description AS "description: HomeworkDescription", due_at AS "due_at: Timestamp", - CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END - AS "assigned: Vec", + (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a + WHERE a.homework = homework.id) AS "assigned: Vec", created_by AS "created_by: UserId", created_at AS "created_at: Timestamp""#, homework.get_id().uuid() @@ -822,4 +885,81 @@ mod tests { ); assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once, still"); } + + /// The audience contract in SQL: no `homework_assignment` rows = the whole + /// course (every student's list, later enrollees included); rows name the + /// subset, and `list_for_user_in_course` answers it to the named student + /// alone. The read-back roster is the junction itself. + #[tokio::test] + async fn a_subset_reaches_only_the_named_and_widening_clears_the_rows() { + let (db, _leases) = crate::database::init_test_db().await; + let subject = a_subject("tarih", &db).await; + let teacher = UserId::generate(); + sqlx::query( + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, 'teacher')", + ) + .bind(teacher.uuid()) + .bind(format!("homework-audience-{}", &teacher.key()[30..])) + .execute(&db) + .await + .unwrap(); + let ali = UserId::generate(); + sqlx::query( + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, 'student')", + ) + .bind(ali.uuid()) + .bind(format!("homework-audience-{}", &ali.key()[30..])) + .execute(&db) + .await + .unwrap(); + let veli = UserId::generate(); + sqlx::query( + "INSERT INTO app_user (id, username, created_at, role) \ + VALUES ($1, $2, 0, 'student')", + ) + .bind(veli.uuid()) + .bind(format!("homework-audience-{}", &veli.key()[30..])) + .execute(&db) + .await + .unwrap(); + let course = crate::db::course::a_test_course(&db).await; + let homework = create( + &db, + &course, + subject.get_id(), + HomeworkTitle::try_new("essay").unwrap(), + None, + Timestamp::from_millis(1), + Some(vec![ali]), + &teacher, + ) + .await + .unwrap(); + assert_eq!(homework.get_assigned(), Some(&[ali][..])); + assert_eq!( + list_for_user_in_course(&db, &course, &ali).await.unwrap().len(), + 1, + "the named student sees the subset" + ); + assert!( + list_for_user_in_course(&db, &course, &veli) + .await + .unwrap() + .is_empty(), + "an unnamed student sees nothing" + ); + // Widening back to the whole course (`Some(None)`) empties the + // junction: everyone — including the never-named student — is covered. + let widened = update(&db, homework, None, None, None, None, Some(None)) + .await + .unwrap(); + assert_eq!(widened.get_assigned(), None); + assert_eq!( + list_for_user_in_course(&db, &course, &veli).await.unwrap().len(), + 1, + "whole-course reaches the never-named student" + ); + } } diff --git a/src/db/homework_submission.rs b/src/db/homework_submission.rs index fe300c6..77801a5 100644 --- a/src/db/homework_submission.rs +++ b/src/db/homework_submission.rs @@ -79,7 +79,11 @@ pub async fn upsert( // student the homework no longer names must read as gone — the // same 404 their own lookup answers. r#"SELECT due_at AS "due_at: Timestamp" FROM homework - WHERE id = $1 AND (cardinality(assigned) = 0 OR $2 = ANY(assigned)) + WHERE id = $1 + AND (NOT EXISTS (SELECT 1 FROM homework_assignment a + WHERE a.homework = homework.id) + OR EXISTS (SELECT 1 FROM homework_assignment a + WHERE a.homework = homework.id AND a.student = $2)) FOR UPDATE"#, homework_id.uuid(), user.uuid() diff --git a/src/db/menu.rs b/src/db/menu.rs index bb04a45..d79aac4 100644 --- a/src/db/menu.rs +++ b/src/db/menu.rs @@ -240,12 +240,18 @@ pub async fn delete(db: &Database, menu: Menu) -> Result { if guard.is_none() { return Ok(None); } - // The children go first: both `menu_dish.menu` and - // `meal_attendance.menu` are `ON DELETE NO ACTION`, so the parent - // row cannot leave while they stand. + // The children go first: `menu_dish_tag.dish`, `menu_dish.menu` and + // `meal_attendance.menu` are all `ON DELETE NO ACTION`, so the + // parent rows cannot leave while they stand. sqlx::query!("DELETE FROM meal_attendance WHERE menu = $1", key) .execute(&mut *tx) .await?; + sqlx::query!( + "DELETE FROM menu_dish_tag WHERE dish IN (SELECT id FROM menu_dish WHERE menu = $1)", + key, + ) + .execute(&mut *tx) + .await?; sqlx::query!("DELETE FROM menu_dish WHERE menu = $1", key) .execute(&mut *tx) .await?; diff --git a/src/db/menu_dish.rs b/src/db/menu_dish.rs index e65c4b6..bb0f3b0 100644 --- a/src/db/menu_dish.rs +++ b/src/db/menu_dish.rs @@ -50,30 +50,47 @@ pub async fn create( ) .execute(&mut *tx) .await?; - let placed = sqlx::query_as!( - MenuDish, - "INSERT INTO menu_dish (id, menu, name, description, price_minor, tags, created_at) - SELECT $1, $2, $3, $4, $5, $6, $7 - WHERE (SELECT count(*) FROM menu_dish WHERE menu = $2) < $8 - RETURNING id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", tags AS \"tags: DishTags\", created_at AS \"created_at: Timestamp\"", + let placed = sqlx::query!( + "INSERT INTO menu_dish (id, menu, name, description, price_minor, created_at) + SELECT $1, $2, $3, $4, $5, $6 + WHERE (SELECT count(*) FROM menu_dish WHERE menu = $2) < $7", id.uuid(), menu_key, name.as_str(), description.as_ref().map(|d| d.as_str()), price_minor.as_minor(), - tags.as_slice(), created_at.as_millis(), cap, ) - .fetch_optional(&mut *tx) + .execute(&mut *tx) .await?; - match placed { - Some(dish) => Ok(dish), + if placed.rows_affected() == 0 { // The menu exists (locked above), so an empty result is the cap. - None => Err(AppError::Conflict( + return Err(AppError::Conflict( "the menu already carries the maximum number of dishes", - )), + )); } + // The tags are child rows: one per tag, `ord` carrying the order + // the caller gave the list in (already deduplicated by DishTags). + sqlx::query!( + "INSERT INTO menu_dish_tag (dish, tag, ord) + SELECT $1, tag, ord FROM unnest($2::text[]) WITH ORDINALITY AS t(tag, ord)", + id.uuid(), + tags.as_slice(), + ) + .execute(&mut *tx) + .await?; + let row = sqlx::query_as!( + MenuDish, + "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", + COALESCE((SELECT array_agg(t.tag ORDER BY t.ord) FROM menu_dish_tag t WHERE t.dish = menu_dish.id), '{}'::text[]) AS \"tags!: DishTags\", + created_at AS \"created_at: Timestamp\" + FROM menu_dish WHERE id = $1", + id.uuid(), + ) + .fetch_one(&mut *tx) + .await?; + Ok(row) }) .await } @@ -81,7 +98,9 @@ pub async fn create( pub async fn read(db: &Database, id: &MenuDishId) -> Result, AppError> { let row = sqlx::query_as!( MenuDish, - "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", tags AS \"tags: DishTags\", created_at AS \"created_at: Timestamp\" + "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", + COALESCE((SELECT array_agg(t.tag ORDER BY t.ord) FROM menu_dish_tag t WHERE t.dish = menu_dish.id), '{}'::text[]) AS \"tags!: DishTags\", + created_at AS \"created_at: Timestamp\" FROM menu_dish WHERE id = $1", id.uuid(), ) @@ -104,7 +123,9 @@ pub async fn list_for_menus(db: &Database, menus: &[MenuId]) -> Result = menus.iter().map(|m| m.key().to_string()).collect(); let rows = sqlx::query_as!( MenuDish, - "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", tags AS \"tags: DishTags\", created_at AS \"created_at: Timestamp\" + "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", + COALESCE((SELECT array_agg(t.tag ORDER BY t.ord) FROM menu_dish_tag t WHERE t.dish = menu_dish.id), '{}'::text[]) AS \"tags!: DishTags\", + created_at AS \"created_at: Timestamp\" FROM menu_dish WHERE menu = ANY($1) ORDER BY id ASC", &keys, ) @@ -144,25 +165,50 @@ pub async fn update( if bumped.is_none() { return Err(AppError::NotFound); } - let row = sqlx::query_as!( - MenuDish, + let updated = sqlx::query!( "UPDATE menu_dish SET name = COALESCE($2, name), description = CASE WHEN $3 THEN $4 ELSE description END, - price_minor = COALESCE($5, price_minor), - tags = COALESCE($6, tags) - WHERE id = $1 - RETURNING id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", tags AS \"tags: DishTags\", created_at AS \"created_at: Timestamp\"", + price_minor = COALESCE($5, price_minor) + WHERE id = $1", dish_key, name.as_ref().map(|n| n.as_str()), description.is_some(), description.as_ref().and_then(|d| d.as_ref()).map(|d| d.as_str()), price_minor.map(DishPrice::as_minor), - tags.as_ref().map(|t| t.as_slice()), ) - .fetch_optional(&mut *tx) + .execute(&mut *tx) + .await?; + if updated.rows_affected() == 0 { + return Err(AppError::NotFound); + } + // The tags are child rows now: an absent field keeps the stored + // ones, a carried field replaces the whole set (an empty list + // clears it) — under the same transaction as the bump above. + if let Some(tags) = &tags { + sqlx::query!("DELETE FROM menu_dish_tag WHERE dish = $1", dish_key) + .execute(&mut *tx) + .await?; + sqlx::query!( + "INSERT INTO menu_dish_tag (dish, tag, ord) + SELECT $1, tag, ord FROM unnest($2::text[]) WITH ORDINALITY AS t(tag, ord)", + dish_key, + tags.as_slice(), + ) + .execute(&mut *tx) + .await?; + } + let row = sqlx::query_as!( + MenuDish, + "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", + COALESCE((SELECT array_agg(t.tag ORDER BY t.ord) FROM menu_dish_tag t WHERE t.dish = menu_dish.id), '{}'::text[]) AS \"tags!: DishTags\", + created_at AS \"created_at: Timestamp\" + FROM menu_dish WHERE id = $1", + dish_key, + ) + .fetch_one(&mut *tx) .await?; - row.ok_or(AppError::NotFound) + Ok(row) }) .await } @@ -183,13 +229,23 @@ pub async fn delete(db: &Database, dish: MenuDish) -> Result } let row = sqlx::query_as!( MenuDish, - "DELETE FROM menu_dish WHERE id = $1 - RETURNING id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", tags AS \"tags: DishTags\", created_at AS \"created_at: Timestamp\"", + "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", + COALESCE((SELECT array_agg(t.tag ORDER BY t.ord) FROM menu_dish_tag t WHERE t.dish = menu_dish.id), '{}'::text[]) AS \"tags!: DishTags\", + created_at AS \"created_at: Timestamp\" + FROM menu_dish WHERE id = $1", dish_key, ) .fetch_optional(&mut *tx) .await?; - row.ok_or(AppError::NotFound) + let dish = row.ok_or(AppError::NotFound)?; + // The tag rows go first: `menu_dish_tag.dish` is NO ACTION too. + sqlx::query!("DELETE FROM menu_dish_tag WHERE dish = $1", dish_key) + .execute(&mut *tx) + .await?; + sqlx::query!("DELETE FROM menu_dish WHERE id = $1", dish_key) + .execute(&mut *tx) + .await?; + Ok(dish) }) .await } diff --git a/src/db/note.rs b/src/db/note.rs index bc946fe..acf982f 100644 --- a/src/db/note.rs +++ b/src/db/note.rs @@ -108,6 +108,15 @@ pub async fn update( /// separate `delete_for_note` call stays, as a harmless idempotent repeat. pub async fn delete(db: &Database, note: Note) -> Result<(Note, Vec), AppError> { tx_with_retry(db, true, async move |conn| { + // Links before rows: the outputs' citation links are their children + // (`ON DELETE NO ACTION`). + sqlx::query!( + "DELETE FROM rag_output_source WHERE output IN + (SELECT id FROM rag_output WHERE course_note = $1)", + note.id.uuid() + ) + .execute(&mut *conn) + .await?; sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.id.uuid()) .execute(&mut *conn) .await?; diff --git a/src/db/person.rs b/src/db/person.rs index f14dec3..2ac1868 100644 --- a/src/db/person.rs +++ b/src/db/person.rs @@ -11,7 +11,7 @@ use crate::domain::session::{SessionId, SessionToken}; use crate::domain::timestamp::Timestamp; use crate::domain::user::{PasswordHash, Username}; use crate::error::AppError; -use crate::tenant::{SchoolStatus, Slug}; +use crate::tenant::{SchoolId, SchoolStatus, Slug}; /// The raw account insert behind [`crate::service::person::create_or_load`]. /// The unique index on `username` is the whole availability check; the loser @@ -75,7 +75,7 @@ pub async fn memberships(db: &Database, person: &PersonId) -> Result Result<(), AppError> { sqlx::query!( - "INSERT INTO person_school (person, school, created_at) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING", + "INSERT INTO person_school (person, school, created_at) + SELECT $1, s.id, $3 FROM school s WHERE s.slug = $2 + ON CONFLICT DO NOTHING", person.uuid(), slug.as_str(), Timestamp::now().as_millis() @@ -127,8 +132,8 @@ pub async fn add_membership(db: &Database, person: &PersonId, slug: &Slug) -> Re /// first control-plane half, so `ON DELETE NO ACTION` never refuses the /// registry delete. Persons themselves survive: a person is a global /// account, not the school's. -pub async fn delete_memberships_by_school(db: &Database, slug: &Slug) -> Result<(), AppError> { - sqlx::query!("DELETE FROM person_school WHERE school = $1", slug.as_str()) +pub async fn delete_memberships_by_school(db: &Database, school: &SchoolId) -> Result<(), AppError> { + sqlx::query!("DELETE FROM person_school WHERE school = $1", school.uuid()) .execute(db) .await?; Ok(()) diff --git a/src/db/rag_output.rs b/src/db/rag_output.rs index 27d5e42..83f9018 100644 --- a/src/db/rag_output.rs +++ b/src/db/rag_output.rs @@ -4,12 +4,14 @@ //! the answer), which is what keeps the api-read bridge GET-only. Derived, //! disposable data: the row is dropped and regenerated whenever its input //! changes, so the cascades below — [`delete_for_note`] when the note goes, -//! [`delete_with_source`] when one of the attachments it was built from goes -//! — keep a stale output from outliving its input, even in a deployment with -//! no AI service connected. The row shape lives in +//! [`delete_with_source`] dropping the citation links a file delete strands +//! — keep the stored shape from outliving its input, even in a deployment +//! with no AI service connected. The row shape lives in //! [`crate::domain::rag_output`]. -use crate::database::Database; +use std::collections::HashMap; + +use crate::database::{Database, tx_with_retry}; use crate::db::page::PagedList; use crate::domain::course::CourseId; use crate::domain::course_note::CourseNoteId; @@ -19,53 +21,122 @@ use crate::domain::timestamp::Timestamp; use crate::error::AppError; use serde_json::Value; use sqlx::types::Json; +use uuid::Uuid; + +/// The plain `rag_output` columns. A citation list is not a column on the +/// row — the links live in `rag_output_source`, and the `query!` macros +/// cannot join an aggregate into a row — so every read decodes this shape +/// and one batch junction statement supplies the links that +/// [`RagOutputRow::into_rag_output`](RagOutputRow::into_rag_output) attaches. +#[derive(Debug, sqlx::FromRow)] +struct RagOutputRow { + id: RagOutputId, + course_note: CourseNoteId, + course: CourseId, + payload: Json, + generated_at: Timestamp, +} + +impl RagOutputRow { + fn into_rag_output(self, sources: Vec) -> RagOutput { + RagOutput { + id: self.id, + course_note: self.course_note, + course: self.course, + sources, + payload: self.payload, + generated_at: self.generated_at, + } + } +} + +/// The citation links of many outputs in one statement, grouped by output +/// uuid (the domain id newtype is not `Hash`), every list in `source` order — +/// the one order all reads rebuild, so a create's answer and any later read +/// hand back equal `Vec`s. +async fn sources_for_many( + db: &Database, + outputs: &[RagOutputId], +) -> Result>, AppError> { + let keys: Vec = outputs.iter().map(|output| output.uuid()).collect(); + let links = sqlx::query!( + r#"SELECT output, source AS "source: CourseNoteFileId" + FROM rag_output_source WHERE output = ANY($1) ORDER BY source"#, + &keys + ) + .fetch_all(db) + .await?; + let mut grouped: HashMap> = HashMap::new(); + for link in links { + grouped.entry(link.output).or_default().push(link.source); + } + Ok(grouped) +} + +/// The citation links of one output, in `source` order. +async fn sources_for( + db: &Database, + output: &RagOutputId, +) -> Result, AppError> { + let mut grouped = sources_for_many(db, std::slice::from_ref(output)).await?; + Ok(grouped.remove(&output.uuid()).unwrap_or_default()) +} pub async fn create( db: &Database, note: &CourseNoteId, course: &CourseId, - sources: Vec, + mut sources: Vec, payload: Value, ) -> Result { - let row = RagOutput { - id: RagOutputId::generate(), - course_note: note.clone(), - course: course.clone(), - sources, - payload: sqlx::types::Json(payload), - generated_at: Timestamp::now(), - }; - // whole-row-save-ok: insert of a fresh UUID row built in place — there is no prior row to clobber - let created = sqlx::query_as!( - RagOutput, - r#"INSERT INTO rag_output (id, course_note, course, sources, payload, generated_at) - VALUES ($1, $2, $3, $4, $5, $6) - RETURNING id AS "id: RagOutputId", course_note AS "course_note: CourseNoteId", - course AS "course: CourseId", - sources AS "sources: Vec", - payload AS "payload: Json", - generated_at AS "generated_at: Timestamp""#, - row.id.uuid(), - row.course_note.uuid(), - row.course.uuid(), - &row.sources - .iter() - .map(CourseNoteFileId::uuid) - .collect::>(), - row.payload.0, - row.generated_at.as_millis() - ) - .fetch_one(db) + // Link rows carry no order of their own; the source id is the order. + // Sorting here makes `create`'s answer equal to any later read's. + sources.sort_by_key(|file| file.uuid()); + let keys: Vec = sources.iter().map(|file| file.uuid()).collect(); + let id = RagOutputId::generate(); + let generated_at = Timestamp::now(); + // Owned binds: capturing `&CourseNoteId` / `&CourseId` across the + // `tx_with_retry` await poisons Send at every caller (ai/rag, course_notes). + let id_u = id.uuid(); + let note_u = note.uuid(); + let course_u = course.uuid(); + let at = generated_at.as_millis(); + let row = tx_with_retry(db, false, async move |tx| { + let created = sqlx::query_as!( + RagOutputRow, + r#"INSERT INTO rag_output (id, course_note, course, payload, generated_at) + VALUES ($1, $2, $3, $4, $5) + RETURNING id AS "id: RagOutputId", course_note AS "course_note: CourseNoteId", + course AS "course: CourseId", + payload AS "payload: Json", + generated_at AS "generated_at: Timestamp""#, + id_u, + note_u, + course_u, + &payload, + at + ) + .fetch_one(&mut *tx) + .await?; + sqlx::query!( + "INSERT INTO rag_output_source (output, source) + SELECT $1, s FROM unnest($2::uuid[]) AS t(s)", + created.id.uuid(), + &keys + ) + .execute(&mut *tx) + .await?; + Ok(created) + }) .await?; - Ok(created) + Ok(row.into_rag_output(sources)) } pub async fn read(db: &Database, id: &RagOutputId) -> Result, AppError> { let row = sqlx::query_as!( - RagOutput, + RagOutputRow, r#"SELECT id AS "id: RagOutputId", course_note AS "course_note: CourseNoteId", course AS "course: CourseId", - sources AS "sources: Vec", payload AS "payload: Json", generated_at AS "generated_at: Timestamp" FROM rag_output WHERE id = $1"#, @@ -73,7 +144,13 @@ pub async fn read(db: &Database, id: &RagOutputId) -> Result, ) .fetch_optional(db) .await?; - Ok(row) + match row { + Some(row) => { + let sources = sources_for(db, &row.id).await?; + Ok(Some(row.into_rag_output(sources))) + } + None => Ok(None), + } } /// A note's outputs, newest first. @@ -83,31 +160,67 @@ pub async fn list_for( limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - PagedList::new("rag_output WHERE course_note = $1", "ORDER BY id DESC") + let (rows, total) = PagedList::new("rag_output WHERE course_note = $1", "ORDER BY id DESC") .bind(note.uuid()) - .run::(limit, offset, db) - .await + .run::(limit, offset, db) + .await?; + let ids: Vec = rows.iter().map(|row| row.id).collect(); + let grouped = sources_for_many(db, &ids).await?; + let items = rows + .into_iter() + .map(|row| { + let sources = grouped.get(&row.id.uuid()).cloned().unwrap_or_default(); + row.into_rag_output(sources) + }) + .collect(); + Ok((items, total)) } pub async fn delete(db: &Database, id: &RagOutputId) -> Result { - let deleted = sqlx::query_as!( - RagOutput, - r#"DELETE FROM rag_output WHERE id = $1 - RETURNING id AS "id: RagOutputId", course_note AS "course_note: CourseNoteId", - course AS "course: CourseId", - sources AS "sources: Vec", - payload AS "payload: Json", - generated_at AS "generated_at: Timestamp""#, - id.uuid() - ) - .fetch_optional(db) + let id_u = id.uuid(); + let (row, sources) = tx_with_retry(db, false, async move |tx| { + let sources = sqlx::query!( + r#"SELECT source AS "source: CourseNoteFileId" + FROM rag_output_source WHERE output = $1 ORDER BY source"#, + id_u + ) + .fetch_all(&mut *tx) + .await? + .into_iter() + .map(|link| link.source) + .collect::>(); + sqlx::query!("DELETE FROM rag_output_source WHERE output = $1", id_u) + .execute(&mut *tx) + .await?; + sqlx::query_as!( + RagOutputRow, + r#"DELETE FROM rag_output WHERE id = $1 + RETURNING id AS "id: RagOutputId", course_note AS "course_note: CourseNoteId", + course AS "course: CourseId", + payload AS "payload: Json", + generated_at AS "generated_at: Timestamp""#, + id_u + ) + .fetch_optional(&mut *tx) + .await? + .map(|row| (row, sources)) + .ok_or(AppError::NotFound) + }) .await?; - deleted.ok_or(AppError::NotFound) + Ok(row.into_rag_output(sources)) } /// Cascade: every output of `note`. Deleting none is a success — a note -/// no service ever indexed has nothing to drop. +/// no service ever indexed has nothing to drop. The links go before the +/// rows: they are the rows' children (`ON DELETE NO ACTION`). pub async fn delete_for_note(db: &Database, note: &CourseNoteId) -> Result<(), AppError> { + sqlx::query!( + "DELETE FROM rag_output_source WHERE output IN + (SELECT id FROM rag_output WHERE course_note = $1)", + note.uuid() + ) + .execute(db) + .await?; sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.uuid()) .execute(db) .await?; @@ -129,6 +242,17 @@ pub async fn replace_for_note( payload: Value, ) -> Result { let created = create(db, note, course, sources, payload).await?; + // The superseded rows' links go first (`ON DELETE NO ACTION`), then the + // rows themselves. Neither delete can touch the row just written: its id + // is above every id the generator has minted before it. + sqlx::query!( + "DELETE FROM rag_output_source WHERE output IN + (SELECT id FROM rag_output WHERE course_note = $1 AND id < $2)", + note.uuid(), + created.id.uuid() + ) + .execute(db) + .await?; sqlx::query!( "DELETE FROM rag_output WHERE course_note = $1 AND id < $2", note.uuid(), @@ -139,13 +263,15 @@ pub async fn replace_for_note( Ok(created) } -/// Cascade: every output built from `file`. Runs on a file delete even -/// with no AI service connected, so a stale output cannot survive its -/// source. The GIN index on `sources` turns the containment test into a -/// lookup. +/// Cascade: the citation links that point at `file`. Runs on a file delete +/// even with no AI service connected — `ON DELETE NO ACTION` refuses the +/// file row while any link still cites it. An output a link belonged to +/// stops being true the moment its source is gone; the re-index a file +/// delete triggers regenerates it from what is left, and until then it +/// reads as a shorter — possibly empty — citation list. pub async fn delete_with_source(db: &Database, file: &CourseNoteFileId) -> Result<(), AppError> { sqlx::query!( - "DELETE FROM rag_output WHERE $1 = ANY(sources)", + "DELETE FROM rag_output_source WHERE source = $1", file.uuid() ) .execute(db) @@ -216,8 +342,9 @@ mod tests { .unwrap() } - /// A stored round-trips through JSONB with its sources list intact, and - /// the note cascade takes every row of the note with it. + /// A stored round-trips through JSONB with its citations intact, the + /// file row refuses to go while a citation stands (23503), and the note + /// cascade sweeps the links with the rows so the file can go after. #[tokio::test] async fn create_reads_back_and_cascades_from_the_note() { let (db, _leases) = crate::database::init_test_db().await; @@ -236,14 +363,29 @@ mod tests { assert_eq!(read_back.get_payload(), &json!({"answer": "x"})); assert_eq!(read_back.get_sources(), &[file.get_id().clone()]); + let refused = sqlx::query("DELETE FROM course_note_file WHERE id = $1") + .bind(file.get_id().uuid()) + .execute(&db) + .await; + let err = refused.unwrap_err(); + assert!(crate::database::foreign_key_violation(&err), "{err}"); + delete_for_note(&db, note.get_id()).await.unwrap(); assert!(read(&db, row.get_id()).await.unwrap().is_none()); + // The cascade swept the links with the outputs: the file row goes now. + sqlx::query("DELETE FROM course_note_file WHERE id = $1") + .bind(file.get_id().uuid()) + .execute(&db) + .await + .unwrap(); } /// Replace leaves exactly one row — the newest — and the source cascade - /// drops a row built from a file that is gone. + /// drops the link a file delete strands: the row survives reading as an + /// empty citation list until the re-index replaces it, and the file row + /// can go. #[tokio::test] - async fn replace_is_newest_wins_and_source_cascade_drops() { + async fn replace_is_newest_wins_and_source_cascade_empties_the_citations() { let (db, _leases) = crate::database::init_test_db().await; let note = note_of(&db, "n").await; let file = a_file(&db, ¬e).await; @@ -272,19 +414,36 @@ mod tests { delete_with_source(&db, file.get_id()).await.unwrap(); let (_, total) = list_for(&db, note.get_id(), None, 0).await.unwrap(); - assert_eq!(total, 0); + assert_eq!(total, 1); + let survivor = read(&db, second.get_id()).await.unwrap().unwrap(); + assert!(survivor.get_sources().is_empty()); + // Links first, file after: with the link gone the file row deletes. + sqlx::query("DELETE FROM course_note_file WHERE id = $1") + .bind(file.get_id().uuid()) + .execute(&db) + .await + .unwrap(); } - /// Deleting one row returns it; deleting it again is a 404. + /// Deleting one row returns it, citations included; deleting it again is + /// a 404. #[tokio::test] async fn delete_returns_the_row_then_refuses() { let (db, _leases) = crate::database::init_test_db().await; let note = note_of(&db, "n").await; - let row = create(&db, note.get_id(), note.get_course(), Vec::new(), json!({})) - .await - .unwrap(); + let file = a_file(&db, ¬e).await; + let row = create( + &db, + note.get_id(), + note.get_course(), + vec![file.get_id().clone()], + json!({}), + ) + .await + .unwrap(); let gone = delete(&db, row.get_id()).await.unwrap(); assert_eq!(gone.get_id(), row.get_id()); + assert_eq!(gone.get_sources(), &[file.get_id().clone()]); assert!(matches!( delete(&db, row.get_id()).await, Err(AppError::NotFound) diff --git a/src/db/settings.rs b/src/db/settings.rs index b7cb08f..59ea94b 100644 --- a/src/db/settings.rs +++ b/src/db/settings.rs @@ -1,37 +1,106 @@ //! The `settings` singleton: one row (`settings`, id `'school'`) holding the //! school's policy knobs. An absent row reads as the built-in defaults //! everywhere. +//! +//! The two vocabulary lists (`attendance_statuses`, `dietary_tags`) are no +//! longer array columns: they live in the child tables +//! `settings_attendance_status` and `settings_dietary_tag`, one row per +//! entry. The junction keeps no order, so every read sorts by entry and the +//! compare-and-set guard below compares row *sets*, not bytes. use sqlx::types::Json; -use crate::database::Database; +use crate::database::{Database, tx_with_retry}; use crate::domain::settings::{ExamKindDef, GradeBand, MealSlotDef, Settings}; use crate::error::AppError; -pub async fn load(db: &Database) -> Result { +/// Both sides of every set compare are sorted: the child tables keep no +/// order, and set equality does not want one. +fn sorted(values: &[String]) -> Vec { + let mut sorted = values.to_vec(); + sorted.sort(); + sorted +} + +/// The one read: row columns plus both vocabularies re-assembled from their +/// child tables. An absent dietary set reads as `None` — the same shape an +/// unset column used to carry. +async fn load_row<'e, E>(db: E) -> Result, AppError> +where + E: sqlx::PgExecutor<'e>, +{ let settings = sqlx::query_as!( Settings, - r#"SELECT - exam_kinds AS "exam_kinds: Json>", - attendance_statuses, - grade_bands AS "grade_bands: Json>", - max_file_bytes, - chatbot_history_turns, - max_chatbot_message_len, - max_chatbot_threads, - meal_slots AS "meal_slots: Json>", - dietary_tags, - meal_cancel_cutoff_minutes - FROM settings WHERE id = 'school'"# + r#"SELECT s.exam_kinds AS "exam_kinds: Json>", + COALESCE((SELECT array_agg(t.status ORDER BY t.status) + FROM settings_attendance_status t + WHERE t.settings = s.id), '{}') AS "attendance_statuses!: Vec", + s.grade_bands AS "grade_bands: Json>", + s.max_file_bytes, + s.chatbot_history_turns, + s.max_chatbot_message_len, + s.max_chatbot_threads, + s.meal_slots AS "meal_slots: Json>", + (SELECT array_agg(t.tag ORDER BY t.tag) + FROM settings_dietary_tag t + WHERE t.settings = s.id) AS dietary_tags, + s.meal_cancel_cutoff_minutes + FROM settings s WHERE s.id = 'school'"# ) .fetch_optional(db) .await?; + Ok(settings) +} + +pub async fn load(db: &Database) -> Result { + let settings = load_row(db).await?; Ok(settings.unwrap_or_else(Settings::defaults)) } -/// Persist the policy (single UPSERT on the fixed singleton id), -/// unconditionally — last write wins. Prefer [`save_if_unchanged`] -/// wherever the new policy was merged from a loaded snapshot. +/// Replace the attendance vocabulary wholesale. Callers run inside a +/// transaction (or inside the single CAS statement), so the delete and the +/// insert cannot be observed apart. +async fn replace_statuses( + conn: &mut sqlx::PgConnection, + statuses: &[String], +) -> Result<(), AppError> { + sqlx::query!("DELETE FROM settings_attendance_status WHERE settings = 'school'") + .execute(&mut *conn) + .await?; + sqlx::query!( + "INSERT INTO settings_attendance_status (settings, status) + SELECT 'school', t.status FROM unnest($1::text[]) AS t(status)", + statuses, + ) + .execute(&mut *conn) + .await?; + Ok(()) +} + +/// Replace the dietary vocabulary wholesale. `None` and `Some(empty)` both +/// write zero rows — "explicitly empty" and "never set" are the same state +/// on the child tables. +async fn replace_tags( + conn: &mut sqlx::PgConnection, + tags: Option<&[String]>, +) -> Result<(), AppError> { + sqlx::query!("DELETE FROM settings_dietary_tag WHERE settings = 'school'") + .execute(&mut *conn) + .await?; + sqlx::query!( + "INSERT INTO settings_dietary_tag (settings, tag) + SELECT 'school', t.tag FROM unnest($1::text[]) AS t(tag)", + tags, + ) + .execute(&mut *conn) + .await?; + Ok(()) +} + +/// Persist the policy (single UPSERT on the fixed singleton id plus a +/// wholesale rewrite of both vocabularies, one transaction), unconditionally +/// — last write wins. Prefer [`save_if_unchanged`] wherever the new policy +/// was merged from a loaded snapshot. pub async fn save(db: &Database, settings: Settings) -> Result { // whole-row-save-ok: test-only seeding; every production write merges from a loaded snapshot and goes through save_if_unchanged let exam_kinds = serde_json::to_value(&settings.exam_kinds.0) @@ -44,49 +113,40 @@ pub async fn save(db: &Database, settings: Settings) -> Result>", - attendance_statuses, - grade_bands AS "grade_bands: Json>", - max_file_bytes, - chatbot_history_turns, - max_chatbot_message_len, - max_chatbot_threads, - meal_slots AS "meal_slots: Json>", - dietary_tags, - meal_cancel_cutoff_minutes"#, - exam_kinds, - settings.attendance_statuses.as_slice(), - grade_bands, - settings.max_file_bytes, - settings.chatbot_history_turns, - settings.max_chatbot_message_len, - settings.max_chatbot_threads, - meal_slots, - settings.dietary_tags.as_deref(), - settings.meal_cancel_cutoff_minutes, - ) - .fetch_one(db) - .await?; - Ok(saved) + let attendance = sorted(&settings.attendance_statuses); + let dietary = settings.dietary_tags.clone(); + tx_with_retry(db, true, async move |tx| { + sqlx::query!( + r#"INSERT INTO settings (id, exam_kinds, grade_bands, max_file_bytes, + chatbot_history_turns, max_chatbot_message_len, + max_chatbot_threads, meal_slots, + meal_cancel_cutoff_minutes) + VALUES ('school', $1, $2, $3, $4, $5, $6, $7, $8) + ON CONFLICT (id) DO UPDATE SET + exam_kinds = EXCLUDED.exam_kinds, + grade_bands = EXCLUDED.grade_bands, + max_file_bytes = EXCLUDED.max_file_bytes, + chatbot_history_turns = EXCLUDED.chatbot_history_turns, + max_chatbot_message_len = EXCLUDED.max_chatbot_message_len, + max_chatbot_threads = EXCLUDED.max_chatbot_threads, + meal_slots = EXCLUDED.meal_slots, + meal_cancel_cutoff_minutes = EXCLUDED.meal_cancel_cutoff_minutes"#, + exam_kinds, + grade_bands, + settings.max_file_bytes, + settings.chatbot_history_turns, + settings.max_chatbot_message_len, + settings.max_chatbot_threads, + meal_slots, + settings.meal_cancel_cutoff_minutes, + ) + .execute(&mut *tx) + .await?; + replace_statuses(&mut *tx, &attendance).await?; + replace_tags(&mut *tx, dietary.as_deref()).await?; + load_row(&mut *tx).await?.ok_or(AppError::NotFound) + }) + .await } /// Persist the policy only while the stored row still matches `expected` @@ -97,25 +157,26 @@ pub async fn save(db: &Database, settings: Settings) -> Result( db: E, settings: Settings, @@ -134,57 +195,85 @@ where .map(|slots| serde_json::to_value(&slots.0)) .transpose() .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; - let expected_exam_kinds = serde_json::to_value(&expected.exam_kinds.0) - .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; - let expected_grade_bands = serde_json::to_value(&expected.grade_bands.0) - .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; - let expected_meal_slots = expected - .meal_slots + let attendance = sorted(&settings.attendance_statuses); + let expected_attendance = sorted(&expected.attendance_statuses); + // An empty `Some` must compare equal to the stored NULL an empty set + // reads as, so it is normalized away on the expected side. + let expected_dietary = expected + .dietary_tags .as_ref() - .map(|slots| serde_json::to_value(&slots.0)) - .transpose() - .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; + .filter(|tags| !tags.is_empty()) + .map(|tags| tags.as_slice()); let saved = sqlx::query_as!( Settings, - r#"INSERT INTO settings (id, exam_kinds, attendance_statuses, grade_bands, - max_file_bytes, chatbot_history_turns, - max_chatbot_message_len, max_chatbot_threads, - meal_slots, dietary_tags, meal_cancel_cutoff_minutes) - VALUES ('school', $1, $2, $3, $4, $5, $6, $7, $8, $9, $10) - ON CONFLICT (id) DO UPDATE SET - exam_kinds = $1, - attendance_statuses = $2, - grade_bands = $3, - max_file_bytes = $4, - chatbot_history_turns = $5, - max_chatbot_message_len = $6, - max_chatbot_threads = $7, - meal_slots = $8, - dietary_tags = $9, - meal_cancel_cutoff_minutes = $10 - WHERE settings.exam_kinds IS NOT DISTINCT FROM $11 - AND settings.attendance_statuses IS NOT DISTINCT FROM $12 - AND settings.grade_bands IS NOT DISTINCT FROM $13 - AND settings.max_file_bytes IS NOT DISTINCT FROM $14 - AND settings.chatbot_history_turns IS NOT DISTINCT FROM $15 - AND settings.max_chatbot_message_len IS NOT DISTINCT FROM $16 - AND settings.max_chatbot_threads IS NOT DISTINCT FROM $17 - AND settings.meal_slots IS NOT DISTINCT FROM $18 - AND settings.dietary_tags IS NOT DISTINCT FROM $19 - AND settings.meal_cancel_cutoff_minutes IS NOT DISTINCT FROM $20 - RETURNING - exam_kinds AS "exam_kinds: Json>", - attendance_statuses, - grade_bands AS "grade_bands: Json>", - max_file_bytes, - chatbot_history_turns, - max_chatbot_message_len, - max_chatbot_threads, - meal_slots AS "meal_slots: Json>", - dietary_tags, - meal_cancel_cutoff_minutes"#, + r#"WITH new_row AS ( + INSERT INTO settings (id, exam_kinds, grade_bands, max_file_bytes, + chatbot_history_turns, max_chatbot_message_len, + max_chatbot_threads, meal_slots, + meal_cancel_cutoff_minutes) + VALUES ('school', $1, $3, $4, $5, $6, $7, $8, $10) + ON CONFLICT (id) DO UPDATE SET + exam_kinds = $1, + grade_bands = $3, + max_file_bytes = $4, + chatbot_history_turns = $5, + max_chatbot_message_len = $6, + max_chatbot_threads = $7, + meal_slots = $8, + meal_cancel_cutoff_minutes = $10 + WHERE settings.exam_kinds IS NOT DISTINCT FROM $1 + AND settings.grade_bands IS NOT DISTINCT FROM $3 + AND settings.max_file_bytes IS NOT DISTINCT FROM $4 + AND settings.chatbot_history_turns IS NOT DISTINCT FROM $5 + AND settings.max_chatbot_message_len IS NOT DISTINCT FROM $6 + AND settings.max_chatbot_threads IS NOT DISTINCT FROM $7 + AND settings.meal_slots IS NOT DISTINCT FROM $8 + AND settings.meal_cancel_cutoff_minutes IS NOT DISTINCT FROM $10 + AND COALESCE((SELECT array_agg(s.status ORDER BY s.status) + FROM settings_attendance_status s + WHERE s.settings = settings.id), '{}') + IS NOT DISTINCT FROM $11::text[] + AND (SELECT array_agg(t.tag ORDER BY t.tag) + FROM settings_dietary_tag t + WHERE t.settings = settings.id) + IS NOT DISTINCT FROM $12::text[] + RETURNING exam_kinds, grade_bands, max_file_bytes, + chatbot_history_turns, max_chatbot_message_len, + max_chatbot_threads, meal_slots, meal_cancel_cutoff_minutes), + status_del AS ( + DELETE FROM settings_attendance_status + WHERE settings = 'school' AND EXISTS (SELECT 1 FROM new_row) + RETURNING 1), + status_ins AS ( + INSERT INTO settings_attendance_status (settings, status) + SELECT 'school', t.status FROM unnest($2::text[]) AS t(status) + CROSS JOIN (SELECT count(*) AS deleted FROM status_del) d + WHERE EXISTS (SELECT 1 FROM new_row) + RETURNING status), + tag_del AS ( + DELETE FROM settings_dietary_tag + WHERE settings = 'school' AND EXISTS (SELECT 1 FROM new_row) + RETURNING 1), + tag_ins AS ( + INSERT INTO settings_dietary_tag (settings, tag) + SELECT 'school', t.tag FROM unnest($9::text[]) AS t(tag) + CROSS JOIN (SELECT count(*) AS deleted FROM tag_del) d + WHERE EXISTS (SELECT 1 FROM new_row) + RETURNING tag) + SELECT r.exam_kinds AS "exam_kinds: Json>", + COALESCE((SELECT array_agg(status ORDER BY status) + FROM status_ins), '{}') AS "attendance_statuses!: Vec", + r.grade_bands AS "grade_bands: Json>", + r.max_file_bytes, + r.chatbot_history_turns, + r.max_chatbot_message_len, + r.max_chatbot_threads, + r.meal_slots AS "meal_slots: Json>", + (SELECT array_agg(tag ORDER BY tag) FROM tag_ins) AS dietary_tags, + r.meal_cancel_cutoff_minutes + FROM new_row r"#, exam_kinds, - settings.attendance_statuses.as_slice(), + &attendance, grade_bands, settings.max_file_bytes, settings.chatbot_history_turns, @@ -193,16 +282,8 @@ where meal_slots, settings.dietary_tags.as_deref(), settings.meal_cancel_cutoff_minutes, - expected_exam_kinds, - expected.attendance_statuses.as_slice(), - expected_grade_bands, - expected.max_file_bytes, - expected.chatbot_history_turns, - expected.max_chatbot_message_len, - expected.max_chatbot_threads, - expected_meal_slots, - expected.dietary_tags.as_deref(), - expected.meal_cancel_cutoff_minutes, + &expected_attendance, + expected_dietary, ) .fetch_optional(db) .await?; diff --git a/src/db/user.rs b/src/db/user.rs index 66bd04b..db6ba6d 100644 --- a/src/db/user.rs +++ b/src/db/user.rs @@ -512,7 +512,12 @@ pub async fn set_role_cascade( // board and its whole history, and the creator's `board_count` // seat stays taken, which is correct while the row it counts // exists. Stamped *before* the roster strip so the strip's - // `RETURNING` carries the closed row the caller fans out. + // read-back below carries the closed row the caller fans out. + // The strip itself is the junction's: the demoted user's roster + // rows are deleted and their board ids collected from + // RETURNING, then the affected rooms are read back in the same + // transaction — the junction delete cannot return the whole + // row the way the old `array_remove` `UPDATE` did. sqlx::query!( "UPDATE board SET closed_at = $2 WHERE creator = $1 AND closed_at IS NULL", target.uuid(), @@ -520,21 +525,29 @@ pub async fn set_role_cascade( ) .execute(&mut *tx) .await?; + let stripped = sqlx::query!( + "DELETE FROM board_participant WHERE participant = $1 RETURNING board", + target.uuid(), + ) + .fetch_all(&mut *tx) + .await?; + let stripped_boards: Vec = + stripped.into_iter().map(|row| row.board).collect(); let boards = sqlx::query_as!( Board, - r#"UPDATE board - SET participants = array_remove(participants, $1) - WHERE $1 = ANY(participants) OR creator = $1 - RETURNING id AS "id: BoardId", - creator AS "creator: UserId", - title AS "title: BoardTitle", - participants AS "participants: Vec", - locked, - locked_by AS "locked_by: UserId", - locked_at AS "locked_at: Timestamp", - epoch, - closed_at AS "closed_at: Timestamp", - created_at AS "created_at: Timestamp""#, + r#"SELECT b.id AS "id: BoardId", b.creator AS "creator: UserId", + b.title AS "title: BoardTitle", + ARRAY(SELECT p.participant FROM board_participant p + WHERE p.board = b.id ORDER BY p.participant) + AS "participants!: Vec", + b.locked, b.locked_by AS "locked_by: UserId", + b.locked_at AS "locked_at: Timestamp", b.epoch, + b.closed_at AS "closed_at: Timestamp", + b.created_at AS "created_at: Timestamp" + FROM board b + WHERE b.id = ANY($1::uuid[]) OR b.creator = $2 + ORDER BY b.id"#, + &stripped_boards, target.uuid(), ) .fetch_all(&mut *tx) @@ -549,10 +562,11 @@ pub async fn set_role_cascade( } if !role.at_least(Role::Teacher) { - // Course staffing goes — only teacher+ may hold a seat on the - // list. + // Course staffing goes — only teacher+ may hold a seat, and the + // seat is a `course_teacher` row now: one `DELETE` by its + // `teacher` index takes every assignment. sqlx::query!( - "UPDATE course SET teachers = array_remove(teachers, $1) WHERE $1 = ANY(teachers)", + "DELETE FROM course_teacher WHERE teacher = $1", target.uuid(), ) .execute(&mut *tx) diff --git a/src/domain/class_blueprint.rs b/src/domain/class_blueprint.rs index c00abe0..a8cd385 100644 --- a/src/domain/class_blueprint.rs +++ b/src/domain/class_blueprint.rs @@ -48,13 +48,14 @@ impl ClassBlueprintId { } } -/// One grade's template. `grade` is stored beside the key it *is*, so a read -/// never has to parse a record id back into a domain value. -#[derive(Debug, Clone, sqlx::FromRow)] +/// One grade's template. The id is the grade label itself — the key one +/// grade always maps to — stored here beside the `grade` field so a read +/// never has to parse a record id back into a domain value. `courses` is +/// not a column of the row: it is the `blueprint_course` junction, joined +/// on by the db layer (sorted by course, which is the order every CAS +/// comparison relies on). +#[derive(Debug, Clone)] pub struct ClassBlueprint { - /// The table's `TEXT` primary key column, stored once and read into both - /// this field and `grade` — the key *is* the grade label. - #[sqlx(rename = "grade")] pub(crate) id: ClassBlueprintId, pub(crate) grade: ClassGrade, pub(crate) courses: Vec, diff --git a/src/domain/course.rs b/src/domain/course.rs index 01d96e2..7b2977a 100644 --- a/src/domain/course.rs +++ b/src/domain/course.rs @@ -96,11 +96,12 @@ impl CourseKind { /// `creator` owns the course for good — only they (or a manager+) may delete /// it. `teachers` are the staff a manager assigned to run it: full management /// rights inside the course, no power to delete it or change the assignment -/// list. +/// list. The assignment itself is `course_teacher` rows; the struct carries +/// the resolved list, joined on by the db layer. /// /// Fields are crate-visible: [`crate::db::course`] mints the rows on create /// and reads the id when updating and cascading a delete. -#[derive(Debug, Clone, sqlx::FromRow)] +#[derive(Debug, Clone)] pub struct Course { pub(crate) id: CourseId, pub(crate) creator: UserId, @@ -146,7 +147,8 @@ impl Course { &self.creator == user } - /// The staff assigned to run this course, in assignment order. + /// The staff assigned to run this course. Assignment order is not kept: + /// the links are `course_teacher` rows now, and a set has no order. pub fn get_teachers(&self) -> &[UserId] { &self.teachers } diff --git a/src/domain/dietary_profile.rs b/src/domain/dietary_profile.rs index b407ef5..2ce189c 100644 --- a/src/domain/dietary_profile.rs +++ b/src/domain/dietary_profile.rs @@ -43,7 +43,8 @@ impl DietaryProfileId { /// The tags a student's diet carries, drawn from the school's `dietary_tags` /// list — the same vocabulary a dish is tagged from, deduplicated and in the -/// order given. Stored as a `TEXT[]` column. `no_pg_array` skips the derive's +/// order given. Stored one row per tag in `dietary_profile_tag` (an `ord` +/// column keeps the given order). `no_pg_array` skips the derive's /// element-array assertion (which a `Vec` inner cannot satisfy); the impls /// still delegate to `Vec`. #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] diff --git a/src/domain/homework.rs b/src/domain/homework.rs index 3834c3b..99a2831 100644 --- a/src/domain/homework.rs +++ b/src/domain/homework.rs @@ -81,11 +81,12 @@ impl HomeworkDescription { } } -/// A homework assignment. `assigned` is the optional student subset (`uuid[] -/// NULL`): `NULL` and an empty list both mean "the whole course" — see -/// [`Homework::student_sees`]. Because whole-course homework carries no roster, -/// a student who enrolls later is covered automatically; a subset is a fixed -/// snapshot of the students named at assign (or last PATCH) time. +/// A homework assignment. `assigned` is the optional student subset, +/// assembled from the `homework_assignment` child rows (`None` = no rows = +/// the whole course — see [`Homework::student_sees`]). Because whole-course +/// homework carries no roster, a student who enrolls later is covered +/// automatically; a subset is a fixed snapshot of the students named at +/// assign (or last PATCH) time. #[derive(Debug, Clone, sqlx::FromRow)] pub struct Homework { pub(crate) id: HomeworkId, diff --git a/src/domain/menu_dish.rs b/src/domain/menu_dish.rs index 44ff4a6..00759c3 100644 --- a/src/domain/menu_dish.rs +++ b/src/domain/menu_dish.rs @@ -111,8 +111,9 @@ impl DishPrice { /// The dietary tags a dish carries, drawn from the school's `dietary_tags` /// list. Deduplicated, order preserved — the list is what a student's profile -/// is matched against, so a repeat carries no extra meaning. Stored as a -/// `TEXT[]` column. +/// is matched against, so a repeat carries no extra meaning. Stored one row +/// per tag in `menu_dish_tag` — an `ord` column keeps the given order, and +/// reads re-aggregate in that order. #[derive(Debug, Clone, PartialEq, Eq, Type)] #[sqlx(transparent, no_pg_array)] pub struct DishTags(Vec); diff --git a/src/domain/rag_output.rs b/src/domain/rag_output.rs index a85b873..cc9dece 100644 --- a/src/domain/rag_output.rs +++ b/src/domain/rag_output.rs @@ -9,7 +9,7 @@ //! from both sides of what it was built from — //! [`delete_for_note`](crate::db::rag_output::delete_for_note) when the note //! goes, [`delete_with_source`](crate::db::rag_output::delete_with_source) -//! when one of the attachments it was built from goes — so a stale output +//! dropping the citation links a file delete strands — so the stored shape //! never outlives its input, even in a deployment with no AI service //! connected. Persistence lives in [`crate::db::rag_output`]. @@ -57,16 +57,19 @@ impl RagOutputId { } } -#[derive(Debug, Clone, sqlx::FromRow)] +/// The backend's stored rag-output row. No `sqlx::FromRow`: the citations +/// are `rag_output_source` link rows, not columns — the db layer decodes +/// its own plain-columns struct and attaches the links. +#[derive(Debug, Clone)] pub struct RagOutput { pub(crate) id: RagOutputId, pub(crate) course_note: CourseNoteId, /// The note's course, denormalised so a course-wide read needs no join. pub(crate) course: CourseId, - /// The attachments the output was built from, as they stood at generation - /// time. Deleting any one of them drops this row - /// ([`delete_with_source`](crate::db::rag_output::delete_with_source)) - /// rather than leaving an output citing a file that no longer exists. + /// The attachments the output was built from, in source-id order. + /// Stored as `rag_output_source` link rows; deleting a file drops its + /// links ([`delete_with_source`](crate::db::rag_output::delete_with_source)) + /// and deleting an output drops its links, before either parent goes. pub(crate) sources: Vec, /// The service's answer, stored verbatim in a JSONB column. Opaque to the /// backend — it is a service-owned shape, so this side neither validates diff --git a/src/service/board.rs b/src/service/board.rs index f0c8701..cdb4df3 100644 --- a/src/service/board.rs +++ b/src/service/board.rs @@ -1,5 +1,5 @@ //! Board workflows: the roster gates the REST surface drives, and the -//! atomic-array write that replaced the old process-wide roster lock. The +//! atomic-union insert that replaced the old process-wide roster lock. The //! queries live in [`crate::db::board`]; the room's WebSocket keeps its //! own binding policy in [`crate::web::board_ws`], reading through here. @@ -117,10 +117,10 @@ pub async fn resolve_participants( /// **all-or-nothing**: an over-full union is refused with a `409` naming the /// two numbers and the roster is left exactly as it was. /// -/// The merge itself is one atomic guarded statement -/// ([`board::invite_group`]): `SET` and guard both read the row version the -/// `UPDATE` is acting on, so of two concurrent invites neither can drop the -/// other's group and the cap refuses the second — the property the old +/// The merge itself is one serialized union ([`board::invite_group`]): the +/// board row is locked first, so of two concurrent invites the second +/// waits, counts against the first's committed roster and the cap refuses +/// it — neither can drop the other's group, the property the old /// process-wide roster lock existed to provide, now enforced by the row /// itself. Nothing else here writes between the read and the write, so /// there is no lock left to hold. diff --git a/src/service/class_blueprint.rs b/src/service/class_blueprint.rs index 862b583..16b344f 100644 --- a/src/service/class_blueprint.rs +++ b/src/service/class_blueprint.rs @@ -171,7 +171,8 @@ pub async fn set_courses( /// a silent detach of somebody else's additions. Known hole, accepted: the /// grade label *is* the primary key and the comparison is by **content**, so /// a blueprint deleted and recreated at the same grade with the same list -/// satisfies `WHERE courses = $held` and this call deletes the *new* row. +/// names the same course set as the stored junction rows, and this call +/// deletes the *new* row. /// /// Content-equal is intent-equal — the end state is the one the caller /// asked for — and telling the two apart needs a revision column on the @@ -448,6 +449,15 @@ mod tests { .unwrap() .unwrap(); let blueprint = a_blueprint(vec![course.clone()], &db).await; + // Children first, the ordering the course's own cascade runs: with the + // junction row standing, the raw course delete below is a foreign-key + // refusal. What is left is exactly the pump-window state the handle + // still walks. + sqlx::query("DELETE FROM blueprint_course WHERE course = $1") + .bind(course.uuid()) + .execute(&db) + .await + .unwrap(); sqlx::query("DELETE FROM course WHERE id = $1") .bind(course.uuid()) .execute(&db) @@ -810,6 +820,14 @@ mod tests { let a = a_section("9-A", &db).await; let b = a_section("9-B", &db).await; let mut blueprint = a_blueprint(vec![astronomy.clone(), algebra.clone()], &db).await; + // Children first, the ordering the course's own cascade runs — the + // junction row standing would make the raw delete a foreign-key + // refusal. The handle below still walks the list it read. + sqlx::query("DELETE FROM blueprint_course WHERE course = $1") + .bind(astronomy.uuid()) + .execute(&db) + .await + .unwrap(); sqlx::query("DELETE FROM course WHERE id = $1") .bind(astronomy.uuid()) .execute(&db) diff --git a/src/service/course.rs b/src/service/course.rs index cdbdb12..c7ca4b4 100644 --- a/src/service/course.rs +++ b/src/service/course.rs @@ -17,10 +17,11 @@ use crate::service::term; /// accepted race (see README concurrency model): a term archived after this /// read still lets the write through. pub async fn require_open(db: &Database, course: &Course) -> Result<(), AppError> { - match course.get_term() { - None => Ok(()), - Some(term) => term::require_open(db, term).await, - } + let Some(term) = course.get_term().cloned() else { + return Ok(()); + }; + let db = db.clone(); + term::require_open(&db, &term).await } pub async fn create( diff --git a/src/service/rag_output.rs b/src/service/rag_output.rs index 2c09fe8..bd6437a 100644 --- a/src/service/rag_output.rs +++ b/src/service/rag_output.rs @@ -35,9 +35,9 @@ pub async fn delete_for_note(db: &Database, note: &CourseNoteId) -> Result<(), A rag_output::delete_for_note(db, note).await } -/// Cascade: every output built from `file`. Runs on a file delete even -/// with no AI service connected, so a stale output cannot survive its -/// source. +/// Cascade: the citation links pointing at `file`. Runs on a file delete +/// even with no AI service connected — the file row refuses to go while a +/// link still cites it. pub async fn delete_with_source(db: &Database, file: &CourseNoteFileId) -> Result<(), AppError> { rag_output::delete_with_source(db, file).await } diff --git a/src/tenant.rs b/src/tenant.rs index 8e9ec42..b36f6fc 100644 --- a/src/tenant.rs +++ b/src/tenant.rs @@ -23,10 +23,13 @@ use serde::Serialize; use sqlx::postgres::PgConnectOptions; use crate::constant::{MAX_SLUG_LEN, MIN_SLUG_LEN}; +use uuid::Uuid; + use crate::database::{ Database, create_database_sql, is_duplicate_database, migrate_school, school_pool, unique_violation, }; +use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; use crate::error::{AppError, ValidationError}; use crate::module::ModuleSet; @@ -44,12 +47,12 @@ pub const DEMO_SLUG: &str = "demo"; /// aimed at them. pub const RESERVED_SLUGS: [&str; 3] = ["builder", "control", "person"]; -/// A school's identity everywhere it is named: the cookie prefix, the database -/// name, and the files subdirectory. The character set is deliberately the -/// intersection of what all three accept — lowercase alphanumerics and `-`, -/// starting with an alphanumeric. It is also what makes the database names -/// injective: `school_db_name` maps `-` to `_`, and `_` is not in the slug -/// charset, so two slugs can never collide onto one database. +/// A school's public label: the cookie prefix, the URL paths and the files +/// subdirectory. The character set is deliberately the intersection of what +/// all three accept — lowercase alphanumerics and `-`, starting with an +/// alphanumeric. It is no longer the school's identity: the registry row's +/// uuid is (see [`SchoolId`]), which is why a label rename can no longer +/// orphan anything structural. #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, sqlx::Type)] #[serde(transparent)] #[sqlx(transparent)] @@ -98,11 +101,17 @@ impl std::fmt::Display for Slug { } } -/// A school database's name: `{control_db}_school_{slug}`, the slug's `-` -/// spelled `_` (Postgres identifiers allow `-` only quoted, and the name is -/// built, not user-typed). Injective — see [`Slug`]'s charset note. -pub fn school_db_name(control_db: &str, slug: &Slug) -> String { - format!("{}_school_{}", control_db, slug.as_str().replace('-', "_")) +/// A school database's name: `{control_db}_school_{uuid hex}` — the uuid's +/// lowercase hex without dashes (the contract's example: +/// `019732e3-7b00-7000-8000-00000000dead` → +/// `…_school_019732e37b007000800000000000dead`). Fixed-width and injective: +/// two uuids never share a database, and the slug appears nowhere, so a slug +/// rename can never orphan one. The server's 63-byte identifier cap can clip +/// the name's tail on deployments with a long control-database name — uuid +/// v7's random tail still separates schools far past any realistic registry +/// size, and creator and dialler truncate identically. +pub fn school_db_name(control_db: &str, id: Uuid) -> String { + format!("{}_school_{}", control_db, id.simple()) } /// Whether a school may be reached at all. Suspension is immediate and total: @@ -137,39 +146,51 @@ impl SchoolStatus { } } -/// A school's id **is** its slug — the registry can never hold two rows for -/// one school, and the database name is derived from the same word. -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub struct SchoolId(Slug); +/// A school's identity inside the control plane: the registry row's uuid +/// primary key, app-minted uuid v7. The database name and every structural +/// reference (person_school) mint from it; the slug — the public label — never. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct SchoolId(Uuid); impl SchoolId { - pub fn from_slug(slug: &Slug) -> Self { - Self(slug.clone()) + /// Wrap a uuid read off a registry row — naming a school that already + /// exists (a test evicting the demo pool, say) rather than minting one. + pub fn from_uuid(id: Uuid) -> Self { + Self(id) + } + + /// The next id in write order — see + /// [`crate::domain::monotonic_id::next_uuid`]. + pub fn generate() -> Self { + Self(next_uuid()) } - pub fn key(&self) -> &str { - self.0.as_str() + pub fn uuid(self) -> Uuid { + self.0 } } -/// A row in the control database's school registry. #[derive(Debug, Clone, sqlx::FromRow)] pub struct School { + id: Uuid, slug: Slug, name: String, status: SchoolStatus, created_at: Timestamp, - /// Which product modules this school has bought, as their stored names. - /// Kept as strings rather than a [`ModuleSet`] so a name this binary does - /// not know (an older deploy reading a newer row) is data to ignore, not a - /// deserialization failure that would lock the school out entirely. + /// Which product modules this school has bought, as their stored names — + /// joined in from `school_module` by every read below, never a column of + /// `school`. Kept as strings rather than a [`ModuleSet`] so a name this + /// binary does not know (an older deploy reading a newer row) is data to + /// ignore, not a deserialization failure that would lock the school out + /// entirely. modules: Vec, } impl School { - /// The id is the slug; rebuilt rather than stored a second copy. + /// The row's uuid — the identity the database name and every structural + /// reference (person_school) mint from. The slug is not it. pub fn get_id(&self) -> SchoolId { - SchoolId::from_slug(&self.slug) + SchoolId(self.id) } pub fn slug(&self) -> &Slug { @@ -207,7 +228,11 @@ impl School { pub async fn read(slug: &Slug, control: &Database) -> Result, AppError> { sqlx::query_as::<_, School>( - "SELECT slug, name, status, created_at, modules FROM school WHERE slug = $1", + "SELECT s.id, s.slug, s.name, s.status, s.created_at, + COALESCE(array_agg(sm.module) FILTER (WHERE sm.module IS NOT NULL), '{}') AS modules + FROM school s LEFT JOIN school_module sm ON sm.school = s.id + WHERE s.slug = $1 + GROUP BY s.id", ) .bind(slug.as_str()) .fetch_optional(control) @@ -224,8 +249,11 @@ impl School { control: &Database, ) -> Result<(Vec, i64), AppError> { let rows = sqlx::query_as::<_, School>( - "SELECT slug, name, status, created_at, modules FROM school - ORDER BY created_at DESC, slug DESC + "SELECT s.id, s.slug, s.name, s.status, s.created_at, + COALESCE(array_agg(sm.module) FILTER (WHERE sm.module IS NOT NULL), '{}') AS modules + FROM school s LEFT JOIN school_module sm ON sm.school = s.id + GROUP BY s.id + ORDER BY s.created_at DESC, s.slug DESC LIMIT $1 OFFSET $2", ) .bind(limit) @@ -238,16 +266,24 @@ impl School { Ok((rows, total)) } - /// Rename a school. The slug is immutable — it names a database and a - /// directory, so it is the one field a rename must not touch. + /// Rename a school — its display `name`, not its slug. The slug is + /// immutable in this cut (it is the cookie prefix and the files + /// subdirectory), though it no longer names the database: the uuid does. pub async fn update_name( slug: &Slug, name: &str, control: &Database, ) -> Result { sqlx::query_as::<_, School>( - "UPDATE school SET name = $1 WHERE slug = $2 - RETURNING slug, name, status, created_at, modules", + "WITH updated AS ( + UPDATE school SET name = $1 WHERE slug = $2 + RETURNING id, slug, name, status, created_at + ) + SELECT u.id, u.slug, u.name, u.status, u.created_at, + COALESCE(array_agg(sm.module) FILTER (WHERE sm.module IS NOT NULL), '{}') AS modules + FROM updated u + LEFT JOIN school_module sm ON sm.school = u.id + GROUP BY u.id, u.slug, u.name, u.status, u.created_at", ) .bind(name) .bind(slug.as_str()) @@ -261,6 +297,9 @@ impl School { #[derive(Clone)] pub struct Tenants { control: Database, + /// Live school pools, keyed by the school's uuid hex (no dashes — the + /// same form [`school_db_name`] spells). The slug never keys it: a pool + /// belongs to a school's identity, not to its current label. cache: Arc>>, /// Dial options for the Postgres server the control pool came from — a /// school pool is the same dial with only the database swapped. @@ -297,11 +336,11 @@ impl Tenants { base: PgConnectOptions, control_db: String, leases: crate::database::TestDatabases, - prewarmed: impl IntoIterator, + prewarmed: impl IntoIterator, ) -> Tenants { let cache: HashMap = prewarmed .into_iter() - .map(|(slug, db)| (slug.as_str().to_owned(), db)) + .map(|(id, db)| (id.uuid().simple().to_string(), db)) .collect(); Tenants { control, @@ -346,12 +385,12 @@ impl Tenants { match School::read(slug, &self.control).await? { None => Err(AppError::Unauthorized), Some(school) if school.status == SchoolStatus::Suspended => { - self.evict(slug).await; + self.evict(school.get_id()).await; Err(AppError::Forbidden("school is suspended")) } Some(school) => Ok(ResolvedTenant { slug: slug.clone(), - db: self.handle(slug).await?, + db: self.handle(school.get_id()).await?, modules: school.modules(), }), } @@ -364,14 +403,17 @@ impl Tenants { let school = School::read(slug, &self.control) .await? .ok_or(AppError::NotFound)?; - Ok((self.handle(slug).await?, school.status)) + Ok((self.handle(school.get_id()).await?, school.status)) } /// Register a school and bring its database into being: registry row first /// (so a lost race is a `409` and not a half-made database), then - /// `CREATE DATABASE`, then the school schema. + /// `CREATE DATABASE`, then the school schema. The caller mints the id — + /// the web create path is the one minter — and it becomes the row's PK, + /// the database name's source and the pool cache key. pub async fn create( &self, + id: SchoolId, slug: &Slug, name: &str, modules: ModuleSet, @@ -380,37 +422,53 @@ impl Tenants { // every violation at once), but the registry refuses an unsatisfiable // set too, so no future caller can persist one. modules.validate()?; + // The registry row and its entitlements land as one transaction: a + // school row never stands without the modules its creation asked for. + let mut tx = self.control.begin().await?; let inserted = sqlx::query( - "INSERT INTO school (slug, name, status, created_at, modules) + "INSERT INTO school (id, slug, name, status, created_at) VALUES ($1, $2, $3, $4, $5)", ) + .bind(id.uuid()) .bind(slug.as_str()) .bind(name) .bind(SchoolStatus::Active) .bind(Timestamp::now().as_millis()) - .bind(modules.names()) - .execute(&self.control) + .execute(&mut *tx) .await; if let Err(err) = inserted { - // The slug is the table's only unique key, so a unique violation - // here is exactly "taken" — a rival's row, or the row already - // stood. Same verdict either way, as it always was. + // The slug's UNIQUE constraint (`school_slug`) is the only key a + // rival can collide on — a fresh uuid v7 does not repeat. So a + // unique violation here is exactly "taken": a rival's row, or the + // row already stood. Same verdict either way, as it always was. if unique_violation(&err).is_some() { return Err(AppError::Conflict("school slug already taken")); } return Err(err.into()); } + for name in modules.names() { + sqlx::query("INSERT INTO school_module (school, module) VALUES ($1, $2)") + .bind(id.uuid()) + .bind(name) + .execute(&mut *tx) + .await?; + } + tx.commit().await?; // Everything past the registry row rolls that row back on failure: // the row is what makes the slug "taken", and a slug taken by a // school that never came to exist is wedged for good. (A database // created before the failure is not a wedge: the adopt branch in // [`Self::bring_up`] picks it up, migrations being idempotent.) - let db = match self.bring_up(slug).await { + let db = match self.bring_up(id).await { Ok(db) => db, Err(err) => { - let _ = sqlx::query("DELETE FROM school WHERE slug = $1") - .bind(slug.as_str()) + let _ = sqlx::query("DELETE FROM school_module WHERE school = $1") + .bind(id.uuid()) + .execute(&self.control) + .await; + let _ = sqlx::query("DELETE FROM school WHERE id = $1") + .bind(id.uuid()) .execute(&self.control) .await; return Err(err); @@ -418,14 +476,14 @@ impl Tenants { }; let size = { let mut cache = self.cache.write().expect("tenant cache lock"); - cache.insert(slug.as_str().to_string(), db.clone()); + cache.insert(id.uuid().simple().to_string(), db.clone()); cache.len() }; Self::report_size(size); // A test deployment's lease learns every school the deployment // mints, so a school created mid-test dies with the deployment. if let Some(leases) = &self.leases { - leases.track(&school_db_name(&self.control_db, slug)); + leases.track(&school_db_name(&self.control_db, id.uuid())); } Ok(db) } @@ -433,8 +491,8 @@ impl Tenants { /// Create (or adopt) the school's database and apply the school schema to /// it. Split out of [`Tenants::create`] so one `?` chain can be rolled /// back as a unit. - async fn bring_up(&self, slug: &Slug) -> Result { - let db_name = school_db_name(&self.control_db, slug); + async fn bring_up(&self, id: SchoolId) -> Result { + let db_name = school_db_name(&self.control_db, id.uuid()); // `CREATE DATABASE` cannot run inside a transaction; `Pool::execute` // sends it as a bare autocommit statement. A name left over by a // create that died before its rollback is adopted, not fought. @@ -459,19 +517,17 @@ impl Tenants { /// Flip a school between active and suspended. Suspending also drops the /// cached pool, so nothing that already resolved keeps serving. pub async fn set_status(&self, slug: &Slug, status: SchoolStatus) -> Result<(), AppError> { - let updated = sqlx::query_as::<_, School>( - "UPDATE school SET status = $1 WHERE slug = $2 - RETURNING slug, name, status, created_at, modules", - ) - .bind(status) - .bind(slug.as_str()) - .fetch_optional(&self.control) - .await?; - if updated.is_none() { + let updated: Option = + sqlx::query_scalar("UPDATE school SET status = $1 WHERE slug = $2 RETURNING id") + .bind(status) + .bind(slug.as_str()) + .fetch_optional(&self.control) + .await?; + let Some(id) = updated else { return Err(AppError::NotFound); - } + }; if status == SchoolStatus::Suspended { - self.evict(slug).await; + self.evict(SchoolId(id)).await; } Ok(()) } @@ -482,17 +538,29 @@ impl Tenants { /// stale answer. pub async fn set_modules(&self, slug: &Slug, modules: &ModuleSet) -> Result<(), AppError> { modules.validate()?; - let updated = sqlx::query_as::<_, School>( - "UPDATE school SET modules = $1 WHERE slug = $2 - RETURNING slug, name, status, created_at, modules", - ) - .bind(modules.names()) - .bind(slug.as_str()) - .fetch_optional(&self.control) - .await?; - if updated.is_none() { + // The swap is parent + children in one transaction: take the registry + // row's lock so racing sellers serialize, then replace the whole shelf. + let mut tx = self.control.begin().await?; + let id: Option = + sqlx::query_scalar("SELECT id FROM school WHERE slug = $1 FOR UPDATE") + .bind(slug.as_str()) + .fetch_optional(&mut *tx) + .await?; + let Some(id) = id else { return Err(AppError::NotFound); + }; + sqlx::query("DELETE FROM school_module WHERE school = $1") + .bind(id) + .execute(&mut *tx) + .await?; + for name in modules.names() { + sqlx::query("INSERT INTO school_module (school, module) VALUES ($1, $2)") + .bind(id) + .bind(name) + .execute(&mut *tx) + .await?; } + tx.commit().await?; Ok(()) } @@ -500,26 +568,38 @@ impl Tenants { /// pool. Irreversible on purpose — there is no soft-delete state, that is /// what [`SchoolStatus::Suspended`] is for. pub async fn drop(&self, slug: &Slug) -> Result<(), AppError> { + // The id comes off the row: the database is named by the uuid, not + // the slug. A row already gone means the goal state stands — nothing + // to destroy left. + let Some(school) = School::read(slug, &self.control).await? else { + return Ok(()); + }; + let id = school.get_id(); // Close the pool first: nothing should be dialling a school whose // database is about to go away, and `WITH (FORCE)` should never find // one of our connections to kill. - self.evict(slug).await; - // The control-plane membership rows point at the school by slug, and - // `ON DELETE NO ACTION` would refuse the registry delete while any - // stand. Person sessions carry no school, so only memberships go — - // the persons themselves survive (a person is a global account, not - // the school's). - crate::db::person::delete_memberships_by_school(&self.control, slug).await?; - sqlx::query("DELETE FROM school WHERE slug = $1") - .bind(slug.as_str()) + self.evict(id).await; + // The control-plane rows pointing at the school by uuid — membership + // and entitlement alike — go first: `ON DELETE NO ACTION` would refuse + // the registry delete while any stand. Person sessions carry no + // school, so only memberships go — the persons themselves survive (a + // person is a global account, not the school's). + crate::db::person::delete_memberships_by_school(&self.control, &id).await?; + sqlx::query("DELETE FROM school_module WHERE school = $1") + .bind(id.uuid()) .execute(&self.control) .await?; - let db_name = school_db_name(&self.control_db, slug); + let db_name = school_db_name(&self.control_db, id.uuid()); sqlx::query(sqlx::AssertSqlSafe( create_database_sql("DROP DATABASE IF EXISTS", &db_name) + " WITH (FORCE)", )) .execute(&self.control) .await?; + sqlx::query("DELETE FROM school WHERE id = $1") + .bind(id.uuid()) + .execute(&self.control) + .await?; + Ok(()) } @@ -530,43 +610,40 @@ impl Tenants { /// re-reads the registry row on every request, so a suspension is refused /// whether or not a pool survived it. [`Tenants::drop`], which does mean /// to destroy the store, evicts unconditionally. - pub async fn evict(&self, slug: &Slug) { - if let Some(pool) = self.forget(slug) { + pub async fn evict(&self, id: SchoolId) { + if let Some(pool) = self.forget(id) { pool.close().await; } } - fn forget(&self, slug: &Slug) -> Option { + fn forget(&self, id: SchoolId) -> Option { + let key = id.uuid().simple().to_string(); let (removed, size) = { let mut cache = self.cache.write().expect("tenant cache lock"); - (cache.remove(slug.as_str()), cache.len()) + (cache.remove(&key), cache.len()) }; if removed.is_some() { - tracing::info!(school = %slug, "tenant pool evicted"); + tracing::info!(school = %id.uuid(), "tenant pool evicted"); Self::report_size(size); } removed } /// The cached pool, or a freshly dialled one. - async fn handle(&self, slug: &Slug) -> Result { - if let Some(db) = self - .cache - .read() - .expect("tenant cache lock") - .get(slug.as_str()) - { + async fn handle(&self, id: SchoolId) -> Result { + let key = id.uuid().simple().to_string(); + if let Some(db) = self.cache.read().expect("tenant cache lock").get(&key) { return Ok(db.clone()); } - let db = school_pool(&self.base, &school_db_name(&self.control_db, slug)).await?; + let db = school_pool(&self.base, &school_db_name(&self.control_db, id.uuid())).await?; // Losing the race here is harmless — both pools are equivalent — but // the winner is kept so two requests never diverge onto two pools. let (db, size) = { let mut cache = self.cache.write().expect("tenant cache lock"); - let db = cache.entry(slug.as_str().to_string()).or_insert(db).clone(); + let db = cache.entry(key).or_insert(db).clone(); (db, cache.len()) }; - tracing::info!(school = %slug, "tenant pool opened"); + tracing::info!(school = %id.uuid(), "tenant pool opened"); Self::report_size(size); Ok(db) } @@ -583,9 +660,6 @@ impl Tenants { mod tests { use super::*; - fn slug(value: &str) -> Slug { - Slug::try_new(value).expect(value) - } #[test] fn a_slug_names_a_school_and_nothing_reserved() { @@ -611,35 +685,30 @@ mod tests { } /// The database-per-school model lives or dies by this mapping: two - /// schools sharing a database name would share every row in it. `-` - /// becoming `_` is the only rewrite, and `_` is not in the slug charset, - /// so no two slugs can land on one name. + /// schools sharing a database name would share every row in it. The name + /// now mints from the school's uuid — lowercase hex without dashes, fixed + /// width — so it is injective by construction, and the slug appears + /// nowhere: a slug rename can never orphan a database. #[test] fn school_db_names_are_injective() { let control = "hezarfen_control"; + // The contract's example, pinned byte for byte. + let id = Uuid::try_parse("019732e3-7b00-7000-8000-00000000dead").unwrap(); assert_eq!( - school_db_name(control, &slug("demo")), - "hezarfen_control_school_demo" + school_db_name(control, id), + "hezarfen_control_school_019732e37b007000800000000000dead" ); - assert_eq!( - school_db_name(control, &slug("ata-koleji")), - "hezarfen_control_school_ata_koleji" + // Two uuids never collide onto one database, and no slug is in the + // name — not even the slug the uuid was minted for. + let other = Uuid::try_parse("019732e3-7b00-7000-8000-00000000beef").unwrap(); + assert_ne!( + school_db_name(control, id), + school_db_name(control, other), + "two uuids must not share a database" ); - // Slugs are at least two characters, so the shortest pair stands in - // for the old single-letter probe. - for a in ["ab", "a-b", "abc", "a1b", "1a", "x-y-z"] { - for b in ["ab", "a-b", "abc", "a1b", "1a", "x-y-z"] { - if a != b { - assert_ne!( - school_db_name(control, &slug(a)), - school_db_name(control, &slug(b)), - "{a:?} and {b:?} must not share a database" - ); - } - } - } + assert!(!school_db_name(control, id).contains("demo")); // The control database's own name is never a school's name: the // suffix keeps the namespaces apart. - assert_ne!(school_db_name(control, &slug("school")), control); + assert_ne!(school_db_name(control, id), control); } } diff --git a/src/web/builder.rs b/src/web/builder.rs index 40c38b7..959072f 100644 --- a/src/web/builder.rs +++ b/src/web/builder.rs @@ -34,7 +34,7 @@ use crate::module::{Module, ModuleSet, Package}; use crate::rate_limit::{RateLimitConfig, RateLimiter}; use crate::service; use crate::state::AppState; -use crate::tenant::{School, SchoolStatus, Slug}; +use crate::tenant::{School, SchoolId, SchoolStatus, Slug}; use crate::validate::validate_required; use crate::web::tenant_state::school_files_path; @@ -124,8 +124,9 @@ impl SchoolResponse { #[derive(Deserialize, ToSchema)] struct CreateSchool { /// Lowercase `a-z`, `0-9` and `-`, starting with a letter or digit. Names - /// the school's database, its blob directory and its cookie prefix, so it - /// is immutable once taken. + /// the school's blob directory and its cookie prefix. It is the school's + /// public label, not its identity — the uuid minted at create time is — + /// and it must stay unique across the deployment. #[schema(example = "ata-koleji", min_length = 2, max_length = 32)] slug: String, #[schema(example = "Ata Koleji", max_length = 120)] @@ -369,7 +370,11 @@ async fn create_school( )); } - let db = st.tenants.create(&slug, &name, modules).await?; + // The school's uuid is minted here, on the one path that creates schools: + // it becomes the registry row's PK and the database name's source, and + // the slug stays a label the wire keeps answering with. + let id = SchoolId::generate(); + let db = st.tenants.create(id, &slug, &name, modules).await?; let seeded = async { crate::service::user::create_with_role(&db, username, Some(*person.get_id()), Role::Admin) .await?; @@ -444,8 +449,9 @@ async fn get_school( } /// Rename a school and/or flip it between `active` and `suspended`. Omitted -/// fields keep their value. The slug itself is immutable — it names a database -/// and a directory. +/// fields keep their value. The slug itself is immutable in this cut — it is +/// the cookie prefix and the blob directory — though it no longer names the +/// database (the school's uuid does); a rename API is not offered yet. /// /// Suspending is immediate and total for the school's own users: their next /// request is a `403`, live session or not. diff --git a/src/web/course_notes.rs b/src/web/course_notes.rs index ce1beb1..88a9d7a 100644 --- a/src/web/course_notes.rs +++ b/src/web/course_notes.rs @@ -56,11 +56,12 @@ pub fn routes() -> OpenApiRouter { /// The note plus its course, or a 404 — every entity handler here gates on /// the parent course, so they always travel together. -async fn note_with_course(id: &str, db: &Database) -> Result<(CourseNote, Course), AppError> { - let note = service::course_note::read(db, &CourseNoteId::from_key(id)) +async fn note_with_course(id: String, db: Database) -> Result<(CourseNote, Course), AppError> { + let id = CourseNoteId::from_key(&id); + let note = service::course_note::read(&db, &id) .await? .ok_or(AppError::NotFound)?; - let course = crate::service::course::read(db, note.get_course()) + let course = crate::service::course::read(&db, note.get_course()) .await? .ok_or(AppError::NotFound)?; Ok((note, course)) @@ -214,7 +215,7 @@ async fn get_one( CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result, AppError> { - let (note, course) = note_with_course(&id, &st.db).await?; + let (note, course) = note_with_course(id.clone(), st.db.clone()).await?; if !can_view_course(&course, &user, &st.db).await? { return Err(AppError::Forbidden( "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course note", @@ -249,7 +250,7 @@ async fn update( Path(id): Path, Json(req): Json, ) -> Result, AppError> { - let (note, course) = note_with_course(&id, &st.db).await?; + let (note, course) = note_with_course(id.clone(), st.db.clone()).await?; if !can_manage_course(&course, &user) { return Err(AppError::Forbidden( "only the course creator, an assigned teacher, or a manager/admin can edit this course note", @@ -295,7 +296,7 @@ async fn delete_one( RequireTeacher(user): RequireTeacher, Path(id): Path, ) -> Result { - let (note, course) = note_with_course(&id, &st.db).await?; + let (note, course) = note_with_course(id.clone(), st.db.clone()).await?; if !can_manage_course(&course, &user) { return Err(AppError::Forbidden( "only the course creator, an assigned teacher, or a manager/admin can delete this course note", @@ -373,7 +374,7 @@ async fn upload_file( Path(id): Path, mut multipart: Multipart, ) -> Result<(StatusCode, Json), AppError> { - let (note, course) = note_with_course(&id, &st.db).await?; + let (note, course) = note_with_course(id.clone(), st.db.clone()).await?; if !can_manage_course(&course, &user) { return Err(AppError::Forbidden( "only the course creator, an assigned teacher, or a manager/admin can add a file to this course note", @@ -436,7 +437,7 @@ async fn list_files( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let (note, course) = note_with_course(&id, &st.db).await?; + let (note, course) = note_with_course(id.clone(), st.db.clone()).await?; if !can_view_course(&course, &user, &st.db).await? { return Err(AppError::Forbidden( "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course note's files", @@ -471,7 +472,7 @@ async fn download_file( CurrentUser(user): CurrentUser, Path((id, file_id)): Path<(String, String)>, ) -> Result { - let (note, course) = note_with_course(&id, &st.db).await?; + let (note, course) = note_with_course(id.clone(), st.db.clone()).await?; if !can_view_course(&course, &user, &st.db).await? { return Err(AppError::Forbidden( "only enrolled users, the course creator, an assigned teacher, or a manager/admin can download this course note's files", @@ -533,7 +534,7 @@ async fn delete_file( RequireTeacher(user): RequireTeacher, Path((id, file_id)): Path<(String, String)>, ) -> Result { - let (note, course) = note_with_course(&id, &st.db).await?; + let (note, course) = note_with_course(id.clone(), st.db.clone()).await?; if !can_manage_course(&course, &user) { return Err(AppError::Forbidden( "only the course creator, an assigned teacher, or a manager/admin can delete this course note's files", @@ -547,10 +548,10 @@ async fn delete_file( ) .await? .ok_or(AppError::NotFound)?; - // Drop every output built from this file before the file itself, so a - // stale index cannot outlive its source in a deployment with no AI service - // at all, and a failure here leaves the file whole instead of stranding its - // blob; the re-index rebuilds from what is left, if a service is connected. + // Drop every link citing this file before the file itself — the file + // row refuses to go while one stands — so a failure here leaves the file + // whole instead of stranding its blob; the re-index rebuilds the + // outputs from what is left, if a service is connected. service::rag_output::delete_with_source(&st.db, file.get_id()).await?; let file = service::course_note_file::delete(&st.db, file).await?; remove_blob(&st.files_path, &file.get_id().key()).await; @@ -615,7 +616,7 @@ async fn list_rag( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let (note, course) = note_with_course(&id, &st.db).await?; + let (note, course) = note_with_course(id.clone(), st.db.clone()).await?; if !can_view_course(&course, &user, &st.db).await? { return Err(AppError::Forbidden( "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course note's AI outputs", @@ -652,7 +653,7 @@ async fn delete_rag( RequireTeacher(user): RequireTeacher, Path((id, output_id)): Path<(String, String)>, ) -> Result { - let (note, course) = note_with_course(&id, &st.db).await?; + let (note, course) = note_with_course(id.clone(), st.db.clone()).await?; if !can_manage_course(&course, &user) { return Err(AppError::Forbidden( "only the course creator, an assigned teacher, or a manager/admin can delete this course note's AI outputs", diff --git a/tests/ai_bridge.rs b/tests/ai_bridge.rs index 46c116e..448d1dd 100644 --- a/tests/ai_bridge.rs +++ b/tests/ai_bridge.rs @@ -1784,7 +1784,12 @@ async fn an_index_dispatch_names_the_notes_own_school_and_stores_the_answer_ther let (app, demo_db, tenants) = common::app_with_ai_tenants(Some(bridge.clone())).await; let beta = Slug::try_new("beta").unwrap(); let beta_db = tenants - .create(&beta, "Beta College", ModuleSet::all()) + .create( + hezarfen_backend::tenant::SchoolId::generate(), + &beta, + "Beta College", + ModuleSet::all(), + ) .await .expect("beta"); diff --git a/tests/ai_protocol.rs b/tests/ai_protocol.rs index 4a40c0f..0e20ad5 100644 --- a/tests/ai_protocol.rs +++ b/tests/ai_protocol.rs @@ -1208,6 +1208,7 @@ async fn two_schools(bridge: &AiBridge) -> (axum::Router, Tenants, String, Strin let (app, demo_db, tenants) = common::app_with_ai_tenants(Some(bridge.clone())).await; let beta_db = tenants .create( + hezarfen_backend::tenant::SchoolId::generate(), &Slug::try_new("beta").unwrap(), "Beta College", ModuleSet::all(), diff --git a/tests/builder_api.rs b/tests/builder_api.rs index 6882ae7..273f302 100644 --- a/tests/builder_api.rs +++ b/tests/builder_api.rs @@ -2082,11 +2082,15 @@ async fn probe_a_refused_batch_leaves_the_row_byte_identical() { let builder = builder_login(&app).await; async fn raw_row(tenants: &Tenants) -> Vec { - sqlx::query_scalar("SELECT modules FROM school WHERE slug = $1") - .bind(DEMO_SLUG) - .fetch_one(tenants.control()) - .await - .expect("raw read") + sqlx::query_scalar( + "SELECT sm.module FROM school_module sm + JOIN school s ON s.id = sm.school + WHERE s.slug = $1 ORDER BY sm.module", + ) + .bind(DEMO_SLUG) + .fetch_all(tenants.control()) + .await + .expect("raw read") } let before = raw_row(&tenants).await; diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 6ee159b..c1d7182 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -641,6 +641,7 @@ pub async fn deployment_with(schools: &[(&str, &str)]) -> TestDeployment { for (slug, name) in schools { tenants .create( + hezarfen_backend::tenant::SchoolId::generate(), &Slug::try_new(slug).expect("a school slug"), name, ModuleSet::all(), diff --git a/tests/integration.rs b/tests/integration.rs index 908ffa4..51eadf5 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -6638,8 +6638,14 @@ async fn db_down_refuses_before_touching_the_database() { // Recovery is eviction: the dead pool leaves the cache, the next request // dials fresh — and the refused write is still not in the database. + let demo_id: Uuid = sqlx::query_scalar("SELECT id FROM school WHERE slug = 'demo'") + .fetch_one(tenants.control()) + .await + .expect("demo id"); let slug = Slug::try_new("demo").expect("slug"); - tenants.evict(&slug).await; + tenants + .evict(hezarfen_backend::tenant::SchoolId::from_uuid(demo_id)) + .await; let live = tenants.get(&slug).await.expect("redial after eviction"); assert_eq!( count_rows(&live, "app_user").await, @@ -27406,7 +27412,12 @@ async fn two_schools() -> ( let (app, db_a, tenants) = common::app_and_tenants().await; let slug_b = Slug::try_new("beta").expect("slug"); let db_b = tenants - .create(&slug_b, "Beta Koleji", ModuleSet::all()) + .create( + hezarfen_backend::tenant::SchoolId::generate(), + &slug_b, + "Beta Koleji", + ModuleSet::all(), + ) .await .expect("school B"); (app, db_a, db_b, tenants) @@ -28475,7 +28486,8 @@ async fn remote_probe_remote_mode_keeps_two_schools_apart() { // ------------------------------------------------------------------------- /// The server's database list, off the control handle: the control database -/// itself plus every school database, named `{control}_school_{slug}`. +/// itself plus every school database, named `{control}_school_{uuid hex}` — +/// the school's uuid, never its slug. async fn namespace_databases(tenants: &Tenants) -> Vec { let control = tenants.control(); let control_db: String = sqlx::query_scalar("SELECT current_database()") @@ -28495,6 +28507,22 @@ async fn namespace_databases(tenants: &Tenants) -> Vec { names } +/// A school database's name, read off the registry: the control database's +/// name plus the school's uuid in lowercase hex, no dashes. Postgres +/// truncates identifiers at 63 bytes (NAMEDATALEN - 1), and a test control +/// database's `heztest_` prefix runs the name one character past that — the +/// server creates and dials the truncated name on both sides, so the +/// expectation truncates with it. +async fn school_db_by_slug(control_db: &str, slug: &str, control: &sqlx::PgPool) -> String { + let id: Uuid = sqlx::query_scalar("SELECT id FROM school WHERE slug = $1") + .bind(slug) + .fetch_one(control) + .await + .expect("school id"); + let name = format!("{control_db}_school_{}", id.simple()); + name.chars().take(63).collect() +} + /// A school **is** a database, so the server must hold exactly the created /// schools plus the control database — and `DELETE /schools/{slug}` must drop /// the database, not merely delete the registry row. @@ -28505,13 +28533,13 @@ async fn remote_probe_a_school_is_a_database_and_delete_removes_it() { .fetch_one(d.tenants.control()) .await .expect("control name"); + let demo_db = school_db_by_slug(&control_db, DEMO_SLUG, d.tenants.control()).await; + let beta_db = school_db_by_slug(&control_db, "beta", d.tenants.control()).await; + let mut expected = vec![control_db.clone(), demo_db.clone(), beta_db]; + expected.sort(); assert_eq!( namespace_databases(&d.tenants).await, - vec![ - control_db.clone(), - format!("{control_db}_school_beta"), - format!("{control_db}_school_demo"), - ], + expected, "the server holds exactly the two schools and the control database" ); @@ -28535,9 +28563,11 @@ async fn remote_probe_a_school_is_a_database_and_delete_removes_it() { let res = send(&d.app, "DELETE", "/schools/beta", Some(&builder), None).await; assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); + let mut expected = vec![control_db.clone(), demo_db]; + expected.sort(); assert_eq!( namespace_databases(&d.tenants).await, - vec![control_db.clone(), format!("{control_db}_school_demo")], + expected, "DELETE /schools/beta dropped beta's database" ); } diff --git a/tests/persistence.rs b/tests/persistence.rs index a230113..f935e6a 100644 --- a/tests/persistence.rs +++ b/tests/persistence.rs @@ -571,10 +571,12 @@ async fn settings_slots_without_a_serving_minute_still_patch() { &app, "PATCH", "/settings", - Some(&send(&app, "POST", "/auth/login", None, Some(login.clone())) - .await - .cookie - .unwrap()), + Some( + &send(&app, "POST", "/auth/login", None, Some(login.clone())) + .await + .cookie + .unwrap(), + ), Some(json!({ "meal_slots": [{ "name": "lunch" }] })), ) .await; @@ -810,22 +812,19 @@ async fn boards_and_their_strokes_survive_remigration() { // the rows: a re-migration must not have reset either of them. use sqlx::Row as _; let board_id = hezarfen_backend::domain::board::BoardId::from_key(&board); - let row = sqlx::query( - "SELECT epoch_stroke_count, total_stroke_count FROM board WHERE id = $1", - ) - .bind(board_id.uuid()) - .fetch_one(&db) - .await - .expect("board row"); + let row = sqlx::query("SELECT epoch_stroke_count, total_stroke_count FROM board WHERE id = $1") + .bind(board_id.uuid()) + .fetch_one(&db) + .await + .expect("board row"); let epoch_count: i64 = row.try_get(0).unwrap(); let total_count: i64 = row.try_get(1).unwrap(); let user_id = hezarfen_backend::domain::user::UserId::from_key(&ali_id); - let board_count: i64 = - sqlx::query_scalar("SELECT board_count FROM app_user WHERE id = $1") - .bind(user_id.uuid()) - .fetch_one(&db) - .await - .expect("creator row"); + let board_count: i64 = sqlx::query_scalar("SELECT board_count FROM app_user WHERE id = $1") + .bind(user_id.uuid()) + .fetch_one(&db) + .await + .expect("creator row"); assert_eq!( (epoch_count, total_count, board_count), (1, 4, 1), @@ -859,7 +858,12 @@ async fn an_empty_module_list_survives_a_second_boot() { let tenants = database::init_test_tenants().await; let slug = Slug::try_new("bare").unwrap(); tenants - .create(&slug, "Bare School", ModuleSet::empty()) + .create( + hezarfen_backend::tenant::SchoolId::generate(), + &slug, + "Bare School", + ModuleSet::empty(), + ) .await .expect("a school with nothing switched on"); @@ -867,18 +871,17 @@ async fn an_empty_module_list_survives_a_second_boot() { .await .expect("a second boot"); - use sqlx::Row as _; - let stored: Option> = sqlx::query( - "SELECT modules FROM school WHERE slug = $1", + let stored: i64 = sqlx::query_scalar( + "SELECT count(*) FROM school_module sm + JOIN school s ON s.id = sm.school + WHERE s.slug = $1", ) .bind(slug.as_str()) - .fetch_optional(tenants.control()) + .fetch_one(tenants.control()) .await - .expect("read the row back") - .map(|row| row.try_get::, _>(0).unwrap()); + .expect("read the row back"); assert_eq!( - stored.unwrap_or_default(), - Vec::::new(), + stored, 0, "an empty list is a decision, never a hole to fill" ); } @@ -901,7 +904,12 @@ async fn probe_control_migration_is_idempotent_over_aged_rows() { ("narrow", "Narrow School", narrow), ] { tenants - .create(&Slug::try_new(slug).unwrap(), name, modules) + .create( + hezarfen_backend::tenant::SchoolId::generate(), + &Slug::try_new(slug).unwrap(), + name, + modules, + ) .await .unwrap_or_else(|err| panic!("create {slug}: {err}")); } @@ -921,21 +929,29 @@ async fn probe_control_migration_is_idempotent_over_aged_rows() { assert_eq!(before, after, "a re-run must not disturb school rows"); } -/// Every school row as `(slug, name, status, modules)`, in slug order. +/// Every school row as `(slug, name, status, modules)`, in slug order — the +/// modules aggregated off the `school_module` child table, as every read path +/// assembles them. async fn school_rows(control: &Database) -> Vec<(String, String, String, Vec)> { use sqlx::Row as _; - sqlx::query("SELECT slug, name, status, modules FROM school ORDER BY slug") - .fetch_all(control) - .await - .expect("school rows") - .into_iter() - .map(|row| { - ( - row.try_get::(0).unwrap(), - row.try_get::(1).unwrap(), - row.try_get::(2).unwrap(), - row.try_get::, _>(3).unwrap(), - ) - }) - .collect() + sqlx::query( + "SELECT s.slug, s.name, s.status, + COALESCE(array_agg(sm.module) FILTER (WHERE sm.module IS NOT NULL), '{}') + FROM school s LEFT JOIN school_module sm ON sm.school = s.id + GROUP BY s.id + ORDER BY s.slug", + ) + .fetch_all(control) + .await + .unwrap() + .into_iter() + .map(|row| { + ( + row.try_get::(0).unwrap(), + row.try_get::(1).unwrap(), + row.try_get::(2).unwrap(), + row.try_get::, _>(3).unwrap(), + ) + }) + .collect() } diff --git a/tests/regress_blueprints.rs b/tests/regress_blueprints.rs index b34ec5e..b282dc2 100644 --- a/tests/regress_blueprints.rs +++ b/tests/regress_blueprints.rs @@ -74,7 +74,9 @@ async fn source_of(class: &str, course: &str, db: &Database) -> Option { /// Does that grade's template still name that course, in the store? async fn templated(grade: &str, course: &str, db: &Database) -> bool { sqlx::query_scalar::<_, i64>( - "SELECT count(*) FROM class_blueprint WHERE grade = $1 AND $2 = ANY(courses)", + "SELECT count(*) FROM blueprint_course bc \ + JOIN class_blueprint b ON b.id = bc.blueprint \ + WHERE b.grade = $1 AND bc.course = $2", ) .bind(grade) .bind(CourseId::from_key(course)) @@ -459,13 +461,14 @@ async fn creating_a_class_stocks_it_from_its_grades_blueprint() { /// A create whose stocking cannot place everything still creates the class: the /// pair that did not fit comes back in `skipped`, best-effort exactly like /// every other pump here. -/// /// The dead course is forged in the store rather than deleted through the API, -/// because `DELETE /courses/{id}` now takes the id out of every template naming -/// it (see `deleting_a_course_takes_it_out_of_every_blueprint`) and would leave -/// nothing to skip. What is left here is exactly the state that still occurs: a -/// row written before that cascade existed, and the pump's own window — a -/// course deleted after the pump read the list it walks. +/// because `DELETE /courses/{id}` takes the id out of every template naming it +/// (see `deleting_a_course_takes_it_out_of_every_blueprint`) and would leave +/// nothing to skip. Under the `blueprint_course` junction the live store cannot +/// hold this state at all — the link is a foreign key — so the course row is +/// deleted with FK triggers suspended: the legacy-row state the prune still +/// exists for, and the same shape the pump's own window meets (a course gone +/// after the pump read the list it walks). #[tokio::test] async fn a_create_reports_what_its_blueprint_could_not_stock() { let (app, db) = app_and_db().await; @@ -486,12 +489,21 @@ async fn a_create_reports_what_its_blueprint_could_not_stock() { // the state the delete's own sweep no longer produces, and the one a pump // meets when a course goes after it read the list. Nothing carries it yet // (no section exists at grade 9), so this is the pair that cannot fit when - // the first one is created. + // the first one is created. The junction makes the live state impossible — + // `blueprint_course.course` is a foreign key — so the course row goes with + // FK triggers suspended: exactly what a row written before that cascade + // existed looks like, which is the state the prune still exists for. + let mut tx = db.begin().await.unwrap(); + sqlx::query("SET LOCAL session_replication_role = replica") + .execute(&mut *tx) + .await + .unwrap(); sqlx::query("DELETE FROM course WHERE id = $1") .bind(CourseId::from_key(&physics)) - .execute(&db) + .execute(&mut *tx) .await .unwrap(); + tx.commit().await.unwrap(); assert!( templated("9", &physics, &db).await, "the id is still listed" @@ -1424,11 +1436,15 @@ async fn a_half_swept_removal_is_finished_by_the_documented_re_patch() { // The state a sweep that died half-way leaves: the list is stored without // history, its attachment is not. - sqlx::query("UPDATE class_blueprint SET courses = $1 WHERE grade = '9'") - .bind(vec![CourseId::from_key(&algebra)]) - .execute(&db) - .await - .unwrap(); + sqlx::query( + "DELETE FROM blueprint_course \ + WHERE course = $1 \ + AND blueprint = (SELECT id FROM class_blueprint WHERE grade = '9')", + ) + .bind(CourseId::from_key(&history)) + .execute(&db) + .await + .unwrap(); let courses = held(&app, &manager, "9").await; assert_eq!( @@ -1491,9 +1507,10 @@ async fn a_half_swept_removal_is_finished_by_the_documented_re_patch() { /// the `201`/`200` listed a course the `GET` a moment later did not. /// /// Both write routes are driven, and the window is opened by the schema rather -/// than by a lucky interleaving: a `DEFINE EVENT` on `class_blueprint` fires -/// inside the very transaction that stores the list, which is exactly "after -/// the courses were resolved, before the pump runs", every single time. +/// than by a lucky interleaving: a trigger on `blueprint_course` fires inside +/// the very transaction that stores the list — after the link row landed, so +/// the foreign key allows the course's own death — which is exactly "after the +/// courses were resolved, before the pump runs", every single time. #[tokio::test] async fn a_course_pruned_mid_pump_is_out_of_the_body_that_pruned_it() { let (app, db) = app_and_db().await; @@ -1505,10 +1522,13 @@ async fn a_course_pruned_mid_pump_is_out_of_the_body_that_pruned_it() { let mut conn = db.acquire().await.expect("acquire for the trigger"); sqlx::raw_sql(sqlx::AssertSqlSafe(format!( "CREATE FUNCTION heztest_kill_on_create() RETURNS trigger AS $$ - BEGIN DELETE FROM course WHERE id = '{algebra}'; RETURN NULL; END; + BEGIN DELETE FROM blueprint_course WHERE blueprint = NEW.blueprint \ + AND course = NEW.course; + DELETE FROM course WHERE id = NEW.course; RETURN NULL; END; $$ LANGUAGE plpgsql; - CREATE TRIGGER heztest_kill_on_create AFTER INSERT ON class_blueprint - FOR EACH ROW EXECUTE FUNCTION heztest_kill_on_create();" + CREATE TRIGGER heztest_kill_on_create AFTER INSERT ON blueprint_course + FOR EACH ROW WHEN (NEW.course = '{algebra}') + EXECUTE FUNCTION heztest_kill_on_create();" ))) .execute(&mut *conn) .await @@ -1540,10 +1560,13 @@ async fn a_course_pruned_mid_pump_is_out_of_the_body_that_pruned_it() { // The same window on the edit route. sqlx::raw_sql(sqlx::AssertSqlSafe(format!( "CREATE FUNCTION heztest_kill_on_update() RETURNS trigger AS $$ - BEGIN DELETE FROM course WHERE id = '{history}'; RETURN NULL; END; + BEGIN DELETE FROM blueprint_course WHERE blueprint = NEW.blueprint \ + AND course = NEW.course; + DELETE FROM course WHERE id = NEW.course; RETURN NULL; END; $$ LANGUAGE plpgsql; - CREATE TRIGGER heztest_kill_on_update AFTER UPDATE ON class_blueprint - FOR EACH ROW EXECUTE FUNCTION heztest_kill_on_update();" + CREATE TRIGGER heztest_kill_on_update AFTER INSERT ON blueprint_course + FOR EACH ROW WHEN (NEW.course = '{history}') + EXECUTE FUNCTION heztest_kill_on_update();" ))) .execute(&mut *conn) .await diff --git a/tests/regress_classes.rs b/tests/regress_classes.rs index 25c687d..b3a52b5 100644 --- a/tests/regress_classes.rs +++ b/tests/regress_classes.rs @@ -1610,7 +1610,7 @@ async fn a_course_assignment_whose_teacher_is_demoted_mid_write_is_undone() { ); assert_eq!(role_of(&teacher_id, &db).await, "student", "the seam fired"); assert_eq!( - counter("SELECT COALESCE(sum(cardinality(teachers)), 0)::bigint FROM course", &db).await, + counter("SELECT count(*) FROM course_teacher", &db).await, 0, "the assignment must be dropped again, not left granting nothing" );