Skip to main content

uqa_engine/session/
settings.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Logical-session search path, PRNG, runtime variables, and DISCARD.
8
9use super::{Engine, SQLError, StorageBackendResult};
10
11impl Engine {
12    /// Return the current `search_path`.
13    pub fn search_path(&self) -> Vec<String> {
14        self.session.state.read().search_path.clone()
15    }
16
17    /// `LOAD 'library'`. The engine embeds Apache AGE and PL/pgSQL, so loading either succeeds as a no-op through every spelling `PostgreSQL` resolves against `$libdir`; any other library fails exactly like a missing shared object.
18    pub fn load_library(&self, library: &str) -> Result<(), SQLError> {
19        let requested = library.strip_prefix("$libdir/").unwrap_or(library);
20        let base = requested.strip_suffix(".so").unwrap_or(requested);
21        if matches!(base, "age" | "plpgsql") && !requested.contains('/') {
22            self.load_language(base);
23            return Ok(());
24        }
25        let path = if library.contains('/') {
26            library.to_string()
27        } else {
28            format!("$libdir/{library}")
29        };
30        Err(SQLError::Routine {
31            sqlstate: "58P01".into(),
32            message: format!("could not access file \"{path}\": No such file or directory"),
33        })
34    }
35
36    /// Load the library of `language` into the session, which defines its parameters: `PL/pgSQL` is the only embedded language whose library defines any.
37    pub(crate) fn load_language(&self, language: &str) {
38        if language == "plpgsql" {
39            self.load_parameter_library("plpgsql");
40        }
41    }
42
43    /// First usable namespace on this logical session's explicit search path: a durable, virtual system or graph namespace.
44    pub fn current_schema_name(&self) -> StorageBackendResult<Option<String>> {
45        self.with_catalog_read_snapshot(Self::current_schema_name_in_execution)
46    }
47
48    pub(crate) fn current_schema_name_in_execution(&self) -> StorageBackendResult<Option<String>> {
49        self.catalog_execution()
50            .current_schema_name()
51            .map_err(|error| uqa_storage::StorageBackendError::backend("schema namespace", error))
52    }
53
54    /// Existing schemas with USAGE privilege in this logical session's search path. `PostgreSQL` implicitly searches `pg_catalog` unless it is already named explicitly.
55    pub fn current_schema_names(
56        &self,
57        include_implicit: bool,
58    ) -> StorageBackendResult<Vec<String>> {
59        self.with_catalog_read_snapshot(|engine| {
60            engine.current_schema_names_in_execution(include_implicit)
61        })
62    }
63
64    pub(crate) fn current_schema_names_in_execution(
65        &self,
66        include_implicit: bool,
67    ) -> StorageBackendResult<Vec<String>> {
68        self.catalog_execution()
69            .current_schema_names(include_implicit)
70            .map_err(|error| uqa_storage::StorageBackendError::backend("schema namespace", error))
71    }
72
73    /// Draw every bit of one word from this logical session's PRNG.
74    pub fn next_random_u64(&self) -> u64 {
75        let mut state = self.session.random_state.lock();
76        let s0 = state.s0;
77        let mixed = state.s1 ^ s0;
78        let value = s0.wrapping_mul(5).rotate_left(7).wrapping_mul(9);
79        state.s0 = s0.rotate_left(24) ^ mixed ^ (mixed << 16);
80        state.s1 = mixed.rotate_left(37);
81        value
82    }
83
84    /// Draw one value in `[0, 1)` from this logical session's PRNG.
85    pub fn next_random_value(&self) -> f64 {
86        let sample = self.next_random_u64() >> 12;
87        sample as f64 * (1.0 / ((1_u64 << 52) as f64))
88    }
89
90    /// Reseed this logical session's PRNG. Equal seeds produce equal streams
91    /// without changing any sibling session.
92    pub fn set_random_seed(&self, seed: f64) -> Result<(), String> {
93        if !seed.is_finite() || !(-1.0..=1.0).contains(&seed) {
94            return Err(format!(
95                "setseed parameter {seed} is out of allowed range [-1,1]"
96            ));
97        }
98        let scaled = (((1_u64 << 52) - 1) as f64 * seed) as i64;
99        *self.session.random_state.lock() = crate::random_state_from_seed(scaled as u64);
100        Ok(())
101    }
102
103    /// Set the session's `search_path` to `path`, each schema quoted as an identifier needs, as `SET search_path TO` with those names does. An empty path finds unqualified names only in the system schemas.
104    pub fn set_search_path(&self, path: &[String]) -> Result<(), SQLError> {
105        let setting = path
106            .iter()
107            .map(|schema| uqa_sql::expr::quote_ident(schema))
108            .collect::<Vec<_>>()
109            .join(", ");
110        self.set_runtime_parameter("search_path", Some(&setting), false)
111    }
112
113    /// Bound the memory each query workspace of this session may hold before it spills, in place of `work_mem`; `None` returns to `work_mem`. Unlike `work_mem`, whose minimum is `PostgreSQL`'s 64 kB, the bound may be as small as one byte, so that a host can make queries over little data spill.
114    pub fn set_query_memory_limit(&self, bytes: Option<usize>) {
115        self.session.query_memory_limit.store(
116            bytes.map_or(0, |bytes| bytes.max(1)),
117            std::sync::atomic::Ordering::Release,
118        );
119    }
120
121    /// Apply `SET <name> [TO|=] <value>` for the session.
122    pub fn set_variable(&self, name: &str, value: &str) -> Result<(), SQLError> {
123        self.set_runtime_parameter(name, Some(value), false)
124    }
125
126    pub fn reset_variable(&self, name: &str) -> Result<(), SQLError> {
127        self.set_runtime_parameter(name, None, false)
128    }
129
130    /// `RESET ALL`: every parameter except those `RESET ALL` leaves alone returns to the setting `RESET` restores.
131    pub fn reset_all_variables(&self) {
132        let search_path = self.reset_search_path();
133        let mut session = self.session.state.write();
134        session.session_vars.clear();
135        session.parameter_scopes.reset_all();
136        session.search_path = search_path;
137        session.sql_statement_cache.clear();
138    }
139
140    /// The value of the parameter `name` as `SHOW` reports it; a name nothing defines is an error.
141    pub fn show_variable(&self, name: &str) -> Result<String, SQLError> {
142        self.session_execution_view().show_variable(name)
143    }
144
145    pub(crate) fn set_runtime_parameter(
146        &self,
147        name: &str,
148        value: Option<&str>,
149        local: bool,
150    ) -> Result<(), SQLError> {
151        use uqa_sql::semantics::parameters::ParameterAssignment;
152        self.assign_runtime_parameter(
153            name,
154            value,
155            if local {
156                ParameterAssignment::Local
157            } else {
158                ParameterAssignment::Session
159            },
160        )
161    }
162
163    pub(crate) fn set_configured_parameter(&self, name: &str, value: &str) -> Result<(), SQLError> {
164        self.assign_runtime_parameter(
165            name,
166            Some(value),
167            uqa_sql::semantics::parameters::ParameterAssignment::Save,
168        )
169    }
170
171    fn assign_runtime_parameter(
172        &self,
173        name: &str,
174        value: Option<&str>,
175        action: uqa_sql::semantics::parameters::ParameterAssignment,
176    ) -> Result<(), SQLError> {
177        use crate::state::RuntimeParameterValue;
178        let key = crate::capabilities::session_parameters::parameter_key(name);
179        let before = {
180            let state = self.session.state.read();
181            let setting = state.session_vars.get(&key).cloned();
182            match key.as_str() {
183                "search_path" => RuntimeParameterValue::SearchPath {
184                    setting,
185                    path: state.search_path.clone(),
186                },
187                "role" => RuntimeParameterValue::Role(state.authorization.selected().cloned()),
188                "session_authorization" => RuntimeParameterValue::SessionAuthorization(
189                    state.authorization.session().clone(),
190                ),
191                _ => RuntimeParameterValue::Setting(setting),
192            }
193        };
194        let prior_role = (key == "session_authorization").then(|| {
195            RuntimeParameterValue::Role(self.session.state.read().authorization.selected().cloned())
196        });
197        if key == "session_authorization" {
198            uqa_execution::catalog::security::role_lifecycle::set_session_authorization(
199                &self.role_execution_context(),
200                value,
201            )?;
202        } else if key == "role" {
203            uqa_execution::catalog::security::role_lifecycle::set_role(
204                &self.role_execution_context(),
205                value,
206            )?;
207        } else if let Some(value) = value {
208            self.assign_parameter(name, value)?;
209        } else {
210            self.reset_parameter(name)?;
211        }
212        // Every SQL statement runs in a transaction, its own when no block is open, which ends the statement's LOCAL assignments.
213        let in_transaction = self.transaction_depth() != 0
214            || self
215                .runtime
216                .sql_execution_depth
217                .load(std::sync::atomic::Ordering::Relaxed)
218                != 0;
219        let mut state = self.session.state.write();
220        if let Some(prior_role) = prior_role {
221            if let Some(previous) =
222                state
223                    .parameter_scopes
224                    .assigned("role".into(), prior_role, action, in_transaction)
225            {
226                restore_runtime_parameter(&mut state, "role", previous);
227            }
228        }
229        if let Some(previous) =
230            state
231                .parameter_scopes
232                .assigned(key.clone(), before, action, in_transaction)
233        {
234            // A LOCAL assignment outside any transaction lasts only for its own statement; the statement executor reports the warning.
235            restore_runtime_parameter(&mut state, &key, previous);
236        }
237        Ok(())
238    }
239
240    pub(crate) fn restore_local_runtime_parameters(&self) {
241        let mut state = self.session.state.write();
242        let saved = state.parameter_scopes.finish_transaction();
243        for (name, value) in saved {
244            restore_runtime_parameter(&mut state, &name, value);
245        }
246    }
247
248    pub(crate) fn work_mem_bytes(&self) -> Result<usize, SQLError> {
249        self.query_runtime_view().work_mem_bytes()
250    }
251
252    pub(crate) fn session_replication_role_is_replica(&self) -> bool {
253        self.session.setting("session_replication_role") == "replica"
254    }
255
256    pub(crate) fn session_replication_role_is_replica_with_control(
257        &self,
258        control: &uqa_core::memory::ProductionControl<'_>,
259    ) -> Result<bool, SQLError> {
260        control.check()?;
261        if let Some(role) = self
262            .session
263            .state
264            .read()
265            .session_vars
266            .get("session_replication_role")
267        {
268            return Ok(role == "replica");
269        }
270        Ok(self
271            .session
272            .parameters
273            .lock()
274            .client_setting_with_control("session_replication_role", control)?
275            .is_some_and(|role| role == "replica"))
276    }
277
278    /// Whether a query may project the values that indexes hold instead of reading documents, as `PostgreSQL`'s `enable_indexonlyscan` does.
279    pub(crate) fn index_only_scans_enabled(&self) -> bool {
280        self.session.setting("enable_indexonlyscan") == "on"
281    }
282
283    /// Whether `ASSERT` checks its condition (`plpgsql.check_asserts`), which applies once the session has loaded `PL/pgSQL`, as running an `ASSERT` has.
284    pub(crate) fn plpgsql_asserts_enabled(&self) -> bool {
285        self.session.setting("plpgsql.check_asserts") == "on"
286    }
287
288    /// Apply `DISCARD <target>`. `ALL` resets every kind of session state;
289    /// the narrower
290    /// variants are scoped accordingly.
291    pub fn discard(&self, target: uqa_sql::ast::DiscardTarget) -> Result<(), SQLError> {
292        use uqa_sql::ast::DiscardTarget;
293        let _statement = self.lock_statement_gate();
294        if target == DiscardTarget::All && self.in_transaction_block() {
295            return Err(SQLError::Routine {
296                sqlstate: "25001".into(),
297                message: "DISCARD ALL cannot run inside a transaction block".into(),
298            });
299        }
300        if matches!(target, DiscardTarget::All | DiscardTarget::Temp) {
301            self.discard_temporary_objects()?;
302            if self.transaction_depth() == 0 {
303                self.row_locks.close_temporary_roles(self.session_id);
304            }
305        }
306        if matches!(target, DiscardTarget::All | DiscardTarget::Sequences) {
307            self.discard_sequence_session_values();
308        }
309        if target == DiscardTarget::All {
310            if self.transaction_depth() == 0 {
311                self.clear_notification_listener_without_transaction()?;
312            } else {
313                self.unlisten(None)?;
314            }
315        }
316        let search_path = self.reset_search_path();
317        let mut session = self.session.state.write();
318        match target {
319            DiscardTarget::All => {
320                session.session_vars.clear();
321                session.search_path = search_path;
322                self.session.prepared.write().clear();
323                self.invalidate_prepared_analysis();
324                session.sql_statement_cache.clear();
325                session.authorization.discard();
326                drop(session);
327                self.session.portals.lock().clear();
328                return Ok(());
329            }
330            DiscardTarget::Plans => {
331                self.invalidate_prepared_analysis();
332                session.sql_statement_cache.clear();
333            }
334            DiscardTarget::Sequences | DiscardTarget::Temp => {}
335        }
336        Ok(())
337    }
338
339    pub(crate) fn discard_temporary_objects(&self) -> Result<(), SQLError> {
340        use uqa_execution::schema::deletion::CatalogRemovalInputs;
341        if !self.temporary_namespace_allocated() {
342            return Ok(());
343        }
344        let schema = self.temporary_schema_name();
345        self.with_definition_publication(|engine| {
346            uqa_execution::schema::deletion::remove_namespace_members(
347                &engine.catalog_removal_context(),
348                &schema,
349            )
350        })
351    }
352}
353
354pub(crate) fn restore_runtime_parameter(
355    state: &mut crate::SessionStateSnapshot,
356    name: &str,
357    value: crate::state::RuntimeParameterValue,
358) {
359    use crate::state::RuntimeParameterValue;
360    let setting = match value {
361        RuntimeParameterValue::Setting(value) => value,
362        RuntimeParameterValue::SearchPath { setting, path } => {
363            state.search_path = path;
364            state.sql_statement_cache.clear();
365            setting
366        }
367        RuntimeParameterValue::SessionAuthorization(role) => {
368            state.authorization.restore_session(role);
369            state.sql_statement_cache.clear();
370            return;
371        }
372        RuntimeParameterValue::Role(role) => {
373            state.authorization.set_role(role);
374            state.sql_statement_cache.clear();
375            return;
376        }
377    };
378    state
379        .session_vars
380        .retain(|key, _| !key.eq_ignore_ascii_case(name));
381    if let Some(value) = setting {
382        state.session_vars.insert(name.into(), value);
383    }
384}