fraiseql-core 2.17.0

Core execution engine for FraiseQL v2 - Compiled GraphQL over SQL
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
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
//! Field introspection helpers.
//!
//! Converts `FieldDefinition`, `FieldType`, and validation rules from the compiled
//! schema into their `__Field`, `__InputValue`, and related introspection types.

use super::{
    super::{
        FieldDefinition, FieldType, LOCALIZED_INPUT_TYPE, LOCALIZED_STRING_INPUT_TYPE,
        LOCALIZED_STRING_TYPE, TRANSLATIONS_SUFFIX,
    },
    types::{
        IntrospectionField, IntrospectionInputValue, IntrospectionType,
        IntrospectionValidationRule, TypeKind,
    },
};

// =============================================================================
// Field and type-reference helpers (used by IntrospectionBuilder)
// =============================================================================

/// Build `__Field` introspection from `FieldDefinition`.
pub(super) fn build_field(field: &FieldDefinition) -> IntrospectionField {
    IntrospectionField {
        name:               field.output_name().to_string(),
        description:        field.description.clone(),
        // #1513: a localized field takes `locale:`; no other field has arguments.
        args:               if field.localized {
            vec![locale_argument()]
        } else {
            vec![]
        },
        field_type:         field_type_to_introspection(
            &field.field_type,
            field.published_nullable(),
        ),
        is_deprecated:      field.is_deprecated(),
        deprecation_reason: field.deprecation_reason().map(ToString::to_string),
    }
}

/// A localized field's translations sibling (#1513): `<field>Translations:
/// [LocalizedString!]!`, every allowed label of the field.
pub(super) fn build_translations_field(field: &FieldDefinition) -> IntrospectionField {
    let element = non_null(type_ref_with_kind(LOCALIZED_STRING_TYPE, TypeKind::Object));
    IntrospectionField {
        name:               format!("{}{TRANSLATIONS_SUFFIX}", field.output_name()),
        description:        Some(format!(
            "Every allowed locale's label of `{}`, in the order of the allowed locales.",
            field.output_name()
        )),
        args:               vec![],
        field_type:         non_null(IntrospectionType {
            kind:               TypeKind::List,
            name:               None,
            description:        None,
            fields:             None,
            interfaces:         None,
            possible_types:     None,
            enum_values:        None,
            input_fields:       None,
            of_type:            Some(Box::new(element)),
            specified_by_u_r_l: None,
        }),
        is_deprecated:      field.is_deprecated(),
        deprecation_reason: field.deprecation_reason().map(ToString::to_string),
    }
}

/// `LocalizedString { locale: String! value: String! }`, the element of every translations
/// sibling (#1513).
pub(super) fn build_localized_string_type() -> IntrospectionType {
    let field = |name: &str, description: &str| IntrospectionField {
        name:               name.to_string(),
        description:        Some(description.to_string()),
        args:               vec![],
        field_type:         non_null(type_ref("String")),
        is_deprecated:      false,
        deprecation_reason: None,
    };
    IntrospectionType {
        kind:               TypeKind::Object,
        name:               Some(LOCALIZED_STRING_TYPE.to_string()),
        description:        Some("One locale's label of a localized field.".to_string()),
        fields:             Some(vec![
            field("locale", "The locale tag."),
            field("value", "The label in that locale."),
        ]),
        interfaces:         Some(vec![]),
        possible_types:     None,
        enum_values:        None,
        input_fields:       None,
        of_type:            None,
        specified_by_u_r_l: None,
    }
}

