dbschema 0.1.3

Define database schema's as HCL files, and generate idempotent SQL migrations
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
use anyhow::{anyhow, Context, Result};
use clap::{Parser, Subcommand};
use dbschema::frontend::env::EnvVars;
use dbschema::{
    apply_filters,
    config::{self, Config as DbschemaConfig, ResourceKind, TargetConfig},
    load_config, validate, Loader, OutputSpec,
};
use log::{error, info};
use postgres::{Client, NoTls};
use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;

#[derive(Parser)]
#[command(name = "dbschema", version, disable_version_flag = true)]
#[command(about = "Define database schema's as HCL files, and generate idempotent SQL migrations.", long_about = None)]
struct Cli {
    /// Print the version and exit
    #[arg(long = "version", short = 'v', action = clap::ArgAction::Version)]
    version: (),

    /// Root HCL file (default: main.hcl)
    #[arg(long, default_value = "main.hcl")]
    input: PathBuf,

    /// Set a variable: --var key=value (repeatable)
    #[arg(long, value_parser = parse_key_val::<String, String>)]
    var: Vec<(String, String)>,

    /// Load variables from a file (HCL or .tfvars-like). Can repeat.
    #[arg(long)]
    var_file: Vec<PathBuf>,

    /// Backend to use: postgres|prisma|json (ignored if using config file)
    #[arg(long, default_value = "postgres")]
    backend: String,

    /// Include only these resources (repeatable). If none, includes all.
    #[arg(long = "include", value_enum)]
    include_resources: Vec<ResourceKind>,

    /// Exclude these resources (repeatable)
    #[arg(long = "exclude", value_enum)]
    exclude_resources: Vec<ResourceKind>,

    /// Use dbschema.toml configuration file
    #[arg(long)]
    config: bool,

    /// Target name(s) to run (when using config file). Can specify multiple.
    #[arg(long)]
    target: Vec<String>,

    /// Enable strict mode (errors on undefined enums)
    #[arg(long)]
    strict: bool,

    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// Validate HCL and print a summary
    Validate {},
    /// Lint schema and report potential issues
    Lint {
        /// Lint rules to allow (suppress)
        #[arg(long = "allow")]
        allow: Vec<String>,
        /// Lint rules to warn on
        #[arg(long = "warn")]
        warn: Vec<String>,
        /// Lint rules to treat as errors
        #[arg(long = "error")]
        error: Vec<String>,
    },
    /// Format HCL files in place
    Fmt {
        /// Files or directories to format (defaults to current directory)
        #[arg(value_name = "PATH", default_value = ".")]
        paths: Vec<PathBuf>,
    },
    /// Create a SQL migration file from the HCL
    CreateMigration {
        /// Output directory for migration files; if omitted, prints to stdout
        #[arg(long)]
        out_dir: Option<PathBuf>,
        /// Optional migration name (used in filename when writing to a dir)
        #[arg(long)]
        name: Option<String>,
    },
    /// Run tests defined in HCL against a database
    Test {
        /// Database connection string (falls back to env DATABASE_URL)
        #[arg(long)]
        dsn: Option<String>,
        /// Test backend: postgres
        #[arg(long, default_value = "postgres")]
        backend: String,
        /// Names of tests to run (repeatable). If omitted, runs all.
        #[arg(long = "name")]
        names: Vec<String>,
        /// Generate and apply migrations before running tests (postgres only)
        #[arg(long)]
        apply: bool,
        /// Create a temporary database with this name, run tests against it, then drop it (postgres only)
        #[arg(long = "create-db")]
        create_db: Option<String>,
        /// Keep the database created via --create-db after tests finish (postgres only)
        #[arg(long = "keep-db")]
        keep_db: bool,
        /// Verbose: print SQL being executed (apply + test phases)
        #[arg(long)]
        verbose: bool,
    },
}

