che-rest 0.2.0

Typed REST framework and project tooling for che-orm applications
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
use std::{
    collections::{BTreeMap, HashMap, HashSet},
    env, fs,
    path::PathBuf,
    process::Command,
    time::{SystemTime, UNIX_EPOCH},
};

use che_orm::{Database, Model, SchemaSet, SqliteDialect, rusqlite::OptionalExtension};
use clap::{Parser, Subcommand};
use time::{OffsetDateTime, format_description::well_known::Rfc3339};

use crate::auth::{User, hash_password};
use crate::{AppConfig, AppModule, AppState, InstalledApps, StartAppOptions, StartProjectOptions};

type ManageResult<T> = Result<T, Box<dyn std::error::Error>>;

#[derive(Debug, Parser)]
#[command(name = "manage", about = "Project management commands")]
struct Cli {
    #[command(subcommand)]
    command: CommandKind,
}

#[derive(Debug, Subcommand)]
enum CommandKind {
    Startproject {
        name: String,
        #[arg(long, default_value = ".")]
        out: PathBuf,
        #[arg(long, default_value = "")]
        che_rest_path: String,
        #[arg(long, default_value = "")]
        che_orm_path: String,
        #[arg(long, default_value_t = false)]
        with_auth: bool,
        #[arg(long, default_value_t = false)]
        force: bool,
    },
    Startapp {
        name: String,
        #[arg(long = "model")]
        models: Vec<String>,
        #[arg(long)]
        root: Option<PathBuf>,
        #[arg(long, default_value_t = false)]
        force: bool,
    },
    Schema,
    Makemigrations {
        name: Option<String>,
        #[arg(long, default_value = "migrations")]
        dir: PathBuf,
    },
    Migrate {
        #[command(subcommand)]
        action: Option<MigrateAction>,
        #[arg(long, default_value = "app.toml")]
        config: PathBuf,
        #[arg(long, default_value = "migrations")]
        dir: PathBuf,
    },
    Createsuperuser {
        #[arg(long)]
        username: String,
        #[arg(long)]
        password: String,
        #[arg(long, default_value = "app.toml")]
        config: PathBuf,
    },
    GenerateTs {
        #[arg(long, default_value = "frontend/client/src/generated")]
        out: PathBuf,
        #[arg(long, default_value = "app.toml")]
        config: PathBuf,
    },
    GenerateAdmin {
        #[arg(long, default_value = "frontend/admin")]
        out: PathBuf,
        #[arg(long, default_value = "app.toml")]
        config: PathBuf,
        #[arg(long, default_value_t = false)]
        force: bool,
    },
}

#[derive(Debug, Subcommand)]
enum MigrateAction {
    Apply,
    Status,
    Lint,
    Diff { name: String },
}

pub struct Management {
    apps: InstalledApps,
    project_root: PathBuf,
}

impl Management {
    pub fn new(apps: InstalledApps) -> Self {
        Self {
            apps,
            project_root: PathBuf::from("."),
        }
    }

    pub fn project_root(mut self, project_root: impl Into<PathBuf>) -> Self {
        self.project_root = project_root.into();
        self
    }

    pub async fn run(self) -> ManageResult<()> {
        self.run_from(Cli::parse()).await
    }

