risingwave_frontend/handler/
variable.rs

1// Copyright 2025 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use anyhow::Context;
16use itertools::Itertools;
17use pgwire::pg_field_descriptor::PgFieldDescriptor;
18use pgwire::pg_protocol::ParameterStatus;
19use pgwire::pg_response::{PgResponse, StatementType};
20use risingwave_common::session_config::{ConfigReporter, SESSION_CONFIG_LIST_SEP};
21use risingwave_common::system_param::reader::SystemParamsRead;
22use risingwave_common::types::Fields;
23use risingwave_sqlparser::ast::{Ident, SetTimeZoneValue, SetVariableValue, Value};
24
25use super::{RwPgResponse, RwPgResponseBuilderExt, fields_to_descriptors};
26use crate::error::Result;
27use crate::handler::HandlerArgs;
28
29/// convert `SetVariableValue` to string while remove the quotes on literals.
30pub(crate) fn set_var_to_param_str(value: &SetVariableValue) -> Option<String> {
31    match value {
32        SetVariableValue::Single(var) => Some(var.to_string_unquoted()),
33        SetVariableValue::List(list) => Some(
34            list.iter()
35                .map(|var| var.to_string_unquoted())
36                .join(SESSION_CONFIG_LIST_SEP),
37        ),
38        SetVariableValue::Default => None,
39    }
40}
41
42pub fn handle_set(
43    handler_args: HandlerArgs,
44    name: Ident,
45    value: SetVariableValue,
46) -> Result<RwPgResponse> {
47    // Strip double and single quotes
48    let string_val = set_var_to_param_str(&value);
49
50    let mut status = ParameterStatus::default();
51
52    struct Reporter<'a> {
53        status: &'a mut ParameterStatus,
54    }
55
56    impl ConfigReporter for Reporter<'_> {
57        fn report_status(&mut self, key: &str, new_val: String) {
58            if key == "APPLICATION_NAME" {
59                self.status.application_name = Some(new_val);
60            }
61        }
62    }
63
64    // Currently store the config variable simply as String -> ConfigEntry(String).
65    // In future we can add converter/parser to make the API more robust.
66    // We remark that the name of session parameter is always case-insensitive.
67    handler_args.session.set_config_report(
68        &name.real_value().to_lowercase(),
69        string_val,
70        Reporter {
71            status: &mut status,
72        },
73    )?;
74
75    Ok(PgResponse::builder(StatementType::SET_VARIABLE)
76        .status(status)
77        .into())
78}
79
80pub(super) fn handle_set_time_zone(
81    handler_args: HandlerArgs,
82    value: SetTimeZoneValue,
83) -> Result<RwPgResponse> {
84    let tz_info = match value {
85        SetTimeZoneValue::Local => {
86            iana_time_zone::get_timezone().context("Failed to get local time zone")
87        }
88        SetTimeZoneValue::Default => Ok("UTC".to_owned()),
89        SetTimeZoneValue::Ident(ident) => Ok(ident.real_value()),
90        SetTimeZoneValue::Literal(Value::DoubleQuotedString(s))
91        | SetTimeZoneValue::Literal(Value::SingleQuotedString(s)) => Ok(s),
92        _ => Ok(value.to_string()),
93    }?;
94
95    handler_args.session.set_config("timezone", tz_info)?;
96
97    Ok(PgResponse::empty_result(StatementType::SET_VARIABLE))
98}
99
100pub(super) fn handle_show(handler_args: HandlerArgs, variable: Vec<Ident>) -> Result<RwPgResponse> {
101    // TODO: Verify that the name used in `show` command is indeed always case-insensitive.
102    let name = variable.iter().map(|e| e.real_value()).join(" ");
103    if name.eq_ignore_ascii_case("PARAMETERS") {
104        handle_show_system_params(handler_args)
105    } else if name.eq_ignore_ascii_case("ALL") {
106        handle_show_all(handler_args.clone())
107    } else {
108        let config_reader = handler_args.session.config();
109        Ok(PgResponse::builder(StatementType::SHOW_VARIABLE)
110            .rows([ShowVariableRow {
111                name: config_reader.get(&name)?,
112            }])
113            .into())
114    }
115}
116
117fn handle_show_all(handler_args: HandlerArgs) -> Result<RwPgResponse> {
118    let config_reader = handler_args.session.config();
119
120    let all_variables = config_reader.show_all();
121
122    let rows = all_variables.iter().map(|info| ShowVariableAllRow {
123        name: info.name.clone(),
124        setting: info.setting.clone(),
125        description: info.description.clone(),
126    });
127    Ok(PgResponse::builder(StatementType::SHOW_VARIABLE)
128        .rows(rows)
129        .into())
130}
131
132fn handle_show_system_params(handler_args: HandlerArgs) -> Result<RwPgResponse> {
133    let params = handler_args
134        .session
135        .env()
136        .system_params_manager()
137        .get_params()
138        .load();
139    let rows = params
140        .get_all()
141        .into_iter()
142        .map(|info| ShowVariableParamsRow {
143            name: info.name.into(),
144            value: info.value,
145            description: info.description.into(),
146            mutable: info.mutable,
147        });
148    Ok(PgResponse::builder(StatementType::SHOW_VARIABLE)
149        .rows(rows)
150        .into())
151}
152
153pub fn infer_show_variable(name: &str) -> Vec<PgFieldDescriptor> {
154    fields_to_descriptors(if name.eq_ignore_ascii_case("ALL") {
155        ShowVariableAllRow::fields()
156    } else if name.eq_ignore_ascii_case("PARAMETERS") {
157        ShowVariableParamsRow::fields()
158    } else {
159        ShowVariableRow::fields()
160    })
161}
162
163#[derive(Fields)]
164#[fields(style = "Title Case")]
165struct ShowVariableRow {
166    name: String,
167}
168
169#[derive(Fields)]
170#[fields(style = "Title Case")]
171struct ShowVariableAllRow {
172    name: String,
173    setting: String,
174    description: String,
175}
176
177#[derive(Fields)]
178#[fields(style = "Title Case")]
179struct ShowVariableParamsRow {
180    name: String,
181    value: String,
182    description: String,
183    mutable: bool,
184}