fn main() -> Result<()> {
    env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();

    let cli = Cli::parse();

    if cli.config && cli.command.is_none() {
        let dbschema_config = config::load_config()
            .with_context(|| "failed to load dbschema.toml")?
            .ok_or_else(|| anyhow!("dbschema.toml not found"))?;

        let targets_to_run = if !cli.target.is_empty() {
            // Multiple targets specified
            cli.target
                .iter()
                .map(|name| {
                    dbschema_config
                        .targets
                        .iter()
                        .find(|t| t.name == *name)
                        .ok_or_else(|| anyhow!("target '{}' not found in dbschema.toml", name))
                        .cloned()
                })
                .collect::<Result<Vec<_>>>()?
        } else {
            // No targets specified, run all
            dbschema_config.targets.clone()
        };

        for target in targets_to_run {
            run_target(&dbschema_config, &target, cli.strict)?;
        }
    } else if let Some(command) = cli.command {
        match command {
            Commands::Validate {} => {
                let mut vars: HashMap<String, hcl::Value> = HashMap::new();
                for vf in &cli.var_file {
                    let loaded = load_var_file(vf)
                        .with_context(|| format!("loading var file {}", vf.display()))?;
                    vars.extend(loaded);
                }
                for (k, v) in cli.var.iter() {
                    vars.insert(k.clone(), hcl::Value::String(v.clone()));
                }

                let fs_loader = FsLoader;
                let env = EnvVars {
                    vars,
                    ..EnvVars::default()
                };
                let config = load_config(&cli.input, &fs_loader, env.clone())
                    .with_context(|| format!("loading root HCL {}", cli.input.display()))?;

                let (include_set, exclude_set) =
                    cli_filter_sets(&cli.backend, &cli.include_resources, &cli.exclude_resources);
                let filtered = apply_filters(&config, &include_set, &exclude_set);

                dbschema::validate(&filtered, cli.strict)?;
                info!(
                    "Valid: {} schema(s), {} enum(s), {} table(s), {} view(s), {} materialized view(s), {} function(s), {} procedure(s), {} trigger(s)",
                    filtered.schemas.len(),
                    filtered.enums.len(),
                    filtered.tables.len(),
                    filtered.views.len(),
                    filtered.materialized.len(),
                    filtered.functions.len(),
                    filtered.procedures.len(),
                    filtered.triggers.len()
                );
                print_outputs(&filtered.outputs);
            }
            Commands::Lint { allow, warn, error } => {
                let mut vars: HashMap<String, hcl::Value> = HashMap::new();
                for vf in &cli.var_file {
                    let loaded = load_var_file(vf)
                        .with_context(|| format!("loading var file {}", vf.display()))?;
                    vars.extend(loaded);
                }
                for (k, v) in cli.var.iter() {
                    vars.insert(k.clone(), hcl::Value::String(v.clone()));
                }

                let fs_loader = FsLoader;
                let env = EnvVars {
                    vars,
                    ..EnvVars::default()
                };
                let config = load_config(&cli.input, &fs_loader, env.clone())
                    .with_context(|| format!("loading root HCL {}", cli.input.display()))?;

                let (include_set, exclude_set) =
                    cli_filter_sets(&cli.backend, &cli.include_resources, &cli.exclude_resources);
                let filtered = apply_filters(&config, &include_set, &exclude_set);

                let mut lint_settings = config::load_config()?
                    .map(|c| c.settings.lint)
                    .unwrap_or_default();
                for rule in allow {
                    lint_settings
                        .severity
                        .insert(rule, dbschema::lint::LintSeverity::Allow);
                }
                for rule in warn {
                    lint_settings
                        .severity
                        .insert(rule, dbschema::lint::LintSeverity::Warn);
                }
                for rule in error {
                    lint_settings
                        .severity
                        .insert(rule, dbschema::lint::LintSeverity::Error);
                }
                let lints = dbschema::lint::run(&filtered, &lint_settings);
                if lints.is_empty() {
                    info!("No lint issues found");
                } else {
                    let mut has_error = false;
                    for l in &lints {
                        println!("[{:?}] [{}] {}", l.severity, l.check, l.message);
                        if l.severity == dbschema::lint::LintSeverity::Error {
                            has_error = true;
                        }
                    }
                    if has_error {
                        std::process::exit(1);
                    }
                }
            }
            Commands::Fmt { paths } => {
                for p in paths {
                    format_path(&p)?;
                }
            }
            Commands::CreateMigration { out_dir, name } => {
                let mut vars: HashMap<String, hcl::Value> = HashMap::new();
                for vf in &cli.var_file {
                    let loaded = load_var_file(vf)
                        .with_context(|| format!("loading var file {}", vf.display()))?;
                    vars.extend(loaded);
                }
                for (k, v) in cli.var.iter() {
                    vars.insert(k.clone(), hcl::Value::String(v.clone()));
                }

                let fs_loader = FsLoader;
                let env = EnvVars {
                    vars,
                    ..EnvVars::default()
                };
                let config = load_config(&cli.input, &fs_loader, env.clone())
                    .with_context(|| format!("loading root HCL {}", cli.input.display()))?;

                let (include_set, exclude_set) =
                    cli_filter_sets(&cli.backend, &cli.include_resources, &cli.exclude_resources);
                let filtered = apply_filters(&config, &include_set, &exclude_set);

                dbschema::validate(&filtered, cli.strict)?;
                let artifact =
                    dbschema::generate_with_backend(&cli.backend, &filtered, cli.strict)?;
                if let Some(dir) = out_dir {
                    let name = name.unwrap_or_else(|| "triggers".to_string());
                    let ext = dbschema::backends::get_backend(&cli.backend)
                        .as_ref()
                        .map(|b| b.file_extension())
                        .unwrap_or("txt");
                    let path = write_artifact(&dir, &name, ext, &artifact)?;
                    info!("Wrote migration: {}", path.display());
                } else {
                    print!("{}", artifact);
                }
                print_outputs(&filtered.outputs);
            }
            Commands::Test {
                dsn,
                names,
                backend,
                apply,
                create_db,
                keep_db,
                verbose,
            } => {
                let mut backend = backend;
                let (dsn, config) = if cli.config {
                    let dbschema_config = config::load_config()
                        .with_context(|| "failed to load dbschema.toml")?
                        .ok_or_else(|| anyhow!("dbschema.toml not found"))?;
                    for (key, value) in &dbschema_config.settings.env {
                        unsafe {
                            std::env::set_var(key, value);
                        }
                    }
                    let mut vars: HashMap<String, hcl::Value> = HashMap::new();
                    for vf in &dbschema_config.settings.var_files {
                        vars.extend(load_var_file(&PathBuf::from(vf))?);
                    }
                    let input_path = dbschema_config
                        .settings
                        .input
                        .as_deref()
                        .unwrap_or("main.hcl");
                    let fs_loader = FsLoader;
                    let env = EnvVars {
                        vars,
                        ..EnvVars::default()
                    };
                    let cfg = load_config(&PathBuf::from(input_path), &fs_loader, env.clone())
                        .with_context(|| format!("loading root HCL from {}", input_path))?;
                    let dsn = dsn
                        .or_else(|| dbschema_config.settings.test_dsn.clone())
                        .or_else(|| std::env::var("DATABASE_URL").ok());
                    if backend.eq_ignore_ascii_case("postgres") {
                        if let Some(be) = &dbschema_config.settings.test_backend {
                            backend = be.clone();
                        }
                    }
                    (dsn, cfg)
                } else {
                    let mut vars: HashMap<String, hcl::Value> = HashMap::new();
                    for vf in &cli.var_file {
                        let loaded = load_var_file(vf)
                            .with_context(|| format!("loading var file {}", vf.display()))?;
                        vars.extend(loaded);
                    }
                    for (k, v) in cli.var.iter() {
                        vars.insert(k.clone(), hcl::Value::String(v.clone()));
                    }
                    let fs_loader = FsLoader;
                    let env = EnvVars {
                        vars,
                        ..EnvVars::default()
                    };
                    let cfg = load_config(&cli.input, &fs_loader, env.clone())
                        .with_context(|| format!("loading root HCL {}", cli.input.display()))?;
                    (dsn, cfg)
                };
                let backend_name = backend;
                let backend_key = backend_name.to_lowercase();
                let backend_is_postgres = backend_key == "postgres";
                let registry = dbschema::test_runner::get_default_test_backend_registry();
                let runner = match registry.get(&backend_key) {
                    Some(runner) => runner,
                    None => {
                        let mut available = registry.list_backends();
                        available.sort_unstable();
                        let available = if available.is_empty() {
                            "none registered".to_string()
                        } else {
                            available.join(", ")
                        };
                        return Err(anyhow!(
                            "unknown test backend '{}'; available backends: {}",
                            backend_name,
                            available
                        ));
                    }
                };
                let mut dsn = dsn
                    .or_else(|| std::env::var("DATABASE_URL").ok())
                    .ok_or_else(|| anyhow!("missing DSN: pass --dsn or set DATABASE_URL"))?;
                let mut temp_database: Option<(String, String)> = None;

                // Optionally create and later drop a temporary database for Postgres
                if let Some(dbname) = create_db.clone() {
                    if !runner.supports_temporary_database() {
                        return Err(anyhow!(
                            "--create-db is not supported by the '{}' test backend",
                            backend_name
                        ));
                    }
                    let new_dsn = runner.setup_temporary_database(&dsn, &dbname, verbose)?;
                    temp_database = Some((new_dsn.clone(), dbname));
                    dsn = new_dsn;
                }
                // Optionally generate and apply migrations for Postgres
                if apply {
                    if backend_is_postgres {
                        dbschema::validate(&config, cli.strict)?;
                        let artifact =
                            dbschema::generate_with_backend("postgres", &config, cli.strict)?;
                        if verbose {
                            info!("-- applying migration --\n{}", artifact);
                        }
                        let mut client = Client::connect(&dsn, NoTls)
                            .with_context(|| format!("connecting to database: {}", &dsn))?;
                        client
                            .batch_execute(&artifact)
                            .with_context(|| "applying generated migration to database")?;
                    } else {
                        return Err(anyhow!(
                            "--apply is only supported for the 'postgres' test backend (requested '{}')",
                            backend_name
                        ));
                    }
                }

                dbschema::test_runner::set_verbose(verbose);
                let only: Option<std::collections::HashSet<String>> = if names.is_empty() {
                    None
                } else {
                    Some(names.into_iter().collect())
                };
                let summary = runner.run(&config, &dsn, only.as_ref())?;
                for r in summary.results {
                    if r.passed {
                        info!("ok - {}", r.name);
                    } else {
                        error!("FAIL - {}: {}", r.name, r.message);
                    }
                }
                if summary.failed > 0 {
                    error!(
                        "Summary: {} passed, {} failed ({} total)",
                        summary.passed, summary.failed, summary.total
                    );
                    std::process::exit(1);
                } else {
                    info!(
                        "Summary: {} passed, {} failed ({} total)",
                        summary.passed, summary.failed, summary.total
                    );
                }
                print_outputs(&config.outputs);

                // Optionally drop the created database after tests complete
                if !keep_db {
                    if let Some((temp_dsn, dbname)) = temp_database {
                        runner.cleanup_temporary_database(&temp_dsn, &dbname, verbose)?;
                    }
                }
            }
        }
    }

    Ok(())
}

