fraiseql-cli 2.17.1

CLI tools for FraiseQL v2 - Schema compilation and development utilities
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
//! `fraiseql migrate` - Database migration wrapper
//!
//! Wraps confiture for database migrations: every verb is one `confiture migrate <verb> …`
//! invocation, assembled by `ConfitureCommand` from the option table its doc comment
//! holds. Confiture must be installed and on `PATH`; `run` says so and stops when it is not.
//!
//! The call shape follows confiture's CLI reference, `docs/reference/cli.md` in
//! <https://github.com/fraiseql/confiture> at tag `v1.37.0`, section "`confiture migrate`".
//! That is the confiture the `integration (postgres)` leg installs from
//! `tools/confiture-requirements.txt` and runs `tests/migrate_against_confiture.rs` against;
//! a bump of that pin is where a change to the table gets checked (#1376).

use std::{path::Path, process::Command};

use anyhow::{Context, Result};
use fraiseql_db::postgres::PostgresTlsConfig;
use tracing::info;

use crate::{config::DatabaseRuntimeConfig, output::OutputFormatter};

/// Migration subcommand
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum MigrateAction {
    /// Apply pending migrations
    Up {
        /// Database connection URL
        database_url: String,
        /// Migration directory
        dir:          String,
    },
    /// Roll back migrations
    Down {
        /// Database connection URL
        database_url: String,
        /// Migration directory
        dir:          String,
        /// Number of steps to roll back
        steps:        u32,
    },
    /// Show migration status
    Status {
        /// Database connection URL
        database_url: String,
        /// Migration directory
        dir:          String,
    },
    /// Create a new migration file
    Create {
        /// Migration name
        name: String,
        /// Migration directory
        dir:  String,
    },
    /// Generate a new migration from schema diff
    Generate {
        /// Migration name
        name: String,
        /// Migration directory
        dir:  String,
    },
    /// Validate migration files for naming, idempotency, and drift
    Validate {
        /// Migration directory
        dir: String,
    },
    /// Pre-deploy safety check on pending migrations
    Preflight {
        /// Migration directory
        dir: String,
    },
}

/// Run the migrate command
///
/// # Errors
///
/// Returns an error if `confiture` is not installed, or if the underlying
/// `confiture` subprocess fails (non-zero exit status or spawn failure).
pub fn run(action: &MigrateAction, formatter: &OutputFormatter) -> Result<()> {
    require_confiture(formatter)?;

    let (command, done, failed) = match action {
        MigrateAction::Up { database_url, dir } => {
            info!("Running migrations up from {dir}");
            formatter.progress(&format!("Applying migrations from {dir}..."));
            (
                ConfitureCommand::new(ConfitureVerb::Up, dir, formatter).database_url(database_url),
                "Migrations applied successfully.".to_string(),
                "Migration failed. Check the output above for details.",
            )
        },
        MigrateAction::Down {
            database_url,
            dir,
            steps,
        } => {
            info!("Rolling back {steps} migration(s) from {dir}");
            formatter.progress(&format!("Rolling back {steps} migration(s)..."));
            (
                ConfitureCommand::new(ConfitureVerb::Down, dir, formatter)
                    .database_url(database_url)
                    .steps(*steps),
                "Rollback completed successfully.".to_string(),
                "Rollback failed. Check the output above for details.",
            )
        },
        MigrateAction::Status { database_url, dir } => {
            info!("Checking migration status for {dir}");
            (
                ConfitureCommand::new(ConfitureVerb::Status, dir, formatter)
                    .database_url(database_url),
                String::new(),
                "Failed to get migration status.",
            )
        },
        MigrateAction::Create { name, dir } => {
            info!("Creating migration: {name} in {dir}");
            ensure_migrations_dir(dir)?;
            (
                ConfitureCommand::new(ConfitureVerb::Generate, dir, formatter).name(name),
                format!("Migration created in {dir}/"),
                "Failed to create migration.",
            )
        },
        MigrateAction::Generate { name, dir } => {
            info!("Generating migration: {name} in {dir}");
            ensure_migrations_dir(dir)?;
            formatter.progress(&format!("Generating migration '{name}' in {dir}..."));
            (
                ConfitureCommand::new(ConfitureVerb::Generate, dir, formatter).name(name),
                format!("Migration generated in {dir}/"),
                "Failed to generate migration.",
            )
        },
        MigrateAction::Validate { dir } => {
            info!("Validating migrations in {dir}");
            (
                ConfitureCommand::new(ConfitureVerb::Validate, dir, formatter),
                String::new(),
                "Migration validation failed. Check the output above for details.",
            )
        },
        MigrateAction::Preflight { dir } => {
            info!("Running preflight checks for {dir}");
            formatter.progress(&format!("Running preflight checks on {dir}..."));
            (
                ConfitureCommand::new(ConfitureVerb::Preflight, dir, formatter),
                "Preflight checks passed.".to_string(),
                "Preflight checks failed. Check the output above for details.",
            )
        },
    };

    if command.succeeds()? {
        if !done.is_empty() {
            formatter.progress(&done);
        }
        Ok(())
    } else {
        anyhow::bail!("{failed}")
    }
}