    async fn run_from(self, cli: Cli) -> ManageResult<()> {
        match cli.command {
            CommandKind::Startproject {
                name,
                out,
                che_rest_path,
                che_orm_path,
                with_auth,
                force,
            } => crate::startproject(StartProjectOptions {
                name,
                out,
                che_rest_path,
                che_orm_path,
                with_auth,
                force,
            })?,
            CommandKind::Startapp {
                name,
                models,
                root,
                force,
            } => crate::startapp(StartAppOptions {
                name,
                models,
                root: root.unwrap_or(self.project_root),
                force,
            })?,
            CommandKind::Schema => print_schema(&self.apps),
            CommandKind::Makemigrations { name, dir } => {
                let name = name.unwrap_or_else(|| {
                    let seconds = SystemTime::now()
                        .duration_since(UNIX_EPOCH)
                        .map_or(0, |duration| duration.as_secs());
                    format!("auto_{seconds}")
                });
                atlas_diff(&self.apps, &dir, &name)?;
            }
            CommandKind::Migrate {
                action,
                config,
                dir,
            } => {
                let config = AppConfig::from_file(config)?;
                let action = action.unwrap_or(MigrateAction::Apply);
                match action {
                    MigrateAction::Apply => apply_migrations(&config, dir).await?,
                    MigrateAction::Status => migration_status(&config, dir).await?,
                    MigrateAction::Lint => atlas_command(&[
                        "migrate",
                        "lint",
                        "--dir",
                        &file_url(&dir),
                        "--dev-url",
                        "sqlite://dev?mode=memory",
                    ])?,
                    MigrateAction::Diff { name } => atlas_diff(&self.apps, &dir, &name)?,
                }
            }
            CommandKind::Createsuperuser {
                username,
                password,
                config,
            } => create_superuser(username, password, config).await?,
            CommandKind::GenerateTs { out, config } => {
                AppConfig::from_file(config)?;
                let state = AppState::from_database(Database::connect_in_memory()?);
                let endpoints = self.apps.api_endpoints(state.clone());
                let signals = self.apps.api_signals(state);
                let files = crate::generate_ts::generate(
                    &out,
                    &endpoints,
                    &signals,
                    self.apps.find("auth").is_some(),
                )?;
                println!("generated {} files in {}", files.len(), out.display());
            }
            CommandKind::GenerateAdmin { out, config, force } => {
                AppConfig::from_file(config)?;
                let state = AppState::from_database(Database::connect_in_memory()?);
                let endpoints = self.apps.api_endpoints(state.clone());
                let signals = self.apps.api_signals(state);
                let generated = crate::generate_ts::generate(
                    &out.join("src/generated"),
                    &endpoints,
                    &signals,
                    self.apps.find("auth").is_some(),
                )?;
                let admin = crate::generate_admin::generate(&out, &endpoints, force)?;
                println!(
                    "generated {} files in {}",
                    generated.len() + admin.len(),
                    out.display()
                );
            }
        }
        Ok(())
    }
}

async fn create_superuser(username: String, password: String, config: PathBuf) -> ManageResult<()> {
    let state = AppState::from_config_file(config).await?;
    if state
        .database()
        .fetch_one(User::query().filter(User::USERNAME.eq(username.clone())))
        .await?
        .is_some()
    {
        return Err(format!("user `{username}` already exists").into());
    }

    let password_hash =
        hash_password(&password).map_err(|error| format!("could not hash password: {error}"))?;
    state
        .database()
        .create::<User>()
        .set(User::USERNAME, username.as_str())
        .set(User::PASSWORD_HASH, password_hash)
        .set(User::IS_ACTIVE, true)
        .set(User::IS_STAFF, true)
        .set(User::IS_ADMIN, true)
        .set(User::IS_SUPERUSER, true)
        .execute()
        .await?;
    println!("Superuser created.");
    Ok(())
}

fn schema(apps: &InstalledApps) -> SchemaSet {
    apps.iter()
        .map(AppModule::schema)
        .fold(SchemaSet::new(), SchemaSet::merge)
}

fn print_schema(apps: &InstalledApps) {
    print!("{}", schema(apps).to_sql::<SqliteDialect>());
}

async fn apply_migrations(config: &AppConfig, dir: PathBuf) -> ManageResult<()> {
    let migrations = load_atlas_migrations(&dir)?;
    let applied_count = run_sqlite_migrations(config, migrations).await?;

    if applied_count == 0 {
        println!("No pending migrations.");
    } else {
        println!("Applied {applied_count} migration(s).");
    }
    Ok(())
}