fn format_path(path: &Path) -> Result<()> {
    if path.is_file() {
        format_file(path)?;
    } else if path.is_dir() {
        for entry in WalkDir::new(path) {
            let entry = entry?;
            if entry.file_type().is_file()
                && entry
                    .path()
                    .extension()
                    .and_then(|s| s.to_str())
                    .map(|s| s.eq_ignore_ascii_case("hcl"))
                    .unwrap_or(false)
            {
                format_file(entry.path())?;
            }
        }
    }
    Ok(())
}

fn format_file(path: &Path) -> Result<()> {
    let content =
        fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
    let body = hcl::parse(&content).with_context(|| format!("parsing {}", path.display()))?;
    let formatted = hcl::format::to_string(&body)?;
    fs::write(path, formatted).with_context(|| format!("writing {}", path.display()))?;
    Ok(())
}

fn run_target(dbschema_config: &DbschemaConfig, target: &TargetConfig, strict: bool) -> Result<()> {
    info!("Running target: {}", target.name);

    for (key, value) in &dbschema_config.settings.env {
        unsafe {
            std::env::set_var(key, value);
        }
    }

    let input_path = target
        .input
        .as_deref()
        .or(dbschema_config.settings.input.as_deref())
        .unwrap_or("main.hcl");

    let mut vars = HashMap::new();
    for var_file in &dbschema_config.settings.var_files {
        vars.extend(load_var_file(&PathBuf::from(var_file))?);
    }
    for var_file in &target.var_files {
        vars.extend(load_var_file(&PathBuf::from(var_file))?);
    }
    for (key, value) in &target.vars {
        vars.insert(key.clone(), toml_to_hcl(value)?);
    }

    let fs_loader = FsLoader;
    let env = EnvVars {
        vars,
        ..EnvVars::default()
    };
    let config = load_config(&PathBuf::from(input_path), &fs_loader, env.clone())
        .with_context(|| format!("loading root HCL from {}", input_path))?;

    let include_set = target.get_include_set()?;
    let exclude_set = target.get_exclude_set()?;

    let filtered = apply_filters(&config, &include_set, &exclude_set);

    validate(&filtered, strict)?;
    let artifact = dbschema::generate_with_backend(&target.backend, &filtered, strict)?;

    if let Some(output_path) = &target.output {
        let path = Path::new(output_path);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::write(path, artifact)?;
        info!("Wrote output to: {}", output_path);
    } else {
        print!("{}", artifact);
    }

    print_outputs(&filtered.outputs);

    Ok(())
}

