Skip to main content

uqa_sql/ir/retained/
observation.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Representation comparison retains independent decoded values until both observations finish.
8
9use super::{RetainedConstantValue, RetainedScalarLiteral};
10use crate::SQLError;
11use uqa_core::{
12    memory::{Produced, ProductionControl},
13    Value,
14};
15
16pub(crate) enum Observation<'a> {
17    Resident(&'a Value),
18    Decoded(Produced<Value>),
19}
20
21impl std::ops::Deref for Observation<'_> {
22    type Target = Value;
23    fn deref(&self) -> &Value {
24        match self {
25            Self::Resident(value) => value,
26            Self::Decoded(value) => value,
27        }
28    }
29}
30
31pub(crate) fn observe<'a>(
32    value: &'a RetainedConstantValue,
33    control: &ProductionControl<'_>,
34) -> Result<Option<Observation<'a>>, SQLError> {
35    crate::expr::check_statement_cancellation()?;
36    control.check()?;
37    if let Some(value) = value.resident_value() {
38        return Ok(Some(Observation::Resident(value)));
39    }
40    match value.read_with_control(control) {
41        Ok(value) => Ok(Some(Observation::Decoded(value))),
42        Err(error) if matches!(error.sqlstate(), Some("53200" | "57014")) => Err(error),
43        Err(_) => Ok(None),
44    }
45}
46
47impl RetainedScalarLiteral {
48    /// Compare the exact retained value and metadata with admission for independent spilled reads. Semantic read failures conservatively decline equality; resource failures remain observable errors.
49    pub fn has_same_representation_with_control(
50        &self,
51        other: &Self,
52        control: &ProductionControl<'_>,
53    ) -> Result<bool, SQLError> {
54        control.check()?;
55        let value_matches = if self.value.shares_value_with(&other.value) {
56            true
57        } else {
58            // Preserve both independent observations before comparing metadata, even if one semantic read fails.
59            let left = observe(&self.value, control)?;
60            let right = observe(&other.value, control)?;
61            match (left, right) {
62                (Some(left), Some(right)) => left.has_same_representation(&right),
63                _ => false,
64            }
65        };
66        Ok(value_matches
67            && self.ty == other.ty
68            && self.declaration == other.declaration
69            && self.collation_oid == other.collation_oid)
70    }
71}