uqa-sql 0.5.4

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
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! Declared-column assignment coercion for scalar, array, vector, and temporal values.

use super::AssignmentContext;
use crate::{ColumnType, SQLError};
use uqa_core::{ArrayValue, DecimalValue, TemporalValue, Value};

mod carrier;
pub(super) use carrier::normalize_existing;
pub use carrier::{contains_legacy_vectors, normalize_legacy_vector_carrier_with_control};

pub fn coerce_assignment_value(
    context: &dyn AssignmentContext,
    value: Value,
    target: &ColumnType,
    source: Option<&ColumnType>,
) -> Result<Value, SQLError> {
    if source.is_some_and(|source| same_catalog_value_type(source, target)) {
        return normalize_existing(value, target);
    }
    if matches!(target, ColumnType::Domain { .. }) {
        let source = source.map(ColumnType::catalog_name);
        if let Some(value) =
            super::domain::assign_domain_value_from(context, &value, source.as_deref(), target)?
        {
            return Ok(value);
        }
    }
    let value = if target.is_character_string() {
        source
            .map(|source| crate::expr::format_regtype_value(&value, source, Some(context)))
            .transpose()?
            .flatten()
            .map(Value::Str)
            .unwrap_or(value)
    } else {
        value
    };
    convert_value_to_column_type_with_context_from(context, value, target, source)
}

fn same_catalog_value_type(source: &ColumnType, target: &ColumnType) -> bool {
    match (source, target) {
        (ColumnType::Domain { oid: source, .. }, ColumnType::Domain { oid: target, .. }) => {
            source == target
        }
        (ColumnType::Composite(source), ColumnType::Composite(target)) => source.oid == target.oid,
        (ColumnType::InternalChar, ColumnType::InternalChar)
        | (ColumnType::PgNodeTree, ColumnType::PgNodeTree) => true,
        (ColumnType::Domain { base, .. }, _) => same_catalog_value_type(base, target),
        (ColumnType::Array(source), ColumnType::Array(target)) => {
            same_catalog_value_type(source, target)
        }
        _ => false,
    }
}

pub fn coerce_json_value(value: Value, jsonb: bool) -> Result<Value, SQLError> {
    crate::expr::cast_value(&value, if jsonb { "jsonb" } else { "json" })
}

pub fn convert_declared_value_to_column_type(
    context: &dyn AssignmentContext,
    value: Value,
    source_ty: &ColumnType,
    target_ty: &ColumnType,
) -> Result<Value, SQLError> {
    if same_catalog_value_type(source_ty, target_ty) {
        return normalize_existing(value, target_ty);
    }
    match (source_ty, target_ty) {
        (ColumnType::Domain { base, .. }, target) => {
            convert_declared_value_to_column_type(context, value, base, target)
        }
        (source, ColumnType::Domain { base, .. }) => {
            convert_declared_value_to_column_type(context, value, source, base)
        }
        (ColumnType::Array(source), ColumnType::Array(target)) => {
            let Value::Array(array) = value else {
                return Err(SQLError::TypeMismatch(format!(
                    "cannot cast a non-array value to {}[]",
                    column_type_name(target)
                )));
            };
            let source = array_scalar_type(source);
            let target = array_scalar_type(target);
            let converted =
                convert_declared_array_elements(context, array.elements(), source, target)?;
            ArrayValue::with_lower_bounds(converted, array.lower_bounds().to_vec())
                .map(|array| {
                    array.with_element_type_oid(Some(crate::catalog::type_metadata::pg_type_oid(
                        target,
                    ) as u32))
                })
                .map(Value::Array)
                .ok_or_else(|| {
                    SQLError::TypeMismatch(
                        "multidimensional arrays must have matching dimensions".into(),
                    )
                })
        }
        (ColumnType::Range(source), ColumnType::Range(target)) if source == target => {
            crate::expr::cast_value_from(&value, target.range_name(), Some(source.range_name()))
        }
        (ColumnType::Range(source), ColumnType::Multirange(target)) if source == target => {
            crate::expr::cast_value_from(
                &value,
                target.multirange_name(),
                Some(source.range_name()),
            )
        }
        (ColumnType::Multirange(source), ColumnType::Multirange(target)) if source == target => {
            crate::expr::cast_value_from(
                &value,
                target.multirange_name(),
                Some(source.multirange_name()),
            )
        }
        (_, ColumnType::Range(_) | ColumnType::Multirange(_)) => {
            Err(SQLError::TypeMismatch(format!(
                "column cannot be cast automatically from type {} to type {}",
                column_type_name(source_ty),
                column_type_name(target_ty)
            )))
        }
        (source, ColumnType::Oid)
            if matches!(
                source,
                ColumnType::SmallInteger
                    | ColumnType::Integer
                    | ColumnType::BigInteger
                    | ColumnType::Oid
                    | ColumnType::Regproc
                    | ColumnType::Regprocedure
                    | ColumnType::Regclass
                    | ColumnType::Regcollation
                    | ColumnType::Regnamespace
                    | ColumnType::Regrole
                    | ColumnType::Regtype
            ) =>
        {
            crate::expr::cast_value_from(&value, "oid", Some(column_type_name(source)))
        }
        (ColumnType::Xid, ColumnType::Xid) => Ok(value),
        (ColumnType::Bytea, ColumnType::Bytea) => Ok(value),
        (_, ColumnType::Oid | ColumnType::Xid | ColumnType::Bytea) => {
            Err(SQLError::TypeMismatch(format!(
                "column cannot be cast automatically from type {} to type {}",
                column_type_name(source_ty),
                column_type_name(target_ty)
            )))
        }
        _ => convert_value_to_column_type_with_context_from(
            context,
            value,
            target_ty,
            Some(source_ty),
        ),
    }
}