async fn run_sqlite_migrations(
    config: &AppConfig,
    migrations: Vec<refinery::Migration>,
) -> ManageResult<usize> {
    let database = Database::connect_with_pool_size(
        sqlite_path(&config.database.url),
        config.database.max_connections as usize,
    )?;
    let pool = database.pool().clone();
    let result = pool
        .get()
        .await?
        .interact(move |connection| apply_sqlite_migrations(connection, migrations))
        .await
        .map_err(|error| format!("database interaction error: {error}"))?;
    result.map_err(|error| error as Box<dyn std::error::Error>)
}

fn apply_sqlite_migrations(
    connection: &mut che_orm::rusqlite::Connection,
    migrations: Vec<refinery::Migration>,
) -> Result<usize, Box<dyn std::error::Error + Send + Sync>> {
    let applied = applied_migrations(connection)?;
    let filesystem = migrations
        .iter()
        .map(|migration| (migration.version(), migration.clone()))
        .collect::<HashMap<_, _>>();
    for migration in &applied {
        match filesystem.get(&migration.version()) {
            Some(expected)
                if expected.name() == migration.name()
                    && expected.checksum() == migration.checksum() => {}
            Some(expected) => {
                return Err(format!(
                    "divergent V{}__{} (filesystem: V{}__{})",
                    migration.version(),
                    migration.name(),
                    expected.version(),
                    expected.name()
                )
                .into());
            }
            None => {
                return Err(
                    format!("missing V{}__{}", migration.version(), migration.name()).into(),
                );
            }
        }
    }

    let applied_versions = applied
        .iter()
        .map(|migration| migration.version())
        .collect::<HashSet<_>>();
    let pending = migrations
        .into_iter()
        .filter(|migration| !applied_versions.contains(&migration.version()))
        .collect::<Vec<_>>();
    if pending.is_empty() {
        return Ok(0);
    }

    connection
        .execute_batch("PRAGMA foreign_keys = OFF; BEGIN IMMEDIATE;")
        .map_err(|error| Box::new(error) as Box<dyn std::error::Error + Send + Sync>)?;
    let result = (|| {
        connection.execute_batch(MIGRATION_HISTORY_SQL)?;
        for migration in &pending {
            connection.execute_batch(
                migration
                    .sql()
                    .ok_or("pending migration is missing SQL content")?,
            )?;
            connection.execute(
                "INSERT INTO refinery_schema_history (version, name, applied_on, checksum) VALUES (?1, ?2, ?3, ?4)",
                che_orm::rusqlite::params![
                    migration.version(),
                    migration.name(),
                    OffsetDateTime::now_utc().format(&Rfc3339)?,
                    migration.checksum().to_string(),
                ],
            )?;
        }
        assert_foreign_keys_valid(connection)?;
        Ok::<_, Box<dyn std::error::Error + Send + Sync>>(())
    })();

    match result {
        Ok(()) => {
            connection
                .execute_batch("COMMIT; PRAGMA foreign_keys = ON;")
                .map_err(|error| Box::new(error) as Box<dyn std::error::Error + Send + Sync>)?;
            Ok(pending.len())
        }
        Err(error) => {
            let _ = connection.execute_batch("ROLLBACK; PRAGMA foreign_keys = ON;");
            Err(error)
        }
    }
}

const MIGRATION_HISTORY_SQL: &str = "CREATE TABLE IF NOT EXISTS refinery_schema_history(\n             version int8 PRIMARY KEY,\n             name VARCHAR(255),\n             applied_on VARCHAR(255),\n             checksum VARCHAR(255));";

