rullst-orm 13.0.0-alpha.1

Fast, un-opinionated, database-agnostic ORM and query builder for Rust
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
use super::migration_lock::MigrationLock;
use super::validation::validate_table_name;
use crate::Error;

#[async_trait::async_trait]
pub trait Migration: Send + Sync {
    fn name(&self) -> &'static str;
    async fn up(&self) -> Result<(), Error>;
    async fn down(&self) -> Result<(), Error>;

    /// Whether the runner applies `up()` (or `down()`) and records it in the
    /// `migrations` table inside one [`crate::Orm::transaction`], so a failure
    /// between the two cannot leave the change applied but unrecorded.
    ///
    /// Only statements that join the task-scoped transaction are covered:
    /// `Schema` calls, `execute_query!`/`dispatch_executor!` and generated
    /// model methods. A query sent to `Orm::pool()` directly runs on another
    /// connection outside the transaction and cannot see its uncommitted
    /// tables, so a migration that uses one must keep the default `false`.
    /// PostgreSQL and SQLite roll DDL back with the transaction; MySQL and
    /// MariaDB commit implicitly at each DDL statement, so there only data
    /// changes after the last DDL statement are atomic with the record.
    /// Statements that cannot run in a transaction block, such as PostgreSQL
    /// `CREATE INDEX CONCURRENTLY`, need `false`. Unpublished v13 API.
    fn within_transaction(&self) -> bool {
        false
    }
}

#[cfg_attr(test, mutants::skip)]
pub async fn run_artisan_with_args(
    args: &[String],
    migrations: Vec<Box<dyn Migration>>,
    seeders: Vec<Box<dyn crate::Seeder>>,
) -> Result<(), Error> {
    if args.len() < 2 {
        println!("Rullst ORM Artisan CLI");
        println!("Usage:");
        println!("  make:migration <name>   Generate a new migration");
        println!("  migrate                  Run all pending migrations");
        println!("  migrate:rollback         Rollback the last batch of migrations");
        println!("  status                   Show migrations status");
        println!("  db:seed                  Populate the database with seeders");
        println!(
            "  sail:install [--force]   Generate a local docker-compose.yml (Laravel Sail style); --force replaces an existing file"
        );
        return Ok(());
    }

    let command = &args[1];
    match command.as_str() {
        "make:migration" => {
            if args.len() < 3 {
                println!("Error: migration name is required.");
                return Ok(());
            }
            let name = &args[2];
            create_migration_files(name)?;
        }
        "migrate" | "db:migrate" => {
            run_migrations(migrations).await?;
        }
        "migrate:rollback" | "db:rollback" => {
            rollback_migrations(migrations).await?;
        }
        "status" | "db:status" => {
            status_migrations(migrations).await?;
        }
        "db:seed" => {
            println!("Seeding database...");
            crate::Orm::seed(seeders).await?;
            println!("Database seeded successfully!");
        }
        "sail:install" => {
            let force = args.iter().skip(2).any(|argument| argument == "--force");
            let path = super::sail::install(std::path::Path::new("."), force)?;
            println!(
                "{} created successfully! Run `docker compose up -d` to start.",
                path.display()
            );
        }
        _ => {
            println!("Unknown command: {}", command);
        }
    }
    Ok(())
}

#[cfg_attr(test, mutants::skip)]
pub async fn run_artisan(
    migrations: Vec<Box<dyn Migration>>,
    seeders: Vec<Box<dyn crate::Seeder>>,
) -> Result<(), Error> {
    let args: Vec<String> = std::env::args().collect();
    run_artisan_with_args(&args, migrations, seeders).await
}

#[cfg_attr(mutants, mutants::skip)]
async fn migrations_table_exists(pool: &crate::RullstPool, driver: &str) -> Result<bool, Error> {
    // Only the schema/database that unqualified `migrations` statements use
    // counts; a same-named table of another application must not.
    match driver {
        "postgres" | "mysql" => {
            let query_str = if driver == "postgres" {
                "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = current_schema() AND table_name = 'migrations'"
            } else {
                "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'migrations'"
            };
            let row: (i64,) = sqlx::query_as(query_str).fetch_one(pool).await?;
            Ok(row.0 > 0)
        }
        _ => {
            let query_str =
                "SELECT COUNT(*) FROM sqlite_schema WHERE type='table' AND name='migrations'";
            let row: (i64,) = sqlx::query_as(query_str).fetch_one(pool).await?;
            Ok(row.0 > 0)
        }
    }
}

