fraiseql-cli 2.3.2

CLI tools for FraiseQL v2 - Schema compilation and development utilities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! Schema Converter
//!
//! Converts `IntermediateSchema` (language-agnostic) to `CompiledSchema` (Rust-specific)

mod directives;
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;

impl SchemaConverter {
    /// Convert `IntermediateSchema` to `CompiledSchema`
    ///
    /// This performs:
    /// 1. Type conversion (intermediate types → compiled types)
    /// 2. Field name normalization (type → `field_type`)
    /// 3. Validation (type references, circular refs, etc.)
    /// 4. Optimization
    ///
    /// # 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(intermediate: IntermediateSchema) -> Result<CompiledSchema> {
        info!("Converting intermediate schema to compiled format");

        // 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) */
            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,
            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")?;
            }
        }

        // 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")?;

        // Validate the compiled schema
        Self::validate(&compiled)?;

        info!("Schema conversion successful");
        Ok(compiled)
    }

    #[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
        let mut interface_names = HashSet::new();
        for interface_def in &schema.interfaces {
            interface_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) {
                    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) {
                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) {
                    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) {
                    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 {
                            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()),
        }
    }
}