/// Fail, with install instructions, when `confiture` is not on `PATH`.
///
/// Checked before anything connects: a missing confiture is the error a user can act on
/// first, whatever the database turns out to be.
///
/// # Errors
///
/// Returns an error when `confiture --version` cannot be run.
pub fn require_confiture(formatter: &OutputFormatter) -> Result<()> {
    if is_confiture_installed() {
        return Ok(());
    }
    print_install_instructions(formatter);
    anyhow::bail!("confiture is not installed. See instructions above.")
}

/// Refuse a PostgreSQL server below FraiseQL's floor before confiture touches it.
///
/// `up`, `down` and `status` hand the URL to confiture, which would run migrations against
/// any server; every other connection FraiseQL opens asks the version first (#1452). This
/// opens the same checked connection the catalogue commands use, with the TLS settings the
/// URL was resolved with, and drops it.
///
/// # Errors
///
/// Returns the floor refusal for a server below PostgreSQL 18, or the connection error.
pub async fn refuse_unsupported_server(database: &ResolvedDatabase) -> Result<()> {
    crate::connection::postgres_adapter(&database.url, "migration", &database.tls)
        .await
        .map(drop)
}

/// The `confiture migrate` verbs this wrapper invokes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ConfitureVerb {
    /// `confiture migrate up`
    Up,
    /// `confiture migrate down`
    Down,
    /// `confiture migrate status`
    Status,
    /// `confiture migrate generate` — the verb that writes a new migration file
    Generate,
    /// `confiture migrate validate`
    Validate,
    /// `confiture migrate preflight`
    Preflight,
}

impl ConfitureVerb {
    /// The verb as confiture spells it.
    pub(crate) const fn as_str(self) -> &'static str {
        match self {
            Self::Up => "up",
            Self::Down => "down",
            Self::Status => "status",
            Self::Generate => "generate",
            Self::Validate => "validate",
            Self::Preflight => "preflight",
        }
    }

    /// Whether the verb has a `--no-config` option: `up`, `down`, `status` and `preflight`
    /// do, `generate` and `validate` do not (`confiture migrate <verb> --help`, 1.29.0).
    pub(crate) const fn accepts_no_config(self) -> bool {
        matches!(self, Self::Up | Self::Down | Self::Status | Self::Preflight)
    }
}

/// One `confiture migrate <verb>` invocation.
///
/// Every option this wrapper passes is a row of this table, and every row was checked
/// against `confiture migrate <verb> --help`:
///
/// | argv                          | verbs                      | source                           |
/// |-------------------------------|----------------------------|----------------------------------|
/// | `--migrations-dir <dir>`      | all six                    | the resolved migration directory |
/// | `<name>` (positional)         | `generate`                 | the migration name               |
/// | `--steps <n>`                 | `down`                     | how many migrations to roll back |
/// | `--no-config`                 | `up`, `down`, `status`     | accompanies the DSN (below)      |
/// | `--format json`               | all six                    | the CLI's global `--json`        |
///
/// No verb takes a schema directory (`validate` has `--ddl-dir`/`--schema`; the rest have
/// no schema path at all), so none is passed.
///
/// The DSN never travels on argv, where `ps aux` and `/proc/<pid>/cmdline` would show it.
/// It is exported as `CONFITURE_DATABASE_URL`, confiture's canonical variable, together
/// with `--no-config`. Under that flag confiture's connection ladder (its
/// `docs/reference/cli.md`, §"Connection source and precedence") reads the environment as
/// the sole DSN source and skips config-file discovery, so the DSN [`resolve_database_url`]
/// settled on is the one confiture connects with; no `confiture.yaml` or
/// `db/environments/*.yaml` in the working directory can shadow it. The same ladder is why
/// the ambient `DATABASE_URL` is never used for the handoff: confiture ignores it for
/// `status` (every migration "unknown (no config)", exit 0) and refuses it for `up` and
/// `down` (`CONFIG_010`). `preflight` also has `--no-config`, but the wrapper hands it no
/// DSN, so it runs under confiture's own discovery.
#[derive(Clone)]
pub(crate) struct ConfitureCommand {
    verb:           ConfitureVerb,
    migrations_dir: String,
    name:           Option<String>,
    steps:          Option<u32>,
    json:           bool,
    database_url:   Option<String>,
}

