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
use anyhow::{Context, Result};
use fraiseql_core::{
schema::{
EnumDefinition, EnumValueDefinition, FieldDefinition, FieldDenyPolicy, FieldType,
InputFieldDefinition, InputObjectDefinition, InterfaceDefinition, TypeDefinition,
UnionDefinition,
},
validation::CustomTypeDef,
};
use super::SchemaConverter;
use crate::schema::intermediate::{
IntermediateEnum, IntermediateEnumValue, IntermediateField, IntermediateInputField,
IntermediateInputObject, IntermediateInterface, IntermediateScalar, IntermediateType,
IntermediateUnion,
};
impl SchemaConverter {
/// Convert an `IntermediateType` to a compiled `TypeDefinition`.
///
/// # Errors
///
/// Returns an error if any field in the type cannot be converted.
pub(super) fn convert_type(intermediate: IntermediateType) -> Result<TypeDefinition> {
let fields = intermediate
.fields
.into_iter()
.map(Self::convert_field)
.collect::<Result<Vec<_>>>()
.context(format!("Failed to convert type '{}'", intermediate.name))?;
// Owned types bind their relation on the query that returns them, so the
// type-level source is normally empty. An owner-split `extend type`
// federation entity carries a type-level `sql_source` (it has no local
// backing query) which the `_entities` resolver uses as its fallback
// relation (#507); its fields project from the standard `data` jsonb
// column — symmetric with the query path, whose `jsonb_column` also
// defaults to `data`. Regular types keep both empty (byte-identical
// compiled output, and the optimizer's projection-hint heuristic stays off).
let type_sql_source = intermediate.sql_source.unwrap_or_default();
let type_jsonb_column = if type_sql_source.is_empty() {
String::new()
} else {
"data".to_string()
};
Ok(TypeDefinition {
name: intermediate.name.into(),
fields,
description: intermediate.description,
sql_source: type_sql_source.into(),
jsonb_column: type_jsonb_column,
sql_projection_hint: None, // Will be populated by optimizer in
implements: intermediate.implements,
requires_role: intermediate.requires_role,
is_error: intermediate.is_error,
relay: intermediate.relay,
relationships: Vec::new(),
})
}
/// Convert `IntermediateEnum` to `EnumDefinition`
pub(super) fn convert_enum(intermediate: IntermediateEnum) -> EnumDefinition {
let values = intermediate.values.into_iter().map(Self::convert_enum_value).collect();
EnumDefinition {
name: intermediate.name,
values,
description: intermediate.description,
}
}
/// Convert `IntermediateEnumValue` to `EnumValueDefinition`
pub(super) fn convert_enum_value(intermediate: IntermediateEnumValue) -> EnumValueDefinition {
let deprecation = intermediate
.deprecated
.map(|d| fraiseql_core::schema::DeprecationInfo { reason: d.reason });
EnumValueDefinition {
name: intermediate.name,
description: intermediate.description,
deprecation,
}
}
/// Convert `IntermediateScalar` to `CustomTypeDef`
///
/// # Errors
///
/// Currently infallible; always returns `Ok`. The `Result` return type is
/// reserved for future validation of scalar definitions.
pub(super) fn convert_custom_scalar(intermediate: IntermediateScalar) -> Result<CustomTypeDef> {
Ok(CustomTypeDef {
name: intermediate.name,
description: intermediate.description,
specified_by_url: intermediate.specified_by_url,
validation_rules: intermediate.validation_rules,
elo_expression: None,
base_type: intermediate.base_type,
})
}
/// Convert `IntermediateInputObject` to `InputObjectDefinition`
pub(super) fn convert_input_object(
intermediate: IntermediateInputObject,
) -> InputObjectDefinition {
let fields = intermediate.fields.into_iter().map(Self::convert_input_field).collect();
InputObjectDefinition {
name: intermediate.name,
fields,
description: intermediate.description,
metadata: None,
}
}
/// Convert `IntermediateInputField` to `InputFieldDefinition`
pub(super) fn convert_input_field(
intermediate: IntermediateInputField,
) -> InputFieldDefinition {
let deprecation = intermediate
.deprecated
.map(|d| fraiseql_core::schema::DeprecationInfo { reason: d.reason });
// Convert default value to JSON string if present
let default_value = intermediate.default.map(|v| v.to_string());
InputFieldDefinition {
name: intermediate.name,
field_type: intermediate.field_type,
// Carry per-field nullability into the compiled schema so the runtime
// can enforce required input fields (#414). Output fields already do
// this via `convert_field`.
nullable: intermediate.nullable,
description: intermediate.description,
default_value,
deprecation,
validation_rules: Vec::new(),
}
}
/// Convert `IntermediateInterface` to `InterfaceDefinition`
pub(super) fn convert_interface(
intermediate: IntermediateInterface,
) -> Result<InterfaceDefinition> {
let fields = intermediate
.fields
.into_iter()
.map(Self::convert_field)
.collect::<Result<Vec<_>>>()
.context(format!("Failed to convert interface '{}'", intermediate.name))?;
Ok(InterfaceDefinition {
name: intermediate.name,
fields,
description: intermediate.description,
})
}
/// Convert `IntermediateUnion` to `UnionDefinition`
pub(super) fn convert_union(intermediate: IntermediateUnion) -> UnionDefinition {
let mut union_def =
UnionDefinition::new(&intermediate.name).with_members(intermediate.member_types);
if let Some(desc) = intermediate.description {
union_def = union_def.with_description(&desc);
}
union_def
}
/// Convert `IntermediateField` to `FieldDefinition`
///
/// **Key normalization**: `type` → `field_type`
///
/// # Errors
///
/// Returns an error if the field's type string cannot be parsed into a
/// `FieldType`.
pub(super) fn convert_field(intermediate: IntermediateField) -> Result<FieldDefinition> {
let field_type = Self::parse_field_type(&intermediate.field_type)?;
// Extract deprecation info from @deprecated directive if present
let deprecation = intermediate.directives.as_ref().and_then(|directives| {
directives.iter().find(|d| d.name == "deprecated").map(|d| {
let reason = d
.arguments
.as_ref()
.and_then(|args| args.get("reason").and_then(|v| v.as_str()).map(String::from));
fraiseql_core::schema::DeprecationInfo { reason }
})
});
Ok(FieldDefinition {
name: intermediate.name.into(),
field_type,
nullable: intermediate.nullable,
default_value: None,
description: intermediate.description,
vector_config: None,
alias: None,
deprecation,
requires_scope: intermediate.requires_scope,
on_deny: intermediate.on_deny.map_or(FieldDenyPolicy::default(), |v| {
if v == "mask" {
FieldDenyPolicy::Mask
} else {
FieldDenyPolicy::Reject
}
}),
authorize: intermediate.authorize.unwrap_or(false),
encryption: None,
hierarchy: intermediate.hierarchy,
})
}
/// Parse string type name to `FieldType` enum
///
/// Handles built-in scalars, custom object types, and SDL list/non-null
/// wrappers. A list field/argument arrives as the SDL string `"[Inner!]"`,
/// which is unwrapped (recursively) into [`FieldType::List`] so the runtime
/// projects it as a list rather than a single object (#434). A trailing `!`
/// (non-null marker — list-element non-null, or a redundant marker; outer
/// field nullability is tracked separately in `nullable`) is stripped before
/// the base name is matched.
///
/// # Errors
///
/// Currently infallible; unrecognised type names are treated as
/// `FieldType::Object`. The `Result` return type is reserved for future
/// strict validation.
pub(super) fn parse_field_type(type_name: &str) -> Result<FieldType> {
let type_name = type_name.trim();
// Strip a trailing non-null marker first — it can wrap a list ("[Inner!]!")
// or a scalar/object ("Inner!"). Doing this before the list check lets a
// non-null list unwrap correctly; outer field nullability is tracked
// separately in `nullable`.
let type_name = type_name.strip_suffix('!').unwrap_or(type_name).trim();
// SDL list wrapper: "[Inner]" / "[Inner!]" → List(parse(Inner)). Recurse so
// nested lists ("[[Inner!]!]") and the element non-null marker are handled.
if let Some(inner) = type_name.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
return Ok(FieldType::List(Box::new(Self::parse_field_type(inner)?)));
}
Ok(match type_name {
"String" => FieldType::String,
"Int" => FieldType::Int,
"Float" => FieldType::Float,
"Boolean" => FieldType::Boolean,
"ID" => FieldType::Id,
"DateTime" => FieldType::DateTime,
"Date" => FieldType::Date,
"Time" => FieldType::Time,
"Json" => FieldType::Json,
"UUID" => FieldType::Uuid,
"Decimal" => FieldType::Decimal,
"Vector" => FieldType::Vector,
// Custom object types (User, Post, etc.)
custom => FieldType::Object(custom.to_string()),
})
}
/// Check whether a string is a safe SQL identifier.
///
/// Accepts up to three dot-separated segments (`name`, `schema.name`, or
/// `catalog.schema.name`), each matching `[A-Za-z_][A-Za-z0-9_]*`.
/// This prevents SQL injection via view names supplied in
/// `additional_views` or `invalidates_fact_tables`.
pub(crate) fn is_safe_sql_identifier(s: &str) -> bool {
if s.is_empty() {
return false;
}
let parts: Vec<&str> = s.split('.').collect();
if parts.len() > 3 {
return false;
}
parts.iter().all(|part| {
if part.is_empty() {
return false;
}
let mut chars = part.chars();
let first = chars.next().expect("non-empty checked above");
if !first.is_ascii_alphabetic() && first != '_' {
return false;
}
chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
})
}
}