Skip to main content

spg_engine/
session.rs

1//! Session-parameter handling split out of `lib.rs` (lib.rs split 16):
2//! `set_session_param` records a `SET <name> = <value>` (folding the
3//! MySQL/PG FK-check + string-dialect toggles into engine state),
4//! `session_param` reads one back (the FTS dispatcher consults
5//! `default_text_search_config`), and `ev_ctx` builds an `EvalContext`
6//! pre-chained with that config. Whole `impl Engine` methods; the
7//! execute dispatcher drives `set_session_param`, `select.rs` drives
8//! `ev_ctx`, and `dml.rs` / `plpgsql.rs` read via `session_param`.
9
10use alloc::string::String;
11
12use spg_storage::ColumnSchema;
13
14use crate::Engine;
15use crate::eval::EvalContext;
16
17/// v7.39 (RLS) — reserved `session_params` key holding the effective session
18/// role set by `SET ROLE` (absent = the default Admin superuser login).
19/// `current_user` / RLS enforcement read it via `EvalContext.session_gucs`.
20/// The `__spg_` prefix keeps it out of the user-visible GUC namespace.
21pub(crate) const CURRENT_ROLE_KEY: &str = "__spg_current_role";
22
23/// v7.39 (read01 round 51) — reserved `session_params` key holding the LOGIN
24/// identity: the `user` the client sent in the startup packet. `session_user`
25/// reports it, and `current_user` falls back to it when no `SET ROLE` is in
26/// effect. Absent (embedded engine, or a wire that never set it) = LOGIN_ROLE.
27pub(crate) const SESSION_USER_KEY: &str = "__spg_session_user";
28
29/// v7.37 (round 830) — reserved `session_params` key marking the login
30/// identity as VERIFIED: the connection presented a credential the server
31/// checked (SCRAM or cleartext), rather than merely naming itself in the
32/// startup packet. Absent = unverified, which is the embedded engine and
33/// the server's open mode.
34///
35/// The distinction is what lets a login name carry privilege. Open mode
36/// accepts any startup as the admin role, so a name there is a label and
37/// nothing more — keying privilege on it would let anyone pick their own.
38/// A checked credential is a different thing, and it is the only
39/// configuration where roles and their policies mean anything at all.
40pub(crate) const SESSION_AUTHENTICATED_KEY: &str = "__spg_session_authenticated";
41
42/// v7.39 (RLS) — the login identity (superuser). SPG's embedded engine and
43/// its default server session both authenticate as this.
44pub(crate) const LOGIN_ROLE: &str = "admin";
45
46/// v7.39 (read01 round 58) — PG's bootstrap superuser. `synth_pg_roles` has
47/// always reported a `postgres` row (admin tools probe for it), so the name has
48/// to BE a role: refusing `SET ROLE postgres` while advertising it in pg_roles
49/// would be the same self-contradiction the ACL work went and fixed. It is a
50/// superuser, like the login role.
51pub(crate) const BOOTSTRAP_ROLE: &str = "postgres";
52
53/// The parameter names a session may name at all, beyond PG18's own
54/// inventory.
55///
56/// v7.39 — one list, asked by every surface. They used to decide
57/// separately and gave FOUR answers to one question: measured on the
58/// same name, `SET nosuch_guc` refused it in PG's words,
59/// `SHOW nosuch_guc` refused it in SPG's own words,
60/// `current_setting('nosuch_guc')` returned an empty string and
61/// `set_config('nosuch_guc', 'x', false)` returned `x`. Only the first
62/// was PG's answer.
63///
64/// Three families are accepted past PG's list because refusing them
65/// would break callers that are not wrong:
66///
67/// * anything containing a dot — PG treats `myapp.thing` as a
68///   customised option and accepts it, and extensions rely on that;
69/// * the MySQL-dialect names SPG honours (`sql_mode`,
70///   `foreign_key_checks`, …), which PG has no concept of and which
71///   `mysqldump` preambles emit;
72/// * SPG's own internal keys.
73pub(crate) fn guc_name_accepted_beyond_pg(key: &str) -> bool {
74    key.contains('.')
75        || key.starts_with("__spg")
76        || matches!(
77            key,
78            "sql_mode"
79                | "foreign_key_checks"
80                | "unique_checks"
81                | "autocommit"
82                | "names"
83                | "character_set_client"
84                | "character_set_connection"
85                | "character_set_results"
86                | "collation_connection"
87                | "sql_quote_show_create"
88                | "sql_notes"
89                | "time_zone"
90                | "sql_safe_updates"
91                | "innodb_strict_mode"
92                | "net_write_timeout"
93                | "net_read_timeout"
94                | "wait_timeout"
95                | "interactive_timeout"
96                | "max_allowed_packet"
97                | "group_concat_max_len"
98                | "old_alter_table"
99                | "sql_log_bin"
100                | "session_replication_role"
101        )
102}
103
104/// Is this a name PG18 knows, or one of the three families above?
105///
106/// The read path (`current_setting`, `SHOW`) asks this; the write path
107/// asks [`Engine::reject_unsettable_guc`], which adds PG's per-context
108/// refusals on top of the same list.
109pub(crate) fn guc_name_known(key: &str) -> bool {
110    guc_name_accepted_beyond_pg(key) || crate::guc_catalog::guc_context(key).is_some()
111}
112
113impl Engine {
114    /// v7.39 (read01 round 51) — the login identity: the startup packet's
115    /// `user`, else the Admin default. Drives `session_user`.
116    #[must_use]
117    pub(crate) fn session_user(&self) -> &str {
118        self.session_params
119            .get(SESSION_USER_KEY)
120            .map_or(LOGIN_ROLE, String::as_str)
121    }
122
123    /// v7.39 (read01 round 51) — record the connection's login identity.
124    /// The server calls this once per connection from the startup packet.
125    pub fn set_session_user(&mut self, user: &str) {
126        self.session_params
127            .insert(String::from(SESSION_USER_KEY), String::from(user));
128    }
129
130    /// v7.37 (round 830) — record that this connection's login identity was
131    /// verified against a stored credential. The server calls it once per
132    /// connection, right after `set_session_user`, when it demanded a
133    /// password; open-mode connections never do.
134    pub fn set_session_authenticated(&mut self) {
135        self.session_params
136            .insert(String::from(SESSION_AUTHENTICATED_KEY), String::from("1"));
137    }
138
139    /// Was this session's login identity checked against a credential?
140    #[must_use]
141    pub(crate) fn session_is_authenticated(&self) -> bool {
142        self.session_params.contains_key(SESSION_AUTHENTICATED_KEY)
143    }
144
145    /// v7.39 (RLS) — the effective session role: the `SET ROLE` override, or
146    /// the login identity. Drives `current_user` and RLS role matching.
147    #[must_use]
148    pub(crate) fn current_role(&self) -> &str {
149        self.session_params
150            .get(CURRENT_ROLE_KEY)
151            .map_or_else(|| self.session_user(), String::as_str)
152    }
153
154    /// v7.39 (RLS) — whether the session bypasses RLS. PG: superusers always
155    /// bypass. SPG maps this to "no non-Admin `SET ROLE` is in effect": the
156    /// default login and an explicit `SET ROLE admin` are superuser; any other
157    /// role is policy-subject.
158    #[must_use]
159    pub(crate) fn is_superuser(&self) -> bool {
160        // v7.39 (read01 round 51) — keyed on whether an explicit `SET ROLE` to
161        // a non-superuser role is in effect, NOT on the login NAME. The wire
162        // reports the startup packet's `user` as current_user / session_user;
163        // if superuser-ness followed that name, every connection as e.g.
164        // "unmei" would silently become RLS-subject. Reported identity and
165        // privilege semantics stay decoupled.
166        //
167        // v7.39 (read01 round 58) — the role's own SUPERUSER attribute decides
168        // now. `SET ROLE admin` still is one (the built-in login role), and so
169        // is any role created SUPERUSER. PG never inherits the attribute
170        // through membership, so this reads the role itself, not its set.
171        match self.session_params.get(CURRENT_ROLE_KEY) {
172            Some(r) => self.role_is_superuser(r),
173            // v7.37 (round 830) — with no SET ROLE in effect, the login
174            // identity decides IF it was verified. Measured before this:
175            // psql authenticated as a role with rolsuper = f, over a table
176            // with row security enabled and a USING policy in place, read
177            // every row including another owner's — for every projection
178            // shape, because the predicate was never injected at all.
179            //
180            // The unconditional `true` this replaces was deliberate and is
181            // still right for the case it was written for: in open mode the
182            // startup `user` is unverified, so letting it carry privilege
183            // would mean anyone could name themselves into a role. What
184            // changed is that the name is no longer always unverified — once
185            // a credentialed LOGIN role exists the server demands SCRAM, and
186            // that is exactly the configuration where policies and grants
187            // are supposed to bind.
188            //
189            // `role_is_superuser` still exempts the admin and bootstrap
190            // logins and any role created SUPERUSER, so authenticating as an
191            // administrator changes nothing.
192            None if self.session_is_authenticated() => self.role_is_superuser(self.session_user()),
193            None => true,
194        }
195    }
196
197    /// v7.39 (round 334, V55) — is THAT role a superuser? Split out of
198    /// [`Self::is_superuser`] so a `SECURITY DEFINER` body can be
199    /// authorised as the function's owner rather than the session's role.
200    pub(crate) fn role_is_superuser(&self, role: &str) -> bool {
201        role.eq_ignore_ascii_case(LOGIN_ROLE)
202            || role.eq_ignore_ascii_case(BOOTSTRAP_ROLE)
203            || self.users.get(role).is_some_and(|rec| rec.superuser)
204    }
205
206    /// v7.12.1 — record a `SET <name> = <value>` parameter. Names
207    /// are case-folded to lowercase to match PG; values keep their
208    /// caller-supplied form so observability paths see what was
209    /// requested. Only `default_text_search_config` is consulted by
210    /// the engine today.
211    /// v7.39 (round 501) — is `name` a parameter this session may set?
212    ///
213    /// PG18 answers `ERROR: unrecognized configuration parameter "x"` for
214    /// a name it does not know, and refuses the ones a session cannot
215    /// change with a wording that says why. SPG accepted anything —
216    /// round 500 measured `SET nonexistent_knob = 3` answering `SET` — so
217    /// a typo'd parameter name was taken silently and the setting the
218    /// caller believed they had made was never made.
219    ///
220    /// Three kinds of name are accepted beyond PG18's own list, because
221    /// rejecting them would break callers that are not wrong:
222    ///
223    /// * anything containing a dot — PG treats `myapp.thing` as a
224    ///   customised option and accepts it, and extensions rely on that;
225    /// * the MySQL-dialect names SPG honours (`sql_mode`,
226    ///   `foreign_key_checks`, …), which PG has no concept of and which
227    ///   `mysqldump` preambles emit;
228    /// * SPG's own internal keys.
229    ///
230    /// Returns the PG error text, or `None` when the SET may proceed.
231    pub(crate) fn reject_unsettable_guc(&self, name: &str) -> Option<alloc::string::String> {
232        let key = name.to_ascii_lowercase();
233        if guc_name_accepted_beyond_pg(&key) {
234            return None;
235        }
236        match crate::guc_catalog::guc_context(&key) {
237            None => Some(alloc::format!(
238                "unrecognized configuration parameter \"{key}\""
239            )),
240            // PG's own wording per context, so a client that matches on
241            // the message keeps working.
242            Some("internal") => Some(alloc::format!("parameter \"{key}\" cannot be changed")),
243            Some("postmaster") => Some(alloc::format!(
244                "parameter \"{key}\" cannot be changed without restarting the server"
245            )),
246            Some("sighup") => Some(alloc::format!("parameter \"{key}\" cannot be changed now")),
247            Some(_) => None,
248        }
249    }
250
251    /// Clear a session parameter, PG's way.
252    ///
253    /// v7.39 — a CUSTOM (dotted) parameter that this session has set
254    /// once stays defined for the rest of the session and reads back an
255    /// EMPTY STRING, not nothing: measured on PG 18.6, `SET app.z='1';
256    /// RESET app.z; current_setting('app.z', true)` answers `''`, and so
257    /// does the same read after a `SET LOCAL app.y` transaction commits.
258    /// SPG removed the key, so both answered NULL and `SHOW app.z`
259    /// errored — an application that branches on `IS NULL` versus `= ''`
260    /// branches the other way. A name this session never set still
261    /// answers NULL, which PG agrees with.
262    pub(crate) fn clear_session_param(&mut self, name: &str) {
263        let key = name.to_ascii_lowercase();
264        if key.contains('.') {
265            self.session_params
266                .insert(key, alloc::string::String::new());
267        } else {
268            self.session_params.remove(&key);
269        }
270        self.refresh_render_style();
271    }
272
273    pub(crate) fn set_session_param(&mut self, name: String, value: spg_sql::ast::SetValue) {
274        let normalised = match value {
275            spg_sql::ast::SetValue::String(s) => s,
276            spg_sql::ast::SetValue::Ident(s) => s,
277            spg_sql::ast::SetValue::Number(s) => s,
278            // v7.39 (GUC) — `SET name = DEFAULT` / `SET TIME ZONE
279            // LOCAL` restore the default, i.e. drop the session
280            // override (storing "" would make SHOW render an empty
281            // string instead of the default).
282            spg_sql::ast::SetValue::Default => {
283                self.clear_session_param(&name);
284                return;
285            }
286        };
287        let key = name.to_ascii_lowercase();
288        // v7.14.0 — mysqldump preamble emits
289        // `SET FOREIGN_KEY_CHECKS=0` so it can CREATE TABLE in any
290        // order despite cross-table FK references; the closing
291        // section emits `SET FOREIGN_KEY_CHECKS=1` (or
292        // `=@OLD_FOREIGN_KEY_CHECKS` which resolves to "ON" in our
293        // session-variable-aware path). Match both shapes.
294        // Also accept PG's `session_replication_role = 'replica'`
295        // which suppresses trigger + FK enforcement during a
296        // logical replication apply (pg_dump preserves this for
297        // schema-only mode but it shows up in some restores).
298        let value_off = matches!(
299            normalised.to_ascii_lowercase().as_str(),
300            "0" | "off" | "false"
301        );
302        let value_on = matches!(
303            normalised.to_ascii_lowercase().as_str(),
304            "1" | "on" | "true"
305        );
306        // v7.39 — `SET NAMES <charset>` sets the three character_set_*
307        // session variables and, unless a `COLLATE` clause follows,
308        // the charset's DEFAULT collation. The parser emits the charset
309        // under `names` and the expansion lives here, beside the rest of
310        // the MySQL session semantics.
311        //
312        // An unknown charset sets the character_set_* trio and leaves
313        // `collation_connection` alone rather than guessing: a session
314        // that pads differently from what it was told is worse than one
315        // that did not change.
316        if key == "names" {
317            for k in [
318                "character_set_client",
319                "character_set_connection",
320                "character_set_results",
321            ] {
322                self.session_params
323                    .insert(String::from(k), normalised.clone());
324            }
325            if let Some(coll) = crate::collate::charset_default_collation(&normalised) {
326                self.session_params
327                    .insert(String::from("collation_connection"), String::from(coll));
328            }
329            self.refresh_render_style();
330            return;
331        }
332        if key == "foreign_key_checks"
333            || key == "session_replication_role" && normalised.eq_ignore_ascii_case("replica")
334        {
335            if value_off || key == "session_replication_role" {
336                self.foreign_key_checks = false;
337            } else if value_on
338                || (key == "session_replication_role" && normalised.eq_ignore_ascii_case("origin"))
339            {
340                self.foreign_key_checks = true;
341                // Drain pending FK queue against the now-complete
342                // catalog. Errors here surface as the SET reply —
343                // caller knows enabling checks revealed orphans.
344                let _ = self.drain_pending_foreign_keys();
345            }
346        }
347        // v7.22 (round-13 T3) — string-literal dialect signals.
348        // `SET sql_mode = …` is something only MySQL clients and
349        // mysqldump preambles emit → MySQL escape semantics.
350        // `SET standard_conforming_strings = on|off` is PG's own
351        // switch for exactly this behaviour (every pg_dump preamble
352        // sets it to on). The same SQL text lexes differently per
353        // dialect, so a flip invalidates the plan cache.
354        let new_escapes = if key == "sql_mode" {
355            // MySQL/MariaDB turn backslash escapes OFF only when the
356            // sql_mode list contains NO_BACKSLASH_ESCAPES; any other
357            // value (including an empty list) leaves them ON. Verified
358            // vs MariaDB: `SET sql_mode='STRICT_TRANS_TABLES'` → `'\n'`
359            // is a newline, `='NO_BACKSLASH_ESCAPES,STRICT_TRANS_TABLES'`
360            // → two bytes. sql_mode is a full replacement, so evaluate
361            // the whole new value rather than tracking a delta.
362            Some(
363                !normalised
364                    .to_ascii_uppercase()
365                    .contains("NO_BACKSLASH_ESCAPES"),
366            )
367        } else if key == "standard_conforming_strings" {
368            Some(value_off)
369        } else {
370            None
371        };
372        if let Some(flag) = new_escapes
373            && flag != self.backslash_escapes
374        {
375            self.backslash_escapes = flag;
376            self.plan_cache.clear();
377        }
378        // v7.39 (round 470) — the OTHER thing sql_mode carries: strictness.
379        // MariaDB's default list has STRICT_TRANS_TABLES, and a list
380        // without any STRICT_ flag makes a value that would raise get bent
381        // to fit instead. Measured on MariaDB 11 with `SET sql_mode=''`:
382        // INT <- 99999999999999 stores 2147483647, TINYINT <- 999 stores
383        // 127, INT UNSIGNED <- -5 stores 0, VARCHAR(3) <- 'toolong' stores
384        // 'too', INT <- 'abc' stores 0 and <- '12xy' stores 12.
385        if key == "sql_mode" {
386            let upper = normalised.to_ascii_uppercase();
387            self.mysql_strict =
388                upper.contains("STRICT_TRANS_TABLES") || upper.contains("STRICT_ALL_TABLES");
389            // v7.39 — and the third thing sql_mode carries: whether
390            // `"…"` is an identifier. Measured on MySQL 9.7.2,
391            // `SET sql_mode='ANSI_QUOTES'; SELECT "abc"` gives
392            // `Unknown column 'abc'` where the default list gives
393            // `abc`. The same text lexes differently either way, so a
394            // flip invalidates the plan cache exactly as
395            // `backslash_escapes` does.
396            // Only a MySQL client or a mysqldump preamble sends this.
397            self.speaks_mysql = true;
398            let ansi = upper.contains("ANSI_QUOTES");
399            if ansi != self.mysql_ansi_quotes {
400                self.mysql_ansi_quotes = ansi;
401                self.plan_cache.clear();
402            }
403        }
404        // v7.39 (GUC) — PG stores ms-unit time GUCs as an integer and
405        // renders SHOW/current_setting in the largest whole unit
406        // ("250" → "250ms", "5000" → "5s"). Normalise at store time so
407        // every read surface agrees.
408        // v7.39 (round 204) — memory GUCs canonicalize to the largest
409        // binary unit at store time, so `SET work_mem = '65536'` and
410        // `= '64MB'` both SHOW `64MB`, matching PG.
411        // v7.39 (round 522) — which parameters those are now comes from
412        // `guc_unit`, the same table `pg_settings` reads.
413        let normalised = match guc_unit(key.as_str()) {
414            Some("ms") => match parse_pg_duration_ms(&normalised) {
415                Some(ms) => render_pg_duration_ms(ms),
416                None => normalised,
417            },
418            Some(_) => match parse_pg_mem_kb(&normalised) {
419                Some(kb) => render_pg_mem_kb(kb),
420                None => normalised,
421            },
422            None => normalised,
423        };
424        // v7.39 (GUC knife 3) — datestyle is sticky per category (a bare
425        // 'DMY' keeps the current style; 'German' forces DMY); PG stores
426        // and SHOWs the RESOLVED canonical pair. intervalstyle /
427        // extra_float_digits just refresh the cached RenderStyle.
428        let normalised = if key == "datestyle" {
429            match parse_datestyle_parts(&normalised, self.render_style) {
430                Some((st, ord)) => String::from(datestyle_canonical(st, ord)),
431                // Invalid values are rejected earlier (validate_known_guc);
432                // an unvalidated caller keeps the raw text.
433                None => normalised,
434            }
435        } else {
436            normalised
437        };
438        let is_render_guc = matches!(
439            key.as_str(),
440            // v7.39 (round 524) — `bytea_output` joins them: it was
441            // accepted and never read.
442            "datestyle" | "intervalstyle" | "extra_float_digits" | "bytea_output"
443        );
444        self.session_params.insert(key, normalised);
445        if is_render_guc {
446            self.refresh_render_style();
447        }
448    }
449
450    /// v7.39 (GUC knife 3) — recompute the cached `RenderStyle` from the
451    /// session store. Called after any write/removal of a render GUC.
452    pub(crate) fn refresh_render_style(&mut self) {
453        let mut style = crate::eval::RenderStyle::default();
454        if let Some(ds) = self.session_param("datestyle")
455            && let Some((st, ord)) = parse_datestyle_parts(ds, style)
456        {
457            style.date_style = st;
458            style.date_order = ord;
459        }
460        if let Some(is) = self.session_param("intervalstyle")
461            && let Some(k) = parse_intervalstyle(is)
462        {
463            style.interval_style = k;
464        }
465        if let Some(efd) = self.session_param("extra_float_digits")
466            && let Ok(n) = efd.trim().parse::<i32>()
467        {
468            style.extra_float_digits = n;
469        }
470        if let Some(bo) = self.session_param("bytea_output") {
471            style.bytea_escape = bo.trim().eq_ignore_ascii_case("escape");
472        }
473        self.render_style = style;
474    }
475
476    /// v7.12.1 — read a session parameter set via `SET`. Used by
477    /// the FTS function dispatcher to resolve the default config
478    /// for `to_tsvector(text)` / `plainto_tsquery(text)` etc.
479    /// v7.39 (tz epic) — validate + canonicalise a `SET timezone`
480    /// value: 'utc' -> 'UTC'; fixed offsets / abbreviations keep their
481    /// spelling; IANA names resolve through the host tzdb to their
482    /// canonical case. Unknown -> PG's invalid-parameter error.
483    pub(crate) fn canonicalize_timezone(&self, value: &str) -> Result<String, crate::EngineError> {
484        let v = value.trim();
485        if v.eq_ignore_ascii_case("utc") || v.eq_ignore_ascii_case("gmt") {
486            return Ok(v.to_ascii_uppercase());
487        }
488        if crate::eval::datetime_resolve_zone_offset(v).is_some() {
489            return Ok(String::from(v));
490        }
491        match self.tz_canon_fn {
492            Some(f) => match f(v) {
493                Some(canon) => Ok(canon),
494                None => Err(crate::EngineError::Unsupported(alloc::format!(
495                    "invalid value for parameter \"TimeZone\": \"{v}\""
496                ))),
497            },
498            // No host tzdb (bare no_std embedding): keep the pre-epic
499            // accept-and-store behaviour — rendering degrades to UTC
500            // rather than rejecting a name we cannot verify.
501            None => Ok(String::from(v)),
502        }
503    }
504
505    /// v7.39 (GUC knife 3) — the parsed session render style (wire /
506    /// COPY renderers snapshot it once per statement).
507    #[must_use]
508    pub fn render_style(&self) -> crate::eval::RenderStyle {
509        self.render_style
510    }
511
512    /// v7.39 (round 547) — apply the GUC defaults `ALTER ROLE … SET` /
513    /// `ALTER DATABASE … SET` recorded, in PG's order of specificity.
514    ///
515    /// Measured on PG18: with all four scopes set, a new session got the
516    /// role-in-database value. So the least specific is applied first and
517    /// the most specific last, each overwriting.
518    pub fn apply_db_role_settings(&mut self, database: &str, role: &str) {
519        let scopes: alloc::vec::Vec<(alloc::string::String, alloc::string::String)> = alloc::vec![
520            (alloc::string::String::new(), alloc::string::String::new()),
521            (
522                alloc::string::String::from(database),
523                alloc::string::String::new()
524            ),
525            (
526                alloc::string::String::new(),
527                alloc::string::String::from(role)
528            ),
529            (
530                alloc::string::String::from(database),
531                alloc::string::String::from(role)
532            ),
533        ];
534        let mut apply: alloc::vec::Vec<(alloc::string::String, alloc::string::String)> =
535            alloc::vec::Vec::new();
536        for key in &scopes {
537            if let Some(params) = self.active_catalog().db_role_settings().get(key) {
538                for (k, v) in params {
539                    apply.push((k.clone(), v.clone()));
540                }
541            }
542        }
543        for (k, v) in apply {
544            let _ = self.execute(&alloc::format!("SET {k} = '{v}'"));
545        }
546    }
547
548    /// v7.39 (tz epic) — per-statement session TimeZone snapshot for
549    /// the timestamptz renderers. SET already validated the value, so
550    /// an unresolvable name here (host lost its tzdb) degrades to UTC.
551    #[must_use]
552    pub fn session_tz(&self) -> crate::SessionTz {
553        let Some(z) = self.session_param("timezone") else {
554            return crate::SessionTz::Utc;
555        };
556        if z.eq_ignore_ascii_case("utc") || z.eq_ignore_ascii_case("gmt") {
557            return crate::SessionTz::Utc;
558        }
559        if let Some(off) = crate::eval::datetime_resolve_zone_offset(z) {
560            return if off == 0 {
561                crate::SessionTz::Utc
562            } else {
563                crate::SessionTz::Fixed(off)
564            };
565        }
566        match (self.tz_offset_fn, self.tz_abbrev_fn) {
567            (Some(of), Some(af)) => crate::SessionTz::Named(String::from(z), of, af),
568            _ => crate::SessionTz::Utc,
569        }
570    }
571
572    #[must_use]
573    pub fn session_param(&self, name: &str) -> Option<&str> {
574        let lower = name.to_ascii_lowercase();
575        // v7.39 (read01 round 118, B3) — `transaction_isolation` is not a plain
576        // session GUC in the params map; it tracks the live per-transaction
577        // level (`BEGIN ISOLATION LEVEL …`, reset at COMMIT/ROLLBACK). The wire
578        // `SHOW` handler reads this, so it must report the live value rather
579        // than a seeded "read committed".
580        if lower == "transaction_isolation" {
581            return Some(self.current_isolation_level.as_pg_str());
582        }
583        self.session_params.get(&lower).map(String::as_str)
584    }
585
586    /// v7.39 (read01 round 46) — raise a PG-style NOTICE for the statement
587    /// now executing. The text is PG's exact wording minus the "NOTICE:  "
588    /// banner (the wire layer adds that); e.g. `table "t" does not exist,
589    /// skipping`.
590    pub(crate) fn notice(&mut self, text: alloc::string::String) {
591        self.pending_notices.push(crate::Notice {
592            severity: crate::NoticeSeverity::Notice,
593            message: text,
594        });
595    }
596
597    /// v7.39 (round 320, V53) — `RESET ALL` / the reset half of
598    /// `DISCARD ALL`: drop every GUC override, keeping the internal keys
599    /// that are not GUCs at all (the connection's login identity and its
600    /// database). Clearing the whole map took those with it.
601    pub(crate) fn reset_all_gucs(&mut self) {
602        let keep: alloc::vec::Vec<(String, String)> = [SESSION_USER_KEY, "spg.database"]
603            .iter()
604            .filter_map(|k| {
605                self.session_params
606                    .get(*k)
607                    .map(|v| (String::from(*k), v.clone()))
608            })
609            .collect();
610        self.session_params.clear();
611        for (k, v) in keep {
612            self.session_params.insert(k, v);
613        }
614    }
615
616    /// v7.39 (round 318, V41) — raise a PG-style WARNING. Same channel as
617    /// [`Self::notice`], one level louder: PG uses it for "the command
618    /// succeeded but did nothing useful" cases such as `SET CONSTRAINTS`
619    /// outside a transaction block.
620    pub(crate) fn warning(&mut self, text: alloc::string::String) {
621        self.pending_notices.push(crate::Notice {
622            severity: crate::NoticeSeverity::Warning,
623            message: text,
624        });
625    }
626
627    /// v7.39 (round 757, F31-B3) — deliver a plpgsql body's RAISE
628    /// messages into the pending-notice queue, honouring
629    /// `client_min_messages` (INFO passes unconditionally, as in PG).
630    pub(crate) fn drain_raise_sink(&mut self, sink: crate::triggers::NoticeSink) {
631        self.queue_raised(sink.into_inner());
632    }
633
634    /// The vec-shaped half: body walkers that cannot hold `&mut self`
635    /// collect into a plain Vec and the owning method queues it here.
636    pub(crate) fn queue_raised(
637        &mut self,
638        raised: alloc::vec::Vec<(crate::NoticeSeverity, alloc::string::String)>,
639    ) {
640        for (severity, message) in raised {
641            if self.notice_severity_reaches_client(severity) {
642                self.pending_notices
643                    .push(crate::Notice { severity, message });
644            }
645        }
646    }
647
648    /// v7.39 (read01 round 46) — drain the NOTICEs the last statement
649    /// raised. pgwire emits one NoticeResponse per entry ahead of the
650    /// statement's CommandComplete; embedded callers may ignore them.
651    #[must_use]
652    pub fn take_notices(&mut self) -> alloc::vec::Vec<crate::Notice> {
653        core::mem::take(&mut self.pending_notices)
654    }
655
656    /// v7.37.7 — PG `statement_timeout` GUC read accessor. Returns the
657    /// session-set value in **milliseconds**, parsed from the raw
658    /// `SET statement_timeout = N` string. Returns `None` when:
659    /// - the GUC is unset,
660    /// - the value is `0` (PG semantics: 0 = no timeout),
661    /// - the value fails to parse.
662    ///
663    /// Accepted input shapes mirror PG's `GUC_UNIT_MS` parser:
664    /// - bare digits: `100` → 100 ms (PG default unit when GUC is in ms)
665    /// - explicit ms: `100ms`, `100 ms`
666    /// - seconds:     `1s`, `30s` → 1000 / 30000 ms
667    /// - minutes:     `5min` → 300000 ms
668    ///
669    /// The host (`spg-server` per-query watchdog) consults this when
670    /// constructing the `CancelToken` deadline so a SQL-set
671    /// `SET statement_timeout = 1000` is honoured per-session — the
672    /// effective deadline becomes `min(SPG_QUERY_TIMEOUT_MS, session)`.
673    /// Returning `None` from this fn means "no session override, use
674    /// the host-level timeout only".
675    #[must_use]
676    pub fn session_statement_timeout_ms(&self) -> Option<u64> {
677        let raw = self.session_param("statement_timeout")?;
678        parse_pg_duration_ms(raw).filter(|ms| *ms > 0)
679    }
680
681    /// `work_mem` in BYTES, which is what a sort has to compare against.
682    ///
683    /// The GUC has been accepted, unit-normalised and rendered since
684    /// round 204, and never read: nothing in the engine turned it into a
685    /// budget, so a sort's memory was bounded by the row count and not
686    /// by the setting. Round 863 added this so the external sort has a
687    /// ceiling to spill at.
688    ///
689    /// PG's default is 4 MB, and the same default applies when the
690    /// session has not set it or the stored value will not parse.
691    #[must_use]
692    pub fn session_work_mem_bytes(&self) -> usize {
693        const DEFAULT_KB: usize = 4 * 1024;
694        let kb = self
695            .session_param("work_mem")
696            .and_then(parse_pg_mem_kb)
697            .and_then(|kb| usize::try_from(kb).ok())
698            .filter(|kb| *kb > 0)
699            .unwrap_or(DEFAULT_KB);
700        kb.saturating_mul(1024)
701    }
702
703    /// v7.39 (round 621) — does a message of this severity reach the client?
704    ///
705    /// `client_min_messages` was validated on the way in and then never read,
706    /// so `SET client_min_messages = warning` — and even `= error` — left the
707    /// NOTICEs coming. Every `DROP … IF EXISTS` on a name that is not there
708    /// said so, which is why the standing differential corpus could not use
709    /// the GUC to quieten its own setup and carried the asymmetry in eighteen
710    /// of its files.
711    ///
712    /// PG's order, ascending: debug5 < debug4 < debug3 < debug2 < debug1 <
713    /// log < notice < warning < error < fatal < panic. A message is sent when
714    /// its own severity is at least the setting. Anything above `warning`
715    /// suppresses both of the severities SPG raises.
716    #[must_use]
717    pub fn notice_severity_reaches_client(&self, severity: crate::NoticeSeverity) -> bool {
718        fn rank(s: &str) -> u8 {
719            match s {
720                "debug5" => 0,
721                "debug4" => 1,
722                "debug3" => 2,
723                "debug2" => 3,
724                "debug1" => 4,
725                "log" => 5,
726                "notice" => 6,
727                "warning" => 7,
728                "error" => 8,
729                "fatal" => 9,
730                "panic" => 10,
731                // Not one of PG's levels — SET would have refused it, so this
732                // is the default rather than a silent drop.
733                _ => 6,
734            }
735        }
736        let setting = self
737            .session_param("client_min_messages")
738            .map_or(6, |v| rank(&v.trim().to_ascii_lowercase()));
739        let own = match severity {
740            crate::NoticeSeverity::Notice => 6,
741            crate::NoticeSeverity::Warning => 7,
742            // PG sends INFO to the client unconditionally.
743            crate::NoticeSeverity::Info => return true,
744        };
745        own >= setting
746    }
747
748    /// v7.12.1 — build an `EvalContext` chained with the session's
749    /// `default_text_search_config`. Engine-internal callers use
750    /// this instead of `EvalContext::new` so the FTS function
751    /// dispatcher sees the SET configuration.
752    /// v7.39 (round 523) — the session zone's offset at a UTC instant,
753    /// or 0 when the session is on UTC.
754    ///
755    /// The clock rewrite needs it: `current_date` and the local-clock
756    /// family read the session's wall clock, and SPG's unified clock
757    /// reads UTC, so `SET TimeZone = 'Asia/Tokyo'` left `current_date`
758    /// naming yesterday for nine hours of every day.
759    pub(crate) fn session_tz_offset_at(&self, utc_micros: i64) -> i64 {
760        let Some(zone) = self.session_params.get("timezone") else {
761            return 0;
762        };
763        if zone.eq_ignore_ascii_case("utc") || zone.eq_ignore_ascii_case("gmt") {
764            return 0;
765        }
766        if let Some(off) = crate::eval::resolve_zone_offset_pub(zone) {
767            return off;
768        }
769        self.tz_offset_fn
770            .and_then(|f| f(zone, utc_micros))
771            .unwrap_or(0)
772    }
773
774    /// v7.39 (round 524) — the session, cloned for a write path's
775    /// evaluation context. See [`crate::eval::DmlSession`].
776    pub(crate) fn dml_session(&self) -> crate::eval::DmlSession {
777        crate::eval::DmlSession {
778            gucs: self.session_params.clone(),
779            users: self.users.clone(),
780            render_style: self.render_style,
781            tz_offset_fn: self.tz_offset_fn,
782            tz_localize_fn: self.tz_localize_fn,
783            tz_abbrev_fn: self.tz_abbrev_fn,
784        }
785    }
786
787    /// v7.39 (round 523) — the session facts an assignment into a
788    /// column is read under: the zone a naive timestamp names a
789    /// wall-clock reading in, and the order an ambiguous date is read
790    /// with. `None` when both are the defaults.
791    ///
792    /// The INSERT path evaluates VALUES through a context-free literal
793    /// walker with no `EvalContext`, so it takes these as an argument
794    /// the way it already takes the dialect.
795    /// v7.39 (round 524) — the date order joined it: the same
796    /// context-free walker read every written date as MDY.
797    pub(crate) fn session_coercion(&self) -> Option<crate::eval::SessionCoercion> {
798        let zone = self
799            .session_params
800            .get("timezone")
801            .filter(|z| !z.eq_ignore_ascii_case("utc") && !z.eq_ignore_ascii_case("gmt"))
802            .cloned();
803        let order = self.render_style.date_order;
804        if zone.is_none() && order == crate::eval::DateOrder::Mdy {
805            return None;
806        }
807        Some(crate::eval::SessionCoercion {
808            zone,
809            localize: self.tz_localize_fn,
810            order,
811        })
812    }
813
814    pub(crate) fn ev_ctx<'a>(
815        &'a self,
816        columns: &'a [ColumnSchema],
817        alias: Option<&'a str>,
818    ) -> EvalContext<'a> {
819        EvalContext::new(columns, alias)
820            .with_render_style(self.render_style)
821            .with_tz_fns(self.tz_offset_fn, self.tz_localize_fn, self.tz_abbrev_fn)
822            .with_default_text_search_config(self.session_param("default_text_search_config"))
823            // Thread the session GUC map so current_setting resolves
824            // custom `SET app.foo = …` settings (request-context / RLS).
825            .with_session_gucs(&self.session_params)
826            // v7.39 (read01 round 58) — and the role store, so the privilege
827            // builtins can expand role membership.
828            .with_users(&self.users)
829            // v7.39 (read01 round 63) — and the engine itself, so a user
830            // function whose body has its own FROM can run that body through
831            // the real executor (visibility filter and all).
832            .with_engine(self)
833            // v7.37.16 (16.12) — thread the read-only catalog so
834            // builtins like pg_partition_root can walk partition
835            // roles. Other EvalContext call sites (scan paths,
836            // joinfold, aggregate) continue to construct without
837            // catalog access; catalog-aware builtins return NULL
838            // there per documented contract.
839            //
840            // v7.38.19 — the ACTIVE catalog, not the committed one.
841            //
842            // A multi-statement simple query is an implicit transaction,
843            // so a function created earlier in the string lives in the
844            // transaction's shadow catalog. Reading the committed one
845            // meant `CREATE FUNCTION f() …; SELECT f()` answered
846            // `function f() does not exist` while the CREATE in that same
847            // string had just succeeded, and PostgreSQL 18.4 answers `1`.
848            //
849            // `CREATE TABLE t(…); SELECT count(*) FROM t` in the same
850            // position was already right, which is why this looked like
851            // an array-return defect when it surfaced: it was found while
852            // re-verifying a customer's ledger entry that said
853            // `RETURNS bigint[]` had been fixed in v7.37.25. Run on its
854            // own it is fixed; run beside its own CREATE it was not, and
855            // the ledger's probe had been the two-statement form.
856            //
857            // Ninth member of the family v7.38.18 documented for
858            // `ANALYZE` -- eight statement kinds read the active catalog
859            // there and one did not.
860            .with_catalog(self.active_catalog())
861            // v7.38 (read01 P5.24) — thread the host CSPRNG so gen_random_bytes
862            // / gen_salt use real entropy instead of the predictable PRNG.
863            .with_salt_fn(self.salt_fn)
864            // v7.39 (read01 pgstatfuncs.c) — calling-connection identity.
865            .with_backend_pid_fn(self.backend_pid_fn)
866            .with_wal_lsn_fn(self.wal_lsn_fn)
867            // v7.39 (round 318, V51) — and the connection-control hook, so
868            // pg_cancel_backend / pg_terminate_backend really signal.
869            .with_backend_signal_fn(self.backend_signal_fn)
870            // v7.38 (read01 P6.08) — thread the host wall clock so uuidv7 gets
871            // a real time-ordered prefix.
872            .with_clock(self.clock)
873            // v7.38 (T24) — thread the transaction-version state so the txid_*
874            // builtins report real ids instead of a constant stub.
875            .with_xact(self.xact_view())
876    }
877
878    /// v7.38 (T24) — read-only snapshot of the transaction-version state the
879    /// `txid_*` / `pg_xact_status` builtins read. A transaction's id is
880    /// allocated at BEGIN (`transaction.rs`), so it is stable across the
881    /// statements of that transaction, as in PG. In autocommit the id exists
882    /// only once the statement has written.
883    pub(crate) fn xact_view(&self) -> crate::eval::XactView<'_> {
884        crate::eval::XactView {
885            current: self
886                .current_tx
887                .and_then(|t| self.tx_writer_versions.get(&t).copied())
888                .or(self.stmt_writer_version),
889            active: &self.active_writer_versions,
890            aborted: &self.aborted_versions,
891        }
892    }
893}
894
895/// v7.37.7 — parse a PG-style `GUC_UNIT_MS` duration string into
896/// milliseconds. Accepts the same shapes PG itself accepts for
897/// `statement_timeout` and related ms-based GUCs.
898///
899/// Returns `None` on parse failure (callers treat None as "GUC not
900/// set / default applies").
901/// v7.39 (GUC knife 3) — parse a DateStyle value ('ISO, MDY' / 'German'
902/// / 'DMY' / …) against the current style: keywords apply in order,
903/// each updating its own category (PG semantics; German implies DMY).
904/// Returns None on any unrecognised keyword.
905pub(crate) fn parse_datestyle_parts(
906    value: &str,
907    current: crate::eval::RenderStyle,
908) -> Option<(crate::eval::DateStyleKind, crate::eval::DateOrder)> {
909    use crate::eval::{DateOrder, DateStyleKind};
910    let mut st = current.date_style;
911    let mut ord = current.date_order;
912    let mut any = false;
913    for part in value.split(',') {
914        let p = part.trim().to_ascii_lowercase();
915        match p.as_str() {
916            "iso" => st = DateStyleKind::Iso,
917            "german" => {
918                st = DateStyleKind::German;
919                ord = DateOrder::Dmy;
920            }
921            "sql" => st = DateStyleKind::Sql,
922            "postgres" => st = DateStyleKind::Postgres,
923            "mdy" | "us" | "noneuro" | "noneuropean" => ord = DateOrder::Mdy,
924            "dmy" | "euro" | "european" => ord = DateOrder::Dmy,
925            "ymd" => ord = DateOrder::Ymd,
926            _ => return None,
927        }
928        any = true;
929    }
930    if any { Some((st, ord)) } else { None }
931}
932
933/// The canonical `SHOW datestyle` text for a resolved pair.
934pub(crate) fn datestyle_canonical(
935    st: crate::eval::DateStyleKind,
936    ord: crate::eval::DateOrder,
937) -> &'static str {
938    use crate::eval::{DateOrder, DateStyleKind};
939    match (st, ord) {
940        (DateStyleKind::Iso, DateOrder::Mdy) => "ISO, MDY",
941        (DateStyleKind::Iso, DateOrder::Dmy) => "ISO, DMY",
942        (DateStyleKind::Iso, DateOrder::Ymd) => "ISO, YMD",
943        (DateStyleKind::German, DateOrder::Mdy) => "German, MDY",
944        (DateStyleKind::German, DateOrder::Dmy) => "German, DMY",
945        (DateStyleKind::German, DateOrder::Ymd) => "German, YMD",
946        (DateStyleKind::Sql, DateOrder::Mdy) => "SQL, MDY",
947        (DateStyleKind::Sql, DateOrder::Dmy) => "SQL, DMY",
948        (DateStyleKind::Sql, DateOrder::Ymd) => "SQL, YMD",
949        (DateStyleKind::Postgres, DateOrder::Mdy) => "Postgres, MDY",
950        (DateStyleKind::Postgres, DateOrder::Dmy) => "Postgres, DMY",
951        (DateStyleKind::Postgres, DateOrder::Ymd) => "Postgres, YMD",
952    }
953}
954
955/// v7.39 (GUC knife 3) — IntervalStyle keyword → kind.
956pub(crate) fn parse_intervalstyle(value: &str) -> Option<crate::eval::IntervalStyleKind> {
957    use crate::eval::IntervalStyleKind as K;
958    match value.trim().to_ascii_lowercase().as_str() {
959        "postgres" => Some(K::Postgres),
960        "sql_standard" => Some(K::SqlStandard),
961        "iso_8601" => Some(K::Iso8601),
962        "postgres_verbose" => Some(K::PostgresVerbose),
963        _ => None,
964    }
965}
966
967pub(crate) fn parse_pg_duration_ms(raw: &str) -> Option<u64> {
968    let s = raw.trim();
969    if s.is_empty() {
970        return None;
971    }
972    // PG accepts trailing unit suffix: ms / s / min / h / d. Strip in
973    // priority order (longer first so `min` doesn't match as `m`).
974    let lowered = s.to_ascii_lowercase();
975    let (num_part, multiplier_ms): (&str, u64) = if let Some(p) = lowered.strip_suffix("ms") {
976        (p, 1)
977    } else if let Some(p) = lowered.strip_suffix("min") {
978        (p, 60_000)
979    } else if let Some(p) = lowered.strip_suffix('s') {
980        (p, 1_000)
981    } else if let Some(p) = lowered.strip_suffix('h') {
982        (p, 3_600_000)
983    } else if let Some(p) = lowered.strip_suffix('d') {
984        (p, 86_400_000)
985    } else {
986        // No unit suffix — bare digits in the GUC's native unit (ms
987        // for `statement_timeout`).
988        (lowered.as_str(), 1)
989    };
990    let n: u64 = num_part.trim().parse().ok()?;
991    n.checked_mul(multiplier_ms)
992}
993
994/// v7.39 (GUC) — render a millisecond count the way PG's SHOW does:
995/// the largest unit that divides it evenly; zero is unit-less.
996fn render_pg_duration_ms(ms: u64) -> String {
997    use alloc::format;
998    if ms == 0 {
999        return String::from("0");
1000    }
1001    if ms % 86_400_000 == 0 {
1002        format!("{}d", ms / 86_400_000)
1003    } else if ms % 3_600_000 == 0 {
1004        format!("{}h", ms / 3_600_000)
1005    } else if ms % 60_000 == 0 {
1006        format!("{}min", ms / 60_000)
1007    } else if ms % 1_000 == 0 {
1008        format!("{}s", ms / 1_000)
1009    } else {
1010        format!("{ms}ms")
1011    }
1012}
1013
1014/// v7.39 (round 522) — the unit PG counts a GUC in.
1015///
1016/// PG keeps a parameter's value in TWO forms and they are not the same
1017/// string: `pg_settings.setting` is a bare number counting `unit`s
1018/// (`work_mem` → `4096`, unit `kB`), while SHOW / `current_setting`
1019/// render the human form (`4MB`). Measured on PG18: a value with no
1020/// suffix is already in the GUC's unit, so `SET work_mem = 8192` and
1021/// `= '8MB'` are the same setting.
1022///
1023/// One table so the SET-time normaliser and `pg_settings` cannot drift
1024/// apart on which parameters carry a unit — round 515 spent a round
1025/// re-syncing two copies of a list like this one.
1026pub(crate) fn guc_unit(name: &str) -> Option<&'static str> {
1027    match name {
1028        "statement_timeout"
1029        | "lock_timeout"
1030        | "idle_in_transaction_session_timeout"
1031        | "idle_session_timeout"
1032        | "transaction_timeout" => Some("ms"),
1033        "work_mem" | "maintenance_work_mem" => Some("kB"),
1034        // Counted in BLOCKS, and PG names the block size as the unit.
1035        "shared_buffers" | "temp_buffers" | "effective_cache_size" | "wal_buffers" => Some("8kB"),
1036        _ => None,
1037    }
1038}
1039
1040/// The bare count `pg_settings.setting` reports for a stored value —
1041/// the inverse of the human form SHOW renders. `None` when the
1042/// parameter has no unit or the value does not parse, and the caller
1043/// keeps the string it already had.
1044pub(crate) fn guc_raw_setting(name: &str, stored: &str) -> Option<String> {
1045    match guc_unit(name)? {
1046        "ms" => parse_pg_duration_ms(stored).map(|ms| alloc::format!("{ms}")),
1047        "kB" => parse_pg_mem_kb(stored).map(|kb| alloc::format!("{kb}")),
1048        // A block count, so the kB reading divides by the block size.
1049        "8kB" => parse_pg_mem_kb(stored).map(|kb| alloc::format!("{}", kb / 8)),
1050        _ => None,
1051    }
1052}
1053
1054/// v7.39 (round 204) — parse a PG memory-size GUC value to a count of
1055/// KILOBYTES (work_mem's base unit). Accepts a bare integer (already
1056/// kB) or a `<n><unit>` with unit B/kB/MB/GB/TB. `None` on malformed
1057/// input so the caller keeps the raw string.
1058pub(crate) fn parse_pg_mem_kb(raw: &str) -> Option<u64> {
1059    let s = raw.trim();
1060    if s.is_empty() {
1061        return None;
1062    }
1063    let lowered = s.to_ascii_lowercase();
1064    let (num_part, mult_kb): (&str, u64) = if let Some(p) = lowered.strip_suffix("tb") {
1065        (p, 1024 * 1024 * 1024)
1066    } else if let Some(p) = lowered.strip_suffix("gb") {
1067        (p, 1024 * 1024)
1068    } else if let Some(p) = lowered.strip_suffix("mb") {
1069        (p, 1024)
1070    } else if let Some(p) = lowered.strip_suffix("kb") {
1071        (p, 1)
1072    } else if let Some(p) = lowered.strip_suffix('b') {
1073        // bytes → kB only when a whole multiple of 1024.
1074        let n: u64 = p.trim().parse().ok()?;
1075        return if n % 1024 == 0 { Some(n / 1024) } else { None };
1076    } else {
1077        (lowered.as_str(), 1)
1078    };
1079    let n: u64 = num_part.trim().parse().ok()?;
1080    n.checked_mul(mult_kb)
1081}
1082
1083/// v7.39 (round 204) — render a kB count the way PG's SHOW does: the
1084/// largest binary unit that divides it evenly.
1085fn render_pg_mem_kb(kb: u64) -> String {
1086    use alloc::format;
1087    if kb == 0 {
1088        return String::from("0");
1089    }
1090    if kb % (1024 * 1024) == 0 {
1091        format!("{}GB", kb / (1024 * 1024))
1092    } else if kb % 1024 == 0 {
1093        format!("{}MB", kb / 1024)
1094    } else {
1095        format!("{kb}kB")
1096    }
1097}
1098
1099#[cfg(test)]
1100mod tests {
1101    use super::parse_pg_duration_ms;
1102    use alloc::format;
1103
1104    #[test]
1105    fn parse_bare_digits_treats_as_ms() {
1106        assert_eq!(parse_pg_duration_ms("100"), Some(100));
1107        assert_eq!(parse_pg_duration_ms("0"), Some(0));
1108        assert_eq!(parse_pg_duration_ms("60000"), Some(60_000));
1109    }
1110
1111    #[test]
1112    fn parse_ms_suffix() {
1113        assert_eq!(parse_pg_duration_ms("100ms"), Some(100));
1114        assert_eq!(parse_pg_duration_ms("100 ms"), Some(100));
1115    }
1116
1117    #[test]
1118    fn parse_seconds() {
1119        assert_eq!(parse_pg_duration_ms("1s"), Some(1_000));
1120        assert_eq!(parse_pg_duration_ms("30s"), Some(30_000));
1121    }
1122
1123    #[test]
1124    fn parse_minutes_uses_three_letter_suffix() {
1125        assert_eq!(parse_pg_duration_ms("5min"), Some(300_000));
1126        // `5m` is NOT valid PG (PG requires `min`); confirm we mirror.
1127        assert_eq!(parse_pg_duration_ms("5m"), None);
1128    }
1129
1130    #[test]
1131    fn parse_invalid_returns_none() {
1132        assert_eq!(parse_pg_duration_ms(""), None);
1133        assert_eq!(parse_pg_duration_ms("abc"), None);
1134        assert_eq!(parse_pg_duration_ms("100x"), None);
1135    }
1136
1137    #[test]
1138    fn parse_handles_whitespace() {
1139        assert_eq!(parse_pg_duration_ms("  100  "), Some(100));
1140    }
1141
1142    #[test]
1143    fn parse_overflow_returns_none() {
1144        // u64::MAX seconds overflows when multiplied by 1000 ms/s.
1145        assert_eq!(parse_pg_duration_ms(&format!("{}s", u64::MAX)), None);
1146    }
1147
1148    #[cfg(test)]
1149    mod session_integration {
1150        use crate::Engine;
1151        use spg_sql::ast::SetValue;
1152
1153        #[test]
1154        fn set_statement_timeout_round_trips_ms() {
1155            let mut e = Engine::new();
1156            e.set_session_param("statement_timeout".into(), SetValue::Number("250".into()));
1157            assert_eq!(e.session_statement_timeout_ms(), Some(250));
1158        }
1159
1160        #[test]
1161        fn set_statement_timeout_zero_is_none() {
1162            // PG semantics: 0 means "no timeout".
1163            let mut e = Engine::new();
1164            e.set_session_param("statement_timeout".into(), SetValue::Number("0".into()));
1165            assert_eq!(e.session_statement_timeout_ms(), None);
1166        }
1167
1168        #[test]
1169        fn statement_timeout_unset_is_none() {
1170            let e = Engine::new();
1171            assert_eq!(e.session_statement_timeout_ms(), None);
1172        }
1173
1174        #[test]
1175        fn statement_timeout_accepts_ms_suffix_via_string_set() {
1176            let mut e = Engine::new();
1177            e.set_session_param(
1178                "statement_timeout".into(),
1179                SetValue::String("1500ms".into()),
1180            );
1181            assert_eq!(e.session_statement_timeout_ms(), Some(1500));
1182        }
1183
1184        /// v7.39 (round 621) — `client_min_messages` decided nothing: the GUC
1185        /// was validated on the way in (round 204) and then never read, so
1186        /// `SET client_min_messages = warning` — and even `= error` — left
1187        /// every `DROP … IF EXISTS` notice coming.
1188        ///
1189        /// The wire half of this was checked against live PG18 over seven
1190        /// shapes and matches byte for byte; what is pinned here is the
1191        /// decision itself, which is the part that can drift.
1192        #[test]
1193        fn client_min_messages_gates_by_pg_severity_order() {
1194            use crate::NoticeSeverity::{Notice, Warning};
1195            let mut e = Engine::new();
1196            // The default is `notice`: both severities reach the client.
1197            assert!(e.notice_severity_reaches_client(Notice));
1198            assert!(e.notice_severity_reaches_client(Warning));
1199
1200            e.execute("SET client_min_messages = warning").unwrap();
1201            assert!(!e.notice_severity_reaches_client(Notice));
1202            assert!(e.notice_severity_reaches_client(Warning));
1203
1204            for above in ["error", "fatal", "panic"] {
1205                e.execute(&alloc::format!("SET client_min_messages = {above}"))
1206                    .unwrap();
1207                assert!(!e.notice_severity_reaches_client(Notice), "{above}");
1208                assert!(!e.notice_severity_reaches_client(Warning), "{above}");
1209            }
1210
1211            // Everything at or below `notice` lets both through — PG's order
1212            // is debug5 < … < log < notice < warning < error < fatal < panic.
1213            for below in ["notice", "log", "debug1", "debug5"] {
1214                e.execute(&alloc::format!("SET client_min_messages = {below}"))
1215                    .unwrap();
1216                assert!(e.notice_severity_reaches_client(Notice), "{below}");
1217                assert!(e.notice_severity_reaches_client(Warning), "{below}");
1218            }
1219
1220            // Case is not the caller's problem, and RESET is the road back.
1221            e.execute("SET client_min_messages = WARNING").unwrap();
1222            assert!(!e.notice_severity_reaches_client(Notice));
1223            e.execute("RESET client_min_messages").unwrap();
1224            assert!(e.notice_severity_reaches_client(Notice));
1225
1226            // And an out-of-domain value is still refused rather than
1227            // silently taken as some default.
1228            assert!(e.execute("SET client_min_messages = bogus_zz").is_err());
1229        }
1230    }
1231
1232    /// `work_mem` had been accepted, normalised and rendered since round
1233    /// 204 without anything reading it, so a sort's memory answered to
1234    /// the row count and not to the setting. These pin the read that
1235    /// round 863 added, including that it is the SAME number whichever
1236    /// spelling the session used — PG canonicalises at store time and
1237    /// the byte value has to follow.
1238    ///
1239    /// Round 863 checked these bite: with the accessor made to ignore
1240    /// the session, the `64MB` case drops to the 4MB default and this
1241    /// goes red. The fallback test below stays green either way, which
1242    /// is why it is not the one carrying the claim.
1243    #[test]
1244    fn work_mem_reads_back_as_bytes() {
1245        let mut e = crate::Engine::new();
1246        assert_eq!(
1247            e.session_work_mem_bytes(),
1248            4 * 1024 * 1024,
1249            "an untouched session gets PG's 4MB default"
1250        );
1251
1252        e.execute("SET work_mem = '64MB'").unwrap();
1253        assert_eq!(e.session_work_mem_bytes(), 64 * 1024 * 1024);
1254
1255        // Bare integers are kB, PG's base unit for this GUC.
1256        e.execute("SET work_mem = '65536'").unwrap();
1257        assert_eq!(
1258            e.session_work_mem_bytes(),
1259            64 * 1024 * 1024,
1260            "'65536' and '64MB' are the same setting and must be the same bytes"
1261        );
1262
1263        e.execute("SET work_mem = '1024kB'").unwrap();
1264        assert_eq!(e.session_work_mem_bytes(), 1024 * 1024);
1265    }
1266
1267    #[test]
1268    fn work_mem_that_cannot_be_read_falls_back_to_the_default() {
1269        let mut e = crate::Engine::new();
1270        // A rejected SET leaves the previous value in place; the point
1271        // here is that the accessor never hands back 0, which would
1272        // make a sort spill on its first row.
1273        let _ = e.execute("SET work_mem = 'not_a_size'");
1274        assert_eq!(e.session_work_mem_bytes(), 4 * 1024 * 1024);
1275        assert!(e.session_work_mem_bytes() > 0);
1276    }
1277}