1use 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#[derive(Debug, Default)]
27pub struct CompileOptions<'a> {
28 pub input: &'a str,
30 pub types: Option<&'a str>,
32 pub schema_dir: Option<&'a str>,
34 pub type_files: Vec<String>,
36 pub query_files: Vec<String>,
38 pub mutation_files: Vec<String>,
40 pub database: Option<&'a str>,
42 pub skip_hash: bool,
44}
45
46impl<'a> CompileOptions<'a> {
47 #[must_use]
49 pub fn new(input: &'a str) -> Self {
50 Self {
51 input,
52 ..Default::default()
53 }
54 }
55
56 #[must_use]
58 pub fn with_types(mut self, types: &'a str) -> Self {
59 self.types = Some(types);
60 self
61 }
62
63 #[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 #[must_use]
72 pub fn with_database(mut self, database: &'a str) -> Self {
73 self.database = Some(database);
74 self
75 }
76}
77
78#[allow(clippy::cognitive_complexity)] fn 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#[allow(clippy::cognitive_complexity)] pub async fn compile_to_schema(
142 opts: CompileOptions<'_>,
143) -> Result<(CompiledSchema, OptimizationReport)> {
144 info!("Compiling schema: {}", opts.input);
145
146 let input_path = Path::new(opts.input);
148 if !input_path.exists() {
149 anyhow::bail!("Input file not found: {}", opts.input);
150 }
151
152 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 info!("Using legacy JSON workflow");
170 let schema_json = fs::read_to_string(input_path).context("Failed to read schema.json")?;
171
172 info!("Parsing intermediate schema...");
174 serde_json::from_str(&schema_json).context("Failed to parse schema.json")?
175 };
176
177 let mut auto_error_union = false;
183 let mut naming_acronyms: Vec<String> = Vec::new();
185 let mut operation_cost_weights: std::collections::HashMap<String, usize> =
187 std::collections::HashMap::new();
188 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 let mut security_json = config.fraiseql.security.to_json();
209
210 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 fraiseql_core::utils::casing::set_runtime_acronyms(&naming_acronyms);
237
238 if !is_toml {
244 intermediate.naming_convention = naming_convention;
245 }
246
247 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 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 if validation_report.warning_count() > 0 {
285 validation_report.print();
286 }
287
288 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 schema.naming_acronyms = naming_acronyms;
297
298 if !operation_cost_weights.is_empty() {
302 schema.operation_cost_weights = operation_cost_weights;
303 }
304
305 info!("Analyzing schema for optimization opportunities...");
307 let report = SchemaOptimizer::optimize(&mut schema).context("Failed to optimize schema")?;
308
309 schema.schema_format_version = Some(CURRENT_SCHEMA_FORMAT_VERSION);
311
312 infer_native_columns_from_arg_types(&mut schema);
315
316 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 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 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 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 check_sqlite_compatibility_warnings(&schema, opts.input, is_toml, opts.database);
383
384 warn_wide_cascade_mutations(&schema);
386
387 warn_jsonb_preserve_mismatch(&schema);
390
391 Ok((schema, report))
392}
393
394#[allow(clippy::too_many_arguments)]
423#[doc(hidden)] pub 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 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 {
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 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 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 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 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 if let Some(ddl_dir) = emit_ddl {
512 emit_ddl_to_dir(&schema, ddl_dir)?;
513 }
514
515 if check_migrations {
517 run_check_migrations(&schema)?;
518 }
519
520 Ok(())
521}
522
523pub 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
555fn 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 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
598pub(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
610fn 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
649pub(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 FieldType::Enum(name) => name.clone(),
665 FieldType::Input(_) | FieldType::Interface(_) | FieldType::Union(_) => "JSONB".to_string(),
666 _ => "TEXT".to_string(),
668 }
669}
670
671fn 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 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
732fn 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
746pub(crate) const WIDE_FANOUT_THRESHOLD: usize = 3;
749
750pub(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
766fn 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 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 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
821pub(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 let single_jsonb = matches!(mutation.input_style, InputStyle::Jsonb)
842 || matches!(mutation.operation, MutationOperation::Update { .. });
843 if !single_jsonb {
844 continue;
845 }
846 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 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
878fn 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
895fn 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
922async 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 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 for query in &schema.queries {
960 if let Some(view_name) = &query.sql_source {
961 total_views += 1;
962
963 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
993const NATIVE_COLUMN_SKIP_ARGS: &[&str] = &[
995 "where", "limit", "offset", "orderBy", "first", "last", "after", "before",
996];
997
998pub(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; }
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}