ic-sql-migrate 0.0.5

A lightweight database migration library for Internet Computer (ICP) canisters with SQLite and Turso support.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
//! Turso database migration support for ICP canisters.
//!
//! This module provides migration functionality for Turso databases in Internet Computer canisters
//! using the `turso` crate. It manages database schema versioning through a `_migrations` table
//! that tracks which migrations have been applied.
//!
//! # Features
//! - Automatic migration tracking via `_migrations` table
//! - Transactional migration execution (all-or-nothing)
//! - Idempotent migrations (safe to run multiple times)
//! - Ordered execution of pending migrations
//!
//! # Usage in ICP Canisters
//! ```ignore
//! use ic_cdk::{init, post_upgrade, pre_upgrade};
//! use turso::Connection;
//! use std::cell::RefCell;
//!
//! static MIGRATIONS: &[ic_sql_migrate::Migration] = ic_sql_migrate::include!();
//!
//! thread_local! {
//!     static CONNECTION: RefCell<Option<Connection>> = const { RefCell::new(None) };
//! }
//!
//! async fn get_connection() -> Connection {
//!     // Initialize or get existing connection
//!     // See examples for complete implementation
//! }
//!
//! async fn run_migrations() {
//!     let mut conn = get_connection().await;
//!     ic_sql_migrate::turso::migrate(&mut conn, MIGRATIONS).await.unwrap();
//! }
//!
//! #[init]
//! async fn init() {
//!     // Initialize memory/storage
//!     run_migrations().await;
//! }
//!
//! #[pre_upgrade]
//! fn pre_upgrade() {
//!     // Close database connection
//! }
//!
//! #[post_upgrade]
//! async fn post_upgrade() {
//!     // Re-initialize memory/storage
//!     run_migrations().await;
//! }
//! ```

use std::collections::HashSet;
use turso::Connection;

use crate::{Error, MigrateResult, Migration, Seed};

/// Ensures the migrations tracking table exists in the database.
///
/// Creates a `_migrations` table if it doesn't exist, which tracks:
/// - `id`: The unique identifier of each applied migration
/// - `applied_at`: Timestamp when the migration was applied
async fn ensure_migrations_table(conn: &Connection) -> MigrateResult<()> {
    conn.execute(
        "CREATE TABLE IF NOT EXISTS _migrations (
            id TEXT PRIMARY KEY,
            applied_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
        )",
        (),
    )
    .await?;
    Ok(())
}

/// Retrieves the set of already applied migration IDs from the database.
async fn get_applied_migrations(conn: &Connection) -> MigrateResult<HashSet<String>> {
    let mut rows = conn.query("SELECT id FROM _migrations", ()).await?;

    let mut applied_set = HashSet::new();
    while let Some(row) = rows.next().await? {
        let value = row.get_value(0)?;
        if let Some(text) = value.as_text() {
            applied_set.insert(text.to_string());
        }
    }

    Ok(applied_set)
}

/// Executes all pending migrations in order.
///
/// This function:
/// 1. Ensures the migrations tracking table exists
/// 2. Identifies which migrations have already been applied
/// 3. Executes pending migrations in the order they appear in the slice
/// 4. Records each migration as applied
///
/// All migrations are executed within a single transaction for atomicity.
/// If any migration fails, all changes are rolled back.
///
/// # Arguments
/// * `conn` - Mutable reference to the Turso connection
/// * `migrations` - Slice of migrations to apply in order
///
/// # Returns
/// * `Ok(())` - If all pending migrations were successfully applied or if there were no pending migrations
/// * `Err(Error)` - If any migration failed to execute
///
/// # Errors
/// Returns an error if:
/// - Database operations fail
/// - Migration SQL is invalid
/// - Transaction cannot be committed
///
/// # Example in ICP Canister
/// ```no_run
/// use turso::Connection;
/// use ic_sql_migrate::Migration;
///
/// static MIGRATIONS: &[Migration] = &[
///     Migration::new("001_initial", "CREATE TABLE users (id INTEGER PRIMARY KEY);"),
///     Migration::new("002_add_email", "ALTER TABLE users ADD COLUMN email TEXT;"),
/// ];
///
/// async fn apply_migrations(conn: &mut Connection) {
///     ic_sql_migrate::turso::migrate(conn, MIGRATIONS).await.unwrap();
/// }
/// ```
pub async fn migrate(conn: &mut Connection, migrations: &[Migration]) -> MigrateResult<()> {
    ensure_migrations_table(conn).await?;
    let applied_migrations = get_applied_migrations(conn).await?;

    // Check if there are any migrations to apply
    let pending_migrations: Vec<&Migration> = migrations
        .iter()
        .filter(|m| !applied_migrations.contains(m.id))
        .collect();

    if pending_migrations.is_empty() {
        return Ok(());
    }

    // Start transaction for all migrations
    let tx = conn.transaction().await?;

    for migration in pending_migrations {
        if let Err(e) = tx.execute_batch(migration.sql).await {
            tx.rollback().await?;
            return Err(Error::MigrationFailed {
                id: migration.id.to_string(),
                message: e.to_string(),
            });
        }

        // Record migration as applied
        if let Err(e) = tx
            .execute("INSERT INTO _migrations(id) VALUES (?)", [migration.id])
            .await
        {
            tx.rollback().await?;
            return Err(Error::MigrationFailed {
                id: migration.id.to_string(),
                message: e.to_string(),
            });
        };
    }

    // Commit all migrations atomically
    tx.commit().await?;

    Ok(())
}

