uqa-sql 0.6.3

PostgreSQL-compatible SQL compiler built on libpg_query
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! SQL function volatility and expression rewrite safety over catalog metadata.
//!
//! Volatility is a semantic property, not merely an optimizer hint.  A
//! `VOLATILE` call may not be duplicated, elided, moved to a different join
//! level, or hidden behind a statement-local view cache.  Keep the decision in
//! one place so the view, CTE, predicate-pushdown, column-pruning, and `DPccp`
//! paths cannot drift apart.

use crate::ast::{FunctionBinding, FunctionVolatility};
use crate::plan::{QueryBlockPlan, QueryPlan, UnifiedPlan};
use crate::SQLError;
use crate::ScalarExpr;

mod production;
pub use production::{
    builtin_function_volatility_with_control, expr_contains_volatile_function_with_control,
    function_volatility_with_binding_and_control, query_contains_volatile_function_with_control,
    scalar_calls_are_volatile_with_control,
    scalar_in_scope_contains_volatile_function_with_control,
    select_contains_volatile_function_with_control,
    unified_plan_contains_volatile_function_with_control,
};

/// Metadata needed to classify SQL expressions without invoking a routine or reading a row.
pub trait VolatilityCatalog {
    fn host_function_volatility(&self, name: &str) -> Option<FunctionVolatility>;
    fn routine_volatilities(
        &self,
        name: &str,
        binding: Option<&FunctionBinding>,
    ) -> Option<Vec<FunctionVolatility>>;
    /// Aggregate an external catalog's completed metadata; native registries override this with a borrowed fold.
    fn routine_volatility_with_control(
        &self,
        name: &str,
        binding: Option<&FunctionBinding>,
        control: &uqa_core::memory::ProductionControl<'_>,
    ) -> Result<Option<FunctionVolatility>, SQLError> {
        control.check()?;
        let result = self
            .routine_volatilities(name, binding)
            .as_deref()
            .map(production::strongest);
        control.check()?;
        Ok(result)
    }
    fn view_query(&self, name: &str) -> Result<Option<QueryPlan>, SQLError>;

    /// Lend the selected view plan for one read. Catalogs retaining immutable definitions can override this adapter without constructing an owned plan.
    fn with_view_query(
        &self,
        name: &str,
        read: &mut dyn FnMut(&QueryPlan) -> Result<bool, SQLError>,
    ) -> Result<Option<bool>, SQLError> {
        self.view_query(name)?.as_ref().map(read).transpose()
    }

    /// Read a retained native view under the current production scope. The external default keeps its existing callback boundary; native borrowed overrides do not construct a query copy.
    fn with_view_query_with_control(
        &self,
        name: &str,
        control: &uqa_core::memory::ProductionControl<'_>,
        read: &mut dyn FnMut(&QueryPlan) -> Result<bool, SQLError>,
    ) -> Result<Option<bool>, SQLError> {
        control.check()?;
        let result = self.with_view_query(name, &mut |query| {
            control.check()?;
            read(query)
        })?;
        control.check()?;
        Ok(result)
    }
}

use super::builtin_function_dispatch_name;

/// Resolve the volatility of the implementation that can run for `name`.
///
/// Rust extension callbacks default to `VOLATILE`, while registrations with
/// explicit options use their declared volatility. SQL routine overloads are
/// combined conservatively: a name is only non-volatile when every overload
/// registered under it is non-volatile. This remains correct before runtime
/// argument coercion selects a particular overload.
pub fn function_volatility(
    catalog: &dyn VolatilityCatalog,
    name: &str,
    argument_count: usize,
) -> FunctionVolatility {
    function_volatility_with_binding(catalog, name, None, argument_count)
}

pub fn function_binding_is_volatile(
    catalog: &dyn VolatilityCatalog,
    name: &str,
    binding: Option<&FunctionBinding>,
    argument_count: usize,
) -> bool {
    function_volatility_with_binding(catalog, name, binding, argument_count)
        == FunctionVolatility::Volatile
}

fn is_intrinsic_scalar_syntax(binding: Option<&FunctionBinding>) -> bool {
    binding
        .and_then(|binding| binding.dispatch)
        .is_some_and(crate::ast::FunctionDispatch::is_concatenation)
        || matches!(
            binding.and_then(|binding| binding.dispatch),
            Some(
                crate::ast::FunctionDispatch::NumericOperator(_)
                    | crate::ast::FunctionDispatch::Pattern { .. }
                    | crate::ast::FunctionDispatch::PatternEscape { .. }
                    | crate::ast::FunctionDispatch::Collate { .. }
                    | crate::ast::FunctionDispatch::BooleanTest(_)
                    | crate::ast::FunctionDispatch::ArraySubscripts
                    | crate::ast::FunctionDispatch::ArraySlices
                    | crate::ast::FunctionDispatch::ArraySlicesWithBounds(_)
            )
        )
}

