Skip to main content

uqa_sql/expr/range/datum/
encoding.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Range physical producers admit output and endpoint scratch under one original allowance.
8
9use super::{
10    align, corrupt, CanonicalMultirange, CanonicalRange, ColumnType, Produced, ProductionControl,
11    ProductionVec, SQLError, Value, ABSOLUTE_OFFSET, EMPTY, LOWER_INCLUSIVE, LOWER_INFINITE,
12    UPPER_INCLUSIVE, UPPER_INFINITE,
13};
14use crate::{
15    catalog::type_metadata::{pg_type_len, pg_type_oid, pg_type_storage},
16    expr::{
17        composites::CompositeTypeCatalog,
18        datums::encoding::{append, header, pad_to},
19        range::RangeValueDescriptor,
20    },
21};
22
23/// The surrounding tuple or catalog constant owns the outer varlena header.
24pub(crate) fn encode(text: &str, ty: &ColumnType) -> Result<Vec<u8>, SQLError> {
25    encode_with_control(text, ty, &ProductionControl::uncontrolled()).map(|bytes| {
26        bytes
27            .into_uncontrolled()
28            .expect("ordinary range Datum encoding")
29    })
30}
31
32pub(crate) fn encode_with_control(
33    text: &str,
34    ty: &ColumnType,
35    control: &ProductionControl<'_>,
36) -> Result<Produced<Vec<u8>>, SQLError> {
37    control.check()?;
38    let mut bytes = ProductionVec::new(*control);
39    append(&mut bytes, &(pg_type_oid(ty) as u32).to_le_bytes())?;
40    match ty {
41        ColumnType::Range(subtype) => {
42            let range = super::super::parse_range_with_control(text, *subtype, control)?;
43            write_bounds(&range, &subtype.scalar_type(), None, &mut bytes, control)?;
44            bytes.push_copy(flags(&range))?;
45        }
46        ColumnType::Multirange(subtype) => {
47            let ranges = super::super::parse_multirange_with_control(text, *subtype, control)?;
48            write_multirange(&ranges, &subtype.scalar_type(), None, &mut bytes, control)?;
49        }
50        _ => return Err(corrupt("non-range payload type")),
51    }
52    Ok(bytes.finish()?)
53}
54
55fn write_multirange<I>(
56    ranges: &CanonicalMultirange<I>,
57    endpoint: &ColumnType,
58    catalog: Option<&dyn CompositeTypeCatalog>,
59    bytes: &mut ProductionVec<'_, u8>,
60    control: &ProductionControl<'_>,
61) -> Result<(), SQLError> {
62    let count = ranges.ranges.len();
63    let count_word = u32::try_from(count).map_err(|_| corrupt("too many ranges"))?;
64    append(bytes, &count_word.to_le_bytes())?;
65    let flags_start = 8 + count.saturating_sub(1) * 4;
66    let start = align(flags_start + count + 4, endpoint)? - 4;
67    pad_to(bytes, start)?;
68    let mut previous = 0;
69    for (index, range) in ranges.ranges.iter().enumerate() {
70        control.check()?;
71        let offset = u32::try_from(bytes.len() - start)
72            .ok()
73            .filter(|offset| *offset < ABSOLUTE_OFFSET)
74            .ok_or_else(|| corrupt("range payload too large"))?;
75        if index > 0 {
76            let item = if index % 4 == 0 {
77                offset | ABSOLUTE_OFFSET
78            } else {
79                offset - previous
80            };
81            bytes.as_mut_slice()[8 + (index - 1) * 4..8 + index * 4]
82                .copy_from_slice(&item.to_le_bytes());
83        }
84        previous = offset;
85        bytes.as_mut_slice()[flags_start + index] = flags(range);
86        write_bounds(range, endpoint, catalog, bytes, control)?;
87        pad_to(bytes, align(bytes.len() + 4, endpoint)? - 4)?;
88    }
89    Ok(())
90}
91
92fn flags<I>(range: &CanonicalRange<I>) -> u8 {
93    if range.empty {
94        return EMPTY;
95    }
96    let lower = if range.lower.is_none() {
97        LOWER_INFINITE
98    } else if range.lower_inclusive {
99        LOWER_INCLUSIVE
100    } else {
101        0
102    };
103    let upper = if range.upper.is_none() {
104        UPPER_INFINITE
105    } else if range.upper_inclusive {
106        UPPER_INCLUSIVE
107    } else {
108        0
109    };
110    lower | upper
111}
112
113fn write_bounds<I>(
114    range: &CanonicalRange<I>,
115    ty: &ColumnType,
116    catalog: Option<&dyn CompositeTypeCatalog>,
117    bytes: &mut ProductionVec<'_, u8>,
118    control: &ProductionControl<'_>,
119) -> Result<(), SQLError> {
120    for value in [range.lower.as_ref(), range.upper.as_ref()]
121        .into_iter()
122        .flatten()
123    {
124        control.check()?;
125        let payload = crate::expr::datums::encoding::encode(value, ty, catalog, control)?;
126        let length = pg_type_len(ty);
127        if length == -1 {
128            if payload.len() < 127 && pg_type_storage(ty) != "p" {
129                bytes.push_copy(((payload.len() as u8 + 1) << 1) | 1)?;
130            } else {
131                pad_to(bytes, align(bytes.len() + 4, ty)? - 4)?;
132                append(bytes, &header(payload.len())?)?;
133            }
134        } else {
135            if usize::try_from(length).ok() != Some(payload.len()) {
136                return Err(corrupt("invalid range bound width"));
137            }
138            pad_to(bytes, align(bytes.len() + 4, ty)? - 4)?;
139        }
140        append(bytes, &payload)?;
141    }
142    Ok(())
143}
144
145/// Preserve a completed range's identity and admitted bounds in the physical carrier, without repeating any selected construction operation.
146pub fn declared_range_datum_with_control(
147    range: &CanonicalRange<u32>,
148    descriptor: &RangeValueDescriptor,
149    catalog: Option<&dyn CompositeTypeCatalog>,
150    control: &ProductionControl<'_>,
151) -> Result<Produced<Value>, SQLError> {
152    control.check()?;
153    check_identity(range.subtype, descriptor)?;
154    let mut bytes = ProductionVec::new(*control);
155    append(&mut bytes, &descriptor.range_oid.to_le_bytes())?;
156    write_bounds(range, &descriptor.endpoint, catalog, &mut bytes, control)?;
157    bytes.push_copy(flags(range))?;
158    finish_datum(descriptor.range_oid, bytes, control)
159}
160
161/// The caller supplies an already normalized multirange; serialization neither sorts members nor invokes canonicalization.
162pub fn declared_multirange_datum_with_control(
163    ranges: &CanonicalMultirange<u32>,
164    descriptor: &RangeValueDescriptor,
165    catalog: Option<&dyn CompositeTypeCatalog>,
166    control: &ProductionControl<'_>,
167) -> Result<Produced<Value>, SQLError> {
168    control.check()?;
169    check_identity(ranges.subtype, descriptor)?;
170    for range in &ranges.ranges {
171        control.check()?;
172        check_identity(range.subtype, descriptor)?;
173    }
174    let mut bytes = ProductionVec::new(*control);
175    append(&mut bytes, &descriptor.multirange_oid.to_le_bytes())?;
176    write_multirange(ranges, &descriptor.endpoint, catalog, &mut bytes, control)?;
177    finish_datum(descriptor.multirange_oid, bytes, control)
178}
179
180fn check_identity(oid: u32, descriptor: &RangeValueDescriptor) -> Result<(), SQLError> {
181    if oid == 0
182        || oid != descriptor.range_oid
183        || descriptor.multirange_oid == 0
184        || oid == descriptor.multirange_oid
185    {
186        return Err(corrupt("inconsistent range type descriptor"));
187    }
188    Ok(())
189}
190
191fn finish_datum(
192    oid: u32,
193    mut bytes: ProductionVec<'_, u8>,
194    control: &ProductionControl<'_>,
195) -> Result<Produced<Value>, SQLError> {
196    let length = bytes.len();
197    let header = header(length)?;
198    append(&mut bytes, &[0; 4])?;
199    bytes.as_mut_slice().copy_within(..length, 4);
200    bytes.as_mut_slice()[..4].copy_from_slice(&header);
201    let (datum, memory) =
202        uqa_core::DatumValue::with_control(oid, 0, bytes.finish()?, control)?.into_parts();
203    Ok(control.finish(Value::Datum(datum), memory)?)
204}