runique 2.1.1

A Django-inspired web framework for Rust with ORM, templates, and comprehensive security middleware
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
//! `migrate` command — applies SeaORM migrations in the database.
use crate::utils::trad::{t, tf};
use anyhow::{Context, Result};
use sea_orm::{ConnectionTrait, Database, DatabaseConnection, DbBackend, TransactionTrait};
use std::{fs, path::Path};

// ============================================================
// Public API
// ============================================================

pub async fn up(migrations_path: &str) -> Result<()> {
    dotenvy::dotenv().ok();

    let migration_dir = migrations_path
        .trim_end_matches("/src")
        .trim_end_matches("\\src");

    println!("{}", tf("migrate.applying", &[migration_dir]));

    let status = tokio::process::Command::new("sea-orm-cli")
        .args(["migrate", "up", "--migration-dir", migration_dir])
        .status()
        .await
        .with_context(
            || "Unable to launch sea-orm-cli. Is it installed? Run: cargo install sea-orm-cli",
        )?;

    if !status.success() {
        anyhow::bail!("sea-orm-cli migrate up failed (code: {:?})", status.code());
    }

    println!("{}", t("migrate.complete_up"));
    Ok(())
}

pub async fn down(migrations_path: &str, files: Vec<String>, batch: Option<String>) -> Result<()> {
    if files.is_empty() && batch.is_none() {
        list_available(migrations_path)?;
        return Ok(());
    }

    dotenvy::dotenv().ok();

    let db_url = std::env::var("DATABASE_URL")
        .with_context(|| "DATABASE_URL not set. Add it to your .env file.")?;

    let db = Database::connect(&db_url)
        .await
        .with_context(|| "Failed to connect to database.")?;

    if let Some(batch_ts) = batch {
        rollback_batch(migrations_path, &batch_ts, &db).await?;
    } else {
        for file_arg in &files {
            rollback_file(migrations_path, file_arg, &db).await?;
        }
    }

    println!("\n{}", t("migrate.complete"));
    Ok(())
}

pub fn status(migrations_path: &str) -> Result<()> {
    println!("{}", tf("migrate.available_for", &[migrations_path]));
    list_available(migrations_path)?;
    Ok(())
}

// ============================================================
// Rollback: batch + file
// ============================================================

async fn rollback_batch(
    migrations_path: &str,
    timestamp: &str,
    db: &DatabaseConnection,
) -> Result<()> {
    let by_time_dir = format!("{}/applied/by_time", migrations_path);
    let batch_file = format!("{}/{}.rs", by_time_dir, timestamp);

    if !Path::new(&batch_file).exists() {
        anyhow::bail!(
            "Batch '{}' not found.\nRun 'runique migration status' to list available batches.",
            timestamp
        );
    }

    check_order_batch(&by_time_dir, timestamp)?;

    println!("{}", tf("migrate.rolling_back_batch", &[timestamp]));

    let source = fs::read_to_string(&batch_file)
        .with_context(|| format!("Cannot read batch file: {}", batch_file))?;

    execute_down_block(&source, db).await?;

    println!("  {}", tf("migrate.done", &[timestamp]));
    Ok(())
}

async fn rollback_file(
    migrations_path: &str,
    file_arg: &str,
    db: &DatabaseConnection,
) -> Result<()> {
    let applied_dir = format!("{}/applied", migrations_path);

    let file_path = if file_arg.ends_with(".rs") {
        format!("{}/{}", applied_dir, file_arg)
    } else {
        format!("{}/{}.rs", applied_dir, file_arg)
    };

    if !Path::new(&file_path).exists() {
        anyhow::bail!(
            "File not found: {}\nRun 'runique migration status' to list available files.",
            file_path
        );
    }

    // enforce rollback order per table if file_arg is "table/timestamp"
    let parts: Vec<&str> = file_arg.trim_end_matches(".rs").splitn(2, '/').collect();
    if parts.len() == 2 {
        let table = parts[0];
        let timestamp = parts[1];
        let table_dir = format!("{}/{}", applied_dir, table);
        check_order_file(&table_dir, timestamp)?;
    }

    println!("{}", tf("migrate.rolling_back", &[file_arg]));

    let source = fs::read_to_string(&file_path)
        .with_context(|| format!("Cannot read file: {}", file_path))?;

    execute_down_block(&source, db).await?;

    println!("  {}", tf("migrate.done", &[file_arg]));
    Ok(())
}

