Skip to main content

fraiseql_cli/commands/
compile.rs

1//! Schema compilation command
2//!
3//! Compiles schema.json (from Python/TypeScript/etc.) into optimized schema.compiled.json
4
5use std::{fs, path::Path, process::Command};
6
7use anyhow::{Context, Result};
8use fraiseql_core::schema::{
9    CURRENT_SCHEMA_FORMAT_VERSION, CompiledSchema, FieldType, InputStyle, MutationOperation,
10    NamingConvention, canonicalize_json,
11};
12use tracing::{info, warn};
13
14use crate::{
15    config::TomlProjectConfig,
16    schema::{
17        ConvertOptions, IntermediateSchema, OptimizationReport, SchemaConverter, SchemaOptimizer,
18        SchemaValidator,
19        database_validator::validate_schema_against_database,
20        mutation_contract::{Severity, validate_mutation_contract},
21        pg_catalog::PgCatalog,
22    },
23};
24
25/// Input source configuration for schema compilation.
26#[derive(Debug, Default)]
27pub struct CompileOptions<'a> {
28    /// Path to `fraiseql.toml` (TOML workflow) or `schema.json` (legacy).
29    pub input:          &'a str,
30    /// Optional path to `types.json` (TOML workflow, backward compat).
31    pub types:          Option<&'a str>,
32    /// Optional directory for schema file auto-discovery.
33    pub schema_dir:     Option<&'a str>,
34    /// Explicit type file paths (highest priority).
35    pub type_files:     Vec<String>,
36    /// Explicit query file paths.
37    pub query_files:    Vec<String>,
38    /// Explicit mutation file paths.
39    pub mutation_files: Vec<String>,
40    /// Optional database URL for indexed column validation.
41    pub database:       Option<&'a str>,
42    /// Skip embedding content hash in compiled schema (for test fixtures).
43    pub skip_hash:      bool,
44}
45
46impl<'a> CompileOptions<'a> {
47    /// Create new compile options with just the input path.
48    #[must_use]
49    pub fn new(input: &'a str) -> Self {
50        Self {
51            input,
52            ..Default::default()
53        }
54    }
55
56    /// Set the types path.
57    #[must_use]
58    pub fn with_types(mut self, types: &'a str) -> Self {
59        self.types = Some(types);
60        self
61    }
62
63    /// Set the schema directory for auto-discovery.
64    #[must_use]
65    pub fn with_schema_dir(mut self, schema_dir: &'a str) -> Self {
66        self.schema_dir = Some(schema_dir);
67        self
68    }
69
70    /// Set the database URL for validation.
71    #[must_use]
72    pub fn with_database(mut self, database: &'a str) -> Self {
73        self.database = Some(database);
74        self
75    }
76}
77
78/// Select and execute the appropriate schema-loading strategy for TOML-based workflows.
79///
80/// Tries strategies in priority order:
81/// 1. Explicit file lists (highest priority)
82/// 2. Directory auto-discovery
83/// 3. Single types file (backward-compatible)
84/// 4. Domain discovery → TOML includes → TOML-only (fallback sequence)
85#[allow(clippy::cognitive_complexity)] // Reason: multi-strategy schema discovery with fallback chain
86fn load_intermediate_schema(
87    toml_path: &str,
88    type_files: &[String],
89    query_files: &[String],
90    mutation_files: &[String],
91    schema_dir: Option<&str>,
92    types_path: Option<&str>,
93) -> Result<IntermediateSchema> {
94    if !type_files.is_empty() || !query_files.is_empty() || !mutation_files.is_empty() {
95        info!("Mode: Explicit file lists");
96        return crate::schema::SchemaMerger::merge_explicit_files(
97            toml_path,
98            type_files,
99            query_files,
100            mutation_files,
101        )
102        .context("Failed to load explicit schema files");
103    }
104    if let Some(dir) = schema_dir {
105        info!("Mode: Auto-discovery from directory: {}", dir);
106        return crate::schema::SchemaMerger::merge_from_directory(toml_path, dir)
107            .context("Failed to load schema from directory");
108    }
109    if let Some(types) = types_path {
110        info!("Mode: Language + TOML (types.json + fraiseql.toml)");
111        return crate::schema::SchemaMerger::merge_files(types, toml_path)
112            .context("Failed to merge types.json with TOML");
113    }
114    info!("Mode: TOML-based (checking for domain discovery...)");
115    if let Ok(schema) = crate::schema::SchemaMerger::merge_from_domains(toml_path) {
116        return Ok(schema);
117    }
118    info!("No domains configured, checking for TOML includes...");
119    if let Ok(schema) = crate::schema::SchemaMerger::merge_with_includes(toml_path) {
120        return Ok(schema);
121    }
122    info!("No includes configured, using TOML-only definitions");
123    crate::schema::SchemaMerger::merge_toml_only(toml_path)
124        .context("Failed to load schema from TOML")
125}
126
127/// Compile a schema to `CompiledSchema` without writing to disk.
128///
129/// This is the core compilation logic, shared between `compile` (which writes to disk)
130/// and `run` (which serves in-memory without any file artifacts).
131///
132/// # Arguments
133///
134/// * `opts` - Compilation options including input paths and configuration
135///
136/// # Errors
137///
138/// Returns error if input is missing, parsing fails, validation fails, or the database
139/// connection fails (when `database` is provided).
140#[allow(clippy::cognitive_complexity)] // Reason: end-to-end compilation pipeline with validation, introspection, and output stages
141pub async fn compile_to_schema(
142    opts: CompileOptions<'_>,
143) -> Result<(CompiledSchema, OptimizationReport)> {
144    info!("Compiling schema: {}", opts.input);
145
146    // 1. Determine workflow based on input file and options
147    let input_path = Path::new(opts.input);
148    if !input_path.exists() {
149        anyhow::bail!("Input file not found: {}", opts.input);
150    }
151
152    // Load schema based on file type and options
153    let is_toml = input_path
154        .extension()
155        .and_then(|ext| ext.to_str())
156        .is_some_and(|ext| ext.eq_ignore_ascii_case("toml"));
157    let mut intermediate: IntermediateSchema = if is_toml {
158        info!("Using TOML-based workflow");
159        load_intermediate_schema(
160            opts.input,
161            &opts.type_files,
162            &opts.query_files,
163            &opts.mutation_files,
164            opts.schema_dir,
165            opts.types,
166        )?
167    } else {
168        // Legacy JSON workflow
169        info!("Using legacy JSON workflow");
170        let schema_json = fs::read_to_string(input_path).context("Failed to read schema.json")?;
171
172        // 2. Parse JSON into IntermediateSchema (language-agnostic format)
173        info!("Parsing intermediate schema...");
174        serde_json::from_str(&schema_json).context("Failed to parse schema.json")?
175    };
176
177    // 2a. Load and apply security configuration from fraiseql.toml if it exists.
178    // Skip when the input itself is a TomlSchema file: in that case the security
179    // settings are embedded in the TomlSchema, and the CWD fraiseql.toml uses a
180    // different TOML format (TomlSchema vs TomlProjectConfig) that is not compatible.
181    // Opt-in mutation-error-union synthesis, read from [fraiseql.mutations] below.
182    let mut auto_error_union = false;
183    // Casing acronyms from [fraiseql.naming], added on top of the built-in defaults.
184    let mut naming_acronyms: Vec<String> = Vec::new();
185    // Per-operation @cost weight overrides from [fraiseql.cost_weights] (#379).
186    let mut operation_cost_weights: std::collections::HashMap<String, usize> =
187        std::collections::HashMap::new();
188    // GraphQL surface convention for the legacy JSON (Workflow-B) path. Defaults
189    // to camelCase (snake_case DB, camelCase client surface + input recasing);
190    // [fraiseql.naming] convention = "preserve" restores the as-authored names.
191    // The TomlSchema path carries its own naming_convention via the merger and is
192    // left untouched (see the `if !is_toml` apply below).
193    let mut naming_convention = NamingConvention::CamelCase;
194    if !is_toml && Path::new("fraiseql.toml").exists() {
195        info!("Loading security configuration from fraiseql.toml...");
196        match TomlProjectConfig::from_file("fraiseql.toml") {
197            Ok(config) => {
198                info!("Validating security configuration...");
199                config.validate()?;
200
201                auto_error_union = config.fraiseql.mutations.auto_error_union;
202                naming_acronyms.clone_from(&config.fraiseql.naming.acronyms);
203                operation_cost_weights.clone_from(&config.fraiseql.cost_weights);
204                naming_convention = config.fraiseql.naming.convention;
205
206                info!("Applying security configuration to schema...");
207                // Merge security config into intermediate schema
208                let mut security_json = config.fraiseql.security.to_json();
209
210                // Embed tenancy configuration into the security section
211                if !matches!(
212                    config.fraiseql.tenancy.mode,
213                    crate::config::security::TenancyModeConfig::None
214                ) {
215                    security_json["tenancy"] = config.fraiseql.tenancy.to_json();
216                }
217
218                intermediate.security = Some(security_json);
219
220                info!("Security configuration applied successfully");
221            },
222            Err(e) => {
223                anyhow::bail!(
224                    "Failed to parse fraiseql.toml: {e}\n\
225                     Fix the configuration file or remove it to use defaults."
226                );
227            },
228        }
229    } else {
230        info!("No fraiseql.toml found, using default security configuration");
231    }
232
233    // Install the project's casing acronyms so compile-time key inference
234    // (native-column resolution, DDL) agrees with the runtime. Defaults apply
235    // when none are configured.
236    fraiseql_core::utils::casing::set_runtime_acronyms(&naming_acronyms);
237
238    // Apply the naming convention to the legacy JSON (Workflow-B) path. The
239    // JSON schema never carries one, so without this it would fall to the enum
240    // default (Preserve); Workflow-B instead defaults to CamelCase (overridable
241    // via [fraiseql.naming].convention). The TomlSchema path already carries its
242    // own convention from the merger, so it is left untouched.
243    if !is_toml {
244        intermediate.naming_convention = naming_convention;
245    }
246
247    // 2b. Validate @tenant_id annotations when tenancy mode is "row".
248    // Extract tenancy config from the already-embedded security JSON.
249    let tenancy_row_claim: Option<String> = intermediate.security.as_ref().and_then(|sec| {
250        let tenancy = sec.get("tenancy")?;
251        let mode = tenancy.get("mode").and_then(|m| m.as_str()).unwrap_or("none");
252        if mode == "row" {
253            Some(
254                tenancy
255                    .get("tenantClaim")
256                    .and_then(|c| c.as_str())
257                    .unwrap_or("tenant_id")
258                    .to_string(),
259            )
260        } else {
261            None
262        }
263    });
264    if let Some(tenant_claim) = &tenancy_row_claim {
265        info!("Validating @tenant_id annotations for row-isolation tenancy...");
266        crate::schema::converter::tenancy::validate_tenant_annotations(
267            &mut intermediate,
268            tenant_claim,
269        )
270        .context("@tenant_id validation failed")?;
271    }
272
273    // 3. Validate intermediate schema
274    info!("Validating schema structure...");
275    let validation_report =
276        SchemaValidator::validate(&intermediate).context("Failed to validate schema")?;
277
278    if !validation_report.is_valid() {
279        validation_report.print();
280        anyhow::bail!("Schema validation failed with {} error(s)", validation_report.error_count());
281    }
282
283    // Print warnings if any
284    if validation_report.warning_count() > 0 {
285        validation_report.print();
286    }
287
288    // 4. Convert to CompiledSchema (validates and normalizes)
289    info!("Converting to compiled format...");
290    let mut schema =
291        SchemaConverter::convert_with_options(intermediate, &ConvertOptions { auto_error_union })
292            .context("Failed to convert schema to compiled format")?;
293
294    // Carry the project's casing acronyms into the compiled schema so the runtime
295    // installs them at boot (see `fraiseql_db::utils::set_runtime_acronyms`).
296    schema.naming_acronyms = naming_acronyms;
297
298    // Carry the project's @cost weight overrides (#379) into the compiled schema so
299    // the runtime per-tenant cost-budget check can apply them. Non-clobbering: only
300    // overwrite when configured, leaving any value a future merger path may set.
301    if !operation_cost_weights.is_empty() {
302        schema.operation_cost_weights = operation_cost_weights;
303    }
304
305    // 5. Optimize schema and generate SQL hints (mutates schema in place, report for display)
306    info!("Analyzing schema for optimization opportunities...");
307    let report = SchemaOptimizer::optimize(&mut schema).context("Failed to optimize schema")?;
308
309    // 5a. Stamp schema format version for runtime compatibility checks.
310    schema.schema_format_version = Some(CURRENT_SCHEMA_FORMAT_VERSION);
311
312    // 5b-pre. Infer native_columns for ID/UUID-typed arguments on JSONB-backed queries.
313    // DB introspection (step 5b) overrides these inferred values when `--database` is provided.
314    infer_native_columns_from_arg_types(&mut schema);
315
316    // 5b. Optional: Validate indexed columns and native columns against database.
317    if let Some(db_url) = opts.database {
318        info!("Validating indexed columns against database...");
319        validate_indexed_columns(&schema, db_url).await?;
320
321        info!("Validating native columns for direct query arguments...");
322        let pg_introspector = build_postgres_introspector(db_url)
323            .context("Failed to connect for native column validation")?;
324        let db_report = validate_schema_against_database(&schema, &pg_introspector).await?;
325        for w in &db_report.warnings {
326            warn!("{w}");
327        }
328        // Patch QueryDefinitions with DB-discovered native_columns, overriding inferred values.
329        for query in &mut schema.queries {
330            if let Some(cols) = db_report.native_columns.get(&query.name) {
331                query.native_columns = cols.clone();
332            }
333        }
334
335        // Mutation call/response contract (#384 item 3: inject_params resolve to real
336        // function arguments). PostgreSQL-only — the catalog reads `pg_proc`; other
337        // dialects are validated structurally above. Advisory like the rest of
338        // `compile --database`: findings warn, they never fail the compile.
339        if db_url.starts_with("postgres") {
340            info!("Validating mutation contract against the database...");
341            let catalog = PgCatalog::connect(db_url)
342                .context("Failed to connect for mutation-contract validation")?;
343            let contract = validate_mutation_contract(&schema, &catalog).await?;
344            for m in &contract.mutations {
345                for v in &m.violations {
346                    let kind = match v.severity() {
347                        Severity::Error => "contract error",
348                        Severity::Warn => "contract warning",
349                    };
350                    warn!("mutation `{}` (sql_source: {}): {v} [{kind}]", m.mutation, m.sql_source);
351                }
352            }
353        }
354    } else {
355        // Warn for queries that still have unresolved direct arguments after inference.
356        // Arguments already covered by native_columns inference are not warned about.
357        for query in &schema.queries {
358            if query.sql_source.is_none() {
359                continue;
360            }
361            let unresolved: Vec<_> = query
362                .arguments
363                .iter()
364                .filter(|a| !NATIVE_COLUMN_SKIP_ARGS.contains(&a.name.as_str()))
365                .filter(|a| !query.native_columns.contains_key(&a.name))
366                .collect();
367            if !unresolved.is_empty() {
368                let names: Vec<_> = unresolved.iter().map(|a| a.name.as_str()).collect();
369                warn!(
370                    "query `{}`: argument(s) {:?} on `{}` could not be resolved to native \
371                     columns — no --database URL provided. These filters will use JSONB \
372                     extraction. Provide --database or annotate with native_columns.",
373                    query.name,
374                    names,
375                    query.sql_source.as_deref().unwrap_or("?"),
376                );
377            }
378        }
379    }
380
381    // 5c. Warn when SQLite is the target but the schema uses features SQLite doesn't support.
382    check_sqlite_compatibility_warnings(&schema, opts.input, is_toml, opts.database);
383
384    // 5d. Warn when mutations have wide invalidation fan-out (HOT update pressure).
385    warn_wide_cascade_mutations(&schema);
386
387    // 5e. Warn when a `preserve` schema would silently forward camelCase input keys
388    // to snake_case SQL functions on the single-JSONB mutation path (#456).
389    warn_jsonb_preserve_mismatch(&schema);
390
391    Ok((schema, report))
392}
393
394/// Run the compile command
395///
396/// # Arguments
397///
398/// * `input` - Path to fraiseql.toml (TOML) or schema.json (legacy)
399/// * `types` - Optional path to types.json (when using TOML workflow)
400/// * `schema_dir` - Optional directory for auto-discovery of schema files
401/// * `type_files` - Optional vector of explicit type file paths
402/// * `query_files` - Optional vector of explicit query file paths
403/// * `mutation_files` - Optional vector of explicit mutation file paths
404/// * `output` - Path to write schema.compiled.json
405/// * `check` - If true, validate only without writing output
406/// * `database` - Optional database URL for indexed column validation
407/// * `emit_ddl` - Optional directory to write `CREATE TABLE` DDL files (confiture format)
408/// * `check_migrations` - If true, run `confiture migrate validate` after compilation
409/// * `skip_hash` - Skip embedding content hash (for test fixtures)
410///
411/// # Errors
412///
413/// Returns error if:
414/// - Input file doesn't exist or can't be read
415/// - JSON/TOML parsing fails
416/// - Schema validation fails
417/// - Output file can't be written
418/// - Database connection fails (when database URL is provided)
419/// - DDL output directory cannot be created (when `emit_ddl` is provided)
420/// - `confiture` is not installed (when `check_migrations` is true)
421/// - Migration drift detected (when `check_migrations` is true)
422#[allow(clippy::too_many_arguments)]
423// Reason: run() is the CLI entry point that receives individual args from clap; keeping them
424// separate for clarity
425#[doc(hidden)] // Internal-pub: CLI entry point dispatched by runner.rs; not a stable downstream API.
426pub async fn run(
427    input: &str,
428    types: Option<&str>,
429    schema_dir: Option<&str>,
430    type_files: Vec<String>,
431    query_files: Vec<String>,
432    mutation_files: Vec<String>,
433    output: &str,
434    check: bool,
435    database: Option<&str>,
436    emit_ddl: Option<&str>,
437    check_migrations: bool,
438    skip_hash: bool,
439) -> Result<()> {
440    // Defense-in-depth: never write the compiled output over the input schema.
441    // The removed `serve` command did exactly this (H23) by deriving an output
442    // path identical to its input via a faulty extension swap. `--check` writes
443    // nothing, so the guard only applies to a real write.
444    if !check && Path::new(output) == Path::new(input) {
445        anyhow::bail!(
446            "Refusing to write compiled output over the input file '{input}'. \
447             Use a distinct --output path (e.g. schema.compiled.json)."
448        );
449    }
450
451    let opts = CompileOptions {
452        input,
453        types,
454        schema_dir,
455        type_files,
456        query_files,
457        mutation_files,
458        database,
459        skip_hash,
460    };
461    let (schema, optimization_report) = compile_to_schema(opts).await?;
462
463    // If check-only mode, stop here
464    if check {
465        println!("✓ Schema is valid");
466        println!("  Types: {}", schema.types.len());
467        println!("  Queries: {}", schema.queries.len());
468        println!("  Mutations: {}", schema.mutations.len());
469        optimization_report.print();
470        return Ok(());
471    }
472
473    // Write compiled schema
474    info!("Writing compiled schema to: {output}");
475    let output_json = if skip_hash {
476        serde_json::to_string_pretty(&schema).context("Failed to serialize compiled schema")?
477    } else {
478        use sha2::{Digest, Sha256};
479
480        let body =
481            serde_json::to_string_pretty(&schema).context("Failed to serialize compiled schema")?;
482        let value: serde_json::Value = serde_json::from_str(&body)?;
483        // Canonicalize (recursively sort keys) before hashing — matches from_json verifier
484        let canonical = serde_json::to_string_pretty(&canonicalize_json(&value))?;
485        let hash = Sha256::digest(canonical.as_bytes());
486        let hash_hex = hex::encode(&hash[..16]);
487
488        let obj = value.as_object().context("schema must serialise as JSON object")?;
489
490        // Insert _content_hash as the first field (serde_json::Map preserves insertion order)
491        let mut new_obj = serde_json::Map::new();
492        new_obj.insert("_content_hash".to_string(), serde_json::Value::String(hash_hex));
493        for (k, v) in obj {
494            new_obj.insert(k.clone(), v.clone());
495        }
496        serde_json::to_string_pretty(&serde_json::Value::Object(new_obj))?
497    };
498
499    fs::write(output, output_json).context("Failed to write compiled schema")?;
500
501    // Success message
502    println!("✓ Schema compiled successfully");
503    println!("  Input:  {input}");
504    println!("  Output: {output}");
505    println!("  Types: {}", schema.types.len());
506    println!("  Queries: {}", schema.queries.len());
507    println!("  Mutations: {}", schema.mutations.len());
508    optimization_report.print();
509
510    // Emit DDL to directory if requested
511    if let Some(ddl_dir) = emit_ddl {
512        emit_ddl_to_dir(&schema, ddl_dir)?;
513    }
514
515    // Check for migration drift if requested
516    if check_migrations {
517        run_check_migrations(&schema)?;
518    }
519
520    Ok(())
521}
522
523/// Emit `CREATE TABLE` DDL files for all compiled schema types to `output_dir`.
524///
525/// Each type produces one `<type_snake_case>.sql` file containing a `CREATE TABLE IF NOT EXISTS`
526/// statement. The output directory is created if it does not already exist.
527///
528/// Output is compatible with confiture's `db/schema/` directory format, so that
529/// `fraiseql migrate generate` can auto-detect drift between the compiled schema and the
530/// current migrations.
531///
532/// # Errors
533///
534/// Returns an error if the output directory cannot be created, or if any DDL file
535/// cannot be written.
536pub fn emit_ddl_to_dir(schema: &CompiledSchema, output_dir: &str) -> Result<()> {
537    fs::create_dir_all(output_dir)
538        .context(format!("Failed to create DDL output directory: {output_dir}"))?;
539
540    let mut count = 0;
541    for type_def in &schema.types {
542        let table_name = to_snake_case(type_def.name.as_str());
543        let ddl = build_create_table_ddl(&table_name, type_def);
544
545        let file_path = Path::new(output_dir).join(format!("{table_name}.sql"));
546        fs::write(&file_path, ddl)
547            .context(format!("Failed to write DDL for type '{}'", type_def.name))?;
548        count += 1;
549    }
550
551    println!("✓ DDL emitted to {output_dir}/ ({count} table(s))");
552    Ok(())
553}
554
555/// Delegate to `confiture migrate validate` for migration drift detection.
556///
557/// Emits DDL to a temporary directory, then invokes confiture. Exits non-zero when
558/// drift is detected, printing a friendly remediation hint.
559///
560/// # Errors
561///
562/// Returns an error if confiture is not installed, if the temp directory cannot be
563/// created, or if confiture reports drift or validation failures.
564fn run_check_migrations(schema: &CompiledSchema) -> Result<()> {
565    let tmp_dir = tempfile::tempdir().context("Failed to create temporary DDL directory")?;
566    let tmp_path = tmp_dir.path().to_str().context("Temp directory path is not valid UTF-8")?;
567
568    emit_ddl_to_dir(schema, tmp_path)?;
569
570    info!("Running confiture migrate validate for drift detection...");
571
572    let status = Command::new("confiture").args(["migrate", "validate"]).status();
573
574    match status {
575        Err(_) => {
576            // confiture not installed — warn but don't fail the build
577            eprintln!(
578                "WARN: confiture is not installed; skipping migration drift check.\n\
579                 Install it with: cargo install confiture"
580            );
581            Ok(())
582        },
583        Ok(s) if s.success() => {
584            println!("✓ No migration drift detected.");
585            Ok(())
586        },
587        Ok(_) => {
588            eprintln!(
589                "WARN: compiled schema diverges from database — run fraiseql migrate generate"
590            );
591            anyhow::bail!(
592                "Migration drift detected. Run `fraiseql migrate generate` to create a migration."
593            )
594        },
595    }
596}
597
598/// Convert a `PascalCase` or `camelCase` type name to `snake_case`.
599pub(crate) fn to_snake_case(name: &str) -> String {
600    let mut result = String::with_capacity(name.len() + 4);
601    for (i, ch) in name.chars().enumerate() {
602        if ch.is_uppercase() && i > 0 {
603            result.push('_');
604        }
605        result.extend(ch.to_lowercase());
606    }
607    result
608}
609
610/// Generate a `CREATE TABLE IF NOT EXISTS` DDL statement for a compiled type definition.
611fn build_create_table_ddl(
612    table_name: &str,
613    type_def: &fraiseql_core::schema::TypeDefinition,
614) -> String {
615    let mut lines: Vec<String> = Vec::new();
616    lines.push("-- Generated by fraiseql compile --emit-ddl".to_string());
617    lines.push(format!("-- Type: {}", type_def.name));
618    if let Some(desc) = &type_def.description {
619        lines.push(format!("-- {desc}"));
620    }
621    lines.push(String::new());
622    lines.push(format!("CREATE TABLE IF NOT EXISTS tb_{table_name} ("));
623
624    let col_lines: Vec<String> = type_def
625        .fields
626        .iter()
627        .map(|field| {
628            let col_name = to_snake_case(field.name.as_str());
629            let pg_type = field_type_to_pg(&field.field_type);
630            let nullable = if field.nullable { "" } else { " NOT NULL" };
631            format!("    {col_name} {pg_type}{nullable}")
632        })
633        .collect();
634
635    let last = col_lines.len().saturating_sub(1);
636    for (i, col) in col_lines.iter().enumerate() {
637        if i < last {
638            lines.push(format!("{col},"));
639        } else {
640            lines.push(col.clone());
641        }
642    }
643
644    lines.push(");".to_string());
645    lines.push(String::new());
646    lines.join("\n")
647}
648
649/// Map a `FieldType` to its PostgreSQL column type string.
650pub(crate) fn field_type_to_pg(ft: &FieldType) -> String {
651    match ft {
652        FieldType::String | FieldType::Scalar(_) => "TEXT".to_string(),
653        FieldType::Int => "INTEGER".to_string(),
654        FieldType::Float => "DOUBLE PRECISION".to_string(),
655        FieldType::Boolean => "BOOLEAN".to_string(),
656        FieldType::Id | FieldType::Uuid => "UUID".to_string(),
657        FieldType::DateTime => "TIMESTAMPTZ".to_string(),
658        FieldType::Date => "DATE".to_string(),
659        FieldType::Time => "TIME".to_string(),
660        FieldType::Json | FieldType::List(_) | FieldType::Object(_) => "JSONB".to_string(),
661        FieldType::Decimal => "NUMERIC".to_string(),
662        FieldType::Vector => "VECTOR".to_string(),
663        // Use the actual Postgres enum type name so DDL matches the schema.
664        FieldType::Enum(name) => name.clone(),
665        FieldType::Input(_) | FieldType::Interface(_) | FieldType::Union(_) => "JSONB".to_string(),
666        // FieldType is #[non_exhaustive]; future variants default to TEXT.
667        _ => "TEXT".to_string(),
668    }
669}
670
671/// Emit warnings when schema uses features that SQLite does not support.
672///
673/// SQLite executes direct-SQL Insert/Delete mutations, but lacks Update /
674/// stored-procedure (`fn_*`) mutations and relay/subscription support. A
675/// compile-time warning helps catch this before runtime failures.
676fn check_sqlite_compatibility_warnings(
677    schema: &CompiledSchema,
678    input_path: &str,
679    is_toml: bool,
680    database_url: Option<&str>,
681) {
682    let target_is_sqlite = database_url
683        .is_some_and(|url| url.to_ascii_lowercase().starts_with("sqlite://"))
684        || is_toml && detect_sqlite_target_in_toml(input_path);
685
686    if !target_is_sqlite {
687        return;
688    }
689
690    // SQLite executes direct-SQL Insert/Delete mutations via the `DirectSql` strategy;
691    // only Update and custom / stored-procedure (`fn_*`) mutations are unsupported.
692    let unsupported_mutation_count = schema
693        .mutations
694        .iter()
695        .filter(|m| {
696            matches!(
697                m.operation,
698                fraiseql_core::schema::MutationOperation::Update { .. }
699                    | fraiseql_core::schema::MutationOperation::Custom
700            )
701        })
702        .count();
703    let relay_count = schema.queries.iter().filter(|q| q.relay).count();
704    let subscription_count = schema.subscriptions.len();
705
706    if unsupported_mutation_count > 0 {
707        warn!(
708            "Schema contains {} Update or custom mutation(s) but target database is SQLite. \
709             SQLite supports only direct-SQL Insert/Delete mutations. \
710             See: https://fraiseql.dev/docs/database-compatibility",
711            unsupported_mutation_count,
712        );
713    }
714    if relay_count > 0 {
715        warn!(
716            "Schema contains {} relay query/queries but target database is SQLite. \
717             Relay (keyset pagination) is not supported on SQLite. \
718             See: https://fraiseql.dev/docs/database-compatibility",
719            relay_count,
720        );
721    }
722    if subscription_count > 0 {
723        warn!(
724            "Schema contains {} subscription(s) but target database is SQLite. \
725             Subscriptions are not supported on SQLite. \
726             See: https://fraiseql.dev/docs/database-compatibility",
727            subscription_count,
728        );
729    }
730}
731
732/// Check if the TOML schema file specifies `database_target = "sqlite"`.
733///
734/// Reads and parses the TOML to extract the schema metadata. Returns `false`
735/// on any parse error (non-fatal — warning detection is best-effort).
736fn detect_sqlite_target_in_toml(toml_path: &str) -> bool {
737    let Ok(content) = fs::read_to_string(toml_path) else {
738        return false;
739    };
740    let Ok(toml_schema) = toml::from_str::<crate::config::toml_schema::TomlSchema>(&content) else {
741        return false;
742    };
743    toml_schema.schema.database_target.to_ascii_lowercase().contains("sqlite")
744}
745
746/// Minimum distinct invalidation targets (views + fact tables) that triggers
747/// the HOT-update fan-out warning.
748pub(crate) const WIDE_FANOUT_THRESHOLD: usize = 3;
749
750/// Return mutations whose total invalidation fan-out meets or exceeds `threshold`.
751///
752/// Fan-out is the count of distinct views (`invalidates_views`) plus fact tables
753/// (`invalidates_fact_tables`) that a mutation touches on every successful write.
754/// Used by [`warn_wide_cascade_mutations`] and exposed for unit testing.
755pub(crate) fn wide_cascade_mutations(
756    schema: &CompiledSchema,
757    threshold: usize,
758) -> Vec<&fraiseql_core::schema::MutationDefinition> {
759    schema
760        .mutations
761        .iter()
762        .filter(|m| m.invalidates_views.len() + m.invalidates_fact_tables.len() >= threshold)
763        .collect()
764}
765
766/// Emit a warning for each mutation whose invalidation fan-out is wide enough
767/// to risk exhausting PostgreSQL HOT-update page slots under high write load.
768///
769/// When a mutation touches many tables on every write, the free space reserved
770/// on each heap page (needed for HOT updates) fills up quickly. Subsequent
771/// mutations must write to a new page instead of updating in place, which
772/// increases I/O and table bloat. Setting `fillfactor=70-80` on the backing
773/// tables leaves 20-30 % of each page free, keeping HOT updates available.
774///
775/// The warning lists ready-to-run `ALTER TABLE … SET (fillfactor = 75)` statements
776/// derived from the view names using FraiseQL naming conventions
777/// (`tv_foo` / `v_foo` → `tb_foo`).
778fn warn_wide_cascade_mutations(schema: &CompiledSchema) {
779    for mutation in wide_cascade_mutations(schema, WIDE_FANOUT_THRESHOLD) {
780        let total = mutation.invalidates_views.len() + mutation.invalidates_fact_tables.len();
781
782        // Build a sorted, deduplicated target list for a stable message.
783        let mut targets: Vec<&str> = mutation
784            .invalidates_views
785            .iter()
786            .chain(mutation.invalidates_fact_tables.iter())
787            .map(String::as_str)
788            .collect();
789        targets.sort_unstable();
790        targets.dedup();
791
792        // Derive a likely backing-table name from FraiseQL view naming conventions.
793        // tv_foo → tb_foo, v_foo → tb_foo, anything else (e.g. fact tables) unchanged.
794        let alter_stmts: Vec<String> = targets
795            .iter()
796            .map(|&name| {
797                let table = name
798                    .strip_prefix("tv_")
799                    .or_else(|| name.strip_prefix("v_"))
800                    .map_or_else(|| name.to_string(), |rest| format!("tb_{rest}"));
801                format!("ALTER TABLE {table} SET (fillfactor = 75);")
802            })
803            .collect();
804
805        warn!(
806            "mutation '{}' has a wide invalidation fan-out ({} targets: [{}]). \
807             Under high write load, HOT-update page slots on these tables may be \
808             exhausted, forcing full-page writes and reducing mutation throughput. \
809             Set fillfactor=70-80 on the backing tables: {}  \
810             Monitor HOT efficiency: SELECT relname, \
811             n_tup_hot_upd * 100 / NULLIF(n_tup_upd, 0) AS hot_pct \
812             FROM pg_stat_user_tables WHERE n_tup_upd > 0 ORDER BY hot_pct;",
813            mutation.name,
814            total,
815            targets.join(", "),
816            alter_stmts.join("  "),
817        );
818    }
819}
820
821/// Detect single-JSONB mutations that would silently forward `camelCase` input
822/// keys to a `snake_case` SQL function under `naming_convention = "preserve"`.
823///
824/// Returns `(mutation_name, camelCase_field_names)` for every mutation that, on a
825/// `Preserve` schema, takes one declared `input` Input type through the
826/// single-JSONB path (`input_style = "jsonb"` or an `Update`) and whose Input
827/// type has `camelCase`-looking field name(s). Under `Preserve` the runtime
828/// forwards the payload verbatim — no `snake_case` recasing — so a function
829/// reading `payload->>'snake_field'` sees NULL for every multi-word field (#456).
830///
831/// Pure (no I/O) so it can be unit-tested; [`warn_jsonb_preserve_mismatch`] is the
832/// thin logging wrapper.
833pub(crate) fn jsonb_preserve_mismatches(schema: &CompiledSchema) -> Vec<(String, Vec<String>)> {
834    if schema.naming_convention != NamingConvention::Preserve {
835        return Vec::new();
836    }
837    let mut out = Vec::new();
838    for mutation in &schema.mutations {
839        // The single-JSONB path: an explicit `input_style = jsonb` or an Update,
840        // both of which forward the whole `input` object as one JSONB arg.
841        let single_jsonb = matches!(mutation.input_style, InputStyle::Jsonb)
842            || matches!(mutation.operation, MutationOperation::Update { .. });
843        if !single_jsonb {
844            continue;
845        }
846        // The single-`input`-object pattern: exactly one arg named "input" whose
847        // type is a declared input type (mirrors the runtime's detection). The
848        // compiler emits input-type references as `FieldType::Object`, never
849        // `FieldType::Input`, so recognise an `Object` naming a registered input
850        // type too — otherwise this warning is blind to every real compiled schema
851        // (#456).
852        let input_type_name = match mutation.arguments.as_slice() {
853            [arg] if arg.name == "input" => match &arg.arg_type {
854                FieldType::Input(name) => name.as_str(),
855                FieldType::Object(name) if schema.find_input_type(name).is_some() => name.as_str(),
856                _ => continue,
857            },
858            _ => continue,
859        };
860        let Some(input_type) = schema.find_input_type(input_type_name) else {
861            continue;
862        };
863        // A field name with any uppercase letter is camelCase-looking — under
864        // Preserve it reaches the function verbatim and won't match a snake key.
865        let camel_fields: Vec<String> = input_type
866            .fields
867            .iter()
868            .filter(|f| f.name.chars().any(|c| c.is_ascii_uppercase()))
869            .map(|f| f.name.clone())
870            .collect();
871        if !camel_fields.is_empty() {
872            out.push((mutation.name.clone(), camel_fields));
873        }
874    }
875    out
876}
877
878/// Warn for every [`jsonb_preserve_mismatches`] hit — the silent #456
879/// misconfiguration where a `preserve` schema forwards camelCase input keys to a
880/// snake_case SQL function on the single-JSONB path.
881fn warn_jsonb_preserve_mismatch(schema: &CompiledSchema) {
882    for (mutation, fields) in jsonb_preserve_mismatches(schema) {
883        warn!(
884            "mutation '{mutation}' forwards its input as a single JSONB payload but the schema \
885             uses naming_convention = \"preserve\", and its input type has camelCase field(s) \
886             [{}]. Under 'preserve' the runtime forwards input keys verbatim (no snake_case \
887             recasing), so a SQL function reading payload->>'snake_field' will receive these \
888             camelCase keys and see NULL. Set naming_convention = \"camelCase\" (the default for \
889             new schemas) if the function expects snake_case keys, or rename the fields. (#456)",
890            fields.join(", "),
891        );
892    }
893}
894
895/// Build a PostgreSQL introspector connected to `db_url`.
896///
897/// Shared by `validate_indexed_columns` and the native column validation path.
898///
899/// # Errors
900///
901/// Returns error if the pool cannot be created or the connection URL is invalid.
902fn build_postgres_introspector(
903    db_url: &str,
904) -> Result<fraiseql_core::db::postgres::PostgresIntrospector> {
905    use deadpool_postgres::{Config, ManagerConfig, RecyclingMethod, Runtime};
906    use tokio_postgres::NoTls;
907
908    let mut cfg = Config::new();
909    cfg.url = Some(db_url.to_string());
910    cfg.manager = Some(ManagerConfig {
911        recycling_method: RecyclingMethod::Fast,
912    });
913    cfg.pool = Some(deadpool_postgres::PoolConfig::new(2));
914
915    let pool = cfg
916        .create_pool(Some(Runtime::Tokio1), NoTls)
917        .context("Failed to create connection pool for database validation")?;
918
919    Ok(fraiseql_core::db::postgres::PostgresIntrospector::new(pool))
920}
921
922/// Validate indexed columns against database views.
923///
924/// Connects to the database and introspects view columns to verify that
925/// any indexed column naming conventions are properly set up.
926///
927/// # Arguments
928///
929/// * `schema` - The compiled schema to validate
930/// * `db_url` - Database connection URL
931///
932/// # Errors
933///
934/// Returns error if database connection fails. Warnings are printed for
935/// missing indexed columns but don't cause validation to fail.
936async fn validate_indexed_columns(schema: &CompiledSchema, db_url: &str) -> Result<()> {
937    use deadpool_postgres::{Config, ManagerConfig, RecyclingMethod, Runtime};
938    use fraiseql_core::db::postgres::PostgresIntrospector;
939    use tokio_postgres::NoTls;
940
941    // Create pool for introspection
942    let mut cfg = Config::new();
943    cfg.url = Some(db_url.to_string());
944    cfg.manager = Some(ManagerConfig {
945        recycling_method: RecyclingMethod::Fast,
946    });
947    cfg.pool = Some(deadpool_postgres::PoolConfig::new(2));
948
949    let pool = cfg
950        .create_pool(Some(Runtime::Tokio1), NoTls)
951        .context("Failed to create connection pool for indexed column validation")?;
952
953    let introspector = PostgresIntrospector::new(pool);
954
955    let mut total_indexed = 0;
956    let mut total_views = 0;
957
958    // Check each query's sql_source (view)
959    for query in &schema.queries {
960        if let Some(view_name) = &query.sql_source {
961            total_views += 1;
962
963            // Get indexed columns for this view
964            match introspector.get_indexed_nested_columns(view_name).await {
965                Ok(indexed_cols) => {
966                    if !indexed_cols.is_empty() {
967                        info!(
968                            "View '{}': found {} indexed column(s): {:?}",
969                            view_name,
970                            indexed_cols.len(),
971                            indexed_cols
972                        );
973                        total_indexed += indexed_cols.len();
974                    }
975                },
976                Err(e) => {
977                    warn!(
978                        "Could not introspect view '{}': {}. Skipping indexed column check.",
979                        view_name, e
980                    );
981                },
982            }
983        }
984    }
985
986    println!("✓ Indexed column validation complete");
987    println!("  Views checked: {total_views}");
988    println!("  Indexed columns found: {total_indexed}");
989
990    Ok(())
991}
992
993/// Auto-param names excluded from `native_columns` inference and JSONB-extraction warnings.
994const NATIVE_COLUMN_SKIP_ARGS: &[&str] = &[
995    "where", "limit", "offset", "orderBy", "first", "last", "after", "before",
996];
997
998/// Infer `native_columns` for `ID`/`UUID`-typed arguments on JSONB-backed queries.
999///
1000/// When a query reads from a JSONB table (`sql_source` + non-empty `jsonb_column`) and an
1001/// argument is typed [`FieldType::Id`] or [`FieldType::Uuid`], the argument name almost
1002/// certainly maps to a native UUID column alongside the `data` JSONB column
1003/// (e.g. `id UUID NOT NULL`). Emitting `WHERE id = $1::uuid` instead of
1004/// `WHERE data->>'id' = $1` lets the planner use the B-tree index without
1005/// needing a database connection at compile time.
1006///
1007/// Auto-param names (`where`, `limit`, `offset`, etc.) are skipped.
1008/// Arguments already present in `native_columns` are not overridden.
1009pub(crate) fn infer_native_columns_from_arg_types(schema: &mut CompiledSchema) {
1010    for query in &mut schema.queries {
1011        if query.sql_source.is_none() || query.jsonb_column.is_empty() {
1012            continue;
1013        }
1014        for arg in &query.arguments {
1015            if NATIVE_COLUMN_SKIP_ARGS.contains(&arg.name.as_str()) {
1016                continue;
1017            }
1018            if query.native_columns.contains_key(&arg.name) {
1019                continue; // already explicitly declared — don't override
1020            }
1021            if matches!(arg.arg_type, FieldType::Id | FieldType::Uuid) {
1022                query.native_columns.insert(arg.name.clone(), "uuid".to_string());
1023            }
1024        }
1025    }
1026}