/// Ensures the seeds tracking table exists in the database.
///
/// Creates a `_seeds` table if it doesn't exist, which tracks:
/// - `id`: The unique identifier of each applied seed
/// - `applied_at`: Timestamp when the seed was applied
async fn ensure_seeds_table(conn: &Connection) -> MigrateResult<()> {
    conn.execute(
        "CREATE TABLE IF NOT EXISTS _seeds (
            id TEXT PRIMARY KEY,
            applied_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
        )",
        (),
    )
    .await?;
    Ok(())
}

/// Retrieves the set of already applied seed IDs from the database.
async fn get_applied_seeds(conn: &Connection) -> MigrateResult<HashSet<String>> {
    let mut rows = conn.query("SELECT id FROM _seeds", ()).await?;

    let mut applied_set = HashSet::new();
    while let Some(row) = rows.next().await? {
        let value = row.get_value(0)?;
        if let Some(text) = value.as_text() {
            applied_set.insert(text.to_string());
        }
    }

    Ok(applied_set)
}

/// Executes all pending seeds in order.
///
/// This function:
/// 1. Ensures the seeds tracking table exists
/// 2. Identifies which seeds have already been applied
/// 3. Executes pending seeds in the order they appear in the slice
/// 4. Records each seed as applied
///
/// All seeds are executed within individual transactions for atomicity.
/// If any seed fails, changes for that seed are rolled back.
///
/// # Arguments
/// * `conn` - Mutable reference to the Turso connection
/// * `seeds` - Slice of seeds to apply in order
///
/// # Returns
/// * `Ok(())` - If all pending seeds were successfully applied or if there were no pending seeds
/// * `Err(Error)` - If any seed failed to execute
///
/// # Errors
/// Returns an error if:
/// - Database operations fail
/// - Seed function returns an error
/// - Transaction cannot be committed
///
/// # Example
/// ```no_run
/// use turso::Connection;
/// use ic_sql_migrate::Seed;
///
/// async fn seed_users(conn: &mut Connection) -> ic_sql_migrate::MigrateResult<()> {
///     conn.execute("INSERT INTO users (name) VALUES ('Alice')", ()).await?;
///     Ok(())
/// }
///
/// async fn apply_seeds(conn: &mut Connection) {
///     // Seeds would be defined here
///     // ic_sql_migrate::turso::seed(conn, SEEDS).await.unwrap();
/// }
/// ```
pub async fn seed(conn: &mut Connection, seeds: &[Seed]) -> MigrateResult<()> {
    ensure_seeds_table(conn).await?;
    let applied_seeds = get_applied_seeds(conn).await?;

    let pending_seeds: Vec<&Seed> = seeds
        .iter()
        .filter(|s| !applied_seeds.contains(s.id))
        .collect();

    if pending_seeds.is_empty() {
        return Ok(());
    }

    for seed in pending_seeds {
        let tx = conn.transaction().await?;

        if let Err(e) = (seed.seed_fn)(&tx).await {
            tx.rollback().await?;
            return Err(Error::MigrationFailed {
                id: seed.id.to_string(),
                message: e.to_string(),
            });
        }

        if let Err(e) = tx
            .execute("INSERT INTO _seeds(id) VALUES (?)", [seed.id])
            .await
        {
            tx.rollback().await?;
            return Err(Error::MigrationFailed {
                id: seed.id.to_string(),
                message: e.to_string(),
            });
        }

        tx.commit().await?;
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_migration_creation() {
        let migration = Migration::new("001_test", "CREATE TABLE test (id INTEGER);");
        assert_eq!(migration.id, "001_test");
        assert_eq!(migration.sql, "CREATE TABLE test (id INTEGER);");
    }

    #[tokio::test]
    async fn test_ensure_migrations_table() {
        // Create in-memory Turso database
        let db = turso::Builder::new_local(":memory:").build().await.unwrap();
        let conn = db.connect().unwrap();

        ensure_migrations_table(&conn).await.unwrap();

        // Verify table exists by querying it
        let mut rows = conn
            .query("SELECT COUNT(*) FROM _migrations", ())
            .await
            .unwrap();
        assert!(rows.next().await.unwrap().is_some());
    }

    #[tokio::test]
    async fn test_up_migrations() {
        // Create in-memory Turso database
        let db = turso::Builder::new_local(":memory:").build().await.unwrap();
        let mut conn = db.connect().unwrap();

        let migrations = &[
            Migration::new(
                "001_create_users",
                "CREATE TABLE users (id INTEGER PRIMARY KEY);",
            ),
            Migration::new("002_add_email", "ALTER TABLE users ADD COLUMN email TEXT;"),
        ];

        // Run migrations
        migrate(&mut conn, migrations).await.unwrap();

        // Verify migrations were applied
        let applied = get_applied_migrations(&conn).await.unwrap();
        assert!(applied.contains("001_create_users"));
        assert!(applied.contains("002_add_email"));

        // Verify table structure by checking if we can query the email column
        let result = conn
            .execute(
                "INSERT INTO users (id, email) VALUES (1, 'test@test.com')",
                (),
            )
            .await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_up_migrations_idempotency() {
        // Create in-memory Turso database
        let db = turso::Builder::new_local(":memory:").build().await.unwrap();
        let mut conn = db.connect().unwrap();

        let migrations = &[Migration::new(
            "001_test",
            "CREATE TABLE test (id INTEGER);",
        )];

        // Run migrations twice
        migrate(&mut conn, migrations).await.unwrap();
        migrate(&mut conn, migrations).await.unwrap();

        // Should only be applied once
        let mut rows = conn
            .query("SELECT COUNT(*) FROM _migrations WHERE id='001_test'", ())
            .await
            .unwrap();

        if let Some(row) = rows.next().await.unwrap() {
            let count = row.get_value(0).unwrap();
            assert_eq!(*count.as_integer().unwrap(), 1);
        } else {
            panic!("Expected a count result");
        }
    }

    #[tokio::test]
    async fn test_migration_failure_rollback() {
        let db = turso::Builder::new_local(":memory:").build().await.unwrap();
        let mut conn = db.connect().unwrap();

        let migrations = &[
            Migration::new("001_valid", "CREATE TABLE test (id INTEGER);"),
            Migration::new("002_invalid", "INVALID SQL STATEMENT;"),
        ];

        let result = migrate(&mut conn, migrations).await;
        assert!(result.is_err());

        let applied = get_applied_migrations(&conn).await.unwrap();
        assert!(applied.is_empty());

        let result = conn.query("SELECT * FROM test", ()).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_ensure_seeds_table() {
        let db = turso::Builder::new_local(":memory:").build().await.unwrap();
        let conn = db.connect().unwrap();

        ensure_seeds_table(&conn).await.unwrap();

        let mut rows = conn
            .query("SELECT COUNT(*) FROM _seeds", ())
            .await
            .unwrap();
        assert!(rows.next().await.unwrap().is_some());
    }

    fn seed_test_data(conn: &Connection) -> std::pin::Pin<Box<dyn std::future::Future<Output = MigrateResult<()>> + Send>> {
        let conn = conn.clone();
        Box::pin(async move {
            conn.execute("CREATE TABLE IF NOT EXISTS test_users (id INTEGER PRIMARY KEY, name TEXT)", ()).await?;
            conn.execute("INSERT INTO test_users (name) VALUES ('Alice')", ()).await?;
            conn.execute("INSERT INTO test_users (name) VALUES ('Bob')", ()).await?;
            Ok(())
        })
    }

    fn seed_more_data(conn: &Connection) -> std::pin::Pin<Box<dyn std::future::Future<Output = MigrateResult<()>> + Send>> {
        let conn = conn.clone();
        Box::pin(async move {
            conn.execute("INSERT INTO test_users (name) VALUES ('Charlie')", ()).await?;
            Ok(())
        })
    }

    #[tokio::test]
    async fn test_seed_execution() {
        let db = turso::Builder::new_local(":memory:").build().await.unwrap();
        let mut conn = db.connect().unwrap();

        let seeds = &[
            Seed::new("001_initial", seed_test_data),
            Seed::new("002_more", seed_more_data),
        ];

        seed(&mut conn, seeds).await.unwrap();

        let applied = get_applied_seeds(&conn).await.unwrap();
        assert!(applied.contains("001_initial"));
        assert!(applied.contains("002_more"));

        let mut rows = conn
            .query("SELECT COUNT(*) FROM test_users", ())
            .await
            .unwrap();

        if let Some(row) = rows.next().await.unwrap() {
            let count = row.get_value(0).unwrap();
            assert_eq!(*count.as_integer().unwrap(), 3);
        } else {
            panic!("Expected count result");
        }
    }

    #[tokio::test]
    async fn test_seed_idempotency() {
        let db = turso::Builder::new_local(":memory:").build().await.unwrap();
        let mut conn = db.connect().unwrap();

        let seeds = &[Seed::new("001_test", seed_test_data)];

        seed(&mut conn, seeds).await.unwrap();
        seed(&mut conn, seeds).await.unwrap();

        let mut rows = conn
            .query("SELECT COUNT(*) FROM _seeds WHERE id='001_test'", ())
            .await
            .unwrap();

        if let Some(row) = rows.next().await.unwrap() {
            let count = row.get_value(0).unwrap();
            assert_eq!(*count.as_integer().unwrap(), 1);
        } else {
            panic!("Expected count result");
        }

        let mut rows = conn
            .query("SELECT COUNT(*) FROM test_users", ())
            .await
            .unwrap();

        if let Some(row) = rows.next().await.unwrap() {
            let count = row.get_value(0).unwrap();
            assert_eq!(*count.as_integer().unwrap(), 2);
        } else {
            panic!("Expected count result");
        }
    }
}