1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
//! Schema Converter
//!
//! Converts `IntermediateSchema` (language-agnostic) to `CompiledSchema` (Rust-specific)
mod cascade_types;
mod directives;
mod identity;
mod interface_conformance;
mod mutation_error_union;
mod mutations;
mod queries;
mod relay;
mod subscriptions;
pub(crate) mod tenancy;
mod types;
#[cfg(test)]
mod tests;
use std::collections::HashSet;
use anyhow::{Context, Result};
use fraiseql_core::{
compiler::fact_table::{
DimensionColumn, DimensionPath, FactTableMetadata, FilterColumn, MeasureColumn, SqlType,
},
schema::{CompiledSchema, FieldType},
validation::CustomTypeRegistry,
};
use tracing::{info, warn};
use super::{
intermediate::{IntermediateFactTable, IntermediateSchema},
rich_filters::{RichFilterConfig, compile_rich_filters},
};
/// Converts intermediate format to compiled format
pub struct SchemaConverter;
/// Optional, default-off behaviours for [`SchemaConverter::convert_with_options`].
///
/// Threaded here rather than on [`IntermediateSchema`] so adding an option never
/// breaks the many full-literal `IntermediateSchema { .. }` constructions, and
/// the plain [`SchemaConverter::convert`] keeps its historical signature.
#[derive(Debug, Clone, Default)]
pub struct ConvertOptions {
/// Auto-synthesize a shared `MutationError` type + per-mutation result unions
/// and rewrite object-returning mutations to those unions (`[fraiseql.mutations]
/// auto_error_union`).
pub auto_error_union: bool,
}
impl SchemaConverter {
/// Convert `IntermediateSchema` to `CompiledSchema` with default options.
///
/// # Errors
///
/// See [`SchemaConverter::convert_with_options`].
pub fn convert(intermediate: IntermediateSchema) -> Result<CompiledSchema> {
Self::convert_with_options(intermediate, &ConvertOptions::default())
}
/// Convert `IntermediateSchema` to `CompiledSchema`.
///
/// This performs:
/// 1. Type conversion (intermediate types → compiled types)
/// 2. Field name normalization (type → `field_type`)
/// 3. Optional mutation-error-union synthesis (`options.auto_error_union`)
/// 4. Validation (type references, circular refs, etc.)
///
/// # Errors
///
/// Returns an error if any type, query, mutation, interface, subscription,
/// or directive conversion fails, if federation/security/observer config JSON
/// cannot be deserialized, or if compiled schema validation detects unknown
/// type references.
pub fn convert_with_options(
intermediate: IntermediateSchema,
options: &ConvertOptions,
) -> Result<CompiledSchema> {
info!("Converting intermediate schema to compiled format");
// Aggregate the per-type `@subscribable(tables=[...])` annotations (#366)
// into the top-level `CompiledSchema.subscribable` list BEFORE the types
// are consumed below. Empty `tables` is treated as "not subscribable".
let subscribable: Vec<fraiseql_core::schema::SubscribableEntity> = intermediate
.types
.iter()
.filter_map(|t| {
t.subscribable_tables
.as_ref()
.filter(|tables| !tables.is_empty())
.map(|tables| fraiseql_core::schema::SubscribableEntity {
entity_type: t.name.clone(),
tables: tables.clone(),
pre_image: t.subscribable_pre_image,
})
})
.collect();
// Convert types
let types = intermediate
.types
.into_iter()
.map(Self::convert_type)
.collect::<Result<Vec<_>>>()
.context("Failed to convert types")?;
// Extract query_defaults before consuming intermediate.queries.
// unwrap_or_default() → all-true, matching historical behaviour when no
// [query_defaults] section is present in fraiseql.toml.
let defaults = intermediate.query_defaults.unwrap_or_default();
// Convert queries
let queries = intermediate
.queries
.into_iter()
.map(|q| Self::convert_query(q, &defaults))
.collect::<Result<Vec<_>>>()
.context("Failed to convert queries")?;
// Convert mutations
let mutations = intermediate
.mutations
.into_iter()
.map(Self::convert_mutation)
.collect::<Result<Vec<_>>>()
.context("Failed to convert mutations")?;
// Convert enums
let enums = intermediate.enums.into_iter().map(Self::convert_enum).collect::<Vec<_>>();
// Convert input types
let input_types = intermediate
.input_types
.into_iter()
.map(Self::convert_input_object)
.collect::<Vec<_>>();
// Convert interfaces
let interfaces = intermediate
.interfaces
.into_iter()
.map(Self::convert_interface)
.collect::<Result<Vec<_>>>()
.context("Failed to convert interfaces")?;
// Convert unions
let unions = intermediate.unions.into_iter().map(Self::convert_union).collect::<Vec<_>>();
// Convert subscriptions
let subscriptions = intermediate
.subscriptions
.into_iter()
.map(Self::convert_subscription)
.collect::<Result<Vec<_>>>()
.context("Failed to convert subscriptions")?;
// Convert custom directives
let directives = intermediate
.directives
.unwrap_or_default()
.into_iter()
.map(Self::convert_directive)
.collect::<Result<Vec<_>>>()
.context("Failed to convert directives")?;
// Convert fact tables from Vec<IntermediateFactTable> to HashMap<String, FactTableMetadata>
let fact_tables = intermediate
.fact_tables
.unwrap_or_default()
.into_iter()
.map(|ft| {
let name = ft.table_name.clone();
let metadata = Self::convert_fact_table(ft);
(name, metadata)
})
.collect();
let mut compiled = CompiledSchema {
types,
enums,
input_types,
interfaces,
unions,
queries,
mutations,
subscriptions,
directives,
fact_tables, // Analytics metadata
observers: Vec::new(), /* Observer definitions (populated from
* IntermediateSchema) */
sources: intermediate.sources.clone().unwrap_or_default(), /* #573 scheduled ingress
* sources */
subscribable, // @subscribable capture-trigger declarations (#366)
federation: intermediate
.federation_config
.map(serde_json::from_value)
.transpose()
.context("federation_config: invalid JSON structure")?,
security: intermediate
.security
.map(serde_json::from_value)
.transpose()
.context("security: invalid JSON structure")?,
observers_config: intermediate
.observers_config
.map(serde_json::from_value)
.transpose()
.context("observers_config: invalid JSON structure")?,
subscriptions_config: intermediate.subscriptions_config, /* Subscriptions config from
* TOML */
validation_config: intermediate.validation_config, // Validation limits from TOML
debug_config: intermediate.debug_config, // Debug config from TOML
mcp_config: intermediate.mcp_config, // MCP config from TOML
rest_config: intermediate.rest_config, // REST config from TOML
naming_convention: intermediate.naming_convention, // Naming convention from TOML
session_variables: intermediate.session_variables.unwrap_or_default(),
hierarchies_config: intermediate.hierarchies_config,
changelog: intermediate.changelog_config, // Changelog exposure config from TOML
schema_sdl: None, // Raw GraphQL SDL
custom_scalars: CustomTypeRegistry::default(), // Custom scalar registry
schema_format_version: Some(fraiseql_core::schema::CURRENT_SCHEMA_FORMAT_VERSION),
..Default::default()
};
// Populate custom scalars from intermediate schema
if let Some(custom_scalars_vec) = intermediate.custom_scalars {
for scalar_def in custom_scalars_vec {
let custom_type = Self::convert_custom_scalar(scalar_def)?;
compiled
.custom_scalars
.register(custom_type.name.clone(), custom_type)
.context("Failed to register custom scalar")?;
}
}
// Changelog exposure requires the observer system: the views it exposes read
// from tables (`tb_entity_change_log`, `tb_transport_checkpoint`) that the
// observer install convention supplies. Emitting GraphQL types over absent
// tables would only fail later, at runtime — reject it here instead.
if let Some(ref cl) = compiled.changelog {
if cl.expose && !compiled.observers_config.as_ref().is_some_and(|o| o.enabled) {
anyhow::bail!(
"[changelog] expose = true requires [observers] to be enabled: the tables \
it exposes (tb_entity_change_log, tb_transport_checkpoint) are installed by \
the observer system."
);
}
// #497: the change-log surface is a per-database stream, not a federated
// value type — the injected `EntityChangeLog` type and `entity_change_logs`
// root query are not `@shareable`. Two subgraphs in one supergraph that both
// `expose` it inject the identical type/root field, which `rover supergraph
// compose` rejects with INVALID_FIELD_SHARING. We can't detect the collision
// here (each subgraph compiles alone), so warn on the federated+exposed combo
// and point at the single-owner pattern. This is a reminder, not an error —
// the owning subgraph legitimately sets both.
if cl.expose && compiled.federation.as_ref().is_some_and(|f| f.enabled) {
warn!(
"[changelog] expose = true on a federation subgraph: EntityChangeLog / \
entity_change_logs are not @shareable, so expose the change-log in exactly \
one subgraph per supergraph (others keep capturing via [changelog] \
write_enabled). Two exposing subgraphs fail `rover supergraph compose` with \
INVALID_FIELD_SHARING. See the changelog-graphql guide for the single-owner \
pattern."
);
}
}
// Canonicalize the Trinity external identity (`id: UUID` → `id: ID`, ADR-0017)
// before the interface-forcing passes, so Relay `Node` / `CascadeNode` see a
// conformant `id: ID` on every entity. Wire-transparent (a UUID is an `ID`).
identity::normalize_entity_identity(&mut compiled);
// Inject synthetic Relay types (PageInfo, Node interface, XxxConnection, XxxEdge).
relay::inject_relay_types(&mut compiled)?;
// Compile rich filter types (EmailAddress, VIN, IBAN, etc.)
let rich_filter_config = RichFilterConfig::default();
compile_rich_filters(&mut compiled, &rich_filter_config)
.context("Failed to compile rich filter types")?;
// Inject the changelog GraphQL surface (EntityChangeLog / TransportCheckpoint
// types + cursor query + point lookup + upsert mutation) when opted in.
fraiseql_core::schema::inject_changelog(&mut compiled);
// Synthesize the typed cascade surface (CascadeNode interface + envelope
// types + per-mutation `<Name>Payload` wrappers) for mutations that opt in
// via `cascade = true`. Runs BEFORE error-union synthesis so a cascade
// payload becomes the success member of the result union
// (`<Name>Result = <Name>Payload | MutationError`). Inert with no cascade
// mutations.
cascade_types::synthesize_cascade_types(&mut compiled)?;
// Auto-synthesize a shared MutationError type + per-mutation result unions
// when opted in (`[fraiseql.mutations] auto_error_union`), so the runtime's
// success/error discrimination has a union to resolve against.
if options.auto_error_union {
mutation_error_union::synthesize_mutation_error_unions(&mut compiled);
}
// IR honesty (#456): `parse_field_type` has no `Input` variant, so an
// argument referencing a declared input type was resolved to
// `FieldType::Object`. Rewrite those argument types to `FieldType::Input`
// now that every input type is registered (after relay / rich-filter /
// changelog / error-union injection) so the IR honestly represents the
// GraphQL input position — which also makes introspection report the correct
// `INPUT_OBJECT` kind for those args. The runtime already accepts both
// shapes, so this is purely representational.
Self::promote_input_type_args(&mut compiled);
// Validate the compiled schema
Self::validate(&compiled)?;
info!("Schema conversion successful");
Ok(compiled)
}
/// Rewrite mutation/query argument types of the form `Object(name)` (and lists
/// thereof) to `Input(name)` when `name` is a registered input type, so the IR
/// honestly represents input-position references (#456). Input type names are
/// disjoint from output type names per the GraphQL spec, so the lookup is exact
/// — an output-object argument is never misclassified.
fn promote_input_type_args(schema: &mut CompiledSchema) {
fn promote(ft: &mut FieldType, input_names: &HashSet<String>) {
match ft {
FieldType::Object(name) if input_names.contains(name) => {
*ft = FieldType::Input(name.clone());
},
FieldType::List(inner) => promote(inner, input_names),
_ => {},
}
}
let input_names: HashSet<String> =
schema.input_types.iter().map(|i| i.name.clone()).collect();
if input_names.is_empty() {
return;
}
for mutation in &mut schema.mutations {
for arg in &mut mutation.arguments {
promote(&mut arg.arg_type, &input_names);
}
}
for query in &mut schema.queries {
for arg in &mut query.arguments {
promote(&mut arg.arg_type, &input_names);
}
}
}
#[allow(clippy::cognitive_complexity)] // Reason: comprehensive schema validation with many field-level checks
fn validate(schema: &CompiledSchema) -> Result<()> {
info!("Validating compiled schema");
// Build type registry
let mut type_names: HashSet<String> = HashSet::new();
for type_def in &schema.types {
type_names.insert(type_def.name.to_string());
}
// Build interface registry. Interfaces are *also* valid query/mutation
// return types (a field may return an interface, narrowed via inline
// fragments), so register them in `type_names` too — previously omitted,
// which made a query/mutation returning an interface silently fail the
// reference check below.
let mut interface_names = HashSet::new();
for interface_def in &schema.interfaces {
interface_names.insert(interface_def.name.clone());
type_names.insert(interface_def.name.clone());
}
// Add input types — valid as mutation argument types (fraiseql/fraiseql#190)
for input_type in &schema.input_types {
type_names.insert(input_type.name.clone());
}
// Add union type names — valid as mutation/query return types
for union_def in &schema.unions {
type_names.insert(union_def.name.clone());
}
// Add built-in scalars
for scalar in crate::schema::BUILTIN_SCALAR_NAMES {
type_names.insert((*scalar).to_string());
}
// Collect custom scalars implicitly: any type name used in object field definitions
// (e.g. IPAddress, Hostname, MACAddress, CIDR, Money, etc.)
for type_def in &schema.types {
for field in &type_def.fields {
let base = Self::extract_type_name(&field.field_type);
type_names.insert(base);
}
}
// Validate queries
for query in &schema.queries {
if !type_names.contains(&query.return_type) {
warn!("Query '{}' references unknown type: {}", query.name, query.return_type);
anyhow::bail!(
"Query '{}' references unknown type '{}'",
query.name,
query.return_type
);
}
// Validate argument types
for arg in &query.arguments {
let type_name = Self::extract_type_name(&arg.arg_type);
if !type_names.contains(&type_name) {
warn!(
"Query '{}' argument '{}' references unknown type: {}",
query.name, arg.name, type_name
);
anyhow::bail!(
"Query '{}' argument '{}' references unknown type '{}'",
query.name,
arg.name,
type_name
);
}
}
}
// Validate mutations
for mutation in &schema.mutations {
if !type_names.contains(&mutation.return_type) {
warn!(
"Mutation '{}' references unknown type: {}",
mutation.name, mutation.return_type
);
anyhow::bail!(
"Mutation '{}' references unknown type '{}'",
mutation.name,
mutation.return_type
);
}
// Validate argument types
for arg in &mutation.arguments {
let type_name = Self::extract_type_name(&arg.arg_type);
if !type_names.contains(&type_name) {
warn!(
"Mutation '{}' argument '{}' references unknown type: {}",
mutation.name, arg.name, type_name
);
anyhow::bail!(
"Mutation '{}' argument '{}' references unknown type '{}'",
mutation.name,
arg.name,
type_name
);
}
}
}
// Validate interface implementations
for type_def in &schema.types {
for interface_name in &type_def.implements {
if !interface_names.contains(interface_name) {
warn!(
"Type '{}' implements unknown interface: {}",
type_def.name, interface_name
);
anyhow::bail!(
"Type '{}' implements unknown interface '{}'",
type_def.name,
interface_name
);
}
// Validate that the type has all fields required by the interface
if let Some(interface) = schema.find_interface(interface_name) {
for interface_field in &interface.fields {
let type_has_field = type_def.fields.iter().any(|f| {
f.name == interface_field.name
&& f.field_type == interface_field.field_type
});
if !type_has_field {
warn!(
"Type '{}' implements interface '{}' but is missing field: {}",
type_def.name, interface_name, interface_field.name
);
anyhow::bail!(
"Type '{}' implements interface '{}' but is missing field '{}'",
type_def.name,
interface_name,
interface_field.name
);
}
}
}
}
}
info!("Schema validation passed");
Ok(())
}
/// Extract type name from `FieldType` for validation
///
/// Built-in types return their scalar name, Object types return the object name
fn extract_type_name(field_type: &FieldType) -> String {
match field_type {
FieldType::String => "String".to_string(),
FieldType::Int => "Int".to_string(),
FieldType::Float => "Float".to_string(),
FieldType::Boolean => "Boolean".to_string(),
FieldType::Id => "ID".to_string(),
FieldType::DateTime => "DateTime".to_string(),
FieldType::Date => "Date".to_string(),
FieldType::Time => "Time".to_string(),
FieldType::Json => "Json".to_string(),
FieldType::Uuid => "UUID".to_string(),
FieldType::Decimal => "Decimal".to_string(),
FieldType::Vector => "Vector".to_string(),
FieldType::Scalar(name) => name.clone(),
FieldType::Object(name) => name.clone(),
FieldType::Enum(name) => name.clone(),
FieldType::Input(name) => name.clone(),
FieldType::Interface(name) => name.clone(),
FieldType::Union(name) => name.clone(),
FieldType::List(inner) => Self::extract_type_name(inner),
// Reason: non_exhaustive requires catch-all for cross-crate matches
_ => "Unknown".to_string(),
}
}
/// Convert `IntermediateFactTable` to `FactTableMetadata`.
fn convert_fact_table(ft: IntermediateFactTable) -> FactTableMetadata {
FactTableMetadata {
table_name: ft.table_name,
measures: ft
.measures
.into_iter()
.map(|m| MeasureColumn {
name: m.name,
sql_type: Self::parse_sql_type(&m.sql_type),
nullable: m.nullable,
})
.collect(),
dimensions: DimensionColumn {
name: ft.dimensions.name,
paths: ft
.dimensions
.paths
.into_iter()
.map(|p| DimensionPath {
name: p.name,
json_path: p.json_path,
data_type: p.data_type,
})
.collect(),
},
denormalized_filters: ft
.denormalized_filters
.into_iter()
.map(|f| FilterColumn {
name: f.name,
sql_type: Self::parse_sql_type(&f.sql_type),
indexed: f.indexed,
})
.collect(),
calendar_dimensions: vec![],
partial_period: None,
native_measures: ft.native_measures,
native_dimension_mapping: ft.native_dimension_mapping,
}
}
/// Parse a SQL type string into a `SqlType` enum variant.
fn parse_sql_type(s: &str) -> SqlType {
match s.to_uppercase().as_str() {
"INT" | "INTEGER" | "SMALLINT" | "INT4" | "INT2" => SqlType::Int,
"BIGINT" | "INT8" => SqlType::BigInt,
"DECIMAL" | "NUMERIC" | "MONEY" => SqlType::Decimal,
"REAL" | "FLOAT" | "DOUBLE" | "FLOAT8" | "FLOAT4" | "DOUBLE PRECISION" => {
SqlType::Float
},
"JSONB" => SqlType::Jsonb,
"JSON" => SqlType::Json,
"TEXT" | "VARCHAR" | "STRING" | "CHAR" | "CHARACTER VARYING" => SqlType::Text,
"UUID" => SqlType::Uuid,
"TIMESTAMP" | "TIMESTAMPTZ" | "TIMESTAMP WITH TIME ZONE" | "DATETIME" => {
SqlType::Timestamp
},
"DATE" => SqlType::Date,
"BOOLEAN" | "BOOL" => SqlType::Boolean,
_ => SqlType::Other(s.to_string()),
}
}
}