Skip to main content

uqa_sql/semantics/
volatility.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! SQL function volatility and expression rewrite safety over catalog metadata.
8//!
9//! Volatility is a semantic property, not merely an optimizer hint.  A
10//! `VOLATILE` call may not be duplicated, elided, moved to a different join
11//! level, or hidden behind a statement-local view cache.  Keep the decision in
12//! one place so the view, CTE, predicate-pushdown, column-pruning, and `DPccp`
13//! paths cannot drift apart.
14
15use std::collections::BTreeSet;
16
17use crate::ast::{FunctionBinding, FunctionVolatility};
18use crate::plan::{QueryBlockPlan, QueryPlan, RelationalPlan, SourcePlan, UnifiedPlan};
19use crate::SQLError;
20use crate::ScalarExpr;
21
22/// Metadata needed to classify SQL expressions without invoking a routine or reading a row.
23pub trait VolatilityCatalog {
24    fn host_function_volatility(&self, name: &str) -> Option<FunctionVolatility>;
25    fn routine_volatilities(
26        &self,
27        name: &str,
28        binding: Option<&FunctionBinding>,
29    ) -> Option<Vec<FunctionVolatility>>;
30    fn view_query(&self, name: &str) -> Result<Option<QueryPlan>, SQLError>;
31}
32
33use super::builtin_function_dispatch_name;
34
35/// Resolve the volatility of the implementation that can run for `name`.
36///
37/// Rust extension callbacks default to `VOLATILE`, while registrations with
38/// explicit options use their declared volatility. SQL routine overloads are
39/// combined conservatively: a name is only non-volatile when every overload
40/// registered under it is non-volatile. This remains correct before runtime
41/// argument coercion selects a particular overload.
42pub fn function_volatility(
43    catalog: &dyn VolatilityCatalog,
44    name: &str,
45    argument_count: usize,
46) -> FunctionVolatility {
47    function_volatility_with_binding(catalog, name, None, argument_count)
48}
49
50pub fn function_binding_is_volatile(
51    catalog: &dyn VolatilityCatalog,
52    name: &str,
53    binding: Option<&FunctionBinding>,
54    argument_count: usize,
55) -> bool {
56    function_volatility_with_binding(catalog, name, binding, argument_count)
57        == FunctionVolatility::Volatile
58}
59
60fn is_intrinsic_scalar_syntax(binding: Option<&FunctionBinding>) -> bool {
61    binding
62        .and_then(|binding| binding.dispatch)
63        .is_some_and(crate::ast::FunctionDispatch::is_concatenation)
64        || matches!(
65            binding.and_then(|binding| binding.dispatch),
66            Some(
67                crate::ast::FunctionDispatch::NumericOperator(_)
68                    | crate::ast::FunctionDispatch::Pattern { .. }
69                    | crate::ast::FunctionDispatch::PatternEscape { .. }
70                    | crate::ast::FunctionDispatch::Collate { .. }
71                    | crate::ast::FunctionDispatch::BooleanTest(_)
72                    | crate::ast::FunctionDispatch::ArraySubscripts
73                    | crate::ast::FunctionDispatch::ArraySlices
74                    | crate::ast::FunctionDispatch::ArraySlicesWithBounds(_)
75            )
76        )
77}
78
79pub fn function_volatility_with_binding(
80    catalog: &dyn VolatilityCatalog,
81    name: &str,
82    binding: Option<&FunctionBinding>,
83    argument_count: usize,
84) -> FunctionVolatility {
85    let builtin = builtin_function_volatility(name, binding, argument_count);
86    if is_intrinsic_scalar_syntax(binding) || builtin == FunctionVolatility::Volatile {
87        return builtin;
88    }
89    let identity = name.to_ascii_lowercase();
90
91    // Registrations made through the original APIs retain the conservative
92    // VOLATILE default. Explicit options let pure callbacks participate in
93    // the same optimizer rules as declared SQL routines.
94    if let Some(volatility) = catalog.host_function_volatility(&identity) {
95        return volatility;
96    }
97
98    if let Some(volatility) = sql_routine_volatility(catalog, &identity, binding) {
99        return volatility;
100    }
101    builtin
102}
103
104/// Classify an already selected built-in without consulting host or SQL routine registrations. Callers that have not resolved the routine must use the catalog-aware entry point instead.
105pub fn builtin_function_volatility(
106    name: &str,
107    binding: Option<&FunctionBinding>,
108    argument_count: usize,
109) -> FunctionVolatility {
110    if let Some(crate::ast::FunctionDispatch::Concat { oid }) =
111        binding.and_then(|binding| binding.dispatch)
112    {
113        return oid
114            .and_then(|oid| crate::type_resolution::binary_operator_by_oid(i64::from(oid)))
115            .filter(|operator| operator.name == "||")
116            .map_or(FunctionVolatility::Stable, |operator| operator.volatility());
117    }
118    if is_intrinsic_scalar_syntax(binding) {
119        return FunctionVolatility::Immutable;
120    }
121    let lower = builtin_function_dispatch_name(&name.to_ascii_lowercase());
122    if builtin_is_volatile(&lower) {
123        return FunctionVolatility::Volatile;
124    }
125
126    // UQA retrieval/graph functions not listed above read the statement's
127    // catalog snapshot.  Session/catalog introspection functions have the same
128    // statement-stable contract.  All remaining built-ins are value-pure.
129    if crate::registry::is_registered(&lower)
130        || matches!(
131            lower.as_str(),
132            "current_schema"
133                | "concat"
134                | "concat_ws"
135                | "format"
136                | "pg_typeof"
137                | "pg_collation_for"
138                | "typeof"
139                | "row_to_json"
140                | "to_json"
141                | "to_jsonb"
142                | "json_build_object"
143                | "jsonb_build_object"
144                | "json_build_array"
145                | "jsonb_build_array"
146                | "to_char"
147                | "to_date"
148                | "to_number"
149                | "now"
150                | "current_date"
151                | "current_time"
152                | "current_timestamp"
153                | "localtime"
154                | "localtimestamp"
155                | "statement_timestamp"
156                | "transaction_timestamp"
157                | "current_schemas"
158                | "current_setting"
159                | "pg_backend_pid"
160                | "pg_my_temp_schema"
161                | "pg_is_other_temp_schema"
162                | "pg_trigger_depth"
163                | "version"
164                | "pg_listening_channels"
165                | "to_regclass"
166                | "to_regcollation"
167                | "to_regnamespace"
168                | "to_regproc"
169                | "to_regprocedure"
170                | "to_regrole"
171                | "to_regtype"
172                | "current_database"
173                | "current_catalog"
174                | "current_user"
175                | "session_user"
176                | "list_analyzers"
177                | "fts_index_stats"
178                | "pg_get_expr"
179                | "pg_get_partkeydef"
180                | "pg_get_serial_sequence"
181                | "pg_sequence_parameters"
182                | "pg_get_triggerdef"
183                | "pg_get_ruledef"
184                | "pg_get_viewdef"
185                | "pg_get_indexdef"
186                | "pg_get_constraintdef"
187                | "pg_get_function_arguments"
188                | "pg_get_function_identity_arguments"
189                | "pg_get_function_result"
190                | "pg_get_functiondef"
191            | "pg_get_function_sqlbody"
192                | "format_type"
193                | "pg_describe_object"
194            | "obj_description"
195                | "pg_has_role"
196                | "pg_get_userbyid"
197                | "has_database_privilege"
198                | "has_table_privilege"
199                | "has_column_privilege"
200                | "has_schema_privilege"
201                | "has_sequence_privilege"
202                | "has_function_privilege"
203                | "has_type_privilege"
204                // The enum support functions that read a type's label list see labels added later in the transaction.
205                | "enum_first"
206                | "enum_last"
207                | "enum_range"
208        )
209        || builtin_overload_is_stable(&lower, binding, argument_count)
210    {
211        FunctionVolatility::Stable
212    } else {
213        FunctionVolatility::Immutable
214    }
215}
216
217fn builtin_overload_is_stable(
218    name: &str,
219    binding: Option<&FunctionBinding>,
220    argument_count: usize,
221) -> bool {
222    (matches!(name, "age" | "timezone") && argument_count == 1)
223        || (name == "to_timestamp" && argument_count == 2)
224        || (matches!(name, "quote_literal" | "quote_nullable")
225            && binding.is_none_or(|binding| binding.argument_types.as_slice() != ["text"]))
226        || (matches!(name, "date_part" | "extract" | "date_trunc")
227            && argument_count == 2
228            && binding.is_none_or(|binding| {
229                binding
230                    .argument_types
231                    .iter()
232                    .any(|ty| matches!(ty.as_str(), "timestamptz" | "timestamp with time zone"))
233            }))
234}
235
236// These built-ins mutate catalog/session state or derive a fresh value on every evaluation.
237fn builtin_is_volatile(name: &str) -> bool {
238    matches!(
239        name,
240        "random"
241            | "setseed"
242            | "set_config"
243            | "pg_sleep"
244            | "pg_sleep_for"
245            | "pg_sleep_until"
246            | "pg_notify"
247            | "pg_notification_queue_usage"
248            | "array_sample"
249            | "nextval"
250            | "currval"
251            | "lastval"
252            | "setval"
253            | "pg_get_sequence_data"
254            | "pg_sequence_last_value"
255            | "clock_timestamp"
256            | "timeofday"
257            | "gen_random_uuid"
258            | "uuidv4"
259            | "uuidv7"
260            | "create_analyzer"
261            | "drop_analyzer"
262            | "set_table_analyzer"
263            | "graph_create"
264            | "graph_drop"
265            | "create_graph"
266            | "drop_graph"
267            | "graph_exists"
268            | "create_vlabel"
269            | "create_elabel"
270            | "drop_label"
271            | "alter_graph"
272            | "cypher"
273            | "deep_learn"
274            // Retrieval calibration learns and persists parameters on a
275            // cache miss; it therefore is not a read-only scalar operation.
276            | "bayesian_match"
277            | "bayesian_match_with_prior"
278            | "fts_match"
279            | "multi_field_match"
280    )
281}
282
283fn sql_routine_volatility(
284    catalog: &dyn VolatilityCatalog,
285    identity: &str,
286    binding: Option<&FunctionBinding>,
287) -> Option<FunctionVolatility> {
288    let overloads = catalog.routine_volatilities(identity, binding)?;
289    if overloads.contains(&FunctionVolatility::Volatile) {
290        return Some(FunctionVolatility::Volatile);
291    }
292    if overloads.contains(&FunctionVolatility::Stable) {
293        return Some(FunctionVolatility::Stable);
294    }
295    Some(FunctionVolatility::Immutable)
296}
297
298pub fn expr_contains_volatile_function(catalog: &dyn VolatilityCatalog, expr: &ScalarExpr) -> bool {
299    expr_contains_volatile_function_with(catalog, expr, true)
300}
301
302/// Query-level walks inspect a block's subquery plans themselves, so their expression scan treats a subquery reference as opaque-but-inspected (`conservative_subqueries == false`) instead of assuming volatility.
303fn expr_contains_volatile_function_with(
304    catalog: &dyn VolatilityCatalog,
305    expr: &ScalarExpr,
306    conservative_subqueries: bool,
307) -> bool {
308    let mut volatile = false;
309    expr.visit(&mut |part| {
310        if volatile {
311            return;
312        }
313        match part {
314            ScalarExpr::Func {
315                name,
316                binding,
317                args,
318                ..
319            } => {
320                volatile =
321                    function_volatility_with_binding(catalog, name, binding.as_ref(), args.len())
322                        == FunctionVolatility::Volatile;
323            }
324            ScalarExpr::WindowCall { name, args, .. } => {
325                volatile =
326                    function_volatility(catalog, name, args.len()) == FunctionVolatility::Volatile;
327            }
328            // Query-valued children are inspected by the enclosing QueryPlan. At expression-only rewrite sites, retaining the conservative rule prevents an opaque child query from being duplicated or reordered.
329            ScalarExpr::ScalarSubquery(_)
330            | ScalarExpr::Exists { .. }
331            | ScalarExpr::InSubquery { .. } => volatile = conservative_subqueries,
332            _ => {}
333        }
334    });
335    volatile
336}
337
338/// Inspect a scalar plan with its query arena instead of treating every subquery as an opaque volatile call.
339pub fn expression_plan_contains_volatile_function(
340    catalog: &dyn VolatilityCatalog,
341    plan: &crate::plan::ExpressionPlan,
342) -> Result<bool, SQLError> {
343    if expr_contains_volatile_function_with(catalog, &plan.scalar, false) {
344        return Ok(true);
345    }
346    for query in &plan.subqueries {
347        if query_contains_volatile_function(catalog, query)? {
348            return Ok(true);
349        }
350    }
351    Ok(false)
352}
353
354/// The block's own subquery plans are inspected separately by the query-level walk, so subquery references here are not conservatively volatile.
355pub fn select_contains_volatile_function(
356    catalog: &dyn VolatilityCatalog,
357    block: &QueryBlockPlan,
358) -> bool {
359    block
360        .projections
361        .iter()
362        .any(|projection| expr_contains_volatile_function_with(catalog, &projection.expr, false))
363        || block
364            .r#where
365            .as_ref()
366            .is_some_and(|expr| expr_contains_volatile_function_with(catalog, expr, false))
367        || block
368            .group_by
369            .iter()
370            .any(|expr| expr_contains_volatile_function_with(catalog, expr, false))
371        || block.grouping_sets.iter().any(|set| {
372            set.iter()
373                .any(|expr| expr_contains_volatile_function_with(catalog, expr, false))
374        })
375        || block
376            .having
377            .as_ref()
378            .is_some_and(|expr| expr_contains_volatile_function_with(catalog, expr, false))
379        || block
380            .order_by
381            .iter()
382            .any(|order| expr_contains_volatile_function_with(catalog, &order.expr, false))
383        || block
384            .limit
385            .as_ref()
386            .is_some_and(|expr| expr_contains_volatile_function_with(catalog, expr, false))
387        || block
388            .offset
389            .as_ref()
390            .is_some_and(|expr| expr_contains_volatile_function_with(catalog, expr, false))
391        || block
392            .distinct_on
393            .iter()
394            .any(|expr| expr_contains_volatile_function_with(catalog, expr, false))
395}
396
397/// Inspect a complete query, including transitive view dependencies.
398pub fn query_contains_volatile_function(
399    catalog: &dyn VolatilityCatalog,
400    plan: &QueryPlan,
401) -> Result<bool, SQLError> {
402    query_contains_volatile_function_inner(catalog, plan, &mut BTreeSet::new())
403}
404
405fn query_contains_volatile_function_inner(
406    catalog: &dyn VolatilityCatalog,
407    plan: &QueryPlan,
408    visiting_views: &mut BTreeSet<String>,
409) -> Result<bool, SQLError> {
410    for cte in &plan.ctes {
411        if match &cte.body {
412            crate::plan::CtePlanBody::Query(query) => {
413                query_contains_volatile_function_inner(catalog, query, visiting_views)?
414            }
415            crate::plan::CtePlanBody::Command(_) => true,
416        } {
417            return Ok(true);
418        }
419    }
420    match &plan.root {
421        RelationalPlan::QueryBlock(block) => {
422            if select_contains_volatile_function(catalog, block) {
423                return Ok(true);
424            }
425            for subquery in &block.subqueries {
426                if query_contains_volatile_function_inner(catalog, subquery, visiting_views)? {
427                    return Ok(true);
428                }
429            }
430            if let Some(source) = &block.from {
431                source_contains_volatile_function(catalog, source, visiting_views)
432            } else {
433                Ok(false)
434            }
435        }
436        RelationalPlan::SetOp {
437            left,
438            right,
439            order_by,
440            limit,
441            offset,
442            subqueries,
443            ..
444        } => {
445            if query_contains_volatile_function_inner(catalog, left, visiting_views)?
446                || query_contains_volatile_function_inner(catalog, right, visiting_views)?
447                || order_by
448                    .iter()
449                    .any(|order| expr_contains_volatile_function(catalog, &order.expr))
450                || limit
451                    .as_ref()
452                    .is_some_and(|expr| expr_contains_volatile_function(catalog, expr))
453                || offset
454                    .as_ref()
455                    .is_some_and(|expr| expr_contains_volatile_function(catalog, expr))
456            {
457                return Ok(true);
458            }
459            for subquery in subqueries {
460                if query_contains_volatile_function_inner(catalog, subquery, visiting_views)? {
461                    return Ok(true);
462                }
463            }
464            Ok(false)
465        }
466        RelationalPlan::Values { rows, subqueries } => {
467            if rows
468                .iter()
469                .flatten()
470                .any(|expr| expr_contains_volatile_function(catalog, expr))
471            {
472                return Ok(true);
473            }
474            for subquery in subqueries {
475                if query_contains_volatile_function_inner(catalog, subquery, visiting_views)? {
476                    return Ok(true);
477                }
478            }
479            Ok(false)
480        }
481    }
482}
483
484fn source_contains_volatile_function(
485    catalog: &dyn VolatilityCatalog,
486    source: &SourcePlan,
487    visiting_views: &mut BTreeSet<String>,
488) -> Result<bool, SQLError> {
489    match source {
490        crate::plan::SourcePlan::RetainedRows(_) => Ok(false),
491        SourcePlan::Table { name, .. } => {
492            let key = name.to_ascii_lowercase();
493            if !visiting_views.insert(key.clone()) {
494                return Ok(false);
495            }
496            let result = match catalog.view_query(name)? {
497                Some(view) => {
498                    query_contains_volatile_function_inner(catalog, &view, visiting_views)
499                }
500                None => Ok(false),
501            };
502            visiting_views.remove(&key);
503            result
504        }
505        SourcePlan::Join {
506            left, right, on, ..
507        } => {
508            if on
509                .as_ref()
510                .is_some_and(|expr| expr_contains_volatile_function(catalog, expr))
511            {
512                return Ok(true);
513            }
514            Ok(
515                source_contains_volatile_function(catalog, left, visiting_views)?
516                    || source_contains_volatile_function(catalog, right, visiting_views)?,
517            )
518        }
519        SourcePlan::Values { rows, .. } => Ok(rows
520            .iter()
521            .flatten()
522            .any(|expr| expr_contains_volatile_function(catalog, expr))),
523        SourcePlan::Function {
524            name,
525            binding,
526            args,
527            ..
528        } => Ok(
529            function_volatility_with_binding(catalog, name, binding.as_ref(), args.len())
530                == FunctionVolatility::Volatile
531                || args
532                    .iter()
533                    .any(|expr| expr_contains_volatile_function(catalog, expr)),
534        ),
535        SourcePlan::FunctionGroup { functions, .. } => Ok(functions.iter().any(|function| {
536            function_volatility_with_binding(
537                catalog,
538                &function.name,
539                function.binding.as_ref(),
540                function.args.len(),
541            ) == FunctionVolatility::Volatile
542                || function
543                    .args
544                    .iter()
545                    .any(|expr| expr_contains_volatile_function(catalog, expr))
546        })),
547        SourcePlan::Subquery { body, .. } => {
548            query_contains_volatile_function_inner(catalog, body, visiting_views)
549        }
550    }
551}
552
553/// Whether scalar optimizer rewrites or `DPccp` join enumeration must be kept
554/// away from a plan.  `rewrite_scalar_expressions` is exhaustive over query,
555/// mutation, CTE, prepared/explained, and expression-plan children.
556pub fn unified_plan_contains_volatile_function(
557    catalog: &dyn VolatilityCatalog,
558    plan: &UnifiedPlan,
559) -> bool {
560    let mut inspected = plan.clone();
561    let mut volatile = false;
562    inspected.rewrite_scalar_expressions(&mut |expr| {
563        if volatile {
564            return;
565        }
566        match expr {
567            ScalarExpr::Func {
568                name,
569                binding,
570                args,
571                ..
572            } => {
573                volatile =
574                    function_volatility_with_binding(catalog, name, binding.as_ref(), args.len())
575                        == FunctionVolatility::Volatile;
576            }
577            ScalarExpr::WindowCall { name, args, .. } => {
578                volatile =
579                    function_volatility(catalog, name, args.len()) == FunctionVolatility::Volatile;
580            }
581            _ => {}
582        }
583    });
584    volatile
585}
586
587#[cfg(test)]
588mod tests {
589    use super::{
590        expr_contains_volatile_function, FunctionBinding, FunctionVolatility, QueryPlan, SQLError,
591        ScalarExpr, VolatilityCatalog,
592    };
593
594    struct EmptyCatalog;
595    impl VolatilityCatalog for EmptyCatalog {
596        fn host_function_volatility(&self, _: &str) -> Option<FunctionVolatility> {
597            None
598        }
599        fn routine_volatilities(
600            &self,
601            _: &str,
602            _: Option<&FunctionBinding>,
603        ) -> Option<Vec<FunctionVolatility>> {
604            None
605        }
606        fn view_query(&self, _: &str) -> Result<Option<QueryPlan>, SQLError> {
607            Ok(None)
608        }
609    }
610    use crate::ast::{FrameExclusion, FrameMode};
611    use crate::{ScalarFrameBound, ScalarWindowFrame, ScalarWindowSpec};
612
613    #[test]
614    fn collation_volatility_follows_only_its_operand() {
615        struct Shadowed;
616        impl VolatilityCatalog for Shadowed {
617            fn host_function_volatility(&self, _: &str) -> Option<FunctionVolatility> {
618                Some(FunctionVolatility::Volatile)
619            }
620            fn routine_volatilities(
621                &self,
622                _: &str,
623                _: Option<&FunctionBinding>,
624            ) -> Option<Vec<FunctionVolatility>> {
625                unreachable!("host function wins ordinary calls")
626            }
627            fn view_query(&self, _: &str) -> Result<Option<QueryPlan>, SQLError> {
628                unreachable!("no view")
629            }
630        }
631        for (input, expected) in [
632            ("'x' COLLATE \"C\"", false),
633            ("nextval('effect')::text COLLATE \"C\"", true),
634            ("\"COLLATE\"('x')", true),
635            ("true IS TRUE", false),
636            ("(nextval('effect') > 0) IS NOT FALSE", true),
637            ("\"IS TRUE\"(true)", true),
638            ("(ARRAY[1,2])[1]", false),
639            ("(ARRAY[1,2])[:1]", false),
640            ("(ARRAY[1,2])[nextval('effect')]", true),
641            ("(ARRAY[1,2])[:nextval('effect')]", true),
642            ("slice(ARRAY[1,2], 1, 2)", true),
643            ("subscript(ARRAY[1,2], 1)", true),
644        ] {
645            let crate::Statement::Select(mut query) = crate::compile(&format!("SELECT {input}"))
646                .unwrap()
647                .remove(0)
648            else {
649                panic!("SELECT")
650            };
651            let scalar =
652                crate::plan::ExpressionPlan::lower(query.projections.remove(0).expr).scalar;
653            assert_eq!(
654                expr_contains_volatile_function(&Shadowed, &scalar),
655                expected,
656                "{input}"
657            );
658        }
659        let binding =
660            FunctionBinding::dispatched(crate::ast::FunctionDispatch::Collate { oid: Some(950) });
661        assert_eq!(
662            super::builtin_function_volatility("nextval", Some(&binding), 2),
663            FunctionVolatility::Immutable
664        );
665    }
666
667    #[test]
668    fn builtin_constants_preserve_postgresql_statement_and_session_inputs() {
669        // Checked against PostgreSQL 18.4 pg_proc.provolatile before enabling bound built-in constant folding.
670        for name in [
671            "concat",
672            "concat_ws",
673            "format",
674            "pg_typeof",
675            "row_to_json",
676            "to_json",
677            "to_jsonb",
678            "json_build_object",
679            "jsonb_build_array",
680            "to_char",
681            "to_date",
682            "to_number",
683            "has_table_privilege",
684            "has_column_privilege",
685        ] {
686            assert_eq!(
687                super::builtin_function_volatility(name, None, 2),
688                FunctionVolatility::Stable,
689                "{name}"
690            );
691        }
692        for name in ["repeat", "upper"] {
693            assert_eq!(
694                super::builtin_function_volatility(name, None, 2),
695                FunctionVolatility::Immutable,
696                "{name}"
697            );
698        }
699        assert_eq!(
700            super::builtin_function_volatility("nextval", None, 1),
701            FunctionVolatility::Volatile
702        );
703    }
704
705    #[test]
706    fn sequence_introspection_volatility_matches_postgresql() {
707        for (name, expected) in [
708            ("pg_get_sequence_data", FunctionVolatility::Volatile),
709            ("pg_sequence_last_value", FunctionVolatility::Volatile),
710            ("pg_sequence_parameters", FunctionVolatility::Stable),
711        ] {
712            for qualified in [name.to_string(), format!("pg_catalog.{name}")] {
713                assert_eq!(
714                    super::function_volatility(&EmptyCatalog, &qualified, 1),
715                    expected,
716                    "{qualified}"
717                );
718            }
719        }
720    }
721
722    #[test]
723    fn timestamp_zone_volatility_preserves_session_dependence() {
724        assert_eq!(
725            super::builtin_function_volatility("timezone", None, 1),
726            FunctionVolatility::Stable
727        );
728        assert_eq!(
729            super::builtin_function_volatility("timezone", None, 2),
730            FunctionVolatility::Immutable
731        );
732    }
733
734    #[test]
735    fn volatility_inspection_includes_window_frame_expressions() {
736        let expression = ScalarExpr::WindowCall {
737            name: "sum".into(),
738            args: vec![ScalarExpr::Column("amount".into())],
739            spec: ScalarWindowSpec {
740                definition: None,
741                partition_by: Vec::new(),
742                order_by: Vec::new(),
743                frame: Some(ScalarWindowFrame {
744                    mode: FrameMode::Rows,
745                    start: ScalarFrameBound::Preceding(Box::new(ScalarExpr::Func {
746                        order_syntax: crate::ast::FunctionOrderSyntax::Ordinary,
747                        name: "random".into(),
748                        binding: None,
749                        args: Vec::new(),
750                        distinct: false,
751                        order_by: Vec::new(),
752                        filter: None,
753                    })),
754                    end: ScalarFrameBound::CurrentRow,
755                    between: true,
756                    exclusion: FrameExclusion::NoOthers,
757                }),
758            },
759            filter: None,
760            modifiers: crate::ast::WindowCallModifiers::default(),
761        };
762        assert!(expr_contains_volatile_function(&EmptyCatalog, &expression));
763    }
764    #[test]
765    fn scalar_plan_volatility_inspects_its_subquery_body() {
766        for (sql, expected) in [
767            ("SELECT (SELECT 1 / 0)", false),
768            ("SELECT (SELECT nextval('ticks'))", true),
769        ] {
770            let crate::plan::UnifiedPlan::Query(query) =
771                crate::plan::UnifiedPlan::lower(crate::compile(sql).unwrap().remove(0))
772            else {
773                panic!("query");
774            };
775            let crate::plan::RelationalPlan::QueryBlock(mut block) = query.root else {
776                panic!("query block");
777            };
778            let plan = crate::plan::ExpressionPlan {
779                scalar: block.projections.remove(0).expr,
780                subqueries: block.subqueries,
781            };
782            assert_eq!(
783                super::expression_plan_contains_volatile_function(&EmptyCatalog, &plan).unwrap(),
784                expected,
785                "{sql}"
786            );
787        }
788    }
789}