// ============================================================
// Rollback order checks
// ============================================================

fn check_order_batch(by_time_dir: &str, timestamp: &str) -> Result<()> {
    let mut batches = list_files_in_dir(by_time_dir)?;
    batches.sort();

    if let Some(latest) = batches.last() {
        let latest_ts = latest.trim_end_matches(".rs");
        if latest_ts != timestamp {
            anyhow::bail!(
                "Cannot rollback batch '{}'.\nA more recent batch exists: '{}'.\nRollback most recent first.",
                timestamp,
                latest_ts
            );
        }
    }

    Ok(())
}

fn check_order_file(table_dir: &str, timestamp: &str) -> Result<()> {
    let mut files = list_files_in_dir(table_dir)?;
    files.sort();

    if let Some(latest) = files.last() {
        let latest_ts = latest.trim_end_matches(".rs");
        if latest_ts != timestamp {
            anyhow::bail!(
                "Cannot rollback '{}'.\nA more recent migration exists for this table: '{}'.\nRollback most recent first.",
                timestamp,
                latest_ts
            );
        }
    }

    Ok(())
}

// ============================================================
// Listing
// ============================================================

fn list_files_in_dir(dir: &str) -> Result<Vec<String>> {
    if !Path::new(dir).exists() {
        return Ok(vec![]);
    }

    let files = fs::read_dir(dir)?
        .filter_map(|e| e.ok())
        .filter(|e| e.path().extension().and_then(|x| x.to_str()) == Some("rs"))
        .filter_map(|e| e.file_name().into_string().ok())
        .collect();

    Ok(files)
}

fn list_available(migrations_path: &str) -> Result<()> {
    let applied_dir = format!("{}/applied", migrations_path);

    if !Path::new(&applied_dir).exists() {
        println!("{}", t("migrate.no_applied_dir"));
        return Ok(());
    }

    let mut found = false;

    let mut tables: Vec<String> = fs::read_dir(&applied_dir)?
        .filter_map(|e| e.ok())
        .filter(|e| e.path().is_dir())
        .filter_map(|e| e.file_name().into_string().ok())
        .filter(|n| n != "by_time")
        .collect();
    tables.sort();

    for table in &tables {
        let table_dir = format!("{}/{}", applied_dir, table);
        let mut files = list_files_in_dir(&table_dir)?;
        files.sort();

        if !files.is_empty() {
            found = true;
            println!("\n  {}:", table);
            for file in &files {
                println!("    {}/{}", table, file.trim_end_matches(".rs"));
            }
        }
    }

    let by_time_dir = format!("{}/by_time", applied_dir);
    let mut batches = list_files_in_dir(&by_time_dir)?;
    batches.sort();

    if !batches.is_empty() {
        found = true;
        println!("\n  {}:", t("migrate.by_time_header"));
        for batch in &batches {
            println!("    {}", batch.trim_end_matches(".rs"));
        }
    }

    if !found {
        println!("{}", t("migrate.none_available"));
    } else {
        println!("\n{}", t("migrate.usage"));
        println!("  {}", t("migrate.usage_files"));
        println!("  {}", t("migrate.usage_batch"));
    }

    Ok(())
}

// ============================================================
// Core: execute down()
// ============================================================

async fn execute_down_block(source: &str, db: &DatabaseConnection) -> Result<()> {
    let backend = db.get_database_backend();

    // 1) capture down() block safely
    let down_block = extract_fn_block(source, "down").unwrap_or_default();

    // 2) build SQL statements from down() content
    let statements = extract_statements_from_block(&down_block, source, backend);

    if statements.is_empty() {
        println!("  {}", t("migrate.no_down"));
        return Ok(());
    }

    let txn = db.begin().await.context("Failed to begin transaction")?;

    let result: Result<()> = async {
        for sql in &statements {
            println!("  {}", tf("migrate.executing", &[sql]));
            txn.execute_unprepared(sql)
                .await
                .with_context(|| format!("Failed to execute: {}", sql))?;
        }
        Ok(())
    }
    .await;

    match result {
        Ok(()) => txn.commit().await.context("Failed to commit transaction")?,
        Err(e) => {
            let _ = txn.rollback().await;
            return Err(e);
        }
    }

    Ok(())
}

// ============================================================
// Extract function block
// ============================================================

