migratrom-postgres 0.2.0

PostgreSQL (sqlx) adapter for migratrom.
Documentation
//! Apply [`migratrom`] migrations through a `sqlx::PgPool`.
//!
//! This is the normal application entry point for PostgreSQL. [`apply_migrations`]
//! acquires one pooled connection and pins it for the complete run, so
//! `BEGIN`/`COMMIT`/`ROLLBACK` and PostgreSQL advisory locks all use the same
//! session. Use [`PostgresAdapter`] only when an application must call the core
//! engine directly with an already acquired connection.
//!
//! # Quick start
//!
//! ```no_run
//! use migratrom::operations::{create_index, create_table};
//! use migratrom::{ApplyOptions, ColumnDef, CreateIndexOptions, Migration, PostgresDialect};
//! use migratrom_postgres::apply_migrations;
//! use sqlx::PgPool;
//!
//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
//! let pool = PgPool::connect("postgres://localhost/my_app").await?;
//! let dialect = PostgresDialect;
//! let create_users = Migration::new(
//!     1,
//!     None,
//!     vec![create_table(
//!         "public",
//!         "users",
//!         &[ColumnDef::new("id", "bigint"), ColumnDef::new("email", "text")],
//!         None,
//!         &dialect,
//!     )?],
//! );
//! let add_email_index = Migration::new(
//!     2,
//!     Some(1),
//!     vec![create_index(
//!         "public",
//!         "users",
//!         "users_email_idx",
//!         &["email".into()],
//!         &CreateIndexOptions { concurrently: true },
//!         &dialect,
//!     )?],
//! );
//!
//! apply_migrations(
//!     &[create_users, add_email_index],
//!     &pool,
//!     &ApplyOptions::default(),
//! ).await?;
//! # Ok(())
//! # }
//! ```
//!
//! A concurrent index runs outside the migration transaction, as required by
//! PostgreSQL. The core [`migratrom::operations`] cookbook documents all builders,
//! including PostgreSQL schemas, extensions, enum types, and materialized views.

#![deny(missing_docs)]

use async_trait::async_trait;
use migratrom::{
    apply_migrations as core_apply, ApplyOptions, ApplyResult, Db, Migration, MigratromError,
    PostgresDialect, Row,
};
use sqlx::pool::PoolConnection;
use sqlx::postgres::PgRow;
use sqlx::{PgPool, Postgres, Row as SqlxRow};
use tokio::sync::Mutex;

fn db_err(e: sqlx::Error) -> MigratromError {
    MigratromError::Db(e.to_string())
}

struct Inner {
    conn: PoolConnection<Postgres>,
    /// Transaction nesting depth; only the outermost begin/commit touches SQL.
    depth: u32,
}

/// A [`Db`] over one pinned PostgreSQL connection.
pub struct PostgresAdapter {
    inner: Mutex<Inner>,
}

impl PostgresAdapter {
    /// Wrap an acquired pooled connection.
    pub fn new(conn: PoolConnection<Postgres>) -> Self {
        Self {
            inner: Mutex::new(Inner { conn, depth: 0 }),
        }
    }
}

struct PgRowWrap(PgRow);

impl Row for PgRowWrap {
    fn i64_at(&self, idx: usize) -> Option<i64> {
        self.0.try_get::<i64, _>(idx).ok()
    }
    fn str_at(&self, idx: usize) -> Option<String> {
        self.0.try_get::<String, _>(idx).ok()
    }
}

fn read_check(row: &PgRow) -> Result<bool, MigratromError> {
    if let Ok(b) = row.try_get::<bool, _>(0) {
        return Ok(b);
    }
    match row.try_get::<i64, _>(0) {
        Ok(i) => Ok(i != 0),
        Err(e) => Err(MigratromError::CheckShape {
            message: format!("check must return a boolean: {e}"),
            row_preview: None,
        }),
    }
}

#[async_trait]
impl Db for PostgresAdapter {
    async fn query_bool(&self, sql: &str) -> Result<bool, MigratromError> {
        let mut g = self.inner.lock().await;
        let row = sqlx::query(sql)
            .fetch_one(&mut *g.conn)
            .await
            .map_err(db_err)?;
        read_check(&row)
    }

    async fn execute(&self, sql: &str) -> Result<(), MigratromError> {
        let mut g = self.inner.lock().await;
        sqlx::query(sql)
            .execute(&mut *g.conn)
            .await
            .map_err(db_err)?;
        Ok(())
    }

    async fn query_rows(&self, sql: &str) -> Result<Vec<Box<dyn Row>>, MigratromError> {
        let mut g = self.inner.lock().await;
        let rows = sqlx::query(sql)
            .fetch_all(&mut *g.conn)
            .await
            .map_err(db_err)?;
        Ok(rows
            .into_iter()
            .map(|r| Box::new(PgRowWrap(r)) as Box<dyn Row>)
            .collect())
    }

    async fn begin(&self) -> Result<(), MigratromError> {
        let mut g = self.inner.lock().await;
        if g.depth == 0 {
            sqlx::query("BEGIN")
                .execute(&mut *g.conn)
                .await
                .map_err(db_err)?;
        }
        g.depth += 1;
        Ok(())
    }

    async fn commit(&self) -> Result<(), MigratromError> {
        let mut g = self.inner.lock().await;
        g.depth -= 1;
        if g.depth == 0 {
            sqlx::query("COMMIT")
                .execute(&mut *g.conn)
                .await
                .map_err(db_err)?;
        }
        Ok(())
    }

    async fn rollback(&self) -> Result<(), MigratromError> {
        let mut g = self.inner.lock().await;
        g.depth -= 1;
        if g.depth == 0 {
            sqlx::query("ROLLBACK")
                .execute(&mut *g.conn)
                .await
                .map_err(db_err)?;
        }
        Ok(())
    }
}

/// Apply migrations against a PostgreSQL pool using [`PostgresDialect`].
///
/// Acquires one connection for the whole run (required for advisory locking),
/// then delegates to the core engine.
pub async fn apply_migrations(
    migrations: &[Migration],
    pool: &PgPool,
    options: &ApplyOptions,
) -> Result<ApplyResult, MigratromError> {
    let conn = pool.acquire().await.map_err(db_err)?;
    let adapter = PostgresAdapter::new(conn);
    core_apply(migrations, &adapter, &PostgresDialect, options).await
}