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

use super::super::*;
use crate::{
    expr::{
        composites::{CompositeAttribute, CompositeTypeDescriptor},
        enums::EnumTypeLabels,
        SQLValueCatalog,
    },
    ColumnType,
};
use std::sync::Arc;
use uqa_core::{
    memory::MemoryBudget, ArrayValue, CancellationToken, RecordFieldType, RecordValue, RowValue,
};

fn row(text: &str, collation_oid: u32) -> Value {
    Value::Row(
        RowValue::typed(
            vec![Value::Str(text.into())],
            vec![RecordFieldType {
                oid: 25,
                type_modifier: -1,
                collation_oid: Some(collation_oid),
            }],
        )
        .unwrap(),
    )
}

struct Catalog(Vec<Arc<CompositeTypeDescriptor>>);

impl Catalog {
    fn new() -> Self {
        Self(
            [
                (90_001, ColumnType::Text, 950),
                (90_002, ColumnType::Text, 963),
                (90_003, composite_type(90_001), 0),
                (90_004, composite_type(90_002), 0),
                (90_005, ColumnType::Array(Box::new(ColumnType::Text)), 963),
            ]
            .into_iter()
            .map(|(type_oid, ty, collation)| {
                Arc::new(CompositeTypeDescriptor {
                    type_oid,
                    relation_oid: type_oid + 10,
                    dropped: vec![],
                    attributes: vec![CompositeAttribute {
                        name: "v".into(),
                        number: 1,
                        ty,
                        collation_oid: Some(collation),
                    }],
                })
            })
            .collect(),
        )
    }
}

impl SQLValueCatalog for Catalog {
    fn value_type_by_oid(&self, oid: u32) -> Result<Option<ColumnType>> {
        if self.0.iter().any(|descriptor| descriptor.type_oid == oid) {
            return Ok(Some(composite_type(oid)));
        }
        if [90_101, 90_102].contains(&oid) {
            return Ok(Some(domain_type(oid)));
        }
        Ok(crate::catalog::type_metadata::builtin_array_element(oid)
            .map(|element| ColumnType::Array(Box::new(element.clone()))))
    }

    fn value_composite_type(&self, oid: u32) -> Result<Option<Arc<CompositeTypeDescriptor>>> {
        Ok(self
            .0
            .iter()
            .find(|descriptor| descriptor.type_oid == oid)
            .cloned())
    }
    fn enum_type_labels(&self, _: u32) -> Result<Option<Arc<EnumTypeLabels>>> {
        Ok(None)
    }
    fn enum_label_uncommitted(&self, _: u32) -> bool {
        false
    }
    fn enum_type_name(&self, _: u32) -> Result<Option<String>> {
        Ok(None)
    }
    fn has_enum_types(&self) -> bool {
        false
    }
}

fn typed_row(values: Vec<Value>, fields: &[(u32, Option<u32>)]) -> Value {
    Value::Row(
        RowValue::typed(
            values,
            fields
                .iter()
                .map(|(oid, collation_oid)| RecordFieldType {
                    oid: *oid,
                    type_modifier: -1,
                    collation_oid: *collation_oid,
                })
                .collect(),
        )
        .unwrap(),
    )
}

fn named(text: &str, oid: u32) -> Value {
    Value::Record(RecordValue::from_parts(
        vec![("v".into(), Value::Str(text.into()))],
        Some(oid),
    ))
}

fn array(text: Option<&str>) -> Value {
    Value::Array(
        ArrayValue::try_new(text.into_iter().map(|v| Value::Str(v.into())).collect())
            .unwrap()
            .with_element_type_oid(Some(25)),
    )
}