#[cfg_attr(test, mutants::skip)]
async fn status_migrations(migrations: Vec<Box<dyn Migration>>) -> Result<(), Error> {
    let pool = crate::Orm::try_pool()?;
    let driver = crate::Orm::try_driver()?;

    let table_exists = migrations_table_exists(pool, driver).await?;

    let executed_set = if table_exists {
        let executed: Vec<(String,)> = sqlx::query_as("SELECT migration FROM migrations")
            .fetch_all(pool)
            .await?;
        executed
            .into_iter()
            .map(|(m,)| m)
            .collect::<std::collections::HashSet<String>>()
    } else {
        std::collections::HashSet::new()
    };

    let name_header = "Migration Name";
    let status_header = "Status";
    println!("{name_header:<40} | {status_header}");
    println!("{}", "-".repeat(55));
    for m in migrations {
        let name = m.name();
        let status = if executed_set.contains(name) {
            "Applied"
        } else {
            "Pending"
        };
        println!("{:<40} | {}", name, status);
    }

    Ok(())
}

#[cfg_attr(test, mutants::skip)]
fn create_migration_files(name: &str) -> Result<(), Error> {
    validate_table_name(name)?;
    use std::fs;

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
        .to_string();
    let sanitized_name = name.replace(['/', '\\'], "");
    let snake_name = sanitized_name.to_lowercase().replace("-", "_");
    let file_name = format!("m{}_{}", now, snake_name);

    fs::create_dir_all("src/migrations")
        .map_err(|e| Error::Internal(format!("Failed to create migrations directory: {}", e)))?;

    let new_file_path = format!("src/migrations/{}.rs", file_name);
    let template = include_str!("../migration_template.rs.txt");
    let migration_code = template
        .replace("{timestamp}", &now)
        .replace("{name}", &snake_name);

    fs::write(&new_file_path, migration_code)
        .map_err(|e| Error::Internal(format!("Failed to write migration file: {}", e)))?;
    println!("Created migration file: {}", new_file_path);

    regenerate_migrations_mod()?;

    Ok(())
}

#[cfg_attr(test, mutants::skip)]
fn regenerate_migrations_mod() -> Result<(), Error> {
    use std::fs;
    let paths = fs::read_dir("src/migrations")
        .map_err(|e| Error::Internal(format!("Failed to read migrations dir: {}", e)))?;

    let mut modules = vec![];
    for path in paths {
        let path = path.map_err(|e| Error::Internal(e.to_string()))?.path();
        if let Some(ext) = path.extension()
            && ext == "rs"
            && let Some(stem) = path.file_stem()
        {
            let stem_str = stem.to_string_lossy().to_string();
            if stem_str != "mod" && stem_str.starts_with('m') {
                modules.push(stem_str);
            }
        }
    }
    modules.sort();

    use std::fmt::Write;
    let mut mod_content = String::new();
    mod_content.push_str("// Generated by Rullst ORM Artisan. Do not edit manually.\n\n");
    for m in &modules {
        let _ = writeln!(mod_content, "pub mod {};", m);
    }
    mod_content
        .push_str("\npub fn get_migrations() -> Vec<Box<dyn rullst_orm::schema::Migration>> {\n");
    mod_content.push_str("    vec![\n");
    for m in &modules {
        let _ = writeln!(mod_content, "        Box::new({}::MigrationImpl),", m);
    }
    mod_content.push_str("    ]\n");
    mod_content.push_str("}\n");

    fs::write("src/migrations/mod.rs", mod_content)
        .map_err(|e| Error::Internal(format!("Failed to write mod.rs: {}", e)))?;
    println!("Regenerated src/migrations/mod.rs");

    Ok(())
}

/// Applies pending migrations while holding the database's runner lock, so
/// concurrent runners (for example replicas starting together) apply each
/// migration once: the executed set is read only after the lock is held.
#[cfg_attr(test, mutants::skip)]
async fn run_migrations(migrations: Vec<Box<dyn Migration>>) -> Result<(), Error> {
    let pool = crate::Orm::try_pool()?;
    let driver = crate::Orm::try_driver()?;
    let lock = MigrationLock::acquire(pool, driver).await?;
    let result = run_pending_migrations(pool, driver, migrations).await;
    lock.release().await;
    result
}

