Skip to main content

query/range_select/
plan_rewrite.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::{BTreeSet, HashSet};
16use std::sync::Arc;
17use std::time::Duration;
18
19use arrow_schema::DataType;
20use catalog::table_source::DfTableSourceProvider;
21use chrono::{DateTime, Utc};
22use common_function::aggrs::aggr_wrapper::get_aggr_func;
23use common_time::interval::{MS_PER_DAY, NANOS_PER_MILLI};
24use common_time::timestamp::TimeUnit;
25use common_time::{IntervalDayTime, IntervalMonthDayNano, IntervalYearMonth, Timestamp, Timezone};
26use datafusion::datasource::DefaultTableSource;
27use datafusion::prelude::Column;
28use datafusion::scalar::ScalarValue;
29use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRecursion, TreeNodeRewriter};
30use datafusion_common::{DFSchema, DataFusionError, Result as DFResult};
31use datafusion_expr::expr::WildcardOptions;
32use datafusion_expr::simplify::SimplifyContext;
33use datafusion_expr::utils::expr_to_columns;
34use datafusion_expr::{
35    Aggregate, Analyze, Cast, Distinct, DistinctOn, Explain, Expr, ExprSchemable, Extension,
36    Literal, LogicalPlan, LogicalPlanBuilder, Projection,
37};
38use datafusion_optimizer::simplify_expressions::ExprSimplifier;
39use datatypes::prelude::ConcreteDataType;
40use datatypes::schema::TIME_INDEX_KEY;
41use promql_parser::util::parse_duration;
42use session::context::QueryContextRef;
43use snafu::{OptionExt, ResultExt, ensure};
44use table::table::adapter::DfTableProviderAdapter;
45
46use crate::error::{
47    CatalogSnafu, RangeQuerySnafu, Result, TimeIndexNotFoundSnafu, UnknownTableSnafu,
48};
49use crate::plan::ExtractExpr;
50use crate::range_select::plan::{Fill, RangeFn, RangeSelect};
51
52/// `RangeExprRewriter` will recursively search certain `Expr`, find all `range_fn` scalar udf contained in `Expr`,
53/// and collect the information required by the RangeSelect query,
54/// and finally modify the `range_fn` scalar udf to an ordinary column field.
55pub struct RangeExprRewriter<'a> {
56    input_plan: &'a Arc<LogicalPlan>,
57    align: Duration,
58    align_to: i64,
59    by: Vec<Expr>,
60    /// Use `BTreeSet` to avoid in case like `avg(a) RANGE '5m' + avg(a) RANGE '5m'`, duplicate range expr `avg(a) RANGE '5m'` be calculate twice
61    range_fn: BTreeSet<RangeFn>,
62    sub_aggr: &'a Aggregate,
63    query_ctx: &'a QueryContextRef,
64}
65
66impl RangeExprRewriter<'_> {
67    pub fn get_range_expr(&self, args: &[Expr], i: usize) -> DFResult<Expr> {
68        match args.get(i) {
69            Some(Expr::Column(column)) => {
70                let index = self.sub_aggr.schema.index_of_column(column)?;
71                let len = self.sub_aggr.group_expr.len();
72                self.sub_aggr
73                    .aggr_expr
74                    .get(index - len)
75                    .cloned()
76                    .ok_or(DataFusionError::Plan(
77                        "Range expr not found in underlying Aggregate Plan".into(),
78                    ))
79            }
80            Some(Expr::Alias(alias)) => {
81                self.get_range_expr(std::slice::from_ref(alias.expr.as_ref()), 0)
82            }
83            other => Err(dispose_parse_error(other)),
84        }
85    }
86}
87
88#[inline]
89fn dispose_parse_error(expr: Option<&Expr>) -> DataFusionError {
90    DataFusionError::Plan(
91        expr.map(|x| {
92            format!(
93                "Illegal argument `{}` in range select query",
94                x.schema_name()
95            )
96        })
97        .unwrap_or("Missing argument in range select query".into()),
98    )
99}
100
101fn parse_str_expr(args: &[Expr], i: usize) -> DFResult<&str> {
102    match args.get(i) {
103        Some(Expr::Literal(ScalarValue::Utf8(Some(str)), _)) => Ok(str.as_str()),
104        other => Err(dispose_parse_error(other)),
105    }
106}
107
108fn parse_expr_to_string(args: &[Expr], i: usize) -> DFResult<String> {
109    match args.get(i) {
110        Some(Expr::Literal(ScalarValue::Utf8(Some(str)), _)) => Ok(str.clone()),
111        Some(expr) => Ok(expr.schema_name().to_string()),
112        None => Err(dispose_parse_error(None)),
113    }
114}
115
116fn time_millisecond_overflow(expr: &Expr) -> DataFusionError {
117    DataFusionError::Plan(format!(
118        "overflow converting `{}` to milliseconds in range select query",
119        expr.schema_name()
120    ))
121}
122
123fn seconds_to_millisecond(seconds: i64, expr: &Expr) -> DFResult<i64> {
124    seconds
125        .checked_mul(1_000)
126        .ok_or_else(|| time_millisecond_overflow(expr))
127}
128
129/// Parse a duration expr:
130/// 1. duration string (e.g. `'1h'`)
131/// 2. Interval expr (e.g. `INTERVAL '1 year 3 hours 20 minutes'`)
132/// 3. An interval expr can be evaluated at the logical plan stage (e.g. `INTERVAL '2' day - INTERVAL '1' day`)
133fn parse_duration_expr(args: &[Expr], i: usize) -> DFResult<Duration> {
134    match args.get(i) {
135        Some(Expr::Literal(ScalarValue::Utf8(Some(str)), _)) => {
136            parse_duration(str).map_err(DataFusionError::Plan)
137        }
138        Some(expr) => {
139            let ms = evaluate_expr_to_millisecond(args, i, true, None)?;
140            if ms <= 0 {
141                return Err(dispose_parse_error(Some(expr)));
142            }
143            Ok(Duration::from_millis(ms as u64))
144        }
145        None => Err(dispose_parse_error(None)),
146    }
147}
148
149/// Evaluate a time calculation expr, case like:
150/// 1. `INTERVAL '1' day + INTERVAL '1 year 2 hours 3 minutes'`
151/// 2. `now() - INTERVAL '1' day` (when `interval_only==false`)
152///
153/// Output a millisecond timestamp
154///
155/// if `interval_only==true`, only accept expr with all interval type (case 2 will return a error)
156fn evaluate_expr_to_millisecond(
157    args: &[Expr],
158    i: usize,
159    interval_only: bool,
160    scheduled_time: Option<DateTime<Utc>>,
161) -> DFResult<i64> {
162    let Some(expr) = args.get(i) else {
163        return Err(dispose_parse_error(None));
164    };
165    if interval_only && !interval_only_in_expr(expr) {
166        return Err(dispose_parse_error(Some(expr)));
167    }
168    let info = match scheduled_time {
169        Some(dt) => SimplifyContext::builder()
170            .with_query_execution_start_time(Some(dt))
171            .build(),
172        None => SimplifyContext::builder().with_current_time().build(),
173    };
174    let simplify_expr = ExprSimplifier::new(info).simplify(expr.clone())?;
175    match simplify_expr {
176        Expr::Literal(ScalarValue::TimestampNanosecond(ts_nanos, _), _) => {
177            ts_nanos.map(|v| v.div_euclid(NANOS_PER_MILLI))
178        }
179        Expr::Literal(ScalarValue::DurationNanosecond(ts_nanos), _) => {
180            ts_nanos.map(|v| v / NANOS_PER_MILLI)
181        }
182        Expr::Literal(ScalarValue::TimestampMicrosecond(ts_micros, _), _) => {
183            ts_micros.map(|v| v.div_euclid(1_000))
184        }
185        Expr::Literal(ScalarValue::DurationMicrosecond(ts_micros), _) => {
186            ts_micros.map(|v| v / 1_000)
187        }
188        Expr::Literal(ScalarValue::TimestampMillisecond(ts_millis, _), _)
189        | Expr::Literal(ScalarValue::DurationMillisecond(ts_millis), _) => ts_millis,
190        Expr::Literal(ScalarValue::TimestampSecond(ts_secs, _), _)
191        | Expr::Literal(ScalarValue::DurationSecond(ts_secs), _) => ts_secs
192            .map(|v| seconds_to_millisecond(v, expr))
193            .transpose()?,
194        // We don't support interval with months as days in a month is unclear.
195        Expr::Literal(ScalarValue::IntervalYearMonth(interval), _) => interval
196            .map(|v| {
197                let interval = IntervalYearMonth::from_i32(v);
198                if interval.months != 0 {
199                    return Err(DataFusionError::Plan(format!(
200                        "Year or month interval is not allowed in range query: {}",
201                        expr.schema_name()
202                    )));
203                }
204
205                Ok(0)
206            })
207            .transpose()?,
208        Expr::Literal(ScalarValue::IntervalDayTime(interval), _) => interval.map(|v| {
209            let interval = IntervalDayTime::from(v);
210            interval.as_millis()
211        }),
212        Expr::Literal(ScalarValue::IntervalMonthDayNano(interval), _) => interval
213            .map(|v| {
214                let interval = IntervalMonthDayNano::from(v);
215                if interval.months != 0 {
216                    return Err(DataFusionError::Plan(format!(
217                        "Year or month interval is not allowed in range query: {}",
218                        expr.schema_name()
219                    )));
220                }
221
222                let day_millis = (interval.days as i64)
223                    .checked_mul(MS_PER_DAY)
224                    .ok_or_else(|| time_millisecond_overflow(expr))?;
225                let nanosecond_millis = interval.nanoseconds.div_euclid(NANOS_PER_MILLI);
226                day_millis
227                    .checked_add(nanosecond_millis)
228                    .ok_or_else(|| time_millisecond_overflow(expr))
229            })
230            .transpose()?,
231        _ => None,
232    }
233    .ok_or_else(|| {
234        DataFusionError::Plan(format!(
235            "{} is not a expr can be evaluate and use in range query",
236            expr.schema_name()
237        ))
238    })
239}
240
241/// Parse the `align to` clause and return a UTC timestamp with unit of millisecond,
242/// which is used as the basis for dividing time slot during the align operation.
243/// 1. NOW: align to current execute time
244/// 2. Timestamp string: align to specific timestamp
245/// 3. An expr can be evaluated at the logical plan stage (e.g. `now() - INTERVAL '1' day`)
246/// 4. leave empty (as Default Option): align to unix epoch 0 (timezone aware)
247fn parse_align_to(
248    args: &[Expr],
249    i: usize,
250    timezone: Option<&Timezone>,
251    scheduled_time: Option<DateTime<Utc>>,
252) -> DFResult<i64> {
253    let Ok(s) = parse_str_expr(args, i) else {
254        return evaluate_expr_to_millisecond(args, i, false, scheduled_time);
255    };
256    let upper = s.to_uppercase();
257    match upper.as_str() {
258        "NOW" => {
259            return Ok(scheduled_time
260                .map(|dt| dt.timestamp_millis())
261                .unwrap_or_else(|| Timestamp::current_millis().value()));
262        }
263        // default align to unix epoch 0 (timezone aware)
264        "" => return Ok(timezone.map(|tz| tz.local_minus_utc() * 1000).unwrap_or(0)),
265        _ => (),
266    }
267
268    Timestamp::from_str(s, timezone)
269        .map_err(|e| {
270            DataFusionError::Plan(format!(
271                "Illegal `align to` argument `{}` in range select query, can't be parse as NOW/CALENDAR/Timestamp, error: {}",
272                s, e
273            ))
274        })?.convert_to(TimeUnit::Millisecond).map(|x|x.value()).ok_or(DataFusionError::Plan(format!(
275            "Illegal `align to` argument `{}` in range select query, can't be convert to a valid Timestamp",
276            s
277        ))
278        )
279}
280
281fn parse_expr_list(args: &[Expr], start: usize, len: usize) -> DFResult<Vec<Expr>> {
282    let mut outs = Vec::with_capacity(len);
283    for i in start..start + len {
284        outs.push(match &args.get(i) {
285            Some(
286                Expr::Column(_)
287                | Expr::Literal(_, _)
288                | Expr::BinaryExpr(_)
289                | Expr::ScalarFunction(_),
290            ) => args[i].clone(),
291            Some(Expr::Alias(alias)) if matches!(*alias.expr, Expr::ScalarFunction(_)) => {
292                args[i].clone()
293            }
294            other => {
295                return Err(dispose_parse_error(*other));
296            }
297        });
298    }
299    Ok(outs)
300}
301
302macro_rules! inconsistent_check {
303    ($self: ident.$name: ident, $cond: expr) => {
304        if $cond && $self.$name != $name {
305            return Err(DataFusionError::Plan(
306                concat!(
307                    "Inconsistent ",
308                    stringify!($name),
309                    " given in Range Function Rewrite"
310                )
311                .into(),
312            ));
313        } else {
314            $self.$name = $name;
315        }
316    };
317}
318
319impl TreeNodeRewriter for RangeExprRewriter<'_> {
320    type Node = Expr;
321
322    fn f_down(&mut self, node: Expr) -> DFResult<Transformed<Expr>> {
323        if let Expr::ScalarFunction(func) = &node
324            && func.name() == "range_fn"
325        {
326            // `range_fn(func, range, fill, byc, [byv], align, to)`
327            // `[byv]` are variadic arguments, byc indicate the length of arguments
328            let range_expr = self.get_range_expr(&func.args, 0)?;
329            let range = parse_duration_expr(&func.args, 1)?;
330            let byc = str::parse::<usize>(parse_str_expr(&func.args, 3)?)
331                .map_err(|e| DataFusionError::Plan(e.to_string()))?;
332            let by = parse_expr_list(&func.args, 4, byc)?;
333            let align = parse_duration_expr(&func.args, byc + 4)?;
334            let scheduled_time =
335                crate::options::parse_scheduled_time_datetime(&self.query_ctx.extensions())
336                    .map_err(|err| DataFusionError::Plan(err.to_string()))?;
337            let align_to = parse_align_to(
338                &func.args,
339                byc + 5,
340                Some(&self.query_ctx.timezone()),
341                scheduled_time,
342            )?;
343            let mut data_type = range_expr.get_type(self.input_plan.schema())?;
344            let mut need_cast = false;
345            let fill = Fill::try_from_str(parse_str_expr(&func.args, 2)?, &data_type)?;
346            if matches!(fill, Some(Fill::Linear)) && data_type.is_integer() {
347                data_type = DataType::Float64;
348                need_cast = true;
349            }
350            inconsistent_check!(self.by, !self.by.is_empty());
351            inconsistent_check!(self.align, self.align != Duration::default());
352            inconsistent_check!(self.align_to, self.align_to != 0);
353            let range_fn = RangeFn {
354                name: if let Some(fill) = &fill {
355                    format!(
356                        "{} RANGE {} FILL {}",
357                        range_expr.schema_name(),
358                        parse_expr_to_string(&func.args, 1)?,
359                        fill
360                    )
361                } else {
362                    format!(
363                        "{} RANGE {}",
364                        range_expr.schema_name(),
365                        parse_expr_to_string(&func.args, 1)?,
366                    )
367                },
368                data_type,
369                expr: range_expr,
370                range,
371                fill,
372                need_cast,
373            };
374            let alias = Expr::Column(Column::from_name(range_fn.name.clone()));
375            self.range_fn.insert(range_fn);
376            return Ok(Transformed::yes(alias));
377        }
378        Ok(Transformed::no(node))
379    }
380}
381
382/// In order to implement RangeSelect query like `avg(field_0) RANGE '5m' FILL NULL`,
383/// All RangeSelect query items are converted into udf scalar function in sql parse stage, with format like `range_fn(avg(field_0), .....)`.
384/// `range_fn` contains all the parameters we need to execute RangeSelect.
385/// In order to correctly execute the query process of range select, we need to modify the query plan generated by datafusion.
386/// We need to recursively find the entire LogicalPlan, and find all `range_fn` scalar udf contained in the project plan,
387/// collecting info we need to generate RangeSelect Query LogicalPlan and rewrite th original LogicalPlan.
388pub struct RangePlanRewriter {
389    table_provider: DfTableSourceProvider,
390    query_ctx: QueryContextRef,
391}
392
393impl RangePlanRewriter {
394    pub fn new(table_provider: DfTableSourceProvider, query_ctx: QueryContextRef) -> Self {
395        Self {
396            table_provider,
397            query_ctx,
398        }
399    }
400
401    pub async fn rewrite(&mut self, plan: LogicalPlan) -> Result<LogicalPlan> {
402        match self.rewrite_logical_plan(&plan).await? {
403            Some(new_plan) => Ok(new_plan),
404            None => Ok(plan),
405        }
406    }
407
408    /// Rewrites `plan` bottom-up and returns `None` if nothing changed.
409    ///
410    /// The walk uses explicit stacks rather than recursion because plans such as long
411    /// `UNION ALL` chains can be deep enough to overflow the thread stack.
412    async fn rewrite_logical_plan(&mut self, plan: &LogicalPlan) -> Result<Option<LogicalPlan>> {
413        let mut pending = vec![plan];
414        let mut nodes = vec![];
415        while let Some(node) = pending.pop() {
416            let inputs = node.inputs();
417            pending.extend(inputs.iter().copied());
418            nodes.push((node, inputs));
419        }
420        // In reverse, `nodes` lists every node after all of its inputs, which come in order,
421        // so the results of a node's inputs are the last entries of `rewritten`.
422        let mut rewritten = vec![];
423        for (node, inputs) in nodes.into_iter().rev() {
424            let new_inputs = rewritten.split_off(rewritten.len() - inputs.len());
425            rewritten.push(self.rewrite_plan_node(node, inputs, new_inputs).await?);
426        }
427        Ok(rewritten.pop().flatten())
428    }
429
430    /// Rewrites a single node, given the rewrite results of its `inputs`.
431    async fn rewrite_plan_node(
432        &mut self,
433        plan: &LogicalPlan,
434        inputs: Vec<&LogicalPlan>,
435        new_inputs: Vec<Option<LogicalPlan>>,
436    ) -> Result<Option<LogicalPlan>> {
437        match plan {
438            LogicalPlan::Projection(Projection { expr, input, .. })
439                if have_range_in_exprs(expr) =>
440            {
441                let (aggr_plan, input) = if let LogicalPlan::Aggregate(aggr) = input.as_ref() {
442                    // Expr like `rate(max(a) RANGE '6m') RANGE '6m'` have legal syntax but illegal semantic.
443                    if have_range_in_exprs(&aggr.aggr_expr) {
444                        return RangeQuerySnafu {
445                            msg: "Nest Range Query is not allowed",
446                        }
447                        .fail();
448                    }
449                    (aggr, aggr.input.clone())
450                } else {
451                    return RangeQuerySnafu {
452                        msg: "Window functions is not allowed in Range Query",
453                    }
454                    .fail();
455                };
456                let query_ctx = self.query_ctx.clone();
457                let mut range_rewriter = RangeExprRewriter {
458                    input_plan: &input,
459                    align: Duration::default(),
460                    align_to: 0,
461                    by: vec![],
462                    range_fn: BTreeSet::new(),
463                    sub_aggr: aggr_plan,
464                    query_ctx: &query_ctx,
465                };
466                let new_expr = expr
467                    .iter()
468                    .map(|expr| expr.clone().rewrite(&mut range_rewriter).map(|x| x.data))
469                    .collect::<DFResult<Vec<_>>>()?;
470                let need_default_by = range_rewriter.by.is_empty();
471                let (time_index, default_by) =
472                    self.get_index_by(input.schema(), need_default_by).await?;
473                if need_default_by {
474                    range_rewriter.by = default_by;
475                }
476                let range_exprs = range_rewriter.range_fn.into_iter().collect::<Vec<_>>();
477                let input = Arc::new(build_range_input_projection(
478                    input.as_ref(),
479                    &range_exprs,
480                    &time_index,
481                    &range_rewriter.by,
482                )?);
483                let range_select = RangeSelect::try_new(
484                    input,
485                    range_exprs,
486                    range_rewriter.align,
487                    range_rewriter.align_to,
488                    time_index,
489                    range_rewriter.by,
490                    &new_expr,
491                )?;
492                let no_additional_project = range_select.schema_project.is_some();
493                let range_plan = LogicalPlan::Extension(Extension {
494                    node: Arc::new(range_select),
495                });
496                if no_additional_project {
497                    Ok(Some(range_plan))
498                } else {
499                    let project_plan = LogicalPlanBuilder::from(range_plan)
500                        .project(new_expr)
501                        .and_then(|x| x.build())?;
502                    Ok(Some(project_plan))
503                }
504            }
505            _ => {
506                if new_inputs.iter().any(|x| x.is_some()) {
507                    let inputs: Vec<LogicalPlan> = new_inputs
508                        .into_iter()
509                        .zip(inputs)
510                        .map(|(x, y)| match x {
511                            Some(plan) => plan,
512                            None => y.clone(),
513                        })
514                        .collect();
515                    // Due to the limitations of Datafusion, for `LogicalPlan::Analyze` and `LogicalPlan::Explain`,
516                    // directly using the method `with_new_inputs` to rebuild a new `LogicalPlan` will cause an error,
517                    // so here we directly use the `LogicalPlanBuilder` to build a new plan.
518                    let plan = match plan {
519                        LogicalPlan::Analyze(Analyze { verbose, .. }) => {
520                            ensure!(
521                                inputs.len() == 1,
522                                RangeQuerySnafu {
523                                    msg: "Illegal subplan nums when rewrite Analyze logical plan",
524                                }
525                            );
526                            LogicalPlanBuilder::from(inputs[0].clone())
527                                .explain(*verbose, true)?
528                                .build()
529                        }
530                        LogicalPlan::Explain(Explain { verbose, .. }) => {
531                            ensure!(
532                                inputs.len() == 1,
533                                RangeQuerySnafu {
534                                    msg: "Illegal subplan nums when rewrite Explain logical plan",
535                                }
536                            );
537                            LogicalPlanBuilder::from(inputs[0].clone())
538                                .explain(*verbose, false)?
539                                .build()
540                        }
541                        LogicalPlan::Distinct(Distinct::On(DistinctOn {
542                            on_expr,
543                            select_expr,
544                            sort_expr,
545                            ..
546                        })) => {
547                            ensure!(
548                                inputs.len() == 1,
549                                RangeQuerySnafu {
550                                    msg: "Illegal subplan nums when rewrite DistinctOn logical plan",
551                                }
552                            );
553                            LogicalPlanBuilder::from(inputs[0].clone())
554                                .distinct_on(
555                                    on_expr.clone(),
556                                    select_expr.clone(),
557                                    sort_expr.clone(),
558                                )?
559                                .build()
560                        }
561                        _ => plan.with_new_exprs(plan.expressions_consider_join(), inputs),
562                    }?;
563                    Ok(Some(plan))
564                } else {
565                    Ok(None)
566                }
567            }
568        }
569    }
570
571    /// Finds the time index column and default row-key grouping from the input schema.
572    ///
573    /// Returns `(time_index, [row_columns])` to the rewriter. If the user omits `BY`,
574    /// `[row_columns]` is used as the default time-series grouping.
575    ///
576    /// For derived inputs such as subqueries, joins, or set operations, the source table
577    /// qualifier may no longer resolve back to a table provider. In that case we can still
578    /// recover the time index from column metadata, but we cannot safely reconstruct the
579    /// original row-key columns, so omitted `BY` must be rejected by the caller.
580    async fn get_index_by(
581        &mut self,
582        schema: &Arc<DFSchema>,
583        need_default_by: bool,
584    ) -> Result<(Expr, Vec<Expr>)> {
585        #[allow(deprecated)]
586        let mut time_index_expr = Expr::Wildcard {
587            qualifier: None,
588            options: Box::new(WildcardOptions::default()),
589        };
590        let mut default_by = vec![];
591        let metadata_time_index_expr = (0..schema.fields().len()).find_map(|i| {
592            let (qualifier, field) = schema.qualified_field(i);
593            if field.metadata().contains_key(TIME_INDEX_KEY)
594                && matches!(field.data_type(), DataType::Timestamp(_, _))
595            {
596                Some(Expr::Column(Column::new(
597                    qualifier.cloned(),
598                    field.name().clone(),
599                )))
600            } else {
601                None
602            }
603        });
604        for i in 0..schema.fields().len() {
605            let (qualifier, _) = schema.qualified_field(i);
606            if let Some(table_ref) = qualifier {
607                let table_source = match self.table_provider.resolve_table(table_ref.clone()).await
608                {
609                    Ok(table_source) => table_source,
610                    Err(error) => {
611                        // `TableNotExist` here usually means the qualifier now refers to a derived
612                        // input instead of a base table. Skip it and let the checks below take the
613                        // time index from field metadata or report `TimeIndexNotFound`.
614                        if matches!(&error, catalog::error::Error::TableNotExist { .. }) {
615                            continue;
616                        }
617                        return Err(error).context(CatalogSnafu);
618                    }
619                };
620                let table = table_source
621                    .downcast_ref::<DefaultTableSource>()
622                    .context(UnknownTableSnafu)?
623                    .table_provider
624                    .downcast_ref::<DfTableProviderAdapter>()
625                    .context(UnknownTableSnafu)?
626                    .table();
627                let schema = table.schema();
628                let time_index_column =
629                    schema
630                        .timestamp_column()
631                        .with_context(|| TimeIndexNotFoundSnafu {
632                            table: table_ref.to_string(),
633                        })?;
634                // assert time_index's datatype is timestamp
635                if let ConcreteDataType::Timestamp(_) = time_index_column.data_type {
636                    default_by = table
637                        .table_info()
638                        .meta
639                        .row_key_column_names()
640                        .map(|key| Expr::Column(Column::new(Some(table_ref.clone()), key)))
641                        .collect();
642                    // If the user does not specify a primary key when creating a table,
643                    // then by default all data will be aggregated into one time series,
644                    // which is equivalent to using `by(1)` in SQL
645                    if default_by.is_empty() {
646                        default_by = vec![1.lit()];
647                    }
648                    time_index_expr = Expr::Column(Column::new(
649                        Some(table_ref.clone()),
650                        time_index_column.name.clone(),
651                    ));
652                }
653            }
654        }
655        #[allow(deprecated)]
656        if matches!(time_index_expr, Expr::Wildcard { .. })
657            && let Some(expr) = metadata_time_index_expr
658        {
659            common_telemetry::debug!(
660                "Range query falling back to time-index metadata for derived input schema: {}",
661                schema
662            );
663            ensure!(
664                !need_default_by,
665                RangeQuerySnafu {
666                    msg: "Cannot infer default BY columns from derived range query input"
667                }
668            );
669            time_index_expr = expr;
670        }
671        #[allow(deprecated)]
672        if matches!(time_index_expr, Expr::Wildcard { .. }) {
673            TimeIndexNotFoundSnafu {
674                table: schema.to_string(),
675            }
676            .fail()
677        } else {
678            Ok((time_index_expr, default_by))
679        }
680    }
681}
682
683/// Builds the narrow child projection required by [`RangeSelect`].
684///
685/// The physical Range implementation consumes aggregate arguments and aggregate
686/// ordering expressions, but does not support aggregate `FILTER` expressions.
687fn build_range_input_projection(
688    input: &LogicalPlan,
689    range_exprs: &[RangeFn],
690    time_expr: &Expr,
691    by_exprs: &[Expr],
692) -> DFResult<LogicalPlan> {
693    let mut required_columns = HashSet::new();
694    for range_expr in range_exprs {
695        let range_expr = match &range_expr.expr {
696            Expr::Alias(alias) => alias.expr.as_ref(),
697            expr => expr,
698        };
699        let Some(aggr) = get_aggr_func(range_expr) else {
700            return Err(DataFusionError::Plan(format!(
701                "Unexpected Expr: {} in RangeSelect",
702                range_expr
703            )));
704        };
705        if aggr.params.filter.is_some() {
706            return Err(DataFusionError::NotImplemented(
707                "Range aggregate FILTER is unsupported".to_string(),
708            ));
709        }
710        for expr in &aggr.params.args {
711            expr_to_columns(expr, &mut required_columns)?;
712        }
713        for sort_expr in &aggr.params.order_by {
714            expr_to_columns(&sort_expr.expr, &mut required_columns)?;
715        }
716    }
717    expr_to_columns(time_expr, &mut required_columns)?;
718    for by_expr in by_exprs {
719        expr_to_columns(by_expr, &mut required_columns)?;
720    }
721
722    let required_indices = required_columns
723        .iter()
724        .map(|column| input.schema().index_of_column(column))
725        .collect::<DFResult<BTreeSet<_>>>()?;
726    let projection = required_indices
727        .into_iter()
728        .map(|index| {
729            let (qualifier, field) = input.schema().qualified_field(index);
730            Expr::Column(Column::new(qualifier.cloned(), field.name()))
731        })
732        .collect::<Vec<_>>();
733    LogicalPlanBuilder::from(input.clone())
734        .project(projection)?
735        .build()
736}
737
738fn have_range_in_exprs(exprs: &[Expr]) -> bool {
739    exprs.iter().any(|expr| {
740        let mut find_range = false;
741        let _ = expr.apply(|expr| {
742            Ok(match expr {
743                Expr::ScalarFunction(func) if func.name() == "range_fn" => {
744                    find_range = true;
745                    TreeNodeRecursion::Stop
746                }
747                _ => TreeNodeRecursion::Continue,
748            })
749        });
750        find_range
751    })
752}
753
754fn interval_only_in_expr(expr: &Expr) -> bool {
755    let mut all_interval = true;
756    let _ = expr.apply(|expr| {
757        // A cast expression for an interval.
758        if matches!(
759            expr,
760            Expr::Cast(Cast {
761                expr,
762                field,
763            }) if matches!(field.data_type(), DataType::Interval(_))
764                && matches!(&**expr, Expr::Literal(ScalarValue::Utf8(_), _))
765        ) {
766            // Stop checking the sub `expr`,
767            // which is a `Utf8` type and has already been tested above.
768            return Ok(TreeNodeRecursion::Stop);
769        }
770
771        if !(matches!(
772            expr,
773            Expr::Literal(ScalarValue::IntervalDayTime(_), _)
774                | Expr::Literal(ScalarValue::IntervalMonthDayNano(_), _)
775                | Expr::Literal(ScalarValue::IntervalYearMonth(_), _)
776                | Expr::BinaryExpr(_)
777        ) || matches!(
778            expr,
779            Expr::Cast(Cast { field, .. }) if matches!(field.data_type(), DataType::Interval(_))
780        )) {
781            all_interval = false;
782            Ok(TreeNodeRecursion::Stop)
783        } else {
784            Ok(TreeNodeRecursion::Continue)
785        }
786    });
787
788    all_interval
789}
790
791#[cfg(test)]
792mod test {
793
794    use arrow::datatypes::{IntervalUnit, TimeUnit};
795    use catalog::RegisterTableRequest;
796    use catalog::memory::MemoryCatalogManager;
797    use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
798    use common_function::function::FunctionContext;
799    use common_function::function_registry::FUNCTION_REGISTRY;
800    use common_query::test_util::DummyDecoder;
801    use common_time::IntervalYearMonth;
802    use datafusion::functions_aggregate::expr_fn::avg;
803    use datafusion_common::TableReference;
804    use datafusion_expr::{BinaryExpr, Literal, Operator, UserDefinedLogicalNodeCore, col};
805    use datatypes::prelude::ConcreteDataType;
806    use datatypes::schema::{ColumnSchema, Schema};
807    use session::context::{QueryContext, QueryContextBuilder};
808    use table::metadata::{TableInfoBuilder, TableMetaBuilder};
809    use table::table::TableRef;
810    use table::test_util::EmptyTable;
811
812    use super::*;
813    use crate::options::QueryOptions;
814    use crate::parser::QueryLanguageParser;
815    use crate::{QueryEngineFactory, QueryEngineRef};
816
817    async fn create_test_engine() -> QueryEngineRef {
818        create_test_engine_with_tables(&["test"], false).await
819    }
820
821    async fn create_union_test_engine() -> QueryEngineRef {
822        create_test_engine_with_tables(&["test_0", "test_1"], true).await
823    }
824
825    async fn create_test_engine_with_tables(
826        table_names: &[&str],
827        with_extra_timestamp: bool,
828    ) -> QueryEngineRef {
829        let catalog_list = MemoryCatalogManager::with_default_setup();
830        for (i, table_name) in table_names.iter().enumerate() {
831            let table = create_test_table(table_name, with_extra_timestamp);
832            assert!(
833                catalog_list
834                    .register_table_sync(RegisterTableRequest {
835                        catalog: DEFAULT_CATALOG_NAME.to_string(),
836                        schema: DEFAULT_SCHEMA_NAME.to_string(),
837                        table_name: (*table_name).to_string(),
838                        table_id: 1024 + i as u32,
839                        table,
840                    })
841                    .is_ok()
842            );
843        }
844        QueryEngineFactory::new(
845            catalog_list,
846            None,
847            None,
848            None,
849            None,
850            false,
851            QueryOptions::default(),
852        )
853        .query_engine()
854    }
855
856    fn create_test_table(table_name: &str, with_extra_timestamp: bool) -> TableRef {
857        let mut columns = vec![];
858        for i in 0..5 {
859            columns.push(ColumnSchema::new(
860                format!("tag_{i}"),
861                ConcreteDataType::string_datatype(),
862                false,
863            ));
864        }
865        columns.push(
866            ColumnSchema::new(
867                "timestamp".to_string(),
868                ConcreteDataType::timestamp_millisecond_datatype(),
869                false,
870            )
871            .with_time_index(true),
872        );
873        if with_extra_timestamp {
874            columns.push(ColumnSchema::new(
875                "timestamp_2".to_string(),
876                ConcreteDataType::timestamp_millisecond_datatype(),
877                true,
878            ));
879        }
880        for i in 0..5 {
881            columns.push(ColumnSchema::new(
882                format!("field_{i}"),
883                ConcreteDataType::float64_datatype(),
884                true,
885            ));
886        }
887        let schema = Arc::new(Schema::new(columns));
888        let table_meta = TableMetaBuilder::empty()
889            .schema(schema)
890            .primary_key_indices((0..5).collect())
891            .value_indices(if with_extra_timestamp {
892                (6..12).collect()
893            } else {
894                (6..11).collect()
895            })
896            .next_column_id(1024)
897            .build()
898            .unwrap();
899        let table_info = TableInfoBuilder::default()
900            .name(table_name)
901            .meta(table_meta)
902            .build()
903            .unwrap();
904        EmptyTable::from_table_info(&table_info)
905    }
906
907    async fn do_query(sql: &str) -> Result<LogicalPlan> {
908        let stmt = QueryLanguageParser::parse_sql(sql, &QueryContext::arc()).unwrap();
909        let engine = create_test_engine().await;
910        engine.planner().plan(&stmt, QueryContext::arc()).await
911    }
912
913    async fn do_query_with_ctx(sql: &str, query_ctx: QueryContextRef) -> Result<LogicalPlan> {
914        let stmt = QueryLanguageParser::parse_sql(sql, &query_ctx).unwrap();
915        let engine = create_test_engine().await;
916        engine.planner().plan(&stmt, query_ctx).await
917    }
918
919    async fn do_union_query(sql: &str) -> Result<LogicalPlan> {
920        let stmt = QueryLanguageParser::parse_sql(sql, &QueryContext::arc()).unwrap();
921        let engine = create_union_test_engine().await;
922        engine.planner().plan(&stmt, QueryContext::arc()).await
923    }
924
925    async fn query_plan_compare(sql: &str, expected: String) {
926        let plan = do_query(sql).await.unwrap();
927        assert_eq!(plan.display_indent_schema().to_string(), expected);
928    }
929
930    #[tokio::test]
931    async fn range_align_to_now_uses_scheduled_time_extension() {
932        let query_ctx = Arc::new(
933            QueryContextBuilder::default()
934                .set_extension(
935                    crate::options::FLOW_SCHEDULED_TIME_MILLIS.to_string(),
936                    "1700000000123".to_string(),
937                )
938                .build(),
939        );
940        let query = r#"SELECT timestamp, tag_0, tag_1, avg(field_0) RANGE '5m' FROM test ALIGN '1h' TO NOW by (tag_0,tag_1);"#;
941        let plan = do_query_with_ctx(query, query_ctx).await.unwrap();
942
943        assert!(
944            plan.display_indent_schema()
945                .to_string()
946                .contains("align_to=1700000000123ms")
947        );
948    }
949
950    #[tokio::test]
951    async fn range_no_project() {
952        let query = r#"SELECT timestamp, tag_0, tag_1, avg(field_0 + field_1) RANGE '5m' FROM test ALIGN '1h' by (tag_0,tag_1);"#;
953        let expected = String::from(
954            "RangeSelect: range_exprs=[avg(test.field_0 + test.field_1) RANGE 5m], align=3600000ms, align_to=0ms, align_by=[test.tag_0, test.tag_1], time_index=timestamp [timestamp:Timestamp(ms), tag_0:Utf8, tag_1:Utf8, avg(test.field_0 + test.field_1) RANGE 5m:Float64;N]\
955            \n  Projection: test.tag_0, test.tag_1, test.timestamp, test.field_0, test.field_1 [tag_0:Utf8, tag_1:Utf8, timestamp:Timestamp(ms), field_0:Float64;N, field_1:Float64;N]\
956            \n    TableScan: test [tag_0:Utf8, tag_1:Utf8, tag_2:Utf8, tag_3:Utf8, tag_4:Utf8, timestamp:Timestamp(ms), field_0:Float64;N, field_1:Float64;N, field_2:Float64;N, field_3:Float64;N, field_4:Float64;N]",
957        );
958        query_plan_compare(query, expected).await;
959    }
960
961    #[tokio::test]
962    async fn range_select_rewrite_projects_required_input_columns() {
963        let query = r#"SELECT timestamp, tag_0, tag_1, avg(field_0 + field_1) RANGE '5m' FROM test ALIGN '1h' by (tag_0,tag_1);"#;
964        let plan = do_query(query).await.unwrap();
965        let LogicalPlan::Extension(extension) = plan else {
966            panic!("expected RangeSelect rewrite output, got: {plan}");
967        };
968        let range_select = extension
969            .node
970            .as_any()
971            .downcast_ref::<RangeSelect>()
972            .expect("expected RangeSelect extension");
973
974        let LogicalPlan::Projection(projection) = range_select.input.as_ref() else {
975            panic!(
976                "expected a narrow Projection below RangeSelect, got: {}",
977                range_select.input
978            );
979        };
980        assert_eq!(
981            projection
982                .schema
983                .fields()
984                .iter()
985                .map(|field| field.name().as_str())
986                .collect::<Vec<_>>(),
987            vec!["tag_0", "tag_1", "timestamp", "field_0", "field_1",]
988        );
989        assert_eq!(
990            range_select
991                .schema
992                .fields()
993                .iter()
994                .map(|field| (
995                    field.name().as_str(),
996                    field.data_type().clone(),
997                    field.is_nullable()
998                ))
999                .collect::<Vec<_>>(),
1000            vec![
1001                (
1002                    "timestamp",
1003                    DataType::Timestamp(TimeUnit::Millisecond, None),
1004                    false
1005                ),
1006                ("tag_0", DataType::Utf8, false),
1007                ("tag_1", DataType::Utf8, false),
1008                (
1009                    "avg(test.field_0 + test.field_1) RANGE 5m",
1010                    DataType::Float64,
1011                    true,
1012                ),
1013            ]
1014        );
1015        assert_eq!(
1016            range_select.schema.qualified_field(0).0,
1017            projection.schema.qualified_field(2).0
1018        );
1019        assert_eq!(
1020            range_select.schema.qualified_field(1).0,
1021            projection.schema.qualified_field(0).0
1022        );
1023    }
1024
1025    async fn assert_range_select_input_columns(sql: &str, expected: &[&str]) {
1026        let plan = do_query(sql).await.unwrap();
1027        let LogicalPlan::Extension(extension) = plan else {
1028            panic!("expected RangeSelect rewrite output, got: {plan}");
1029        };
1030        let range_select = extension
1031            .node
1032            .as_any()
1033            .downcast_ref::<RangeSelect>()
1034            .expect("expected RangeSelect extension");
1035        let LogicalPlan::Projection(projection) = range_select.input.as_ref() else {
1036            panic!("expected narrow Projection, got: {}", range_select.input);
1037        };
1038        assert_eq!(
1039            projection
1040                .schema
1041                .fields()
1042                .iter()
1043                .map(|field| field.name().as_str())
1044                .collect::<Vec<_>>(),
1045            expected
1046        );
1047    }
1048
1049    #[tokio::test]
1050    async fn range_select_input_projection_collects_range_dependencies() {
1051        assert_range_select_input_columns(
1052            r#"SELECT timestamp, tag_0, avg(field_0 + field_1) RANGE '5m', sum(field_2) RANGE '5m' FROM test ALIGN '1h' BY (tag_0);"#,
1053            &["tag_0", "timestamp", "field_0", "field_1", "field_2"],
1054        )
1055        .await;
1056        assert_range_select_input_columns(
1057            r#"SELECT timestamp, tag_0, last_value(field_0 ORDER BY field_2) RANGE '5m' FROM test ALIGN '1h' BY (tag_0);"#,
1058            &["tag_0", "timestamp", "field_0", "field_2"],
1059        )
1060        .await;
1061        assert_range_select_input_columns(
1062            r#"SELECT timestamp, count(*) RANGE '5m' FILL NULL FROM test ALIGN '1h';"#,
1063            &["tag_0", "tag_1", "tag_2", "tag_3", "tag_4", "timestamp"],
1064        )
1065        .await;
1066        assert_range_select_input_columns(
1067            r#"SELECT timestamp, count(1) RANGE '5m' FILL PREV FROM test ALIGN '1h' BY (tag_0);"#,
1068            &["tag_0", "timestamp"],
1069        )
1070        .await;
1071    }
1072
1073    #[tokio::test]
1074    async fn range_select_input_projection_collects_nested_alias_dependencies() {
1075        let plan = do_query(
1076            r#"SELECT timestamp, tag_0, avg(field_0 + field_1) RANGE '5m' FROM test ALIGN '1h' BY (tag_0);"#,
1077        )
1078        .await
1079        .unwrap();
1080        let LogicalPlan::Extension(extension) = plan else {
1081            panic!("expected RangeSelect rewrite output, got: {plan}");
1082        };
1083        let range_select = extension
1084            .node
1085            .as_any()
1086            .downcast_ref::<RangeSelect>()
1087            .expect("expected RangeSelect extension");
1088        let mut range_exprs = range_select.range_expr.clone();
1089        range_exprs[0].expr = range_exprs[0]
1090            .expr
1091            .clone()
1092            .alias("inner_alias")
1093            .alias("outer_alias");
1094
1095        let input = build_range_input_projection(
1096            range_select.input.as_ref(),
1097            &range_exprs,
1098            &range_select.time_expr,
1099            &range_select.by,
1100        )
1101        .unwrap();
1102        let LogicalPlan::Projection(projection) = input else {
1103            panic!("expected narrow Projection, got: {input}");
1104        };
1105        assert_eq!(
1106            projection
1107                .schema
1108                .fields()
1109                .iter()
1110                .map(|field| field.name().as_str())
1111                .collect::<Vec<_>>(),
1112            ["tag_0", "timestamp", "field_0", "field_1"],
1113        );
1114    }
1115
1116    #[tokio::test]
1117    async fn range_select_physical_plan_accepts_nested_aggregate_aliases() {
1118        let query_ctx = QueryContext::arc();
1119        let stmt = QueryLanguageParser::parse_sql(
1120            r#"SELECT timestamp, tag_0, avg(field_0) RANGE '5m' FROM test ALIGN '1h' BY (tag_0);"#,
1121            &query_ctx,
1122        )
1123        .unwrap();
1124        let engine = create_test_engine().await;
1125        let plan = engine
1126            .planner()
1127            .plan(&stmt, query_ctx.clone())
1128            .await
1129            .unwrap();
1130        let LogicalPlan::Extension(extension) = plan else {
1131            panic!("expected RangeSelect rewrite output, got: {plan}");
1132        };
1133        let range_select = extension
1134            .node
1135            .as_any()
1136            .downcast_ref::<RangeSelect>()
1137            .expect("expected RangeSelect extension");
1138        let mut exprs = range_select.expressions();
1139        exprs[0] = exprs[0].clone().alias("inner_alias").alias("outer_alias");
1140        let plan = LogicalPlan::Extension(Extension {
1141            node: Arc::new(
1142                range_select
1143                    .with_exprs_and_inputs(exprs, vec![range_select.input.as_ref().clone()])
1144                    .unwrap(),
1145            ),
1146        });
1147
1148        engine.execute(plan, query_ctx).await.unwrap();
1149    }
1150
1151    #[tokio::test]
1152    async fn range_select_input_projection_resolves_derived_aliases() {
1153        let plan = do_query(
1154            r#"SELECT d.ts, d.group_tag, avg(d.value) RANGE '5m' FROM (SELECT timestamp AS ts, tag_0 AS group_tag, field_0 AS value, field_4 AS ignored FROM test) AS d ALIGN '1h' BY (d.group_tag);"#,
1155        )
1156        .await
1157        .unwrap();
1158        let LogicalPlan::Extension(extension) = plan else {
1159            panic!("expected RangeSelect rewrite output, got: {plan}");
1160        };
1161        let range_select = extension
1162            .node
1163            .as_any()
1164            .downcast_ref::<RangeSelect>()
1165            .expect("expected RangeSelect extension");
1166        let LogicalPlan::Projection(projection) = range_select.input.as_ref() else {
1167            panic!("expected narrow Projection, got: {}", range_select.input);
1168        };
1169        assert_eq!(
1170            projection
1171                .schema
1172                .fields()
1173                .iter()
1174                .map(|field| field.name().as_str())
1175                .collect::<Vec<_>>(),
1176            ["ts", "group_tag", "value"],
1177        );
1178        assert!(
1179            projection
1180                .schema
1181                .fields()
1182                .iter()
1183                .enumerate()
1184                .all(|(index, _)| projection
1185                    .schema
1186                    .qualified_field(index)
1187                    .0
1188                    .unwrap()
1189                    .to_string()
1190                    == "d")
1191        );
1192    }
1193
1194    #[tokio::test]
1195    async fn range_select_rejects_aggregate_filter() {
1196        let error = do_query(
1197            r#"SELECT timestamp, tag_0, avg(field_0) FILTER (WHERE field_1 > 0) RANGE '5m' FROM test ALIGN '1h' BY (tag_0);"#,
1198        )
1199        .await
1200        .unwrap_err()
1201        .to_string();
1202        assert_eq!(
1203            error,
1204            "This feature is not implemented: Range aggregate FILTER is unsupported"
1205        );
1206    }
1207
1208    #[tokio::test]
1209    async fn range_expr_calculation() {
1210        let query = r#"SELECT (avg(field_0 + field_1)/4) RANGE '5m' FROM test ALIGN '1h' by (tag_0,tag_1);"#;
1211        let expected = String::from(
1212            "Projection: avg(test.field_0 + test.field_1) RANGE 5m / Int64(4) [avg(test.field_0 + test.field_1) RANGE 5m / Int64(4):Float64;N]\
1213            \n  RangeSelect: range_exprs=[avg(test.field_0 + test.field_1) RANGE 5m], align=3600000ms, align_to=0ms, align_by=[test.tag_0, test.tag_1], time_index=timestamp [avg(test.field_0 + test.field_1) RANGE 5m:Float64;N, timestamp:Timestamp(ms), tag_0:Utf8, tag_1:Utf8]\
1214            \n    Projection: test.tag_0, test.tag_1, test.timestamp, test.field_0, test.field_1 [tag_0:Utf8, tag_1:Utf8, timestamp:Timestamp(ms), field_0:Float64;N, field_1:Float64;N]\
1215            \n      TableScan: test [tag_0:Utf8, tag_1:Utf8, tag_2:Utf8, tag_3:Utf8, tag_4:Utf8, timestamp:Timestamp(ms), field_0:Float64;N, field_1:Float64;N, field_2:Float64;N, field_3:Float64;N, field_4:Float64;N]",
1216        );
1217        query_plan_compare(query, expected).await;
1218    }
1219
1220    #[tokio::test]
1221    async fn range_multi_args() {
1222        let query =
1223            r#"SELECT (covar(field_0 + field_1, field_1)/4) RANGE '5m' FROM test ALIGN '1h';"#;
1224        let expected = String::from(
1225            "Projection: covar_samp(test.field_0 + test.field_1,test.field_1) RANGE 5m / Int64(4) [covar_samp(test.field_0 + test.field_1,test.field_1) RANGE 5m / Int64(4):Float64;N]\
1226            \n  RangeSelect: range_exprs=[covar_samp(test.field_0 + test.field_1,test.field_1) RANGE 5m], align=3600000ms, align_to=0ms, align_by=[test.tag_0, test.tag_1, test.tag_2, test.tag_3, test.tag_4], time_index=timestamp [covar_samp(test.field_0 + test.field_1,test.field_1) RANGE 5m:Float64;N, timestamp:Timestamp(ms), tag_0:Utf8, tag_1:Utf8, tag_2:Utf8, tag_3:Utf8, tag_4:Utf8]\
1227            \n    Projection: test.tag_0, test.tag_1, test.tag_2, test.tag_3, test.tag_4, test.timestamp, test.field_0, test.field_1 [tag_0:Utf8, tag_1:Utf8, tag_2:Utf8, tag_3:Utf8, tag_4:Utf8, timestamp:Timestamp(ms), field_0:Float64;N, field_1:Float64;N]\
1228            \n      TableScan: test [tag_0:Utf8, tag_1:Utf8, tag_2:Utf8, tag_3:Utf8, tag_4:Utf8, timestamp:Timestamp(ms), field_0:Float64;N, field_1:Float64;N, field_2:Float64;N, field_3:Float64;N, field_4:Float64;N]",
1229        );
1230        query_plan_compare(query, expected).await;
1231    }
1232
1233    #[tokio::test]
1234    async fn range_calculation() {
1235        let query = r#"SELECT ((avg(field_0)+sum(field_1))/4) RANGE '5m' FROM test ALIGN '1h' by (tag_0,tag_1) FILL NULL;"#;
1236        let expected = String::from(
1237            "Projection: (avg(test.field_0) RANGE 5m FILL NULL + sum(test.field_1) RANGE 5m FILL NULL) / Int64(4) [avg(test.field_0) RANGE 5m FILL NULL + sum(test.field_1) RANGE 5m FILL NULL / Int64(4):Float64;N]\
1238            \n  RangeSelect: range_exprs=[avg(test.field_0) RANGE 5m FILL NULL, sum(test.field_1) RANGE 5m FILL NULL], align=3600000ms, align_to=0ms, align_by=[test.tag_0, test.tag_1], time_index=timestamp [avg(test.field_0) RANGE 5m FILL NULL:Float64;N, sum(test.field_1) RANGE 5m FILL NULL:Float64;N, timestamp:Timestamp(ms), tag_0:Utf8, tag_1:Utf8]\
1239            \n    Projection: test.tag_0, test.tag_1, test.timestamp, test.field_0, test.field_1 [tag_0:Utf8, tag_1:Utf8, timestamp:Timestamp(ms), field_0:Float64;N, field_1:Float64;N]\
1240            \n      TableScan: test [tag_0:Utf8, tag_1:Utf8, tag_2:Utf8, tag_3:Utf8, tag_4:Utf8, timestamp:Timestamp(ms), field_0:Float64;N, field_1:Float64;N, field_2:Float64;N, field_3:Float64;N, field_4:Float64;N]",
1241        );
1242        query_plan_compare(query, expected).await;
1243    }
1244
1245    #[tokio::test]
1246    async fn range_as_sub_query() {
1247        let query = r#"SELECT foo + 1 from (SELECT ((avg(field_0)+sum(field_1))/4) RANGE '5m' as foo FROM test ALIGN '1h' by (tag_0,tag_1) FILL NULL) where foo > 1;"#;
1248        let expected = String::from(
1249            "Projection: foo + Int64(1) [foo + Int64(1):Float64;N]\
1250            \n  Filter: foo > Int64(1) [foo:Float64;N]\
1251            \n    Projection: (avg(test.field_0) RANGE 5m FILL NULL + sum(test.field_1) RANGE 5m FILL NULL) / Int64(4) AS foo [foo:Float64;N]\
1252            \n      RangeSelect: range_exprs=[avg(test.field_0) RANGE 5m FILL NULL, sum(test.field_1) RANGE 5m FILL NULL], align=3600000ms, align_to=0ms, align_by=[test.tag_0, test.tag_1], time_index=timestamp [avg(test.field_0) RANGE 5m FILL NULL:Float64;N, sum(test.field_1) RANGE 5m FILL NULL:Float64;N, timestamp:Timestamp(ms), tag_0:Utf8, tag_1:Utf8]\
1253            \n        Projection: test.tag_0, test.tag_1, test.timestamp, test.field_0, test.field_1 [tag_0:Utf8, tag_1:Utf8, timestamp:Timestamp(ms), field_0:Float64;N, field_1:Float64;N]\
1254            \n          TableScan: test [tag_0:Utf8, tag_1:Utf8, tag_2:Utf8, tag_3:Utf8, tag_4:Utf8, timestamp:Timestamp(ms), field_0:Float64;N, field_1:Float64;N, field_2:Float64;N, field_3:Float64;N, field_4:Float64;N]",
1255        );
1256        query_plan_compare(query, expected).await;
1257    }
1258
1259    #[tokio::test]
1260    async fn range_from_nest_query() {
1261        let query = r#"SELECT ((avg(a)+sum(b))/4) RANGE '5m' FROM (SELECT field_0 as a, field_1 as b, tag_0 as c, tag_1 as d, timestamp from test where field_0 > 1.0) ALIGN '1h' by (c, d) FILL NULL;"#;
1262        let expected = String::from(
1263            "Projection: (avg(a) RANGE 5m FILL NULL + sum(b) RANGE 5m FILL NULL) / Int64(4) [avg(a) RANGE 5m FILL NULL + sum(b) RANGE 5m FILL NULL / Int64(4):Float64;N]\
1264            \n  RangeSelect: range_exprs=[avg(a) RANGE 5m FILL NULL, sum(b) RANGE 5m FILL NULL], align=3600000ms, align_to=0ms, align_by=[c, d], time_index=timestamp [avg(a) RANGE 5m FILL NULL:Float64;N, sum(b) RANGE 5m FILL NULL:Float64;N, timestamp:Timestamp(ms), c:Utf8, d:Utf8]\
1265            \n    Projection: a, b, c, d, test.timestamp [a:Float64;N, b:Float64;N, c:Utf8, d:Utf8, timestamp:Timestamp(ms)]\
1266            \n      Projection: test.field_0 AS a, test.field_1 AS b, test.tag_0 AS c, test.tag_1 AS d, test.timestamp [a:Float64;N, b:Float64;N, c:Utf8, d:Utf8, timestamp:Timestamp(ms)]\
1267            \n        Filter: test.field_0 > Float64(1) [tag_0:Utf8, tag_1:Utf8, tag_2:Utf8, tag_3:Utf8, tag_4:Utf8, timestamp:Timestamp(ms), field_0:Float64;N, field_1:Float64;N, field_2:Float64;N, field_3:Float64;N, field_4:Float64;N]\
1268            \n          TableScan: test [tag_0:Utf8, tag_1:Utf8, tag_2:Utf8, tag_3:Utf8, tag_4:Utf8, timestamp:Timestamp(ms), field_0:Float64;N, field_1:Float64;N, field_2:Float64;N, field_3:Float64;N, field_4:Float64;N]",
1269        );
1270        query_plan_compare(query, expected).await;
1271    }
1272
1273    #[tokio::test]
1274    async fn range_from_union_query() {
1275        let queries = [
1276            r#"SELECT timestamp, tag_0, avg(field_0) RANGE '5m'
1277            FROM (
1278                SELECT timestamp, tag_0, field_0, timestamp_2 FROM test_0
1279                UNION ALL
1280                SELECT timestamp, tag_0, field_0, timestamp_2 FROM test_1
1281            )
1282            WHERE timestamp >= '1970-01-01 00:00:00'
1283            ALIGN '1h' by (tag_0)"#,
1284            r#"SELECT tmp.timestamp, tmp.tag_0, avg(tmp.field_0) RANGE '5m'
1285            FROM (
1286                SELECT timestamp, tag_0, field_0, timestamp_2 FROM test_0
1287                UNION ALL
1288                SELECT timestamp, tag_0, field_0, timestamp_2 FROM test_1
1289            ) AS tmp
1290            WHERE tmp.timestamp >= '1970-01-01 00:00:00'
1291            ALIGN '1h' by (tmp.tag_0)"#,
1292        ];
1293
1294        for query in queries {
1295            let plan = do_union_query(query)
1296                .await
1297                .unwrap()
1298                .display_indent_schema()
1299                .to_string();
1300
1301            assert!(plan.contains("RangeSelect"));
1302            assert!(plan.contains("Union"));
1303            assert!(plan.contains("time_index=timestamp"));
1304        }
1305    }
1306
1307    #[tokio::test]
1308    async fn range_from_derived_query_without_by_err() {
1309        let queries = [
1310            r#"SELECT timestamp, tag_0, avg(field_0) RANGE '5m'
1311            FROM (
1312                SELECT timestamp, tag_0, field_0, timestamp_2 FROM test_0
1313                UNION ALL
1314                SELECT timestamp, tag_0, field_0, timestamp_2 FROM test_1
1315            )
1316            WHERE timestamp >= '1970-01-01 00:00:00'
1317            ALIGN '1h'"#,
1318            r#"SELECT tmp.timestamp, tmp.tag_0, avg(tmp.field_0) RANGE '5m'
1319            FROM (
1320                SELECT timestamp, tag_0, field_0, timestamp_2 FROM test_0
1321                UNION ALL
1322                SELECT timestamp, tag_0, field_0, timestamp_2 FROM test_1
1323            ) AS tmp
1324            WHERE tmp.timestamp >= '1970-01-01 00:00:00'
1325            ALIGN '1h'"#,
1326        ];
1327
1328        for query in queries {
1329            assert_eq!(
1330                do_union_query(query).await.unwrap_err().to_string(),
1331                "Range Query: Cannot infer default BY columns from derived range query input"
1332            );
1333        }
1334    }
1335
1336    #[test]
1337    fn range_rewrite_deep_union_all() {
1338        // Regression for #9356: release builds poll queries on 2 MiB worker stacks.
1339        std::thread::Builder::new()
1340            .stack_size(2 * 1024 * 1024)
1341            .spawn(|| {
1342                tokio::runtime::Builder::new_current_thread()
1343                    .enable_all()
1344                    .build()
1345                    .unwrap()
1346                    .block_on(async {
1347                        let engine = create_test_engine().await;
1348                        let table_provider = || {
1349                            DfTableSourceProvider::new(
1350                                engine.engine_state().catalog_manager().clone(),
1351                                false,
1352                                QueryContext::arc(),
1353                                DummyDecoder::arc(),
1354                                false,
1355                            )
1356                        };
1357                        // Construct the plans of 400 branches joined by `UNION ALL` directly
1358                        // to isolate this rewrite from other planner passes.
1359                        let union_all = |select: LogicalPlan| {
1360                            let mut builder = LogicalPlanBuilder::from(select.clone());
1361                            for _ in 1..400 {
1362                                builder = builder.union(select.clone()).unwrap();
1363                            }
1364                            builder
1365                        };
1366
1367                        // `SELECT 1 AS a UNION ALL ...`
1368                        let select = LogicalPlanBuilder::empty(true)
1369                            .project(vec![1.lit().alias("a")])
1370                            .unwrap()
1371                            .build()
1372                            .unwrap();
1373                        let plan = RangePlanRewriter::new(table_provider(), QueryContext::arc())
1374                            .rewrite(union_all(select).build().unwrap())
1375                            .await
1376                            .unwrap();
1377                        assert!(matches!(plan, LogicalPlan::Union(_)));
1378
1379                        // `SELECT timestamp, tag_0, avg(field_0) RANGE '5m' FROM
1380                        // (SELECT timestamp, tag_0, field_0 FROM test UNION ALL ...) ALIGN '1h' BY (tag_0)`
1381                        let source = table_provider()
1382                            .resolve_table(TableReference::bare("test"))
1383                            .await
1384                            .unwrap();
1385                        let select = LogicalPlanBuilder::scan("test", source, None)
1386                            .unwrap()
1387                            .project(vec![col("timestamp"), col("tag_0"), col("field_0")])
1388                            .unwrap()
1389                            .build()
1390                            .unwrap();
1391                        let range_fn = FUNCTION_REGISTRY
1392                            .get_function("range_fn")
1393                            .unwrap()
1394                            .provide(FunctionContext::default())
1395                            .call(vec![
1396                                Expr::Column(Column::from_name("avg(field_0)")),
1397                                "5m".lit(),
1398                                "".lit(),
1399                                "1".lit(),
1400                                col("tag_0"),
1401                                "1h".lit(),
1402                                "".lit(),
1403                            ]);
1404                        let plan = union_all(select)
1405                            .aggregate(
1406                                vec![col("tag_0"), col("timestamp")],
1407                                vec![avg(col("field_0"))],
1408                            )
1409                            .unwrap()
1410                            .project(vec![col("timestamp"), col("tag_0"), range_fn])
1411                            .unwrap()
1412                            .build()
1413                            .unwrap();
1414                        let plan = RangePlanRewriter::new(table_provider(), QueryContext::arc())
1415                            .rewrite(plan)
1416                            .await
1417                            .unwrap();
1418                        let LogicalPlan::Extension(extension) = plan else {
1419                            panic!("expected RangeSelect rewrite output");
1420                        };
1421                        assert!(extension.node.as_any().is::<RangeSelect>());
1422                    })
1423            })
1424            .unwrap()
1425            .join()
1426            .unwrap();
1427    }
1428
1429    #[test]
1430    fn range_deep_union_all_sql() {
1431        // Regression for #9356 through the SQL planner: debug builds poll queries on 8 MiB worker
1432        // stacks. Chains a little longer than this one still overflow there while cloning the
1433        // statement in `TryFrom<&Statement> for DfStatement`.
1434        std::thread::Builder::new()
1435            .stack_size(8 * 1024 * 1024)
1436            .spawn(|| {
1437                tokio::runtime::Builder::new_current_thread()
1438                    .enable_all()
1439                    .build()
1440                    .unwrap()
1441                    .block_on(async {
1442                        let union_all = |select: &str| vec![select; 400].join(" UNION ALL ");
1443
1444                        let plan = do_query(&union_all("SELECT 1 AS a")).await.unwrap();
1445                        assert!(matches!(plan, LogicalPlan::Union(_)));
1446
1447                        let query = format!(
1448                            "SELECT timestamp, tag_0, avg(field_0) RANGE '5m' FROM ({}) ALIGN '1h' BY (tag_0)",
1449                            union_all("SELECT timestamp, tag_0, field_0 FROM test")
1450                        );
1451                        let plan = do_query(&query).await.unwrap();
1452                        let LogicalPlan::Extension(extension) = plan else {
1453                            panic!("expected RangeSelect rewrite output");
1454                        };
1455                        assert!(extension.node.as_any().is::<RangeSelect>());
1456                    })
1457            })
1458            .unwrap()
1459            .join()
1460            .unwrap();
1461    }
1462
1463    #[tokio::test]
1464    async fn range_in_expr() {
1465        let query = r#"SELECT sin(avg(field_0 + field_1) RANGE '5m' + 1) FROM test ALIGN '1h' by (tag_0,tag_1);"#;
1466        let expected = String::from(
1467            "Projection: sin(avg(test.field_0 + test.field_1) RANGE 5m + Int64(1)) [sin(avg(test.field_0 + test.field_1) RANGE 5m + Int64(1)):Float64;N]\
1468            \n  RangeSelect: range_exprs=[avg(test.field_0 + test.field_1) RANGE 5m], align=3600000ms, align_to=0ms, align_by=[test.tag_0, test.tag_1], time_index=timestamp [avg(test.field_0 + test.field_1) RANGE 5m:Float64;N, timestamp:Timestamp(ms), tag_0:Utf8, tag_1:Utf8]\
1469            \n    Projection: test.tag_0, test.tag_1, test.timestamp, test.field_0, test.field_1 [tag_0:Utf8, tag_1:Utf8, timestamp:Timestamp(ms), field_0:Float64;N, field_1:Float64;N]\
1470            \n      TableScan: test [tag_0:Utf8, tag_1:Utf8, tag_2:Utf8, tag_3:Utf8, tag_4:Utf8, timestamp:Timestamp(ms), field_0:Float64;N, field_1:Float64;N, field_2:Float64;N, field_3:Float64;N, field_4:Float64;N]",
1471        );
1472        query_plan_compare(query, expected).await;
1473    }
1474
1475    #[tokio::test]
1476    async fn duplicate_range_expr() {
1477        let query = r#"SELECT avg(field_0) RANGE '5m' FILL 6.0 + avg(field_0) RANGE '5m' FILL 6.0 FROM test ALIGN '1h' by (tag_0,tag_1);"#;
1478        let expected = String::from(
1479            "Projection: avg(test.field_0) RANGE 5m FILL 6 + avg(test.field_0) RANGE 5m FILL 6 [avg(test.field_0) RANGE 5m FILL 6 + avg(test.field_0) RANGE 5m FILL 6:Float64]\
1480            \n  RangeSelect: range_exprs=[avg(test.field_0) RANGE 5m FILL 6], align=3600000ms, align_to=0ms, align_by=[test.tag_0, test.tag_1], time_index=timestamp [avg(test.field_0) RANGE 5m FILL 6:Float64, timestamp:Timestamp(ms), tag_0:Utf8, tag_1:Utf8]\
1481            \n    Projection: test.tag_0, test.tag_1, test.timestamp, test.field_0 [tag_0:Utf8, tag_1:Utf8, timestamp:Timestamp(ms), field_0:Float64;N]\
1482            \n      TableScan: test [tag_0:Utf8, tag_1:Utf8, tag_2:Utf8, tag_3:Utf8, tag_4:Utf8, timestamp:Timestamp(ms), field_0:Float64;N, field_1:Float64;N, field_2:Float64;N, field_3:Float64;N, field_4:Float64;N]",
1483        );
1484        query_plan_compare(query, expected).await;
1485    }
1486
1487    #[tokio::test]
1488    async fn deep_nest_range_expr() {
1489        let query = r#"SELECT round(sin(avg(field_0 + field_1) RANGE '5m' + 1)) FROM test ALIGN '1h' by (tag_0,tag_1);"#;
1490        let expected = String::from(
1491            "Projection: round(sin(avg(test.field_0 + test.field_1) RANGE 5m + Int64(1))) [round(sin(avg(test.field_0 + test.field_1) RANGE 5m + Int64(1))):Float64;N]\
1492            \n  RangeSelect: range_exprs=[avg(test.field_0 + test.field_1) RANGE 5m], align=3600000ms, align_to=0ms, align_by=[test.tag_0, test.tag_1], time_index=timestamp [avg(test.field_0 + test.field_1) RANGE 5m:Float64;N, timestamp:Timestamp(ms), tag_0:Utf8, tag_1:Utf8]\
1493            \n    Projection: test.tag_0, test.tag_1, test.timestamp, test.field_0, test.field_1 [tag_0:Utf8, tag_1:Utf8, timestamp:Timestamp(ms), field_0:Float64;N, field_1:Float64;N]\
1494            \n      TableScan: test [tag_0:Utf8, tag_1:Utf8, tag_2:Utf8, tag_3:Utf8, tag_4:Utf8, timestamp:Timestamp(ms), field_0:Float64;N, field_1:Float64;N, field_2:Float64;N, field_3:Float64;N, field_4:Float64;N]",
1495        );
1496        query_plan_compare(query, expected).await;
1497    }
1498
1499    #[tokio::test]
1500    async fn complex_range_expr() {
1501        let query = r#"SELECT gcd(CAST(max(field_0 + 1) Range '5m' FILL NULL AS Int64), CAST(tag_0 AS Int64)) + round(max(field_2+1) Range '6m' FILL NULL + 1) + max(field_2+3) Range '10m' FILL NULL * CAST(tag_1 AS Float64) + 1 FROM test ALIGN '1h' by (tag_0, tag_1);"#;
1502        let expected = String::from(
1503            "Projection: gcd(arrow_cast(max(test.field_0 + Int64(1)) RANGE 5m FILL NULL, Utf8(\"Int64\")), arrow_cast(test.tag_0, Utf8(\"Int64\"))) + round(max(test.field_2 + Int64(1)) RANGE 6m FILL NULL + Int64(1)) + max(test.field_2 + Int64(3)) RANGE 10m FILL NULL * arrow_cast(test.tag_1, Utf8(\"Float64\")) + Int64(1) [gcd(arrow_cast(max(test.field_0 + Int64(1)) RANGE 5m FILL NULL,Utf8(\"Int64\")),arrow_cast(test.tag_0,Utf8(\"Int64\"))) + round(max(test.field_2 + Int64(1)) RANGE 6m FILL NULL + Int64(1)) + max(test.field_2 + Int64(3)) RANGE 10m FILL NULL * arrow_cast(test.tag_1,Utf8(\"Float64\")) + Int64(1):Float64;N]\
1504            \n  RangeSelect: range_exprs=[max(test.field_0 + Int64(1)) RANGE 5m FILL NULL, max(test.field_2 + Int64(1)) RANGE 6m FILL NULL, max(test.field_2 + Int64(3)) RANGE 10m FILL NULL], align=3600000ms, align_to=0ms, align_by=[test.tag_0, test.tag_1], time_index=timestamp [max(test.field_0 + Int64(1)) RANGE 5m FILL NULL:Float64;N, max(test.field_2 + Int64(1)) RANGE 6m FILL NULL:Float64;N, max(test.field_2 + Int64(3)) RANGE 10m FILL NULL:Float64;N, timestamp:Timestamp(ms), tag_0:Utf8, tag_1:Utf8]\
1505            \n    Projection: test.tag_0, test.tag_1, test.timestamp, test.field_0, test.field_2 [tag_0:Utf8, tag_1:Utf8, timestamp:Timestamp(ms), field_0:Float64;N, field_2:Float64;N]\
1506            \n      TableScan: test [tag_0:Utf8, tag_1:Utf8, tag_2:Utf8, tag_3:Utf8, tag_4:Utf8, timestamp:Timestamp(ms), field_0:Float64;N, field_1:Float64;N, field_2:Float64;N, field_3:Float64;N, field_4:Float64;N]",
1507        );
1508        query_plan_compare(query, expected).await;
1509    }
1510
1511    #[tokio::test]
1512    async fn range_linear_on_integer() {
1513        let query = r#"SELECT min(CAST(field_0 AS Int64) + CAST(field_1 AS Int64)) RANGE '5m' FILL LINEAR FROM test ALIGN '1h' by (tag_0,tag_1);"#;
1514        let expected = String::from(
1515            "RangeSelect: range_exprs=[min(arrow_cast(test.field_0,Utf8(\"Int64\")) + arrow_cast(test.field_1,Utf8(\"Int64\"))) RANGE 5m FILL LINEAR], align=3600000ms, align_to=0ms, align_by=[test.tag_0, test.tag_1], time_index=timestamp [min(arrow_cast(test.field_0,Utf8(\"Int64\")) + arrow_cast(test.field_1,Utf8(\"Int64\"))) RANGE 5m FILL LINEAR:Float64;N]\
1516            \n  Projection: test.tag_0, test.tag_1, test.timestamp, test.field_0, test.field_1 [tag_0:Utf8, tag_1:Utf8, timestamp:Timestamp(ms), field_0:Float64;N, field_1:Float64;N]\
1517            \n    TableScan: test [tag_0:Utf8, tag_1:Utf8, tag_2:Utf8, tag_3:Utf8, tag_4:Utf8, timestamp:Timestamp(ms), field_0:Float64;N, field_1:Float64;N, field_2:Float64;N, field_3:Float64;N, field_4:Float64;N]",
1518        );
1519        query_plan_compare(query, expected).await;
1520    }
1521
1522    #[tokio::test]
1523    async fn range_nest_range_err() {
1524        let query = r#"SELECT sum(avg(field_0 + field_1) RANGE '5m' + 1) RANGE '5m' + 1 FROM test ALIGN '1h' by (tag_0,tag_1);"#;
1525        assert_eq!(
1526            do_query(query).await.unwrap_err().to_string(),
1527            "Failed to plan SQL"
1528        )
1529    }
1530
1531    #[tokio::test]
1532    /// Start directly from the rewritten SQL and check whether the error reported by the range expression rewriting is as expected.
1533    /// the right argument is `range_fn(avg(field_0), '5m', 'NULL', '0', '1h')`
1534    async fn range_argument_err_1() {
1535        let query = r#"SELECT range_fn('5m', avg(field_0), 'NULL', '1', tag_0, '1h') FROM test group by tag_0;"#;
1536        let error = do_query(query).await.unwrap_err().to_string();
1537        assert_eq!(
1538            error,
1539            "Error during planning: Illegal argument `Utf8(\"5m\")` in range select query"
1540        )
1541    }
1542
1543    #[tokio::test]
1544    async fn range_argument_err_2() {
1545        let query = r#"SELECT range_fn(avg(field_0), 5, 'NULL', '1', tag_0, '1h') FROM test group by tag_0;"#;
1546        let error = do_query(query).await.unwrap_err().to_string();
1547        assert_eq!(
1548            error,
1549            "Error during planning: Illegal argument `Int64(5)` in range select query"
1550        )
1551    }
1552
1553    #[test]
1554    fn qbs_timestamp_submillisecond_uses_floor() {
1555        let assert_timestamp_millis = |timestamp: ScalarValue, expected: i64| {
1556            let args = vec![timestamp.lit()];
1557            assert_eq!(
1558                evaluate_expr_to_millisecond(&args, 0, false, None).unwrap(),
1559                expected
1560            );
1561            assert_eq!(parse_align_to(&args, 0, None, None).unwrap(), expected);
1562        };
1563
1564        assert_timestamp_millis(ScalarValue::TimestampNanosecond(Some(-1), None), -1);
1565        assert_timestamp_millis(ScalarValue::TimestampMicrosecond(Some(-1), None), -1);
1566        assert_timestamp_millis(ScalarValue::TimestampNanosecond(Some(999_999), None), 0);
1567        assert_timestamp_millis(ScalarValue::TimestampMicrosecond(Some(999), None), 0);
1568        assert_timestamp_millis(
1569            ScalarValue::TimestampNanosecond(Some(-NANOS_PER_MILLI), None),
1570            -1,
1571        );
1572        assert_timestamp_millis(ScalarValue::TimestampMicrosecond(Some(-1_000), None), -1);
1573    }
1574
1575    #[test]
1576    fn qbs_second_to_millisecond_safe_thresholds() {
1577        let max_safe_seconds = i64::MAX / 1_000;
1578        let min_safe_seconds = i64::MIN / 1_000;
1579
1580        for seconds in [min_safe_seconds, max_safe_seconds] {
1581            let expected = seconds * 1_000;
1582            let args = vec![ScalarValue::TimestampSecond(Some(seconds), None).lit()];
1583            assert_eq!(
1584                evaluate_expr_to_millisecond(&args, 0, false, None).unwrap(),
1585                expected
1586            );
1587
1588            let args = vec![ScalarValue::DurationSecond(Some(seconds)).lit()];
1589            assert_eq!(
1590                evaluate_expr_to_millisecond(&args, 0, false, None).unwrap(),
1591                expected
1592            );
1593        }
1594    }
1595
1596    fn assert_millisecond_overflow(result: DFResult<i64>, source_expr: &Expr) {
1597        let error = result.unwrap_err();
1598        let DataFusionError::Plan(message) = error else {
1599            panic!("expected a plan error");
1600        };
1601        assert!(message.contains("overflow"));
1602        let source_expr_name = source_expr.schema_name().to_string();
1603        assert!(message.contains(&source_expr_name));
1604    }
1605
1606    #[test]
1607    fn qbs_second_to_millisecond_timestamp_positive_overflow_is_error() {
1608        let args = vec![ScalarValue::TimestampSecond(Some(i64::MAX / 1_000 + 1), None).lit()];
1609        assert_millisecond_overflow(
1610            evaluate_expr_to_millisecond(&args, 0, false, None),
1611            &args[0],
1612        );
1613    }
1614
1615    #[test]
1616    fn qbs_second_to_millisecond_timestamp_negative_overflow_is_error() {
1617        let args = vec![ScalarValue::TimestampSecond(Some(i64::MIN / 1_000 - 1), None).lit()];
1618        assert_millisecond_overflow(
1619            evaluate_expr_to_millisecond(&args, 0, false, None),
1620            &args[0],
1621        );
1622    }
1623
1624    #[test]
1625    fn qbs_second_to_millisecond_duration_positive_overflow_is_error() {
1626        let args = vec![ScalarValue::DurationSecond(Some(i64::MAX / 1_000 + 1)).lit()];
1627        assert_millisecond_overflow(
1628            evaluate_expr_to_millisecond(&args, 0, false, None),
1629            &args[0],
1630        );
1631    }
1632
1633    #[test]
1634    fn qbs_second_to_millisecond_duration_negative_overflow_is_error() {
1635        let args = vec![ScalarValue::DurationSecond(Some(i64::MIN / 1_000 - 1)).lit()];
1636        assert_millisecond_overflow(
1637            evaluate_expr_to_millisecond(&args, 0, false, None),
1638            &args[0],
1639        );
1640    }
1641
1642    #[test]
1643    fn qbs_duration_submillisecond_contract() {
1644        // Arrow Duration literals are not accepted by the public interval-only parser.
1645        let args = vec![ScalarValue::DurationNanosecond(Some(-1)).lit()];
1646        assert!(parse_duration_expr(&args, 0).is_err());
1647        let args = vec![ScalarValue::DurationNanosecond(Some(999_999)).lit()];
1648        assert!(parse_duration_expr(&args, 0).is_err());
1649        let args = vec![ScalarValue::DurationNanosecond(Some(NANOS_PER_MILLI)).lit()];
1650        assert!(parse_duration_expr(&args, 0).is_err());
1651
1652        let args = vec!["1ms".lit()];
1653        assert_eq!(
1654            parse_duration_expr(&args, 0).unwrap(),
1655            Duration::from_millis(1)
1656        );
1657
1658        let args = vec![
1659            ScalarValue::IntervalMonthDayNano(Some(IntervalMonthDayNano::new(0, 0, -1).into()))
1660                .lit(),
1661        ];
1662        assert!(parse_duration_expr(&args, 0).is_err());
1663        let args = vec![
1664            ScalarValue::IntervalMonthDayNano(Some(
1665                IntervalMonthDayNano::new(0, 0, 999_999).into(),
1666            ))
1667            .lit(),
1668        ];
1669        assert!(parse_duration_expr(&args, 0).is_err());
1670        let args = vec![
1671            ScalarValue::IntervalMonthDayNano(Some(
1672                IntervalMonthDayNano::new(0, 0, NANOS_PER_MILLI).into(),
1673            ))
1674            .lit(),
1675        ];
1676        assert_eq!(
1677            parse_duration_expr(&args, 0).unwrap(),
1678            Duration::from_millis(1)
1679        );
1680
1681        let args = vec![
1682            ScalarValue::IntervalMonthDayNano(Some(IntervalMonthDayNano::new(0, 1, -1).into()))
1683                .lit(),
1684        ];
1685        assert_eq!(
1686            parse_duration_expr(&args, 0).unwrap(),
1687            Duration::from_millis(MS_PER_DAY as u64 - 1)
1688        );
1689        let args = vec![
1690            ScalarValue::IntervalMonthDayNano(Some(
1691                IntervalMonthDayNano::new(0, 1, 999_999).into(),
1692            ))
1693            .lit(),
1694        ];
1695        assert_eq!(
1696            parse_duration_expr(&args, 0).unwrap(),
1697            Duration::from_millis(MS_PER_DAY as u64)
1698        );
1699    }
1700
1701    #[test]
1702    fn test_parse_duration_expr() {
1703        // test IntervalYearMonth
1704        let interval = IntervalYearMonth::new(10);
1705        let args = vec![ScalarValue::IntervalYearMonth(Some(interval.to_i32())).lit()];
1706        assert!(parse_duration_expr(&args, 0).is_err(),);
1707        // test IntervalDayTime
1708        let interval = IntervalDayTime::new(10, 10);
1709        let args = vec![ScalarValue::IntervalDayTime(Some(interval.into())).lit()];
1710        assert_eq!(
1711            parse_duration_expr(&args, 0).unwrap().as_millis() as i64,
1712            interval.as_millis()
1713        );
1714        // test IntervalMonthDayNano
1715        let interval = IntervalMonthDayNano::new(0, 10, 10);
1716        let args = vec![ScalarValue::IntervalMonthDayNano(Some(interval.into())).lit()];
1717        assert_eq!(
1718            parse_duration_expr(&args, 0).unwrap().as_millis() as i64,
1719            interval.days as i64 * MS_PER_DAY + interval.nanoseconds.div_euclid(NANOS_PER_MILLI),
1720        );
1721        // test Duration
1722        let args = vec!["1y4w".lit()];
1723        assert_eq!(
1724            parse_duration_expr(&args, 0).unwrap(),
1725            parse_duration("1y4w").unwrap()
1726        );
1727        // test cast expression
1728        let args = vec![Expr::Cast(Cast::new(
1729            Box::new("15 minutes".lit()),
1730            DataType::Interval(IntervalUnit::MonthDayNano),
1731        ))];
1732        assert_eq!(
1733            parse_duration_expr(&args, 0).unwrap(),
1734            parse_duration("15m").unwrap()
1735        );
1736        // test index err
1737        assert!(parse_duration_expr(&args, 10).is_err());
1738        // test evaluate expr
1739        let args = vec![Expr::BinaryExpr(BinaryExpr {
1740            left: Box::new(
1741                ScalarValue::IntervalDayTime(Some(IntervalDayTime::new(0, 10).into())).lit(),
1742            ),
1743            op: Operator::Plus,
1744            right: Box::new(
1745                ScalarValue::IntervalDayTime(Some(IntervalDayTime::new(0, 10).into())).lit(),
1746            ),
1747        })];
1748        assert_eq!(
1749            parse_duration_expr(&args, 0).unwrap(),
1750            Duration::from_millis(20)
1751        );
1752        let args = vec![Expr::BinaryExpr(BinaryExpr {
1753            left: Box::new(
1754                ScalarValue::IntervalDayTime(Some(IntervalDayTime::new(0, 10).into())).lit(),
1755            ),
1756            op: Operator::Minus,
1757            right: Box::new(
1758                ScalarValue::IntervalDayTime(Some(IntervalDayTime::new(0, 10).into())).lit(),
1759            ),
1760        })];
1761        // test zero interval error
1762        assert!(parse_duration_expr(&args, 0).is_err());
1763        // test must all be interval
1764        let args = vec![Expr::BinaryExpr(BinaryExpr {
1765            left: Box::new(
1766                ScalarValue::IntervalYearMonth(Some(IntervalYearMonth::new(10).to_i32())).lit(),
1767            ),
1768            op: Operator::Minus,
1769            right: Box::new(ScalarValue::Time64Microsecond(Some(0)).lit()),
1770        })];
1771        assert!(parse_duration_expr(&args, 0).is_err());
1772    }
1773
1774    #[test]
1775    fn test_parse_align_to() {
1776        // test NOW
1777        let args = vec!["NOW".lit()];
1778        let epsinon =
1779            parse_align_to(&args, 0, None, None).unwrap() - Timestamp::current_millis().value();
1780        assert!(epsinon.abs() < 100);
1781        let scheduled_time = DateTime::from_timestamp(1_700_000_000, 123_000_000).unwrap();
1782        assert_eq!(
1783            scheduled_time.timestamp_millis(),
1784            parse_align_to(&args, 0, None, Some(scheduled_time)).unwrap()
1785        );
1786        // test default
1787        let args = vec!["".lit()];
1788        assert_eq!(0, parse_align_to(&args, 0, None, None).unwrap());
1789        // test default with timezone
1790        let args = vec!["".lit()];
1791        assert_eq!(
1792            -36000 * 1000,
1793            parse_align_to(
1794                &args,
1795                0,
1796                Some(&Timezone::from_tz_string("HST").unwrap()),
1797                None
1798            )
1799            .unwrap()
1800        );
1801        assert_eq!(
1802            28800 * 1000,
1803            parse_align_to(
1804                &args,
1805                0,
1806                Some(&Timezone::from_tz_string("Asia/Shanghai").unwrap()),
1807                None
1808            )
1809            .unwrap()
1810        );
1811
1812        // test Timestamp
1813        let args = vec!["1970-01-01T00:00:00+08:00".lit()];
1814        assert_eq!(
1815            parse_align_to(&args, 0, None, None).unwrap(),
1816            -8 * 60 * 60 * 1000
1817        );
1818        // timezone
1819        let args = vec!["1970-01-01T00:00:00".lit()];
1820        assert_eq!(
1821            parse_align_to(
1822                &args,
1823                0,
1824                Some(&Timezone::from_tz_string("Asia/Shanghai").unwrap()),
1825                None
1826            )
1827            .unwrap(),
1828            -8 * 60 * 60 * 1000
1829        );
1830        // test evaluate expr
1831        let args = vec![Expr::BinaryExpr(BinaryExpr {
1832            left: Box::new(
1833                ScalarValue::IntervalDayTime(Some(IntervalDayTime::new(0, 10).into())).lit(),
1834            ),
1835            op: Operator::Plus,
1836            right: Box::new(
1837                ScalarValue::IntervalDayTime(Some(IntervalDayTime::new(0, 10).into())).lit(),
1838            ),
1839        })];
1840        assert_eq!(parse_align_to(&args, 0, None, None).unwrap(), 20);
1841    }
1842
1843    #[test]
1844    fn test_interval_only() {
1845        let expr = Expr::BinaryExpr(BinaryExpr {
1846            left: Box::new(ScalarValue::DurationMillisecond(Some(20)).lit()),
1847            op: Operator::Minus,
1848            right: Box::new(
1849                ScalarValue::IntervalDayTime(Some(IntervalDayTime::new(10, 0).into())).lit(),
1850            ),
1851        });
1852        assert!(!interval_only_in_expr(&expr));
1853        let expr = Expr::BinaryExpr(BinaryExpr {
1854            left: Box::new(
1855                ScalarValue::IntervalDayTime(Some(IntervalDayTime::new(10, 0).into())).lit(),
1856            ),
1857            op: Operator::Minus,
1858            right: Box::new(
1859                ScalarValue::IntervalDayTime(Some(IntervalDayTime::new(10, 0).into())).lit(),
1860            ),
1861        });
1862        assert!(interval_only_in_expr(&expr));
1863
1864        let expr = Expr::BinaryExpr(BinaryExpr {
1865            left: Box::new(Expr::Cast(Cast::new(
1866                Box::new("15 minute".lit()),
1867                DataType::Interval(IntervalUnit::MonthDayNano),
1868            ))),
1869            op: Operator::Minus,
1870            right: Box::new(
1871                ScalarValue::IntervalDayTime(Some(IntervalDayTime::new(10, 0).into())).lit(),
1872            ),
1873        });
1874        assert!(interval_only_in_expr(&expr));
1875
1876        let expr = Expr::Cast(Cast::new(
1877            Box::new(Expr::BinaryExpr(BinaryExpr {
1878                left: Box::new(Expr::Cast(Cast::new(
1879                    Box::new("15 minute".lit()),
1880                    DataType::Interval(IntervalUnit::MonthDayNano),
1881                ))),
1882                op: Operator::Minus,
1883                right: Box::new(
1884                    ScalarValue::IntervalDayTime(Some(IntervalDayTime::new(10, 0).into())).lit(),
1885                ),
1886            })),
1887            DataType::Interval(IntervalUnit::MonthDayNano),
1888        ));
1889
1890        assert!(interval_only_in_expr(&expr));
1891    }
1892}