sql/statements/
set_variables.rs1use std::fmt::Display;
16
17use serde::Serialize;
18use sqlparser::ast::{Expr, ObjectName, ObjectNamePart, Value, ValueWithSpan};
19use sqlparser_derive::{Visit, VisitMut};
20
21#[derive(Debug, Clone, PartialEq, Eq, Visit, VisitMut, Serialize)]
23pub struct SetVariables {
24 pub variable: ObjectName,
25 pub value: Vec<Expr>,
26}
27
28impl SetVariables {
29 pub fn search_path(&self) -> Option<Vec<String>> {
31 let [ObjectNamePart::Identifier(variable)] = self.variable.0.as_slice() else {
32 return None;
33 };
34 if !variable.value.eq_ignore_ascii_case("search_path") {
35 return None;
36 }
37
38 if let [Expr::Identifier(value)] = self.value.as_slice()
39 && value.quote_style.is_none()
40 && value.value.eq_ignore_ascii_case("default")
41 {
42 return Some(vec!["$user".to_string(), "public".to_string()]);
43 }
44
45 self.value
46 .iter()
47 .map(|value| match value {
48 Expr::Value(ValueWithSpan {
49 value: Value::SingleQuotedString(value) | Value::DoubleQuotedString(value),
50 ..
51 }) => Some(value.clone()),
52 Expr::Identifier(value) if value.quote_style.is_none() => {
53 Some(value.value.to_lowercase())
54 }
55 Expr::Identifier(value) => Some(value.value.clone()),
56 _ => None,
57 })
58 .collect()
59 }
60}
61
62impl Display for SetVariables {
63 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64 let variable = &self.variable;
65 let value = &self
66 .value
67 .iter()
68 .map(|expr| format!("{}", expr))
69 .collect::<Vec<_>>()
70 .join(", ");
71
72 write!(f, r#"SET {variable} = {value}"#)
73 }
74}
75
76#[cfg(test)]
77mod tests {
78 use std::assert_matches;
79
80 use crate::dialect::GreptimeDbDialect;
81 use crate::parser::{ParseOptions, ParserContext};
82 use crate::statements::statement::Statement;
83
84 #[test]
85 fn test_display_show_variables() {
86 let sql = r"set delayed_insert_timeout=300;";
87 let stmts =
88 ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
89 .unwrap();
90 assert_eq!(1, stmts.len());
91 assert_matches!(&stmts[0], Statement::SetVariables { .. });
92
93 match &stmts[0] {
94 Statement::SetVariables(set) => {
95 let new_sql = format!("\n{}", set);
96 assert_eq!(
97 r#"
98SET delayed_insert_timeout = 300"#,
99 &new_sql
100 );
101 }
102 _ => {
103 unreachable!();
104 }
105 }
106 }
107
108 #[test]
109 fn test_search_path() {
110 for (sql, expected) in [
111 ("SET search_path TO public", Some(vec!["public"])),
112 ("SET search_path TO DEFAULT", Some(vec!["$user", "public"])),
113 (r#"SET search_path TO "default""#, Some(vec!["default"])),
114 ("SET search_path TO 'default'", Some(vec!["default"])),
115 ("SET SEARCH_PATH TO 'private'", Some(vec!["private"])),
116 ("SET search_path TO \"quoted\"", Some(vec!["quoted"])),
117 ("SET \"search_path\" TO private", Some(vec!["private"])),
118 ("SET timezone TO 'UTC'", None),
119 (
120 r#"SET search_path TO "$user", MISSING, "Mixed", 'a,b'"#,
121 Some(vec!["$user", "missing", "Mixed", "a,b"]),
122 ),
123 ("SET search_path TO ''", Some(vec![""])),
124 ("SET search_path TO public, 42", None),
125 ] {
126 let statements = ParserContext::create_with_dialect(
127 sql,
128 &GreptimeDbDialect {},
129 ParseOptions::default(),
130 )
131 .unwrap();
132 let [Statement::SetVariables(set)] = statements.as_slice() else {
133 unreachable!()
134 };
135 assert_eq!(
136 expected.map(|v| v.into_iter().map(str::to_owned).collect::<Vec<_>>()),
137 set.search_path()
138 );
139 }
140 }
141}