mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-12-01 07:04:09 +00:00
feat(promql): answer aliased TQL statements natively (#10669)
* feat(promql): answer aliased TQL statements natively `TQL EVAL ... AS name` (also used by CREATE FLOW) wraps the expression in an alias extension that the native compiler rejected, so these statements always fell back with `no_kernel_for_the_statement_shape`. The native route now offers the aliased expression and projects its rows into the layout the existing planner publishes: the value column under the alias, the labels, then the time index, with no metric name column. Labels follow the existing planner's order: a `by(...)` list keeps the order it names, `without(...)` sorts the rest, and a binary operation follows its vector operand. An alias over more than one value column fails with the same error the existing planner reports. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * fix(promql): take the aliased label order from the existing planner The alias layout guessed the existing planner's label order from the root's shape, which is wrong for `topk by(...)` (keeps its input's order), `count_values` (appends its label after the grouping), and any call or unary wrapper around a `by(...)` aggregate. The order is a by-product of planning the expression (`ctx.tag_columns`), so plan the aliased expression on the existing path with the native route off and project the native answer into that layout. A native answer whose label set differs from it declines, and the multi-value error now comes from the same field count the existing planner checks. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * fix(promql): fall back when a native output column name collides Signed-off-by: Dennis Zhuang <killme2008@gmail.com> --------- Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
This commit is contained in:
@@ -58,15 +58,6 @@ pub enum Error {
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display(
|
||||
"duplicate native PromQL output column name(s): {names}; time index, value and tag columns must have distinct names"
|
||||
))]
|
||||
DuplicateOutputColumns {
|
||||
names: String,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Unexpected plan or expression: {}", desc))]
|
||||
UnexpectedPlanExpr {
|
||||
desc: String,
|
||||
@@ -298,8 +289,7 @@ impl ErrorExt for Error {
|
||||
| AtModifierTimestampOutOfRange { .. }
|
||||
| InvalidRegularExpression { .. }
|
||||
| InvalidDestinationLabelName { .. }
|
||||
| InvalidLabelName { .. }
|
||||
| DuplicateOutputColumns { .. } => StatusCode::InvalidArguments,
|
||||
| InvalidLabelName { .. } => StatusCode::InvalidArguments,
|
||||
|
||||
UnknownTable { .. } => StatusCode::Internal,
|
||||
|
||||
|
||||
@@ -397,7 +397,7 @@ impl PromPlanner {
|
||||
// expression has already been split into the nodes those functions would have shared. A
|
||||
// shape it does not accept is planned by the existing path exactly as if it were not here.
|
||||
if let Some(plan) = planner
|
||||
.try_plan_native_fused(&stmt.expr, query_engine_state)
|
||||
.try_plan_native_statement(&stmt.expr, query_engine_state)
|
||||
.await?
|
||||
{
|
||||
return planner.strip_tsid_column(plan);
|
||||
|
||||
@@ -33,10 +33,12 @@ use common_query::native_histogram::native_histogram_value_type;
|
||||
use common_query::series_frame::raw_series_frame_schema_with_ordering;
|
||||
use common_telemetry::debug;
|
||||
use datafusion::arrow::datatypes::DataType as ArrowDataType;
|
||||
use datafusion::common::{DFSchema, DFSchemaRef};
|
||||
use datafusion::common::{Column, DFSchema, DFSchemaRef};
|
||||
use datafusion::error::DataFusionError;
|
||||
use datafusion::logical_expr::UserDefinedLogicalNode;
|
||||
use datafusion::logical_expr::{EmptyRelation, Extension, LogicalPlan, TableScanBuilder, Union};
|
||||
use datafusion::logical_expr::{
|
||||
EmptyRelation, Extension, LogicalPlan, LogicalPlanBuilder, TableScanBuilder, Union,
|
||||
};
|
||||
use datafusion::physical_plan::ExecutionPlan;
|
||||
use datafusion::prelude::Expr as DfExpr;
|
||||
use datafusion_expr::Expr;
|
||||
@@ -69,11 +71,14 @@ use promql_parser::parser::{
|
||||
EvalStmt, Expr as PromExpr, MatrixSelector, ParenExpr, SubqueryExpr, VectorSelector,
|
||||
};
|
||||
use session::context::{MetricDiscoveryScope, QueryContextRef};
|
||||
use snafu::{ResultExt, ensure};
|
||||
use snafu::{OptionExt, ResultExt, ensure};
|
||||
use store_api::metric_engine_consts::{DATA_SCHEMA_TABLE_ID_COLUMN_NAME, METRIC_ENGINE_NAME};
|
||||
use store_api::region_engine::RawLabelSource;
|
||||
|
||||
use crate::promql::error::{DataFusionPlanningSnafu, DuplicateOutputColumnsSnafu, Result};
|
||||
use crate::parser::AliasExpr;
|
||||
use crate::promql::error::{
|
||||
DataFusionPlanningSnafu, Result, TimeIndexNotFoundSnafu, UnsupportedExprSnafu,
|
||||
};
|
||||
use crate::promql::native_compile::{
|
||||
InfoInput, bind_evaluated_binary, compile_selectors_with_grid, compile_statement_with_grid,
|
||||
info_input, statement_grid, subquery_child_grid,
|
||||
@@ -427,6 +432,80 @@ impl PromPlanner {
|
||||
)))
|
||||
}
|
||||
|
||||
/// Offers a statement root to the native route, including a TQL `AS` alias over the expression
|
||||
/// it names.
|
||||
///
|
||||
/// An alias is not a PromQL shape: it renames the answer's one value column. So the aliased
|
||||
/// expression is offered, and its rows are laid out the way the existing planner's
|
||||
/// `apply_alias` publishes them - the value under the alias, then the labels, then the time
|
||||
/// index - which a flow sinking the answer into a table relies on.
|
||||
pub(super) async fn try_plan_native_statement(
|
||||
&mut self,
|
||||
prom_expr: &PromExpr,
|
||||
query_engine_state: &QueryEngineState,
|
||||
) -> Result<Option<LogicalPlan>> {
|
||||
let alias = match prom_expr {
|
||||
PromExpr::Extension(extension) => extension.expr.as_any().downcast_ref::<AliasExpr>(),
|
||||
_ => None,
|
||||
};
|
||||
let Some(alias) = alias else {
|
||||
return self
|
||||
.try_plan_native_fused(prom_expr, query_engine_state)
|
||||
.await;
|
||||
};
|
||||
let statement_ctx = self.ctx.clone();
|
||||
let Some(plan) = self
|
||||
.try_plan_native_fused(&alias.expr, query_engine_state)
|
||||
.await?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
// The label order of the existing layout is a by-product of planning the whole expression
|
||||
// (`ctx.tag_columns`), not a rule that can be read off its shape: `by(...)` keeps the order
|
||||
// it names, `topk by(...)` keeps its input's, `count_values` appends its label, and a wrapper
|
||||
// keeps whatever it wraps. So the existing planner is asked, with the native route off so
|
||||
// that it does not answer itself.
|
||||
let native_ctx = std::mem::replace(&mut self.ctx, statement_ctx.clone());
|
||||
let native_fused = std::mem::replace(&mut self.native_fused, false);
|
||||
let existing = self
|
||||
.prom_expr_to_plan(&alias.expr, query_engine_state)
|
||||
.await
|
||||
.map(|_| {
|
||||
(
|
||||
std::mem::take(&mut self.ctx.field_columns),
|
||||
std::mem::take(&mut self.ctx.tag_columns),
|
||||
self.ctx.time_index_column.take(),
|
||||
)
|
||||
});
|
||||
self.native_fused = native_fused;
|
||||
self.ctx = native_ctx;
|
||||
let (fields, labels, time) = existing?;
|
||||
ensure!(
|
||||
fields.len() == 1,
|
||||
UnsupportedExprSnafu {
|
||||
name: "alias on multi-value result"
|
||||
}
|
||||
);
|
||||
let time = time.context(TimeIndexNotFoundSnafu {
|
||||
table: statement_ctx.table_name.clone().unwrap_or_default(),
|
||||
})?;
|
||||
match aliased_rows(plan, &alias.alias, &labels, &time)? {
|
||||
Some(plan) => Ok(Some(plan)),
|
||||
None => {
|
||||
// The existing plan reports a different label set, so only it can answer in its own
|
||||
// layout.
|
||||
self.ctx = statement_ctx;
|
||||
let reason = "alias_labels_differ_from_existing_plan";
|
||||
crate::metrics::NATIVE_PROMQL_DECLINED_TOTAL
|
||||
.with_label_values(&[reason])
|
||||
.inc();
|
||||
#[cfg(test)]
|
||||
REPORTED_DECLINE.with(|reported| reported.set(Some(reason)));
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn try_plan_native_fused(
|
||||
&mut self,
|
||||
prom_expr: &PromExpr,
|
||||
@@ -763,13 +842,19 @@ impl PromPlanner {
|
||||
};
|
||||
// A data-free tree reads no input, so every field it answers is a float.
|
||||
let output_schema = match format {
|
||||
FusedOutputFormat::PlainRows => fused_output_schema(
|
||||
&expression,
|
||||
&values,
|
||||
&with_row_name_column(tree.root(), output_tags.clone()),
|
||||
&time_index,
|
||||
FieldKind::Float,
|
||||
)?,
|
||||
FusedOutputFormat::PlainRows => {
|
||||
let Some(schema) = fused_output_schema(
|
||||
&expression,
|
||||
&values,
|
||||
&with_row_name_column(tree.root(), output_tags.clone()),
|
||||
&time_index,
|
||||
FieldKind::Float,
|
||||
)?
|
||||
else {
|
||||
return Ok(declined("output_column_names_collide"));
|
||||
};
|
||||
schema
|
||||
}
|
||||
FusedOutputFormat::SeriesFrame => {
|
||||
let frame =
|
||||
FusedSeries::series_frame_schema(&tree).context(DataFusionPlanningSnafu)?;
|
||||
@@ -1595,7 +1680,12 @@ impl PromPlanner {
|
||||
}
|
||||
let output_schema = match format {
|
||||
FusedOutputFormat::PlainRows => {
|
||||
fused_output_schema(&expression, &root_fields, &output_tags, &time, root_kind)?
|
||||
let Some(schema) =
|
||||
fused_output_schema(&expression, &root_fields, &output_tags, &time, root_kind)?
|
||||
else {
|
||||
return Ok(declined("output_column_names_collide"));
|
||||
};
|
||||
schema
|
||||
}
|
||||
FusedOutputFormat::SeriesFrame => {
|
||||
let frame =
|
||||
@@ -1640,8 +1730,8 @@ impl PromPlanner {
|
||||
|
||||
/// The columns a [`FusedSeries`] node over `tree` produces.
|
||||
///
|
||||
/// `Ok(None)` when the root is not a value the node can publish or its tags cannot be derived.
|
||||
/// Duplicate column names are an error, not a decline.
|
||||
/// `Ok(None)` when the root is not a value the node can publish, its tags cannot be derived, or
|
||||
/// two of its columns share a name.
|
||||
fn fused_root_schema(
|
||||
expression: &str,
|
||||
tree: &NativeTree,
|
||||
@@ -1664,7 +1754,7 @@ impl PromPlanner {
|
||||
};
|
||||
// `root_kind` comes from the uncut tree: after segmentation an input leaf no longer shows
|
||||
// that `count_over_time(h[5m])` turned histograms into floats.
|
||||
fused_output_schema(expression, &root_fields, &output_tags, time, root_kind).map(Some)
|
||||
fused_output_schema(expression, &root_fields, &output_tags, time, root_kind)
|
||||
}
|
||||
|
||||
/// The rows layout a segmented statement root publishes, under the segment builders' callback.
|
||||
@@ -1812,6 +1902,58 @@ fn epoch_millis(millis: i64) -> Option<SystemTime> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Projects a native rows answer into the layout of an aliased statement: the value column under
|
||||
/// `alias`, then `labels` in the order the existing planner reports them, then the time index under
|
||||
/// the existing planner's name `time`.
|
||||
///
|
||||
/// A rows layout is the time index, the value columns, the labels as strings and the metric name
|
||||
/// last; the existing planner publishes no metric name for an alias. `None` when the answer's labels
|
||||
/// are not exactly `labels`, as a layout with a label missing or added is not the existing one.
|
||||
fn aliased_rows(
|
||||
plan: LogicalPlan,
|
||||
alias: &str,
|
||||
labels: &[String],
|
||||
time: &str,
|
||||
) -> Result<Option<LogicalPlan>> {
|
||||
let mut columns = plan
|
||||
.schema()
|
||||
.iter()
|
||||
.filter(|(_, field)| field.name() != METRIC_NAME)
|
||||
.map(|(qualifier, field)| Column::from((qualifier, field)));
|
||||
let Some(native_time) = columns.next() else {
|
||||
return Err(DataFusionError::Plan(
|
||||
"a native rows answer has no time index".to_string(),
|
||||
))
|
||||
.context(DataFusionPlanningSnafu);
|
||||
};
|
||||
let (label_columns, values): (Vec<_>, Vec<_>) =
|
||||
columns.partition(|column| labels.contains(&column.name));
|
||||
// An answer column that is not one of `labels` is a value or a label the existing plan lacks,
|
||||
// so anything but one such column is a layout the existing plan does not report.
|
||||
let [value] = values.as_slice() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(label_columns) = labels
|
||||
.iter()
|
||||
.map(|label| label_columns.iter().find(|column| &column.name == label))
|
||||
.collect::<Option<Vec<_>>>()
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let projection = std::iter::once(DfExpr::Column(value.clone()).alias(alias))
|
||||
.chain(
|
||||
label_columns
|
||||
.into_iter()
|
||||
.map(|column| DfExpr::Column(column.clone())),
|
||||
)
|
||||
.chain(std::iter::once(DfExpr::Column(native_time).alias(time)));
|
||||
LogicalPlanBuilder::from(plan)
|
||||
.project(projection)
|
||||
.and_then(LogicalPlanBuilder::build)
|
||||
.map(Some)
|
||||
.context(DataFusionPlanningSnafu)
|
||||
}
|
||||
|
||||
/// Finds a subquery at the statement root, treating parentheses as transparent.
|
||||
fn root_subquery(expr: &PromExpr) -> Option<&SubqueryExpr> {
|
||||
match expr {
|
||||
@@ -1871,38 +2013,27 @@ fn free_time_index(time_index: &str, value_names: &[String], tags: &[String]) ->
|
||||
/// tags.
|
||||
///
|
||||
/// Values are named by [`expression_field_names`]; the layout is
|
||||
/// [`segment::fused_output_schema`]'s. Errors with the colliding names when a column name repeats.
|
||||
/// [`segment::fused_output_schema`]'s. `None` when a column name repeats: a value is named after
|
||||
/// the expression, which can be the time index's or a tag's name, while the existing plan names
|
||||
/// its value after the field and answers such a statement.
|
||||
fn fused_output_schema(
|
||||
expression: &str,
|
||||
fields: &[String],
|
||||
tags: &[String],
|
||||
time_index: &str,
|
||||
field_kind: FieldKind,
|
||||
) -> Result<DFSchemaRef> {
|
||||
) -> Result<Option<DFSchemaRef>> {
|
||||
let value_names = expression_field_names(expression, fields);
|
||||
// Detected here because `DFSchema`'s own error does not name the columns.
|
||||
let mut names = Vec::with_capacity(value_names.len() + tags.len() + 1);
|
||||
names.push(time_index.to_string());
|
||||
names.extend(value_names.iter().cloned());
|
||||
names.extend(tags.iter().cloned());
|
||||
let mut occurrences: std::collections::HashMap<&str, usize> =
|
||||
std::collections::HashMap::with_capacity(names.len());
|
||||
for name in &names {
|
||||
*occurrences.entry(name.as_str()).or_default() += 1;
|
||||
let mut names = std::collections::HashSet::with_capacity(value_names.len() + tags.len() + 1);
|
||||
let distinct = std::iter::once(time_index)
|
||||
.chain(value_names.iter().map(String::as_str))
|
||||
.chain(tags.iter().map(String::as_str))
|
||||
.all(|name| names.insert(name));
|
||||
if !distinct {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut reported = std::collections::HashSet::new();
|
||||
let duplicates = names
|
||||
.iter()
|
||||
.filter(|name| occurrences[name.as_str()] > 1 && reported.insert(name.as_str()))
|
||||
.map(String::as_str)
|
||||
.collect::<Vec<_>>();
|
||||
ensure!(
|
||||
duplicates.is_empty(),
|
||||
DuplicateOutputColumnsSnafu {
|
||||
names: duplicates.join(", ")
|
||||
}
|
||||
);
|
||||
segment::fused_output_schema(&value_names, tags, time_index, field_kind)
|
||||
.map(Some)
|
||||
.context(DataFusionPlanningSnafu)
|
||||
}
|
||||
|
||||
@@ -3049,10 +3180,9 @@ mod tests {
|
||||
|
||||
/// The value columns are named after the expression, so a tree whose own field is named
|
||||
/// `__name__` still publishes that value under the expression's name - the name column is the
|
||||
/// layout's own. A time index of that name collides with it, and the collision is reported
|
||||
/// rather than published as a layout the reader cannot address.
|
||||
/// layout's own. A time index of that name collides with it, which is no layout to publish.
|
||||
#[test]
|
||||
fn a_time_index_named_after_the_metric_name_is_reported() {
|
||||
fn a_time_index_named_after_the_metric_name_collides() {
|
||||
let sources = [vec!["host".to_string()]];
|
||||
// The field is renamed by the expression, so it no longer stands where the name column is.
|
||||
let tree = compiled_test_tree_with_fields("x", &[METRIC_NAME]);
|
||||
@@ -3067,14 +3197,13 @@ mod tests {
|
||||
.map(|field| field.name().as_str())
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
// A time index of that name collides with the row-name column, and the error names it.
|
||||
let tree = compiled_test_tree("x");
|
||||
let error =
|
||||
assert!(
|
||||
PromPlanner::fused_root_schema("x", &tree, &sources, METRIC_NAME, FieldKind::Float)
|
||||
.expect_err("a time index named after the metric collides with the name column");
|
||||
let message = error.to_string().to_lowercase();
|
||||
assert!(message.contains("duplicate"), "{message}");
|
||||
assert!(message.contains(METRIC_NAME), "{message}");
|
||||
.unwrap()
|
||||
.is_none(),
|
||||
"a time index named after the metric collides with the name column"
|
||||
);
|
||||
}
|
||||
|
||||
/// A `__name__` rewrite publishes a name column, canonicalizes the complete runtime label set,
|
||||
@@ -3257,6 +3386,7 @@ mod tests {
|
||||
"ts",
|
||||
FieldKind::Float,
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
vec![
|
||||
|
||||
@@ -6979,36 +6979,22 @@ async fn native_fused_cross_table_union_with_a_colliding_column_stays_native() {
|
||||
assert!(find_fused_series(&plan).is_some(), "{plan}");
|
||||
}
|
||||
|
||||
/// A value is named after the expression, so a bare selector whose metric shares the time index's or
|
||||
/// a tag's name declines and the existing plan, which names the value after its field, answers it.
|
||||
#[tokio::test]
|
||||
async fn native_fused_rejects_expression_names_that_collide_with_time_or_tag() {
|
||||
for (table, tags, time, field, query, column) in [
|
||||
("ts", Vec::<&str>::new(), "ts", "val", "ts", "ts"),
|
||||
("host", vec!["host"], "timestamp", "val", "host", "host"),
|
||||
async fn native_fused_declines_expression_names_that_collide_with_time_or_tag() {
|
||||
for (table, tags, time, field, query) in [
|
||||
("ts", Vec::<&str>::new(), "ts", "val", "ts"),
|
||||
("host", vec!["host"], "timestamp", "val", "host"),
|
||||
] {
|
||||
let provider = native_tables_provider(&[(table, &tags, time, field)]);
|
||||
let error = PromPlanner::stmt_to_plan_with_annotations(
|
||||
provider,
|
||||
&build_eval_stmt(query),
|
||||
&build_query_engine_state(),
|
||||
None,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.expect_err("the expression-derived value name collides with an output column");
|
||||
let message = error.to_string();
|
||||
// The collision is reported by name, not through the wrapped `DFSchema` refusal, whose
|
||||
// display says only that building the plan failed.
|
||||
assert!(
|
||||
!message.contains("Internal error"),
|
||||
"`{query}`: the error names the collision: {message}"
|
||||
);
|
||||
assert!(
|
||||
message.to_lowercase().contains("duplicate"),
|
||||
"`{query}`: {message}"
|
||||
);
|
||||
assert!(
|
||||
message.contains(column),
|
||||
"`{query}`: the error names the colliding column `{column}`: {message}"
|
||||
take_reported_decline();
|
||||
let plan = build_native_fused_plan_with_provider(query, true, provider).await;
|
||||
assert!(find_fused_series(&plan).is_none(), "`{query}`: {plan}");
|
||||
assert_eq!(
|
||||
Some("output_column_names_collide"),
|
||||
take_reported_decline(),
|
||||
"`{query}`"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ use api::v1::{
|
||||
};
|
||||
use common_base::Plugins;
|
||||
use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
|
||||
use common_error::ext::ErrorExt;
|
||||
use common_query::prelude::{GREPTIME_TEMPORALITY_DELTA, OTLP_AGGREGATION_TEMPORALITY_LABEL};
|
||||
use common_query::prometheus::PROMETHEUS_STALE_NAN_BITS;
|
||||
use common_query::{Output, OutputData};
|
||||
@@ -13980,6 +13981,123 @@ async fn native_promql_casts_integer_samples_before_folding() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A TQL `AS` alias is answered natively with the existing plan's columns: the value under the
|
||||
/// alias, the labels, then the time index, with no metric name column.
|
||||
///
|
||||
/// A flow that sinks a TQL answer into a table reads it by these column names, so the layout is
|
||||
/// compared column by column, while the rows are compared by value: native `count` answers floats
|
||||
/// where the existing plan answers integers.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn native_promql_answers_an_aliased_statement_in_the_existing_layout() {
|
||||
common_telemetry::init_default_ut_logging();
|
||||
let (standalone, observer) =
|
||||
native_test_instance(GreptimeDbStandaloneBuilder::new("native_promql_alias")).await;
|
||||
let instance = standalone.fe_instance().clone();
|
||||
execute_all(
|
||||
&instance,
|
||||
"CREATE TABLE alias_metric (k STRING, l STRING, ts TIMESTAMP(3) TIME INDEX, i DOUBLE, PRIMARY KEY (k, l)); \
|
||||
INSERT INTO alias_metric (k, l, ts, i) VALUES \
|
||||
('a', 'x', 0, 1), ('a', 'y', 0, 2), ('b', 'x', 0, 3), \
|
||||
('a', 'x', 5000, 4), ('a', 'y', 5000, 5), ('b', 'x', 5000, 6); \
|
||||
CREATE TABLE sensor_readings (`value` DOUBLE, ts TIMESTAMP(3) TIME INDEX, sensor STRING, loc STRING, PRIMARY KEY (sensor, loc)); \
|
||||
INSERT INTO sensor_readings VALUES (20, 0, 'test', 'A'), (30, 0, 'test', 'B'), (10, 0, 'other', 'A'); \
|
||||
CREATE TABLE alias_two (k STRING PRIMARY KEY, ts TIMESTAMP(3) TIME INDEX, a DOUBLE, b DOUBLE); \
|
||||
INSERT INTO alias_two VALUES ('a', 0, 1, 2); \
|
||||
CREATE TABLE ts (ts TIMESTAMP(3) TIME INDEX, val DOUBLE); \
|
||||
INSERT INTO ts VALUES (0, 1);",
|
||||
QueryContext::arc(),
|
||||
)
|
||||
.await;
|
||||
|
||||
// An alias names one value column, so a statement with two fails on both routes alike.
|
||||
let sql = "TQL EVAL (0, 10, '5s') alias_two AS v";
|
||||
let mut errors = Vec::new();
|
||||
for enabled in [true, false] {
|
||||
let output = instance
|
||||
.do_query(sql, native_query_context(enabled, 4))
|
||||
.await
|
||||
.remove(0);
|
||||
errors.push(output.map(|_| ()).unwrap_err().output_msg());
|
||||
}
|
||||
let [native, legacy] = <[String; 2]>::try_from(errors).unwrap();
|
||||
assert_eq!(native, legacy);
|
||||
assert!(native.contains("alias on multi-value result"), "{native}");
|
||||
|
||||
// Native names a value after the expression, here the time index's name, so it leaves these to
|
||||
// the existing plan, which names the value after its field.
|
||||
for sql in ["TQL EVAL (0, 0, '1s') ts AS v", "TQL EVAL (0, 0, '1s') ts"] {
|
||||
assert_eq!(
|
||||
native_output_text(native_tql_output(&instance, sql, true).await).await,
|
||||
native_output_text(native_tql_output(&instance, sql, false).await).await,
|
||||
"{sql}"
|
||||
);
|
||||
}
|
||||
|
||||
for query in [
|
||||
r#"{__name__="alias_metric"} AS test_series"#,
|
||||
"count by (k) (alias_metric) AS c",
|
||||
// `by` reports its labels in the order it names them.
|
||||
"sum by (l, k) (alias_metric) AS s",
|
||||
"2 * sum by (l, k) (alias_metric) AS s",
|
||||
"alias_metric * 2 AS doubled",
|
||||
// The existing order is not a property of the root alone: `topk by(...)` keeps its input's
|
||||
// order, `count_values` appends its label after the sorted `without` set, and a wrapper
|
||||
// keeps the order of the aggregate it wraps.
|
||||
"topk by (l) (1, alias_metric) AS t",
|
||||
r#"count_values without (l) ("a", alias_metric) AS c"#,
|
||||
"abs(sum by (l, k) (alias_metric)) AS s",
|
||||
// The two statements `flow_tql_avg` sinks into a table.
|
||||
"avg by(sensor) (sensor_readings) AS value",
|
||||
"(sum by(sensor) (sensor_readings) / count by(sensor) (sensor_readings)) AS value",
|
||||
] {
|
||||
let sql = format!("TQL EVAL (0, 10, '5s') {query}");
|
||||
observer.clear();
|
||||
let (native_columns, native) =
|
||||
native_columns_and_answer(native_tql_output(&instance, &sql, true).await).await;
|
||||
assert_eq!(
|
||||
Some("FusedSeriesExec".to_string()),
|
||||
observer.answering_node(),
|
||||
"`{query}` must answer from the fused node, not the existing plan"
|
||||
);
|
||||
let (legacy_columns, legacy) =
|
||||
native_columns_and_answer(native_tql_output(&instance, &sql, false).await).await;
|
||||
assert_eq!(native_columns, legacy_columns, "`{query}`: the columns");
|
||||
let values = |answer: &Answer| {
|
||||
answer
|
||||
.rows
|
||||
.iter()
|
||||
.map(|(time, labels, values)| {
|
||||
let values = values
|
||||
.iter()
|
||||
.map(|value| value.parse::<f64>().unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
(*time, labels.clone(), values)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(values(&native), values(&legacy), "`{query}`: the rows");
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a TQL answer's column names in order, beside the [`Answer`] it holds.
|
||||
async fn native_columns_and_answer(output: Output) -> (Vec<String>, Answer) {
|
||||
let batches = match output.data {
|
||||
OutputData::Stream(stream) => collect_batches(stream).await.unwrap(),
|
||||
OutputData::RecordBatches(batches) => batches,
|
||||
_ => unreachable!("TQL EVAL returns record batches"),
|
||||
};
|
||||
let columns = batches
|
||||
.schema()
|
||||
.column_schemas()
|
||||
.iter()
|
||||
.map(|column| column.name.clone())
|
||||
.collect();
|
||||
(
|
||||
columns,
|
||||
native_answer(Output::new_with_record_batches(batches)).await,
|
||||
)
|
||||
}
|
||||
|
||||
/// Enabling Narthex index maintenance must preserve the ordinary Parquet raw scan.
|
||||
/// Compare integer and float fields through native and legacy PromQL.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
|
||||
Reference in New Issue
Block a user