fn toml_to_hcl(value: &toml::Value) -> Result<hcl::Value> {
    match value {
        toml::Value::String(s) => Ok(hcl::Value::String(s.clone())),
        toml::Value::Integer(i) => Ok(hcl::Value::Number(hcl::Number::from(*i))),
        toml::Value::Float(f) => Ok(hcl::Value::Number(
            hcl::Number::from_f64(*f).ok_or_else(|| anyhow!("invalid float"))?,
        )),
        toml::Value::Boolean(b) => Ok(hcl::Value::Bool(*b)),
        toml::Value::Array(arr) => {
            let mut values = Vec::new();
            for v in arr {
                values.push(toml_to_hcl(v)?);
            }
            Ok(hcl::Value::Array(values))
        }
        toml::Value::Table(map) => {
            let mut hcl_map = hcl::Map::new();
            for (k, v) in map {
                hcl_map.insert(k.clone(), toml_to_hcl(v)?);
            }
            Ok(hcl::Value::Object(hcl_map))
        }
        _ => Err(anyhow!("Unsupported toml value type")),
    }
}

fn write_artifact(out_dir: &Path, name: &str, ext: &str, contents: &str) -> Result<PathBuf> {
    fs::create_dir_all(out_dir)?;
    let ts = chrono::Local::now().format("%Y%m%d%H%M%S");
    let file = format!("{}_{}.{}", ts, sanitize_filename(name), ext);
    let path = out_dir.join(file);
    fs::write(&path, contents)?;
    Ok(path)
}