fn extract_fn_block(source: &str, fn_name: &str) -> Option<String> {
    let mut in_fn = false;
    let mut depth: i32 = 0;
    let mut out = String::new();

    for line in source.lines() {
        let trimmed = line.trim();

        if !in_fn && trimmed.contains(&format!("async fn {}", fn_name)) {
            in_fn = true;

            out.push_str(line);
            out.push('\n');

            depth = depth.saturating_add(trimmed.chars().filter(|&c| c == '{').count() as i32);
            depth = depth.saturating_sub(trimmed.chars().filter(|&c| c == '}').count() as i32);

            if depth == 0 {
                return Some(out);
            }
            continue;
        }

        if !in_fn {
            continue;
        }

        out.push_str(line);
        out.push('\n');

        depth = depth.saturating_add(trimmed.chars().filter(|&c| c == '{').count() as i32);
        depth = depth.saturating_sub(trimmed.chars().filter(|&c| c == '}').count() as i32);

        if depth == 0 {
            return Some(out);
        }
    }

    None
}

// ============================================================
// SQL extraction (expanded)
// ============================================================

fn extract_statements_from_block(
    block: &str,
    full_source: &str,
    backend: DbBackend,
) -> Vec<String> {
    let mut statements = Vec::new();

    // table name: try block first, fallback to whole file
    let table_name = extract_table_from_source(block)
        .or_else(|| extract_table_from_source(full_source))
        .unwrap_or_default();

    if table_name.is_empty() {
        return statements;
    }

    for line in block.lines() {
        let trimmed = line.trim();

        // ----------------------------
        // add_column
        // ----------------------------
        if trimmed.contains(".add_column(")
            && trimmed.contains("Alias::new(\"")
            && let Some(col) = extract_alias_value(trimmed)
        {
            let col_type = seaorm_sql_type(trimmed);
            let null = if trimmed.contains(".null()") {
                ""
            } else {
                " NOT NULL"
            };

            let sql = match backend {
                DbBackend::Postgres => format!(
                    "ALTER TABLE \"{}\" ADD COLUMN \"{}\" {}{};",
                    table_name, col, col_type, null
                ),
                _ => format!(
                    "ALTER TABLE `{}` ADD COLUMN `{}` {}{};",
                    table_name, col, col_type, null
                ),
            };
            statements.push(sql);
        }

        // ----------------------------
        // drop_column
        // ----------------------------
        if trimmed.contains(".drop_column(Alias::new(\"")
            && let Some(col) = extract_alias_value(trimmed)
        {
            let sql = match backend {
                DbBackend::Postgres => {
                    format!("ALTER TABLE \"{}\" DROP COLUMN \"{}\";", table_name, col)
                }
                _ => format!("ALTER TABLE `{}` DROP COLUMN `{}`;", table_name, col),
            };
            statements.push(sql);
        }

        // ----------------------------
        // modify_column : nullable only (SET/DROP NOT NULL)
        // Expected pattern: .modify_column(ColumnDef::new(Alias::new("bio")).text().not_null())
        // ----------------------------
        if trimmed.contains(".modify_column(")
            && trimmed.contains("Alias::new(\"")
            && let Some(col) = extract_alias_value(trimmed)
        {
            // Here we only handle NOT NULL / NULL (sufficient for your test)
            let make_null = trimmed.contains(".null()");
            let sql = match backend {
                DbBackend::Postgres => {
                    if make_null {
                        format!(
                            "ALTER TABLE \"{}\" ALTER COLUMN \"{}\" DROP NOT NULL;",
                            table_name, col
                        )
                    } else {
                        format!(
                            "ALTER TABLE \"{}\" ALTER COLUMN \"{}\" SET NOT NULL;",
                            table_name, col
                        )
                    }
                }
                _ => {
                    // MySQL/MariaDB: MODIFY COLUMN requires the type. We do an "unsafe" fallback.
                    // => If you target MySQL, you'll need to use sea_query to be correct.
                    if make_null {
                        format!(
                            "-- WARNING: modify_column NULL not supported safely on this backend for `{}`.`{}`",
                            table_name, col
                        )
                    } else {
                        format!(
                            "-- WARNING: modify_column NOT NULL not supported safely on this backend for `{}`.`{}`",
                            table_name, col
                        )
                    }
                }
            };
            statements.push(sql);
        }

        // ----------------------------
        // drop_table
        // ----------------------------
        if trimmed.contains(".drop_table(")
            && trimmed.contains("Alias::new(\"")
            && let Some(t) = extract_alias_value(trimmed)
        {
            let sql = match backend {
                DbBackend::Postgres => format!("DROP TABLE IF EXISTS \"{}\";", t),
                _ => format!("DROP TABLE IF EXISTS `{}`;", t),
            };
            statements.push(sql);
        }

        // ----------------------------
        // drop_index (pattern: Index::drop().name("idx").table(Alias::new("t")))
        // ----------------------------
        if trimmed.contains(".drop_index(")
            && trimmed.contains(".name(\"")
            && let Some(idx) = extract_name_value(trimmed)
        {
            let sql = match backend {
                DbBackend::Postgres => format!("DROP INDEX IF EXISTS \"{}\";", idx),
                _ => format!("DROP INDEX `{}`;", idx),
            };
            statements.push(sql);
        }

        // ----------------------------
        // drop_foreign_key (pattern: ForeignKey::drop().table(Alias::new("t")).name("t_col_ref_fkey"))
        // ----------------------------
        if trimmed.contains(".drop_foreign_key(")
            && trimmed.contains(".name(\"")
            && let Some(fk_name) = extract_name_value(trimmed)
        {
            let sql = match backend {
                DbBackend::Postgres => format!(
                    "ALTER TABLE \"{}\" DROP CONSTRAINT IF EXISTS \"{}\";",
                    table_name, fk_name
                ),
                _ => format!(
                    "ALTER TABLE `{}` DROP FOREIGN KEY `{}`;",
                    table_name, fk_name
                ),
            };
            statements.push(sql);
        }
    }

    statements
}