fn operands(suffix: &str) -> (Value, Value) {
    let mismatch = || (row("a", 950), row("b", 963));
    match suffix {
        "equal_text_mismatch" => (row("a", 950), row("a", 963)),
        "unequal_text_mismatch" => mismatch(),
        "null_text_mismatch" => (
            typed_row(vec![Value::Null], &[(25, Some(950))]),
            typed_row(vec![Value::Null], &[(25, Some(963))]),
        ),
        "one_null_mismatch" => (
            typed_row(vec![Value::Null], &[(25, Some(950))]),
            row("a", 963),
        ),
        "deciding_prefix" | "reached_mismatch" => {
            let right_prefix = if suffix == "deciding_prefix" { 2 } else { 1 };
            (
                typed_row(
                    vec![Value::Int(1), Value::Str("a".into())],
                    &[(23, Some(0)), (25, Some(950))],
                ),
                typed_row(
                    vec![Value::Int(right_prefix), Value::Str("b".into())],
                    &[(23, Some(0)), (25, Some(963))],
                ),
            )
        }
        "named_mismatch" => (named("B", 90_001), named("a", 90_002)),
        "named_unicode" => (named("B", 90_002), named("a", 90_002)),
        "named_c" => (named("B", 90_001), named("a", 90_001)),
        "array_field_mismatch" | "empty_array_mismatch" => {
            let populated = suffix == "array_field_mismatch";
            (
                typed_row(vec![array(populated.then_some("a"))], &[(1009, Some(950))]),
                typed_row(vec![array(populated.then_some("b"))], &[(1009, Some(963))]),
            )
        }
        other => panic!("uncaptured record input {other}"),
    }
}

#[test]
fn record_collation_matches_all_postgresql_lazy_field_cases() {
    let reference: serde_json::Value =
        serde_json::from_str(include_str!("record_collations.json")).unwrap();
    let memory = MemoryBudget::new(1024 * 1024);
    let token = CancellationToken::new();
    let catalog = Catalog::new();
    for control in [
        ProductionControl::uncontrolled(),
        ProductionControl::new(&memory, &token, &token),
    ] {
        for case in reference["cases"].as_array().unwrap() {
            let name = case["name"].as_str().unwrap();
            let ordering = name.starts_with("btrecordcmp_");
            let suffix = name
                .strip_prefix("btrecordcmp_")
                .or_else(|| name.strip_prefix("record_eq_"))
                .unwrap();
            let (left, right) = operands(suffix);
            let result = if ordering {
                compare_typed_values_with_enum_catalog(
                    &left,
                    &right,
                    &control,
                    Some(&catalog),
                    None,
                )
                .map(|v| match v {
                    Ordering::Less => "-1",
                    Ordering::Equal => "0",
                    Ordering::Greater => "1",
                })
            } else {
                equal_typed_values_with_enum_catalog(&left, &right, &control, Some(&catalog))
                    .map(|v| if v { "t" } else { "f" })
            };
            match result {
                Ok(value) => assert_eq!(case["output"].as_str(), Some(value), "{name}"),
                Err(error) => {
                    assert_eq!(error.sqlstate(), case["sqlstate"].as_str(), "{name}");
                    assert_eq!(
                        error.to_string(),
                        case["message"].as_str().unwrap(),
                        "{name}"
                    );
                    assert_eq!(error.hint(), case["hint"].as_str(), "{name}");
                }
            }
            assert_eq!(memory.used(), 0, "{name}");
        }
    }
    assert_eq!(reference["cases"].as_array().unwrap().len(), 22);
}

#[test]
fn selected_collation_reaches_array_elements_and_preserves_empty_and_null_shortcuts() {
    let control = ProductionControl::uncontrolled();
    let left = array(Some("B"));
    let right = array(Some("a"));
    assert!(
        compare_typed_values_with_catalog_and_collation(&left, &right, 963, &control, None)
            .unwrap()
            .is_gt()
    );
    assert!(
        compare_typed_values_with_catalog_and_collation(&left, &right, 950, &control, None)
            .unwrap()
            .is_lt()
    );
    assert_eq!(
        compare_typed_values_with_catalog_and_collation(&left, &right, 0, &control, None)
            .unwrap_err()
            .sqlstate(),
        Some("42P22")
    );
    assert!(equal_typed_values_with_catalog_and_collation(
        &array(None),
        &array(None),
        0,
        &control,
        None
    )
    .unwrap());
    assert!(compare_typed_values_with_catalog_and_collation(
        &Value::Null,
        &Value::Null,
        0,
        &control,
        None
    )
    .unwrap()
    .is_eq());
    let legacy = typed_row(vec![Value::Str("a".into())], &[(25, None)]);
    assert!(equal_typed_values_with_enum_catalog(&legacy, &row("a", 100), &control, None).unwrap());
    let invalid = row("a", 0);
    assert_eq!(
        equal_typed_values_with_enum_catalog(&invalid, &invalid, &control, None)
            .unwrap_err()
            .sqlstate(),
        Some("42P22")
    );
}