fn applied_migrations(
    connection: &che_orm::rusqlite::Connection,
) -> Result<Vec<refinery::Migration>, Box<dyn std::error::Error + Send + Sync>> {
    let has_history = connection
        .query_row(
            "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'refinery_schema_history'",
            [],
            |_| Ok(()),
        )
        .optional()?;
    if has_history.is_none() {
        return Ok(Vec::new());
    }
    let mut statement = connection.prepare(
        "SELECT version, name, applied_on, checksum FROM refinery_schema_history ORDER BY version ASC",
    )?;
    let mut rows = statement.query([])?;
    let mut migrations = Vec::new();
    while let Some(row) = rows.next()? {
        let applied_on: String = row.get(2)?;
        migrations.push(refinery::Migration::applied(
            row.get(0)?,
            row.get(1)?,
            OffsetDateTime::parse(&applied_on, &Rfc3339)?,
            row.get::<_, String>(3)?.parse()?,
        ));
    }
    Ok(migrations)
}

async fn migration_status(config: &AppConfig, dir: PathBuf) -> ManageResult<()> {
    let migrations = load_atlas_migrations(&dir)?;
    let filesystem = migrations
        .iter()
        .map(|migration| (migration.version(), migration.clone()))
        .collect::<BTreeMap<_, _>>();
    let applied = run_with_refinery(config, migrations, |runner, connection| {
        let has_history = connection
            .query_row(
                "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'refinery_schema_history'",
                [],
                |_| Ok(()),
            )
            .optional()?;
        if has_history.is_none() {
            return Ok(Vec::new());
        }
        runner.get_applied_migrations(connection).map_err(Into::into)
    })
    .await?;
    let applied_versions = applied
        .iter()
        .map(|migration| migration.version())
        .collect::<HashSet<_>>();
    let mut has_status_error = false;

    for migration in &applied {
        match filesystem.get(&migration.version()) {
            Some(expected)
                if expected.name() == migration.name()
                    && expected.checksum() == migration.checksum() =>
            {
                println!("applied V{}__{}", migration.version(), migration.name());
            }
            Some(expected) => {
                has_status_error = true;
                println!(
                    "divergent V{}__{} (filesystem: V{}__{})",
                    migration.version(),
                    migration.name(),
                    expected.version(),
                    expected.name()
                );
            }
            None => {
                has_status_error = true;
                println!("missing V{}__{}", migration.version(), migration.name());
            }
        }
    }

    for migration in filesystem.values() {
        if !applied_versions.contains(&migration.version()) {
            println!("pending V{}__{}", migration.version(), migration.name());
        }
    }

    if has_status_error {
        Err("migration history contains missing or divergent migrations".into())
    } else {
        Ok(())
    }
}

async fn run_with_refinery<T, F>(
    config: &AppConfig,
    migrations: Vec<refinery::Migration>,
    action: F,
) -> ManageResult<T>
where
    T: Send + 'static,
    F: FnOnce(
            refinery::Runner,
            &mut che_orm::rusqlite::Connection,
        ) -> Result<T, Box<dyn std::error::Error + Send + Sync>>
        + Send
        + 'static,
{
    let database = Database::connect_with_pool_size(
        sqlite_path(&config.database.url),
        config.database.max_connections as usize,
    )?;
    let pool = database.pool().clone();
    let result = pool
        .get()
        .await?
        .interact(move |connection| {
            let runner = refinery::Runner::new(&migrations)
                .set_abort_divergent(true)
                .set_abort_missing(true);
            action(runner, connection)
        })
        .await
        .map_err(|error| format!("database interaction error: {error}"))?;
    result.map_err(|error| error as Box<dyn std::error::Error>)
}

fn assert_foreign_keys_valid(
    connection: &che_orm::rusqlite::Connection,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let mut statement = connection
        .prepare("PRAGMA foreign_key_check;")
        .map_err(|error| Box::new(error) as Box<dyn std::error::Error + Send + Sync>)?;
    let mut rows = statement
        .query([])
        .map_err(|error| Box::new(error) as Box<dyn std::error::Error + Send + Sync>)?;
    if rows
        .next()
        .map_err(|error| Box::new(error) as Box<dyn std::error::Error + Send + Sync>)?
        .is_some()
    {
        return Err("migration left foreign key violations".into());
    }
    Ok(())
}