/// `LocalizedInput` and `LocalizedStringInput`, the input types of localized arguments and
/// input fields (#1513).
pub(super) fn build_localized_input_types() -> [IntrospectionType; 2] {
    let value =
        |name: &str, description: &str, input_type: IntrospectionType| IntrospectionInputValue {
            name: name.to_string(),
            description: Some(description.to_string()),
            input_type,
            default_value: None,
            is_deprecated: false,
            deprecation_reason: None,
            validation_rules: vec![],
        };
    let input_object =
        |name: &str, description: &str, fields: Vec<IntrospectionInputValue>| IntrospectionType {
            kind:               TypeKind::InputObject,
            name:               Some(name.to_string()),
            description:        Some(description.to_string()),
            fields:             None,
            interfaces:         None,
            possible_types:     None,
            enum_values:        None,
            input_fields:       Some(fields),
            of_type:            None,
            specified_by_u_r_l: None,
        };
    let list_of_translations = IntrospectionType {
        kind:               TypeKind::List,
        name:               None,
        description:        None,
        fields:             None,
        interfaces:         None,
        possible_types:     None,
        enum_values:        None,
        input_fields:       None,
        of_type:            Some(Box::new(non_null(type_ref_with_kind(
            LOCALIZED_STRING_INPUT_TYPE,
            TypeKind::InputObject,
        )))),
        specified_by_u_r_l: None,
    };
    [
        input_object(
            LOCALIZED_INPUT_TYPE,
            "A localized value: exactly one of `value` (the request locale's label) and \
             `translations`.",
            vec![
                value("value", "The request locale's label.", type_ref("String")),
                value("translations", "Labels by locale.", list_of_translations),
            ],
        ),
        input_object(
            LOCALIZED_STRING_INPUT_TYPE,
            "One locale's label; a null value removes it.",
            vec![
                value("locale", "An allowed locale.", non_null(type_ref("String"))),
                value("value", "The label, or null to remove it.", type_ref("String")),
            ],
        ),
    ]
}

/// `inner`, wrapped in `NON_NULL`.
fn non_null(inner: IntrospectionType) -> IntrospectionType {
    wrap(TypeKind::NonNull, inner)
}

/// A localized field's `locale: String` argument (#1513).
fn locale_argument() -> IntrospectionInputValue {
    IntrospectionInputValue {
        name:               crate::runtime::LOCALE_ARGUMENT.to_string(),
        description:        Some(
            "Read this field in another allowed locale than the request's.".to_string(),
        ),
        input_type:         type_ref("String"),
        default_value:      None,
        is_deprecated:      false,
        deprecation_reason: None,
        validation_rules:   vec![],
    }
}

/// Convert a `FieldType` to its introspection type, wrapping it in `NON_NULL` when not
/// `nullable`, with each list level's items as the type declares them (`[T]` or `[T!]`, at
/// any depth, #1586).
///
/// The one rendering for every position: an output field, an argument (#1614: arguments
/// used to publish every item nullable, so a client was told it may send `[null]` to a
/// `[T!]` argument) and the SDL, which is rendered from this model. It is what responses are
/// completed against (#1522) and what argument values are adjudicated against.
pub(super) fn field_type_to_introspection(
    field_type: &FieldType,
    nullable: bool,
) -> IntrospectionType {
    let inner = match field_type {
        FieldType::Int => type_ref("Int"),
        FieldType::Float => type_ref("Float"),
        // A bit vector's value IS its text form (`0`/`1` characters), and a
        // sparse vector's is `{1:0.5}/1000`, so both introspect as the scalar a
        // client actually receives (#959).
        FieldType::String | FieldType::BitVector | FieldType::SparseVector => type_ref("String"),
        FieldType::Boolean => type_ref("Boolean"),
        FieldType::Id => type_ref("ID"),
        FieldType::DateTime => type_ref("DateTime"),
        FieldType::Date => type_ref("Date"),
        FieldType::Time => type_ref("Time"),
        FieldType::Uuid => type_ref("UUID"),
        // JSON and the dense float vectors are both exposed as JSON
        FieldType::Json | FieldType::Vector | FieldType::HalfVector => type_ref("JSON"),
        FieldType::Decimal => type_ref("Decimal"),
        FieldType::Scalar(name) => type_ref(name), // Rich/custom scalars
        FieldType::Object(name) => type_ref_with_kind(name, TypeKind::Object),
        FieldType::Enum(name) => type_ref_with_kind(name, TypeKind::Enum),
        FieldType::Input(name) => type_ref_with_kind(name, TypeKind::InputObject),
        FieldType::Interface(name) => type_ref_with_kind(name, TypeKind::Interface),
        FieldType::Union(name) => type_ref_with_kind(name, TypeKind::Union),
        FieldType::List {
            item,
            nullable_items,
        } => wrap(TypeKind::List, field_type_to_introspection(item, *nullable_items)),
    };

    if nullable { inner } else { non_null(inner) }
}

