Skip to main content

uqa_sql/expr/
uuid.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! `PostgreSQL`-compatible UUID parsing, generation, and extraction.
8
9use std::sync::atomic::{AtomicI64, Ordering as AtomicOrdering};
10use std::time::{SystemTime, UNIX_EPOCH};
11
12use uqa_core::{
13    memory::{Produced, ProductionControl},
14    TemporalValue, Value,
15};
16
17use crate::error::{Result, SQLError};
18
19use super::{
20    out_of_range, time::timestamp_tz_plus_interval, EngineHook, EvalContext, IntervalFields,
21};
22
23const NANOS_PER_MICROSECOND: i64 = 1_000;
24const NANOS_PER_MILLISECOND: i64 = 1_000_000;
25const UUID_V1_UNIX_EPOCH_OFFSET_TICKS: i128 = 0x01b2_1dd2_1381_4000;
26const UUID_V7_SUBMILLISECOND_BITS: u32 = 12;
27
28#[cfg(any(target_os = "macos", target_os = "windows"))]
29const UUID_V7_CLOCK_PRECISION_BITS: u32 = 10;
30#[cfg(not(any(target_os = "macos", target_os = "windows")))]
31const UUID_V7_CLOCK_PRECISION_BITS: u32 = 12;
32
33const UUID_V7_MINIMUM_STEP_NANOS: i64 =
34    NANOS_PER_MILLISECOND / (1_i64 << UUID_V7_CLOCK_PRECISION_BITS) + 1;
35static UUID_V7_PREVIOUS_NANOS: AtomicI64 = AtomicI64::new(0);
36
37pub(super) fn canonicalize_uuid_with_control(
38    text: &str,
39    control: &ProductionControl<'_>,
40) -> Result<Produced<String>> {
41    let bytes = parse_uuid_bytes_with_control(text, control)?;
42    format_uuid_with_control(bytes, control)
43}
44
45pub(super) fn extract_uuid_version(
46    value: &Value,
47    control: &ProductionControl<'_>,
48) -> Result<Value> {
49    let bytes = uuid_value_bytes(value, control)?;
50    Ok(uuid_version(&bytes).map_or(Value::Null, |version| Value::Int(i64::from(version))))
51}
52
53pub(super) fn extract_uuid_timestamp(
54    value: &Value,
55    control: &ProductionControl<'_>,
56) -> Result<Value> {
57    let bytes = uuid_value_bytes(value, control)?;
58    let Some(version) = uuid_version(&bytes) else {
59        return Ok(Value::Null);
60    };
61    let micros = match version {
62        1 => uuid_v1_unix_micros(&bytes),
63        7 => uuid_v7_unix_micros(&bytes),
64        _ => return Ok(Value::Null),
65    }?;
66    let postgres_micros = micros
67        .checked_sub(uqa_core::POSTGRES_EPOCH_MICROS)
68        .ok_or_else(|| crate::expr::datetime_out_of_range("timestamp"))?;
69    Ok(Value::Temporal(TemporalValue::TimestampTz {
70        postgres_micros,
71    }))
72}
73
74pub(super) fn generate_random_uuid() -> Result<String> {
75    let mut bytes = [0u8; 16];
76    getrandom::fill(&mut bytes)
77        .map_err(|error| SQLError::Internal(format!("failed to obtain random bytes: {error}")))?;
78    bytes[6] = (bytes[6] & 0x0f) | 0x40;
79    bytes[8] = (bytes[8] & 0x3f) | 0x80;
80    Ok(format_uuid(bytes))
81}
82
83pub(super) fn eval_uuid_v7(args: &[Value], context: Option<&EvalContext<'_>>) -> Result<Value> {
84    let shift = match args {
85        [] => None,
86        [Value::Temporal(interval @ TemporalValue::Interval { .. })] => Some(interval),
87        [Value::Null] => return Ok(Value::Null),
88        [_] => {
89            return Err(SQLError::TypeMismatch(
90                "uuidv7 shift must be an interval".into(),
91            ))
92        }
93        _ => return Err(SQLError::TypeMismatch("uuidv7 takes 0 or 1 args".into())),
94    };
95    generate_uuid_v7_at_clock(
96        real_time_nanos_ascending()?,
97        shift,
98        context.and_then(|context| context.engine),
99    )
100    .map(Value::Str)
101}
102
103fn generate_uuid_v7_at_clock(
104    now_nanos: i64,
105    shift: Option<&TemporalValue>,
106    engine: Option<&dyn EngineHook>,
107) -> Result<String> {
108    let now_micros = now_nanos.div_euclid(NANOS_PER_MICROSECOND);
109    let sub_microsecond_nanos = now_nanos.rem_euclid(NANOS_PER_MICROSECOND);
110    let timestamp_micros = match shift {
111        None => now_micros - uqa_core::POSTGRES_EPOCH_MICROS,
112        Some(TemporalValue::Interval {
113            months,
114            days,
115            micros,
116        }) => timestamp_tz_plus_interval(
117            now_micros - uqa_core::POSTGRES_EPOCH_MICROS,
118            IntervalFields {
119                months: *months,
120                days: *days,
121                micros: *micros,
122            },
123            engine,
124            &ProductionControl::uncontrolled(),
125        )?,
126        Some(other) => {
127            return Err(SQLError::TypeMismatch(format!(
128                "uuidv7: expected interval, got {other:?}"
129            )));
130        }
131    };
132    // uuidv7_interval adds the Unix epoch to PostgreSQL's raw timestamp after
133    // arithmetic, including its infinity bit patterns, with signed wrapping.
134    let unix_micros = timestamp_micros.wrapping_add(uqa_core::POSTGRES_EPOCH_MICROS);
135    // PostgreSQL truncates signed division toward zero before narrowing the
136    // millisecond and fractional parts to the generator's unsigned arguments.
137    let unix_millis = (unix_micros / 1_000).cast_unsigned();
138    let sub_millisecond_nanos =
139        (unix_micros % 1_000) * NANOS_PER_MICROSECOND + sub_microsecond_nanos;
140    #[expect(
141        clippy::cast_possible_truncation,
142        clippy::cast_sign_loss,
143        reason = "PostgreSQL narrows the signed sub-millisecond expression to uint32"
144    )]
145    generate_uuid_v7_at(unix_millis, sub_millisecond_nanos as u32)
146}
147
148/// Parse every UUID input spelling accepted by `PostgreSQL` into network-order bytes.
149pub fn parse_uuid_bytes(text: &str) -> Result<[u8; 16]> {
150    parse_uuid_bytes_with_control(text, &ProductionControl::uncontrolled())
151}
152
153/// Parse `PostgreSQL` UUID input under the invoking cancellation scope without allocating a payload.
154pub fn parse_uuid_bytes_with_control(
155    text: &str,
156    control: &ProductionControl<'_>,
157) -> Result<[u8; 16]> {
158    control.check()?;
159    let digits = text
160        .strip_prefix('{')
161        .and_then(|text| text.strip_suffix('}'))
162        .unwrap_or(text);
163    if digits.starts_with('{') || digits.ends_with('}') {
164        return Err(invalid_uuid(text));
165    }
166    let mut normalized = [0_u8; 32];
167    let mut digit_count = 0;
168    let mut group_digits = 0_usize;
169    for character in digits.chars() {
170        control.check()?;
171        if character == '-' {
172            if group_digits == 0 || !group_digits.is_multiple_of(4) {
173                return Err(invalid_uuid(text));
174            }
175            group_digits = 0;
176            continue;
177        }
178        if !character.is_ascii_hexdigit() {
179            return Err(invalid_uuid(text));
180        }
181        let Some(digit) = normalized.get_mut(digit_count) else {
182            return Err(invalid_uuid(text));
183        };
184        *digit = character.to_ascii_lowercase() as u8;
185        digit_count += 1;
186        group_digits += 1;
187    }
188    if digit_count != 32 || group_digits == 0 {
189        return Err(invalid_uuid(text));
190    }
191    let mut bytes = [0_u8; 16];
192    for (index, pair) in normalized.as_chunks::<2>().0.iter().enumerate() {
193        bytes[index] = (hex_value(pair[0]) << 4) | hex_value(pair[1]);
194    }
195    Ok(bytes)
196}
197
198fn uuid_value_bytes(value: &Value, control: &ProductionControl<'_>) -> Result<[u8; 16]> {
199    match value {
200        Value::Str(text) | Value::FixedChar(text) => parse_uuid_bytes_with_control(text, control),
201        other => Err(SQLError::TypeMismatch(format!(
202            "expected uuid value, got {other:?}"
203        ))),
204    }
205}
206
207fn uuid_version(bytes: &[u8; 16]) -> Option<u8> {
208    ((bytes[8] & 0xc0) == 0x80).then_some(bytes[6] >> 4)
209}
210
211fn uuid_v1_unix_micros(bytes: &[u8; 16]) -> Result<i64> {
212    let low = u32::from_be_bytes(bytes[0..4].try_into().expect("UUID time_low width"));
213    let middle = u16::from_be_bytes(bytes[4..6].try_into().expect("UUID time_mid width"));
214    let high = u16::from_be_bytes(bytes[6..8].try_into().expect("UUID time_high width")) & 0x0fff;
215    let ticks = (i128::from(high) << 48) | (i128::from(middle) << 32) | i128::from(low);
216    i64::try_from((ticks - UUID_V1_UNIX_EPOCH_OFFSET_TICKS).div_euclid(10))
217        .map_err(|_| out_of_range("uuid timestamp"))
218}
219
220fn uuid_v7_unix_micros(bytes: &[u8; 16]) -> Result<i64> {
221    let milliseconds = bytes[..6]
222        .iter()
223        .fold(0_i64, |value, byte| (value << 8) | i64::from(*byte));
224    milliseconds
225        .checked_mul(1_000)
226        .ok_or_else(|| out_of_range("uuid timestamp"))
227}
228
229fn real_time_nanos_ascending() -> Result<i64> {
230    let elapsed = SystemTime::now()
231        .duration_since(UNIX_EPOCH)
232        .map_err(|_| out_of_range("uuidv7 timestamp"))?;
233    let actual = i64::try_from(elapsed.as_nanos()).map_err(|_| out_of_range("uuidv7 timestamp"))?;
234    loop {
235        let previous = UUID_V7_PREVIOUS_NANOS.load(AtomicOrdering::Relaxed);
236        let minimum = previous
237            .checked_add(UUID_V7_MINIMUM_STEP_NANOS)
238            .ok_or_else(|| out_of_range("uuidv7 timestamp"))?;
239        let candidate = if minimum >= actual { minimum } else { actual };
240        if UUID_V7_PREVIOUS_NANOS
241            .compare_exchange_weak(
242                previous,
243                candidate,
244                AtomicOrdering::Relaxed,
245                AtomicOrdering::Relaxed,
246            )
247            .is_ok()
248        {
249            return Ok(candidate);
250        }
251    }
252}
253
254fn generate_uuid_v7_at(unix_millis: u64, sub_millisecond_nanos: u32) -> Result<String> {
255    let mut bytes = [0u8; 16];
256    getrandom::fill(&mut bytes[8..])
257        .map_err(|error| SQLError::Internal(format!("failed to obtain random bytes: {error}")))?;
258    let timestamp = unix_millis.to_be_bytes();
259    bytes[..6].copy_from_slice(&timestamp[2..]);
260    let increased_clock_precision = sub_millisecond_nanos
261        .wrapping_mul(1_u32 << UUID_V7_SUBMILLISECOND_BITS)
262        / NANOS_PER_MILLISECOND as u32;
263    bytes[6] = (increased_clock_precision >> 8) as u8;
264    bytes[7] = increased_clock_precision as u8;
265
266    #[cfg(any(target_os = "macos", target_os = "windows"))]
267    {
268        bytes[7] ^= bytes[8] >> 6;
269    }
270
271    bytes[6] = (bytes[6] & 0x0f) | 0x70;
272    bytes[8] = (bytes[8] & 0x3f) | 0x80;
273    Ok(format_uuid(bytes))
274}
275
276pub(crate) fn format_uuid(bytes: [u8; 16]) -> String {
277    format_uuid_with_control(bytes, &ProductionControl::uncontrolled())
278        .expect("ordinary UUID formatting")
279        .into_uncontrolled()
280        .expect("ordinary UUID text")
281}
282
283/// Format network-order UUID octets as canonical text under the original production allowance.
284pub fn format_uuid_with_control(
285    bytes: [u8; 16],
286    control: &ProductionControl<'_>,
287) -> Result<Produced<String>> {
288    Ok(control.format(format_args!(
289        "{:02x}{:02x}{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
290        bytes[0], bytes[1], bytes[2], bytes[3],
291        bytes[4], bytes[5],
292        bytes[6], bytes[7],
293        bytes[8], bytes[9],
294        bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15],
295    ))?)
296}
297
298fn hex_value(byte: u8) -> u8 {
299    match byte {
300        b'0'..=b'9' => byte - b'0',
301        b'a'..=b'f' => byte - b'a' + 10,
302        _ => unreachable!("UUID parser retained only lowercase hexadecimal digits"),
303    }
304}
305
306fn invalid_uuid(text: &str) -> SQLError {
307    SQLError::Routine {
308        sqlstate: "22P02".into(),
309        message: format!("invalid input syntax for type uuid: \"{text}\""),
310    }
311}
312
313#[cfg(test)]
314mod tests;