// ============================================================
// Helpers: extract table + alias + name("...")
// ============================================================

fn extract_table_from_source(source: &str) -> Option<String> {
    for line in source.lines() {
        let trimmed = line.trim();
        if trimmed.contains(".table(Alias::new(\"") {
            return extract_alias_value(trimmed);
        }
    }
    None
}

fn extract_alias_value(s: &str) -> Option<String> {
    let marker = "Alias::new(\"";
    let pos = s.find(marker)?.saturating_add(marker.len());
    let end = s[pos..].find('"')?.saturating_add(pos);
    Some(s[pos..end].to_string())
}

fn extract_name_value(s: &str) -> Option<String> {
    let marker = ".name(\"";
    let pos = s.find(marker)?.saturating_add(marker.len());
    let end = s[pos..].find('"')?.saturating_add(pos);
    Some(s[pos..end].to_string())
}

// ============================================================
// Type mapping heuristic (as before)
// ============================================================

fn seaorm_sql_type(line: &str) -> &str {
    if line.contains(".blob()")
        || line.contains(".binary(")
        || line.contains(".binary_len(")
        || line.contains(".var_binary(")
    {
        "BYTEA"
    } else if line.contains(".text()") {
        "TEXT"
    } else if line.contains(".char()") || line.contains(".char_len(") {
        "CHAR"
    } else if line.contains(".tiny_integer()") || line.contains(".small_integer()") {
        "SMALLINT"
    } else if line.contains(".big_unsigned()") {
        "BIGINT"
    } else if line.contains(".unsigned()") {
        "INTEGER"
    } else if line.contains(".big_integer()") {
        "BIGINT"
    } else if line.contains(".integer()") {
        "INTEGER"
    } else if line.contains(".float()") {
        "REAL"
    } else if line.contains(".double()") {
        "DOUBLE PRECISION"
    } else if line.contains(".decimal(") || line.contains(".decimal_len(") {
        "DECIMAL"
    } else if line.contains(".boolean()") {
        "BOOLEAN"
    } else if line.contains(".timestamp_tz()") || line.contains(".timestamp_with_time_zone()") {
        "TIMESTAMP WITH TIME ZONE"
    } else if line.contains(".timestamp()")
        || line.contains(".date_time()")
        || line.contains(".datetime()")
    {
        "TIMESTAMP"
    } else if line.contains(".date()") {
        "DATE"
    } else if line.contains(".time()") {
        "TIME"
    } else if line.contains(".uuid()") {
        "UUID"
    } else if line.contains(".json_binary()") {
        "JSONB"
    } else if line.contains(".json()") {
        "JSON"
    } else if line.contains(".inet()") {
        "INET"
    } else if line.contains(".cidr()") {
        "CIDR"
    } else if line.contains(".mac_address()") {
        "MACADDR"
    } else if line.contains(".interval()") {
        "INTERVAL"
    } else {
        "VARCHAR(255)"
    }
}