fn load_atlas_migrations(dir: &PathBuf) -> ManageResult<Vec<refinery::Migration>> {
    let mut migrations = Vec::new();
    let mut versions = HashSet::new();
    for entry in fs::read_dir(dir)? {
        let entry = entry?;
        let path = entry.path();
        if path.extension().and_then(|extension| extension.to_str()) != Some("sql") {
            continue;
        }
        let stem = path
            .file_stem()
            .and_then(|stem| stem.to_str())
            .ok_or_else(|| format!("invalid migration filename: {}", path.display()))?;
        let Some((version, name)) = stem.split_once('_') else {
            return Err(format!(
                "invalid Atlas migration filename `{}`; expected <version>_<name>.sql",
                path.display()
            )
            .into());
        };
        if version.len() != 14 || !version.chars().all(|ch| ch.is_ascii_digit()) {
            return Err(format!(
                "invalid Atlas migration version `{version}` in {}; expected 14 digits",
                path.display()
            )
            .into());
        }
        if name.is_empty()
            || !name
                .chars()
                .all(|ch| ch.is_ascii_alphanumeric() || ch == '_')
        {
            return Err(format!(
                "invalid Atlas migration name `{name}` in {}; use only ascii letters, digits, and underscores",
                path.display()
            )
            .into());
        }
        if !versions.insert(version.to_string()) {
            return Err(format!("duplicate migration version `{version}`").into());
        }

        let sql = fs::read_to_string(&path)?;
        let refinery_name = format!("V{version}__{name}");
        migrations.push(refinery::Migration::unapplied(&refinery_name, &sql)?);
    }
    migrations.sort();
    Ok(migrations)
}

fn sqlite_path(url: &str) -> String {
    url.strip_prefix("sqlite://")
        .and_then(|value| value.split('?').next())
        .filter(|value| !value.is_empty())
        .unwrap_or(url)
        .to_string()
}

fn atlas_diff(apps: &InstalledApps, dir: &PathBuf, name: &str) -> ManageResult<()> {
    let temp_path = env::temp_dir().join(format!("che-rest-schema-{}.sql", std::process::id()));
    fs::write(&temp_path, schema(apps).to_sql::<SqliteDialect>())?;
    let to = file_url(&temp_path);
    let result = atlas_command(&[
        "migrate",
        "diff",
        name,
        "--dir",
        &file_url(dir),
        "--to",
        &to,
        "--dev-url",
        "sqlite://dev?mode=memory",
    ]);
    let _ = fs::remove_file(temp_path);
    result
}

fn atlas_command(args: &[&str]) -> ManageResult<()> {
    let binary = env::var_os("ATLAS_BIN").unwrap_or_else(|| "atlas".into());
    let status = Command::new(binary).args(args).status()?;
    if status.success() {
        Ok(())
    } else {
        Err(format!("atlas exited with status {status}").into())
    }
}

fn file_url(path: &PathBuf) -> String {
    let path = if path.is_absolute() {
        path.clone()
    } else {
        env::current_dir().unwrap_or_default().join(path)
    };
    format!("file://{}", path.display())
}

#[cfg(test)]
mod tests {
    use std::{
        fs,
        path::PathBuf,
        time::{SystemTime, UNIX_EPOCH},
    };

    use che_orm::{Database, Model, rusqlite::OptionalExtension};
    use clap::Parser;

    use super::{Cli, Management, apply_migrations, migration_status};
    use crate::InstalledApps;
    use crate::auth::{User, verify_password};
    use crate::{AppConfig, DatabaseConfig};

    fn temp_path(name: &str, extension: &str) -> PathBuf {
        let suffix = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        std::env::temp_dir().join(format!("che_rest_{name}_{suffix}.{extension}"))
    }

