Skip to main content

fraiseql_cli/
cli.rs

1//! CLI argument definitions: `Cli` struct, `Commands` enum, and all sub-command enums.
2
3use clap::{Parser, Subcommand};
4
5/// Exit codes documented in help text
6pub(crate) const EXIT_CODES_HELP: &str = "\
7EXIT CODES:
8    0  Success - Command completed successfully
9    1  Error - Command failed with an error
10    2  Validation failed - Schema or input validation failed";
11
12/// FraiseQL CLI - Compile GraphQL schemas to optimized SQL execution
13#[derive(Parser)]
14#[command(name = "fraiseql")]
15#[command(author, version, about, long_about = None)]
16#[command(propagate_version = true)]
17#[command(after_help = EXIT_CODES_HELP)]
18pub(crate) struct Cli {
19    /// Enable verbose logging
20    #[arg(short, long, global = true)]
21    pub(crate) verbose: bool,
22
23    /// Enable debug logging
24    #[arg(short, long, global = true)]
25    pub(crate) debug: bool,
26
27    /// Output as JSON (machine-readable)
28    #[arg(long, global = true)]
29    pub(crate) json: bool,
30
31    /// Suppress output (exit code only)
32    #[arg(short, long, global = true)]
33    pub(crate) quiet: bool,
34
35    #[command(subcommand)]
36    pub(crate) command: Commands,
37}
38
39#[derive(Subcommand)]
40pub(crate) enum Commands {
41    /// Compile schema to optimized schema.compiled.json
42    ///
43    /// Supports three workflows:
44    /// 1. TOML-only: fraiseql compile fraiseql.toml
45    /// 2. Language + TOML: fraiseql compile fraiseql.toml --types types.json
46    /// 3. Legacy JSON: fraiseql compile schema.json
47    #[command(after_help = "\
48EXAMPLES:
49    fraiseql compile fraiseql.toml
50    fraiseql compile fraiseql.toml --types types.json
51    fraiseql compile schema.json -o schema.compiled.json
52    fraiseql compile fraiseql.toml --check")]
53    Compile {
54        /// Input file path: fraiseql.toml (TOML) or schema.json (legacy)
55        #[arg(value_name = "INPUT")]
56        input: String,
57
58        /// Optional types.json from language implementation (used with fraiseql.toml)
59        #[arg(long, value_name = "TYPES")]
60        types: Option<String>,
61
62        /// Directory for auto-discovery of schema files (recursive *.json)
63        #[arg(long, value_name = "DIR")]
64        schema_dir: Option<String>,
65
66        /// Type files (repeatable): fraiseql compile fraiseql.toml --type-file a.json --type-file
67        /// b.json
68        #[arg(long = "type-file", value_name = "FILE")]
69        type_files: Vec<String>,
70
71        /// Query files (repeatable)
72        #[arg(long = "query-file", value_name = "FILE")]
73        query_files: Vec<String>,
74
75        /// Mutation files (repeatable)
76        #[arg(long = "mutation-file", value_name = "FILE")]
77        mutation_files: Vec<String>,
78
79        /// Output schema.compiled.json file path
80        #[arg(
81            short,
82            long,
83            value_name = "OUTPUT",
84            default_value = "schema.compiled.json"
85        )]
86        output: String,
87
88        /// Validate only, don't write output
89        #[arg(long)]
90        check: bool,
91
92        /// Skip embedding content hash in compiled schema (for test fixtures)
93        #[arg(long)]
94        skip_hash: bool,
95
96        /// Optional database URL: check the schema against the live database
97        ///
98        /// Validates each `sql_source`, mutation function, JSONB key and query argument
99        /// against the relations it names, and fills `native_columns` from the views'
100        /// columns. Drift classified as an error fails the compile (see `--allow-drift`).
101        #[arg(long, value_name = "DATABASE_URL")]
102        database: Option<String>,
103
104        /// Emit DDL files for all schema types to the given directory
105        ///
106        /// Writes `CREATE TABLE` DDL for each compiled type to `<DIR>/<type>.sql`.
107        /// Output is compatible with confiture's `db/schema/` directory format,
108        /// enabling `fraiseql migrate generate` to auto-detect schema drift.
109        #[arg(long, value_name = "DIR")]
110        emit_ddl: Option<String>,
111
112        /// Check compiled schema against the database for migration drift
113        ///
114        /// Emits DDL to a temporary directory, then delegates to
115        /// `confiture migrate validate` for drift detection.
116        /// Exits non-zero when the compiled schema diverges from the database.
117        #[arg(long)]
118        check_migrations: bool,
119
120        /// Compile despite error-severity schema↔database drift (advisory mode)
121        ///
122        /// With `--database`, drift the linter classifies as an error (a
123        /// `sql_source` that does not exist, a required field's JSONB key
124        /// absent from every sampled row, a mutation with no backing function)
125        /// fails the compile. This flag downgrades those findings to reported
126        /// advisories and writes the artifact anyway.
127        #[arg(long, requires = "database")]
128        allow_drift: bool,
129
130        /// Project config to compile with. Default: the nearest fraiseql.toml beside
131        /// or above the input, up to the repository root — never the working directory
132        #[arg(long, value_name = "PATH")]
133        config: Option<String>,
134    },
135
136    /// Extract schema from annotated source files
137    ///
138    /// Parses FraiseQL annotations in any supported language and generates schema.json.
139    /// No language runtime required — pure text processing.
140    #[command(after_help = "\
141EXAMPLES:
142    fraiseql extract schema/schema.py
143    fraiseql extract schema/ --recursive
144    fraiseql extract schema.rs --language rust -o schema.json")]
145    Extract {
146        /// Source file(s) or directory to extract from
147        #[arg(value_name = "INPUT")]
148        input: Vec<String>,
149
150        /// Override language detection (python, typescript, rust, java, kotlin, go, csharp, swift,
151        /// scala)
152        #[arg(short, long)]
153        language: Option<String>,
154
155        /// Recursively scan directories
156        #[arg(short, long)]
157        recursive: bool,
158
159        /// Output file path
160        #[arg(short, long, default_value = "schema.json")]
161        output: String,
162    },
163
164    /// Explain query execution plan and complexity
165    ///
166    /// Shows GraphQL query execution plan, SQL, and complexity analysis.
167    #[command(after_help = "\
168EXAMPLES:
169    fraiseql explain '{ users { id name } }'
170    fraiseql explain '{ user(id: 1) { posts { title } } }' --json")]
171    Explain {
172        /// GraphQL query string
173        #[arg(value_name = "QUERY")]
174        query: String,
175    },
176
177    /// Calculate query complexity score
178    ///
179    /// Quick analysis of query complexity (depth, field count, score).
180    #[command(after_help = "\
181EXAMPLES:
182    fraiseql cost '{ users { id name } }'
183    fraiseql cost '{ deeply { nested { query { here } } } }' --json")]
184    Cost {
185        /// GraphQL query string
186        #[arg(value_name = "QUERY")]
187        query: String,
188    },
189
190    /// Analyze schema for optimization opportunities
191    ///
192    /// Provides recommendations across 6 categories:
193    /// performance, security, federation, complexity, caching, indexing
194    #[command(after_help = "\
195EXAMPLES:
196    fraiseql analyze schema.compiled.json
197    fraiseql analyze schema.compiled.json --json")]
198    Analyze {
199        /// Path to schema.compiled.json
200        #[arg(value_name = "SCHEMA")]
201        schema: String,
202    },
203
204    /// Analyze schema type dependencies
205    ///
206    /// Exports dependency graph, detects cycles, and finds unused types.
207    /// Supports multiple output formats for visualization and CI integration.
208    #[command(after_help = "\
209EXAMPLES:
210    fraiseql dependency-graph schema.compiled.json
211    fraiseql dependency-graph schema.compiled.json -f dot > graph.dot
212    fraiseql dependency-graph schema.compiled.json -f mermaid
213    fraiseql dependency-graph schema.compiled.json --json")]
214    DependencyGraph {
215        /// Path to schema.compiled.json
216        #[arg(value_name = "SCHEMA")]
217        schema: String,
218
219        /// Output format (json, dot, mermaid, d2, console)
220        #[arg(short, long, value_name = "FORMAT", default_value = "json")]
221        format: String,
222    },
223
224    /// Federation tools: draw the graph subgraphs form, check a subgraph
225    ///
226    /// `graph` takes each subgraph's compiled schema and draws who extends whose entities.
227    #[command(after_help = "\
228EXAMPLES:
229    fraiseql federation graph users.compiled.json orders.compiled.json
230    fraiseql federation graph users.compiled.json orders.compiled.json -f dot
231    fraiseql federation graph users.compiled.json orders.compiled.json -f mermaid
232    fraiseql federation check schema.compiled.json --against other.compiled.json
233    fraiseql federation sdl schema.compiled.json -o subgraph.graphql   (--features federation)")]
234    Federation {
235        /// Schema path (positional argument passed to subcommand)
236        #[command(subcommand)]
237        command: FederationCommands,
238    },
239
240    /// Lint schema for FraiseQL design quality
241    ///
242    /// Analyzes schema using FraiseQL-calibrated design rules.
243    /// Detects JSONB batching issues, compilation problems, auth boundaries, etc.
244    #[command(after_help = "\
245EXAMPLES:
246    fraiseql lint schema.json
247    fraiseql lint schema.compiled.json --federation
248    fraiseql lint schema.json --fail-on-critical
249    fraiseql lint schema.json --json")]
250    Lint {
251        /// Path to schema.json or schema.compiled.json
252        #[arg(value_name = "SCHEMA")]
253        schema: String,
254
255        /// Only show federation audit
256        #[arg(long)]
257        federation: bool,
258
259        /// Only show cost audit
260        #[arg(long)]
261        cost: bool,
262
263        /// Only show cache audit
264        #[arg(long)]
265        cache: bool,
266
267        /// Only show auth audit
268        #[arg(long)]
269        auth: bool,
270
271        /// Only show compilation audit
272        #[arg(long)]
273        compilation: bool,
274
275        /// Exit with error if any critical issues found
276        #[arg(long)]
277        fail_on_critical: bool,
278
279        /// Exit with error if any warning or critical issues found
280        #[arg(long)]
281        fail_on_warning: bool,
282    },
283
284    /// Generate DDL for Arrow views (va_*, tv_*, ta_*)
285    #[command(after_help = "\
286EXAMPLES:
287    fraiseql generate-views -s schema.json -e User --view va_users
288    fraiseql generate-views -s schema.json -e Order --view tv_orders --refresh-strategy scheduled")]
289    GenerateViews {
290        /// Path to schema.json
291        #[arg(short, long, value_name = "SCHEMA")]
292        schema: String,
293
294        /// Entity name from schema
295        #[arg(short, long, value_name = "NAME")]
296        entity: String,
297
298        /// View name (must start with va_, tv_, or ta_)
299        #[arg(long, value_name = "NAME")]
300        view: String,
301
302        /// Refresh strategy (trigger-based or scheduled)
303        #[arg(long, value_name = "STRATEGY", default_value = "trigger-based")]
304        refresh_strategy: String,
305
306        /// Output file path (default: {view}.sql)
307        #[arg(short, long, value_name = "PATH")]
308        output: Option<String>,
309
310        /// Include helper/composition views
311        #[arg(long, default_value = "true")]
312        include_composition_views: bool,
313
314        /// Include monitoring functions
315        #[arg(long, default_value = "true")]
316        include_monitoring: bool,
317
318        /// Validate the generated DDL by executing it against PostgreSQL
319        /// (DATABASE_URL) in a rolled-back transaction; don't write a file
320        #[arg(long)]
321        validate: bool,
322
323        /// Show generation steps (use global --verbose flag)
324        #[arg(long, action = clap::ArgAction::SetTrue)]
325        gen_verbose: bool,
326    },
327
328    /// Generate external-write capture-trigger DDL for @subscribable types (#366)
329    ///
330    /// Emits a self-contained, idempotent PostgreSQL script (the capture function
331    /// plus per-table statement-level triggers) that brings raw external writes
332    /// (psql / migrations / third-party tools) to a `@subscribable` type's table(s)
333    /// onto the Change Spine, without double-emitting for FraiseQL-mediated writes.
334    #[command(after_help = "\
335EXAMPLES:
336    fraiseql generate-capture-triggers -s schema.compiled.json | psql \"$DATABASE_URL\"
337    fraiseql generate-capture-triggers -s schema.compiled.json -o capture.sql")]
338    GenerateCaptureTriggers {
339        /// Path to the compiled schema (schema.compiled.json)
340        #[arg(short, long, value_name = "SCHEMA")]
341        schema: String,
342
343        /// Output file path (default: stdout, for piping into psql)
344        #[arg(short, long, value_name = "PATH")]
345        output: Option<String>,
346
347        /// Omit the capture function definition (emit only the per-table triggers)
348        #[arg(long)]
349        no_function: bool,
350    },
351
352    /// Validate schema.json or fact tables
353    ///
354    /// Performs comprehensive schema validation including:
355    /// - JSON structure validation
356    /// - Type reference validation
357    /// - Circular dependency detection (with --check-cycles)
358    /// - Unused type detection (with --check-unused)
359    #[command(after_help = "\
360EXAMPLES:
361    fraiseql validate schema.json
362    fraiseql validate schema.json --check-unused
363    fraiseql validate schema.json --strict
364    fraiseql validate facts -s schema.json --database postgres://localhost/db")]
365    Validate {
366        #[command(subcommand)]
367        command: Option<ValidateCommands>,
368
369        /// Schema.json file path to validate (if no subcommand)
370        #[arg(value_name = "INPUT")]
371        input: Option<String>,
372
373        /// Check for circular dependencies between types
374        #[arg(long, default_value = "true")]
375        check_cycles: bool,
376
377        /// Check for unused types (no incoming references)
378        #[arg(long)]
379        check_unused: bool,
380
381        /// Strict mode: treat warnings as errors (unused types become errors)
382        #[arg(long)]
383        strict: bool,
384
385        /// Only analyze specific type(s) - comma-separated list
386        #[arg(long, value_name = "TYPES", value_delimiter = ',')]
387        types: Vec<String>,
388
389        /// Validate the mutation contract against a live PostgreSQL database.
390        ///
391        /// For each DB-backed mutation, checks that its `sql_source` function
392        /// exists with the argument layout the server sends and returns the
393        /// columns the server decodes into `MutationResponse`. Requires a
394        /// compiled schema (schema.compiled.json) as INPUT. (#397)
395        #[arg(long, value_name = "DATABASE_URL")]
396        against_db: Option<String>,
397    },
398
399    /// Introspect database for fact tables and output suggestions
400    #[command(after_help = "\
401EXAMPLES:
402    fraiseql introspect facts --database postgres://localhost/db
403    fraiseql introspect facts --database postgres://localhost/db -f json")]
404    Introspect {
405        #[command(subcommand)]
406        command: IntrospectCommands,
407    },
408
409    /// Generate authoring-language source from schema.json
410    ///
411    /// The inverse of `fraiseql extract`: reads a schema.json and produces annotated
412    /// source code in any of the 9 supported authoring languages.
413    #[command(after_help = "\
414EXAMPLES:
415    fraiseql generate schema.json --language python
416    fraiseql generate schema.json --language rust -o schema.rs
417    fraiseql generate schema.json --language typescript")]
418    Generate {
419        /// Path to schema.json
420        #[arg(value_name = "INPUT")]
421        input: String,
422
423        /// Target language (python, typescript, rust, java, kotlin, go, csharp, swift, scala)
424        #[arg(short, long)]
425        language: String,
426
427        /// Output file path (default: schema.<ext> based on language)
428        #[arg(short, long)]
429        output: Option<String>,
430    },
431
432    /// Generate consumer-side typed clients from a compiled schema
433    ///
434    /// Distinct from `generate`: `generate` emits server-side authoring code (write
435    /// FraiseQL types in another language, fed back into the compiler), whereas
436    /// `generate-client` emits a typed client for callers of a FraiseQL API
437    /// (interfaces + query/mutation functions) from a compiled schema.compiled.json.
438    #[command(after_help = "\
439EXAMPLES:
440    fraiseql generate-client typescript --out ./src/generated
441    fraiseql generate-client typescript --schema ./schema.compiled.json --out ./gen --force
442    fraiseql generate-client python --out ./app/fraiseql_client
443    fraiseql generate-client go --out ./internal/fraiseqlclient
444    fraiseql generate-client rust --out ./src/generated")]
445    GenerateClient {
446        #[command(subcommand)]
447        language: GenerateClientCommands,
448    },
449
450    /// Initialize a new FraiseQL project
451    ///
452    /// Creates project directory with fraiseql.toml, schema.json,
453    /// database DDL structure, and authoring skeleton.
454    #[command(after_help = "\
455EXAMPLES:
456    fraiseql init my-app
457    fraiseql init my-app --language typescript --database postgres
458    fraiseql init my-app --size xs --no-git")]
459    Init {
460        /// Project name (used as directory name)
461        #[arg(value_name = "PROJECT_NAME")]
462        project_name: String,
463
464        /// Authoring language (python, typescript, rust, java, kotlin, go, csharp, swift, scala)
465        #[arg(short, long, default_value = "python")]
466        language: String,
467
468        /// Target database (postgres — FraiseQL is PostgreSQL-only since v2.15.0)
469        #[arg(long, default_value = "postgres")]
470        database: String,
471
472        /// Project size: xs (single file), s (flat dirs), m (per-entity dirs)
473        #[arg(long, default_value = "s")]
474        size: String,
475
476        /// Skip git init
477        #[arg(long)]
478        no_git: bool,
479    },
480
481    /// Run database migrations
482    ///
483    /// The long help is `commands::migrate::MIGRATE_LONG_ABOUT`: it states the order the
484    /// database URL is resolved in, so it lives beside the resolver.
485    #[command(long_about = crate::commands::migrate::MIGRATE_LONG_ABOUT)]
486    #[command(after_help = "\
487EXAMPLES:
488    fraiseql migrate up --database postgres://localhost/mydb
489    fraiseql migrate down --steps 1
490    fraiseql migrate status
491    fraiseql migrate create add_posts_table")]
492    Migrate {
493        #[command(subcommand)]
494        command: MigrateCommands,
495    },
496
497    /// Generate Software Bill of Materials
498    ///
499    /// Parses Cargo.lock and fraiseql.toml to produce a compliance-ready SBOM.
500    #[command(after_help = "\
501EXAMPLES:
502    fraiseql sbom
503    fraiseql sbom --format spdx
504    fraiseql sbom --format cyclonedx --output sbom.json")]
505    Sbom {
506        /// Output format (cyclonedx, spdx)
507        #[arg(short, long, default_value = "cyclonedx")]
508        format: String,
509
510        /// Output file path (default: stdout)
511        #[arg(short, long, value_name = "FILE")]
512        output: Option<String>,
513    },
514
515    /// Compile schema and immediately start the GraphQL server
516    ///
517    /// Compiles the schema in-memory (no disk artifact) and starts the HTTP server.
518    /// With --watch, the server hot-reloads whenever the schema file changes.
519    ///
520    /// Server and database settings can be declared in fraiseql.toml under [server]
521    /// and [database] sections.  CLI flags take precedence over TOML settings, which
522    /// take precedence over defaults.  The database URL is resolved in this order:
523    /// --database flag > DATABASE_URL env var > [database].url in fraiseql.toml.
524    #[cfg(feature = "run-server")]
525    #[command(after_help = "\
526EXAMPLES:
527    fraiseql run
528    fraiseql run fraiseql.toml --database postgres://localhost/mydb
529    fraiseql run --port 3000 --watch
530    fraiseql run schema.json --introspection
531
532TOML CONFIG:
533    [server]
534    host = \"127.0.0.1\"
535    port = 9000
536
537    [server.cors]
538    origins = [\"https://app.example.com\"]
539
540    [database]
541    url      = \"${DATABASE_URL}\"
542    pool_min = 2
543    pool_max = 20")]
544    Run {
545        /// Input file path (fraiseql.toml or schema.json); auto-detected if omitted
546        #[arg(value_name = "INPUT")]
547        input: Option<String>,
548
549        /// Database URL (overrides [database].url in fraiseql.toml and DATABASE_URL env var)
550        // Long-only: the global `--debug` (`Cli.debug`) already owns `-d`. A local
551        // `-d`/`--database` short here collides with it — clap's debug_asserts panic in
552        // debug builds and the short is ambiguous in release builds (#650).
553        #[arg(long, value_name = "DATABASE_URL")]
554        database: Option<String>,
555
556        /// Port to listen on (overrides [server].port in fraiseql.toml)
557        #[arg(short, long, value_name = "PORT")]
558        port: Option<u16>,
559
560        /// Bind address (overrides [server].host in fraiseql.toml)
561        #[arg(long, value_name = "HOST")]
562        bind: Option<String>,
563
564        /// Watch input file for changes and hot-reload the server
565        #[arg(short, long)]
566        watch: bool,
567
568        /// Enable the GraphQL introspection endpoint (no auth required)
569        #[arg(long)]
570        introspection: bool,
571    },
572
573    /// Watch a schema source and recompile + live-reload a running server on change
574    ///
575    /// Recompiles `schema.compiled.json` on every save and, with `--reload-url`,
576    /// POSTs it to a running server's `/api/v1/admin/reload-schema` endpoint for a
577    /// zero-downtime `ArcSwap` reload (no restart). Unlike `run --watch`, this drives
578    /// a server you started separately.
579    Watch {
580        /// Schema source to watch (fraiseql.toml or schema.json)
581        #[arg(value_name = "INPUT")]
582        input: String,
583
584        /// Compiled-schema output path (the server reads this on reload)
585        #[arg(short, long, default_value = "schema.compiled.json")]
586        output: String,
587
588        /// Base URL of a running server to live-reload (e.g. http://localhost:8080).
589        /// Omit to recompile to disk only.
590        #[arg(long, value_name = "URL")]
591        reload_url: Option<String>,
592
593        /// Bearer token for the server's admin reload endpoint
594        #[arg(long, value_name = "TOKEN")]
595        admin_token: Option<String>,
596
597        /// Database URL for compile-time validation (overrides DATABASE_URL)
598        #[arg(long, value_name = "DATABASE_URL")]
599        database: Option<String>,
600    },
601
602    /// Validate a trusted documents manifest
603    ///
604    /// Checks that the manifest JSON is well-formed and that each key
605    /// is a valid SHA-256 hex string matching its query body.
606    #[command(after_help = "\
607EXAMPLES:
608    fraiseql validate-documents manifest.json
609    fraiseql validate-documents manifest.json --max-cost 1000 --schema schema.compiled.json")]
610    ValidateDocuments {
611        /// Path to the trusted documents manifest JSON file
612        #[arg(value_name = "MANIFEST")]
613        manifest: String,
614
615        /// Fail validation when any document's estimated operation cost exceeds
616        /// this ceiling (#379). Costs are worst-case: a variable-valued
617        /// pagination argument is scored at its fail-closed ceiling.
618        #[arg(long, value_name = "COST")]
619        max_cost: Option<u64>,
620
621        /// Compiled schema (`schema.compiled.json`) supplying the
622        /// `[fraiseql.cost_weights]` used to score documents — the same numbers
623        /// the runtime enforces. Without it, cost equals the complexity score.
624        #[arg(long, value_name = "SCHEMA")]
625        schema: Option<String>,
626    },
627
628    /// Install FraiseQL mutation helper functions
629    ///
630    /// Installs SQL helper functions (fraiseql.mutation_ok, fraiseql.mutation_err, etc.)
631    /// to reduce boilerplate when writing mutation functions under the v2.4.0 protocol.
632    /// The helpers are installed in the `fraiseql` schema, which is owned by FraiseQL's
633    /// database role.
634    #[command(after_help = "\
635EXAMPLES:
636    fraiseql setup --database postgres://localhost/mydb
637    fraiseql setup --dry-run
638    fraiseql setup  # Uses [database].url from fraiseql.toml, else DATABASE_URL")]
639    Setup {
640        /// Database connection URL (else [database].url in fraiseql.toml, else the
641        /// DATABASE_URL env var)
642        #[arg(long, value_name = "DATABASE_URL")]
643        database: Option<String>,
644
645        /// Print SQL without applying changes
646        #[arg(long)]
647        dry_run: bool,
648    },
649
650    /// Inspect schema metadata from a running FraiseQL server
651    ///
652    /// Fetches field-level security metadata (encryption, scope requirements, deny actions)
653    /// from the server's `/api/v1/schema/metadata` endpoint and displays it as a table.
654    #[command(after_help = "\
655EXAMPLES:
656    fraiseql schema metadata
657    fraiseql schema metadata --server http://localhost:8080
658    fraiseql schema metadata --server https://api.example.com --token mytoken")]
659    Schema {
660        #[command(subcommand)]
661        command: SchemaCommands,
662    },
663
664    /// Execute one GraphQL operation against a database and print the JSON result
665    ///
666    /// Boots the compiled schema in-process (no long-lived server, no HTTP layer)
667    /// against PostgreSQL, runs a single query or mutation, prints the GraphQL JSON
668    /// response to stdout, and exits. Exits non-zero on a resolution error — a
669    /// scriptable "does this actually resolve?" check for CI and the inner loop.
670    ///
671    /// Mutations COMMIT unless `--dry-run` is given, which runs the mutation inside
672    /// a transaction that is rolled back (validate-bind-without-commit).
673    #[command(after_help = "\
674EXAMPLES:
675    fraiseql query '{ orders(limit: 1) { id } }'
676    fraiseql query --schema schema.compiled.json --database postgres://localhost/db '{ users { id } }'
677    fraiseql query --variables '{\"id\": 42}' 'query($id: Int!) { user(id: $id) { id } }'
678    fraiseql query --dry-run 'mutation { createUser(name: \"x\") { id } }'")]
679    Query {
680        /// GraphQL operation to execute (a single query or mutation document).
681        #[arg(value_name = "QUERY")]
682        query: String,
683
684        /// Path to schema.compiled.json.
685        #[arg(short = 's', long, default_value = "schema.compiled.json")]
686        schema: std::path::PathBuf,
687
688        /// Database URL (PostgreSQL only). Falls back to the DATABASE_URL env var.
689        #[arg(long, value_name = "DATABASE_URL")]
690        database: Option<String>,
691
692        /// GraphQL variables as a JSON object string (e.g. '{"id": 42}').
693        #[arg(long, value_name = "JSON")]
694        variables: Option<String>,
695
696        /// Run mutations inside a rolled-back transaction: the function binds and
697        /// executes (constraints, triggers, and response shape are validated) but
698        /// nothing is committed. No effect on queries. PostgreSQL only.
699        #[arg(long)]
700        dry_run: bool,
701    },
702
703    /// Run diagnostic checks for common FraiseQL setup problems
704    ///
705    /// Checks schema file, TOML config, DATABASE_URL, JWT secret, Redis, TLS,
706    /// and cache/auth coherence. Prints a color-coded report and exits 0 if
707    /// all checks pass or 1 if any check fails (warnings do not fail).
708    #[command(after_help = "\
709EXAMPLES:
710    fraiseql doctor
711    fraiseql doctor --schema schema.compiled.json --config fraiseql.toml
712    fraiseql doctor --db-url postgres://user:pass@host:5432/db
713    fraiseql doctor --runtime --against-db postgres://user:pass@host:5432/db
714    fraiseql doctor --json")]
715    Doctor {
716        /// Path to fraiseql.toml configuration file.
717        #[arg(long, default_value = "fraiseql.toml")]
718        config: std::path::PathBuf,
719
720        /// Path to schema.compiled.json.
721        #[arg(long, default_value = "schema.compiled.json")]
722        schema: std::path::PathBuf,
723
724        /// Override DATABASE_URL for the connectivity check.
725        #[arg(long)]
726        db_url: Option<String>,
727
728        /// Run the live-database passes against this PostgreSQL database: the
729        /// change-log contract drift check (compares core.tb_entity_change_log
730        /// against the shipped contract — #380), the PL/pgSQL body-resolution
731        /// pass (reports internal calls that no longer resolve — #409), the
732        /// mutation→function contract drift check (every declared mutation has a
733        /// matching backing function with a mutation_response-shaped return —
734        /// #384), and the view-drift check (the same L1/L2/L3 view-composition
735        /// linter `compile --database` runs, reported as structured checks —
736        /// #384).
737        ///
738        /// The body-resolution pass requires the `plpgsql_check` extension and
739        /// skips with a hint when it is unavailable.
740        #[arg(long, value_name = "DATABASE_URL")]
741        against_db: Option<String>,
742
743        /// Runtime smoke mode (#501): boot the compiled schema in-process and
744        /// probe each root query field with a minimal selection, dry-running each
745        /// no-argument mutation (rolled back). Confirms operations actually
746        /// *resolve* end-to-end, complementing the static `--against-db` drift
747        /// checks. Requires a PostgreSQL URL via `--against-db` (or `--db-url`).
748        /// Queries / mutations that require arguments are skipped with a warning.
749        #[arg(long)]
750        runtime: bool,
751
752        /// Schemas to scan in the body-resolution pass (comma-separated).
753        #[arg(
754            long,
755            value_name = "SCHEMAS",
756            value_delimiter = ',',
757            default_value = "public"
758        )]
759        schemas: Vec<String>,
760
761        /// Output machine-readable JSON (for CI integration).
762        #[arg(long)]
763        json: bool,
764    },
765
766    /// Change-log performance observability (#392)
767    ///
768    /// Reads the framework-owned change-log (`core.v_entity_change_log`) and turns
769    /// it into operator-facing forensics: latency regressions between two time
770    /// windows, and ad-hoc reads of the slowest mutations / duration completeness
771    /// / per-operation percentiles.
772    Perf {
773        #[command(subcommand)]
774        command: PerfCommands,
775    },
776
777    /// List scheduled ingress sources and their durable cursor state (#573)
778    ///
779    /// Reads the compiled schema for each source's schedule and `run_as` ceiling,
780    /// and — when a database is reachable — its cursor value, version, and staleness
781    /// (seconds since the last advance). Leadership and last-fire are not reported
782    /// here (an advisory lock has no visible holder, and the lease is released
783    /// between ticks): watch `fraiseql_source_*` metrics and the poller logs for
784    /// those. Always exits 0 — it is a report.
785    #[command(after_help = "\
786EXAMPLES:
787    fraiseql sources
788    fraiseql sources --schema schema.compiled.json
789    fraiseql sources --db-url postgres://user:pass@host:5432/db
790    fraiseql sources --json")]
791    Sources {
792        /// Path to schema.compiled.json.
793        #[arg(long, default_value = "schema.compiled.json")]
794        schema: std::path::PathBuf,
795
796        /// PostgreSQL URL for cursor reads (defaults to `fraiseql.toml` /
797        /// `DATABASE_URL`). Without one, definitions are listed with no cursor state.
798        #[arg(long)]
799        db_url: Option<String>,
800
801        /// Output machine-readable JSON.
802        #[arg(long)]
803        json: bool,
804    },
805
806    /// Author-side function tooling (local test harness).
807    #[cfg(feature = "functions-invoke")]
808    #[command(subcommand)]
809    Functions(FunctionsCommands),
810}
811
812/// `fraiseql functions` subcommands.
813#[cfg(feature = "functions-invoke")]
814#[derive(Subcommand)]
815pub(crate) enum FunctionsCommands {
816    /// Run a compiled function in a real V8 isolate against a fixture payload,
817    /// with mocked host ops — the author's inner test loop.
818    ///
819    /// Exit codes: 0 = ran; 3 = the `when` predicate did not match (nothing would
820    /// fire); 4 = the guest errored; 1 = a config/harness error.
821    #[command(long_about = "\
822Run a compiled function against a fixture payload in a real V8 isolate.
823
824The module is loaded exactly as the server loads it (from the compiled schema's
825module_dir); host ops are mocked so no live server, database, or network is needed.
826Every host-op call the function makes is printed.
827
828EXAMPLES:
829    fraiseql functions invoke notifyApproved --payload event.json
830    fraiseql functions invoke notifyApproved --payload event.json --explain
831    fraiseql functions invoke syncDeal --payload deal.json \\
832        --mock-http http.json --mock-query query.json")]
833    Invoke {
834        /// The function name (matches a definition in the compiled schema).
835        name: String,
836
837        /// Path to the fixture payload JSON. For after:mutation / after:capture:
838        /// `{ \"event_kind\": \"update\", \"old\": {…}, \"new\": {…} }` (a bare
839        /// object is treated as an insert's `new` image).
840        #[arg(long)]
841        payload: std::path::PathBuf,
842
843        /// Path to schema.compiled.json.
844        #[arg(long, default_value = "schema.compiled.json")]
845        schema: std::path::PathBuf,
846
847        /// Canned HTTP responses (JSON array of `{url_contains, method?, status?, body?}`);
848        /// a request matching none fails loud.
849        #[arg(long)]
850        mock_http: Option<std::path::PathBuf>,
851
852        /// Canned query responses (JSON array of `{query_contains?, response}`) for the
853        /// `fraiseql_query` bridge; a query matching none fails loud.
854        #[arg(long)]
855        mock_query: Option<std::path::PathBuf>,
856
857        /// Inject a fixed idempotency token the guest reads via the host op.
858        #[arg(long)]
859        idempotency_token: Option<String>,
860
861        /// Print why the `when` predicates did or did not match this payload.
862        #[arg(long)]
863        explain: bool,
864    },
865}
866
867/// `fraiseql perf` subcommands.
868#[derive(Subcommand)]
869pub(crate) enum PerfCommands {
870    /// Flag mutations whose latency regressed between a baseline and a recent
871    /// window, per `(object_type, modification_type)`.
872    ///
873    /// Only rows carrying the current `duration_calc_version` are compared, and
874    /// latency is never aggregated across modification types — so a shift in the
875    /// operation mix cannot mask a regression as a false improvement. Exits 0 even
876    /// when regressions are found (it is a report); pass `--fail-on-regression`
877    /// for CI gating.
878    RegressionScan {
879        /// PostgreSQL URL (defaults to `fraiseql.toml` / `DATABASE_URL`).
880        #[arg(long, value_name = "DATABASE_URL")]
881        database: Option<String>,
882
883        /// Recent window size, in days.
884        #[arg(long, default_value_t = 7)]
885        recent_days: i64,
886
887        /// Baseline window size (immediately before the recent window), in days.
888        #[arg(long, default_value_t = 7)]
889        baseline_days: i64,
890
891        /// Minimum comparable samples required on each side; thinner groups are
892        /// skipped rather than flagged.
893        #[arg(long, default_value_t = 20)]
894        min_samples: usize,
895
896        /// Minimum p50 increase to flag, in percent.
897        #[arg(long, default_value_t = 25.0)]
898        threshold_pct: f64,
899
900        /// Minimum absolute p50 increase to flag, in milliseconds (the noise floor).
901        #[arg(long, default_value_t = 5.0)]
902        min_delta_ms: f64,
903
904        /// Restrict the scan to a single object_type.
905        #[arg(long, value_name = "TYPE")]
906        object_type: Option<String>,
907
908        /// Exit non-zero when any regression is found (for CI gating).
909        #[arg(long)]
910        fail_on_regression: bool,
911    },
912
913    /// Ad-hoc forensic reads of the change-log.
914    Explore {
915        #[command(subcommand)]
916        command: PerfExploreCommands,
917    },
918}
919
920/// `fraiseql perf explore` subcommands — read-only views over comparable (v2)
921/// change-log rows in a trailing window.
922#[derive(Subcommand)]
923pub(crate) enum PerfExploreCommands {
924    /// The slowest individual mutations, slowest first.
925    Slowest {
926        /// PostgreSQL URL (defaults to `fraiseql.toml` / `DATABASE_URL`).
927        #[arg(long, value_name = "DATABASE_URL")]
928        database: Option<String>,
929
930        /// Trailing window to scan, in days.
931        #[arg(long, default_value_t = 7)]
932        days: i32,
933
934        /// Restrict to a single object_type.
935        #[arg(long, value_name = "TYPE")]
936        object_type: Option<String>,
937
938        /// Maximum rows to return.
939        #[arg(long, default_value_t = 20)]
940        limit: usize,
941    },
942
943    /// `duration_ms` completeness (NULL / pre-fix rates), per operation.
944    NullRate {
945        /// PostgreSQL URL (defaults to `fraiseql.toml` / `DATABASE_URL`).
946        #[arg(long, value_name = "DATABASE_URL")]
947        database: Option<String>,
948
949        /// Trailing window to scan, in days.
950        #[arg(long, default_value_t = 7)]
951        days: i32,
952
953        /// Restrict to a single object_type.
954        #[arg(long, value_name = "TYPE")]
955        object_type: Option<String>,
956    },
957
958    /// Latency percentiles (p50/p95/p99/max), per operation.
959    Summary {
960        /// PostgreSQL URL (defaults to `fraiseql.toml` / `DATABASE_URL`).
961        #[arg(long, value_name = "DATABASE_URL")]
962        database: Option<String>,
963
964        /// Trailing window to scan, in days.
965        #[arg(long, default_value_t = 7)]
966        days: i32,
967
968        /// Restrict to a single object_type.
969        #[arg(long, value_name = "TYPE")]
970        object_type: Option<String>,
971    },
972}
973
974#[derive(Subcommand)]
975pub(crate) enum ValidateCommands {
976    /// Validate that declared fact tables match database schema
977    Facts {
978        /// Schema.json file path
979        #[arg(short, long, value_name = "SCHEMA")]
980        schema: String,
981
982        /// Database connection string
983        // Long-only: `-d` is the global `--debug` short (#650).
984        #[arg(long, value_name = "DATABASE_URL")]
985        database: String,
986    },
987}
988
989#[derive(Subcommand)]
990pub(crate) enum GenerateClientCommands {
991    /// Generate a TypeScript client (interfaces + typed query/mutation functions).
992    Typescript {
993        /// Path to schema.compiled.json (auto-detected from conventional
994        /// locations if omitted).
995        #[arg(long, value_name = "SCHEMA")]
996        schema: Option<std::path::PathBuf>,
997
998        /// Output directory for the generated client.
999        #[arg(long, value_name = "DIR")]
1000        out: std::path::PathBuf,
1001
1002        /// Overwrite an existing generated client in the output directory.
1003        #[arg(long, default_value_t = false)]
1004        force: bool,
1005    },
1006
1007    /// Generate a Python client (TypedDicts + typed query/mutation functions;
1008    /// requires Python >= 3.12).
1009    Python {
1010        /// Path to schema.compiled.json (auto-detected from conventional
1011        /// locations if omitted).
1012        #[arg(long, value_name = "SCHEMA")]
1013        schema: Option<std::path::PathBuf>,
1014
1015        /// Output directory for the generated client (becomes a Python package).
1016        #[arg(long, value_name = "DIR")]
1017        out: std::path::PathBuf,
1018
1019        /// Overwrite an existing generated client in the output directory.
1020        #[arg(long, default_value_t = false)]
1021        force: bool,
1022    },
1023
1024    /// Generate a Go client (structs + typed query/mutation functions; requires
1025    /// Go >= 1.21 for the Relay `Connection[T]`).
1026    Go {
1027        /// Path to schema.compiled.json (auto-detected from conventional
1028        /// locations if omitted).
1029        #[arg(long, value_name = "SCHEMA")]
1030        schema: Option<std::path::PathBuf>,
1031
1032        /// Output directory for the generated client (becomes package
1033        /// `fraiseqlclient`).
1034        #[arg(long, value_name = "DIR")]
1035        out: std::path::PathBuf,
1036
1037        /// Overwrite an existing generated client in the output directory.
1038        #[arg(long, default_value_t = false)]
1039        force: bool,
1040    },
1041
1042    /// Generate a Rust client (serde types + typed query/mutation functions;
1043    /// depends only on serde and serde_json).
1044    Rust {
1045        /// Path to schema.compiled.json (auto-detected from conventional
1046        /// locations if omitted).
1047        #[arg(long, value_name = "SCHEMA")]
1048        schema: Option<std::path::PathBuf>,
1049
1050        /// Output directory for the generated client (becomes a module tree with
1051        /// its own `mod.rs`).
1052        #[arg(long, value_name = "DIR")]
1053        out: std::path::PathBuf,
1054
1055        /// Overwrite an existing generated client in the output directory.
1056        #[arg(long, default_value_t = false)]
1057        force: bool,
1058    },
1059}
1060
1061#[derive(Subcommand)]
1062pub(crate) enum FederationCommands {
1063    /// Draw the federation the given subgraphs form
1064    Graph {
1065        /// Each subgraph's schema.compiled.json
1066        #[arg(value_name = "SCHEMA", required = true, num_args = 1..)]
1067        schema: Vec<String>,
1068
1069        /// Output format (json, dot, mermaid)
1070        #[arg(short, long, value_name = "FORMAT", default_value = "json")]
1071        format: String,
1072    },
1073
1074    /// Print a subgraph's federation SDL, exactly as `_service { sdl }` serves it
1075    ///
1076    /// Reads the compiled schema; no server, database or credentials are needed.
1077    #[cfg(feature = "federation")]
1078    Sdl {
1079        /// Path to the subgraph's schema.compiled.json
1080        #[arg(value_name = "SCHEMA")]
1081        schema: std::path::PathBuf,
1082
1083        /// Write the SDL to this file instead of stdout
1084        #[arg(short, long, value_name = "FILE")]
1085        output: Option<std::path::PathBuf>,
1086    },
1087
1088    /// Validate a subgraph's federation entities and keys
1089    Check {
1090        /// Path to local schema.compiled.json
1091        #[arg(value_name = "SCHEMA")]
1092        schema: String,
1093
1094        /// Another subgraph's schema.compiled.json to compare with (@key agreement,
1095        /// field sharing)
1096        #[arg(short, long, value_name = "OTHER_SCHEMA")]
1097        against: Option<String>,
1098
1099        /// Output result as JSON
1100        #[arg(long)]
1101        json: bool,
1102    },
1103}
1104
1105#[derive(Subcommand)]
1106pub(crate) enum IntrospectCommands {
1107    /// Introspect database for fact tables (tf_* tables)
1108    Facts {
1109        /// Database connection string
1110        // Long-only: `-d` is the global `--debug` short (#650).
1111        #[arg(long, value_name = "DATABASE_URL")]
1112        database: String,
1113
1114        /// Output format (python, json)
1115        #[arg(short, long, value_name = "FORMAT", default_value = "python")]
1116        format: String,
1117    },
1118}
1119
1120#[derive(Subcommand)]
1121pub(crate) enum SchemaCommands {
1122    /// Display field-level security metadata from a running server
1123    Metadata {
1124        /// Server base URL
1125        #[arg(
1126            short,
1127            long,
1128            value_name = "URL",
1129            default_value = "http://localhost:8080"
1130        )]
1131        server: String,
1132
1133        /// Bearer token for authentication
1134        #[arg(short, long, value_name = "TOKEN")]
1135        token: Option<String>,
1136    },
1137}
1138
1139#[derive(Subcommand)]
1140pub(crate) enum MigrateCommands {
1141    /// Apply pending migrations
1142    Up {
1143        /// Database connection URL
1144        #[arg(long, value_name = "DATABASE_URL")]
1145        database: Option<String>,
1146
1147        /// Migration directory
1148        #[arg(long, value_name = "DIR")]
1149        dir: Option<String>,
1150    },
1151
1152    /// Roll back migrations
1153    Down {
1154        /// Database connection URL
1155        #[arg(long, value_name = "DATABASE_URL")]
1156        database: Option<String>,
1157
1158        /// Migration directory
1159        #[arg(long, value_name = "DIR")]
1160        dir: Option<String>,
1161
1162        /// Number of migrations to roll back
1163        #[arg(long, default_value = "1")]
1164        steps: u32,
1165    },
1166
1167    /// Show migration status
1168    Status {
1169        /// Database connection URL
1170        #[arg(long, value_name = "DATABASE_URL")]
1171        database: Option<String>,
1172
1173        /// Migration directory
1174        #[arg(long, value_name = "DIR")]
1175        dir: Option<String>,
1176    },
1177
1178    /// Create a new migration file
1179    ///
1180    /// Delegates to `confiture migrate generate`, like `generate`; kept as the
1181    /// verb the examples above use.
1182    Create {
1183        /// Migration name
1184        #[arg(value_name = "NAME")]
1185        name: String,
1186
1187        /// Migration directory
1188        #[arg(long, value_name = "DIR")]
1189        dir: Option<String>,
1190    },
1191
1192    /// Generate a new migration from schema diff
1193    ///
1194    /// Delegates to `confiture migrate generate`.
1195    /// Creates a timestamped migration file.
1196    Generate {
1197        /// Migration name
1198        #[arg(value_name = "NAME")]
1199        name: String,
1200
1201        /// Migration directory
1202        #[arg(long, value_name = "DIR")]
1203        dir: Option<String>,
1204    },
1205
1206    /// Validate migration files for naming, idempotency, and drift
1207    ///
1208    /// Delegates to `confiture migrate validate`.
1209    /// Checks naming conventions, idempotency, and schema drift.
1210    Validate {
1211        /// Migration directory
1212        #[arg(long, value_name = "DIR")]
1213        dir: Option<String>,
1214    },
1215
1216    /// Pre-deploy safety check on pending migrations
1217    ///
1218    /// Delegates to `confiture migrate preflight`.
1219    /// Verifies reversibility, detects non-transactional statements, checks checksums.
1220    Preflight {
1221        /// Migration directory
1222        #[arg(long, value_name = "DIR")]
1223        dir: Option<String>,
1224    },
1225}