Skip to main content

uqa_sql/expr/
internal_char.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! `PostgreSQL`'s internal char is one unsigned byte, with signed integer conversion and octal high-byte output.
8
9use uqa_core::{
10    memory::{Produced, ProductionControl},
11    Value, ValueRetentionError,
12};
13
14pub(crate) fn input_byte(text: &str) -> u8 {
15    let bytes = text.as_bytes();
16    match bytes {
17        [b'\\', a @ b'0'..=b'7', b @ b'0'..=b'7', c @ b'0'..=b'7'] => {
18            ((u16::from(*a - b'0') << 6) | (u16::from(*b - b'0') << 3) | u16::from(*c - b'0')) as u8
19        }
20        bytes => bytes.first().copied().unwrap_or(0),
21    }
22}
23
24/// Observe an admitted internal-character carrier without applying text input conversion.
25pub fn value_byte(value: &Value) -> Option<u8> {
26    let Value::Str(text) = value else {
27        return None;
28    };
29    if text.is_empty() {
30        return Some(0);
31    }
32    let mut characters = text.chars();
33    let byte = u8::try_from(u32::from(characters.next()?)).ok()?;
34    characters.next().is_none().then_some(byte)
35}
36
37/// Construct an internal-character carrier from its complete unsigned byte domain.
38pub fn carrier_with_control(
39    byte: u8,
40    control: &ProductionControl<'_>,
41) -> Result<Produced<Value>, ValueRetentionError> {
42    let text = if byte == 0 {
43        control.copy_text("")?
44    } else {
45        control.format(format_args!("{}", char::from(byte)))?
46    };
47    let (text, memory) = text.into_parts();
48    control.finish(Value::Str(text), memory)
49}
50
51pub(crate) fn output_with_control(
52    byte: u8,
53    control: &ProductionControl<'_>,
54) -> Result<Produced<String>, ValueRetentionError> {
55    if byte >= 128 {
56        control.format(format_args!("\\{byte:03o}"))
57    } else if byte == 0 {
58        control.copy_text("")
59    } else {
60        control.format(format_args!("{}", char::from(byte)))
61    }
62}
63
64#[cfg(test)]
65mod tests {
66    use super::*;
67    use crate::{
68        expr::{cast_value_from, composites::datum, datums},
69        ColumnType,
70    };
71    use uqa_core::{memory::MemoryBudget, CancellationToken, DatumValue};
72
73    #[test]
74    fn input_and_output_preserve_postgresql_byte_and_integer_rules() {
75        for (text, byte, output) in [
76            ("", 0, ""),
77            ("abc", b'a', "a"),
78            ("é", 0xc3, "\\303"),
79            ("\\377", 255, "\\377"),
80            ("\\777", 255, "\\377"),
81            ("\\128", b'\\', "\\"),
82        ] {
83            assert_eq!(input_byte(text), byte);
84            let value = cast_value_from(
85                &Value::Str(text.into()),
86                "pg_catalog.\"char\"",
87                Some("pg_catalog.\"text\""),
88            )
89            .unwrap();
90            assert_eq!(value_byte(&value), Some(byte));
91            assert_eq!(
92                cast_value_from(&value, "pg_catalog.\"text\"", Some("pg_catalog.\"char\""))
93                    .unwrap(),
94                Value::Str(output.into())
95            );
96            assert_eq!(
97                crate::result::format_postgres_text(&value, &ColumnType::InternalChar, None)
98                    .unwrap(),
99                output
100            );
101        }
102        for integer in -128_i64..=127 {
103            let value = cast_value_from(
104                &Value::Int(integer),
105                "pg_catalog.\"char\"",
106                Some("pg_catalog.\"int4\""),
107            )
108            .unwrap();
109            assert_eq!(value_byte(&value), Some(integer as u8));
110            assert_eq!(
111                cast_value_from(&value, "pg_catalog.\"int4\"", Some("pg_catalog.\"char\""))
112                    .unwrap(),
113                Value::Int(integer)
114            );
115        }
116        for integer in [-129, 128] {
117            let error = cast_value_from(
118                &Value::Int(integer),
119                "pg_catalog.\"char\"",
120                Some("pg_catalog.\"int4\""),
121            )
122            .unwrap_err();
123            assert_eq!(error.sqlstate(), Some("22003"));
124            assert_eq!(error.to_string(), "\"char\" out of range");
125        }
126    }
127
128    #[test]
129    fn retained_bytes_and_carrier_order_preserve_every_unsigned_byte() {
130        let token = CancellationToken::new();
131        let memory = MemoryBudget::new(4096);
132        let control = ProductionControl::new(&memory, &token, &token);
133        let mut previous: Option<Value> = None;
134        for byte in 0..=255 {
135            let value =
136                datums::read_with_control(&DatumValue::new(18, 0, vec![byte]), &control).unwrap();
137            assert_eq!(value_byte(&value), Some(byte));
138            assert_eq!(
139                datum::encode_bits(&value, &ColumnType::InternalChar),
140                Some(u64::from(byte))
141            );
142            assert_eq!(
143                datum::decode_bits(u64::from(byte), &ColumnType::InternalChar),
144                Some((*value).clone())
145            );
146            let encoded = serde_json::to_string(&*value).unwrap();
147            assert_eq!(serde_json::from_str::<Value>(&encoded).unwrap(), *value);
148            if let Some(previous) = &previous {
149                assert!(previous < &*value);
150            }
151            previous = Some((*value).clone());
152            assert_eq!(memory.used(), value.reserved_bytes());
153            drop(value);
154            assert_eq!(memory.used(), 0);
155        }
156    }
157
158    #[test]
159    fn character_reads_and_output_admit_memory_and_both_cancellation_tokens() {
160        let datum = DatumValue::new(18, 0, vec![255]);
161        let token = CancellationToken::new();
162        let memory = MemoryBudget::new(0);
163        let control = ProductionControl::new(&memory, &token, &token);
164        assert_eq!(
165            datums::read_with_control(&datum, &control)
166                .unwrap_err()
167                .sqlstate(),
168            Some("53200")
169        );
170        assert_eq!(
171            crate::SQLError::from(output_with_control(255, &control).unwrap_err()).sqlstate(),
172            Some("53200")
173        );
174        assert_eq!(memory.used(), 0);
175        let memory = MemoryBudget::new(4096);
176        for original_cancelled in [false, true] {
177            let original = CancellationToken::new();
178            let invoking = CancellationToken::new();
179            if original_cancelled {
180                original.cancel();
181            } else {
182                invoking.cancel();
183            }
184            let control = ProductionControl::new(&memory, &original, &invoking);
185            assert_eq!(
186                datums::read_with_control(&datum, &control)
187                    .unwrap_err()
188                    .sqlstate(),
189                Some("57014")
190            );
191            assert_eq!(
192                crate::SQLError::from(output_with_control(255, &control).unwrap_err()).sqlstate(),
193                Some("57014")
194            );
195            assert_eq!(memory.used(), 0);
196        }
197    }
198}