fn print_outputs(outputs: &[OutputSpec]) {
    for o in outputs {
        let val = match &o.value {
            hcl::Value::String(s) => s.clone(),
            hcl::Value::Number(n) => n.to_string(),
            hcl::Value::Bool(b) => b.to_string(),
            _ => serde_json::to_string(&o.value).unwrap_or_default(),
        };
        println!("{} = {}", o.name, val);
    }
}

fn sanitize_filename(s: &str) -> String {
    s.chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
                c
            } else {
                '-'
            }
        })
        .collect()
}

fn load_var_file(path: &Path) -> Result<HashMap<String, hcl::Value>> {
    let content = fs::read_to_string(path)?;
    // Try HCL body, collect top-level attributes as strings
    let body: hcl::Body = hcl::from_str(&content)
        .or_else(|_| {
            // Fallback: simple key = "value" lines parsing
            let mut structs: Vec<hcl::Structure> = Vec::new();
            for line in content.lines() {
                let line = line.trim();
                if line.is_empty() || line.starts_with('#') || line.starts_with("//") {
                    continue;
                }
                if let Some((k, v)) = line.split_once('=') {
                    let key = k.trim();
                    let val = v.trim().trim_matches('"').to_string();
                    structs.push(hcl::Structure::Attribute(hcl::Attribute::new(key, val)));
                }
            }
            Ok::<_, hcl::Error>(hcl::Body::from(structs))
        })
        .map_err(|e| anyhow!("failed to parse var file as HCL: {}", e))?;

    let mut out = HashMap::new();
    for attr in body.attributes() {
        let name = attr.key();
        let v = dbschema::frontend::expr_to_value(attr.expr(), &EnvVars::default())
            .with_context(|| format!("evaluating var '{}': unsupported expression", name))?;
        out.insert(name.to_string(), v);
    }
    Ok(out)
}

fn parse_key_val<K, V>(s: &str) -> Result<(K, V)>
where
    K: std::str::FromStr,
    V: std::str::FromStr,
    <K as std::str::FromStr>::Err: std::fmt::Display,
    <V as std::str::FromStr>::Err: std::fmt::Display,
{
    let pos = s.find('=').ok_or_else(|| anyhow!("expected key=value"))?;
    let key = s[..pos]
        .parse()
        .map_err(|e| anyhow!("failed to parse key: {}", e))?;
    let value = s[pos + 1..]
        .parse()
        .map_err(|e| anyhow!("failed to parse value: {}", e))?;
    Ok((key, value))
}

struct FsLoader;
impl Loader for FsLoader {
    fn load(&self, path: &Path) -> Result<String> {
        Ok(fs::read_to_string(path)?)
    }
}