#[test]
fn selected_collation_keeps_equality_bounded_and_propagates_quota_and_both_cancellations() {
    let text = "a".to_owned() + &"\u{301}\u{323}".repeat(512);
    let left = row(&text, 963);
    let right = row(&(text.clone() + "b"), 963);
    let memory = MemoryBudget::new(0);
    let original = CancellationToken::new();
    let invoking = CancellationToken::new();
    let control = ProductionControl::new(&memory, &original, &invoking);
    assert!(equal_typed_values_with_enum_catalog(&left, &left, &control, None).unwrap());
    assert!(!equal_typed_values_with_enum_catalog(&left, &right, &control, None).unwrap());
    assert_eq!(
        compare_typed_values_with_control(&left, &right, &control)
            .unwrap_err()
            .sqlstate(),
        Some("53200")
    );
    assert_eq!(memory.used(), 0);
    for original_scope in [true, false] {
        let original = CancellationToken::new();
        let invoking = CancellationToken::new();
        let control = ProductionControl::new(&memory, &original, &invoking);
        if original_scope {
            original.cancel();
        } else {
            invoking.cancel();
        }
        assert_eq!(
            compare_typed_values_with_control(&left, &right, &control)
                .unwrap_err()
                .sqlstate(),
            Some("57014")
        );
        assert_eq!(
            equal_typed_values_with_enum_catalog(&left, &right, &control, None)
                .unwrap_err()
                .sqlstate(),
            Some("57014")
        );
        assert_eq!(memory.used(), 0);
    }
}

fn composite_type(oid: u32) -> ColumnType {
    ColumnType::Composite(crate::ast::CompositeTypeReference {
        schema: "public".into(),
        name: format!("collation_record_{oid}"),
        oid,
        array_oid: oid + 1000,
        relation_oid: oid + 10,
    })
}

fn domain_type(oid: u32) -> ColumnType {
    ColumnType::Domain {
        schema: "public".into(),
        name: format!("collation_domain_{oid}"),
        oid,
        array_oid: Some(oid + 1000),
        collation_oid: Some(if oid == 90_101 { 950 } else { 963 }),
        base: Box::new(ColumnType::Text),
    }
}

fn nested_operands(name: &str, text: &str) -> (Value, ColumnType, u32) {
    let collation = if name.ends_with("unicode") {
        963
    } else if name.ends_with("pg_unicode_fast") {
        6411
    } else {
        950
    };
    if name.starts_with("scalar_") {
        return (Value::Str(text.into()), ColumnType::Text, collation);
    }
    if name.starts_with("domain_array_") {
        let oid = if collation == 950 { 90_101 } else { 90_102 };
        let value = Value::Array(
            ArrayValue::try_new(vec![Value::Str(text.into())])
                .unwrap()
                .with_element_type_oid(Some(oid)),
        );
        return (
            value,
            ColumnType::Array(Box::new(domain_type(oid))),
            collation,
        );
    }
    if name.starts_with("array_") || name.starts_with("nested_array_") {
        let value = if name.starts_with("nested_array_") {
            Value::Array(
                ArrayValue::try_new(vec![array(Some(text))])
                    .unwrap()
                    .with_element_type_oid(Some(25)),
            )
        } else {
            array(Some(text))
        };
        return (
            value,
            ColumnType::Array(Box::new(ColumnType::Text)),
            collation,
        );
    }
    if name.starts_with("anonymous_record_") {
        return (row(text, collation), ColumnType::Record, 0);
    }
    let oid = if collation == 950 { 90_001 } else { 90_002 };
    let value = if name.starts_with("nested_record_") {
        Value::Record(RecordValue::from_parts(
            vec![("v".into(), named(text, oid))],
            Some(oid + 2),
        ))
    } else if name == "record_array_field_unicode" {
        Value::Record(RecordValue::from_parts(
            vec![("v".into(), array(Some(text)))],
            Some(90_005),
        ))
    } else {
        named(text, oid)
    };
    (value, ColumnType::Record, 0)
}

