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