uqa-sql 0.5.0

PostgreSQL-compatible SQL compiler built on libpg_query
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
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
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! Catalog-aware cast selection shares controlled type, array and value constructors.

use uqa_core::{
    memory::{Produced, ProductionControl, ProductionString, ProductionVec},
    ArrayValue, Value,
};

use super::super::casting::{cast_value_from_with_control, parse_pg_array_literal_with_control};
use super::{format_regtype_elements_with_control, format_regtype_value_with_control, EngineHook};
use crate::{
    ast::ColumnType,
    error::{Result, SQLError},
};

mod datestyle;
mod timezone;

/// Catalog input needed after analysis selects a type for an unknown literal. Domain array input includes each element's constraints, so the caller must retain this value rather than read the text again at execution.
pub trait CatalogInputFunctions {
    fn read_unknown_input(&self, text: &str, target: &ColumnType) -> Result<Value>;
}

pub(crate) fn requires_domain_array_input(target: &ColumnType) -> bool {
    matches!(target, ColumnType::Array(element) if matches!(array_leaf_type(element), ColumnType::Domain { .. }))
}

/// Input constants containing named composites or domain array elements must be read while the definition's catalog descriptor is available.
pub(crate) fn requires_catalog_constant_input(target: &ColumnType) -> bool {
    requires_domain_array_input(target)
        || match target {
            ColumnType::Composite(_) => true,
            ColumnType::Array(element) | ColumnType::Domain { base: element, .. } => {
                requires_catalog_constant_input(element)
            }
            _ => false,
        }
}

/// Read a catalog-dependent constant once, retaining its typed datum in stored syntax.
pub fn read_catalog_input(
    text: &str,
    target: &ColumnType,
    engine: &dyn EngineHook,
) -> Result<Value> {
    if requires_domain_array_input(target) {
        return read_catalog_array_input(text, target, engine);
    }
    if !requires_catalog_constant_input(target) {
        return Err(SQLError::Internal(
            "catalog input requires a composite or domain array".into(),
        ));
    }
    super::cast_value_with_type_resolution(
        &Value::Str(text.into()),
        Some("unknown"),
        &target.catalog_name(),
        Some(engine),
    )
}

/// Read an array whose elements are domains with the same input and constraint path as a catalog-aware cast. The resolved target preserves domain identity; a scalar outer domain remains the surrounding expression's runtime coercion.
pub fn read_catalog_array_input(
    text: &str,
    target: &ColumnType,
    engine: &dyn EngineHook,
) -> Result<Value> {
    if !requires_domain_array_input(target) {
        return Err(SQLError::Internal(
            "catalog array input requires domain elements".into(),
        ));
    }
    let control = ProductionControl::uncontrolled();
    let parsed = parse_pg_array_literal_with_control(text, &control)?
        .into_uncontrolled()
        .map_err(|_| SQLError::Internal("ordinary catalog array input owner".into()))?;
    cast_catalog_array(&Value::Array(parsed), None, target, engine, &control)?
        .into_uncontrolled()
        .map_err(|_| SQLError::Internal("ordinary catalog array input owner".into()))
}

#[must_use]
pub fn coercion_type_name(ty: &ColumnType) -> String {
    coercion_type_name_with_control(ty, &ProductionControl::uncontrolled())
        .expect("ordinary coercion type name")
        .into_uncontrolled()
        .expect("ordinary coercion type name owner")
}

fn coercion_type_name_with_control(
    ty: &ColumnType,
    control: &ProductionControl<'_>,
) -> Result<Produced<String>> {
    control.check()?;
    match ty {
        ColumnType::Domain { base, .. } => coercion_type_name_with_control(base, control),
        ColumnType::Array(element) => {
            let element = coercion_type_name_with_control(element, control)?;
            let mut name = ProductionString::new(*control);
            name.push_str(&element)?;
            name.push_str("[]")?;
            Ok(name.finish()?)
        }
        _ => Ok(ty.sql_name_with_control(control)?),
    }
}