/// A `LIST` or `NON_NULL` wrapper around `of_type`.
fn wrap(kind: TypeKind, of_type: IntrospectionType) -> IntrospectionType {
    IntrospectionType {
        kind,
        name: None,
        description: None,
        fields: None,
        interfaces: None,
        possible_types: None,
        enum_values: None,
        input_fields: None,
        of_type: Some(Box::new(of_type)),
        specified_by_u_r_l: None,
    }
}

/// Create a named type reference node with `TypeKind::Scalar`.
///
/// Used for built-in and custom scalar types. For composite types (Object,
/// Enum, `InputObject`, Interface, Union) use [`type_ref_with_kind`] instead.
pub fn type_ref(name: &str) -> IntrospectionType {
    type_ref_with_kind(name, TypeKind::Scalar)
}

/// Create a named type reference node with the given `TypeKind`.
///
/// Introspection clients (`GraphiQL`, code-generators) rely on the `kind`
/// field to distinguish Object from Enum from `InputObject` etc. Hardcoding
/// `Scalar` for every named type breaks tooling that reads `__schema`.
pub fn type_ref_with_kind(name: &str, kind: TypeKind) -> IntrospectionType {
    IntrospectionType {
        kind,
        name: Some(name.to_string()),
        description: None,
        fields: None,
        interfaces: None,
        possible_types: None,
        enum_values: None,
        input_fields: None,
        of_type: None,
        specified_by_u_r_l: None,
    }
}

