Skip to main content

mz_sql/plan/statement/
scl.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//! Session control language (SCL).
11//!
12//! This module houses the handlers for statements that manipulate the session,
13//! like `DISCARD` and `SET`.
14
15use mz_ore::str::StrExt;
16use mz_repr::{CatalogItemId, RelationDesc, RelationVersionSelector, SqlScalarType};
17use mz_sql_parser::ast::InspectShardStatement;
18use std::time::Duration;
19use uncased::UncasedStr;
20
21use crate::ast::display::AstDisplay;
22use crate::ast::{
23    CloseStatement, DeallocateStatement, DeclareStatement, DiscardStatement, DiscardTarget,
24    ExecuteStatement, FetchOption, FetchOptionName, FetchStatement, Ident, PrepareStatement,
25    ResetVariableStatement, SetVariableStatement, SetVariableTo, ShowVariableStatement,
26};
27use crate::names::{self, Aug};
28use crate::plan::statement::{StatementContext, StatementDesc};
29use crate::plan::{
30    ClosePlan, DeallocatePlan, DeclarePlan, ExecutePlan, ExecuteTimeout, FetchPlan,
31    InspectShardPlan, Params, Plan, PlanError, PreparePlan, ResetVariablePlan, SetVariablePlan,
32    ShowVariablePlan, VariableValue, describe, query,
33};
34use crate::session::vars;
35use crate::session::vars::{SCHEMA_ALIAS, VarInput};
36
37pub fn describe_set_variable(
38    _: &StatementContext,
39    _: SetVariableStatement,
40) -> Result<StatementDesc, PlanError> {
41    Ok(StatementDesc::new(None))
42}
43
44pub fn plan_set_variable(
45    scx: &StatementContext,
46    SetVariableStatement {
47        local,
48        variable,
49        to,
50    }: SetVariableStatement,
51) -> Result<Plan, PlanError> {
52    let value = plan_set_variable_to(to)?;
53    let name = variable.into_string();
54
55    // Gate feature-flagged isolation levels at plan time. The same check runs in
56    // `SessionVars::set`, which also covers `ALTER ROLE ... SET` and connection
57    // options; running it here too surfaces the error before sequencing.
58    if let VariableValue::Values(values) = &value {
59        vars::check_transaction_isolation_feature_flag(
60            &name,
61            VarInput::SqlSet(values),
62            scx.catalog.system_vars(),
63        )?;
64    }
65
66    Ok(Plan::SetVariable(SetVariablePlan { name, value, local }))
67}
68
69pub fn plan_set_variable_to(to: SetVariableTo) -> Result<VariableValue, PlanError> {
70    match to {
71        SetVariableTo::Default => Ok(VariableValue::Default),
72        SetVariableTo::Values(values) => {
73            // Per PostgreSQL, string literals and identifiers are treated
74            // equivalently during `SET`. We retain only the underlying string
75            // value of each element in the list. It's our caller's
76            // responsibility to figure out how to set the variable to the
77            // provided list of values using variable-specific logic.
78            let values = values
79                .into_iter()
80                .map(|v| v.into_unquoted_value())
81                .collect();
82            Ok(VariableValue::Values(values))
83        }
84    }
85}
86
87pub fn describe_reset_variable(
88    _: &StatementContext,
89    _: ResetVariableStatement,
90) -> Result<StatementDesc, PlanError> {
91    Ok(StatementDesc::new(None))
92}
93
94pub fn plan_reset_variable(
95    _: &StatementContext,
96    ResetVariableStatement { variable }: ResetVariableStatement,
97) -> Result<Plan, PlanError> {
98    Ok(Plan::ResetVariable(ResetVariablePlan {
99        name: variable.to_string(),
100    }))
101}
102
103pub fn describe_show_variable(
104    _: &StatementContext,
105    ShowVariableStatement { variable, .. }: ShowVariableStatement,
106) -> Result<StatementDesc, PlanError> {
107    let desc = if variable.as_str() == UncasedStr::new("ALL") {
108        RelationDesc::builder()
109            .with_column("name", SqlScalarType::String.nullable(false))
110            .with_column("setting", SqlScalarType::String.nullable(false))
111            .with_column("description", SqlScalarType::String.nullable(false))
112            .finish()
113    } else if variable.as_str() == SCHEMA_ALIAS {
114        RelationDesc::builder()
115            .with_column(variable.as_str(), SqlScalarType::String.nullable(true))
116            .finish()
117    } else {
118        RelationDesc::builder()
119            .with_column(variable.as_str(), SqlScalarType::String.nullable(false))
120            .finish()
121    };
122    Ok(StatementDesc::new(Some(desc)))
123}
124
125pub fn plan_show_variable(
126    _: &StatementContext,
127    ShowVariableStatement { variable }: ShowVariableStatement,
128) -> Result<Plan, PlanError> {
129    if variable.as_str() == UncasedStr::new("ALL") {
130        Ok(Plan::ShowAllVariables)
131    } else {
132        Ok(Plan::ShowVariable(ShowVariablePlan {
133            name: variable.to_string(),
134        }))
135    }
136}
137
138pub fn describe_inspect_shard(
139    _: &StatementContext,
140    InspectShardStatement { .. }: InspectShardStatement,
141) -> Result<StatementDesc, PlanError> {
142    let desc = RelationDesc::builder()
143        .with_column("state", SqlScalarType::Jsonb.nullable(false))
144        .finish();
145    Ok(StatementDesc::new(Some(desc)))
146}
147
148pub fn plan_inspect_shard(
149    scx: &StatementContext,
150    InspectShardStatement { id }: InspectShardStatement,
151) -> Result<Plan, PlanError> {
152    let id: CatalogItemId = id.parse().map_err(|_| sql_err!("invalid shard id"))?;
153    // Always inspect the shard at the latest GlobalId.
154    let gid = scx
155        .catalog
156        .try_get_item(&id)
157        .ok_or_else(|| sql_err!("item doesn't exist"))?
158        .at_version(RelationVersionSelector::Latest)
159        .global_id();
160    Ok(Plan::InspectShard(InspectShardPlan { id: gid }))
161}
162
163pub fn describe_discard(
164    _: &StatementContext,
165    _: DiscardStatement,
166) -> Result<StatementDesc, PlanError> {
167    Ok(StatementDesc::new(None))
168}
169
170pub fn plan_discard(
171    _: &StatementContext,
172    DiscardStatement { target }: DiscardStatement,
173) -> Result<Plan, PlanError> {
174    match target {
175        DiscardTarget::All => Ok(Plan::DiscardAll),
176        DiscardTarget::Temp => Ok(Plan::DiscardTemp),
177        DiscardTarget::Sequences => bail_unsupported!("DISCARD SEQUENCES"),
178        DiscardTarget::Plans => bail_unsupported!("DISCARD PLANS"),
179    }
180}
181
182pub fn describe_declare(
183    scx: &StatementContext,
184    DeclareStatement { stmt, .. }: DeclareStatement<Aug>,
185    param_types_in: &[Option<SqlScalarType>],
186) -> Result<StatementDesc, PlanError> {
187    let (stmt_resolved, resolved_ids) = names::resolve(scx.catalog, *stmt)?;
188    // Get the desc for the inner statement, but only for its parameters. The outer DECLARE doesn't
189    // return any rows itself when executed.
190    let desc = describe(
191        scx.pcx()?,
192        scx.catalog,
193        stmt_resolved,
194        param_types_in,
195        &resolved_ids,
196    )?;
197    // The outer describe fn calls scx.finalize_param_types, so we need to transfer the inner desc's
198    // params to this scx.
199    for (i, ty) in desc.param_types.into_iter().enumerate() {
200        scx.param_types.borrow_mut().insert(i + 1, ty);
201    }
202    Ok(StatementDesc::new(None))
203}
204
205/// The lookup key for the prepared statement or portal that `name` refers to.
206///
207/// Both namespaces are shared with the extended protocol, which stores names
208/// exactly as they arrive on the wire, so the key is the identifier's raw value
209/// rather than its SQL rendering, which re-quotes anything not printable bare.
210fn statement_or_portal_name(name: Ident) -> String {
211    name.into_string()
212}
213
214pub fn plan_declare(
215    _: &StatementContext,
216    DeclareStatement { name, stmt, sql }: DeclareStatement<Aug>,
217    params: &Params,
218) -> Result<Plan, PlanError> {
219    Ok(Plan::Declare(DeclarePlan {
220        name: statement_or_portal_name(name),
221        stmt: *stmt,
222        sql,
223        params: params.clone(),
224    }))
225}
226
227pub fn describe_fetch(
228    scx: &StatementContext,
229    FetchStatement {
230        name,
231        count: _,
232        options: _,
233    }: FetchStatement<Aug>,
234) -> Result<StatementDesc, PlanError> {
235    let name = statement_or_portal_name(name);
236    if let Some(mut desc) = scx.catalog.get_portal_desc_unverified(&name).cloned() {
237        // Parameters are already bound to the portal and will not be accepted through
238        // FETCH.
239        desc.param_types = Vec::new();
240        Ok(desc)
241    } else {
242        Err(PlanError::UnknownCursor(name))
243    }
244}
245
246generate_extracted_config!(FetchOption, (Timeout, Duration));
247
248pub fn plan_fetch(
249    _: &StatementContext,
250    FetchStatement {
251        name,
252        count,
253        options,
254    }: FetchStatement<Aug>,
255) -> Result<Plan, PlanError> {
256    let FetchOptionExtracted { timeout, .. } = options.try_into()?;
257    let timeout = match timeout {
258        Some(timeout) => {
259            // Limit FETCH timeouts to 1 day. If users have a legitimate need it can be
260            // bumped. If we do bump it, ensure that the new upper limit is within the
261            // bounds of a tokio time future, otherwise it'll panic.
262            const DAY: Duration = Duration::from_secs(60 * 60 * 24);
263            if timeout > DAY {
264                sql_bail!("timeout out of range: {}s", timeout.as_secs_f64());
265            }
266            ExecuteTimeout::Seconds(timeout.as_secs_f64())
267        }
268        // FETCH defaults to WaitOnce.
269        None => ExecuteTimeout::WaitOnce,
270    };
271    Ok(Plan::Fetch(FetchPlan {
272        name: statement_or_portal_name(name),
273        count,
274        timeout,
275    }))
276}
277
278pub fn describe_close(_: &StatementContext, _: CloseStatement) -> Result<StatementDesc, PlanError> {
279    Ok(StatementDesc::new(None))
280}
281
282pub fn plan_close(
283    _: &StatementContext,
284    CloseStatement { name }: CloseStatement,
285) -> Result<Plan, PlanError> {
286    Ok(Plan::Close(ClosePlan {
287        name: statement_or_portal_name(name),
288    }))
289}
290
291pub fn describe_prepare(
292    _: &StatementContext,
293    _: PrepareStatement<Aug>,
294) -> Result<StatementDesc, PlanError> {
295    Ok(StatementDesc::new(None))
296}
297
298pub fn plan_prepare(
299    scx: &StatementContext,
300    PrepareStatement { name, stmt, sql }: PrepareStatement<Aug>,
301) -> Result<Plan, PlanError> {
302    // TODO: PREPARE supports specifying param types.
303    let param_types = [];
304    let (stmt_resolved, resolved_ids) = names::resolve(scx.catalog, *stmt.clone())?;
305    let desc = describe(
306        scx.pcx()?,
307        scx.catalog,
308        stmt_resolved,
309        &param_types,
310        &resolved_ids,
311    )?;
312    Ok(Plan::Prepare(PreparePlan {
313        name: statement_or_portal_name(name),
314        stmt: *stmt,
315        desc,
316        sql,
317    }))
318}
319
320pub fn describe_execute(
321    scx: &StatementContext,
322    stmt: ExecuteStatement<Aug>,
323) -> Result<StatementDesc, PlanError> {
324    // The evaluation of the statement doesn't happen until it gets to coord. That
325    // means if the statement is now invalid due to an object having been dropped,
326    // describe is unable to notice that. This is currently an existing problem
327    // with prepared statements over pgwire as well, so we can leave this for now.
328    // See database-issues#2563.
329    Ok(plan_execute_desc(scx, stmt)?.0.clone())
330}
331
332pub fn plan_execute(
333    scx: &StatementContext,
334    stmt: ExecuteStatement<Aug>,
335) -> Result<Plan, PlanError> {
336    Ok(plan_execute_desc(scx, stmt)?.1)
337}
338
339fn plan_execute_desc<'a>(
340    scx: &'a StatementContext,
341    ExecuteStatement { name, params }: ExecuteStatement<Aug>,
342) -> Result<(&'a StatementDesc, Plan), PlanError> {
343    let name = statement_or_portal_name(name);
344    let desc = match scx.catalog.get_prepared_statement_desc(&name) {
345        Some(desc) => desc,
346        // TODO(mjibson): use CoordError::UnknownPreparedStatement.
347        None => sql_bail!("unknown prepared statement {}", name.quoted()),
348    };
349    Ok((
350        desc,
351        Plan::Execute(ExecutePlan {
352            name,
353            params: query::plan_params(scx, params, desc)?,
354        }),
355    ))
356}
357
358pub fn describe_deallocate(
359    _: &StatementContext,
360    _: DeallocateStatement,
361) -> Result<StatementDesc, PlanError> {
362    Ok(StatementDesc::new(None))
363}
364
365pub fn plan_deallocate(
366    _: &StatementContext,
367    DeallocateStatement { name }: DeallocateStatement,
368) -> Result<Plan, PlanError> {
369    Ok(Plan::Deallocate(DeallocatePlan {
370        name: name.map(statement_or_portal_name),
371    }))
372}