/// The types of `PostgreSQL`'s string category, which any type casts to through its output function.
fn is_string_type(ty: &ColumnType) -> bool {
    matches!(
        ty,
        ColumnType::Text | ColumnType::Name | ColumnType::Varchar(_) | ColumnType::Character(_)
    )
}

fn regrole_array_type(ty: &ColumnType) -> bool {
    match ty {
        ColumnType::Array(element) => {
            matches!(element.as_ref(), ColumnType::Regrole) || regrole_array_type(element)
        }
        _ => false,
    }
}

fn array_leaf_type(ty: &ColumnType) -> &ColumnType {
    match ty {
        ColumnType::Array(element) => array_leaf_type(element),
        _ => ty,
    }
}

fn optional_type_name(
    name: &str,
    control: &ProductionControl<'_>,
) -> Result<Option<Produced<ColumnType>>> {
    match ColumnType::from_sql_name_with_control(name, control) {
        Ok(ty) => Ok(Some(ty)),
        Err(error) if matches!(error.sqlstate(), Some("53200" | "57014")) => Err(error),
        Err(_) => Ok(None),
    }
}

/// Cast a value after resolving catalog-owned types and enforcing domain constraints before exposing a base-type carrier.
pub fn cast_value_with_type_resolution(
    value: &Value,
    source_ty: Option<&str>,
    target_ty: &str,
    engine: Option<&dyn EngineHook>,
) -> Result<Value> {
    cast_value_with_type_resolution_with_control(
        value,
        source_ty,
        target_ty,
        engine,
        &ProductionControl::uncontrolled(),
    )?
    .into_uncontrolled()
    .map_err(|_| SQLError::Internal("ordinary catalog cast owner".into()))
}

/// The text a value's output function spells, and the type to cast it from, when a cast goes through output: an enum label, `record_out` of a composite record cast to a string type, and a container whose enum fields and elements spell their current labels.
fn output_for_cast<'a>(
    engine: &dyn EngineHook,
    value: &Value,
    source_ty: Option<&'a str>,
    resolved_source_type: Option<&ColumnType>,
    target: &ColumnType,
) -> Result<Option<(Value, Option<&'a str>)>> {
    if let Value::Enum(label) = value {
        let output =
            super::super::enums::enum_output_for_cast(engine.enum_labels(), label, target)?;
        return Ok(Some((output, Some("text"))));
    }
    // `record_out` spells each field through its attribute type's output function.
    if let (Value::Record(_), Some(source @ ColumnType::Composite(_))) =
        (value, resolved_source_type)
    {
        if is_string_type(target) {
            let text = crate::result::format_postgres_text(value, source, Some(engine))?;
            return Ok(Some((Value::Str(text), Some("text"))));
        }
    }
    if matches!(value, Value::Record(_) | Value::Row(_))
        && is_string_type(target)
        && super::super::enums::contains_enum_carrier(value)
    {
        let rendered = super::super::enums::render_enum_labels(engine.enum_labels(), value)?;
        return Ok(Some((rendered, source_ty)));
    }
    Ok(None)
}

/// Array output borrows the input and retains both intermediate labels and final text under the caller's production budget.
fn enum_array_output(
    value: &Value,
    source_ty: Option<&str>,
    target_ty: &str,
    target: &ColumnType,
    engine: &dyn EngineHook,
    control: &ProductionControl<'_>,
) -> Result<Option<Produced<Value>>> {
    if !matches!(value, Value::Array(_))
        || !is_string_type(target)
        || !super::super::enums::contains_enum_carrier(value)
    {
        return Ok(None);
    }
    let text_array = ColumnType::Array(Box::new(ColumnType::Text));
    let labels = cast_catalog_array(value, source_ty, &text_array, engine, control)?;
    cast_value_from_with_control(&labels, target_ty, Some("text[]"), control).map(Some)
}