pub fn function_volatility_with_binding(
    catalog: &dyn VolatilityCatalog,
    name: &str,
    binding: Option<&FunctionBinding>,
    argument_count: usize,
) -> FunctionVolatility {
    function_volatility_with_binding_and_control(
        catalog,
        name,
        binding,
        argument_count,
        &uqa_core::memory::ProductionControl::uncontrolled(),
    )
    .expect("ordinary routine volatility has no resource failure")
}

/// 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.
pub fn builtin_function_volatility(
    name: &str,
    binding: Option<&FunctionBinding>,
    argument_count: usize,
) -> FunctionVolatility {
    if let Some(crate::ast::FunctionDispatch::Concat { oid }) =
        binding.and_then(|binding| binding.dispatch)
    {
        return oid
            .and_then(|oid| crate::type_resolution::binary_operator_by_oid(i64::from(oid)))
            .filter(|operator| operator.name == "||")
            .map_or(FunctionVolatility::Stable, |operator| operator.volatility());
    }
    if is_intrinsic_scalar_syntax(binding) {
        return FunctionVolatility::Immutable;
    }
    let lower = builtin_function_dispatch_name(name);
    if builtin_is_volatile(&lower) {
        return FunctionVolatility::Volatile;
    }

    // UQA retrieval/graph functions not listed above read the statement's
    // catalog snapshot.  Session/catalog introspection functions have the same
    // statement-stable contract.  All remaining built-ins are value-pure.
    if crate::registry::is_registered(&lower)
        || matches!(
            lower.as_ref(),
            "current_schema"
                | "concat"
                | "concat_ws"
                | "format"
                | "pg_typeof"
                | "pg_collation_for"
                | "typeof"
                | "row_to_json"
                | "to_json"
                | "to_jsonb"
                | "json_build_object"
                | "jsonb_build_object"
                | "json_build_array"
                | "jsonb_build_array"
                | "to_char"
                | "to_date"
                | "to_number"
                | "now"
                | "current_date"
                | "current_time"
                | "current_timestamp"
                | "localtime"
                | "localtimestamp"
                | "statement_timestamp"
                | "transaction_timestamp"
                | "current_schemas"
                | "current_setting"
                | "pg_backend_pid"
                | "pg_my_temp_schema"
                | "pg_is_other_temp_schema"
                | "pg_trigger_depth"
                | "version"
                | "pg_listening_channels"
                | "to_regclass"
                | "to_regcollation"
                | "to_regnamespace"
                | "to_regproc"
                | "to_regprocedure"
                | "to_regrole"
                | "to_regtype"
                | "current_database"
                | "current_catalog"
                | "current_user"
                | "session_user"
                | "list_analyzers"
                | "fts_index_stats"
                | "pg_get_expr"
                | "pg_get_partkeydef"
                | "pg_get_serial_sequence"
                | "pg_sequence_parameters"
                | "pg_get_triggerdef"
                | "pg_get_ruledef"
                | "pg_get_viewdef"
                | "pg_get_indexdef"
                | "pg_get_constraintdef"
                | "pg_get_function_arguments"
                | "pg_get_function_identity_arguments"
                | "pg_get_function_result"
                | "pg_get_functiondef"
            | "pg_get_function_sqlbody"
                | "format_type"
                | "pg_describe_object"
            | "obj_description"
                | "pg_has_role"
                | "pg_get_userbyid"
                | "has_database_privilege"
                | "has_table_privilege"
                | "has_column_privilege"
                | "has_schema_privilege"
                | "has_sequence_privilege"
                | "has_function_privilege"
                | "has_type_privilege"
                // The enum support functions that read a type's label list see labels added later in the transaction.
                | "enum_first"
                | "enum_last"
                | "enum_range"
        )
        || builtin_overload_is_stable(&lower, binding, argument_count)
    {
        FunctionVolatility::Stable
    } else {
        FunctionVolatility::Immutable
    }
}

fn builtin_overload_is_stable(
    name: &str,
    binding: Option<&FunctionBinding>,
    argument_count: usize,
) -> bool {
    (matches!(name, "age" | "timezone") && argument_count == 1)
        || (name == "to_timestamp" && argument_count == 2)
        || (matches!(name, "quote_literal" | "quote_nullable")
            && binding.is_none_or(|binding| binding.argument_types.as_slice() != ["text"]))
        || (matches!(name, "date_part" | "extract" | "date_trunc")
            && argument_count == 2
            && binding.is_none_or(|binding| {
                binding
                    .argument_types
                    .iter()
                    .any(|ty| matches!(ty.as_str(), "timestamptz" | "timestamp with time zone"))
            }))
}