/// Whether converting a value to `ty` needs the statement's catalog or session: enum labels, domain constraints, composite attributes, role names or the current time zone.
pub(crate) fn type_requires_catalog_resolution(ty: &ColumnType) -> bool {
    match ty {
        // The OID alias types read a name through the catalog, so an assigned text value becomes the object's OID, as `regclassin` and its siblings read it.
        ColumnType::Regrole
        | ColumnType::Regclass
        | ColumnType::Regtype
        | ColumnType::Regproc
        | ColumnType::Regprocedure
        | ColumnType::Regcollation
        | ColumnType::Regnamespace
        | ColumnType::Domain { .. }
        | ColumnType::Enum(_)
        | ColumnType::Composite(_)
        | ColumnType::TimestampTz
        | ColumnType::TimestampTzPrecision(_) => true,
        ColumnType::Array(element) => type_requires_catalog_resolution(element),
        _ => false,
    }
}

pub fn convert_value_to_column_type_with_context(
    context: &dyn AssignmentContext,
    value: Value,
    ty: &ColumnType,
) -> Result<Value, SQLError> {
    convert_value_to_column_type_with_context_from(context, value, ty, None)
}

fn convert_value_to_column_type_with_context_from(
    context: &dyn AssignmentContext,
    value: Value,
    ty: &ColumnType,
    source: Option<&ColumnType>,
) -> Result<Value, SQLError> {
    // Assignment to a string type calls the enum output function, which reads the current label.
    let value = if textual_target(ty) && crate::expr::enums::contains_enum_carrier(&value) {
        crate::expr::enums::render_enum_labels(
            crate::expr::EngineHook::enum_labels(context),
            &value,
        )?
    } else {
        value
    };
    if let Some(value) = super::domain::assign_domain_value(context, &value, ty)? {
        return Ok(value);
    }
    if matches!(value, Value::Null) {
        return Ok(Value::Null);
    }
    if let ColumnType::Array(element) = ty {
        if type_requires_catalog_resolution(element) {
            return convert_catalog_array(context, value, element);
        }
    }
    if type_requires_catalog_resolution(ty) {
        return crate::expr::cast_value_with_type_resolution(
            &value,
            None,
            &ty.catalog_name(),
            Some(context),
        );
    }
    convert_value_to_column_type_from(value, ty, source)
}

fn textual_target(ty: &ColumnType) -> bool {
    match ty {
        ColumnType::Array(element) => textual_target(element),
        other => other.is_character_string(),
    }
}

fn convert_catalog_array(
    context: &dyn AssignmentContext,
    value: Value,
    element: &ColumnType,
) -> Result<Value, SQLError> {
    let array = match value {
        Value::Array(array) => array,
        Value::Str(text) => crate::expr::parse_pg_array_literal(&text)?,
        other => {
            return Err(SQLError::TypeMismatch(format!(
                "expected an array, got {other:?}"
            )))
        }
    };
    let values = convert_catalog_array_elements(context, array.elements(), element)?;
    ArrayValue::with_lower_bounds(values, array.lower_bounds().to_vec())
        .map(|array| {
            array.with_element_type_oid(Some(crate::catalog::type_metadata::pg_type_oid(
                array_scalar_type(element),
            ) as u32))
        })
        .map(Value::Array)
        .ok_or_else(|| {
            SQLError::TypeMismatch("multidimensional arrays must have matching dimensions".into())
        })
}

