Skip to main content

migratrom_postgres/
lib.rs

1//! Apply [`migratrom`] migrations through a `sqlx::PgPool`.
2//!
3//! This is the normal application entry point for PostgreSQL. [`apply_migrations`]
4//! acquires one pooled connection and pins it for the complete run, so
5//! `BEGIN`/`COMMIT`/`ROLLBACK` and PostgreSQL advisory locks all use the same
6//! session. Use [`PostgresAdapter`] only when an application must call the core
7//! engine directly with an already acquired connection.
8//!
9//! # Quick start
10//!
11//! ```no_run
12//! use migratrom::operations::{create_index, create_table};
13//! use migratrom::{ApplyOptions, ColumnDef, CreateIndexOptions, Migration, PostgresDialect};
14//! use migratrom_postgres::apply_migrations;
15//! use sqlx::PgPool;
16//!
17//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
18//! let pool = PgPool::connect("postgres://localhost/my_app").await?;
19//! let dialect = PostgresDialect;
20//! let create_users = Migration::new(
21//!     1,
22//!     None,
23//!     vec![create_table(
24//!         "public",
25//!         "users",
26//!         &[ColumnDef::new("id", "bigint"), ColumnDef::new("email", "text")],
27//!         None,
28//!         &dialect,
29//!     )?],
30//! );
31//! let add_email_index = Migration::new(
32//!     2,
33//!     Some(1),
34//!     vec![create_index(
35//!         "public",
36//!         "users",
37//!         "users_email_idx",
38//!         &["email".into()],
39//!         &CreateIndexOptions { concurrently: true },
40//!         &dialect,
41//!     )?],
42//! );
43//!
44//! apply_migrations(
45//!     &[create_users, add_email_index],
46//!     &pool,
47//!     &ApplyOptions::default(),
48//! ).await?;
49//! # Ok(())
50//! # }
51//! ```
52//!
53//! A concurrent index runs outside the migration transaction, as required by
54//! PostgreSQL. The core [`migratrom::operations`] cookbook documents all builders,
55//! including PostgreSQL schemas, extensions, enum types, and materialized views.
56
57#![deny(missing_docs)]
58
59use async_trait::async_trait;
60use migratrom::{
61    apply_migrations as core_apply, ApplyOptions, ApplyResult, Db, Migration, MigratromError,
62    PostgresDialect, Row,
63};
64use sqlx::pool::PoolConnection;
65use sqlx::postgres::PgRow;
66use sqlx::{PgPool, Postgres, Row as SqlxRow};
67use tokio::sync::Mutex;
68
69fn db_err(e: sqlx::Error) -> MigratromError {
70    MigratromError::Db(e.to_string())
71}
72
73struct Inner {
74    conn: PoolConnection<Postgres>,
75    /// Transaction nesting depth; only the outermost begin/commit touches SQL.
76    depth: u32,
77}
78
79/// A [`Db`] over one pinned PostgreSQL connection.
80pub struct PostgresAdapter {
81    inner: Mutex<Inner>,
82}
83
84impl PostgresAdapter {
85    /// Wrap an acquired pooled connection.
86    pub fn new(conn: PoolConnection<Postgres>) -> Self {
87        Self {
88            inner: Mutex::new(Inner { conn, depth: 0 }),
89        }
90    }
91}
92
93struct PgRowWrap(PgRow);
94
95impl Row for PgRowWrap {
96    fn i64_at(&self, idx: usize) -> Option<i64> {
97        self.0.try_get::<i64, _>(idx).ok()
98    }
99    fn str_at(&self, idx: usize) -> Option<String> {
100        self.0.try_get::<String, _>(idx).ok()
101    }
102}
103
104fn read_check(row: &PgRow) -> Result<bool, MigratromError> {
105    if let Ok(b) = row.try_get::<bool, _>(0) {
106        return Ok(b);
107    }
108    match row.try_get::<i64, _>(0) {
109        Ok(i) => Ok(i != 0),
110        Err(e) => Err(MigratromError::CheckShape {
111            message: format!("check must return a boolean: {e}"),
112            row_preview: None,
113        }),
114    }
115}
116
117#[async_trait]
118impl Db for PostgresAdapter {
119    async fn query_bool(&self, sql: &str) -> Result<bool, MigratromError> {
120        let mut g = self.inner.lock().await;
121        let row = sqlx::query(sql)
122            .fetch_one(&mut *g.conn)
123            .await
124            .map_err(db_err)?;
125        read_check(&row)
126    }
127
128    async fn execute(&self, sql: &str) -> Result<(), MigratromError> {
129        let mut g = self.inner.lock().await;
130        sqlx::query(sql)
131            .execute(&mut *g.conn)
132            .await
133            .map_err(db_err)?;
134        Ok(())
135    }
136
137    async fn query_rows(&self, sql: &str) -> Result<Vec<Box<dyn Row>>, MigratromError> {
138        let mut g = self.inner.lock().await;
139        let rows = sqlx::query(sql)
140            .fetch_all(&mut *g.conn)
141            .await
142            .map_err(db_err)?;
143        Ok(rows
144            .into_iter()
145            .map(|r| Box::new(PgRowWrap(r)) as Box<dyn Row>)
146            .collect())
147    }
148
149    async fn begin(&self) -> Result<(), MigratromError> {
150        let mut g = self.inner.lock().await;
151        if g.depth == 0 {
152            sqlx::query("BEGIN")
153                .execute(&mut *g.conn)
154                .await
155                .map_err(db_err)?;
156        }
157        g.depth += 1;
158        Ok(())
159    }
160
161    async fn commit(&self) -> Result<(), MigratromError> {
162        let mut g = self.inner.lock().await;
163        g.depth -= 1;
164        if g.depth == 0 {
165            sqlx::query("COMMIT")
166                .execute(&mut *g.conn)
167                .await
168                .map_err(db_err)?;
169        }
170        Ok(())
171    }
172
173    async fn rollback(&self) -> Result<(), MigratromError> {
174        let mut g = self.inner.lock().await;
175        g.depth -= 1;
176        if g.depth == 0 {
177            sqlx::query("ROLLBACK")
178                .execute(&mut *g.conn)
179                .await
180                .map_err(db_err)?;
181        }
182        Ok(())
183    }
184}
185
186/// Apply migrations against a PostgreSQL pool using [`PostgresDialect`].
187///
188/// Acquires one connection for the whole run (required for advisory locking),
189/// then delegates to the core engine.
190pub async fn apply_migrations(
191    migrations: &[Migration],
192    pool: &PgPool,
193    options: &ApplyOptions,
194) -> Result<ApplyResult, MigratromError> {
195    let conn = pool.acquire().await.map_err(db_err)?;
196    let adapter = PostgresAdapter::new(conn);
197    core_apply(migrations, &adapter, &PostgresDialect, options).await
198}