/// Resolve catalog inputs at their external handoff, then admit SQL-owned names, element conversions and output before constructing them.
pub fn cast_value_with_type_resolution_with_control(
    value: &Value,
    source_ty: Option<&str>,
    target_ty: &str,
    engine: Option<&dyn EngineHook>,
    control: &ProductionControl<'_>,
) -> Result<Produced<Value>> {
    control.check()?;
    let resolved_target = engine
        .map(|engine| engine.resolve_type_name(target_ty))
        .transpose()
        .map_err(SQLError::Internal)?
        .flatten()
        .map(|ty| ty.retain_external_with_control(control))
        .transpose()?;
    control.check()?;
    let resolved_source_type = match (engine, source_ty) {
        (Some(engine), Some(source)) => engine
            .resolve_type_name(source)
            .map_err(SQLError::Internal)?,
        _ => None,
    };
    let parsed_target = if resolved_target.is_some() {
        None
    } else {
        optional_type_name(target_ty, control)?
    };
    let target_column_type = resolved_target.as_deref().or(parsed_target.as_deref());
    let _date_order = datestyle::input_scope(value, target_column_type, engine, control)?;
    if let (Some(engine), Some(target)) = (engine, resolved_target.as_deref()) {
        if let Some(value) = engine.cast_domain(value, source_ty, target)? {
            return Ok(control.retain_external_value(value)?);
        }
        if let Some(value) = super::super::enums::cast_to_enum(
            engine.enum_labels(),
            value,
            resolved_source_type.as_ref(),
            target,
        )? {
            return Ok(control.retain_external_value(value)?);
        }
        if let Some(value) = super::super::composites::cast_to_composite(
            engine,
            value,
            resolved_source_type.as_ref(),
            target,
        )? {
            return Ok(control.retain_external_value(value)?);
        }
        if let Some(output) =
            enum_array_output(value, source_ty, target_ty, target, engine, control)?
        {
            return Ok(output);
        }
        if let Some((output, output_source)) = output_for_cast(
            engine,
            value,
            source_ty,
            resolved_source_type.as_ref(),
            target,
        )? {
            return cast_value_with_type_resolution_with_control(
                &output,
                output_source,
                target_ty,
                Some(engine),
                control,
            );
        }
        control.check()?;
        if matches!(target, ColumnType::Array(_))
            && (requires_catalog_array_cast(target)
                || super::super::enums::contains_enum_carrier(value)
                || resolved_source_type
                    .as_ref()
                    .is_some_and(super::super::enums::is_enum_bearing))
        {
            return cast_catalog_array(value, source_ty, target, engine, control);
        }
    }
    let resolved_source = match (engine, source_ty) {
        (Some(engine), Some(source_ty)) => engine
            .resolve_type_name(source_ty)
            .map_err(SQLError::Internal)?
            .map(|ty| {
                let ty = ty.retain_external_with_control(control)?;
                coercion_type_name_with_control(&ty, control)
            })
            .transpose()?,
        _ => None,
    };
    let source_ty = resolved_source.as_deref().map(String::as_str).or(source_ty);
    let target_name = resolved_target
        .as_ref()
        .map(|ty| coercion_type_name_with_control(ty, control))
        .transpose()?;
    let target_ty = target_name.as_ref().map_or(target_ty, |name| name.as_str());
    cast_resolved_value(
        value,
        source_ty,
        target_ty,
        target_column_type,
        engine,
        control,
    )
}