impl ConfitureCommand {
    /// A `confiture migrate <verb> --migrations-dir <dir>` call, `--format json` under `--json`.
    pub(crate) fn new(
        verb: ConfitureVerb,
        migrations_dir: &str,
        formatter: &OutputFormatter,
    ) -> Self {
        Self {
            verb,
            migrations_dir: migrations_dir.to_string(),
            name: None,
            steps: None,
            json: formatter.is_json(),
            database_url: None,
        }
    }

    /// The positional migration name (`generate`).
    pub(crate) fn name(mut self, name: &str) -> Self {
        self.name = Some(name.to_string());
        self
    }

    /// `--steps <n>` (`down`).
    pub(crate) const fn steps(mut self, steps: u32) -> Self {
        self.steps = Some(steps);
        self
    }

    /// The DSN confiture connects with: exported as `CONFITURE_DATABASE_URL`, with
    /// `--no-config` on argv. Only a verb that has `--no-config` can be handed one.
    pub(crate) fn database_url(mut self, url: &str) -> Self {
        debug_assert!(
            self.verb.accepts_no_config(),
            "confiture migrate {} has no --no-config, so it cannot take a DSN this way",
            self.verb.as_str()
        );
        self.database_url = Some(url.to_string());
        self
    }

    /// The arguments after the program name, in the order confiture receives them.
    pub(crate) fn argv(&self) -> Vec<String> {
        let mut argv = vec!["migrate".to_string(), self.verb.as_str().to_string()];
        if let Some(name) = &self.name {
            argv.push(name.clone());
        }
        argv.push("--migrations-dir".to_string());
        argv.push(self.migrations_dir.clone());
        if let Some(steps) = self.steps {
            argv.push("--steps".to_string());
            argv.push(steps.to_string());
        }
        if self.database_url.is_some() {
            argv.push("--no-config".to_string());
        }
        if self.json {
            argv.push("--format".to_string());
            argv.push("json".to_string());
        }
        argv
    }

    /// The process to spawn: `confiture` with [`Self::argv`], and `CONFITURE_DATABASE_URL`
    /// set when a DSN was handed over. Nothing else in the environment is touched.
    pub(crate) fn command(&self) -> Command {
        let mut command = Command::new("confiture");
        command.args(self.argv());
        if let Some(url) = &self.database_url {
            command.env("CONFITURE_DATABASE_URL", url);
        }
        command
    }

    /// Runs confiture with stdio inherited and reports whether it exited 0.
    fn succeeds(&self) -> Result<bool> {
        let status = self.command().status().context("Failed to execute confiture")?;
        Ok(status.success())
    }
}

impl std::fmt::Debug for ConfitureCommand {
    /// The DSN is a credential: it is shown as present or absent, never spelled out.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ConfitureCommand")
            .field("verb", &self.verb)
            .field("migrations_dir", &self.migrations_dir)
            .field("name", &self.name)
            .field("steps", &self.steps)
            .field("json", &self.json)
            .field("database_url", &self.database_url.as_ref().map(|_| "<redacted>"))
            .finish()
    }
}

fn ensure_migrations_dir(dir: &str) -> Result<()> {
    std::fs::create_dir_all(dir).context(format!("Failed to create migration directory: {dir}"))
}

/// The long help of `fraiseql migrate`. It lives beside the resolver whose order it states
/// and the builder whose handoff it describes, so a change to either is a change here; a
/// unit test holds the text to the resolver's order.
pub(crate) const MIGRATE_LONG_ABOUT: &str = "Run database migrations\n\n\
    Wraps confiture: every verb is one `confiture migrate <verb>` call. The database URL is \
    resolved in this order: the --database flag, then [database].url in fraiseql.toml, then \
    the DATABASE_URL environment variable. The result reaches confiture as \
    CONFITURE_DATABASE_URL with --no-config, so confiture's own config files never override \
    it.";

/// Resolves the database URL for the commands that connect: the explicit `--database`
/// flag, else `[database].url` in `fraiseql.toml`, else the `DATABASE_URL` environment
/// variable.
///
/// `fraiseql.toml` is placed above the environment because it is the project's own file,
/// while `DATABASE_URL` is whatever the shell happens to hold; an explicit flag beats both.
/// This is fraiseql's ladder, not confiture's. Confiture has one of its own — its
/// `docs/reference/cli.md`, §"Connection source and precedence" — in which a present config
/// file beats an ambient `DATABASE_URL` and a mutating verb refuses an ambient variable
/// outright. The wrapper does not let the two ladders compete: the URL this function
/// settles on is handed to confiture under `--no-config`, which makes that URL the sole
/// source (`ConfitureCommand`, below).
///
/// # Errors
///
/// Returns an error if `fraiseql.toml` exists but cannot be read or parsed, or if no
/// source provides a URL.
pub fn resolve_database_url(explicit: Option<&str>) -> Result<String> {
    resolve_database(explicit).map(|db| db.url)
}

