migrator/migrations/
m20241004010448_document_refs.rs1use sqlx::{Acquire, PgConnection, Postgres};
2use sqlx_migrator::Operation;
3use sqlx_migrator::error::Error;
4use sqlx_migrator::migration;
5use sqlx_migrator::vec_box;
6
7pub(crate) struct DocumentRefs;
8
9migration!(
10 Postgres,
11 DocumentRefs,
12 "backend",
13 "20241004010448_document_refs",
14 vec_box![],
15 vec_box![MigrationOperation]
16);
17
18struct MigrationOperation;
19#[async_trait::async_trait]
20impl Operation<Postgres> for MigrationOperation {
21 async fn up(&self, conn: &mut PgConnection) -> Result<(), Error> {
22 let mut tx = conn.begin().await?;
23
24 sqlx::query(
25 "
26 CREATE TABLE snapshots (
27 id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
28 for_ref UUID NOT NULL,
29 content JSONB NOT NULL,
30 last_updated TIMESTAMPTZ NOT NULL
31 );
32 ",
33 )
34 .execute(&mut *tx)
35 .await?;
36
37 sqlx::query(
38 "
39 CREATE TABLE refs (
40 id UUID PRIMARY KEY,
41 head INT NOT NULL REFERENCES snapshots (id),
42 created TIMESTAMPTZ NOT NULL
43 );
44 ",
45 )
46 .execute(&mut *tx)
47 .await?;
48
49 sqlx::query(
50 "
51 ALTER TABLE snapshots
52 ADD FOREIGN KEY (for_ref) REFERENCES refs (id) DEFERRABLE INITIALLY DEFERRED;
53 ",
54 )
55 .execute(&mut *tx)
56 .await?;
57
58 tx.commit().await?;
59 Ok(())
60 }
61
62 async fn down(&self, conn: &mut PgConnection) -> Result<(), Error> {
63 sqlx::query("DROP TABLE refs, snapshots").execute(conn).await?;
64 Ok(())
65 }
66}