// These built-ins mutate catalog/session state or derive a fresh value on every evaluation.
fn builtin_is_volatile(name: &str) -> bool {
    matches!(
        name,
        "random"
            | "setseed"
            | "set_config"
            | "pg_sleep"
            | "pg_sleep_for"
            | "pg_sleep_until"
            | "pg_notify"
            | "pg_notification_queue_usage"
            | "array_sample"
            | "nextval"
            | "currval"
            | "lastval"
            | "setval"
            | "pg_get_sequence_data"
            | "pg_sequence_last_value"
            | "clock_timestamp"
            | "timeofday"
            | "gen_random_uuid"
            | "uuidv4"
            | "uuidv7"
            | "create_analyzer"
            | "drop_analyzer"
            | "set_table_analyzer"
            | "graph_create"
            | "graph_drop"
            | "create_graph"
            | "drop_graph"
            | "graph_exists"
            | "create_vlabel"
            | "create_elabel"
            | "drop_label"
            | "alter_graph"
            | "cypher"
            | "deep_learn"
            // Retrieval calibration learns and persists parameters on a
            // cache miss; it therefore is not a read-only scalar operation.
            | "bayesian_match"
            | "bayesian_match_with_prior"
            | "fts_match"
            | "multi_field_match"
    )
}

pub fn expr_contains_volatile_function(catalog: &dyn VolatilityCatalog, expr: &ScalarExpr) -> bool {
    expr_contains_volatile_function_with(catalog, expr, true)
}

/// Inspect calls in this scalar expression only. The caller must inspect query-valued children through their owning arena before moving or duplicating an expression.
pub fn scalar_calls_are_volatile(catalog: &dyn VolatilityCatalog, expr: &ScalarExpr) -> bool {
    expr_contains_volatile_function_with(catalog, expr, false)
}

/// 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.
fn expr_contains_volatile_function_with(
    catalog: &dyn VolatilityCatalog,
    expr: &ScalarExpr,
    conservative_subqueries: bool,
) -> bool {
    production::expression_contains_volatile_with_control(
        catalog,
        expr,
        conservative_subqueries,
        &uqa_core::memory::ProductionControl::uncontrolled(),
    )
    .expect("ordinary scalar volatility has no resource failure")
}

/// Inspect a scalar plan with its query arena instead of treating every subquery as an opaque volatile call.
pub fn expression_plan_contains_volatile_function(
    catalog: &dyn VolatilityCatalog,
    plan: &crate::plan::ExpressionPlan,
) -> Result<bool, SQLError> {
    scalar_with_subqueries_contains_volatile_function(catalog, &plan.scalar, &plan.subqueries)
}

/// Inspect a borrowed expression and only the query children it references in its owning arena. Other projections may share that arena without contributing effects to this expression.
pub fn scalar_with_subqueries_contains_volatile_function(
    catalog: &dyn VolatilityCatalog,
    scalar: &ScalarExpr,
    subqueries: &[QueryPlan],
) -> Result<bool, SQLError> {
    scalar_in_scope_contains_volatile_function(catalog, scalar, subqueries, &|_| false)
}

/// Inspect an expression's referenced subqueries under its enclosing CTE namespace. Those external producers are owned and evaluated by their defining query, not by this scalar expression.
pub fn scalar_in_scope_contains_volatile_function(
    catalog: &dyn VolatilityCatalog,
    scalar: &ScalarExpr,
    subqueries: &[QueryPlan],
    visible_ctes: &dyn Fn(&str) -> bool,
) -> Result<bool, SQLError> {
    scalar_in_scope_contains_volatile_function_with_control(
        catalog,
        scalar,
        subqueries,
        visible_ctes,
        &uqa_core::memory::ProductionControl::uncontrolled(),
    )
}

/// The block's own subquery plans are inspected separately by the query-level walk, so subquery references here are not conservatively volatile.
pub fn select_contains_volatile_function(
    catalog: &dyn VolatilityCatalog,
    block: &QueryBlockPlan,
) -> bool {
    select_contains_volatile_function_with_control(
        catalog,
        block,
        &uqa_core::memory::ProductionControl::uncontrolled(),
    )
    .expect("ordinary block volatility")
}

/// Inspect a complete query, including transitive view dependencies.
pub fn query_contains_volatile_function(
    catalog: &dyn VolatilityCatalog,
    plan: &QueryPlan,
) -> Result<bool, SQLError> {
    query_contains_volatile_function_with_control(
        catalog,
        plan,
        &uqa_core::memory::ProductionControl::uncontrolled(),
    )
}

/// Whether scalar optimizer rewrites or `DPccp` join enumeration must preserve volatile call scheduling. Borrow the plan and its expression roots; inspecting constants must not copy their retained payloads or allocate command child lists.
pub fn unified_plan_contains_volatile_function(
    catalog: &dyn VolatilityCatalog,
    plan: &UnifiedPlan,
) -> bool {
    unified_plan_contains_volatile_function_with_control(
        catalog,
        plan,
        &uqa_core::memory::ProductionControl::uncontrolled(),
    )
    .expect("ordinary statement volatility")
}

#[cfg(test)]
mod tests;