fn cast_resolved_value(
    value: &Value,
    source_ty: Option<&str>,
    target_ty: &str,
    target_column_type: Option<&ColumnType>,
    engine: Option<&dyn EngineHook>,
    control: &ProductionControl<'_>,
) -> Result<Produced<Value>> {
    if target_column_type.is_some_and(regrole_array_type) {
        let source_column_type = source_ty
            .map(|name| optional_type_name(name, control))
            .transpose()?
            .flatten();
        let source_name = source_column_type
            .as_deref()
            .map(array_leaf_type)
            .map(|ty| ty.sql_name_with_control(control))
            .transpose()?;
        return cast_array(
            value,
            source_name.as_ref().map(|name| name.as_str()),
            "regrole",
            "regrole[]",
            engine,
            control,
        );
    }
    // `find_coercion_pathway` casts an OID alias to a string type through its output function, as `CoerceViaIO`, and the string type then applies its own modifier; an array does so element by element.
    if let Some(ColumnType::Array(element)) = target_column_type {
        if is_string_type(element) {
            if let Some(source_ty) = source_ty
                .map(|source| optional_type_name(source, control))
                .transpose()?
                .flatten()
            {
                if let Some(elements) =
                    format_regtype_elements_with_control(value, &source_ty, engine, control)?
                {
                    let (elements, _memory) = elements.into_parts();
                    return cast_value_from_with_control(
                        &Value::Array(elements),
                        target_ty,
                        Some("text[]"),
                        control,
                    );
                }
            }
        }
    }
    let text_target = target_ty.eq_ignore_ascii_case("text");
    if text_target || target_column_type.is_some_and(is_string_type) {
        if let Some(source_ty) = source_ty
            .map(|source| optional_type_name(source, control))
            .transpose()?
            .flatten()
        {
            if let Some(text) =
                format_regtype_value_with_control(value, &source_ty, engine, control)?
            {
                let (text, memory) = text.into_parts();
                if text_target {
                    return Ok(control.finish(Value::Str(text), memory)?);
                }
                return cast_value_from_with_control(
                    &Value::Str(text),
                    target_ty,
                    Some("text"),
                    control,
                );
            }
        }
    }
    if let (Some(engine), Value::Str(name) | Value::FixedChar(name)) = (engine, value) {
        let oid = resolve_regobject_input(name, target_ty, target_column_type, engine, control)?;
        if let Some(oid) = oid {
            return Ok(control.finish(Value::Int(oid), control.empty_reservation())?);
        }
    }
    let zoned = timezone::cast_local_timestamp(value, target_column_type, engine, control)?;
    cast_value_from_with_control(
        zoned.as_ref().unwrap_or(value),
        target_ty,
        source_ty,
        control,
    )
}

fn resolve_regobject_input(
    name: &str,
    target_ty: &str,
    target_column_type: Option<&ColumnType>,
    engine: &dyn EngineHook,
    control: &ProductionControl<'_>,
) -> Result<Option<i64>> {
    enum ObjectKind {
        Relation,
        RoutineName,
        Routine,
        Role,
        Namespace,
        Type,
    }
    let kind = if target_ty.eq_ignore_ascii_case("regclass") {
        ObjectKind::Relation
    } else if matches!(target_column_type, Some(ColumnType::Regproc))
        || target_ty.eq_ignore_ascii_case("regproc")
    {
        ObjectKind::RoutineName
    } else if target_ty.eq_ignore_ascii_case("regprocedure") {
        ObjectKind::Routine
    } else if target_ty.eq_ignore_ascii_case("regrole") {
        ObjectKind::Role
    } else if matches!(target_column_type, Some(ColumnType::Regnamespace)) {
        ObjectKind::Namespace
    } else if matches!(target_column_type, Some(ColumnType::Regtype)) {
        ObjectKind::Type
    } else {
        return Ok(None);
    };
    let oid = match kind {
        ObjectKind::Relation => engine.resolve_regclass_input(name)?,
        // `regprocin` reports its own missing and ambiguous names.
        ObjectKind::RoutineName => return engine.resolve_regproc(name),
        ObjectKind::Routine => engine.resolve_regprocedure_input(name)?,
        ObjectKind::Role => engine.resolve_regrole(name)?,
        ObjectKind::Namespace => engine.resolve_regnamespace(name)?,
        ObjectKind::Type => engine.resolve_regtype_input(name)?,
    };
    control.check()?;
    if oid.is_some() || matches!(kind, ObjectKind::Type) {
        return Ok(oid);
    }
    let (sqlstate, message) = match kind {
        ObjectKind::Relation => ("42P01", format!("relation \"{name}\" does not exist")),
        ObjectKind::Routine => ("42883", format!("function \"{name}\" does not exist")),
        ObjectKind::Role => ("42704", format!("role \"{name}\" does not exist")),
        ObjectKind::Namespace => ("3F000", format!("schema \"{name}\" does not exist")),
        ObjectKind::Type | ObjectKind::RoutineName => {
            unreachable!("regtype and regproc input return before reporting a missing object")
        }
    };
    Err(SQLError::Routine {
        sqlstate: sqlstate.into(),
        message,
    })
}

