Skip to main content

uqa_execution/batch/
row_lock_name.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Shared scan names carry their admission through row, alias and lock-candidate lifetimes.
8
9use std::{
10    fmt,
11    hash::{Hash, Hasher},
12    ops::Deref,
13    sync::Arc,
14};
15use uqa_core::memory::{Produced, ProductionControl};
16use uqa_sql::SQLError;
17
18#[derive(Clone)]
19pub struct RowLockName(Name);
20
21#[derive(Clone)]
22enum Name {
23    Ordinary(Arc<str>),
24    Admitted(Arc<Produced<String>>),
25}
26
27impl RowLockName {
28    pub(crate) fn copy_with_control(
29        name: &str,
30        control: &ProductionControl<'_>,
31    ) -> Result<Self, SQLError> {
32        control.check()?;
33        if control.budget().is_none() {
34            return Ok(Self::from(name));
35        }
36        Self::from_produced(control.copy_text(name)?, control)
37    }
38
39    pub(crate) fn from_produced(
40        name: Produced<String>,
41        control: &ProductionControl<'_>,
42    ) -> Result<Self, SQLError> {
43        if control.budget().is_some() {
44            Ok(Self(Name::Admitted(name.into_shared(control)?)))
45        } else {
46            Ok(Self::from(
47                name.into_uncontrolled().expect("ordinary row-lock name"),
48            ))
49        }
50    }
51}
52impl Deref for RowLockName {
53    type Target = str;
54    fn deref(&self) -> &str {
55        match &self.0 {
56            Name::Ordinary(name) => name,
57            Name::Admitted(name) => name.as_str(),
58        }
59    }
60}
61impl AsRef<str> for RowLockName {
62    fn as_ref(&self) -> &str {
63        self
64    }
65}
66impl std::borrow::Borrow<str> for RowLockName {
67    fn borrow(&self) -> &str {
68        self
69    }
70}
71impl From<Arc<str>> for RowLockName {
72    fn from(name: Arc<str>) -> Self {
73        Self(Name::Ordinary(name))
74    }
75}
76impl From<String> for RowLockName {
77    fn from(name: String) -> Self {
78        Self::from(Arc::<str>::from(name))
79    }
80}
81impl From<&str> for RowLockName {
82    fn from(name: &str) -> Self {
83        Self::from(Arc::<str>::from(name))
84    }
85}
86impl PartialEq for RowLockName {
87    fn eq(&self, other: &Self) -> bool {
88        self.as_ref() == other.as_ref()
89    }
90}
91impl Eq for RowLockName {}
92impl PartialOrd for RowLockName {
93    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
94        Some(self.cmp(other))
95    }
96}
97impl Ord for RowLockName {
98    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
99        self.as_ref().cmp(other.as_ref())
100    }
101}
102impl Hash for RowLockName {
103    fn hash<H: Hasher>(&self, state: &mut H) {
104        self.as_ref().hash(state);
105    }
106}
107impl fmt::Debug for RowLockName {
108    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109        fmt::Debug::fmt(self.as_ref(), f)
110    }
111}
112impl fmt::Display for RowLockName {
113    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114        fmt::Display::fmt(self.as_ref(), f)
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121    use uqa_core::{memory::MemoryBudget, CancellationToken};
122
123    #[test]
124    fn scan_lock_names_follow_the_last_row_and_rebound_alias() {
125        let text = "q".repeat(1 << 20);
126        let memory = MemoryBudget::new(8 << 20);
127        let original = CancellationToken::new();
128        let invoking = CancellationToken::new();
129        let control = ProductionControl::new(&memory, &original, &invoking);
130        let occupied = memory.reserve(memory.available() - 1024).unwrap();
131        let mut denied = None;
132        let allocations = allocation_counter::measure(|| {
133            denied = Some(RowLockName::copy_with_control(&text, &control));
134        });
135        assert_eq!(denied.unwrap().unwrap_err().sqlstate(), Some("53200"));
136        assert!(allocations.bytes_total < 4096, "{allocations:?}");
137        assert_eq!(memory.used(), occupied.bytes());
138        drop(occupied);
139        for token in [&original, &invoking] {
140            token.cancel();
141            assert_eq!(
142                RowLockName::copy_with_control(&text, &control)
143                    .unwrap_err()
144                    .sqlstate(),
145                Some("57014")
146            );
147            assert_eq!(memory.used(), 0);
148            token.reset();
149        }
150        let qualifier = RowLockName::copy_with_control(&text, &control).unwrap();
151        let storage = RowLockName::copy_with_control("public.t", &control).unwrap();
152        let origin = crate::RowLockOrigin::from_shared(qualifier.clone(), storage, 7);
153        let row = crate::PhysicalRow::from_values(Vec::new()).with_lock_origin(origin);
154        let before = memory.used();
155        drop(qualifier);
156        assert_eq!(memory.used(), before);
157        let retained = row.clone().rebind_lock_origin_qualifiers("alias");
158        drop(row);
159        assert_eq!(memory.used(), before);
160        let retained_origin = retained.lock_origins()[0].clone();
161        assert_eq!(retained_origin.qualifier.as_ref(), "alias");
162        assert_eq!(retained_origin.scan_qualifier.as_ref(), text);
163        assert_eq!(retained_origin.storage_name.as_ref(), "public.t");
164        drop(retained);
165        assert_eq!(memory.used(), before);
166        drop(retained_origin);
167        assert_eq!(memory.used(), 0);
168    }
169}