Skip to main content

adk_memory/
migration.rs

1//! Lightweight, embedded migration runner for SQL-backed memory services.
2//!
3//! This module provides shared types and free functions that track applied
4//! schema versions in a per-backend registry table and execute only unapplied
5//! forward-only migration steps.
6//!
7//! The types ([`MigrationStep`], [`AppliedMigration`], [`MigrationError`]) are
8//! always compiled. The SQL runner functions (`run_sql_migrations`,
9//! `run_sql_migrations_on_connection`, `sql_schema_version`) require the
10//! `sqlite-memory` or `database-memory` feature.
11
12use chrono::{DateTime, Utc};
13
14/// A single forward-only migration step.
15///
16/// The struct intentionally does not contain the SQL itself — each backend
17/// defines its own step list as `&[(i64, &str, &str)]` tuples of
18/// `(version, description, sql)`.
19#[derive(Debug, Clone, Copy)]
20pub struct MigrationStep {
21    /// Monotonically increasing version number, starting at 1.
22    pub version: i64,
23    /// Human-readable description of what this step does.
24    pub description: &'static str,
25}
26
27/// Record of an applied migration stored in the registry table.
28#[derive(Debug, Clone)]
29pub struct AppliedMigration {
30    /// The applied version number.
31    pub version: i64,
32    /// Description recorded at apply time.
33    pub description: String,
34    /// UTC timestamp of application.
35    pub applied_at: DateTime<Utc>,
36}
37
38/// Error context for a failed migration step.
39#[derive(Debug)]
40pub struct MigrationError {
41    /// The version that failed.
42    pub version: i64,
43    /// Description of the failed step.
44    pub description: String,
45    /// Underlying cause (database error message, etc.).
46    pub cause: String,
47}
48
49impl std::fmt::Display for MigrationError {
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        write!(f, "migration v{} ({}) failed: {}", self.version, self.description, self.cause)
52    }
53}
54
55impl std::error::Error for MigrationError {}
56
57// ---------------------------------------------------------------------------
58// SQL runner — macro generates concrete implementations per database backend
59// ---------------------------------------------------------------------------
60
61// Registry identifiers are interpolated; migration bodies are trusted executable SQL.
62// PostgreSQL truncates identifiers past 63 bytes, so a longer name could address
63// another registry.
64#[cfg(any(feature = "sqlite-memory", feature = "database-memory"))]
65fn validate_registry_table(name: &str) -> Result<(), adk_core::AdkError> {
66    let mut chars = name.chars();
67    if name.len() > 63
68        || !chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
69        || !chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
70    {
71        return Err(adk_core::AdkError::memory(format!(
72            "invalid migration registry table `{name}`: use an ASCII identifier of at most 63 bytes \
73             starting with a letter or underscore, followed by letters, digits or underscores"
74        )));
75    }
76    Ok(())
77}
78
79/// Expands to the body of a migration run, shared by the pool-based and the
80/// connection-based entry points.
81///
82/// `$exec` is expanded at every statement, so `&mut *conn` reborrows a
83/// connection afresh for each one.
84#[cfg(any(feature = "sqlite-memory", feature = "database-memory"))]
85macro_rules! sql_migration_body {
86    (
87        exec: $exec:expr,
88        begin: $begin:expr,
89        detect: $detect:expr,
90        registry_table: $registry_table:expr,
91        steps: $steps:expr,
92        int_type: $int_type:expr $(,)?
93    ) => {{
94        let registry_table: &str = $registry_table;
95        super::validate_registry_table(registry_table)?;
96        let steps: &[(i64, &str, &str)] = $steps;
97
98        // Step 1: Create registry table if missing
99        let create_sql = format!(
100            "CREATE TABLE IF NOT EXISTS {registry_table} (\
101                version {} PRIMARY KEY, \
102                description TEXT NOT NULL, \
103                applied_at TEXT NOT NULL\
104            )",
105            $int_type
106        );
107        sqlx::query(sqlx::AssertSqlSafe(create_sql)).execute($exec).await.map_err(|e| {
108            adk_core::AdkError::memory(format!("migration registry creation failed: {e}"))
109        })?;
110
111        // Step 2: Read current max applied version
112        let max_sql = format!("SELECT COALESCE(MAX(version), 0) AS max_v FROM {registry_table}");
113        let row =
114            sqlx::query(sqlx::AssertSqlSafe(max_sql)).fetch_one($exec).await.map_err(|e| {
115                adk_core::AdkError::memory(format!("migration registry read failed: {e}"))
116            })?;
117        let mut max_applied: i64 = row.try_get("max_v").map_err(|e| {
118            adk_core::AdkError::memory(format!("migration registry read failed: {e}"))
119        })?;
120
121        // Step 3: Baseline detection — if registry is empty but
122        // tables already exist, record v1 as applied.
123        if max_applied == 0 {
124            let existing = $detect.await?;
125            if existing {
126                if let Some(&(v, desc, _)) = steps.first() {
127                    let now = Utc::now().to_rfc3339();
128                    // Another run may record the same baseline at the same moment.
129                    let ins = format!(
130                        "INSERT INTO {registry_table} \
131                         (version, description, applied_at) \
132                         VALUES ($1, $2, $3) ON CONFLICT (version) DO NOTHING"
133                    );
134                    sqlx::query(sqlx::AssertSqlSafe(ins))
135                        .bind(v)
136                        .bind(desc)
137                        .bind(&now)
138                        .execute($exec)
139                        .await
140                        .map_err(|e| {
141                            adk_core::AdkError::memory(format!(
142                                "{}",
143                                MigrationError {
144                                    version: v,
145                                    description: desc.to_string(),
146                                    cause: e.to_string(),
147                                }
148                            ))
149                        })?;
150                    max_applied = v;
151                }
152            }
153        }
154
155        // Step 4: Compiled-in max version
156        let max_compiled = steps.last().map(|s| s.0).unwrap_or(0);
157
158        // Step 5: Version mismatch check
159        if max_applied > max_compiled {
160            return Err(adk_core::AdkError::memory(format!(
161                "schema version mismatch: database is at v{max_applied} \
162                 but code only knows up to v{max_compiled}. \
163                 Upgrade your ADK version."
164            )));
165        }
166
167        // Step 6: Execute unapplied steps in transactions
168        for &(version, description, sql) in steps {
169            if version <= max_applied {
170                continue;
171            }
172
173            let mut tx = $begin.await.map_err(|e| {
174                adk_core::AdkError::memory(format!(
175                    "{}",
176                    MigrationError {
177                        version,
178                        description: description.to_string(),
179                        cause: format!("transaction begin failed: {e}"),
180                    }
181                ))
182            })?;
183
184            // Another run that read the same registry may have applied this step since.
185            // On SQLite the transaction holds the write lock (`BEGIN IMMEDIATE`), and the
186            // PostgreSQL stores hold an advisory lock, so this read is current.
187            let applied_sql =
188                format!("SELECT COUNT(*) AS n FROM {registry_table} WHERE version = $1");
189            let applied: i64 = sqlx::query(sqlx::AssertSqlSafe(applied_sql))
190                .bind(version)
191                .fetch_one(&mut *tx)
192                .await
193                .and_then(|row| row.try_get("n"))
194                .map_err(|e| {
195                    adk_core::AdkError::memory(format!("migration registry read failed: {e}"))
196                })?;
197            if applied > 0 {
198                tx.rollback().await.map_err(|e| {
199                    adk_core::AdkError::memory(format!("transaction rollback failed: {e}"))
200                })?;
201                continue;
202            }
203
204            // Execute the migration SQL (raw_sql supports multiple
205            // semicolon-separated statements in a single call). Step bodies may be
206            // built at runtime, so the trusted-SQL contract of the runner is asserted.
207            sqlx::Executor::execute(&mut *tx, sqlx::raw_sql(sqlx::AssertSqlSafe(sql)))
208                .await
209                .map_err(|e| {
210                    adk_core::AdkError::memory(format!(
211                        "{}",
212                        MigrationError {
213                            version,
214                            description: description.to_string(),
215                            cause: e.to_string(),
216                        }
217                    ))
218                })?;
219
220            // Record the step in the registry
221            let now = Utc::now().to_rfc3339();
222            let rec = format!(
223                "INSERT INTO {registry_table} \
224                 (version, description, applied_at) \
225                 VALUES ($1, $2, $3)"
226            );
227            sqlx::query(sqlx::AssertSqlSafe(rec))
228                .bind(version)
229                .bind(description)
230                .bind(&now)
231                .execute(&mut *tx)
232                .await
233                .map_err(|e| {
234                    adk_core::AdkError::memory(format!(
235                        "{}",
236                        MigrationError {
237                            version,
238                            description: description.to_string(),
239                            cause: format!("registry record failed: {e}"),
240                        }
241                    ))
242                })?;
243
244            tx.commit().await.map_err(|e| {
245                adk_core::AdkError::memory(format!(
246                    "{}",
247                    MigrationError {
248                        version,
249                        description: description.to_string(),
250                        cause: format!("transaction commit failed: {e}"),
251                    }
252                ))
253            })?;
254        }
255
256        Ok(())
257    }};
258}
259
260/// Generates `run_sql_migrations`, `run_sql_migrations_on_connection`, and
261/// `sql_schema_version` for a concrete sqlx pool and connection type. Each SQL
262/// backend (`sqlite-memory`, `database-memory`) gets its own monomorphised copy, avoiding complex
263/// generic trait bounds.
264#[cfg(any(feature = "sqlite-memory", feature = "database-memory"))]
265macro_rules! impl_sql_migration_runner {
266    (
267        $mod_name:ident,
268        $pool_ty:ty,
269        $conn_ty:ty,
270        $int_type:expr,
271        $begin_sql:expr,
272        $missing_table:expr
273    ) => {
274        /// SQL migration runner for this database backend.
275        pub mod $mod_name {
276            use super::MigrationError;
277            use chrono::Utc;
278            use sqlx::{Connection, Row};
279            use std::future::Future;
280            use std::pin::Pin;
281
282            /// Run all pending migrations for a SQL backend.
283            ///
284            /// `registry_table` must be an ASCII identifier of at most 63 bytes,
285            /// starting with a letter or underscore. Step bodies are trusted executable SQL, never user input.
286            /// Descriptions are bound as values and may contain quotes.
287            ///
288            /// 1. Creates the registry table if it does not exist.
289            /// 2. Calls `detect_existing` to check for pre-existing schema
290            ///    tables. If tables exist but the registry is empty, records
291            ///    version 1 as already applied (baseline).
292            /// 3. Reads the maximum applied version from the registry.
293            /// 4. If the database version exceeds the compiled-in maximum,
294            ///    returns a version-mismatch error.
295            /// 5. Executes each unapplied step inside a transaction and
296            ///    records it in the registry.
297            ///
298            /// Each statement takes a connection from `pool`. Use
299            /// [`run_sql_migrations_on_connection`] when every statement must
300            /// run on the connection that holds a session-level lock.
301            pub async fn run_sql_migrations<F, Fut>(
302                pool: &$pool_ty,
303                registry_table: &str,
304                steps: &[(i64, &str, &str)],
305                detect_existing: F,
306            ) -> Result<(), adk_core::AdkError>
307            where
308                F: FnOnce() -> Fut,
309                Fut: Future<Output = Result<bool, adk_core::AdkError>>,
310            {
311                sql_migration_body!(
312                    exec: pool,
313                    begin: async {
314                        match $begin_sql {
315                            Some(statement) => pool.begin_with(statement).await,
316                            None => pool.begin().await,
317                        }
318                    },
319                    detect: detect_existing(),
320                    registry_table: registry_table,
321                    steps: steps,
322                    int_type: $int_type,
323                )
324            }
325
326            /// Run all pending migrations on one connection.
327            ///
328            /// The identifier and trusted-SQL requirements of [`run_sql_migrations`]
329            /// apply to this entry point too.
330            ///
331            /// Performs the same steps as [`run_sql_migrations`], but every
332            /// statement, including `detect_existing`, runs on `conn`. A
333            /// session-level lock taken on `conn`, such as a PostgreSQL advisory
334            /// lock, therefore covers the whole run, and the run needs no second
335            /// connection.
336            ///
337            /// # Errors
338            ///
339            /// Returns an error when a statement or `detect_existing` fails, or
340            /// when the registry records a version newer than the last entry in
341            /// `steps`.
342            pub async fn run_sql_migrations_on_connection<F>(
343                conn: &mut $conn_ty,
344                registry_table: &str,
345                steps: &[(i64, &str, &str)],
346                detect_existing: F,
347            ) -> Result<(), adk_core::AdkError>
348            where
349                F: FnOnce(
350                    &mut $conn_ty,
351                ) -> Pin<
352                    Box<dyn Future<Output = Result<bool, adk_core::AdkError>> + Send + '_>,
353                >,
354            {
355                sql_migration_body!(
356                    exec: &mut *conn,
357                    begin: async {
358                        match $begin_sql {
359                            Some(statement) => conn.begin_with(statement).await,
360                            None => conn.begin().await,
361                        }
362                    },
363                    detect: detect_existing(&mut *conn),
364                    registry_table: registry_table,
365                    steps: steps,
366                    int_type: $int_type,
367                )
368            }
369
370            /// Returns the highest applied migration version, or 0 if no
371            /// registry table exists or the registry is empty.
372            ///
373            /// # Errors
374            ///
375            /// Returns an error when `registry_table` is not an ASCII identifier of
376            /// at most 63 bytes, or when the registry cannot be read for any reason
377            /// other than the table being absent, such as a lost connection or a
378            /// missing privilege.
379            pub async fn sql_schema_version(
380                pool: &$pool_ty,
381                registry_table: &str,
382            ) -> Result<i64, adk_core::AdkError> {
383                super::validate_registry_table(registry_table)?;
384                let sql =
385                    format!("SELECT COALESCE(MAX(version), 0) AS max_v FROM {registry_table}");
386                let missing_table: fn(&dyn sqlx::error::DatabaseError) -> bool = $missing_table;
387                let row = match sqlx::query(sqlx::AssertSqlSafe(sql)).fetch_one(pool).await {
388                    Ok(row) => row,
389                    Err(sqlx::Error::Database(error)) if missing_table(error.as_ref()) => {
390                        return Ok(0);
391                    }
392                    Err(e) => {
393                        return Err(adk_core::AdkError::memory(format!(
394                            "migration registry read failed: {e}"
395                        )));
396                    }
397                };
398                row.try_get("max_v").map_err(|e| {
399                    adk_core::AdkError::memory(format!("migration registry read failed: {e}"))
400                })
401            }
402        }
403    };
404}
405
406// SQLite reports a missing table only through its message; PostgreSQL uses
407// SQLSTATE 42P01 (undefined_table).
408#[cfg(feature = "sqlite-memory")]
409impl_sql_migration_runner!(
410    sqlite_runner,
411    sqlx::SqlitePool,
412    sqlx::SqliteConnection,
413    "INTEGER",
414    // Takes the write lock at once, so a step and its registry check see no other writer.
415    Some("BEGIN IMMEDIATE"),
416    |error| error.message().starts_with("no such table")
417);
418
419#[cfg(feature = "database-memory")]
420impl_sql_migration_runner!(
421    pg_runner,
422    sqlx::PgPool,
423    sqlx::PgConnection,
424    "BIGINT",
425    None::<&str>,
426    |error| { error.code().as_deref() == Some("42P01") }
427);