Skip to main content

uqa_sql/semantics/sets/
placement_scope.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Whether analysis on a thread places set-returning calls again.
8
9use std::cell::Cell;
10use std::marker::PhantomData;
11use std::rc::Rc;
12
13thread_local! {
14    static PLACING_SET_CALLS: Cell<bool> = const { Cell::new(true) };
15}
16
17/// Decides, until it drops, whether analysis on the current thread places set-returning calls, as parse analysis does for a statement or definition it analyzes for the first time, and restores the enclosing decision when it drops.
18pub struct SetPlacementScope {
19    previous: bool,
20    thread: PhantomData<Rc<()>>,
21}
22
23impl SetPlacementScope {
24    /// Analyze or run a stored definition: a view, a SQL-standard routine body or a rule, which `PostgreSQL` keeps as the tree its parse analysis produced when the definition was created and never analyzes again. Its set-returning calls are not placed again, so a definition stored by an earlier release keeps loading, and evaluating one of them where the executor cannot accept a set reports the executor's diagnostic.
25    #[must_use]
26    pub fn stored_definition() -> Self {
27        Self::enter(false)
28    }
29
30    /// Analyze the statements a routine compiles from its source text when it runs, which `PostgreSQL` analyzes like a new statement even when a stored definition calls the routine.
31    #[must_use]
32    pub fn compiled_source() -> Self {
33        Self::enter(true)
34    }
35
36    fn enter(placing: bool) -> Self {
37        Self {
38            previous: PLACING_SET_CALLS.replace(placing),
39            thread: PhantomData,
40        }
41    }
42}
43
44impl Drop for SetPlacementScope {
45    fn drop(&mut self) {
46        PLACING_SET_CALLS.set(self.previous);
47    }
48}
49
50/// Whether analysis on the current thread places set-returning calls, which it does outside a stored definition.
51pub fn placing_set_calls() -> bool {
52    PLACING_SET_CALLS.get()
53}
54
55#[cfg(test)]
56mod tests {
57    use super::{placing_set_calls, SetPlacementScope};
58
59    #[test]
60    fn stored_definitions_place_no_set_returning_call_until_their_scope_ends() {
61        assert!(placing_set_calls());
62        let stored = SetPlacementScope::stored_definition();
63        assert!(!placing_set_calls());
64        {
65            // A routine compiled from its source inside a stored definition places its calls again.
66            let _source = SetPlacementScope::compiled_source();
67            assert!(placing_set_calls());
68            {
69                let _nested = SetPlacementScope::stored_definition();
70                assert!(!placing_set_calls());
71            }
72            assert!(placing_set_calls());
73        }
74        assert!(!placing_set_calls());
75        drop(stored);
76        assert!(placing_set_calls());
77    }
78}