fn convert_catalog_array_elements(
    context: &dyn AssignmentContext,
    values: &[Value],
    element: &ColumnType,
) -> Result<Vec<Value>, SQLError> {
    let mut element = element;
    while let ColumnType::Array(nested) = element {
        element = nested;
    }
    values
        .iter()
        .map(|value| match value {
            Value::List(values) => {
                convert_catalog_array_elements(context, values, element).map(Value::List)
            }
            value => convert_value_to_column_type_with_context(context, value.clone(), element),
        })
        .collect()
}

mod production;
pub use production::{
    convert_value_to_column_type_from_with_control, convert_value_to_column_type_with_control,
    numeric_field_overflow,
};

pub fn convert_value_to_column_type(value: Value, ty: &ColumnType) -> Result<Value, SQLError> {
    convert_value_to_column_type_from(value, ty, None)
}

/// Convert a catalog-free assignment while retaining the analyzed source identity.
pub fn convert_value_to_column_type_from(
    value: Value,
    ty: &ColumnType,
    source: Option<&ColumnType>,
) -> Result<Value, SQLError> {
    let control = uqa_core::memory::ProductionControl::uncontrolled();
    convert_value_to_column_type_from_with_control(
        control.finish(value, None)?,
        ty,
        source,
        &control,
    )?
    .into_uncontrolled()
    .map_err(|_| SQLError::Internal("ordinary assignment production owner".into()))
}

fn convert_declared_array_elements(
    context: &dyn AssignmentContext,
    elements: &[Value],
    source_type: &ColumnType,
    target_type: &ColumnType,
) -> Result<Vec<Value>, SQLError> {
    elements
        .iter()
        .cloned()
        .map(|element| match element {
            Value::List(nested) => {
                convert_declared_array_elements(context, &nested, source_type, target_type)
                    .map(Value::List)
            }
            scalar => {
                convert_declared_value_to_column_type(context, scalar, source_type, target_type)
            }
        })
        .collect()
}

fn array_scalar_type(mut ty: &ColumnType) -> &ColumnType {
    while let ColumnType::Array(element) = ty {
        ty = element;
    }
    ty
}

pub fn validate_vector_dimensions(expected: u32, actual: usize) -> Result<(), SQLError> {
    let expected = usize::try_from(expected).map_err(|_| {
        SQLError::TypeMismatch(format!(
            "declared vector dimension {expected} exceeds the platform usize range"
        ))
    })?;
    if actual == expected {
        Ok(())
    } else {
        Err(SQLError::VectorDimMismatch { expected, actual })
    }
}

pub use crate::catalog::type_metadata::column_type_name;

pub use crate::expr::value_to_text;

pub fn json_to_core_value(json: serde_json::Value) -> Value {
    match json {
        serde_json::Value::Null => Value::Null,
        serde_json::Value::Bool(b) => Value::Bool(b),
        serde_json::Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                Value::Int(i)
            } else if let Some(d) = DecimalValue::parse(&n.to_string()) {
                Value::Decimal(d)
            } else if let Some(f) = n.as_f64() {
                Value::Float(f)
            } else {
                Value::Null
            }
        }
        serde_json::Value::String(s) => Value::Str(s),
        serde_json::Value::Array(items) => {
            Value::List(items.into_iter().map(json_to_core_value).collect())
        }
        serde_json::Value::Object(obj) => {
            if let Ok(temporal) =
                serde_json::from_value::<TemporalValue>(serde_json::Value::Object(obj.clone()))
            {
                return Value::Temporal(temporal);
            }
            Value::Map(
                obj.into_iter()
                    .map(|(k, v)| (k, json_to_core_value(v)))
                    .collect(),
            )
        }
    }
}

pub use crate::expr::core_value_to_json;

pub fn json_table_value_to_text(value: &serde_json::Value) -> Value {
    match value {
        serde_json::Value::Null => Value::Null,
        serde_json::Value::String(s) => Value::Str(s.clone()),
        serde_json::Value::Bool(b) => Value::Str(b.to_string()),
        serde_json::Value::Number(n) => Value::Str(n.to_string()),
        serde_json::Value::Array(_) | serde_json::Value::Object(_) => Value::Str(value.to_string()),
    }
}

pub fn json_table_arg(value: &Value, name: &str) -> Result<serde_json::Value, SQLError> {
    match value {
        Value::Json(s) | Value::JsonB(s) | Value::Str(s) => {
            serde_json::from_str::<serde_json::Value>(s)
                .map_err(|e| SQLError::TypeMismatch(format!("{name}: invalid JSON: {e}")))
        }
        other => core_value_to_json(other),
    }
}