    fn sqlite_config(database_path: &std::path::Path) -> AppConfig {
        AppConfig {
            database: DatabaseConfig {
                url: format!("sqlite://{}?mode=rwc", database_path.display()),
                max_connections: 1,
            },
            ..AppConfig::default()
        }
    }

    #[test]
    fn parses_project_generation_commands() {
        Cli::try_parse_from([
            "manage",
            "startproject",
            "todo_api",
            "--out",
            "..",
            "--with-auth",
        ])
        .unwrap();
        Cli::try_parse_from([
            "manage", "startapp", "tasks", "--model", "Task", "--model", "Comment",
        ])
        .unwrap();
    }

    #[tokio::test]
    async fn creates_superuser_with_hashed_password() {
        let database_path = temp_path("superuser", "sqlite");
        let config_path = temp_path("superuser", "toml");
        fs::write(
            &config_path,
            format!(
                "[database]\nurl = \"sqlite://{}?mode=rwc\"\n",
                database_path.display()
            ),
        )
        .unwrap();
        Database::connect(database_path.to_string_lossy())
            .unwrap()
            .create_table::<User>()
            .await
            .unwrap();

        let cli = Cli::try_parse_from([
            "manage",
            "createsuperuser",
            "--username",
            "admin",
            "--password",
            "secret",
            "--config",
            config_path.to_str().unwrap(),
        ])
        .unwrap();
        Management::new(InstalledApps::new())
            .run_from(cli)
            .await
            .unwrap();

        let database = Database::connect(database_path.to_string_lossy()).unwrap();
        let user = database
            .fetch_one(User::query().filter(User::USERNAME.eq("admin")))
            .await
            .unwrap()
            .unwrap();
        assert!(verify_password("secret", &user.password_hash));
        assert!(user.is_active && user.is_staff && user.is_admin && user.is_superuser);

        let _ = fs::remove_file(database_path);
        let _ = fs::remove_file(config_path);
    }

    #[tokio::test]
    async fn generate_admin_cli_creates_project_files() {
        let suffix = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let output = std::env::temp_dir().join(format!("che_rest_admin_{suffix}"));
        let config = output.join("app.toml");
        fs::create_dir_all(&output).unwrap();
        fs::write(&config, "[database]\nurl = 'sqlite://unused.sqlite'\n").unwrap();
        let cli = Cli::try_parse_from([
            "manage",
            "generate-admin",
            "--out",
            output.to_str().unwrap(),
            "--config",
            config.to_str().unwrap(),
        ])
        .unwrap();
        Management::new(InstalledApps::new())
            .run_from(cli)
            .await
            .unwrap();
        assert!(output.join("package.json").exists());
        assert!(output.join("src/admin/generated/adminSchema.ts").exists());
        assert!(output.join("src/router.ts").exists());
        let _ = fs::remove_dir_all(output);
    }

    #[tokio::test]
    async fn migrate_apply_runs_refinery_without_atlas() {
        let migrations = temp_path("migrations", "dir");
        fs::create_dir_all(&migrations).unwrap();
        fs::write(
            migrations.join("20260817000000_initial.sql"),
            "CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT NOT NULL);",
        )
        .unwrap();
        fs::write(
            migrations.join("20260817000001_add_rows.sql"),
            "INSERT INTO items (name) VALUES ('one');",
        )
        .unwrap();
        let database_path = temp_path("migrate_apply", "sqlite");
        let config = sqlite_config(&database_path);

        apply_migrations(&config, migrations.clone()).await.unwrap();
        apply_migrations(&config, migrations.clone()).await.unwrap();

        let connection = che_orm::rusqlite::Connection::open(&database_path).unwrap();
        let count: i64 = connection
            .query_row("SELECT COUNT(*) FROM items", [], |row| row.get(0))
            .unwrap();
        assert_eq!(count, 1);

        let history_count: i64 = connection
            .query_row("SELECT COUNT(*) FROM refinery_schema_history", [], |row| {
                row.get(0)
            })
            .unwrap();
        assert_eq!(history_count, 2);

        let _ = fs::remove_dir_all(migrations);
        let _ = fs::remove_file(database_path);
    }