fn cli_filter_sets(
    backend: &str,
    include: &[ResourceKind],
    exclude: &[ResourceKind],
) -> (HashSet<ResourceKind>, HashSet<ResourceKind>) {
    use ResourceKind as R;

    let mut include_set: HashSet<R> = if include.is_empty() {
        ResourceKind::default_include_set()
    } else {
        include.iter().copied().collect()
    };

    let exclude_set: HashSet<R> = exclude.iter().copied().collect();

    for r in &exclude_set {
        include_set.remove(r);
    }

    // Prisma backend supports tables and enums only; enforce that regardless of flags unless explicitly excluded
    if backend.eq_ignore_ascii_case("prisma") {
        include_set = [R::Enums, R::Tables].into_iter().collect();
        for r in &exclude_set {
            include_set.remove(r);
        }
    }

    (include_set, exclude_set)
}

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

    #[test]
    fn test_run_target() -> Result<()> {
        let dir = tempdir()?;
        let dbschema_toml_path = dir.path().join("dbschema.toml");
        let main_hcl_path = dir.path().join("main.hcl");
        let another_hcl_path = dir.path().join("another.hcl");
        let var_file_path = dir.path().join("vars.hcl");

        let dbschema_toml = r#"
[settings]
input = "main.hcl"
var_files = ["vars.hcl"]

[[targets]]
name = "json_all"
backend = "json"
output = "all.json"

[[targets]]
name = "json_tables"
backend = "json"
output = "tables.json"
include = ["tables"]

[[targets]]
name = "another_input"
backend = "json"
input = "another.hcl"
output = "another.json"
include = ["functions"]

[[targets]]
name = "with_vars"
backend = "json"
output = "with_vars.json"
vars = { table_name = "my_users_table" }
include = ["tables"]

[[targets]]
name = "with_alt_name"
backend = "json"
output = "with_alt_name.json"
include = ["tables"]
"#;
        fs::write(&dbschema_toml_path, dbschema_toml)?;

        let main_hcl = r#"
variable "table_name" { default = "users" }
table "users" {
    table_name = var.table_name
}
function "my_func" {
    returns = "trigger"
    language = "plpgsql"
    body = "BEGIN RETURN NEW; END;"
}
"#;
        fs::write(&main_hcl_path, main_hcl)?;

        let another_hcl = r#"
function "another_func" {
    returns = "trigger"
    language = "plpgsql"
    body = "BEGIN RETURN NEW; END;"
}
"#;
        fs::write(&another_hcl_path, another_hcl)?;

        let var_file = r#"
table_name = "from_file"
"#;
        fs::write(&var_file_path, var_file)?;

        let dbschema_config = config::load_config_from_path(&dbschema_toml_path)
            .with_context(|| "failed to load dbschema.toml")?
            .ok_or_else(|| anyhow!("dbschema.toml not found"))?;

        std::env::set_current_dir(dir.path())?;

        // Test target "json_all"
        let target_all = dbschema_config
            .targets
            .iter()
            .find(|t| t.name == "json_all")
            .unwrap();
        run_target(&dbschema_config, target_all, false)?;
        let output_all = fs::read_to_string("all.json")?;
        assert!(output_all.contains("users"));
        assert!(output_all.contains("my_func"));

        // Test target "json_tables"
        let target_tables = dbschema_config
            .targets
            .iter()
            .find(|t| t.name == "json_tables")
            .unwrap();
        run_target(&dbschema_config, target_tables, false)?;
        let output_tables = fs::read_to_string("tables.json")?;
        assert!(output_tables.contains("users"));
        assert!(!output_tables.contains("my_func"));

        // Test target "another_input"
        let target_another = dbschema_config
            .targets
            .iter()
            .find(|t| t.name == "another_input")
            .unwrap();
        run_target(&dbschema_config, target_another, false)?;
        let output_another = fs::read_to_string("another.json")?;
        assert!(output_another.contains("another_func"));
        assert!(!output_another.contains("my_func"));

        // Test target "with_vars"
        let target_vars = dbschema_config
            .targets
            .iter()
            .find(|t| t.name == "with_vars")
            .unwrap();
        run_target(&dbschema_config, target_vars, false)?;
        let output_vars = fs::read_to_string("with_vars.json")?;
        // The variable from the target should be used
        assert!(output_vars.contains("my_users_table"));

        // Test target "with_alt_name"
        let target_alt_name = dbschema_config
            .targets
            .iter()
            .find(|t| t.name == "with_alt_name")
            .unwrap();
        run_target(&dbschema_config, target_alt_name, false)?;
        let output_alt_name = fs::read_to_string("with_alt_name.json")?;
        assert!(output_alt_name.contains("from_file"));

        dir.close()?;
        Ok(())
    }
}