Skip to main content

riverqueue_migrate/
sqlite.rs

1use std::time::{Duration, Instant};
2
3use sqlx::{Row, SqlitePool};
4
5use crate::{
6    Direction, Error, MIGRATION_LINE_MAIN, MigrateOpts, MigrateResult, MigrateVersion, Migration,
7    ValidateResult, run_to_completion, select_migrations, validate_migrations, validate_target,
8};
9
10macro_rules! sqlite_migration {
11    ($version:literal, $name:literal, $file:literal) => {
12        Migration {
13            down_sql: include_str!(concat!("../migrations/sqlite/main/", $file, ".down.sql")),
14            name: $name,
15            up_sql: include_str!(concat!("../migrations/sqlite/main/", $file, ".up.sql")),
16            version: $version,
17        }
18    };
19}
20
21/// Canonical SQLite migration bundle.
22pub const SQLITE_MIGRATIONS: [Migration; 8] = [
23    sqlite_migration!(1, "create_river_migration", "001_create_river_migration"),
24    sqlite_migration!(2, "initial_schema", "002_initial_schema"),
25    sqlite_migration!(3, "river_job_tags_non_null", "003_river_job_tags_non_null"),
26    sqlite_migration!(4, "pending_and_more", "004_pending_and_more"),
27    sqlite_migration!(5, "migration_unique_client", "005_migration_unique_client"),
28    sqlite_migration!(6, "bulk_unique", "006_bulk_unique"),
29    sqlite_migration!(
30        7,
31        "notification_outbox_sqlite_jsonb_and_sql_cleanup",
32        "007_notification_outbox_sqlite_jsonb_and_sql_cleanup"
33    ),
34    sqlite_migration!(8, "job_id_autoincrement", "008_job_id_autoincrement"),
35];
36
37/// Applies and validates River's SQLite migration history.
38#[derive(Clone, Debug)]
39pub struct SqliteMigrator {
40    pool: SqlitePool,
41}
42
43impl SqliteMigrator {
44    /// Creates a migrator for a SQLite pool.
45    #[must_use]
46    pub const fn new(pool: SqlitePool) -> Self {
47        Self { pool }
48    }
49
50    /// Returns every SQLite migration bundled with this crate.
51    #[must_use]
52    pub fn all_versions() -> &'static [Migration] {
53        &SQLITE_MIGRATIONS
54    }
55
56    /// Returns applied main-line versions in ascending order.
57    ///
58    /// # Errors
59    ///
60    /// Returns [`Error::Database`] when the query fails.
61    pub async fn existing_versions(&self) -> Result<Vec<i64>, Error> {
62        let exists: bool = sqlx::query_scalar(
63            "SELECT EXISTS (SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'river_migration')",
64        )
65        .fetch_one(&self.pool)
66        .await
67        .map_err(Error::Database)?;
68        if !exists {
69            return Ok(Vec::new());
70        }
71
72        let has_line: bool = sqlx::query_scalar(
73            "SELECT EXISTS (SELECT 1 FROM pragma_table_info('river_migration') WHERE name = 'line')",
74        )
75        .fetch_one(&self.pool)
76        .await
77        .map_err(Error::Database)?;
78        let rows = if has_line {
79            sqlx::query("SELECT version FROM river_migration WHERE line = ?1 ORDER BY version")
80                .bind(MIGRATION_LINE_MAIN)
81                .fetch_all(&self.pool)
82                .await
83                .map_err(Error::Database)?
84        } else {
85            sqlx::query("SELECT version FROM river_migration ORDER BY version")
86                .fetch_all(&self.pool)
87                .await
88                .map_err(Error::Database)?
89        };
90        Ok(rows.iter().map(|row| row.get("version")).collect())
91    }
92
93    /// Applies up or down migrations with target, step, and dry-run controls.
94    ///
95    /// Each migration runs in its own transaction, so a failure leaves the
96    /// migrations before it applied.
97    ///
98    /// # Errors
99    ///
100    /// Returns [`Error::UnknownVersion`] when the target version doesn't exist,
101    /// [`Error::TargetNotSelected`] when a down target isn't applied or is
102    /// beyond the step limit, [`Error::OtherMigrationLines`] when reverting
103    /// version 5 would lose other migration lines' records, and [`Error::Database`] when a migration fails.
104    ///
105    /// # Cancel safety
106    ///
107    /// Each migration and its record in `river_migration` commit together in
108    /// their own transaction, on a task of their own. Dropping the future
109    /// stops migrating once the migration in progress finishes: it and
110    /// every migration before it stay applied, and migrating again
111    /// continues from there.
112    pub async fn migrate(
113        &self,
114        direction: Direction,
115        opts: MigrateOpts,
116    ) -> Result<MigrateResult, Error> {
117        validate_target(&SQLITE_MIGRATIONS, opts.target_version, true)?;
118        let applied = self.existing_versions().await?;
119        let selected = select_migrations(&SQLITE_MIGRATIONS, direction, opts, &applied)?;
120
121        let mut versions = Vec::with_capacity(selected.len());
122        for migration in selected {
123            let sql = migration_sql(direction, migration).to_owned();
124            let mut duration = Duration::ZERO;
125            if !opts.dry_run {
126                let started_at = Instant::now();
127                // Each migration runs to completion on its own task, so
128                // dropping this future never abandons one partway.
129                let migrator = self.clone();
130                let task_sql = sql.clone();
131                run_to_completion(
132                    async move { migrator.apply(direction, migration, &task_sql).await },
133                )
134                .await?;
135                duration = started_at.elapsed();
136            }
137            versions.push(MigrateVersion {
138                duration,
139                name: migration.name,
140                sql,
141                version: migration.version,
142            });
143        }
144        Ok(MigrateResult {
145            direction,
146            versions,
147        })
148    }
149
150    /// Applies all outstanding up migrations and returns their versions.
151    ///
152    /// # Errors
153    ///
154    /// Returns [`Error::Database`] when a migration fails.
155    ///
156    /// # Cancel safety
157    ///
158    /// Each migration and its record in `river_migration` commit together in
159    /// their own transaction, on a task of their own. Dropping the future
160    /// stops migrating once the migration in progress finishes: it and
161    /// every migration before it stay applied, and migrating again
162    /// continues from there.
163    pub async fn migrate_up(&self) -> Result<Vec<i64>, Error> {
164        Ok(self
165            .migrate(Direction::Up, MigrateOpts::default())
166            .await?
167            .versions
168            .into_iter()
169            .map(|version| version.version)
170            .collect())
171    }
172
173    /// Checks that every migration through an optional target is applied.
174    ///
175    /// # Errors
176    ///
177    /// Returns [`Error::UnknownVersion`] when the target version doesn't exist and
178    /// [`Error::Database`] when reading the applied versions fails.
179    pub async fn validate(&self, target_version: Option<i64>) -> Result<ValidateResult, Error> {
180        validate_target(&SQLITE_MIGRATIONS, target_version, false)?;
181        let applied = self.existing_versions().await?;
182        Ok(validate_migrations(
183            &SQLITE_MIGRATIONS,
184            target_version,
185            &applied,
186        ))
187    }
188
189    async fn apply(
190        &self,
191        direction: Direction,
192        migration: Migration,
193        sql: &str,
194    ) -> Result<(), Error> {
195        let mut transaction = self
196            .pool
197            .begin_with("BEGIN IMMEDIATE")
198            .await
199            .map_err(Error::Database)?;
200        if direction == Direction::Down && migration.version == 5 {
201            let has_other_lines: bool = sqlx::query_scalar(
202                "SELECT EXISTS (SELECT 1 FROM river_migration WHERE line <> ?1)",
203            )
204            .bind(MIGRATION_LINE_MAIN)
205            .fetch_one(&mut *transaction)
206            .await
207            .map_err(Error::Database)?;
208            if has_other_lines {
209                return Err(Error::OtherMigrationLines {
210                    version: migration.version,
211                });
212            }
213        }
214
215        sqlx::raw_sql(sqlx::AssertSqlSafe(sql))
216            .execute(&mut *transaction)
217            .await
218            .map_err(Error::Database)?;
219        match direction {
220            Direction::Down if migration.version == 1 => {}
221            Direction::Down if migration.version <= 5 => {
222                sqlx::query("DELETE FROM river_migration WHERE version = ?1")
223                    .bind(migration.version)
224                    .execute(&mut *transaction)
225                    .await
226                    .map_err(Error::Database)?;
227            }
228            Direction::Down => {
229                sqlx::query("DELETE FROM river_migration WHERE line = ?1 AND version = ?2")
230                    .bind(MIGRATION_LINE_MAIN)
231                    .bind(migration.version)
232                    .execute(&mut *transaction)
233                    .await
234                    .map_err(Error::Database)?;
235            }
236            Direction::Up if migration.version >= 5 => {
237                sqlx::query("INSERT INTO river_migration (line, version) VALUES (?1, ?2)")
238                    .bind(MIGRATION_LINE_MAIN)
239                    .bind(migration.version)
240                    .execute(&mut *transaction)
241                    .await
242                    .map_err(Error::Database)?;
243            }
244            Direction::Up => {
245                sqlx::query("INSERT INTO river_migration (version) VALUES (?1)")
246                    .bind(migration.version)
247                    .execute(&mut *transaction)
248                    .await
249                    .map_err(Error::Database)?;
250            }
251        }
252        transaction.commit().await.map_err(Error::Database)?;
253        Ok(())
254    }
255}
256
257const fn migration_sql(direction: Direction, migration: Migration) -> &'static str {
258    match direction {
259        Direction::Down => migration.down_sql,
260        Direction::Up => migration.up_sql,
261    }
262}