    #[tokio::test]
    async fn migrate_apply_rejects_changed_migration() {
        let migrations = temp_path("migrations_changed", "dir");
        fs::create_dir_all(&migrations).unwrap();
        let migration = migrations.join("20260817000000_initial.sql");
        fs::write(&migration, "CREATE TABLE items (id INTEGER PRIMARY KEY);").unwrap();
        let database_path = temp_path("migrate_changed", "sqlite");
        let config = sqlite_config(&database_path);

        apply_migrations(&config, migrations.clone()).await.unwrap();
        fs::write(&migration, "CREATE TABLE changed (id INTEGER PRIMARY KEY);").unwrap();

        let error = apply_migrations(&config, migrations.clone())
            .await
            .unwrap_err()
            .to_string();
        assert!(!error.is_empty());

        let _ = fs::remove_dir_all(migrations);
        let _ = fs::remove_file(database_path);
    }

    #[tokio::test]
    async fn migrate_status_reports_pending_on_fresh_database() {
        let migrations = temp_path("migrations_status", "dir");
        fs::create_dir_all(&migrations).unwrap();
        fs::write(
            migrations.join("20260817000000_initial.sql"),
            "CREATE TABLE items (id INTEGER PRIMARY KEY);",
        )
        .unwrap();
        let database_path = temp_path("migrate_status", "sqlite");
        let config = sqlite_config(&database_path);

        migration_status(&config, migrations.clone()).await.unwrap();

        let _ = fs::remove_dir_all(migrations);
        let _ = fs::remove_file(database_path);
    }

    #[tokio::test]
    async fn migrate_apply_rejects_foreign_key_violations() {
        let migrations = temp_path("migrations_fk", "dir");
        fs::create_dir_all(&migrations).unwrap();
        fs::write(
            migrations.join("20260817000000_initial.sql"),
            "CREATE TABLE parents (id INTEGER PRIMARY KEY);\nCREATE TABLE children (id INTEGER PRIMARY KEY, parent_id INTEGER NOT NULL REFERENCES parents(id));\nINSERT INTO children (id, parent_id) VALUES (1, 999);",
        )
        .unwrap();
        let database_path = temp_path("migrate_fk", "sqlite");
        let config = sqlite_config(&database_path);

        let error = apply_migrations(&config, migrations.clone())
            .await
            .unwrap_err()
            .to_string();
        assert!(error.contains("foreign key violations"));

        let connection = che_orm::rusqlite::Connection::open(&database_path).unwrap();
        let children_table: Option<String> = connection
            .query_row(
                "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'children'",
                [],
                |row| row.get(0),
            )
            .optional()
            .unwrap();
        assert!(children_table.is_none());
        let history_table: Option<String> = connection
            .query_row(
                "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'refinery_schema_history'",
                [],
                |row| row.get(0),
            )
            .optional()
            .unwrap();
        assert!(history_table.is_none());

        let _ = fs::remove_dir_all(migrations);
        let _ = fs::remove_file(database_path);
    }

    #[tokio::test]
    async fn migrate_apply_runs_checked_in_atlas_migrations() {
        let database_path = temp_path("cli_fullstack_migrate", "sqlite");
        let config = sqlite_config(&database_path);
        let migrations =
            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("examples/cli_fullstack/migrations");

        apply_migrations(&config, migrations).await.unwrap();

        let connection = che_orm::rusqlite::Connection::open(&database_path).unwrap();
        let task_table: String = connection
            .query_row(
                "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'tasks_task'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(task_table, "tasks_task");
        let history_count: i64 = connection
            .query_row("SELECT COUNT(*) FROM refinery_schema_history", [], |row| {
                row.get(0)
            })
            .unwrap();
        assert_eq!(history_count, 3);

        let _ = fs::remove_file(database_path);
    }
}