/// Whether an array cast needs the catalog for its elements: domains, enums, composites and the OID alias types whose input functions read catalog names. `regrole[]` has its own path above.
fn requires_catalog_array_cast(ty: &ColumnType) -> bool {
    match ty {
        ColumnType::Domain { .. }
        | ColumnType::Regtype
        | ColumnType::Regclass
        | ColumnType::Regproc
        | ColumnType::Regprocedure
        | ColumnType::Regnamespace
        | ColumnType::Enum(_)
        | ColumnType::Composite(_)
        | ColumnType::TimestampTz
        | ColumnType::TimestampTzPrecision(_) => true,
        ColumnType::Array(element) => requires_catalog_array_cast(element),
        _ => false,
    }
}

fn cast_catalog_array(
    value: &Value,
    source: Option<&str>,
    target: &ColumnType,
    engine: &dyn EngineHook,
    control: &ProductionControl<'_>,
) -> Result<Produced<Value>> {
    if matches!(value, Value::Null) {
        return Ok(control.finish(Value::Null, control.empty_reservation())?);
    }
    let source_element = source.map(|name| name.trim_end_matches("[]"));
    let leaf = array_leaf_type(target);
    let target_element = control.copy_text(&leaf.catalog_name())?;
    let target_name = target.sql_name_with_control(control)?;
    cast_array(
        value,
        source_element,
        &target_element,
        &target_name,
        Some(engine),
        control,
    )
}

fn cast_array(
    value: &Value,
    source: Option<&str>,
    target_element: &str,
    target_name: &str,
    engine: Option<&dyn EngineHook>,
    control: &ProductionControl<'_>,
) -> Result<Produced<Value>> {
    let parsed;
    let array = match value {
        Value::Array(array) => array,
        Value::Str(text) => {
            parsed = parse_pg_array_literal_with_control(text, control)?;
            &parsed
        }
        other => {
            return Err(SQLError::TypeMismatch(format!(
                "CAST AS {target_name}: expected array, got {other:?}"
            )))
        }
    };
    let elements = cast_array_elements(array.elements(), source, target_element, engine, control)?;
    let array = rebuild_array(array, elements, control)?
        .ok_or_else(|| SQLError::TypeMismatch("array dimensions changed during cast".into()))?;
    let (array, memory) = array.into_parts();
    Ok(control.finish(Value::Array(array), memory)?)
}

fn cast_array_elements(
    values: &[Value],
    source: Option<&str>,
    target: &str,
    engine: Option<&dyn EngineHook>,
    control: &ProductionControl<'_>,
) -> Result<Produced<Vec<Value>>> {
    let mut output = ProductionVec::new(*control);
    output.reserve(values.len())?;
    for value in values {
        let value = match value {
            Value::List(values) => {
                let (values, memory) =
                    cast_array_elements(values, source, target, engine, control)?.into_parts();
                control.finish(Value::List(values), memory)?
            }
            value => cast_value_with_type_resolution_with_control(
                value, source, target, engine, control,
            )?,
        };
        output.push_produced(value)?;
    }
    Ok(output.finish()?)
}

pub(super) fn rebuild_array(
    source: &ArrayValue,
    elements: Produced<Vec<Value>>,
    control: &ProductionControl<'_>,
) -> Result<Option<Produced<ArrayValue>>> {
    let mut bounds = ProductionVec::new(*control);
    bounds.reserve(source.lower_bounds().len())?;
    for bound in source.lower_bounds() {
        bounds.push_copy(*bound)?;
    }
    Ok(ArrayValue::with_lower_bounds_with_control(
        elements,
        bounds.finish()?,
        control,
    )?)
}

#[cfg(test)]
mod tests;