#[test]
fn selected_btree_collation_matches_postgresql_nested_domains_arrays_and_records() {
    let reference: serde_json::Value =
        serde_json::from_str(include_str!("nested_collations.json")).unwrap();
    let memory = MemoryBudget::new(1024 * 1024);
    let token = CancellationToken::new();
    let control = ProductionControl::new(&memory, &token, &token);
    let catalog = Catalog::new();
    for case in reference["cases"].as_array().unwrap() {
        let name = case["name"].as_str().unwrap();
        let (left, ty, collation) = nested_operands(name, "B");
        let (right, _, _) = nested_operands(name, "a");
        let class =
            crate::catalog::index::operator_classes::default_btree_operator_class(&ty).unwrap();
        let binding = class.bind_input(&ty, class.name, &control).unwrap();
        let actual = crate::expr::compare_btree_inputs_with_catalog_and_control(
            binding,
            &left,
            &right,
            collation,
            Some(&catalog),
            &control,
        )
        .unwrap();
        assert_eq!(actual, case["order"].as_i64().unwrap().cmp(&0), "{name}");
        assert_eq!(memory.used(), 0, "{name}");
    }
    assert_eq!(reference["cases"].as_array().unwrap().len(), 19);
}

fn physical_record(value: &Value, ty: &ColumnType, catalog: &Catalog) -> Value {
    let fields = super::super::support::ValueCompositeCatalog(Some(catalog));
    let encoded = crate::expr::datums::encoding::encode(
        value,
        ty,
        Some(&fields),
        &ProductionControl::uncontrolled(),
    )
    .unwrap();
    let mut bytes = vec![0xee];
    bytes.extend_from_slice(&crate::expr::datums::encoding::header(encoded.len()).unwrap());
    bytes.extend_from_slice(&encoded);
    Value::Datum(uqa_core::DatumValue::new(
        crate::catalog::type_metadata::pg_type_oid(ty) as u32,
        1,
        bytes,
    ))
}

#[test]
fn physical_record_collation_reuses_selected_descriptors_and_preserves_diagnostics() {
    let reference: serde_json::Value =
        serde_json::from_str(include_str!("record_collations.json")).unwrap();
    let catalog = Catalog::new();
    let memory = MemoryBudget::new(1024 * 1024);
    let token = CancellationToken::new();
    let control = ProductionControl::new(&memory, &token, &token);
    let mut observations = 0;
    for case in reference["cases"]
        .as_array()
        .unwrap()
        .iter()
        .filter(|case| case["name"].as_str().unwrap().contains("_named_"))
    {
        let name = case["name"].as_str().unwrap();
        let ordering = name.starts_with("btrecordcmp_");
        let suffix = name
            .strip_prefix("btrecordcmp_")
            .or_else(|| name.strip_prefix("record_eq_"))
            .unwrap();
        let (left, right) = operands(suffix);
        let Value::Record(left_record) = &left else {
            panic!("named left")
        };
        let Value::Record(right_record) = &right else {
            panic!("named right")
        };
        let physical_left = physical_record(
            &left,
            &composite_type(left_record.type_oid().unwrap()),
            &catalog,
        );
        let physical_right = physical_record(
            &right,
            &composite_type(right_record.type_oid().unwrap()),
            &catalog,
        );
        for left in [&left, &physical_left] {
            for right in [&right, &physical_right] {
                let result = if ordering {
                    compare_typed_values_with_enum_catalog(
                        left,
                        right,
                        &control,
                        Some(&catalog),
                        None,
                    )
                    .map(|v| match v {
                        Ordering::Less => "-1",
                        Ordering::Equal => "0",
                        Ordering::Greater => "1",
                    })
                } else {
                    equal_typed_values_with_enum_catalog(left, right, &control, Some(&catalog))
                        .map(|v| if v { "t" } else { "f" })
                };
                match result {
                    Ok(value) => assert_eq!(case["output"].as_str(), Some(value), "{name}"),
                    Err(error) => {
                        assert_eq!(error.sqlstate(), case["sqlstate"].as_str(), "{name}");
                        assert_eq!(
                            error.to_string(),
                            case["message"].as_str().unwrap(),
                            "{name}"
                        );
                        assert_eq!(error.hint(), case["hint"].as_str(), "{name}");
                    }
                }
                assert_eq!(memory.used(), 0, "{name}");
                observations += 1;
            }
        }
    }
    assert_eq!(observations, 24);
}