Skip to main content

mz_sql/plan/
side_effecting_func.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Support for side-effecting functions.
11//!
12//! In PostgreSQL, these functions can appear anywhere in a query:
13//!
14//! ```sql
15//! SELECT 1 WHERE pg_cancel_backend(1234)
16//! ```
17//!
18//! In Materialize, our compute layer cannot execute functions with side
19//! effects. So we sniff out the common form of calls to side-effecting
20//! functions, i.e. at the top level of a `SELECT`
21//!
22//! ```sql
23//! SELECT side_effecting_function(...)
24//! ```
25//!
26//! where all arguments are literals or bound parameters, and plan them
27//! specially as a `Plan::SideEffectingFunc`. This gets us compatibility with
28//! PostgreSQL for most real-world use cases, without causing stress for the
29//! compute layer (optimizer, dataflow execution, etc.), as we can apply all the
30//! side effects entirely in the adapter layer.
31
32use std::collections::BTreeMap;
33use std::sync::LazyLock;
34
35use enum_kinds::EnumKind;
36use itertools::Itertools;
37use mz_ore::cast::ReinterpretCast;
38use mz_ore::collections::CollectionExt;
39use mz_ore::result::ResultExt;
40use mz_repr::SqlRelationType;
41use mz_repr::{Datum, RelationDesc, RowArena, SqlColumnType, SqlScalarType};
42use mz_sql_parser::ast::{CteBlock, Expr, Function, FunctionArgs, Select, SelectItem, SetExpr};
43
44use crate::ast::{Query, SelectStatement};
45use crate::func::Func;
46use crate::names::Aug;
47use crate::plan::query::{self, ExprContext, QueryLifetime};
48use crate::plan::scope::Scope;
49use crate::plan::statement::StatementContext;
50use crate::plan::typeconv::CastContext;
51use crate::plan::{HirScalarExpr, Params};
52use crate::plan::{PlanError, QueryContext};
53
54/// A side-effecting function is a function whose evaluation triggers side
55/// effects.
56///
57/// See the module docs for details.
58#[derive(Debug, EnumKind, Clone)]
59#[enum_kind(SefKind)]
60pub enum SideEffectingFunc {
61    /// The `pg_cancel_backend` function.
62    PgCancelBackend {
63        // The ID of the connection to cancel, or `None` if the argument was
64        // `NULL`, in which case the function returns `NULL`.
65        connection_id: Option<u32>,
66    },
67}
68
69/// Describes a `SELECT` if it contains calls to side-effecting functions.
70///
71/// See the module docs for details.
72pub fn describe_select_if_side_effecting(
73    scx: &StatementContext,
74    select: &SelectStatement<Aug>,
75) -> Result<Option<RelationDesc>, PlanError> {
76    let Some(sef_call) = extract_sef_call(scx, select)? else {
77        return Ok(None);
78    };
79
80    // We currently support only a single call to a side-effecting function
81    // without an alias, so there is always a single output column is named
82    // after the function.
83    let desc = RelationDesc::builder()
84        .with_column(sef_call.imp.name, sef_call.imp.return_type.clone())
85        .finish();
86
87    Ok(Some(desc))
88}
89
90/// Plans the `SELECT` if it contains calls to side-effecting functions.
91///
92/// See the module docs for details.
93pub fn plan_select_if_side_effecting(
94    scx: &StatementContext,
95    select: &SelectStatement<Aug>,
96    params: &Params,
97) -> Result<Option<SideEffectingFunc>, PlanError> {
98    let Some(sef_call) = extract_sef_call(scx, select)? else {
99        return Ok(None);
100    };
101
102    // Bind parameters and then eagerly evaluate each argument. Expressions that
103    // cannot be eagerly evaluated should have been rejected by `extract_sef_call`.
104    let temp_storage = RowArena::new();
105    let mut args = vec![];
106    for mut arg in sef_call.args {
107        arg.bind_parameters_and_simplify_offset(scx, QueryLifetime::OneShot, params)?;
108        let arg = arg.lower_uncorrelated(scx.catalog.system_vars())?;
109        args.push(arg);
110    }
111    let mut datums = vec![];
112    for arg in &args {
113        let datum = arg.eval_constant_foldable(&temp_storage)?;
114        datums.push(datum);
115    }
116
117    let func = (sef_call.imp.plan_fn)(&datums);
118
119    Ok(Some(func))
120}
121
122/// Helper function used in both describing and planning a side-effecting
123/// `SELECT`.
124fn extract_sef_call(
125    scx: &StatementContext,
126    select: &SelectStatement<Aug>,
127) -> Result<Option<SefCall>, PlanError> {
128    // First check if the `SELECT` contains exactly one function call.
129    let SelectStatement {
130        query:
131            Query {
132                ctes: CteBlock::Simple(ctes),
133                body: SetExpr::Select(body),
134                order_by,
135                limit: None,
136                offset: None,
137            },
138        as_of: None,
139    } = select
140    else {
141        return Ok(None);
142    };
143    if !ctes.is_empty() || !order_by.is_empty() {
144        return Ok(None);
145    }
146    let Select {
147        distinct: None,
148        projection,
149        from,
150        selection: None,
151        group_by,
152        having: None,
153        qualify: None,
154        options,
155    } = &**body
156    else {
157        return Ok(None);
158    };
159    if !from.is_empty() || !group_by.is_empty() || !options.is_empty() || projection.len() != 1 {
160        return Ok(None);
161    }
162    let [
163        SelectItem::Expr {
164            expr:
165                Expr::Function(Function {
166                    name,
167                    args: FunctionArgs::Args { args, order_by },
168                    filter: None,
169                    over: None,
170                    distinct: false,
171                }),
172            alias: None,
173        },
174    ] = &projection[..]
175    else {
176        return Ok(None);
177    };
178    if !order_by.is_empty() {
179        return Ok(None);
180    }
181
182    // Check if the called function is a scalar function with exactly one
183    // implementation. All side-effecting functions have only a single
184    // implementation.
185    let Ok(func) = scx
186        .get_item_by_resolved_name(name)
187        .and_then(|item| item.func().err_into())
188    else {
189        return Ok(None);
190    };
191    let func_impl = match func {
192        Func::Scalar(impls) if impls.len() == 1 => impls.into_element(),
193        _ => return Ok(None),
194    };
195
196    // Check whether the implementation is a known side-effecting function.
197    let Some(sef_impl) = PG_CATALOG_SEF_BUILTINS.get(&func_impl.oid) else {
198        return Ok(None);
199    };
200
201    // Check that the number of provided arguments matches the function
202    // signature.
203    if args.len() != sef_impl.param_types.len() {
204        // We return `Ok(None)` instead of an error for the same reason to let
205        // the function selection code produce the standard "no function matches
206        // the given name and argument types" error.
207        return Ok(None);
208    }
209
210    // Plan and coerce all argument expressions.
211    let mut args_out = vec![];
212    let qcx = QueryContext::root(scx, QueryLifetime::OneShot);
213    let ecx = ExprContext {
214        qcx: &qcx,
215        name: sef_impl.name,
216        scope: &Scope::empty(),
217        relation_type: &SqlRelationType::empty(),
218        allow_aggregates: false,
219        allow_subqueries: false,
220        allow_parameters: true,
221        allow_windows: false,
222    };
223    for (arg, ty) in args.iter().zip_eq(sef_impl.param_types) {
224        // If we encounter an error when planning the argument expression, that
225        // error is unrelated to planning the function call and can be returned
226        // directly to the user.
227        let arg = query::plan_expr(&ecx, arg)?;
228
229        // Implicitly cast the argument to the correct type. This matches what
230        // the standard function selection code will do.
231        //
232        // If the cast fails, we give up on planning the side-effecting function but
233        // intentionally do not produce an error. This way, we fall into the
234        // standard function selection code, which will produce the correct "no
235        // function matches the given name and argument types" error rather than a
236        // "cast failed" error.
237        let Ok(arg) = arg.cast_to(&ecx, CastContext::Implicit, ty) else {
238            return Ok(None);
239        };
240
241        args_out.push(arg);
242    }
243
244    Ok(Some(SefCall {
245        imp: sef_impl,
246        args: args_out,
247    }))
248}
249
250struct SefCall {
251    imp: &'static SideEffectingFuncImpl,
252    args: Vec<HirScalarExpr>,
253}
254
255/// Defines the implementation of a side-effecting function.
256///
257/// This is a very restricted subset of the [`Func`] struct (no overloads, no
258/// variadic arguments, etc) to make side-effecting functions easier to plan.
259pub struct SideEffectingFuncImpl {
260    /// The name of the function.
261    pub name: &'static str,
262    /// The OID of the function.
263    pub oid: u32,
264    /// The parameter types for the function.
265    pub param_types: &'static [SqlScalarType],
266    /// The return type of the function.
267    pub return_type: SqlColumnType,
268    /// A function that will produce a `SideEffectingFunc` given arguments
269    /// that have been evaluated to `Datum`s.
270    pub plan_fn: fn(&[Datum]) -> SideEffectingFunc,
271}
272
273/// A map of the side-effecting functions in the `pg_catalog` schema, keyed by
274/// OID.
275pub static PG_CATALOG_SEF_BUILTINS: LazyLock<BTreeMap<u32, SideEffectingFuncImpl>> =
276    LazyLock::new(|| {
277        [PG_CANCEL_BACKEND]
278            .into_iter()
279            .map(|f| (f.oid, f))
280            .collect()
281    });
282
283// Implementations of each side-effecting function follow.
284//
285// If you add a new side-effecting function, be sure to add it to the map above.
286
287const PG_CANCEL_BACKEND: SideEffectingFuncImpl = SideEffectingFuncImpl {
288    name: "pg_cancel_backend",
289    oid: 2171,
290    param_types: &[SqlScalarType::Int32],
291    // Like in PostgreSQL, the function returns `NULL` when its argument is
292    // `NULL`, so the output column is nullable.
293    return_type: SqlScalarType::Bool.nullable(true),
294    plan_fn: |datums| -> SideEffectingFunc {
295        let connection_id = match datums[0] {
296            Datum::Null => None,
297            datum => Some(u32::reinterpret_cast(datum.unwrap_int32())),
298        };
299        SideEffectingFunc::PgCancelBackend { connection_id }
300    },
301};