/// A database URL and the transport security to connect to it with.
#[derive(Debug, Clone)]
pub struct ResolvedDatabase {
    /// The connection string.
    pub url: String,
    /// `[database] ssl_mode` when the URL came from `fraiseql.toml`; otherwise unset,
    /// which leaves the URL's own `sslmode` in charge.
    pub tls: PostgresTlsConfig,
}

/// Resolve the database URL like [`resolve_database_url`], together with its TLS
/// settings (#1429).
///
/// A URL taken from `fraiseql.toml`'s `[database]` section brings that section's
/// `ssl_mode` with it: the two are one setting written in two keys. A URL from the flag
/// or `DATABASE_URL` carries its own `?sslmode=`.
///
/// # Errors
///
/// Returns an error if `fraiseql.toml` exists but cannot be read or parsed, if its
/// `ssl_mode` names a mode the connector cannot honour, or if no database URL can be
/// found from any source (flag, TOML, or `DATABASE_URL`).
pub fn resolve_database(explicit: Option<&str>) -> Result<ResolvedDatabase> {
    resolve_configured_database(explicit)?.ok_or_else(|| {
        anyhow::anyhow!(
            "No database URL provided. Use --database, set [database].url in fraiseql.toml, \
             or set DATABASE_URL environment variable."
        )
    })
}

/// [`resolve_database`] for a command whose database is optional.
///
/// "No source names a database" is `Ok(None)` rather than an error. A configuration that
/// names one badly — an unparseable `fraiseql.toml`, an unknown `ssl_mode` — is still an
/// error.
///
/// # Errors
///
/// Returns an error if `fraiseql.toml` exists but cannot be read or parsed, or if its
/// `ssl_mode` names a mode the connector cannot honour.
pub fn resolve_configured_database(explicit: Option<&str>) -> Result<Option<ResolvedDatabase>> {
    if let Some(url) = explicit {
        return Ok(Some(ResolvedDatabase {
            url: url.to_string(),
            tls: PostgresTlsConfig::default(),
        }));
    }

    // Try loading from fraiseql.toml
    let toml_path = Path::new("fraiseql.toml");
    if toml_path.exists() {
        let content = std::fs::read_to_string(toml_path).context("Failed to read fraiseql.toml")?;
        let parsed: toml::Value =
            toml::from_str(&content).context("Failed to parse fraiseql.toml")?;

        let database = DatabaseRuntimeConfig::from_document(&parsed)
            .context("Failed to parse [database] in fraiseql.toml")?;
        if let Some(url) = &database.url {
            info!("Using database URL from fraiseql.toml");
            return Ok(Some(ResolvedDatabase {
                url: url.clone(),
                tls: database.postgres_tls()?,
            }));
        }
    }
    if let Ok(url) = std::env::var("DATABASE_URL") {
        info!("Using DATABASE_URL environment variable");
        return Ok(Some(ResolvedDatabase {
            url,
            tls: PostgresTlsConfig::default(),
        }));
    }

    Ok(None)
}

/// Resolve the migration directory: use explicit flag, or auto-discover
pub fn resolve_migration_dir(explicit: Option<&str>) -> String {
    if let Some(dir) = explicit {
        return dir.to_string();
    }

    // Auto-discover common directory names
    for candidate in &["db/0_schema", "db/migrations", "migrations"] {
        if Path::new(candidate).is_dir() {
            info!("Auto-discovered migration directory: {candidate}");
            return (*candidate).to_string();
        }
    }

    // Default
    "db/0_schema".to_string()
}

fn is_confiture_installed() -> bool {
    Command::new("confiture")
        .arg("--version")
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .is_ok_and(|s| s.success())
}

/// The commands that install confiture, one a line (#1602).
///
/// confiture ships on PyPI as `fraiseql-confiture`, which installs a `confiture` console
/// script and needs Python 3.14 or later. `confiture` on crates.io is an unrelated crate and
/// there is no Homebrew formula: neither installs the tool this command runs.
pub(crate) const CONFITURE_INSTALL_COMMANDS: [&str; 2] = [
    "uv tool install fraiseql-confiture",
    "pipx install fraiseql-confiture",
];

fn print_install_instructions(formatter: &OutputFormatter) {
    formatter.progress("confiture is not installed.");
    formatter.progress("");
    formatter.progress("Install it (Python 3.14 or later) with one of:");
    for command in CONFITURE_INSTALL_COMMANDS {
        formatter.progress(&format!("  {command}"));
    }
    formatter.progress("");
    formatter.progress("Learn more: https://github.com/fraiseql/confiture");
}