#[cfg_attr(test, mutants::skip)]
async fn run_pending_migrations(
    pool: &crate::RullstPool,
    driver: &str,
    migrations: Vec<Box<dyn Migration>>,
) -> Result<(), Error> {
    let query_str = match driver {
        "postgres" => {
            "CREATE TABLE IF NOT EXISTS migrations (
                id SERIAL PRIMARY KEY,
                migration VARCHAR(255) NOT NULL UNIQUE,
                batch INTEGER NOT NULL
            )"
        }
        "mysql" => {
            "CREATE TABLE IF NOT EXISTS migrations (
                id INT AUTO_INCREMENT PRIMARY KEY,
                migration VARCHAR(255) NOT NULL UNIQUE,
                batch INT NOT NULL
            )"
        }
        _ => {
            "CREATE TABLE IF NOT EXISTS migrations (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                migration TEXT NOT NULL UNIQUE,
                batch INTEGER NOT NULL
            )"
        }
    };

    sqlx::query(query_str).execute(pool).await?;

    let executed: Vec<(String,)> = sqlx::query_as("SELECT migration FROM migrations")
        .fetch_all(pool)
        .await?;
    let executed_set: std::collections::HashSet<String> =
        executed.into_iter().map(|(m,)| m).collect();

    let batch_row: (Option<i32>,) = sqlx::query_as("SELECT MAX(batch) FROM migrations")
        .fetch_one(pool)
        .await?;
    let next_batch = batch_row.0.unwrap_or(0) + 1;

    let tracking_sql = if driver == "postgres" {
        "INSERT INTO migrations (migration, batch) VALUES ($1, $2)"
    } else {
        "INSERT INTO migrations (migration, batch) VALUES (?, ?)"
    };
    let mut count = 0;
    for m in migrations {
        let name = m.name();
        if !executed_set.contains(name) {
            println!("Migrating: {}", name);
            if m.within_transaction() {
                // The change and its record commit (or roll back) together.
                crate::Orm::transaction(move |_| {
                    Box::pin(async move {
                        m.up().await?;
                        let record = sqlx::query(tracking_sql).bind(name).bind(next_batch);
                        crate::execute_query!(record, execute, pool)?;
                        Ok::<(), Error>(())
                    })
                })
                .await?;
            } else {
                m.up().await?;
                sqlx::query(tracking_sql)
                    .bind(name)
                    .bind(next_batch)
                    .execute(pool)
                    .await?;
            }
            println!("Migrated:  {}", name);
            count += 1;
        }
    }

    if count == 0 {
        println!("Nothing to migrate.");
    }

    Ok(())
}

/// Rolls back the last batch while holding the database's runner lock.
#[cfg_attr(test, mutants::skip)]
async fn rollback_migrations(migrations: Vec<Box<dyn Migration>>) -> Result<(), Error> {
    let pool = crate::Orm::try_pool()?;
    let driver = crate::Orm::try_driver()?;
    let lock = MigrationLock::acquire(pool, driver).await?;
    let result = rollback_last_batch(pool, driver, migrations).await;
    lock.release().await;
    result
}

#[cfg_attr(test, mutants::skip)]
async fn rollback_last_batch(
    pool: &crate::RullstPool,
    driver: &str,
    migrations: Vec<Box<dyn Migration>>,
) -> Result<(), Error> {
    let table_exists = migrations_table_exists(pool, driver).await?;

    if !table_exists {
        println!("Nothing to rollback.");
        return Ok(());
    }

    let batch_row: (Option<i32>,) = sqlx::query_as("SELECT MAX(batch) FROM migrations")
        .fetch_one(pool)
        .await?;

    let last_batch = match batch_row.0 {
        Some(b) if b > 0 => b,
        _ => {
            println!("Nothing to rollback.");
            return Ok(());
        }
    };

    let rollback_query = if driver == "postgres" {
        "SELECT migration FROM migrations WHERE batch = $1 ORDER BY id DESC"
    } else {
        "SELECT migration FROM migrations WHERE batch = ? ORDER BY id DESC"
    };
    let to_rollback: Vec<(String,)> = sqlx::query_as(rollback_query)
        .bind(last_batch)
        .fetch_all(pool)
        .await?;

    let mut rollback_map: std::collections::HashMap<String, Box<dyn Migration>> =
        std::collections::HashMap::with_capacity(migrations.len());
    for m in migrations {
        rollback_map.insert(m.name().to_string(), m);
    }

    let forget_sql = if driver == "postgres" {
        "DELETE FROM migrations WHERE migration = $1"
    } else {
        "DELETE FROM migrations WHERE migration = ?"
    };
    for (name,) in to_rollback {
        if let Some(m) = rollback_map.remove(&name) {
            println!("Rolling back: {}", name);
            // Forget each migration as soon as its down() succeeds, so a later
            // failing down() leaves only the migrations that were not reverted
            // recorded as applied; the next rollback resumes from there.
            if m.within_transaction() {
                let recorded = name.clone();
                crate::Orm::transaction(move |_| {
                    Box::pin(async move {
                        m.down().await?;
                        let forget = sqlx::query(forget_sql).bind(recorded);
                        crate::execute_query!(forget, execute, pool)?;
                        Ok::<(), Error>(())
                    })
                })
                .await?;
            } else {
                m.down().await?;
                sqlx::query(forget_sql).bind(&name).execute(pool).await?;
            }
            println!("Rolled back:  {}", name);
        } else {
            println!(
                "Warning: migration {} found in database but not in compiled binary.",
                name
            );
        }
    }

    Ok(())
}