Skip to main content

sql/parsers/
utils.rs

1// Copyright 2023 Greptime Team
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 std::collections::HashMap;
16use std::sync::Arc;
17
18use chrono::{DateTime, Utc};
19use datafusion::config::ConfigOptions;
20use datafusion::error::Result as DfResult;
21use datafusion::execution::SessionStateBuilder;
22use datafusion::execution::context::SessionState;
23use datafusion::optimizer::simplify_expressions::ExprSimplifier;
24use datafusion_common::tree_node::{TreeNode, TreeNodeVisitor};
25use datafusion_common::{DFSchema, ScalarValue};
26use datafusion_expr::simplify::SimplifyContext;
27use datafusion_expr::{AggregateUDF, Expr, ScalarUDF, TableSource, WindowUDF};
28use datafusion_sql::TableReference;
29use datafusion_sql::planner::{ContextProvider, SqlToRel};
30use datatypes::arrow::datatypes::DataType;
31use datatypes::schema::{
32    COLUMN_FULLTEXT_OPT_KEY_ANALYZER, COLUMN_FULLTEXT_OPT_KEY_BACKEND,
33    COLUMN_FULLTEXT_OPT_KEY_CASE_SENSITIVE, COLUMN_FULLTEXT_OPT_KEY_FALSE_POSITIVE_RATE,
34    COLUMN_FULLTEXT_OPT_KEY_GRANULARITY, COLUMN_SKIPPING_INDEX_OPT_KEY_FALSE_POSITIVE_RATE,
35    COLUMN_SKIPPING_INDEX_OPT_KEY_GRANULARITY, COLUMN_SKIPPING_INDEX_OPT_KEY_TYPE,
36    COLUMN_VECTOR_INDEX_OPT_KEY_CONNECTIVITY, COLUMN_VECTOR_INDEX_OPT_KEY_ENGINE,
37    COLUMN_VECTOR_INDEX_OPT_KEY_EXPANSION_ADD, COLUMN_VECTOR_INDEX_OPT_KEY_EXPANSION_SEARCH,
38    COLUMN_VECTOR_INDEX_OPT_KEY_METRIC,
39};
40use snafu::{ResultExt, ensure};
41use sqlparser::dialect::Dialect;
42use sqlparser::keywords::Keyword;
43use sqlparser::parser::Parser;
44use table::requests::{SEMANTIC_PREFIX, validate_semantic_option, validate_table_option};
45
46use crate::error::{
47    ConvertToLogicalExpressionSnafu, InvalidSqlSnafu, InvalidTableOptionSnafu, ParseSqlValueSnafu,
48    Result, SimplificationSnafu, SyntaxSnafu,
49};
50use crate::parser::{ParseOptions, ParserContext};
51use crate::parsers::with_tql_parser::CteContent;
52use crate::statements::OptionMap;
53use crate::statements::query::Query;
54use crate::statements::statement::Statement;
55use crate::util::{OptionValue, parse_option_string};
56
57/// Check if the given SQL query is a TQL statement. Simple tql cte query is also considered as TQL statement.
58pub fn is_tql(dialect: &dyn Dialect, sql: &str) -> Result<bool> {
59    let stmts = ParserContext::create_with_dialect(sql, dialect, ParseOptions::default())?;
60
61    ensure!(
62        stmts.len() == 1,
63        InvalidSqlSnafu {
64            msg: format!("Expect only one statement, found {}", stmts.len())
65        }
66    );
67    let stmt = &stmts[0];
68    match stmt {
69        Statement::Tql(_) => Ok(true),
70        Statement::Query(query) => Ok(is_simple_tql_cte_query(query)),
71        _ => Ok(false),
72    }
73}
74
75pub(crate) fn is_simple_tql_cte_query(query: &Query) -> bool {
76    use crate::parser::ParserContext;
77
78    let Some(hybrid_cte) = &query.hybrid_cte else {
79        return false;
80    };
81
82    if !has_only_hybrid_tql_cte(query) {
83        return false;
84    }
85
86    let Some(cte) = hybrid_cte.cte_tables.first() else {
87        return false;
88    };
89    if hybrid_cte.cte_tables.len() != 1 || !matches!(cte.content, CteContent::Tql(_)) {
90        return false;
91    }
92
93    let Some(reference) = extract_simple_select_star_reference(query) else {
94        return false;
95    };
96
97    let reference = ParserContext::canonicalize_identifier(reference).value;
98    let cte_name = ParserContext::canonicalize_identifier(cte.name.clone()).value;
99    reference == cte_name
100}
101
102pub(crate) fn has_tql_cte(query: &Query) -> bool {
103    query.hybrid_cte.as_ref().is_some_and(|with| {
104        with.cte_tables
105            .iter()
106            .any(|cte| matches!(cte.content, CteContent::Tql(_)))
107    })
108}
109
110fn has_only_hybrid_tql_cte(query: &Query) -> bool {
111    query
112        .inner
113        .with
114        .as_ref()
115        .is_none_or(|with| with.cte_tables.is_empty())
116}
117
118fn extract_simple_select_star_reference(query: &Query) -> Option<sqlparser::ast::Ident> {
119    use sqlparser::ast::{SetExpr, TableFactor};
120
121    if !is_plain_query_root(&query.inner) {
122        return None;
123    }
124
125    let SetExpr::Select(select) = &*query.inner.body else {
126        return None;
127    };
128    if !is_plain_select(select) || !is_plain_wildcard_projection(select.projection.as_slice()) {
129        return None;
130    }
131
132    let [table_with_joins] = select.from.as_slice() else {
133        return None;
134    };
135    if !table_with_joins.joins.is_empty() {
136        return None;
137    }
138
139    let TableFactor::Table { name, .. } = &table_with_joins.relation else {
140        return None;
141    };
142    if name.0.len() != 1 {
143        return None;
144    }
145
146    name.0[0].as_ident().cloned()
147}
148
149fn is_plain_query_root(query: &sqlparser::ast::Query) -> bool {
150    query.order_by.is_none()
151        && query.limit_clause.is_none()
152        && query.fetch.is_none()
153        && query.locks.is_empty()
154        && query.for_clause.is_none()
155        && query.settings.is_none()
156        && query.format_clause.is_none()
157        && query.pipe_operators.is_empty()
158}
159
160fn is_plain_select(select: &sqlparser::ast::Select) -> bool {
161    use sqlparser::ast::GroupByExpr;
162
163    select.distinct.is_none()
164        && select.top.is_none()
165        && select.exclude.is_none()
166        && select.into.is_none()
167        && select.lateral_views.is_empty()
168        && select.prewhere.is_none()
169        && select.selection.is_none()
170        && matches!(select.group_by, GroupByExpr::Expressions(ref exprs, _) if exprs.is_empty())
171        && select.cluster_by.is_empty()
172        && select.distribute_by.is_empty()
173        && select.sort_by.is_empty()
174        && select.having.is_none()
175        && select.named_window.is_empty()
176        && select.qualify.is_none()
177        && select.value_table_mode.is_none()
178        && select.connect_by.is_empty()
179}
180
181fn is_plain_wildcard_projection(projection: &[sqlparser::ast::SelectItem]) -> bool {
182    use sqlparser::ast::SelectItem;
183
184    matches!(
185        projection,
186        [SelectItem::Wildcard(options)]
187            if options.opt_ilike.is_none()
188                && options.opt_exclude.is_none()
189                && options.opt_except.is_none()
190                && options.opt_replace.is_none()
191                && options.opt_rename.is_none()
192    )
193}
194
195/// Convert a parser expression to a scalar value. This function will try the
196/// best to resolve and reduce constants. Exprs like `1 + 1` or `now()` can be
197/// handled properly.
198///
199/// if `require_now_expr` is true, it will ensure that the expression contains a `now()` function.
200/// If the expression does not contain `now()`, it will return an error.
201///
202pub fn parser_expr_to_scalar_value_literal(
203    expr: sqlparser::ast::Expr,
204    require_now_expr: bool,
205) -> Result<ScalarValue> {
206    parser_expr_to_scalar_value_literal_at(expr, require_now_expr, None)
207}
208
209/// Same as [`parser_expr_to_scalar_value_literal`] but uses the provided
210/// `scheduled_time` for evaluating `now()`. If `scheduled_time` is
211/// `Some`, `now()` will be simplified to the given timestamp instead of
212/// the current wall-clock time.
213pub fn parser_expr_to_scalar_value_literal_at(
214    expr: sqlparser::ast::Expr,
215    require_now_expr: bool,
216    scheduled_time: Option<DateTime<Utc>>,
217) -> Result<ScalarValue> {
218    // 1. convert parser expr to logical expr
219    let empty_df_schema = DFSchema::empty();
220    let logical_expr = SqlToRel::new(&StubContextProvider::default())
221        .sql_to_expr(expr, &empty_df_schema, &mut Default::default())
222        .context(ConvertToLogicalExpressionSnafu)?;
223
224    struct FindNow {
225        found: bool,
226    }
227
228    impl TreeNodeVisitor<'_> for FindNow {
229        type Node = Expr;
230        fn f_down(
231            &mut self,
232            node: &Self::Node,
233        ) -> DfResult<datafusion_common::tree_node::TreeNodeRecursion> {
234            if let Expr::ScalarFunction(func) = node
235                && func.name().to_lowercase() == "now"
236            {
237                if !func.args.is_empty() {
238                    return Err(datafusion_common::DataFusionError::Plan(
239                        "now() function should not have arguments".to_string(),
240                    ));
241                }
242                self.found = true;
243                return Ok(datafusion_common::tree_node::TreeNodeRecursion::Stop);
244            }
245            Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue)
246        }
247    }
248
249    if require_now_expr {
250        let have_now = {
251            let mut visitor = FindNow { found: false };
252            logical_expr.visit(&mut visitor).unwrap();
253            visitor.found
254        };
255        if !have_now {
256            return ParseSqlValueSnafu {
257                msg: format!(
258                    "expected now() expression, but not found in {}",
259                    logical_expr
260                ),
261            }
262            .fail();
263        }
264    }
265
266    // 2. simplify logical expr — use scheduled time if provided, else wall-clock
267    let info = match scheduled_time {
268        Some(dt) => SimplifyContext::default().with_query_execution_start_time(Some(dt)),
269        None => SimplifyContext::default().with_current_time(),
270    };
271    let simplifier = ExprSimplifier::new(info);
272
273    // Coerce the logical expression so simplifier can handle it correctly. This is necessary for const eval with possible type mismatch. i.e.: `now() - now() + '15s'::interval` which is `TimestampNanosecond - TimestampNanosecond + IntervalMonthDayNano`.
274    let logical_expr = simplifier
275        .coerce(logical_expr, &empty_df_schema)
276        .context(SimplificationSnafu)?;
277
278    let simplified_expr = simplifier
279        .simplify(logical_expr)
280        .context(SimplificationSnafu)?;
281
282    if let datafusion::logical_expr::Expr::Literal(lit, _) = simplified_expr {
283        Ok(lit)
284    } else {
285        // Err(ParseSqlValue)
286        ParseSqlValueSnafu {
287            msg: format!("expected literal value, but found {:?}", simplified_expr),
288        }
289        .fail()
290    }
291}
292
293/// Helper struct for [`parser_expr_to_scalar_value`].
294struct StubContextProvider {
295    state: SessionState,
296}
297
298impl Default for StubContextProvider {
299    fn default() -> Self {
300        Self {
301            state: SessionStateBuilder::new()
302                .with_config(Default::default())
303                .with_runtime_env(Default::default())
304                .with_default_features()
305                .build(),
306        }
307    }
308}
309
310impl ContextProvider for StubContextProvider {
311    fn get_table_source(&self, _name: TableReference) -> DfResult<Arc<dyn TableSource>> {
312        unimplemented!()
313    }
314
315    fn get_function_meta(&self, name: &str) -> Option<Arc<ScalarUDF>> {
316        self.state.scalar_functions().get(name).cloned()
317    }
318
319    fn get_aggregate_meta(&self, name: &str) -> Option<Arc<AggregateUDF>> {
320        self.state.aggregate_functions().get(name).cloned()
321    }
322
323    fn get_window_meta(&self, _name: &str) -> Option<Arc<WindowUDF>> {
324        unimplemented!()
325    }
326
327    fn get_variable_type(&self, _variable_names: &[String]) -> Option<DataType> {
328        unimplemented!()
329    }
330
331    fn options(&self) -> &ConfigOptions {
332        self.state.config_options()
333    }
334
335    fn udf_names(&self) -> Vec<String> {
336        self.state.scalar_functions().keys().cloned().collect()
337    }
338
339    fn udaf_names(&self) -> Vec<String> {
340        self.state.aggregate_functions().keys().cloned().collect()
341    }
342
343    fn udwf_names(&self) -> Vec<String> {
344        self.state.window_functions().keys().cloned().collect()
345    }
346}
347
348pub fn validate_column_fulltext_create_option(key: &str) -> bool {
349    [
350        COLUMN_FULLTEXT_OPT_KEY_ANALYZER,
351        COLUMN_FULLTEXT_OPT_KEY_CASE_SENSITIVE,
352        COLUMN_FULLTEXT_OPT_KEY_BACKEND,
353        COLUMN_FULLTEXT_OPT_KEY_GRANULARITY,
354        COLUMN_FULLTEXT_OPT_KEY_FALSE_POSITIVE_RATE,
355    ]
356    .contains(&key)
357}
358
359pub fn validate_column_skipping_index_create_option(key: &str) -> bool {
360    [
361        COLUMN_SKIPPING_INDEX_OPT_KEY_GRANULARITY,
362        COLUMN_SKIPPING_INDEX_OPT_KEY_TYPE,
363        COLUMN_SKIPPING_INDEX_OPT_KEY_FALSE_POSITIVE_RATE,
364    ]
365    .contains(&key)
366}
367
368pub fn validate_column_vector_index_create_option(key: &str) -> bool {
369    [
370        COLUMN_VECTOR_INDEX_OPT_KEY_ENGINE,
371        COLUMN_VECTOR_INDEX_OPT_KEY_METRIC,
372        COLUMN_VECTOR_INDEX_OPT_KEY_CONNECTIVITY,
373        COLUMN_VECTOR_INDEX_OPT_KEY_EXPANSION_ADD,
374        COLUMN_VECTOR_INDEX_OPT_KEY_EXPANSION_SEARCH,
375    ]
376    .contains(&key)
377}
378
379/// Convert an [`IntervalMonthDayNano`] to a [`Duration`].
380#[cfg(feature = "enterprise")]
381pub fn convert_month_day_nano_to_duration(
382    interval: arrow_buffer::IntervalMonthDayNano,
383) -> Result<std::time::Duration> {
384    let months: i64 = interval.months.into();
385    let days: i64 = interval.days.into();
386    let months_in_seconds: i64 = months * 60 * 60 * 24 * 3044 / 1000;
387    let days_in_seconds: i64 = days * 60 * 60 * 24;
388    let seconds_from_nanos = interval.nanoseconds / 1_000_000_000;
389    let total_seconds = months_in_seconds + days_in_seconds + seconds_from_nanos;
390
391    let mut nanos_remainder = interval.nanoseconds % 1_000_000_000;
392    let mut adjusted_seconds = total_seconds;
393
394    if nanos_remainder < 0 {
395        nanos_remainder += 1_000_000_000;
396        adjusted_seconds -= 1;
397    }
398
399    snafu::ensure!(
400        adjusted_seconds >= 0,
401        crate::error::InvalidIntervalSnafu {
402            reason: "must be a positive interval",
403        }
404    );
405
406    // Cast safety: `adjusted_seconds` is guaranteed to be non-negative before.
407    let adjusted_seconds = adjusted_seconds as u64;
408    // Cast safety: `nanos_remainder` is smaller than 1_000_000_000 which
409    // is checked above.
410    let nanos_remainder = nanos_remainder as u32;
411
412    Ok(std::time::Duration::new(adjusted_seconds, nanos_remainder))
413}
414
415pub fn parse_with_options(parser: &mut Parser) -> Result<OptionMap> {
416    let options = parser
417        .parse_options(Keyword::WITH)
418        .context(SyntaxSnafu)?
419        .into_iter()
420        .map(parse_option_string)
421        .collect::<Result<HashMap<String, OptionValue>>>()?;
422    for (key, value) in &options {
423        if key.starts_with(SEMANTIC_PREFIX) {
424            // Semantic keys are whitelisted and value-checked against their domain,
425            // so a user cannot set an unknown key or an out-of-range value.
426            let value = value.as_string().unwrap_or_default();
427            ensure!(
428                validate_semantic_option(key, value),
429                InvalidTableOptionSnafu { key }
430            );
431        } else {
432            ensure!(validate_table_option(key), InvalidTableOptionSnafu { key });
433        }
434    }
435    Ok(OptionMap::new(options))
436}
437
438#[cfg(test)]
439mod tests {
440    use chrono::DateTime;
441    use datafusion::functions::datetime::expr_fn::now;
442    use datafusion_expr::lit;
443    use datatypes::arrow::datatypes::TimestampNanosecondType;
444
445    use super::*;
446    use crate::dialect::GreptimeDbDialect;
447    use crate::parser::{ParseOptions, ParserContext};
448    use crate::statements::statement::Statement;
449
450    #[test]
451    fn test_is_tql() {
452        let dialect = GreptimeDbDialect {};
453
454        assert!(is_tql(&dialect, "TQL EVAL (0, 10, '1s') cpu_usage_total").unwrap());
455        assert!(!is_tql(&dialect, "SELECT 1").unwrap());
456
457        let tql_cte = r#"
458WITH tql_cte(ts, val) AS (
459    TQL EVAL (0, 15, '5s') metric
460)
461SELECT * FROM tql_cte
462"#;
463        assert!(is_tql(&dialect, tql_cte).unwrap());
464
465        let rename_cols = r#"
466WITH tql (the_timestamp, the_value) AS (
467    TQL EVAL (0, 40, '10s') metric
468)
469SELECT * FROM tql
470"#;
471        assert!(is_tql(&dialect, rename_cols).unwrap());
472        let stmts =
473            ParserContext::create_with_dialect(rename_cols, &dialect, ParseOptions::default())
474                .unwrap();
475        let Statement::Query(q) = &stmts[0] else {
476            panic!("Expected Query statement");
477        };
478        let hybrid = q.hybrid_cte.as_ref().expect("Expected hybrid cte");
479        assert_eq!(hybrid.cte_tables.len(), 1);
480        assert_eq!(hybrid.cte_tables[0].columns.len(), 2);
481        assert_eq!(hybrid.cte_tables[0].columns[0].to_string(), "the_timestamp");
482        assert_eq!(hybrid.cte_tables[0].columns[1].to_string(), "the_value");
483
484        let sql_cte = r#"
485WITH cte AS (SELECT 1)
486SELECT * FROM cte
487"#;
488        assert!(!is_tql(&dialect, sql_cte).unwrap());
489
490        let extra_sql_cte = r#"
491WITH sql_cte AS (SELECT 1), tql_cte(ts, val) AS (
492    TQL EVAL (0, 15, '5s') metric
493)
494SELECT * FROM tql_cte
495"#;
496        assert!(!is_tql(&dialect, extra_sql_cte).unwrap());
497
498        let not_select_star = r#"
499WITH tql_cte(ts, val) AS (
500    TQL EVAL (0, 15, '5s') metric
501)
502SELECT ts FROM tql_cte
503"#;
504        assert!(!is_tql(&dialect, not_select_star).unwrap());
505
506        let with_filter = r#"
507WITH tql_cte(ts, val) AS (
508    TQL EVAL (0, 15, '5s') metric
509)
510SELECT * FROM tql_cte WHERE ts > 0
511"#;
512        assert!(!is_tql(&dialect, with_filter).unwrap());
513    }
514
515    /// Keep this test to make sure we are using datafusion's `ExprSimplifier` correctly.
516    #[test]
517    fn test_simplifier() {
518        let now_time = DateTime::from_timestamp(61, 0).unwrap();
519        let lit_now = lit(ScalarValue::new_timestamp::<TimestampNanosecondType>(
520            now_time.timestamp_nanos_opt(),
521            None,
522        ));
523        let testcases = vec![
524            (now(), lit_now),
525            (now() - now(), lit(ScalarValue::DurationNanosecond(Some(0)))),
526            (
527                now() + lit(ScalarValue::new_interval_dt(0, 1500)),
528                lit(ScalarValue::new_timestamp::<TimestampNanosecondType>(
529                    Some(62500000000),
530                    None,
531                )),
532            ),
533            (
534                now() - (now() + lit(ScalarValue::new_interval_dt(0, 1500))),
535                lit(ScalarValue::DurationNanosecond(Some(-1500000000))),
536            ),
537            // this one failed if type is not coerced
538            (
539                now() - now() + lit(ScalarValue::new_interval_dt(0, 1500)),
540                lit(ScalarValue::new_interval_mdn(0, 0, 1500000000)),
541            ),
542            (
543                lit(ScalarValue::new_interval_mdn(
544                    0,
545                    0,
546                    61 * 86400 * 1_000_000_000,
547                )),
548                lit(ScalarValue::new_interval_mdn(
549                    0,
550                    0,
551                    61 * 86400 * 1_000_000_000,
552                )),
553            ),
554        ];
555
556        let info = SimplifyContext::default().with_query_execution_start_time(Some(now_time));
557        let simplifier = ExprSimplifier::new(info);
558        for (expr, expected) in testcases {
559            let expr_name = expr.schema_name().to_string();
560            let expr = simplifier.coerce(expr, &DFSchema::empty()).unwrap();
561
562            let simplified_expr = simplifier.simplify(expr).unwrap();
563            assert_eq!(
564                simplified_expr, expected,
565                "Failed to simplify expression: {expr_name}"
566            );
567        }
568    }
569}