/// Convert a `ValidationRule` to its introspection representation.
pub(super) fn build_validation_rule(
    rule: &crate::validation::rules::ValidationRule,
) -> IntrospectionValidationRule {
    use crate::validation::rules::ValidationRule;

    match rule {
        ValidationRule::Required => IntrospectionValidationRule {
            rule_type:       "required".to_string(),
            pattern:         None,
            pattern_message: None,
            min:             None,
            max:             None,
            allowed_values:  None,
            algorithm:       None,
            field_reference: None,
            operator:        None,
            field_list:      None,
            description:     Some("Field is required".to_string()),
        },
        ValidationRule::Pattern { pattern, message } => IntrospectionValidationRule {
            rule_type:       "pattern".to_string(),
            pattern:         Some(pattern.as_str().to_string()),
            pattern_message: message.clone(),
            min:             None,
            max:             None,
            allowed_values:  None,
            algorithm:       None,
            field_reference: None,
            operator:        None,
            field_list:      None,
            description:     message.clone(),
        },
        ValidationRule::Length { min, max } => IntrospectionValidationRule {
            rule_type:       "length".to_string(),
            pattern:         None,
            pattern_message: None,
            min:             min.map(|v| i64::try_from(v).unwrap_or(i64::MAX)),
            max:             max.map(|v| i64::try_from(v).unwrap_or(i64::MAX)),
            allowed_values:  None,
            algorithm:       None,
            field_reference: None,
            operator:        None,
            field_list:      None,
            description:     None,
        },
        ValidationRule::Range { min, max } => IntrospectionValidationRule {
            rule_type:       "range".to_string(),
            pattern:         None,
            pattern_message: None,
            min:             *min,
            max:             *max,
            allowed_values:  None,
            algorithm:       None,
            field_reference: None,
            operator:        None,
            field_list:      None,
            description:     None,
        },
        ValidationRule::Enum { values } => IntrospectionValidationRule {
            rule_type:       "enum".to_string(),
            pattern:         None,
            pattern_message: None,
            min:             None,
            max:             None,
            allowed_values:  Some(values.clone()),
            algorithm:       None,
            field_reference: None,
            operator:        None,
            field_list:      None,
            description:     None,
        },
        ValidationRule::Checksum { algorithm } => IntrospectionValidationRule {
            rule_type:       "checksum".to_string(),
            pattern:         None,
            pattern_message: None,
            min:             None,
            max:             None,
            allowed_values:  None,
            algorithm:       Some(algorithm.clone()),
            field_reference: None,
            operator:        None,
            field_list:      None,
            description:     None,
        },
        ValidationRule::CrossField { field, operator } => IntrospectionValidationRule {
            rule_type:       "cross_field".to_string(),
            pattern:         None,
            pattern_message: None,
            min:             None,
            max:             None,
            allowed_values:  None,
            algorithm:       None,
            field_reference: Some(field.clone()),
            operator:        Some(operator.clone()),
            field_list:      None,
            description:     None,
        },
        ValidationRule::Conditional { .. } => IntrospectionValidationRule {
            rule_type:       "conditional".to_string(),
            pattern:         None,
            pattern_message: None,
            min:             None,
            max:             None,
            allowed_values:  None,
            algorithm:       None,
            field_reference: None,
            operator:        None,
            field_list:      None,
            description:     Some("Conditional validation".to_string()),
        },
        ValidationRule::All(_) => IntrospectionValidationRule {
            rule_type:       "all".to_string(),
            pattern:         None,
            pattern_message: None,
            min:             None,
            max:             None,
            allowed_values:  None,
            algorithm:       None,
            field_reference: None,
            operator:        None,
            field_list:      None,
            description:     Some("All rules must pass".to_string()),
        },
        ValidationRule::Any(_) => IntrospectionValidationRule {
            rule_type:       "any".to_string(),
            pattern:         None,
            pattern_message: None,
            min:             None,
            max:             None,
            allowed_values:  None,
            algorithm:       None,
            field_reference: None,
            operator:        None,
            field_list:      None,
            description:     Some("At least one rule must pass".to_string()),
        },
        ValidationRule::OneOf { fields } => IntrospectionValidationRule {
            rule_type:       "one_of".to_string(),
            pattern:         None,
            pattern_message: None,
            min:             None,
            max:             None,
            allowed_values:  None,
            algorithm:       None,
            field_reference: None,
            operator:        None,
            field_list:      Some(fields.clone()),
            description:     None,
        },
        ValidationRule::AnyOf { fields } => IntrospectionValidationRule {
            rule_type:       "any_of".to_string(),
            pattern:         None,
            pattern_message: None,
            min:             None,
            max:             None,
            allowed_values:  None,
            algorithm:       None,
            field_reference: None,
            operator:        None,
            field_list:      Some(fields.clone()),
            description:     None,
        },
        ValidationRule::ConditionalRequired { .. } => IntrospectionValidationRule {
            rule_type:       "conditional_required".to_string(),
            pattern:         None,
            pattern_message: None,
            min:             None,
            max:             None,
            allowed_values:  None,
            algorithm:       None,
            field_reference: None,
            operator:        None,
            field_list:      None,
            description:     None,
        },
        ValidationRule::RequiredIfAbsent { .. } => IntrospectionValidationRule {
            rule_type:       "required_if_absent".to_string(),
            pattern:         None,
            pattern_message: None,
            min:             None,
            max:             None,
            allowed_values:  None,
            algorithm:       None,
            field_reference: None,
            operator:        None,
            field_list:      None,
            description:     None,
        },
        ValidationRule::Email => IntrospectionValidationRule {
            rule_type:       "email".to_string(),
            pattern:         None,
            pattern_message: None,
            min:             None,
            max:             None,
            allowed_values:  None,
            algorithm:       None,
            field_reference: None,
            operator:        None,
            field_list:      None,
            description:     Some("Must be a valid email address".to_string()),
        },
        ValidationRule::Phone => IntrospectionValidationRule {
            rule_type:       "phone".to_string(),
            pattern:         None,
            pattern_message: None,
            min:             None,
            max:             None,
            allowed_values:  None,
            algorithm:       None,
            field_reference: None,
            operator:        None,
            field_list:      None,
            description:     Some("Must be a valid E.164 phone number".to_string()),
        },
    }
}

/// Build `__InputValue` for a query/mutation/subscription argument.
pub(super) fn build_arg_input_value(
    arg: &super::super::ArgumentDefinition,
) -> IntrospectionInputValue {
    // #1513: a localized argument takes `LocalizedInput`.
    let localized = FieldType::Input(LOCALIZED_INPUT_TYPE.to_string());
    let arg_type = if arg.localized {
        &localized
    } else {
        &arg.arg_type
    };
    IntrospectionInputValue {
        name:               arg.name.clone(),
        description:        arg.description.clone(),
        input_type:         field_type_to_introspection(arg_type, arg.nullable),
        default_value:      arg.default_value.as_ref().map(|v| v.to_string()),
        is_deprecated:      arg.is_deprecated(),
        deprecation_reason: arg.deprecation_reason().map(ToString::to_string),
        validation_rules:   vec![],
    }
}