From 141bc0f612a8a66277b539282266a6fba02ae389 Mon Sep 17 00:00:00 2001 From: zxq <3322351820@qq.com> Date: Thu, 5 Nov 2026 22:49:04 +0800 Subject: [PATCH 1/2] Support PIVOT and UNPIVOT in the table model --- .../it/query/recent/IoTDBPivotIT.java | 713 ++++++++++++++++++ .../it/query/recent/IoTDBUnpivotIT.java | 522 +++++++++++++ .../jdbc/IoTDBTablePreparedStatement.java | 12 +- .../jdbc/IoTDBTablePreparedStatementTest.java | 18 + .../operator/process/UnpivotOperator.java | 205 +++++ .../plan/planner/TableOperatorGenerator.java | 23 + .../operator/process/UnpivotOperatorTest.java | 202 +++++ .../confignode/i18n/ConfigNodeMessages.java | 2 + .../confignode/i18n/ManagerMessages.java | 2 + .../confignode/i18n/ConfigNodeMessages.java | 2 + .../confignode/i18n/ManagerMessages.java | 2 + .../confignode/conf/ConfigNodeDescriptor.java | 68 ++ .../confignode/manager/ConfigManager.java | 30 + .../conf/PivotConfigNodeDescriptorTest.java | 63 ++ .../PivotConfigurationValidationTest.java | 57 ++ .../iotdb/db/i18n/DataNodeMiscMessages.java | 2 + .../iotdb/db/i18n/DataNodeQueryMessages.java | 57 ++ .../iotdb/db/i18n/DataNodeMiscMessages.java | 2 + .../iotdb/db/i18n/DataNodeQueryMessages.java | 57 ++ .../apache/iotdb/db/conf/IoTDBDescriptor.java | 66 ++ .../impl/DataNodeInternalRPCServiceImpl.java | 21 +- .../queryengine/common/MPPQueryContext.java | 108 +++ .../queryengine/common/PivotInputStore.java | 73 ++ .../db/queryengine/plan/Coordinator.java | 179 ++++- .../plan/execution/QueryExecution.java | 1 + .../plan/node/PlanGraphJsonPrinter.java | 4 + .../planner/plan/node/PlanGraphPrinter.java | 14 + .../plan/relational/analyzer/Analysis.java | 30 +- .../plan/relational/analyzer/Analyzer.java | 105 ++- .../relational/analyzer/PivotBinding.java | 69 ++ .../analyzer/PivotInputPreparer.java | 47 ++ .../analyzer/PivotLimitValidator.java | 51 ++ .../analyzer/StatementAnalyzer.java | 568 ++++++++++++++ .../relational/analyzer/UnpivotBinding.java | 74 ++ .../CoordinatorPivotInputPreparer.java | 457 +++++++++++ .../relational/planner/CteMaterializer.java | 4 +- .../relational/planner/RelationPlanner.java | 240 ++++++ .../relational/planner/TableModelPlanner.java | 3 +- .../TableDistributedPlanGenerator.java | 27 + .../PushAggregationIntoTableScan.java | 5 + .../PushLimitOffsetIntoTableScan.java | 8 + .../TransformSortToStreamSort.java | 8 + .../UnaliasSymbolReferences.java | 20 + .../sql/ast/DefaultTraversalVisitor.java | 14 + .../relational/sql/parser/AstBuilder.java | 117 +++ .../relational/type/UnpivotTypeUnifier.java | 53 ++ .../iotdb/db/conf/PivotConfigurationTest.java | 90 +++ .../common/MPPQueryContextTest.java | 93 +++ .../operator/CteScanOperatorTest.java | 2 +- .../relational/analyzer/AnalyzerTest.java | 191 +++++ .../CoordinatorPivotInputPreparerTest.java | 157 ++++ .../sql/parser/PivotUnpivotParserTest.java | 111 +++ .../type/PivotUnpivotTypeAndLimitTest.java | 72 ++ .../conf/iotdb-system.properties.template | 19 + .../iotdb/commons/conf/CommonConfig.java | 28 + .../plan/node/CommonPlanNodeDeserializer.java | 3 + .../plan/node/ICoreQueryPlanVisitor.java | 5 + .../plan/planner/plan/node/PlanNodeType.java | 1 + .../relational/planner/node/UnpivotNode.java | 212 ++++++ .../sql/ast/CommonQueryAstVisitor.java | 8 + .../relational/sql/ast/PivotRelation.java | 146 ++++ .../relational/sql/ast/UnpivotRelation.java | 155 ++++ .../sql/util/CommonQuerySqlFormatter.java | 140 ++++ .../queryengine/utils/cte/CteDataStore.java | 71 +- .../planner/node/UnpivotNodeTest.java | 75 ++ .../utils/cte/CteDataStoreBudgetTest.java | 72 ++ .../relational/grammar/sql/RelationalSql.g4 | 58 +- 67 files changed, 6054 insertions(+), 60 deletions(-) create mode 100644 integration-test/src/test/java/org/apache/iotdb/relational/it/query/recent/IoTDBPivotIT.java create mode 100644 integration-test/src/test/java/org/apache/iotdb/relational/it/query/recent/IoTDBUnpivotIT.java create mode 100644 iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/process/UnpivotOperator.java create mode 100644 iotdb-core/calc-commons/src/test/java/org/apache/iotdb/calc/execution/operator/process/UnpivotOperatorTest.java create mode 100644 iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/conf/PivotConfigNodeDescriptorTest.java create mode 100644 iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/manager/PivotConfigurationValidationTest.java create mode 100644 iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/common/PivotInputStore.java create mode 100644 iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/PivotBinding.java create mode 100644 iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/PivotInputPreparer.java create mode 100644 iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/PivotLimitValidator.java create mode 100644 iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/UnpivotBinding.java create mode 100644 iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/CoordinatorPivotInputPreparer.java create mode 100644 iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/type/UnpivotTypeUnifier.java create mode 100644 iotdb-core/datanode/src/test/java/org/apache/iotdb/db/conf/PivotConfigurationTest.java create mode 100644 iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/planner/CoordinatorPivotInputPreparerTest.java create mode 100644 iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/sql/parser/PivotUnpivotParserTest.java create mode 100644 iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/type/PivotUnpivotTypeAndLimitTest.java create mode 100644 iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/planner/node/UnpivotNode.java create mode 100644 iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/sql/ast/PivotRelation.java create mode 100644 iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/sql/ast/UnpivotRelation.java create mode 100644 iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/queryengine/plan/relational/planner/node/UnpivotNodeTest.java create mode 100644 iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/queryengine/utils/cte/CteDataStoreBudgetTest.java diff --git a/integration-test/src/test/java/org/apache/iotdb/relational/it/query/recent/IoTDBPivotIT.java b/integration-test/src/test/java/org/apache/iotdb/relational/it/query/recent/IoTDBPivotIT.java new file mode 100644 index 0000000000000..a569c03435aaa --- /dev/null +++ b/integration-test/src/test/java/org/apache/iotdb/relational/it/query/recent/IoTDBPivotIT.java @@ -0,0 +1,713 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.relational.it.query.recent; + +import org.apache.iotdb.it.env.EnvFactory; +import org.apache.iotdb.it.framework.IoTDBTestRunner; +import org.apache.iotdb.itbase.category.TableClusterIT; +import org.apache.iotdb.itbase.category.TableLocalStandaloneIT; +import org.apache.iotdb.itbase.runtime.ClusterTestConnection; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Locale; + +import static org.apache.iotdb.db.it.utils.TestUtils.tableResultSetEqualTest; +import static org.apache.iotdb.db.it.utils.TestUtils.tableResultSetEqualTestUnordered; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +@RunWith(IoTDBTestRunner.class) +@Category({TableLocalStandaloneIT.class, TableClusterIT.class}) +public class IoTDBPivotIT { + private static final String DATABASE = "pivot_it"; + + @BeforeClass + public static void setUp() throws Exception { + EnvFactory.getEnv().initClusterEnvironment(); + try (Connection connection = EnvFactory.getEnv().getTableConnection(); + Statement statement = connection.createStatement()) { + statement.execute("CREATE DATABASE " + DATABASE); + statement.execute("USE " + DATABASE); + statement.execute( + "CREATE TABLE readings (device STRING TAG, region STRING FIELD, " + + "status STRING FIELD, temp INT32 FIELD)"); + statement.execute( + "INSERT INTO readings (time,device,region,status,temp) VALUES " + + "(1,'d1','north','on',10),(2,'d1','south','off',20)," + + "(3,'d1',NULL,'on',30)"); + statement.execute("FLUSH"); + statement.execute( + "CREATE TABLE ranked (device STRING TAG, region STRING FIELD, temp INT32 FIELD)"); + statement.execute( + "INSERT INTO ranked (time,device,region,temp) VALUES " + + "(1,'d1','north',1),(2,'d2','north',2)," + + "(3,'d1','south',3),(4,'d2','south',5)"); + statement.execute("FLUSH"); + statement.execute( + "CREATE TABLE device_metrics (device_id STRING TAG, region STRING FIELD, " + + "status STRING FIELD, temperature DOUBLE FIELD, humidity DOUBLE FIELD)"); + statement.execute( + "INSERT INTO device_metrics " + + "(time,device_id,region,status,temperature,humidity) VALUES " + + "(0,'device_1','north','online',20.0,40.0)," + + "(1,'device_1','north','online',22.0,42.0)," + + "(2,'device_1','south','offline',30.0,50.0)," + + "(3,'device_1','south','offline',34.0,54.0)," + + "(4,'device_1',NULL,'online',26.0,46.0)," + + "(0,'device_2','north','offline',16.0,60.0)," + + "(1,'device_2','north','offline',18.0,62.0)," + + "(2,'device_2','south','offline',28.0,70.0)," + + "(3,'device_2','south','offline',32.0,NULL)," + + "(4,'device_2',NULL,'offline',24.0,66.0)"); + statement.execute("FLUSH"); + } + } + + @AfterClass + public static void tearDown() { + EnvFactory.getEnv().cleanClusterEnvironment(); + } + + @Test + public void testStaticPivotNullAndPostTransformLimit() { + tableResultSetEqualTest( + "SELECT device,north,south,\"NULL\" FROM (PIVOT readings " + + "ON region IN ('north','south',NULL) USING SUM(temp) GROUP BY device) " + + "ORDER BY device LIMIT 1", + new String[] {"device", "north", "south", "NULL"}, + new String[] {"d1,10.0,20.0,30.0,"}, + DATABASE); + } + + @Test + public void testSqlStyleCartesianProductAndAliases() { + tableResultSetEqualTest( + "SELECT device,n_on_total,n_off_total,s_on_total,s_off_total " + + "FROM readings PIVOT (SUM(temp) AS total FOR " + + "region IN ('north' AS n, 'south' AS s) " + + "status IN ('on','off') GROUP BY device)", + new String[] {"device", "n_on_total", "n_off_total", "s_on_total", "s_off_total"}, + new String[] {"d1,10.0,null,null,20.0,"}, + DATABASE); + } + + @Test + public void testOnExpressionAndMultipleAggregates() { + tableResultSetEqualTest( + "SELECT device,north_on,south_off FROM (PIVOT readings " + + "ON region || '_' || status USING SUM(temp) GROUP BY device)", + new String[] {"device", "north_on", "south_off"}, + new String[] {"d1,10.0,20.0,"}, + DATABASE); + tableResultSetEqualTest( + "SELECT device,north_total,north_n,south_total,south_n " + + "FROM (PIVOT readings ON region IN ('north','south') " + + "USING SUM(temp) AS total, COUNT(temp) AS n GROUP BY device)", + new String[] {"device", "north_total", "north_n", "south_total", "south_n"}, + new String[] {"d1,10.0,1,20.0,1,"}, + DATABASE); + } + + @Test + public void testDynamicPivotDiscoversFromMaterializedInput() { + tableResultSetEqualTest( + "PIVOT readings ON region USING SUM(temp) GROUP BY device ORDER BY device", + new String[] {"device", "north", "south"}, + new String[] {"d1,10.0,20.0,"}, + DATABASE); + tableResultSetEqualTest( + "WITH p AS (PIVOT readings ON region IN ('north'), status " + + "USING SUM(temp) GROUP BY device) " + + "SELECT device,north_off,north_on FROM p ORDER BY device", + new String[] {"device", "north_off", "north_on"}, + new String[] {"d1,null,10.0,"}, + DATABASE); + } + + @Test + public void testDynamicPivotInsideLaterCteCanReadEarlierCte() { + tableResultSetEqualTest( + "WITH source AS (SELECT device,region,temp FROM readings), " + + "p AS (PIVOT source ON region USING SUM(temp) GROUP BY device) " + + "SELECT device,north,south FROM p ORDER BY device", + new String[] {"device", "north", "south"}, + new String[] {"d1,10.0,20.0,"}, + DATABASE); + } + + @Test + public void testNestedDynamicPivotUsesPreparedInnerInput() { + tableResultSetEqualTest( + "PIVOT (PIVOT readings ON region USING SUM(temp) GROUP BY device) " + + "ON device USING SUM(north) GROUP BY south", + new String[] {"south", "d1"}, + new String[] {"20.0,10.0,"}, + DATABASE); + } + + @Test + public void testDynamicPivotEmptyAndNullValues() { + tableResultSetEqualTest( + "PIVOT (SELECT device, region, temp FROM readings WHERE false) " + + "ON region USING SUM(temp) GROUP BY device", + new String[] {"device"}, + new String[0], + DATABASE); + tableResultSetEqualTest( + "PIVOT (SELECT device, CAST(NULL AS STRING) AS empty_value, temp FROM readings) " + + "ON empty_value USING SUM(temp) GROUP BY device ORDER BY device", + new String[] {"device"}, + new String[] {"d1,"}, + DATABASE); + } + + @Test + public void testDynamicValueStringSortAndStaticNameCollision() { + tableResultSetEqualTest( + "PIVOT (SELECT device, temp AS k, temp FROM readings " + + "UNION ALL SELECT device, 100 AS k, temp FROM readings) " + + "ON k USING COUNT(temp) GROUP BY device", + new String[] {"device", "10", "100", "20", "30"}, + new String[] {"d1,1,3,1,1,"}, + DATABASE); + tableResultSetEqualTest( + "PIVOT readings ON region IN ('north' AS device,'south' AS device) " + + "USING SUM(temp) GROUP BY device", + new String[] {"device", "device_1", "device_2"}, + new String[] {"d1,10.0,20.0,"}, + DATABASE); + } + + @Test + public void testEmptyGlobalPivotAndDynamicWithoutOutputColumns() throws Exception { + tableResultSetEqualTest( + "PIVOT (SELECT region,temp FROM readings WHERE false) " + + "ON region IN ('north') USING COUNT(temp)", + new String[] {"north"}, + new String[] {"0,"}, + DATABASE); + try (Connection connection = EnvFactory.getEnv().getTableConnection(); + Statement statement = connection.createStatement()) { + statement.execute("USE " + DATABASE); + SQLException error = + assertThrows( + SQLException.class, + () -> + statement.executeQuery( + "PIVOT (SELECT region,temp FROM readings WHERE false) " + + "ON region USING COUNT(temp)")); + assertTrue(error.getMessage().contains("no columns")); + } + } + + @Test + public void testPreparedParameterInDynamicPivotInput() throws Exception { + try (Connection connection = EnvFactory.getEnv().getTableConnection()) { + Connection directConnection = + connection instanceof ClusterTestConnection + ? ((ClusterTestConnection) connection).writeConnection.getUnderlyingConnection() + : connection; + try (Statement statement = directConnection.createStatement()) { + statement.execute("USE " + DATABASE); + } + try (PreparedStatement statement = + directConnection.prepareStatement( + "PIVOT (SELECT device,region,temp FROM readings WHERE temp >= ?) " + + "ON region USING SUM(temp) GROUP BY device")) { + statement.setInt(1, 20); + try (ResultSet result = statement.executeQuery()) { + assertTrue(result.next()); + assertTrue(result.getMetaData().getColumnCount() == 2); + assertTrue("device".equals(result.getMetaData().getColumnName(1))); + assertTrue("south".equals(result.getMetaData().getColumnName(2))); + assertTrue("d1".equals(result.getString(1))); + assertTrue("20.0".equals(result.getString(2))); + assertTrue(!result.next()); + } + } + } + } + + @Test + public void testPivotLimitBoundary() throws Exception { + try (Connection connection = EnvFactory.getEnv().getTableConnection(); + Statement statement = connection.createStatement()) { + statement.execute("USE " + DATABASE); + statement.execute("SET CONFIGURATION pivot_limit='3'"); + tableResultSetEqualTest( + "PIVOT readings ON region IN ('north','south') USING SUM(temp) GROUP BY device", + new String[] {"device", "north", "south"}, + new String[] {"d1,10.0,20.0,"}, + DATABASE); + + statement.execute("SET CONFIGURATION pivot_limit='2'"); + SQLException error = + assertThrows( + SQLException.class, + () -> + statement.executeQuery( + "PIVOT readings ON region IN ('north','south') " + + "USING SUM(temp) GROUP BY device")); + assertTrue(error.getMessage().contains("exceeds pivot_limit 2")); + } finally { + try (Connection connection = EnvFactory.getEnv().getTableConnection(); + Statement statement = connection.createStatement()) { + statement.execute("SET CONFIGURATION pivot_limit='100000'"); + } + } + } + + @Test + public void testDynamicPivotInputBudgetsAndCleanup() throws Exception { + try (Connection connection = EnvFactory.getEnv().getTableConnection(); + Statement statement = connection.createStatement()) { + statement.execute("USE " + DATABASE); + statement.execute("SET CONFIGURATION pivot_input_buffer_size_in_bytes='1'"); + SQLException byteLimitError = + assertThrows( + SQLException.class, + () -> + statement.executeQuery( + "PIVOT readings ON region USING SUM(temp) GROUP BY device")); + assertTrue(byteLimitError.getMessage().contains("pivot_input_buffer_size_in_bytes")); + statement.execute("SET CONFIGURATION pivot_input_buffer_size_in_bytes='67108864'"); + + statement.execute("SET CONFIGURATION pivot_input_max_rows='1'"); + SQLException rowLimitError = + assertThrows( + SQLException.class, + () -> + statement.executeQuery( + "PIVOT readings ON region USING SUM(temp) GROUP BY device")); + assertTrue(rowLimitError.getMessage().contains("pivot_input_max_rows")); + } finally { + try (Connection connection = EnvFactory.getEnv().getTableConnection(); + Statement statement = connection.createStatement()) { + statement.execute("SET CONFIGURATION pivot_input_buffer_size_in_bytes='67108864'"); + statement.execute("SET CONFIGURATION pivot_input_max_rows='1000000'"); + } + } + tableResultSetEqualTest( + "PIVOT readings ON region USING SUM(temp) GROUP BY device", + new String[] {"device", "north", "south"}, + new String[] {"d1,10.0,20.0,"}, + DATABASE); + } + + @Test + public void testDuplicateInValueRejected() throws Exception { + try (Connection connection = EnvFactory.getEnv().getTableConnection(); + Statement statement = connection.createStatement()) { + statement.execute("USE " + DATABASE); + String[] sqls = { + "PIVOT readings ON region IN ('north','north') USING COUNT(temp) GROUP BY device", + "PIVOT readings ON region IN ('north' AS n1,'north' AS n2) " + + "USING COUNT(temp) GROUP BY device", + "PIVOT readings ON region IN (NULL AS n1,NULL AS n2) " + "USING COUNT(temp) GROUP BY device" + }; + for (String sql : sqls) { + SQLException error = + assertThrows(sql, SQLException.class, () -> statement.executeQuery(sql)); + assertTrue( + error.getMessage(), error.getMessage().contains("Duplicate value in PIVOT IN list")); + } + } + } + + @Test + public void testExplain() throws Exception { + try (Connection connection = EnvFactory.getEnv().getTableConnection(); + Statement statement = connection.createStatement()) { + statement.execute("USE " + DATABASE); + try (ResultSet result = + statement.executeQuery( + "EXPLAIN PIVOT readings ON region IN ('north') " + + "USING SUM(temp) GROUP BY device")) { + assertTrue(result.next()); + } + } + } + + @Test + public void testStaticGlobalAggregation() { + tableResultSetEqualTest( + "PIVOT (SELECT region,temp FROM readings) " + + "ON region IN ('north','south') USING SUM(temp)", + new String[] {"north", "south"}, + new String[] {"10.0,20.0,"}, + DATABASE); + } + + @Test + public void testStaticPivotImplicitGroupingIncludesTime() { + tableResultSetEqualTest( + "PIVOT readings ON region IN ('north','south') USING SUM(temp) ORDER BY time", + new String[] {"time", "device", "status", "north", "south"}, + new String[] { + "1970-01-01T00:00:00.001Z,d1,on,10.0,null,", + "1970-01-01T00:00:00.002Z,d1,off,null,20.0,", + "1970-01-01T00:00:00.003Z,d1,on,null,null," + }, + DATABASE); + } + + @Test + public void testStaticPivotUnmatchedValueStillProducesColumn() { + tableResultSetEqualTest( + "PIVOT readings ON region IN ('east') USING SUM(temp) GROUP BY device", + new String[] {"device", "east"}, + new String[] {"d1,null,"}, + DATABASE); + } + + @Test + public void testOrderByGeneratedColumn() { + tableResultSetEqualTest( + "SELECT device,north,south FROM (PIVOT ranked " + + "ON region IN ('north','south') USING SUM(temp) GROUP BY device) " + + "ORDER BY south DESC LIMIT 1", + new String[] {"device", "north", "south"}, + new String[] {"d2,2.0,5.0,"}, + DATABASE); + } + + @Test + public void testRecursiveCteDynamicPivotReportsUnsupported() throws Exception { + try (Connection connection = EnvFactory.getEnv().getTableConnection(); + Statement statement = connection.createStatement()) { + statement.execute("USE " + DATABASE); + SQLException error = + assertThrows( + SQLException.class, + () -> + statement.executeQuery( + "WITH RECURSIVE r AS (PIVOT readings ON region USING SUM(temp) " + + "GROUP BY device) SELECT * FROM r")); + assertTrue(error.getMessage().toLowerCase(Locale.ENGLISH).contains("cte")); + } + } + + @Test + public void testDynamicPivotDiscoveryValueBudgetAndCleanup() throws Exception { + try (Connection connection = EnvFactory.getEnv().getTableConnection(); + Statement statement = connection.createStatement()) { + statement.execute("USE " + DATABASE); + statement.execute("DROP TABLE IF EXISTS wide_values"); + statement.execute( + "CREATE TABLE wide_values " + + "(device STRING TAG, region STRING FIELD, temp INT32 FIELD)"); + for (int batch = 0; batch < 10; batch++) { + StringBuilder insert = + new StringBuilder("INSERT INTO wide_values (time,device,region,temp) VALUES "); + for (int i = 0; i < 100; i++) { + int id = batch * 100 + i; + if (i > 0) { + insert.append(','); + } + insert + .append('(') + .append(id) + .append(",'d1','r") + .append(String.format("%04d", id)) + .append('_') + .append("x".repeat(60)) + .append("',") + .append(id) + .append(')'); + } + statement.execute(insert.toString()); + } + statement.execute("FLUSH"); + statement.execute("SET CONFIGURATION pivot_input_buffer_size_in_bytes='196608'"); + SQLException error = + assertThrows( + SQLException.class, + () -> + statement.executeQuery( + "PIVOT wide_values ON region USING SUM(temp) GROUP BY device")); + assertTrue(error.getMessage().contains("pivot_input_buffer_size_in_bytes")); + } finally { + try (Connection connection = EnvFactory.getEnv().getTableConnection(); + Statement statement = connection.createStatement()) { + statement.execute("USE " + DATABASE); + statement.execute("SET CONFIGURATION pivot_input_buffer_size_in_bytes='67108864'"); + statement.execute("DROP TABLE IF EXISTS wide_values"); + } + } + tableResultSetEqualTest( + "PIVOT readings ON region USING SUM(temp) GROUP BY device", + new String[] {"device", "north", "south"}, + new String[] {"d1,10.0,20.0,"}, + DATABASE); + } + + @Test + public void testMultipleDynamicPivotsUseIndependentRowBudgets() throws Exception { + try (Connection connection = EnvFactory.getEnv().getTableConnection(); + Statement statement = connection.createStatement()) { + statement.execute("USE " + DATABASE); + statement.execute("SET CONFIGURATION pivot_input_max_rows='3'"); + tableResultSetEqualTestUnordered( + "SELECT south,d1 FROM (PIVOT (PIVOT readings ON region USING SUM(temp)) " + + "ON device USING SUM(north) GROUP BY south)", + new String[] {"south", "d1"}, + new String[] {"null,10.0,", "20.0,null,"}, + DATABASE); + } finally { + try (Connection connection = EnvFactory.getEnv().getTableConnection(); + Statement statement = connection.createStatement()) { + statement.execute("SET CONFIGURATION pivot_input_max_rows='1000000'"); + } + } + } + + @Test + public void testAnalysisFailureAfterDiscoveryReleasesResources() throws Exception { + try (Connection connection = EnvFactory.getEnv().getTableConnection(); + Statement statement = connection.createStatement()) { + statement.execute("USE " + DATABASE); + SQLException error = + assertThrows( + SQLException.class, + () -> + statement.executeQuery( + "PIVOT readings ON region USING COUNT(DISTINCT temp) GROUP BY device")); + assertTrue(error.getMessage().contains("DISTINCT")); + } + tableResultSetEqualTest( + "PIVOT readings ON region USING SUM(temp) GROUP BY device", + new String[] {"device", "north", "south"}, + new String[] {"d1,10.0,20.0,"}, + DATABASE); + } + + @Test + public void testRequirementStaticDynamicAndMixedPivot() { + tableResultSetEqualTest( + "PIVOT device_metrics ON region IN ('north','south') " + + "USING AVG(temperature) AS avg_temp GROUP BY device_id ORDER BY device_id", + new String[] {"device_id", "north_avg_temp", "south_avg_temp"}, + new String[] {"device_1,21.0,32.0,", "device_2,17.0,30.0,"}, + DATABASE); + tableResultSetEqualTest( + "PIVOT device_metrics ON region " + + "USING AVG(temperature) AS avg_temp GROUP BY device_id ORDER BY device_id", + new String[] {"device_id", "north_avg_temp", "south_avg_temp"}, + new String[] {"device_1,21.0,32.0,", "device_2,17.0,30.0,"}, + DATABASE); + tableResultSetEqualTest( + "PIVOT device_metrics ON region IN ('north' AS n,'south' AS s), status " + + "USING AVG(temperature) AS avg_temp GROUP BY device_id ORDER BY device_id", + new String[] { + "device_id", + "n_offline_avg_temp", + "n_online_avg_temp", + "s_offline_avg_temp", + "s_online_avg_temp" + }, + new String[] {"device_1,null,21.0,32.0,null,", "device_2,17.0,null,30.0,null,"}, + DATABASE); + } + + @Test + public void testRequirementOnExpressionNullSemantics() { + tableResultSetEqualTest( + "PIVOT (SELECT device_id,region,status,temperature," + + "CAST(NULL AS STRING) AS empty_key FROM device_metrics) " + + "ON CASE WHEN region IS NULL OR status IS NULL THEN empty_key " + + "ELSE region || '_' || status END USING AVG(temperature) AS avg_temp " + + "GROUP BY device_id ORDER BY device_id", + new String[] { + "device_id", "north_offline_avg_temp", "north_online_avg_temp", "south_offline_avg_temp" + }, + new String[] {"device_1,null,21.0,32.0,", "device_2,17.0,null,30.0,"}, + DATABASE); + tableResultSetEqualTest( + "PIVOT device_metrics ON region || '_' || status " + + "USING AVG(temperature) AS avg_temp GROUP BY device_id ORDER BY device_id", + new String[] { + "device_id", + "_offline_avg_temp", + "_online_avg_temp", + "north_offline_avg_temp", + "north_online_avg_temp", + "south_offline_avg_temp" + }, + new String[] {"device_1,null,26.0,null,21.0,32.0,", "device_2,24.0,null,17.0,null,30.0,"}, + DATABASE); + } + + @Test + public void testRequirementMultipleAggregatesAndGlobalAggregation() { + tableResultSetEqualTest( + "PIVOT device_metrics ON region IN ('north' AS north,'south' AS south) " + + "USING AVG(temperature) AS avg_temp, MAX(temperature) AS max_temp, " + + "AVG(humidity) AS avg_humidity GROUP BY device_id ORDER BY device_id", + new String[] { + "device_id", + "north_avg_temp", + "north_max_temp", + "north_avg_humidity", + "south_avg_temp", + "south_max_temp", + "south_avg_humidity" + }, + new String[] { + "device_1,21.0,22.0,41.0,32.0,34.0,52.0,", "device_2,17.0,18.0,61.0,30.0,32.0,70.0," + }, + DATABASE); + tableResultSetEqualTest( + "PIVOT device_metrics ON region IN ('north','south') " + + "USING AVG(temperature), MAX(temperature) GROUP BY device_id ORDER BY device_id", + new String[] { + "device_id", + "north_avg(temperature)", + "north_max(temperature)", + "south_avg(temperature)", + "south_max(temperature)" + }, + new String[] {"device_1,21.0,22.0,32.0,34.0,", "device_2,17.0,18.0,30.0,32.0,"}, + DATABASE); + tableResultSetEqualTest( + "PIVOT (SELECT region,temperature FROM device_metrics) " + + "ON region IN ('north','south') USING AVG(temperature) AS avg_temp", + new String[] {"north_avg_temp", "south_avg_temp"}, + new String[] {"19.0,31.0,"}, + DATABASE); + tableResultSetEqualTest( + "PIVOT (SELECT region,temperature FROM device_metrics WHERE false) " + + "ON region IN ('north','south') USING AVG(temperature) AS avg_temp", + new String[] {"north_avg_temp", "south_avg_temp"}, + new String[] {"null,null,"}, + DATABASE); + } + + @Test + public void testRequirementImplicitGroupingAndEmptyStaticInput() { + tableResultSetEqualTest( + "PIVOT (SELECT device_id,region,temperature FROM device_metrics) " + + "ON region IN ('north' AS north,'south' AS south) " + + "USING AVG(temperature) AS avg_temp ORDER BY device_id", + new String[] {"device_id", "north_avg_temp", "south_avg_temp"}, + new String[] {"device_1,21.0,32.0,", "device_2,17.0,30.0,"}, + DATABASE); + tableResultSetEqualTest( + "PIVOT (SELECT device_id,region,temperature FROM device_metrics WHERE false) " + + "ON region IN ('north','south') USING AVG(temperature) AS avg_temp " + + "GROUP BY device_id", + new String[] {"device_id", "north_avg_temp", "south_avg_temp"}, + new String[0], + DATABASE); + } + + @Test + public void testRequirementMultipleDynamicOnItemsWithEmptyValueSet() { + tableResultSetEqualTest( + "PIVOT (SELECT device_id,region,CAST(NULL AS STRING) AS empty_status,temperature " + + "FROM device_metrics WHERE region IS NOT NULL) " + + "ON region, empty_status USING AVG(temperature) AS avg_temp " + + "GROUP BY device_id ORDER BY device_id", + new String[] {"device_id"}, + new String[] {"device_1,", "device_2,"}, + DATABASE); + } + + @Test + public void testRequirementDuplicateGeneratedColumnNames() { + tableResultSetEqualTest( + "PIVOT device_metrics ON region IN ('north' AS north,'south' AS south) " + + "USING AVG(temperature) AS metric, MAX(temperature) AS metric " + + "GROUP BY device_id ORDER BY device_id", + new String[] { + "device_id", "north_metric", "north_metric_1", "south_metric", "south_metric_1" + }, + new String[] {"device_1,21.0,22.0,32.0,34.0,", "device_2,17.0,18.0,30.0,32.0,"}, + DATABASE); + tableResultSetEqualTest( + "PIVOT device_metrics ON region IN ('north' AS r,'south' AS r) " + + "USING AVG(temperature) AS avg_temp GROUP BY device_id ORDER BY device_id", + new String[] {"device_id", "r_avg_temp", "r_avg_temp_1"}, + new String[] {"device_1,21.0,32.0,", "device_2,17.0,30.0,"}, + DATABASE); + } + + @Test + public void testRequirementUsingAndGroupByConstraints() throws Exception { + tableResultSetEqualTest( + "PIVOT device_metrics ON region IN ('north','south') " + + "USING AVG(temperature) * 2 AS avg_temp_x2 " + + "GROUP BY device_id ORDER BY device_id", + new String[] {"device_id", "north_avg_temp_x2", "south_avg_temp_x2"}, + new String[] {"device_1,42.0,64.0,", "device_2,34.0,60.0,"}, + DATABASE); + try (Connection connection = EnvFactory.getEnv().getTableConnection(); + Statement statement = connection.createStatement()) { + statement.execute("USE " + DATABASE); + String[][] cases = { + { + "PIVOT device_metrics ON region IN ('north') " + + "USING AVG(temperature) + MAX(temperature) AS combined GROUP BY device_id", + "exactly one aggregate" + }, + { + "PIVOT device_metrics ON region IN ('north') " + + "USING AVG(temperature) + humidity AS combined GROUP BY device_id", + "cannot reference input columns outside its aggregate" + }, + { + "PIVOT device_metrics ON region IN ('north') USING temperature GROUP BY device_id", + "exactly one aggregate" + }, + { + "PIVOT device_metrics ON region IN ('north') " + + "USING AVG(temperature) GROUP BY upper(device_id)", + "GROUP BY accepts only input column references" + } + }; + for (String[] testCase : cases) { + SQLException error = + assertThrows( + testCase[0], SQLException.class, () -> statement.executeQuery(testCase[0])); + assertTrue( + error.getMessage(), + error + .getMessage() + .toLowerCase(Locale.ENGLISH) + .contains(testCase[1].toLowerCase(Locale.ENGLISH))); + } + assertThrows( + SQLException.class, + () -> + statement.executeQuery( + "SELECT * FROM device_metrics " + + "PIVOT (AVG(temperature) FOR region GROUP BY device_id)")); + } + } +} diff --git a/integration-test/src/test/java/org/apache/iotdb/relational/it/query/recent/IoTDBUnpivotIT.java b/integration-test/src/test/java/org/apache/iotdb/relational/it/query/recent/IoTDBUnpivotIT.java new file mode 100644 index 0000000000000..52f2cc6d953c6 --- /dev/null +++ b/integration-test/src/test/java/org/apache/iotdb/relational/it/query/recent/IoTDBUnpivotIT.java @@ -0,0 +1,522 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.relational.it.query.recent; + +import org.apache.iotdb.it.env.EnvFactory; +import org.apache.iotdb.it.framework.IoTDBTestRunner; +import org.apache.iotdb.itbase.category.TableClusterIT; +import org.apache.iotdb.itbase.category.TableLocalStandaloneIT; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import static org.apache.iotdb.db.it.utils.TestUtils.tableResultSetEqualTest; +import static org.apache.iotdb.db.it.utils.TestUtils.tableResultSetEqualTestUnordered; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +@RunWith(IoTDBTestRunner.class) +@Category({TableLocalStandaloneIT.class, TableClusterIT.class}) +public class IoTDBUnpivotIT { + private static final String DATABASE = "unpivot_it"; + + @BeforeClass + public static void setUp() throws Exception { + EnvFactory.getEnv().initClusterEnvironment(); + try (Connection connection = EnvFactory.getEnv().getTableConnection(); + Statement statement = connection.createStatement()) { + statement.execute("CREATE DATABASE " + DATABASE); + statement.execute("USE " + DATABASE); + statement.execute( + "CREATE TABLE readings (device STRING TAG, a INT32 FIELD, b INT32 FIELD, " + + "c INT32 FIELD, d INT32 FIELD)"); + statement.execute( + "INSERT INTO readings (time, device, a, b, c, d) VALUES " + + "(1, 'd1', 10, NULL, 30, 40), (2, 'd1', 20, 21, 31, 41)"); + statement.execute("FLUSH"); + statement.execute( + "CREATE TABLE device_metrics (device_id STRING TAG, region STRING FIELD, " + + "status STRING FIELD, temperature DOUBLE FIELD, humidity DOUBLE FIELD)"); + statement.execute( + "INSERT INTO device_metrics " + + "(time,device_id,region,status,temperature,humidity) VALUES " + + "(0,'device_1','north','online',20.0,40.0)," + + "(1,'device_1','north','online',22.0,42.0)," + + "(2,'device_1','south','offline',30.0,50.0)," + + "(3,'device_1','south','offline',34.0,54.0)," + + "(4,'device_1',NULL,'online',26.0,46.0)," + + "(0,'device_2','north','offline',16.0,60.0)," + + "(1,'device_2','north','offline',18.0,62.0)," + + "(2,'device_2','south','offline',28.0,70.0)," + + "(3,'device_2','south','offline',32.0,NULL)," + + "(4,'device_2',NULL,'offline',24.0,66.0)"); + statement.execute("FLUSH"); + statement.execute( + "CREATE TABLE device_snapshots (device_id STRING TAG, " + + "temperature_current DOUBLE FIELD, humidity_current DOUBLE FIELD, " + + "temperature_previous DOUBLE FIELD, humidity_previous DOUBLE FIELD)"); + statement.execute( + "INSERT INTO device_snapshots " + + "(time,device_id,temperature_current,humidity_current," + + "temperature_previous,humidity_previous) VALUES " + + "(0,'device_1',20.0,40.0,18.0,38.0),(0,'device_2',25.0,NULL,NULL,NULL)"); + statement.execute("FLUSH"); + } + } + + @AfterClass + public static void tearDown() { + EnvFactory.getEnv().cleanClusterEnvironment(); + } + + @Test + public void testSqlStyleNullFilterAndPostTransformLimit() { + tableResultSetEqualTestUnordered( + "SELECT time, device, metric, val FROM readings UNPIVOT " + + "(val FOR metric IN (a AS first, b AS second))", + new String[] {"time", "device", "metric", "val"}, + new String[] { + "1970-01-01T00:00:00.001Z,d1,first,10,", + "1970-01-01T00:00:00.002Z,d1,first,20,", + "1970-01-01T00:00:00.002Z,d1,second,21," + }, + DATABASE); + tableResultSetEqualTest( + "SELECT time, device, metric, val FROM readings UNPIVOT " + + "(val FOR metric IN (a AS first, b AS second)) ORDER BY time, metric LIMIT 2", + new String[] {"time", "device", "metric", "val"}, + new String[] { + "1970-01-01T00:00:00.001Z,d1,first,10,", "1970-01-01T00:00:00.002Z,d1,first,20," + }, + DATABASE); + } + + @Test + public void testMultiValueAndIncludeNulls() { + tableResultSetEqualTestUnordered( + "SELECT time, device, metric, v1, v2 FROM readings " + + "UNPIVOT INCLUDE NULLS ((v1,v2) FOR metric IN " + + "((a,b) AS ab, (c,d) AS cd))", + new String[] {"time", "device", "metric", "v1", "v2"}, + new String[] { + "1970-01-01T00:00:00.001Z,d1,ab,10,null,", + "1970-01-01T00:00:00.001Z,d1,cd,30,40,", + "1970-01-01T00:00:00.002Z,d1,ab,20,21,", + "1970-01-01T00:00:00.002Z,d1,cd,31,41," + }, + DATABASE); + } + + @Test + public void testMultiValueQualifiedSourceColumns() { + tableResultSetEqualTestUnordered( + "UNPIVOT readings ON (readings.a, readings.b) AS ab, " + + "(readings.c, readings.d) AS cd INTO NAME metric VALUES v1, v2", + new String[] {"time", "device", "metric", "v1", "v2"}, + new String[] { + "1970-01-01T00:00:00.001Z,d1,cd,30,40,", + "1970-01-01T00:00:00.002Z,d1,ab,20,21,", + "1970-01-01T00:00:00.002Z,d1,cd,31,41," + }, + DATABASE); + } + + @Test + public void testDefaultMultiValueNullFilteringAndScalarSource() { + tableResultSetEqualTest( + "SELECT time,metric,v1,v2 FROM readings UNPIVOT " + + "((v1,v2) FOR metric IN ((a,b) AS ab, (c,d) AS cd)) " + + "ORDER BY time,metric", + new String[] {"time", "metric", "v1", "v2"}, + new String[] { + "1970-01-01T00:00:00.001Z,cd,30,40,", + "1970-01-01T00:00:00.002Z,ab,20,21,", + "1970-01-01T00:00:00.002Z,cd,31,41," + }, + DATABASE); + tableResultSetEqualTest( + "SELECT time,metric,val FROM (UNPIVOT readings " + + "ON a + 1 AS incremented, b INTO NAME metric VALUE val) " + + "ORDER BY time,metric", + new String[] {"time", "metric", "val"}, + new String[] { + "1970-01-01T00:00:00.001Z,incremented,11,", + "1970-01-01T00:00:00.002Z,b,21,", + "1970-01-01T00:00:00.002Z,incremented,21," + }, + DATABASE); + } + + @Test + public void testSimplifiedColumnsAndCte() { + tableResultSetEqualTestUnordered( + "WITH expanded AS (UNPIVOT readings ON COLUMNS(* EXCLUDE (time,device)) " + + "INTO NAME metric VALUE val) SELECT time,device,metric,val FROM expanded", + new String[] {"time", "device", "metric", "val"}, + new String[] { + "1970-01-01T00:00:00.001Z,d1,a,10,", + "1970-01-01T00:00:00.001Z,d1,c,30,", + "1970-01-01T00:00:00.001Z,d1,d,40,", + "1970-01-01T00:00:00.002Z,d1,a,20,", + "1970-01-01T00:00:00.002Z,d1,b,21,", + "1970-01-01T00:00:00.002Z,d1,c,31,", + "1970-01-01T00:00:00.002Z,d1,d,41," + }, + DATABASE); + } + + @Test + public void testColumnsStarAndCommonNumericType() { + tableResultSetEqualTest( + "UNPIVOT (SELECT a,b FROM readings) ON COLUMNS(*) ORDER BY name,value", + new String[] {"name", "value"}, + new String[] {"a,10,", "a,20,", "b,21,"}, + DATABASE); + tableResultSetEqualTest( + "UNPIVOT (SELECT CAST(a AS INT64) AS a64, CAST(c AS FLOAT) AS cf " + + "FROM readings) ON a64,cf INTO NAME metric VALUE val ORDER BY metric,val", + new String[] {"metric", "val"}, + new String[] {"a64,10.0,", "a64,20.0,", "cf,30.0,", "cf,31.0,"}, + DATABASE); + tableResultSetEqualTest( + "UNPIVOT (SELECT CAST(a AS INT64) AS i64, CAST(b AS INT32) AS i32 " + + "FROM readings WHERE b IS NOT NULL) ON i64,i32 " + + "INTO NAME metric VALUE val ORDER BY metric,val", + new String[] {"metric", "val"}, + new String[] {"i32,21,", "i64,20,"}, + DATABASE); + } + + @Test + public void testSemanticErrors() throws Exception { + try (Connection connection = EnvFactory.getEnv().getTableConnection(); + Statement statement = connection.createStatement()) { + statement.execute("USE " + DATABASE); + for (String sql : + new String[] { + "UNPIVOT readings ON a, device", + "UNPIVOT readings ON a INTO NAME device VALUE val", + "UNPIVOT readings ON COLUMNS(* EXCLUDE (time,device,a,b,c,d)) " + + "INTO NAME n VALUE val", + "UNPIVOT readings ON (a,b),(c) INTO NAME n VALUES v1,v2", + "UNPIVOT readings ON a INCLUDE NULLS" + }) { + assertThrows(sql, SQLException.class, () -> statement.executeQuery(sql)); + } + String[][] semanticCases = { + { + "UNPIVOT readings ON (a,b) AS ab,(c,d) AS cd INTO NAME n VALUE v", + "number of source columns in each UNPIVOT group must match" + }, + { + "UNPIVOT readings ON (a + b,c) AS ab,(c,d) AS cd " + "INTO NAME n VALUES v1,v2", + "do not support expressions or casts" + }, + { + "UNPIVOT readings ON a + b INTO NAME n VALUE v", "must reference exactly one input column" + }, + { + "UNPIVOT readings ON COLUMNS(* EXCLUDE (time,device)) " + "INTO NAME n VALUES v1,v2", + "cannot be used to infer source column groups" + }, + { + "UNPIVOT readings ON a INTO NAME val VALUE val", + "Duplicate column name in UNPIVOT output: val" + }, + { + "UNPIVOT readings ON (a,b) AS ab,(c,d) AS cd INTO NAME n VALUES v,v", + "Duplicate column name in UNPIVOT output: v" + }, + { + "UNPIVOT readings ON a,device INTO NAME n VALUE v", + "UNPIVOT source types are not compatible" + }, + { + "UNPIVOT readings ON COLUMNS(* EXCLUDE (missing)) INTO NAME n VALUE v", + "UNPIVOT source column does not exist: missing" + }, + { + "UNPIVOT (SELECT * FROM readings x JOIN readings y ON x.device = y.device) " + + "ON COLUMNS(* EXCLUDE (a)) INTO NAME n VALUE v", + "UNPIVOT source column is ambiguous: a" + } + }; + for (String[] testCase : semanticCases) { + SQLException error = + assertThrows( + testCase[0], SQLException.class, () -> statement.executeQuery(testCase[0])); + assertTrue(error.getMessage(), error.getMessage().contains(testCase[1])); + } + } + } + + @Test + public void testExplainShowsUnpivot() throws Exception { + try (Connection connection = EnvFactory.getEnv().getTableConnection(); + Statement statement = connection.createStatement()) { + statement.execute("USE " + DATABASE); + try (ResultSet result = + statement.executeQuery( + "EXPLAIN SELECT * FROM readings UNPIVOT (val FOR metric IN (a,b))")) { + StringBuilder plan = new StringBuilder(); + while (result.next()) { + plan.append(result.getString(1)); + } + assertTrue(plan.toString().contains("Unpivot")); + } + } + } + + @Test + public void testColumnsStarOnJoinWithDuplicateNames() throws Exception { + try (Connection connection = EnvFactory.getEnv().getTableConnection(); + Statement statement = connection.createStatement()) { + statement.execute("USE " + DATABASE); + try (ResultSet result = + statement.executeQuery( + "UNPIVOT (SELECT * FROM (SELECT a FROM readings) x " + + "JOIN (SELECT a FROM readings) y ON x.a = y.a) " + + "ON COLUMNS(*) INTO NAME metric VALUE val")) { + List metrics = new ArrayList<>(); + List values = new ArrayList<>(); + while (result.next()) { + metrics.add(result.getString(1)); + values.add(result.getString(2)); + } + assertEquals(4, metrics.size()); + assertTrue(metrics.stream().allMatch("a"::equals)); + Collections.sort(values); + assertEquals(List.of("10", "10", "20", "20"), values); + } + } + } + + @Test + public void testSingleValueIncludeNulls() { + tableResultSetEqualTest( + "SELECT time,metric,val FROM readings UNPIVOT INCLUDE NULLS " + + "(val FOR metric IN (a,b)) ORDER BY time,metric", + new String[] {"time", "metric", "val"}, + new String[] { + "1970-01-01T00:00:00.001Z,a,10,", + "1970-01-01T00:00:00.001Z,b,null,", + "1970-01-01T00:00:00.002Z,a,20,", + "1970-01-01T00:00:00.002Z,b,21," + }, + DATABASE); + } + + @Test + public void testEmptyInputUnpivot() { + tableResultSetEqualTest( + "UNPIVOT (SELECT a,b FROM readings WHERE false) " + "ON a,b INTO NAME metric VALUE val", + new String[] {"metric", "val"}, + new String[0], + DATABASE); + } + + @Test + public void testMultiValueDefaultGroupNames() { + tableResultSetEqualTest( + "SELECT time,metric,v1,v2 FROM readings UNPIVOT " + + "((v1,v2) FOR metric IN ((a,b),(c,d))) ORDER BY time,metric", + new String[] {"time", "metric", "v1", "v2"}, + new String[] { + "1970-01-01T00:00:00.001Z,c_d,30,40,", + "1970-01-01T00:00:00.002Z,a_b,20,21,", + "1970-01-01T00:00:00.002Z,c_d,31,41," + }, + DATABASE); + } + + @Test + public void testExplainJsonKeepsUnpivotAttributes() throws Exception { + try (Connection connection = EnvFactory.getEnv().getTableConnection(); + Statement statement = connection.createStatement()) { + statement.execute("USE " + DATABASE); + try (ResultSet result = + statement.executeQuery( + "EXPLAIN (FORMAT JSON) SELECT * FROM readings UNPIVOT (val FOR metric IN (a,b))")) { + assertTrue(result.next()); + String json = result.getString(1); + assertTrue(json, json.contains("\"Sources\"")); + assertTrue(json, json.contains("\"IncludeNulls\"")); + assertTrue(json, json.contains("UnpivotNode")); + } + } + } + + @Test + public void testRequirementSingleValueSimplifiedAndSqlStyle() { + String[] header = {"time", "device_id", "measurement", "value"}; + String[] rows = { + "1970-01-01T00:00:00.000Z,device_1,humidity,40.0,", + "1970-01-01T00:00:00.000Z,device_1,temperature,20.0,", + "1970-01-01T00:00:00.001Z,device_1,humidity,42.0,", + "1970-01-01T00:00:00.001Z,device_1,temperature,22.0,", + "1970-01-01T00:00:00.002Z,device_1,humidity,50.0,", + "1970-01-01T00:00:00.002Z,device_1,temperature,30.0,", + "1970-01-01T00:00:00.003Z,device_1,humidity,54.0,", + "1970-01-01T00:00:00.003Z,device_1,temperature,34.0,", + "1970-01-01T00:00:00.004Z,device_1,humidity,46.0,", + "1970-01-01T00:00:00.004Z,device_1,temperature,26.0," + }; + tableResultSetEqualTest( + "UNPIVOT (SELECT time,device_id,temperature,humidity FROM device_metrics " + + "WHERE device_id = 'device_1') ON temperature,humidity " + + "INTO NAME measurement VALUE value ORDER BY time,measurement", + header, + rows, + DATABASE); + tableResultSetEqualTest( + "SELECT * FROM (SELECT time,device_id,temperature,humidity FROM device_metrics " + + "WHERE device_id = 'device_1') AS source_data " + + "UNPIVOT (value FOR measurement IN (temperature,humidity)) " + + "ORDER BY time,measurement", + header, + rows, + DATABASE); + } + + @Test + public void testRequirementComputedSourceAndAliases() { + tableResultSetEqualTest( + "UNPIVOT (SELECT time,device_id,temperature,humidity FROM device_metrics " + + "WHERE device_id = 'device_1') ON temperature * 1.8 + 32 AS temperature_f, " + + "humidity AS humidity_pct INTO NAME measurement VALUE value " + + "ORDER BY time,measurement", + new String[] {"time", "device_id", "measurement", "value"}, + new String[] { + "1970-01-01T00:00:00.000Z,device_1,humidity_pct,40.0,", + "1970-01-01T00:00:00.000Z,device_1,temperature_f,68.0,", + "1970-01-01T00:00:00.001Z,device_1,humidity_pct,42.0,", + "1970-01-01T00:00:00.001Z,device_1,temperature_f,71.6,", + "1970-01-01T00:00:00.002Z,device_1,humidity_pct,50.0,", + "1970-01-01T00:00:00.002Z,device_1,temperature_f,86.0,", + "1970-01-01T00:00:00.003Z,device_1,humidity_pct,54.0,", + "1970-01-01T00:00:00.003Z,device_1,temperature_f,93.2,", + "1970-01-01T00:00:00.004Z,device_1,humidity_pct,46.0,", + "1970-01-01T00:00:00.004Z,device_1,temperature_f,78.80000000000001," + }, + DATABASE); + } + + @Test + public void testRequirementSqlStyleColumnsExclude() { + tableResultSetEqualTest( + "SELECT * FROM (SELECT time,device_id,temperature,humidity FROM device_metrics " + + "WHERE device_id = 'device_1' AND time = 0) AS source_data " + + "UNPIVOT (value FOR measurement IN (COLUMNS(* EXCLUDE (time,device_id)))) " + + "ORDER BY measurement", + new String[] {"time", "device_id", "measurement", "value"}, + new String[] { + "1970-01-01T00:00:00.000Z,device_1,humidity,40.0,", + "1970-01-01T00:00:00.000Z,device_1,temperature,20.0," + }, + DATABASE); + } + + @Test + public void testRequirementMultiValueSnapshots() { + tableResultSetEqualTest( + "UNPIVOT device_snapshots ON (temperature_current,humidity_current) AS current, " + + "(temperature_previous,humidity_previous) AS previous " + + "INTO NAME sample VALUES temperature,humidity ORDER BY device_id,sample", + new String[] {"time", "device_id", "sample", "temperature", "humidity"}, + new String[] { + "1970-01-01T00:00:00.000Z,device_1,current,20.0,40.0,", + "1970-01-01T00:00:00.000Z,device_1,previous,18.0,38.0," + }, + DATABASE); + tableResultSetEqualTest( + "SELECT * FROM device_snapshots UNPIVOT INCLUDE NULLS " + + "((temperature,humidity) FOR sample IN " + + "((temperature_current,humidity_current) AS current, " + + "(temperature_previous,humidity_previous) AS previous)) " + + "ORDER BY device_id,sample", + new String[] {"time", "device_id", "sample", "temperature", "humidity"}, + new String[] { + "1970-01-01T00:00:00.000Z,device_1,current,20.0,40.0,", + "1970-01-01T00:00:00.000Z,device_1,previous,18.0,38.0,", + "1970-01-01T00:00:00.000Z,device_2,current,25.0,null,", + "1970-01-01T00:00:00.000Z,device_2,previous,null,null," + }, + DATABASE); + tableResultSetEqualTest( + "UNPIVOT device_snapshots ON (temperature_current,humidity_current), " + + "(temperature_previous,humidity_previous) AS previous " + + "INTO NAME sample VALUES temperature,humidity ORDER BY device_id,sample", + new String[] {"time", "device_id", "sample", "temperature", "humidity"}, + new String[] { + "1970-01-01T00:00:00.000Z,device_1,previous,18.0,38.0,", + "1970-01-01T00:00:00.000Z,device_1,temperature_current_humidity_current,20.0,40.0," + }, + DATABASE); + } + + @Test + public void testRequirementOrderByValueDescLimit() { + tableResultSetEqualTest( + "UNPIVOT (SELECT time,device_id,temperature,humidity FROM device_metrics " + + "WHERE device_id = 'device_1') ON temperature,humidity " + + "INTO NAME measurement VALUE value ORDER BY value DESC LIMIT 3", + new String[] {"time", "device_id", "measurement", "value"}, + new String[] { + "1970-01-01T00:00:00.003Z,device_1,humidity,54.0,", + "1970-01-01T00:00:00.002Z,device_1,humidity,50.0,", + "1970-01-01T00:00:00.004Z,device_1,humidity,46.0," + }, + DATABASE); + } + + @Test + public void testRequirementSingleValueNullHandling() { + tableResultSetEqualTest( + "UNPIVOT (SELECT time,device_id,temperature,humidity FROM device_metrics " + + "WHERE device_id = 'device_2' AND time = 3) ON temperature,humidity " + + "INTO NAME measurement VALUE value ORDER BY measurement", + new String[] {"time", "device_id", "measurement", "value"}, + new String[] {"1970-01-01T00:00:00.003Z,device_2,temperature,32.0,"}, + DATABASE); + tableResultSetEqualTest( + "SELECT * FROM (SELECT time,device_id,temperature,humidity FROM device_metrics " + + "WHERE device_id = 'device_2' AND time = 3) AS source_data " + + "UNPIVOT INCLUDE NULLS (value FOR measurement IN (temperature,humidity)) " + + "ORDER BY measurement", + new String[] {"time", "device_id", "measurement", "value"}, + new String[] { + "1970-01-01T00:00:00.003Z,device_2,humidity,null,", + "1970-01-01T00:00:00.003Z,device_2,temperature,32.0," + }, + DATABASE); + } +} diff --git a/iotdb-client/jdbc/src/main/java/org/apache/iotdb/jdbc/IoTDBTablePreparedStatement.java b/iotdb-client/jdbc/src/main/java/org/apache/iotdb/jdbc/IoTDBTablePreparedStatement.java index 3c95afa107dd1..e0d290a766520 100644 --- a/iotdb-client/jdbc/src/main/java/org/apache/iotdb/jdbc/IoTDBTablePreparedStatement.java +++ b/iotdb-client/jdbc/src/main/java/org/apache/iotdb/jdbc/IoTDBTablePreparedStatement.java @@ -170,7 +170,17 @@ private boolean isQueryStatement(String sql) { return false; } String trimmedSql = sql.trim().toUpperCase(); - return trimmedSql.startsWith("SELECT") || trimmedSql.startsWith("WITH"); + return trimmedSql.startsWith("SELECT") + || trimmedSql.startsWith("WITH") + || startsWithKeyword(trimmedSql, "PIVOT") + || startsWithKeyword(trimmedSql, "UNPIVOT"); + } + + private boolean startsWithKeyword(String sql, String keyword) { + return sql.startsWith(keyword) + && sql.length() > keyword.length() + && (Character.isWhitespace(sql.charAt(keyword.length())) + || sql.charAt(keyword.length()) == '('); } @Override diff --git a/iotdb-client/jdbc/src/test/java/org/apache/iotdb/jdbc/IoTDBTablePreparedStatementTest.java b/iotdb-client/jdbc/src/test/java/org/apache/iotdb/jdbc/IoTDBTablePreparedStatementTest.java index d60cd8afdcf75..7d87eeaece234 100644 --- a/iotdb-client/jdbc/src/test/java/org/apache/iotdb/jdbc/IoTDBTablePreparedStatementTest.java +++ b/iotdb-client/jdbc/src/test/java/org/apache/iotdb/jdbc/IoTDBTablePreparedStatementTest.java @@ -126,6 +126,24 @@ private int countQuestionMarks(String sql) { return count; } + @SuppressWarnings("resource") + @Test + public void testPivotAndUnpivotAreServerSidePreparedQueries() throws Exception { + for (String sql : + new String[] { + "PIVOT (SELECT region,temp FROM readings WHERE temp >= ?) " + "ON region USING SUM(temp)", + "unpivot\n(SELECT a FROM readings WHERE a >= ?) ON a", + "PIVOT(SELECT region,temp FROM readings WHERE temp >= ?) ON region USING SUM(temp)" + }) { + IoTDBTablePreparedStatement statement = + new IoTDBTablePreparedStatement(connection, client, sessionId, sql, zoneId); + statement.setInt(1, 20); + statement.execute(); + } + verify(client, times(3)).prepareStatement(any(TSPrepareReq.class)); + verify(client, times(3)).executePreparedStatement(any(TSExecutePreparedReq.class)); + } + // ========== Table Model SQL Injection Prevention Tests ========== @SuppressWarnings("resource") diff --git a/iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/process/UnpivotOperator.java b/iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/process/UnpivotOperator.java new file mode 100644 index 0000000000000..f9358654cca44 --- /dev/null +++ b/iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/process/UnpivotOperator.java @@ -0,0 +1,205 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.calc.execution.operator.process; + +import org.apache.iotdb.calc.execution.operator.CommonOperatorContext; +import org.apache.iotdb.calc.execution.operator.Operator; +import org.apache.iotdb.calc.plan.planner.CommonOperatorUtils; +import org.apache.iotdb.commons.queryengine.execution.MemoryEstimationHelper; + +import com.google.common.util.concurrent.ListenableFuture; +import org.apache.tsfile.block.column.Column; +import org.apache.tsfile.common.conf.TSFileConfig; +import org.apache.tsfile.enums.TSDataType; +import org.apache.tsfile.read.common.block.TsBlock; +import org.apache.tsfile.read.common.block.TsBlockBuilder; +import org.apache.tsfile.read.common.block.column.RunLengthEncodedColumn; +import org.apache.tsfile.utils.Binary; +import org.apache.tsfile.utils.RamUsageEstimator; + +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** A bounded, row-major expansion of a single input block at a time. */ +public final class UnpivotOperator implements ProcessOperator { + private static final long INSTANCE_SIZE = + RamUsageEstimator.shallowSizeOfInstance(UnpivotOperator.class); + + private final CommonOperatorContext context; + private final Operator child; + private final int[] retained; + private final int[][] sources; + private final Binary[] names; + private final boolean includeNulls; + private final List outputTypes; + private TsBlock input; + private int row; + private int source; + + public UnpivotOperator( + CommonOperatorContext context, + Operator child, + int[] retained, + int[][] sources, + List names, + boolean includeNulls, + List outputTypes) { + if (sources.length == 0 + || sources.length != names.size() + || sources[0].length == 0 + || outputTypes.size() != retained.length + sources[0].length + 1) { + throw new IllegalArgumentException(); + } + for (int[] group : sources) { + if (group.length != sources[0].length) { + throw new IllegalArgumentException(); + } + } + this.context = context; + this.child = child; + this.retained = retained.clone(); + this.sources = new int[sources.length][]; + for (int i = 0; i < sources.length; i++) { + this.sources[i] = sources[i].clone(); + } + this.names = + names.stream() + .map(name -> new Binary(name, TSFileConfig.STRING_CHARSET)) + .toArray(Binary[]::new); + this.includeNulls = includeNulls; + this.outputTypes = List.copyOf(outputTypes); + } + + @Override + public CommonOperatorContext getOperatorContext() { + return context; + } + + @Override + public ListenableFuture isBlocked() { + return input != null && row < input.getPositionCount() ? NOT_BLOCKED : child.isBlocked(); + } + + @Override + public TsBlock next() throws Exception { + TsBlockBuilder output = new TsBlockBuilder(outputTypes); + long startTime = System.nanoTime(); + long maxRuntime = context.getMaxRunTime().roundTo(TimeUnit.NANOSECONDS); + boolean processed = false; + while (!output.isFull()) { + if (processed && System.nanoTime() - startTime >= maxRuntime) { + break; + } + processed = true; + if (input == null || row >= input.getPositionCount()) { + input = null; + if (!child.hasNextWithTimer()) { + break; + } + input = child.nextWithTimer(); + row = 0; + source = 0; + if (input == null) { + break; + } + if (input.isEmpty()) { + input = null; + break; + } + } + boolean valid = true; + if (!includeNulls) { + for (int channel : sources[source]) { + if (input.getColumn(channel).isNull(row)) { + valid = false; + break; + } + } + } + if (valid) { + int target = 0; + for (int channel : retained) { + copy(input.getColumn(channel), row, output, target++); + } + output.getColumnBuilder(target++).writeBinary(names[source]); + for (int channel : sources[source]) { + copy(input.getColumn(channel), row, output, target++); + } + output.declarePosition(); + } + if (++source == sources.length) { + source = 0; + row++; + } + } + if (output.isEmpty()) { + return null; + } + return output.build( + new RunLengthEncodedColumn( + CommonOperatorUtils.TIME_COLUMN_TEMPLATE, output.getPositionCount())); + } + + private static void copy(Column column, int row, TsBlockBuilder output, int channel) { + if (column.isNull(row)) { + output.getColumnBuilder(channel).appendNull(); + } else { + output.getColumnBuilder(channel).write(column, row); + } + } + + @Override + public boolean hasNext() throws Exception { + return (input != null && row < input.getPositionCount()) || child.hasNextWithTimer(); + } + + @Override + public boolean isFinished() throws Exception { + return (input == null || row >= input.getPositionCount()) && child.isFinished(); + } + + @Override + public void close() throws Exception { + input = null; + child.close(); + } + + @Override + public long calculateMaxPeekMemory() { + return child.calculateMaxPeekMemoryWithCounter() + child.calculateMaxReturnSize(); + } + + @Override + public long calculateMaxReturnSize() { + return child.calculateMaxReturnSize(); + } + + @Override + public long calculateRetainedSizeAfterCallingNext() { + return child.calculateRetainedSizeAfterCallingNext() + child.calculateMaxReturnSize(); + } + + @Override + public long ramBytesUsed() { + return INSTANCE_SIZE + + MemoryEstimationHelper.getEstimatedSizeOfAccountableObject(child) + + MemoryEstimationHelper.getEstimatedSizeOfAccountableObject(context); + } +} diff --git a/iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/plan/planner/TableOperatorGenerator.java b/iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/plan/planner/TableOperatorGenerator.java index 5a4ac7f9ac8b9..ab5db7c65c8ec 100644 --- a/iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/plan/planner/TableOperatorGenerator.java +++ b/iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/plan/planner/TableOperatorGenerator.java @@ -40,6 +40,7 @@ import org.apache.iotdb.calc.execution.operator.process.TableSortOperator; import org.apache.iotdb.calc.execution.operator.process.TableStreamSortOperator; import org.apache.iotdb.calc.execution.operator.process.TableTopKOperator; +import org.apache.iotdb.calc.execution.operator.process.UnpivotOperator; import org.apache.iotdb.calc.execution.operator.process.ValuesOperator; import org.apache.iotdb.calc.execution.operator.process.fill.IFill; import org.apache.iotdb.calc.execution.operator.process.fill.ILinearFill; @@ -140,6 +141,7 @@ import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.TopKNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.TopKRankingNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.UnionNode; +import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.UnpivotNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.ValueFillNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.ValuesNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.WindowNode; @@ -699,6 +701,27 @@ public Operator visitLimit(LimitNode node, C context) { return new LimitOperator(operatorContext, node.getCount(), child); } + @Override + public Operator visitUnpivot(UnpivotNode node, C context) { + Operator child = node.getChild().accept(this, context); + CommonOperatorContext operatorContext = + addOperatorContext(context, node.getPlanNodeId(), UnpivotOperator.class.getSimpleName()); + List input = node.getChild().getOutputSymbols(); + int[] retained = node.getRetained().stream().mapToInt(input::indexOf).toArray(); + int[][] sources = + node.getSources().stream() + .map(group -> group.stream().mapToInt(input::indexOf).toArray()) + .toArray(int[][]::new); + return new UnpivotOperator( + operatorContext, + child, + retained, + sources, + node.getNames(), + node.isIncludeNulls(), + getOutputColumnTypes(node, context.getTableTypeProvider())); + } + @Override public Operator visitOffset(OffsetNode node, C context) { Operator child = node.getChild().accept(this, context); diff --git a/iotdb-core/calc-commons/src/test/java/org/apache/iotdb/calc/execution/operator/process/UnpivotOperatorTest.java b/iotdb-core/calc-commons/src/test/java/org/apache/iotdb/calc/execution/operator/process/UnpivotOperatorTest.java new file mode 100644 index 0000000000000..8dde3cb321479 --- /dev/null +++ b/iotdb-core/calc-commons/src/test/java/org/apache/iotdb/calc/execution/operator/process/UnpivotOperatorTest.java @@ -0,0 +1,202 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.calc.execution.operator.process; + +import org.apache.iotdb.calc.execution.operator.CommonOperatorContext; +import org.apache.iotdb.calc.execution.operator.Operator; +import org.apache.iotdb.calc.plan.planner.memory.MemoryReservationManager; +import org.apache.iotdb.commons.queryengine.plan.planner.plan.node.PlanNodeId; + +import com.google.common.util.concurrent.ListenableFuture; +import org.apache.tsfile.enums.TSDataType; +import org.apache.tsfile.read.common.block.TsBlock; +import org.apache.tsfile.read.common.block.TsBlockBuilder; +import org.junit.Test; + +import java.util.Arrays; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +public class UnpivotOperatorTest { + private static final class Context extends CommonOperatorContext { + private Context() { + super(0, new PlanNodeId("unpivot"), "test"); + } + + @Override + public MemoryReservationManager getMemoryReservationContext() { + return null; + } + + @Override + public int getFragmentId() { + return 0; + } + + @Override + public int getPipelineId() { + return 0; + } + + @Override + public long ramBytesUsed() { + return 0; + } + } + + private static final class Input implements Operator { + private final Context context = new Context(); + private final TsBlock[] blocks; + private int index; + private boolean closed; + + private Input(TsBlock... blocks) { + this.blocks = blocks; + } + + @Override + public CommonOperatorContext getOperatorContext() { + return context; + } + + @Override + public ListenableFuture isBlocked() { + return NOT_BLOCKED; + } + + @Override + public boolean hasNext() { + return index < blocks.length; + } + + @Override + public TsBlock next() { + if (!hasNext()) { + throw new IllegalStateException(); + } + return blocks[index++]; + } + + @Override + public boolean isFinished() { + return !hasNext(); + } + + @Override + public void close() { + closed = true; + } + + @Override + public long calculateMaxPeekMemory() { + return 0; + } + + @Override + public long calculateMaxReturnSize() { + return 0; + } + + @Override + public long calculateRetainedSizeAfterCallingNext() { + return 0; + } + + @Override + public long ramBytesUsed() { + return 0; + } + } + + private static TsBlock input() { + // The logical time is a value column; the block's dedicated time slot is unrelated. + TsBlockBuilder builder = + new TsBlockBuilder( + Arrays.asList(TSDataType.INT64, TSDataType.INT32, TSDataType.INT32, TSDataType.INT32)); + for (int row = 0; row < 2; row++) { + builder.getTimeColumnBuilder().writeLong(999); + builder.getColumnBuilder(0).writeLong(10L + row); + builder.getColumnBuilder(1).writeInt(20 + row); + if (row == 0) { + builder.getColumnBuilder(2).writeInt(30); + } else { + builder.getColumnBuilder(2).appendNull(); + } + builder.getColumnBuilder(3).writeInt(40 + row); + builder.declarePosition(); + } + return builder.build(); + } + + private static UnpivotOperator operator(Input input, boolean includeNulls) { + return new UnpivotOperator( + new Context(), + input, + new int[] {0}, + new int[][] {{1, 2}, {1, 3}}, + Arrays.asList("first", "second"), + includeNulls, + Arrays.asList(TSDataType.INT64, TSDataType.STRING, TSDataType.INT32, TSDataType.INT32)); + } + + @Test + public void testRowMajorOrderNullsAndLogicalTime() throws Exception { + Input child = new Input(input()); + UnpivotOperator operator = operator(child, false); + TsBlock output = operator.next(); + assertEquals(3, output.getPositionCount()); + assertEquals(10L, output.getColumn(0).getLong(0)); + assertEquals("first", output.getColumn(1).getBinary(0).toString()); + assertEquals(30, output.getColumn(3).getInt(0)); + assertEquals("second", output.getColumn(1).getBinary(1).toString()); + assertEquals(11L, output.getColumn(0).getLong(2)); + assertEquals(41, output.getColumn(3).getInt(2)); + assertFalse(output.getTimeByIndex(0) == 999L); + assertTrue(operator.isFinished()); + assertFalse(operator.hasNext()); + operator.close(); + assertTrue(child.closed); + } + + @Test + public void testIncludeNullsAndEmptyInput() throws Exception { + UnpivotOperator included = operator(new Input(input()), true); + TsBlock output = included.next(); + assertEquals(4, output.getPositionCount()); + assertTrue(output.getColumn(3).isNull(2)); + included.close(); + + UnpivotOperator empty = operator(new Input(), false); + assertNull(empty.next()); + assertTrue(empty.isFinished()); + empty.close(); + } + + @Test + public void testBlockBoundary() throws Exception { + UnpivotOperator operator = operator(new Input(input(), input()), false); + assertEquals(6, operator.next().getPositionCount()); + assertTrue(operator.isFinished()); + operator.close(); + } +} diff --git a/iotdb-core/confignode/src/main/i18n/en/org/apache/iotdb/confignode/i18n/ConfigNodeMessages.java b/iotdb-core/confignode/src/main/i18n/en/org/apache/iotdb/confignode/i18n/ConfigNodeMessages.java index cfde56c6419da..7e7684e8b88e5 100644 --- a/iotdb-core/confignode/src/main/i18n/en/org/apache/iotdb/confignode/i18n/ConfigNodeMessages.java +++ b/iotdb-core/confignode/src/main/i18n/en/org/apache/iotdb/confignode/i18n/ConfigNodeMessages.java @@ -745,4 +745,6 @@ private ConfigNodeMessages() {} public static final String LOG_FAILED_TO_TRANSFER_CONFIGNODE_LEADERSHIP_BEFORE_SHUTDOWN_CONTINUING_SHUTDOWN_2B9364D5 = "Failed to transfer ConfigNode leadership before shutdown; continuing shutdown."; + public static final String LOG_INVALID_PIVOT_CONFIGURATION_VALUE_FOR_ARG_ARG_KEEPING_ARG_FCB21FF0 = + "Invalid PIVOT configuration value for {}: {}; keeping {}"; } diff --git a/iotdb-core/confignode/src/main/i18n/en/org/apache/iotdb/confignode/i18n/ManagerMessages.java b/iotdb-core/confignode/src/main/i18n/en/org/apache/iotdb/confignode/i18n/ManagerMessages.java index 482da8daad126..bdb48e2bd0b91 100644 --- a/iotdb-core/confignode/src/main/i18n/en/org/apache/iotdb/confignode/i18n/ManagerMessages.java +++ b/iotdb-core/confignode/src/main/i18n/en/org/apache/iotdb/confignode/i18n/ManagerMessages.java @@ -20,6 +20,8 @@ package org.apache.iotdb.confignode.i18n; public final class ManagerMessages { + public static final String MESSAGE_INVALID_PIVOT_CONFIGURATION_VALUE_FOR_ARG_ARG_AB194F23 = + "Invalid PIVOT configuration value for %s: %s"; public static final String ACTIVATEDATAALLOTTABLE_ACTIVATE_SERIESPARTITIONSLOT = "[ActivateDataAllotTable] Activate SeriesPartitionSlot {} "; diff --git a/iotdb-core/confignode/src/main/i18n/zh/org/apache/iotdb/confignode/i18n/ConfigNodeMessages.java b/iotdb-core/confignode/src/main/i18n/zh/org/apache/iotdb/confignode/i18n/ConfigNodeMessages.java index ddf8be67cefc6..94f19f2eecc2a 100644 --- a/iotdb-core/confignode/src/main/i18n/zh/org/apache/iotdb/confignode/i18n/ConfigNodeMessages.java +++ b/iotdb-core/confignode/src/main/i18n/zh/org/apache/iotdb/confignode/i18n/ConfigNodeMessages.java @@ -787,4 +787,6 @@ private ConfigNodeMessages() {} public static final String LOG_FAILED_TO_TRANSFER_CONFIGNODE_LEADERSHIP_BEFORE_SHUTDOWN_CONTINUING_SHUTDOWN_2B9364D5 = "关闭前转移 ConfigNode leader 失败,继续关闭。"; + public static final String LOG_INVALID_PIVOT_CONFIGURATION_VALUE_FOR_ARG_ARG_KEEPING_ARG_FCB21FF0 = + "无效的 PIVOT 配置值 {}:{};保留当前值 {}"; } diff --git a/iotdb-core/confignode/src/main/i18n/zh/org/apache/iotdb/confignode/i18n/ManagerMessages.java b/iotdb-core/confignode/src/main/i18n/zh/org/apache/iotdb/confignode/i18n/ManagerMessages.java index 739ee0029c890..3e8cf291fa747 100644 --- a/iotdb-core/confignode/src/main/i18n/zh/org/apache/iotdb/confignode/i18n/ManagerMessages.java +++ b/iotdb-core/confignode/src/main/i18n/zh/org/apache/iotdb/confignode/i18n/ManagerMessages.java @@ -20,6 +20,8 @@ package org.apache.iotdb.confignode.i18n; public final class ManagerMessages { + public static final String MESSAGE_INVALID_PIVOT_CONFIGURATION_VALUE_FOR_ARG_ARG_AB194F23 = + "无效的 PIVOT 配置值 %s:%s"; public static final String ACTIVATEDATAALLOTTABLE_ACTIVATE_SERIESPARTITIONSLOT = "[ActivateDataAllotTable] 激活 SeriesPartitionSlot {} "; diff --git a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/conf/ConfigNodeDescriptor.java b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/conf/ConfigNodeDescriptor.java index e9ab7657c50a6..2ba0076a07871 100644 --- a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/conf/ConfigNodeDescriptor.java +++ b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/conf/ConfigNodeDescriptor.java @@ -381,6 +381,8 @@ private void loadProperties(TrimProperties properties) throws BadNodeUrlExceptio // commons commonDescriptor.loadCommonProps(properties); + loadPivotConfiguration(properties); + overlayPivotConfiguration(); commonDescriptor.initCommonConfigDir(conf.getSystemDir()); commonDescriptor.initThriftSSL(properties); @@ -944,7 +946,73 @@ public void loadHotModifiedProps(TrimProperties properties) throws IOException { commonDescriptor.loadHotModifiedDiskSpaceWarningThreshold(properties); loadHotModifiedProcedureConfig(properties); loadPipeHotModifiedProp(properties); + loadPivotConfiguration(properties); ConfigurationFileUtils.updateAppliedProperties(properties, true); + overlayPivotConfiguration(); + } + + private void loadPivotConfiguration(TrimProperties properties) { + CommonConfig config = commonDescriptor.getConfig(); + config.setPivotLimit(parsePositivePivotInt(properties, "pivot_limit", config.getPivotLimit())); + config.setPivotInputBufferSizeInBytes( + parsePositivePivotLong( + properties, + "pivot_input_buffer_size_in_bytes", + config.getPivotInputBufferSizeInBytes())); + config.setPivotInputMaxRows( + parsePositivePivotInt(properties, "pivot_input_max_rows", config.getPivotInputMaxRows())); + } + + private int parsePositivePivotInt(TrimProperties properties, String key, int previous) { + String value = properties.getProperty(key); + if (value == null) { + return previous; + } + try { + int parsed = Integer.parseInt(value.trim()); + if (parsed > 0) { + return parsed; + } + } catch (NumberFormatException ignored) { + // Preserve the last effective value for malformed or overflowing startup properties. + } + LOGGER.warn( + ConfigNodeMessages.LOG_INVALID_PIVOT_CONFIGURATION_VALUE_FOR_ARG_ARG_KEEPING_ARG_FCB21FF0, + key, + value, + previous); + return previous; + } + + private long parsePositivePivotLong(TrimProperties properties, String key, long previous) { + String value = properties.getProperty(key); + if (value == null) { + return previous; + } + try { + long parsed = Long.parseLong(value.trim()); + if (parsed > 0) { + return parsed; + } + } catch (NumberFormatException ignored) { + // Preserve the last effective value for malformed or overflowing startup properties. + } + LOGGER.warn( + ConfigNodeMessages.LOG_INVALID_PIVOT_CONFIGURATION_VALUE_FOR_ARG_ARG_KEEPING_ARG_FCB21FF0, + key, + value, + previous); + return previous; + } + + private void overlayPivotConfiguration() { + CommonConfig config = commonDescriptor.getConfig(); + ConfigurationFileUtils.updateAppliedProperties( + "pivot_limit", Integer.toString(config.getPivotLimit())); + ConfigurationFileUtils.updateAppliedProperties( + "pivot_input_buffer_size_in_bytes", Long.toString(config.getPivotInputBufferSizeInBytes())); + ConfigurationFileUtils.updateAppliedProperties( + "pivot_input_max_rows", Integer.toString(config.getPivotInputMaxRows())); } private void loadHotModifiedProcedureConfig(TrimProperties properties) throws IOException { diff --git a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/ConfigManager.java b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/ConfigManager.java index 360a50a24d555..968f63049f20c 100644 --- a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/ConfigManager.java +++ b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/ConfigManager.java @@ -1802,8 +1802,38 @@ public TSStatus clearCache(final Set clearCacheOptions) { : status; } + static TSStatus validatePivotConfiguration(Map configs) { + // Reject malformed and overflowing limits before modifying the file or broadcasting. + for (String key : + new String[] {"pivot_limit", "pivot_input_max_rows", "pivot_input_buffer_size_in_bytes"}) { + String value = configs.get(key); + if (value == null) { + continue; + } + try { + if ("pivot_input_buffer_size_in_bytes".equals(key)) { + Long.parseLong(value.trim()); + } else { + Integer.parseInt(value.trim()); + } + } catch (NumberFormatException e) { + return RpcUtils.getStatus( + TSStatusCode.EXECUTE_STATEMENT_ERROR, + String.format( + ManagerMessages.MESSAGE_INVALID_PIVOT_CONFIGURATION_VALUE_FOR_ARG_ARG_AB194F23, + key, + value)); + } + } + return null; + } + @Override public TSStatus setConfiguration(TSetConfigurationReq req) { + TSStatus invalidPivotConfig = validatePivotConfiguration(req.getConfigs()); + if (invalidPivotConfig != null) { + return invalidPivotConfig; + } for (String key : WAL_THROTTLE_THRESHOLD_KEYS) { String value = req.getConfigs().get(key); if (value == null) { diff --git a/iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/conf/PivotConfigNodeDescriptorTest.java b/iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/conf/PivotConfigNodeDescriptorTest.java new file mode 100644 index 0000000000000..bf4d4d5cbcdae --- /dev/null +++ b/iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/conf/PivotConfigNodeDescriptorTest.java @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.confignode.conf; + +import org.apache.iotdb.commons.conf.CommonConfig; +import org.apache.iotdb.commons.conf.CommonDescriptor; +import org.apache.iotdb.commons.conf.ConfigurationFileUtils; +import org.apache.iotdb.commons.conf.TrimProperties; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class PivotConfigNodeDescriptorTest { + @Test + public void testReloadAndShowEffectiveValues() throws Exception { + CommonConfig config = CommonDescriptor.getInstance().getConfig(); + int oldLimit = config.getPivotLimit(); + long oldBytes = config.getPivotInputBufferSizeInBytes(); + int oldRows = config.getPivotInputMaxRows(); + try { + TrimProperties properties = new TrimProperties(); + properties.setProperty("pivot_limit", "3"); + properties.setProperty("pivot_input_buffer_size_in_bytes", "100"); + properties.setProperty("pivot_input_max_rows", "4"); + ConfigNodeDescriptor.getInstance().loadHotModifiedProps(properties); + assertEquals(3, config.getPivotLimit()); + assertEquals(100, config.getPivotInputBufferSizeInBytes()); + assertEquals(4, config.getPivotInputMaxRows()); + + properties.setProperty("pivot_limit", "0"); + properties.setProperty("pivot_input_buffer_size_in_bytes", "-1"); + properties.setProperty("pivot_input_max_rows", "2147483648"); + ConfigNodeDescriptor.getInstance().loadHotModifiedProps(properties); + assertEquals("3", ConfigurationFileUtils.getAppliedProperties().get("pivot_limit")); + assertEquals( + "100", + ConfigurationFileUtils.getAppliedProperties().get("pivot_input_buffer_size_in_bytes")); + assertEquals("4", ConfigurationFileUtils.getAppliedProperties().get("pivot_input_max_rows")); + } finally { + config.setPivotLimit(oldLimit); + config.setPivotInputBufferSizeInBytes(oldBytes); + config.setPivotInputMaxRows(oldRows); + } + } +} diff --git a/iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/manager/PivotConfigurationValidationTest.java b/iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/manager/PivotConfigurationValidationTest.java new file mode 100644 index 0000000000000..144af93aa5523 --- /dev/null +++ b/iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/manager/PivotConfigurationValidationTest.java @@ -0,0 +1,57 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.confignode.manager; + +import org.apache.iotdb.rpc.TSStatusCode; + +import org.junit.Test; + +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +public class PivotConfigurationValidationTest { + @Test + public void testRejectMalformedAndOverflowBeforeApply() { + assertNull(ConfigManager.validatePivotConfiguration(Map.of())); + assertNull(ConfigManager.validatePivotConfiguration(Map.of("pivot_limit", "0"))); + assertNull(ConfigManager.validatePivotConfiguration(Map.of("pivot_input_max_rows", "-1"))); + assertNull( + ConfigManager.validatePivotConfiguration( + Map.of( + "pivot_limit", + "2147483647", + "pivot_input_buffer_size_in_bytes", + "9223372036854775807"))); + for (Map.Entry entry : + Map.of( + "pivot_limit", "2147483648", + "pivot_input_max_rows", "not-a-number", + "pivot_input_buffer_size_in_bytes", "9223372036854775808") + .entrySet()) { + var status = + ConfigManager.validatePivotConfiguration(Map.of(entry.getKey(), entry.getValue())); + assertNotNull(status); + assertEquals(TSStatusCode.EXECUTE_STATEMENT_ERROR.getStatusCode(), status.getCode()); + } + } +} diff --git a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java index dfb2fb7d441b5..494a55e099cb1 100644 --- a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java +++ b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java @@ -1611,4 +1611,6 @@ private DataNodeMiscMessages() {} public static final String EXCEPTION_BUFFER_SIZE_SHOULD_BE_GREATER_THAN_0_BB68B5C4 = "bufferSize should be greater than 0"; + public static final String LOG_INVALID_PIVOT_CONFIGURATION_VALUE_FOR_ARG_ARG_KEEPING_ARG_FCB21FF0 = + "Invalid PIVOT configuration value for {}: {}; keeping {}"; } diff --git a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java index be040f13e21eb..dbbfddd64e8f1 100644 --- a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java +++ b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java @@ -4094,4 +4094,61 @@ private DataNodeQueryMessages() {} public static final String EXCEPTION_PLAN_NODE_ARG_IS_ALREADY_REGISTERED_ON_MEMORY_SIDE_ARG_NOT_ARG_4C1BB625 = "Plan node %s is already registered on memory side %s, not %s"; public static final String EXCEPTION_MEMORY_RESERVATION_IS_NOT_REGISTERED_FOR_QUERY_ARG_FRAGMENT_ARG_PLAN_NODE_ARG_67A4B81F = "Memory reservation is not registered for query %s, fragment %s, plan node %s"; public static final String LOG_SHARED_EXCHANGE_BUDGET_FOR_FI_ARG_INPUT_ARG_OUTPUT_ARG_98AE1109 = "Shared exchange budget for FI {}: INPUT={}, OUTPUT={}"; + public static final String EXCEPTION_COLUMNS_EXPRESSIONS_CANNOT_BE_USED_TO_INFER_SOURCE_COLUMN_GROUPS_IN_A_MULTI_VALUE_UNPIVOT_D780C590 = + "COLUMNS expressions cannot be used to infer source column groups in a multi-value UNPIVOT"; + public static final String EXCEPTION_COLUMNS_EXPRESSION_IN_UNPIVOT_DID_NOT_SELECT_ANY_SOURCE_COLUMNS_933A605D = + "COLUMNS expression in UNPIVOT did not select any source columns"; + public static final String EXCEPTION_ALL_SOURCE_COLUMN_GROUPS_IN_A_MULTI_VALUE_UNPIVOT_MUST_CONTAIN_THE_SAME_NUMBER_OF_COLUMNS_3B42B00F = + "All source column groups in a multi-value UNPIVOT must contain the same number of columns"; + public static final String EXCEPTION_THE_NUMBER_OF_SOURCE_COLUMNS_IN_EACH_UNPIVOT_GROUP_MUST_MATCH_THE_NUMBER_OF_VALUE_COLUMNS_B6681F40 = + "The number of source columns in each UNPIVOT group must match the number of value columns"; + public static final String EXCEPTION_SOURCE_COLUMN_GROUPS_IN_A_MULTI_VALUE_UNPIVOT_DO_NOT_SUPPORT_EXPRESSIONS_OR_CASTS_2234733C = + "Source column groups in a multi-value UNPIVOT do not support expressions or casts"; + public static final String EXCEPTION_EACH_SOURCE_EXPRESSION_IN_A_SINGLE_VALUE_UNPIVOT_MUST_REFERENCE_EXACTLY_ONE_INPUT_COLUMN_8A926C8E = + "Each source expression in a single-value UNPIVOT must reference exactly one input column"; + public static final String EXCEPTION_DUPLICATE_COLUMN_NAME_IN_UNPIVOT_OUTPUT_ARG_75EC57F1 = + "Duplicate column name in UNPIVOT output: %s"; + public static final String EXCEPTION_UNPIVOT_SOURCE_TYPES_ARE_NOT_COMPATIBLE_C171107C = + "UNPIVOT source types are not compatible"; + public static final String EXCEPTION_UNPIVOT_SOURCE_COLUMN_DOES_NOT_EXIST_ARG_F62BA0EC = + "UNPIVOT source column does not exist: %s"; + public static final String EXCEPTION_UNPIVOT_SOURCE_COLUMN_IS_AMBIGUOUS_ARG_8533957A = + "UNPIVOT source column is ambiguous: %s"; + public static final String EXCEPTION_INCLUDE_NULLS_IS_ONLY_SUPPORTED_IN_SQL_STYLE_UNPIVOT_055D9EEA = + "INCLUDE NULLS is only supported in SQL-style UNPIVOT"; + public static final String EXCEPTION_UNPIVOT_SOURCE_EXPRESSIONS_CANNOT_CONTAIN_AGGREGATE_WINDOW_OR_SUBQUERY_EXPRESSIONS_D0BF754B = + "UNPIVOT source expressions cannot contain aggregate, window, or subquery expressions"; + public static final String EXCEPTION_DYNAMIC_PIVOT_REQUIRES_INPUT_MATERIALIZATION_BEFORE_ANALYSIS_7867520A = + "Dynamic PIVOT requires input materialization before analysis"; + public static final String EXCEPTION_PIVOT_ON_EXPRESSIONS_MUST_NOT_CONTAIN_AGGREGATES_WINDOW_FUNCTIONS_OR_SUBQUERIES_7871DB04 = + "PIVOT ON expressions must not contain aggregates, window functions or subqueries"; + public static final String EXCEPTION_PIVOT_USING_MUST_CONTAIN_EXACTLY_ONE_AGGREGATE_WITHOUT_DISTINCT_WINDOW_FUNCTIONS_OR_SUBQUERIES_C8F1E226 = + "PIVOT USING must contain exactly one aggregate without DISTINCT, window functions or subqueries"; + public static final String EXCEPTION_PIVOT_GROUP_BY_ACCEPTS_ONLY_INPUT_COLUMN_REFERENCES_4C143F37 = + "PIVOT GROUP BY accepts only input column references"; + public static final String EXCEPTION_PIVOT_IN_VALUES_MUST_BE_CONSTANT_AND_CONVERTIBLE_TO_THE_ON_EXPRESSION_TYPE_760875BC = + "PIVOT IN values must be constant and convertible to the ON expression type"; + public static final String EXCEPTION_DUPLICATE_VALUE_IN_PIVOT_IN_LIST_ARG_9051FEC2 = + "Duplicate value in PIVOT IN list: %s"; + public static final String EXCEPTION_PIVOT_USING_CANNOT_REFERENCE_INPUT_COLUMNS_OUTSIDE_ITS_AGGREGATE_54DA6E29 = + "PIVOT USING cannot reference input columns outside its aggregate"; + public static final String EXCEPTION_DYNAMIC_PIVOT_NESTING_DEPTH_EXCEEDS_EIGHT_A3F4F166 = + "Dynamic PIVOT nesting depth exceeds eight"; + public static final String MESSAGE_DISCOVER_DYNAMIC_PIVOT_INPUT_5EBD15BB = + "Discover dynamic PIVOT input"; + public static final String EXCEPTION_DYNAMIC_PIVOT_INPUT_SCHEMA_CHANGED_6A26E6B0 = + "Dynamic PIVOT input schema changed"; + public static final String EXCEPTION_DYNAMIC_PIVOT_INPUT_EXCEEDS_PIVOT_INPUT_BUFFER_SIZE_IN_BYTES_9E2FA334 = + "Dynamic PIVOT input exceeds pivot_input_buffer_size_in_bytes"; + public static final String EXCEPTION_DYNAMIC_PIVOT_INPUT_EXCEEDS_PIVOT_INPUT_MAX_ROWS_BC1F0F40 = + "Dynamic PIVOT input exceeds pivot_input_max_rows"; + public static final String EXCEPTION_DYNAMIC_PIVOT_ON_TYPE_IS_NOT_SUPPORTED_A8F057D9 = + "Dynamic PIVOT ON type is not supported"; + public static final String EXCEPTION_DYNAMIC_PIVOT_PRODUCED_NO_COLUMNS_AND_NO_ROW_DIMENSION_COLUMNS_ARE_AVAILABLE_25DD42E0 = + "Dynamic PIVOT produced no columns and no row dimension columns are available"; + public static final String MESSAGE_UNPIVOT_ARG_8F0CF12D = "Unpivot-%s"; + public static final String MESSAGE_SOURCES_ARG_C7AF5307 = "Sources: %s"; + public static final String MESSAGE_INCLUDENULLS_ARG_13BDAF67 = "IncludeNulls: %s"; + public static final String EXCEPTION_PIVOT_OUTPUT_COLUMN_COUNT_ARG_EXCEEDS_PIVOT_LIMIT_ARG_644AC9B8 = + "PIVOT output column count %d exceeds pivot_limit %d"; } diff --git a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java index d91103c16bab4..67a5757d96c70 100644 --- a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java +++ b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeMiscMessages.java @@ -1593,4 +1593,6 @@ private DataNodeMiscMessages() {} public static final String EXCEPTION_BUFFER_SIZE_SHOULD_BE_GREATER_THAN_0_BB68B5C4 = "bufferSize 应大于 0"; + public static final String LOG_INVALID_PIVOT_CONFIGURATION_VALUE_FOR_ARG_ARG_KEEPING_ARG_FCB21FF0 = + "无效的 PIVOT 配置值 {}:{};保留当前值 {}"; } diff --git a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java index e0c51972501df..5b1d3a943f79c 100644 --- a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java +++ b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java @@ -4849,4 +4849,61 @@ private DataNodeQueryMessages() {} public static final String EXCEPTION_PLAN_NODE_ARG_IS_ALREADY_REGISTERED_ON_MEMORY_SIDE_ARG_NOT_ARG_4C1BB625 = "PlanNode %s 已注册到内存侧 %s,不能注册到 %s"; public static final String EXCEPTION_MEMORY_RESERVATION_IS_NOT_REGISTERED_FOR_QUERY_ARG_FRAGMENT_ARG_PLAN_NODE_ARG_67A4B81F = "查询 %s、Fragment %s、PlanNode %s 尚未注册内存账目"; public static final String LOG_SHARED_EXCHANGE_BUDGET_FOR_FI_ARG_INPUT_ARG_OUTPUT_ARG_98AE1109 = "FI {} 的共享 exchange 预算:INPUT={},OUTPUT={}"; + public static final String EXCEPTION_COLUMNS_EXPRESSIONS_CANNOT_BE_USED_TO_INFER_SOURCE_COLUMN_GROUPS_IN_A_MULTI_VALUE_UNPIVOT_D780C590 = + "COLUMNS 表达式不能推断多 VALUE UNPIVOT 的源列组"; + public static final String EXCEPTION_COLUMNS_EXPRESSION_IN_UNPIVOT_DID_NOT_SELECT_ANY_SOURCE_COLUMNS_933A605D = + "UNPIVOT 中的 COLUMNS 表达式未选中任何源列"; + public static final String EXCEPTION_ALL_SOURCE_COLUMN_GROUPS_IN_A_MULTI_VALUE_UNPIVOT_MUST_CONTAIN_THE_SAME_NUMBER_OF_COLUMNS_3B42B00F = + "多 VALUE UNPIVOT 的所有源列组必须包含相同数量的列"; + public static final String EXCEPTION_THE_NUMBER_OF_SOURCE_COLUMNS_IN_EACH_UNPIVOT_GROUP_MUST_MATCH_THE_NUMBER_OF_VALUE_COLUMNS_B6681F40 = + "每个 UNPIVOT 源列组的列数必须等于 VALUE 列数"; + public static final String EXCEPTION_SOURCE_COLUMN_GROUPS_IN_A_MULTI_VALUE_UNPIVOT_DO_NOT_SUPPORT_EXPRESSIONS_OR_CASTS_2234733C = + "多 VALUE UNPIVOT 的源列组不支持表达式或类型转换"; + public static final String EXCEPTION_EACH_SOURCE_EXPRESSION_IN_A_SINGLE_VALUE_UNPIVOT_MUST_REFERENCE_EXACTLY_ONE_INPUT_COLUMN_8A926C8E = + "单 VALUE UNPIVOT 的每个源表达式必须恰好引用一个输入列"; + public static final String EXCEPTION_DUPLICATE_COLUMN_NAME_IN_UNPIVOT_OUTPUT_ARG_75EC57F1 = + "UNPIVOT 输出列名重复:%s"; + public static final String EXCEPTION_UNPIVOT_SOURCE_TYPES_ARE_NOT_COMPATIBLE_C171107C = + "UNPIVOT 源列类型不兼容"; + public static final String EXCEPTION_UNPIVOT_SOURCE_COLUMN_DOES_NOT_EXIST_ARG_F62BA0EC = + "UNPIVOT 源列不存在:%s"; + public static final String EXCEPTION_UNPIVOT_SOURCE_COLUMN_IS_AMBIGUOUS_ARG_8533957A = + "UNPIVOT 源列存在歧义:%s"; + public static final String EXCEPTION_INCLUDE_NULLS_IS_ONLY_SUPPORTED_IN_SQL_STYLE_UNPIVOT_055D9EEA = + "只有 SQL 风格 UNPIVOT 支持 INCLUDE NULLS"; + public static final String EXCEPTION_UNPIVOT_SOURCE_EXPRESSIONS_CANNOT_CONTAIN_AGGREGATE_WINDOW_OR_SUBQUERY_EXPRESSIONS_D0BF754B = + "UNPIVOT 源表达式不能包含聚合、窗口或子查询表达式"; + public static final String EXCEPTION_DYNAMIC_PIVOT_REQUIRES_INPUT_MATERIALIZATION_BEFORE_ANALYSIS_7867520A = + "动态 PIVOT 需要在分析前物化输入"; + public static final String EXCEPTION_PIVOT_ON_EXPRESSIONS_MUST_NOT_CONTAIN_AGGREGATES_WINDOW_FUNCTIONS_OR_SUBQUERIES_7871DB04 = + "PIVOT ON 表达式不能包含聚合函数、窗口函数或子查询"; + public static final String EXCEPTION_PIVOT_USING_MUST_CONTAIN_EXACTLY_ONE_AGGREGATE_WITHOUT_DISTINCT_WINDOW_FUNCTIONS_OR_SUBQUERIES_C8F1E226 = + "PIVOT USING 必须恰好包含一个聚合函数,且不能包含 DISTINCT、窗口函数或子查询"; + public static final String EXCEPTION_PIVOT_GROUP_BY_ACCEPTS_ONLY_INPUT_COLUMN_REFERENCES_4C143F37 = + "PIVOT GROUP BY 仅支持引用输入列"; + public static final String EXCEPTION_PIVOT_IN_VALUES_MUST_BE_CONSTANT_AND_CONVERTIBLE_TO_THE_ON_EXPRESSION_TYPE_760875BC = + "PIVOT IN 值必须是常量且可以转换为 ON 表达式的类型"; + public static final String EXCEPTION_DUPLICATE_VALUE_IN_PIVOT_IN_LIST_ARG_9051FEC2 = + "PIVOT IN 列表中存在重复值:%s"; + public static final String EXCEPTION_PIVOT_USING_CANNOT_REFERENCE_INPUT_COLUMNS_OUTSIDE_ITS_AGGREGATE_54DA6E29 = + "PIVOT USING 不得在聚合函数外引用输入列"; + public static final String EXCEPTION_DYNAMIC_PIVOT_NESTING_DEPTH_EXCEEDS_EIGHT_A3F4F166 = + "动态 PIVOT 嵌套深度超过八层"; + public static final String MESSAGE_DISCOVER_DYNAMIC_PIVOT_INPUT_5EBD15BB = + "发现动态 PIVOT 输入"; + public static final String EXCEPTION_DYNAMIC_PIVOT_INPUT_SCHEMA_CHANGED_6A26E6B0 = + "动态 PIVOT 输入结构发生变化"; + public static final String EXCEPTION_DYNAMIC_PIVOT_INPUT_EXCEEDS_PIVOT_INPUT_BUFFER_SIZE_IN_BYTES_9E2FA334 = + "动态 PIVOT 输入超出 pivot_input_buffer_size_in_bytes"; + public static final String EXCEPTION_DYNAMIC_PIVOT_INPUT_EXCEEDS_PIVOT_INPUT_MAX_ROWS_BC1F0F40 = + "动态 PIVOT 输入超出 pivot_input_max_rows"; + public static final String EXCEPTION_DYNAMIC_PIVOT_ON_TYPE_IS_NOT_SUPPORTED_A8F057D9 = + "动态 PIVOT ON 类型不受支持"; + public static final String EXCEPTION_DYNAMIC_PIVOT_PRODUCED_NO_COLUMNS_AND_NO_ROW_DIMENSION_COLUMNS_ARE_AVAILABLE_25DD42E0 = + "动态 PIVOT 没有生成列且不存在行维度列"; + public static final String MESSAGE_UNPIVOT_ARG_8F0CF12D = "逆透视-%s"; + public static final String MESSAGE_SOURCES_ARG_C7AF5307 = "源列: %s"; + public static final String MESSAGE_INCLUDENULLS_ARG_13BDAF67 = "包含空值: %s"; + public static final String EXCEPTION_PIVOT_OUTPUT_COLUMN_COUNT_ARG_EXCEEDS_PIVOT_LIMIT_ARG_644AC9B8 = + "PIVOT 输出列数 %d 超过 pivot_limit %d"; } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBDescriptor.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBDescriptor.java index b22ad2dc96920..9d38ebe50e0f2 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBDescriptor.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBDescriptor.java @@ -1131,6 +1131,8 @@ public void loadProperties(TrimProperties properties) throws BadNodeUrlException commonConfig.setMaxRowsInCteBuffer(maxRowsInCteBuffer); } + loadPivotConfiguration(properties); + loadFixedSizeLimitForQuery( properties, "mods_cache_size_limit_per_fi_in_bytes", conf::setModsCacheSizeLimitPerFI); @@ -2415,6 +2417,8 @@ public synchronized void loadHotModifiedProps(TrimProperties properties) commonConfig.setMaxRowsInCteBuffer(maxRowsInCteBuffer); } + loadPivotConfiguration(properties); + // max sub-task num for information table scan int maxSubTaskNumForInformationTableScan = Integer.parseInt( @@ -2449,11 +2453,73 @@ public synchronized void loadHotModifiedProps(TrimProperties properties) // in both the startup (loadProperties) and hot-reload (loadHotModifiedProps) paths, so that // local *and* remote `show configuration` (which reads each node's own map over RPC) stay // correct. + private void loadPivotConfiguration(Properties properties) { + commonConfig.setPivotLimit( + parsePositivePivotInt(properties, "pivot_limit", commonConfig.getPivotLimit())); + commonConfig.setPivotInputBufferSizeInBytes( + parsePositivePivotLong( + properties, + "pivot_input_buffer_size_in_bytes", + commonConfig.getPivotInputBufferSizeInBytes())); + commonConfig.setPivotInputMaxRows( + parsePositivePivotInt( + properties, "pivot_input_max_rows", commonConfig.getPivotInputMaxRows())); + } + + private int parsePositivePivotInt(Properties properties, String key, int previous) { + String value = properties.getProperty(key); + if (value == null) { + return previous; + } + try { + int parsed = Integer.parseInt(value.trim()); + if (parsed > 0) { + return parsed; + } + } catch (NumberFormatException ignored) { + // A malformed or overflowing value does not replace the current effective value. + } + LOGGER.warn( + DataNodeMiscMessages.LOG_INVALID_PIVOT_CONFIGURATION_VALUE_FOR_ARG_ARG_KEEPING_ARG_FCB21FF0, + key, + value, + previous); + return previous; + } + + private long parsePositivePivotLong(Properties properties, String key, long previous) { + String value = properties.getProperty(key); + if (value == null) { + return previous; + } + try { + long parsed = Long.parseLong(value.trim()); + if (parsed > 0) { + return parsed; + } + } catch (NumberFormatException ignored) { + // A malformed or overflowing value does not replace the current effective value. + } + LOGGER.warn( + DataNodeMiscMessages.LOG_INVALID_PIVOT_CONFIGURATION_VALUE_FOR_ARG_ARG_KEEPING_ARG_FCB21FF0, + key, + value, + previous); + return previous; + } + private void overlayEffectiveConfigurationValues() { ConfigurationFileUtils.updateAppliedProperties( "cte_buffer_size_in_bytes", Long.toString(commonConfig.getCteBufferSize())); ConfigurationFileUtils.updateAppliedProperties( "max_rows_in_cte_buffer", Integer.toString(commonConfig.getMaxRowsInCteBuffer())); + ConfigurationFileUtils.updateAppliedProperties( + "pivot_limit", Integer.toString(commonConfig.getPivotLimit())); + ConfigurationFileUtils.updateAppliedProperties( + "pivot_input_buffer_size_in_bytes", + Long.toString(commonConfig.getPivotInputBufferSizeInBytes())); + ConfigurationFileUtils.updateAppliedProperties( + "pivot_input_max_rows", Integer.toString(commonConfig.getPivotInputMaxRows())); ConfigurationFileUtils.updateAppliedProperties( "max_sub_task_num_for_information_table_scan", Integer.toString(conf.getMaxSubTaskNumForInformationTableScan())); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/DataNodeInternalRPCServiceImpl.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/DataNodeInternalRPCServiceImpl.java index 1f5f95b446020..16d482ded6c9e 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/DataNodeInternalRPCServiceImpl.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/protocol/thrift/impl/DataNodeInternalRPCServiceImpl.java @@ -2850,16 +2850,31 @@ public TSStatus killQueryInstance(TKillQueryInstanceReq req) { iQueryExecution -> allowedUsername == null || allowedUsername.equals(iQueryExecution.getUser())) .forEach(IQueryExecution::cancel); + coordinator.getAllQueryContexts().stream() + .filter( + queryContext -> + allowedUsername == null || allowedUsername.equals(queryContext.getUsername())) + .forEach(org.apache.iotdb.db.queryengine.common.MPPQueryContext::cancelQuery); } else { Optional queryExecution = coordinator.getAllQueryExecutions().stream() .filter(iQueryExecution -> iQueryExecution.getQueryId().equals(queryId)) .findAny(); - if (queryExecution.isPresent()) { - if (allowedUsername != null && !allowedUsername.equals(queryExecution.get().getUser())) { + org.apache.iotdb.db.queryengine.common.MPPQueryContext queryContext = + coordinator.getQueryContext(queryId); + if (queryExecution.isPresent() || queryContext != null) { + String queryUser = + queryExecution.isPresent() + ? queryExecution.get().getUser() + : queryContext.getUsername(); + if (allowedUsername != null && !allowedUsername.equals(queryUser)) { return new TSStatus(TSStatusCode.NO_PERMISSION.getStatusCode()); } - queryExecution.get().cancel(); + if (queryContext != null) { + queryContext.cancelQuery(); + } else { + queryExecution.ifPresent(IQueryExecution::cancel); + } } else { return new TSStatus(TSStatusCode.NO_SUCH_QUERY.getStatusCode()) .setMessage(DataNodeMiscMessages.NO_SUCH_QUERY); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/common/MPPQueryContext.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/common/MPPQueryContext.java index d609c5c8e028e..41ef7e1665fee 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/common/MPPQueryContext.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/common/MPPQueryContext.java @@ -32,6 +32,7 @@ import org.apache.iotdb.commons.queryengine.plan.relational.metadata.ColumnSchema; import org.apache.iotdb.commons.queryengine.plan.relational.planner.Symbol; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Identifier; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.PivotRelation; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Query; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Table; import org.apache.iotdb.commons.queryengine.utils.cte.CteDataStore; @@ -46,6 +47,7 @@ import org.apache.iotdb.db.queryengine.plan.analyze.QueryType; import org.apache.iotdb.db.queryengine.plan.analyze.TypeProvider; import org.apache.iotdb.db.queryengine.plan.analyze.lock.SchemaLockType; +import org.apache.iotdb.db.queryengine.plan.execution.IQueryExecution; import org.apache.iotdb.db.queryengine.plan.planner.LocalExecutionPlanner; import org.apache.iotdb.db.queryengine.plan.planner.memory.NotThreadSafeMemoryReservationManager; import org.apache.iotdb.db.queryengine.plan.planner.memory.OperatorMemoryNotEnoughException; @@ -53,6 +55,7 @@ import org.apache.iotdb.db.queryengine.plan.relational.metadata.spill.DeviceEntryIOContext; import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ExplainOutputFormat; import org.apache.iotdb.db.queryengine.statistics.QueryPlanStatistics; +import org.apache.iotdb.rpc.TSStatusCode; import com.google.common.collect.ImmutableList; import org.apache.tsfile.read.filter.basic.Filter; @@ -62,6 +65,7 @@ import java.nio.file.Paths; import java.time.ZoneId; +import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; @@ -86,6 +90,9 @@ public class MPPQueryContext implements IAuditEntity { private String sql; private String auditSqlString; private final QueryId queryId; + private final List cancellationListeners = new ArrayList<>(); + private boolean cancellationRequested; + private IQueryExecution queryExecution; /** The type of explanation for a query. */ public enum ExplainType { @@ -182,6 +189,10 @@ public enum ExplainType { private Map, Query> cteQueries = new HashMap<>(); + // These stores are owned by this query, not by any internal discovery query. + private final Map, PivotInputStore> pivotInputStores = new HashMap<>(); + private final Set> borrowedPivotInputStores = new HashSet<>(); + // Stores the EXPLAIN/EXPLAIN ANALYZE results for Common Table Expressions (CTEs) // Key: CTE table reference // Value: Pair containing (max line length of the explain output, list of formatted explain lines) @@ -277,6 +288,7 @@ public void releaseMemoryForSchemaTree() { } public void prepareForRetry() { + releasePivotInputStores(); if (!isInnerTriggeredQuery()) { cleanUpCte(); } @@ -373,12 +385,70 @@ public void setTimeOut(long timeOut) { } public void checkTimeOut() { + if (isCancellationRequested()) { + throw new org.apache.iotdb.commons.exception.IoTDBRuntimeException( + DataNodeQueryMessages.QUERY_KILLED_BY_OTHERS, + TSStatusCode.QUERY_WAS_KILLED.getStatusCode(), + true); + } long currentTime = System.currentTimeMillis(); if (currentTime - startTime >= timeOut) { throw new QueryTimeoutRuntimeException(startTime, currentTime, timeOut); } } + public synchronized boolean isCancellationRequested() { + return cancellationRequested; + } + + public void cancelQuery() { + List listeners; + IQueryExecution execution; + synchronized (this) { + if (cancellationRequested) { + return; + } + cancellationRequested = true; + listeners = new ArrayList<>(cancellationListeners); + cancellationListeners.clear(); + execution = queryExecution; + } + listeners.forEach(Runnable::run); + if (execution != null) { + execution.cancel(); + } + } + + public void addCancellationListener(Runnable listener) { + boolean runImmediately; + synchronized (this) { + runImmediately = cancellationRequested; + if (!runImmediately) { + cancellationListeners.add(listener); + } + } + if (runImmediately) { + listener.run(); + } + } + + public void setParentQueryContext(MPPQueryContext parent) { + if (parent != null) { + parent.addCancellationListener(this::cancelQuery); + } + } + + public void setQueryExecution(IQueryExecution execution) { + boolean cancelImmediately; + synchronized (this) { + queryExecution = execution; + cancelImmediately = cancellationRequested; + } + if (cancelImmediately) { + execution.cancel(); + } + } + public void setQueryType(QueryType queryType) { this.queryType = queryType; } @@ -1032,6 +1102,44 @@ public void addCteQuery(Table table, Query query) { cteQueries.put(NodeRef.of(table), query); } + public PivotInputStore getPivotInputStore(PivotRelation relation) { + return pivotInputStores.get(NodeRef.of(relation)); + } + + public Map, PivotInputStore> getPivotInputStores() { + return Map.copyOf(pivotInputStores); + } + + // A discovery query can read already prepared inner PIVOTs but must not own their buffers. + public void borrowPivotInputStores(Map, PivotInputStore> stores) { + stores.forEach( + (key, store) -> { + if (!pivotInputStores.containsKey(key)) { + pivotInputStores.put(key, store); + borrowedPivotInputStores.add(key); + } + }); + } + + public void addPivotInputStore(PivotRelation relation, PivotInputStore store) { + NodeRef key = NodeRef.of(relation); + PivotInputStore previous = pivotInputStores.put(key, store); + if (previous != null && !borrowedPivotInputStores.remove(key)) { + previous.clear(); + } + } + + public void releasePivotInputStores() { + pivotInputStores.forEach( + (key, store) -> { + if (!borrowedPivotInputStores.contains(key)) { + store.clear(); + } + }); + pivotInputStores.clear(); + borrowedPivotInputStores.clear(); + } + public Map, Query> getCteQueries() { return cteQueries; } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/common/PivotInputStore.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/common/PivotInputStore.java new file mode 100644 index 0000000000000..c401cd20f1301 --- /dev/null +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/common/PivotInputStore.java @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.db.queryengine.common; + +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.PivotRelation; +import org.apache.iotdb.commons.queryengine.utils.cte.CteDataStore; +import org.apache.iotdb.db.queryengine.plan.planner.memory.NotThreadSafeMemoryReservationManager; + +import java.util.List; + +/** A single dynamic PIVOT's materialized input and the values discovered from that same input. */ +public final class PivotInputStore { + private final CteDataStore data; + private final List> values; + private final List inputColumnNames; + private final int inputColumnCount; + private final NotThreadSafeMemoryReservationManager reservation; + private boolean cleared; + + public PivotInputStore( + CteDataStore data, + List> values, + List inputColumnNames, + int inputColumnCount, + NotThreadSafeMemoryReservationManager reservation) { + this.data = data; + this.values = values.stream().map(List::copyOf).toList(); + this.inputColumnNames = List.copyOf(inputColumnNames); + this.inputColumnCount = inputColumnCount; + this.reservation = reservation; + } + + public CteDataStore getData() { + return data; + } + + public List> getValues() { + return values; + } + + public List getInputColumnNames() { + return inputColumnNames; + } + + public int getInputColumnCount() { + return inputColumnCount; + } + + public void clear() { + if (!cleared) { + cleared = true; + data.clear(); + reservation.releaseAllReservedMemory(); + } + } +} diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/Coordinator.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/Coordinator.java index 79e6e38d4fe1f..a27ddaa4c87d8 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/Coordinator.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/Coordinator.java @@ -39,6 +39,7 @@ import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Expression; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Literal; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Parameter; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.PivotRelation; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Query; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Table; import org.apache.iotdb.commons.queryengine.plan.relational.type.InternalTypeManager; @@ -54,6 +55,7 @@ import org.apache.iotdb.db.queryengine.common.DataNodeEndPoints; import org.apache.iotdb.db.queryengine.common.MPPQueryContext; import org.apache.iotdb.db.queryengine.common.MPPQueryContext.ExplainType; +import org.apache.iotdb.db.queryengine.common.PivotInputStore; import org.apache.iotdb.db.queryengine.common.QueryId; import org.apache.iotdb.db.queryengine.execution.QueryIdGenerator; import org.apache.iotdb.db.queryengine.execution.QueryState; @@ -240,6 +242,7 @@ public class Coordinator { private static final IMemoryBlock coordinatorMemoryBlock; private final ConcurrentHashMap queryExecutionMap; + private final ConcurrentHashMap queryContextMap; private final BlockingDeque currentQueriesInfo = new LinkedBlockingDeque<>(); private final AtomicInteger[] currentQueriesCostHistogram = new AtomicInteger[61]; @@ -284,6 +287,7 @@ public class Coordinator { private Coordinator() { this.queryExecutionMap = new ConcurrentHashMap<>(); + this.queryContextMap = new ConcurrentHashMap<>(); this.typeManager = new InternalTypeManager(); this.executor = getQueryExecutor(); this.scheduledExecutor = getScheduledExecutor(); @@ -327,6 +331,26 @@ private ExecutionResult execution( boolean debug, boolean readOnlyInternalQuery, BiFunction iQueryExecutionFactory) { + return execution( + queryId, + session, + sql, + userQuery, + debug, + readOnlyInternalQuery, + null, + iQueryExecutionFactory); + } + + private ExecutionResult execution( + long queryId, + SessionInfo session, + String sql, + boolean userQuery, + boolean debug, + boolean readOnlyInternalQuery, + MPPQueryContext parentQueryContext, + BiFunction iQueryExecutionFactory) { long startTime = System.currentTimeMillis(); QueryId globalQueryId = queryIdGenerator.createNextQueryId(); MPPQueryContext queryContext = null; @@ -344,7 +368,10 @@ private ExecutionResult execution( DataNodeEndPoints.LOCAL_HOST_INTERNAL_ENDPOINT); queryContext.setUserQuery(userQuery); queryContext.setDebug(debug); + queryContext.setParentQueryContext(parentQueryContext); + queryContextMap.put(globalQueryId.getId(), queryContext); IQueryExecution execution = iQueryExecutionFactory.apply(queryContext, startTime); + queryContext.setQueryExecution(execution); if (readOnlyInternalQuery) { InternalQueryExecutor.validateReadOnlyQuery(execution); } @@ -363,6 +390,7 @@ private ExecutionResult execution( return result; } finally { if (queryContext != null) { + queryContextMap.remove(globalQueryId.getId(), queryContext); queryContext.releaseAllMemoryReservedForFrontEnd(); } DataNodeSchemaLockManager.getInstance().releaseReadLock(queryContext); @@ -506,15 +534,128 @@ public ExecutionResult executeForTableModel( boolean userQuery, boolean debug, boolean isVerbose) { + return executeForTableModel( + statement, + sqlParser, + clientSession, + queryId, + session, + sql, + metadata, + cteQueries, + Map.of(), + explainType, + explainOutputFormat, + timeOut, + userQuery, + debug, + isVerbose); + } + + public ExecutionResult executeForTableModel( + org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Statement statement, + SqlParser sqlParser, + IClientSession clientSession, + long queryId, + SessionInfo session, + String sql, + Metadata metadata, + Map, Query> cteQueries, + Map, PivotInputStore> pivotInputStores, + ExplainType explainType, + ExplainOutputFormat explainOutputFormat, + long timeOut, + boolean userQuery, + boolean debug, + boolean isVerbose) { + return executeForTableModel( + statement, + sqlParser, + clientSession, + queryId, + session, + sql, + metadata, + cteQueries, + pivotInputStores, + explainType, + explainOutputFormat, + timeOut, + userQuery, + debug, + isVerbose, + null); + } + + public ExecutionResult executeForTableModel( + org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Statement statement, + SqlParser sqlParser, + IClientSession clientSession, + long queryId, + SessionInfo session, + String sql, + Metadata metadata, + Map, Query> cteQueries, + Map, PivotInputStore> pivotInputStores, + ExplainType explainType, + ExplainOutputFormat explainOutputFormat, + long timeOut, + boolean userQuery, + boolean debug, + boolean isVerbose, + MPPQueryContext parentQueryContext) { + return executeForTableModel( + statement, + sqlParser, + clientSession, + queryId, + session, + sql, + metadata, + cteQueries, + pivotInputStores, + explainType, + explainOutputFormat, + timeOut, + userQuery, + debug, + isVerbose, + parentQueryContext, + Collections.emptyList(), + Collections.emptyMap()); + } + + public ExecutionResult executeForTableModel( + org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Statement statement, + SqlParser sqlParser, + IClientSession clientSession, + long queryId, + SessionInfo session, + String sql, + Metadata metadata, + Map, Query> cteQueries, + Map, PivotInputStore> pivotInputStores, + ExplainType explainType, + ExplainOutputFormat explainOutputFormat, + long timeOut, + boolean userQuery, + boolean debug, + boolean isVerbose, + MPPQueryContext parentQueryContext, + List parameters, + Map, Expression> parameterLookup) { return execution( queryId, session, sql, userQuery, debug, + false, + parentQueryContext, ((queryContext, startTime) -> { queryContext.setInnerTriggeredQuery(true); queryContext.setCteQueries(cteQueries); + queryContext.borrowPivotInputStores(pivotInputStores); queryContext.setExplainType(explainType); queryContext.setExplainOutputFormat(explainOutputFormat); queryContext.setVerbose(isVerbose); @@ -525,7 +666,9 @@ public ExecutionResult executeForTableModel( queryContext, metadata, timeOut > 0 ? timeOut : CONFIG.getQueryTimeoutThreshold(), - startTime); + startTime, + parameters, + parameterLookup); })); } @@ -705,6 +848,28 @@ private IQueryExecution createQueryExecutionForTableModel( final Metadata metadata, final long timeOut, final long startTime) { + return createQueryExecutionForTableModel( + statement, + sqlParser, + clientSession, + queryContext, + metadata, + timeOut, + startTime, + Collections.emptyList(), + Collections.emptyMap()); + } + + private IQueryExecution createQueryExecutionForTableModel( + final org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Statement statement, + final SqlParser sqlParser, + final IClientSession clientSession, + final MPPQueryContext queryContext, + final Metadata metadata, + final long timeOut, + final long startTime, + final List initialParameters, + final Map, Expression> initialParameterLookup) { queryContext.setTimeOut(timeOut); queryContext.setStartTime(startTime); if (statement instanceof DropDB @@ -790,8 +955,8 @@ private IQueryExecution createQueryExecutionForTableModel( // Initialize variables for TableModelPlanner org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Statement statementToUse = statement; - List parameters = Collections.emptyList(); - Map, Expression> parameterLookup = Collections.emptyMap(); + List parameters = initialParameters; + Map, Expression> parameterLookup = initialParameterLookup; // Unwrap Explain/ExplainAnalyze to check for inner Execute/ExecuteImmediate org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Statement innerStatement = @@ -884,6 +1049,14 @@ public IQueryExecution getQueryExecution(Long queryId) { return queryExecutionMap.get(queryId); } + public MPPQueryContext getQueryContext(String queryId) { + return queryContextMap.get(queryId); + } + + public List getAllQueryContexts() { + return new ArrayList<>(queryContextMap.values()); + } + public List getAllQueryExecutions() { return new ArrayList<>(queryExecutionMap.values()); } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/QueryExecution.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/QueryExecution.java index b8f753d70a016..05ab47f104c41 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/QueryExecution.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/QueryExecution.java @@ -422,6 +422,7 @@ public void stopAndCleanup(Throwable t) { /** Release the resources that current QueryExecution hold with a specified exception */ private void releaseResource(Throwable t) { + context.releasePivotInputStores(); context.recordDeviceEntryDiskIOMetricsOnRelease(); // close ResultHandle to unblock client's getResult request // Actually, we should not close the ResultHandle when the QueryExecution is Finished. diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/PlanGraphJsonPrinter.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/PlanGraphJsonPrinter.java index a5f6e06145306..959f6dbffbf9a 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/PlanGraphJsonPrinter.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/PlanGraphJsonPrinter.java @@ -31,6 +31,7 @@ import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.ProjectNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.SortNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.UnionNode; +import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.UnpivotNode; import org.apache.iotdb.db.queryengine.execution.operator.process.copyto.tsfile.CopyToTsFileOptions; import org.apache.iotdb.db.queryengine.plan.relational.planner.node.CopyToNode; import org.apache.iotdb.db.queryengine.plan.relational.planner.node.DeviceTableScanNode; @@ -120,6 +121,9 @@ private static JsonObject buildProperties(PlanNode node) { ProjectNode n = (ProjectNode) node; properties.add("OutputSymbols", toJsonArray(n.getOutputSymbols())); properties.add("Expressions", toJsonArray(n.getAssignments().getMap().values())); + } else if (node instanceof UnpivotNode n) { + properties.add("Sources", toJsonArray(n.getNames())); + properties.addProperty("IncludeNulls", n.isIncludeNulls()); } else if (node instanceof LimitNode) { LimitNode n = (LimitNode) node; properties.addProperty("Count", n.getCount()); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/PlanGraphPrinter.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/PlanGraphPrinter.java index 557bd714d920f..f292085b6f5f1 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/PlanGraphPrinter.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/plan/node/PlanGraphPrinter.java @@ -47,6 +47,7 @@ import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.TableFunctionProcessorNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.TopKRankingNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.UnionNode; +import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.UnpivotNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.ValueFillNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.ValuesNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.WindowNode; @@ -145,6 +146,19 @@ public class PlanGraphPrinter implements PlanVisitor, PlanGraphPrin "CheckAllFilesInTSFileManagerCost"; public static final String READ_TSFILE_CACHE_VALUE_FILES_COST = "ReadTsFileCacheValueFilesCost"; + @Override + public List visitUnpivot(UnpivotNode node, GraphContext context) { + List lines = new ArrayList<>(); + lines.add( + String.format( + DataNodeQueryMessages.MESSAGE_UNPIVOT_ARG_8F0CF12D, node.getPlanNodeId().getId())); + lines.add(String.format(DataNodeQueryMessages.MESSAGE_SOURCES_ARG_C7AF5307, node.getNames())); + lines.add( + String.format( + DataNodeQueryMessages.MESSAGE_INCLUDENULLS_ARG_13BDAF67, node.isIncludeNulls())); + return render(node, lines, context); + } + @Override public List visitPlan(PlanNode node, GraphContext context) { List boxValue = new ArrayList<>(); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/Analysis.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/Analysis.java index 884d5cbd4e74a..822c7471d7f3b 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/Analysis.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/Analysis.java @@ -45,6 +45,7 @@ import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Offset; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.OrderBy; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Parameter; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.PivotRelation; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.QualifiedName; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.QuantifiedComparisonExpression; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Query; @@ -57,6 +58,7 @@ import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.SubsetDefinition; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Table; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.TableFunctionInvocation; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.UnpivotRelation; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.WindowFrame; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.With; import org.apache.iotdb.commons.queryengine.plan.statement.component.FillPolicy; @@ -141,6 +143,26 @@ public class Analysis implements IAnalysis { // We need to track this separately because there's no node we can attach it to. private final Map, Scope> implicitFromScopes = new LinkedHashMap<>(); private final Map, Scope> scopes = new LinkedHashMap<>(); + private final Map, PivotBinding> pivotBindings = new LinkedHashMap<>(); + + public void setPivotBinding(PivotRelation relation, PivotBinding binding) { + pivotBindings.put(NodeRef.of(relation), binding); + } + + public PivotBinding getPivotBinding(PivotRelation relation) { + return pivotBindings.get(NodeRef.of(relation)); + } + + private final Map, UnpivotBinding> unpivotBindings = + new LinkedHashMap<>(); + + public void setUnpivotBinding(UnpivotRelation relation, UnpivotBinding binding) { + unpivotBindings.put(NodeRef.of(relation), binding); + } + + public UnpivotBinding getUnpivotBinding(UnpivotRelation relation) { + return unpivotBindings.get(NodeRef.of(relation)); + } private final Map, ResolvedField> columnReferences = new LinkedHashMap<>(); @@ -434,8 +456,12 @@ public List getAggregates(QuerySpecification query) { } public boolean noAggregates() { - return aggregates.isEmpty() - || (aggregates.size() == 1 && aggregates.entrySet().iterator().next().getValue().isEmpty()); + // PIVOT aggregates are bound to a relation rather than a QuerySpecification. An empty + // table scan must still run through the aggregation (not finish during partition lookup). + return pivotBindings.isEmpty() + && (aggregates.isEmpty() + || (aggregates.size() == 1 + && aggregates.entrySet().iterator().next().getValue().isEmpty())); } public void setOrderByAggregates(OrderBy node, List aggregates) { diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/Analyzer.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/Analyzer.java index 8b46055d02a8f..bd72d0d3484ad 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/Analyzer.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/Analyzer.java @@ -42,6 +42,7 @@ public class Analyzer { private final StatementAnalyzerFactory statementAnalyzerFactory; + private final PivotInputPreparer pivotInputPreparer; private final MPPQueryContext context; private final SessionInfo session; @@ -61,6 +62,27 @@ public Analyzer( final Map, Expression> parameterLookup, final StatementRewrite statementRewrite, final WarningCollector warningCollector) { + this( + context, + session, + statementAnalyzerFactory, + parameters, + parameterLookup, + statementRewrite, + warningCollector, + PivotInputPreparer.NOOP); + } + + public Analyzer( + final MPPQueryContext context, + final SessionInfo session, + final StatementAnalyzerFactory statementAnalyzerFactory, + final List parameters, + final Map, Expression> parameterLookup, + final StatementRewrite statementRewrite, + final WarningCollector warningCollector, + final PivotInputPreparer pivotInputPreparer) { + this.pivotInputPreparer = requireNonNull(pivotInputPreparer); this.context = context; this.session = requireNonNull(session, DataNodeQueryMessages.EXCEPTION_SESSION_IS_NULL_6CF0F47D); @@ -86,43 +108,62 @@ public Analysis analyze(Statement statement) { parameterLookup, warningCollector); - Analysis analysis = new Analysis(rewrittenStatement, parameterLookup); - analysis.setSqlParser(statementAnalyzerFactory.getSqlParser()); - // Register CTE passed by parent query. - context - .getCteQueries() - .forEach((tableRef, query) -> analysis.registerNamedQuery(tableRef.getNode(), query)); - - Statement innerStatement = - rewrittenStatement instanceof PipeEnriched - ? ((PipeEnriched) rewrittenStatement).getInnerStatement() - : rewrittenStatement; - if (innerStatement instanceof WrappedInsertStatement) { - WrappedInsertStatement insertStatement = (WrappedInsertStatement) innerStatement; - if (insertStatement.getDatabase() != null) { - analysis.setDatabaseName(insertStatement.getDatabase()); + try { + pivotInputPreparer.prepare( + rewrittenStatement, + statementAnalyzerFactory, + context, + session, + parameters, + parameterLookup, + warningCollector); + } catch (RuntimeException | Error failure) { + context.releasePivotInputStores(); + throw failure; + } + + try { + Analysis analysis = new Analysis(rewrittenStatement, parameterLookup); + analysis.setSqlParser(statementAnalyzerFactory.getSqlParser()); + // Register CTE passed by parent query. + context + .getCteQueries() + .forEach((tableRef, query) -> analysis.registerNamedQuery(tableRef.getNode(), query)); + + Statement innerStatement = + rewrittenStatement instanceof PipeEnriched + ? ((PipeEnriched) rewrittenStatement).getInnerStatement() + : rewrittenStatement; + if (innerStatement instanceof WrappedInsertStatement) { + WrappedInsertStatement insertStatement = (WrappedInsertStatement) innerStatement; + if (insertStatement.getDatabase() != null) { + analysis.setDatabaseName(insertStatement.getDatabase()); + } else if (session.getDatabaseName().isPresent()) { + analysis.setDatabaseName(session.getDatabaseName().get()); + } else { + throw new SemanticException( + DataNodeQueryMessages.DATABASE_IS_NOT_SPECIFIED_FOR_INSERT + statement); + } } else if (session.getDatabaseName().isPresent()) { analysis.setDatabaseName(session.getDatabaseName().get()); - } else { - throw new SemanticException( - DataNodeQueryMessages.DATABASE_IS_NOT_SPECIFIED_FOR_INSERT + statement); } - } else if (session.getDatabaseName().isPresent()) { - analysis.setDatabaseName(session.getDatabaseName().get()); - } - long startTime = System.nanoTime(); - StatementAnalyzer analyzer = - statementAnalyzerFactory.createStatementAnalyzer( - analysis, context, session, warningCollector, CorrelationSupport.ALLOWED); + long startTime = System.nanoTime(); + StatementAnalyzer analyzer = + statementAnalyzerFactory.createStatementAnalyzer( + analysis, context, session, warningCollector, CorrelationSupport.ALLOWED); - analyzer.analyze(rewrittenStatement); - if (analysis.isQuery()) { - long analyzeCost = System.nanoTime() - startTime; - QueryPlanCostMetricSet.getInstance().recordTablePlanCost(ANALYZER, analyzeCost); - context.setAnalyzeCost(analyzeCost); - } + analyzer.analyze(rewrittenStatement); + if (analysis.isQuery()) { + long analyzeCost = System.nanoTime() - startTime; + QueryPlanCostMetricSet.getInstance().recordTablePlanCost(ANALYZER, analyzeCost); + context.setAnalyzeCost(analyzeCost); + } - return analysis; + return analysis; + } catch (RuntimeException | Error failure) { + context.releasePivotInputStores(); + throw failure; + } } } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/PivotBinding.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/PivotBinding.java new file mode 100644 index 0000000000000..d4e73b56c1940 --- /dev/null +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/PivotBinding.java @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.db.queryengine.plan.relational.analyzer; + +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Expression; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.FunctionCall; + +import java.util.List; + +/** The analysis-time output layout and typed masks of a static PIVOT. */ +public class PivotBinding { + public record Output(Expression mask, int aggregateIndex) {} + + private final List groupingFields; + private final List onExpressions; + private final List aggregates; + private final List finalExpressions; + private final List outputs; + + public PivotBinding( + List groupingFields, + List onExpressions, + List aggregates, + List finalExpressions, + List outputs) { + this.groupingFields = List.copyOf(groupingFields); + this.onExpressions = List.copyOf(onExpressions); + this.aggregates = List.copyOf(aggregates); + this.finalExpressions = List.copyOf(finalExpressions); + this.outputs = List.copyOf(outputs); + } + + public List getGroupingFields() { + return groupingFields; + } + + public List getOnExpressions() { + return onExpressions; + } + + public List getAggregates() { + return aggregates; + } + + public List getFinalExpressions() { + return finalExpressions; + } + + public List getOutputs() { + return outputs; + } +} diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/PivotInputPreparer.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/PivotInputPreparer.java new file mode 100644 index 0000000000000..87bccf15491bc --- /dev/null +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/PivotInputPreparer.java @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.db.queryengine.plan.relational.analyzer; + +import org.apache.iotdb.commons.queryengine.common.SessionInfo; +import org.apache.iotdb.commons.queryengine.plan.relational.analyzer.NodeRef; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Expression; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Parameter; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Statement; +import org.apache.iotdb.db.queryengine.common.MPPQueryContext; +import org.apache.iotdb.db.queryengine.execution.warnings.WarningCollector; + +import java.util.List; +import java.util.Map; + +/** Prepare data-dependent PIVOT schemas before ordinary statement analysis. */ +@FunctionalInterface +public interface PivotInputPreparer { + PivotInputPreparer NOOP = + (statement, factory, context, session, parameters, lookup, warnings) -> {}; + + void prepare( + Statement statement, + StatementAnalyzerFactory factory, + MPPQueryContext context, + SessionInfo session, + List parameters, + Map, Expression> lookup, + WarningCollector warnings); +} diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/PivotLimitValidator.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/PivotLimitValidator.java new file mode 100644 index 0000000000000..79142b96c092a --- /dev/null +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/PivotLimitValidator.java @@ -0,0 +1,51 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.db.queryengine.plan.relational.analyzer; + +import org.apache.iotdb.commons.exception.SemanticException; +import org.apache.iotdb.db.i18n.DataNodeQueryMessages; + +import java.math.BigInteger; +import java.util.List; + +/** Checks the final output width before constructing any value combinations or result symbols. */ +public final class PivotLimitValidator { + private PivotLimitValidator() {} + + public static BigInteger validate( + int groupCount, int aggregateCount, List valueCounts, int limit) { + BigInteger combinations = BigInteger.ONE; + for (int valueCount : valueCounts) { + combinations = combinations.multiply(BigInteger.valueOf(valueCount)); + } + BigInteger total = + BigInteger.valueOf(groupCount) + .add(combinations.multiply(BigInteger.valueOf(aggregateCount))); + if (total.compareTo(BigInteger.valueOf(limit)) > 0) { + throw new SemanticException( + String.format( + DataNodeQueryMessages + .EXCEPTION_PIVOT_OUTPUT_COLUMN_COUNT_ARG_EXCEEDS_PIVOT_LIMIT_ARG_644AC9B8, + total, + limit)); + } + return total; + } +} diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/StatementAnalyzer.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/StatementAnalyzer.java index 5214b30be992b..e6ffd3e0a82e3 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/StatementAnalyzer.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/StatementAnalyzer.java @@ -20,6 +20,7 @@ package org.apache.iotdb.db.queryengine.plan.relational.analyzer; import org.apache.iotdb.calc.plan.relational.metadata.CommonMetadataUtils; +import org.apache.iotdb.commons.conf.CommonDescriptor; import org.apache.iotdb.commons.exception.IoTDBException; import org.apache.iotdb.commons.exception.IoTDBRuntimeException; import org.apache.iotdb.commons.exception.SemanticException; @@ -74,10 +75,12 @@ import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Node; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.NotExpression; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.NullIfExpression; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.NullLiteral; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Offset; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.OrderBy; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Parameter; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.PatternRecognitionRelation; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.PivotRelation; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.QualifiedName; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.QuantifiedComparisonExpression; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Query; @@ -106,6 +109,7 @@ import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.TimeDurationLiteral; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Trim; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Union; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.UnpivotRelation; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Values; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.VariableDefinition; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.WhenClause; @@ -131,6 +135,7 @@ import org.apache.iotdb.db.i18n.DataNodeQueryMessages; import org.apache.iotdb.db.queryengine.common.MPPQueryContext; import org.apache.iotdb.db.queryengine.common.MPPQueryContext.ExplainType; +import org.apache.iotdb.db.queryengine.common.PivotInputStore; import org.apache.iotdb.db.queryengine.execution.warnings.IoTDBWarning; import org.apache.iotdb.db.queryengine.execution.warnings.WarningCollector; import org.apache.iotdb.db.queryengine.plan.analyze.AnalyzeUtils; @@ -214,6 +219,7 @@ import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.Use; import org.apache.iotdb.db.queryengine.plan.relational.sql.ast.WrappedInsertStatement; import org.apache.iotdb.db.queryengine.plan.relational.type.CompatibleResolver; +import org.apache.iotdb.db.queryengine.plan.relational.type.UnpivotTypeUnifier; import org.apache.iotdb.db.queryengine.plan.statement.crud.InsertBaseStatement; import org.apache.iotdb.db.schemaengine.table.DataNodeTableCache; import org.apache.iotdb.db.schemaengine.table.DataNodeTreeViewSchemaUtils; @@ -298,6 +304,7 @@ import static org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Join.Type.LEFT; import static org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Join.Type.RIGHT; import static org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.PatternRecognitionRelation.RowsPerMatch.ONE; +import static org.apache.iotdb.commons.queryengine.plan.relational.type.TypeSignatureTranslator.toSqlType; import static org.apache.iotdb.commons.schema.table.TsTable.TABLE_ALLOWED_PROPERTIES; import static org.apache.iotdb.commons.udf.builtin.relational.TableBuiltinScalarFunction.DATE_BIN; import static org.apache.iotdb.db.queryengine.execution.warnings.StandardWarningCode.REDUNDANT_ORDER_BY; @@ -4458,6 +4465,567 @@ public Scope visitValues(Values node, Optional scope) { return createAndAssignScope(node, scope, fields); } + @Override + public Scope visitPivotRelation(PivotRelation node, Optional scope) { + Scope inputScope = process(node.getInput(), scope); + RelationType inputType = inputScope.getRelationType(); + PivotInputStore dynamicInput = + node.isDynamic() ? queryContext.getPivotInputStore(node) : null; + if (node.isDynamic() && dynamicInput == null) { + throw new SemanticException( + DataNodeQueryMessages + .EXCEPTION_DYNAMIC_PIVOT_REQUIRES_INPUT_MATERIALIZATION_BEFORE_ANALYSIS_7867520A); + } + if (dynamicInput != null) { + validateDynamicPivotInput(dynamicInput, inputType); + } + List onExpressions = new ArrayList<>(); + List> valueSets = new ArrayList<>(); + Set consumed = new HashSet<>(); + int onIndex = 0; + for (PivotRelation.OnItem item : node.getOnItems()) { + Expression expression = item.expression(); + if (!extractAggregateFunctions(ImmutableList.of(expression)).isEmpty() + || !extractWindowFunctions(ImmutableList.of(expression)).isEmpty() + || preOrder(expression).anyMatch(SubqueryExpression.class::isInstance)) { + throw new SemanticException( + DataNodeQueryMessages + .EXCEPTION_PIVOT_ON_EXPRESSIONS_MUST_NOT_CONTAIN_AGGREGATES_WINDOW_FUNCTIONS_OR_SUBQUERIES_7871DB04); + } + analyzeExpression(expression, inputScope, CorrelationSupport.DISALLOWED); + consumed.addAll(pivotReferencedFields(expression)); + Set distinct = new HashSet<>(); + List selectedValues = + item.values().isPresent() ? item.values().get() : dynamicInput.getValues().get(onIndex); + for (PivotRelation.Value value : selectedValues) { + Expression constant = value.expression(); + if (preOrder(constant) + .filter(Expression.class::isInstance) + .map(Expression.class::cast) + .anyMatch( + ref -> + ref instanceof Identifier + || ref instanceof DereferenceExpression + || ref instanceof SubqueryExpression + || ref instanceof Parameter)) { + throw new SemanticException( + DataNodeQueryMessages + .EXCEPTION_PIVOT_IN_VALUES_MUST_BE_CONSTANT_AND_CONVERTIBLE_TO_THE_ON_EXPRESSION_TYPE_760875BC); + } + Object typed; + try { + typed = + evaluateConstantExpression( + constant instanceof NullLiteral + ? constant + : new Cast(constant, toSqlType(analysis.getType(expression))), + new PlannerContext(metadata, typeManager), + sessionContext); + } catch (RuntimeException e) { + throw new SemanticException( + DataNodeQueryMessages + .EXCEPTION_PIVOT_IN_VALUES_MUST_BE_CONSTANT_AND_CONVERTIBLE_TO_THE_ON_EXPRESSION_TYPE_760875BC); + } + if (!distinct.add(typed)) { + throw new SemanticException( + String.format( + DataNodeQueryMessages.EXCEPTION_DUPLICATE_VALUE_IN_PIVOT_IN_LIST_ARG_9051FEC2, + constant)); + } + } + onExpressions.add(expression); + valueSets.add(selectedValues); + onIndex++; + } + List aggregates = new ArrayList<>(); + List finalExpressions = new ArrayList<>(); + for (PivotRelation.UsingItem item : node.getUsingItems()) { + Expression expression = item.expression(); + List found = extractAggregateFunctions(ImmutableList.of(expression)); + if (found.size() != 1 + || found.get(0).isDistinct() + || !extractWindowFunctions(ImmutableList.of(expression)).isEmpty() + || preOrder(expression).anyMatch(SubqueryExpression.class::isInstance)) { + throw new SemanticException( + DataNodeQueryMessages + .EXCEPTION_PIVOT_USING_MUST_CONTAIN_EXACTLY_ONE_AGGREGATE_WITHOUT_DISTINCT_WINDOW_FUNCTIONS_OR_SUBQUERIES_C8F1E226); + } + FunctionCall aggregate = found.get(0); + analyzeExpression(expression, inputScope, CorrelationSupport.DISALLOWED); + // References outside the aggregate cannot be evaluated after grouping. + if (!pivotOutsideAggregateFields(expression, aggregate).isEmpty()) { + throw new SemanticException( + DataNodeQueryMessages + .EXCEPTION_PIVOT_USING_CANNOT_REFERENCE_INPUT_COLUMNS_OUTSIDE_ITS_AGGREGATE_54DA6E29); + } + consumed.addAll(pivotReferencedFields(aggregate)); + aggregates.add(aggregate); + finalExpressions.add(expression); + } + List grouping = new ArrayList<>(); + if (node.getGroupBy().isPresent()) { + for (Expression expression : node.getGroupBy().get()) { + if (!(expression instanceof Identifier || expression instanceof DereferenceExpression)) { + throw new SemanticException( + DataNodeQueryMessages + .EXCEPTION_PIVOT_GROUP_BY_ACCEPTS_ONLY_INPUT_COLUMN_REFERENCES_4C143F37); + } + analyzeExpression(expression, inputScope, CorrelationSupport.DISALLOWED); + Set indexes = pivotReferencedFields(expression); + if (indexes.size() != 1) { + throw new SemanticException( + DataNodeQueryMessages + .EXCEPTION_PIVOT_GROUP_BY_ACCEPTS_ONLY_INPUT_COLUMN_REFERENCES_4C143F37); + } + int index = indexes.iterator().next(); + if (!grouping.contains(index)) { + grouping.add(index); + } + } + } else { + for (Field field : inputType.getVisibleFields()) { + int index = inputType.indexOf(field); + if (!consumed.contains(index)) { + grouping.add(index); + } + } + } + if (dynamicInput != null) { + ensureDynamicPivotInputProjects(dynamicInput, inputType, consumed); + ensureDynamicPivotInputProjects(dynamicInput, inputType, grouping); + } + if (dynamicInput != null + && grouping.isEmpty() + && valueSets.stream().anyMatch(List::isEmpty)) { + throw new SemanticException( + DataNodeQueryMessages + .EXCEPTION_DYNAMIC_PIVOT_PRODUCED_NO_COLUMNS_AND_NO_ROW_DIMENSION_COLUMNS_ARE_AVAILABLE_25DD42E0); + } + PivotLimitValidator.validate( + grouping.size(), + aggregates.size(), + valueSets.stream().map(List::size).collect(Collectors.toList()), + CommonDescriptor.getInstance().getConfig().getPivotLimit()); + List fields = new ArrayList<>(); + Set usedNames = new HashSet<>(); + for (int index : grouping) { + Field field = inputType.getFieldByIndex(index); + fields.add( + Field.newUnqualified(field.getName(), field.getType(), field.getColumnCategory())); + field.getName().ifPresent(name -> usedNames.add(name.toLowerCase(Locale.ENGLISH))); + } + List outputs = new ArrayList<>(); + buildPivotOutputs( + node, + inputScope, + valueSets, + 0, + new ArrayList<>(), + aggregates, + finalExpressions, + usedNames, + fields, + outputs); + analysis.setPivotBinding( + node, new PivotBinding(grouping, onExpressions, aggregates, finalExpressions, outputs)); + return createAndAssignScope(node, scope, fields); + } + + private void validateDynamicPivotInput(PivotInputStore input, RelationType inputType) { + if (input.getInputColumnNames().size() != input.getInputColumnCount()) { + throw new SemanticException( + DataNodeQueryMessages.EXCEPTION_DYNAMIC_PIVOT_INPUT_SCHEMA_CHANGED_6A26E6B0); + } + if (hasSameInputColumns(input, inputType)) { + if (input.getInputColumnCount() != inputType.getVisibleFields().size()) { + throw new SemanticException( + DataNodeQueryMessages.EXCEPTION_DYNAMIC_PIVOT_INPUT_SCHEMA_CHANGED_6A26E6B0); + } + for (int i = 0; i < input.getInputColumnCount(); i++) { + int physical = input.getData().getColumnIndex2TsBlockColumnIndexList().get(i); + if (!inputType + .getFieldByIndex(i) + .getType() + .equals(input.getData().getTableSchema().getColumns().get(physical).getType())) { + throw new SemanticException( + DataNodeQueryMessages.EXCEPTION_DYNAMIC_PIVOT_INPUT_SCHEMA_CHANGED_6A26E6B0); + } + } + return; + } + + // A projected discovery input intentionally omits columns that the PIVOT cannot read. Match + // the materialized columns to the freshly analyzed input by name instead of by position. + for (int i = 0; i < input.getInputColumnCount(); i++) { + String name = input.getInputColumnNames().get(i); + List matches = + inputType.getVisibleFields().stream() + .filter( + field -> + field.getName().isPresent() && field.getName().get().equalsIgnoreCase(name)) + .collect(Collectors.toList()); + if (matches.size() != 1) { + throw new SemanticException( + DataNodeQueryMessages.EXCEPTION_DYNAMIC_PIVOT_INPUT_SCHEMA_CHANGED_6A26E6B0); + } + int physical = input.getData().getColumnIndex2TsBlockColumnIndexList().get(i); + if (!matches + .get(0) + .getType() + .equals(input.getData().getTableSchema().getColumns().get(physical).getType())) { + throw new SemanticException( + DataNodeQueryMessages.EXCEPTION_DYNAMIC_PIVOT_INPUT_SCHEMA_CHANGED_6A26E6B0); + } + } + } + + private boolean hasSameInputColumns(PivotInputStore input, RelationType inputType) { + if (input.getInputColumnCount() != inputType.getVisibleFields().size() + || input.getInputColumnNames().size() != input.getInputColumnCount()) { + return false; + } + for (int i = 0; i < input.getInputColumnCount(); i++) { + Optional name = inputType.getFieldByIndex(i).getName(); + if (!name.isPresent() || !name.get().equals(input.getInputColumnNames().get(i))) { + return false; + } + } + return true; + } + + private void ensureDynamicPivotInputProjects( + PivotInputStore input, RelationType inputType, Iterable fieldIndexes) { + if (hasSameInputColumns(input, inputType)) { + return; + } + for (int fieldIndex : fieldIndexes) { + Optional name = inputType.getFieldByIndex(fieldIndex).getName(); + if (!name.isPresent() + || input.getInputColumnNames().stream() + .noneMatch(column -> column.equalsIgnoreCase(name.get()))) { + throw new SemanticException( + DataNodeQueryMessages.EXCEPTION_DYNAMIC_PIVOT_INPUT_SCHEMA_CHANGED_6A26E6B0); + } + } + } + + private Set pivotReferencedFields(Node node) { + Set result = new HashSet<>(); + preOrder(node) + .filter(Expression.class::isInstance) + .map(Expression.class::cast) + .map(ref -> analysis.getColumnReferenceFields().get(NodeRef.of(ref))) + .filter(java.util.Objects::nonNull) + .filter(ResolvedField::isLocal) + .forEach(ref -> result.add(ref.getRelationFieldIndex())); + return result; + } + + private Set pivotOutsideAggregateFields(Node node, FunctionCall aggregate) { + if (node == aggregate) { + return java.util.Collections.emptySet(); + } + Set result = new HashSet<>(); + if (node instanceof Expression) { + ResolvedField ref = analysis.getColumnReferenceFields().get(NodeRef.of((Expression) node)); + if (ref != null && ref.isLocal()) { + result.add(ref.getRelationFieldIndex()); + } + } + for (Node child : node.getChildren()) { + result.addAll(pivotOutsideAggregateFields(child, aggregate)); + } + return result; + } + + private void buildPivotOutputs( + PivotRelation node, + Scope inputScope, + List> valueSets, + int depth, + List values, + List aggregates, + List finalExpressions, + Set usedNames, + List fields, + List outputs) { + if (depth != valueSets.size()) { + for (PivotRelation.Value value : valueSets.get(depth)) { + values.add(value); + buildPivotOutputs( + node, + inputScope, + valueSets, + depth + 1, + values, + aggregates, + finalExpressions, + usedNames, + fields, + outputs); + values.remove(values.size() - 1); + } + return; + } + List terms = new ArrayList<>(); + List names = new ArrayList<>(); + for (int i = 0; i < values.size(); i++) { + PivotRelation.Value value = values.get(i); + Expression constant = value.expression(); + terms.add( + constant instanceof NullLiteral + ? new IsNullPredicate(node.getOnItems().get(i).expression()) + : new ComparisonExpression( + ComparisonExpression.Operator.EQUAL, + node.getOnItems().get(i).expression(), + new Cast( + constant, + toSqlType(analysis.getType(node.getOnItems().get(i).expression()))))); + names.add( + value.alias().map(Identifier::getValue).orElseGet(() -> pivotValueName(constant))); + } + Expression mask = + terms.size() == 1 + ? terms.get(0) + : new LogicalExpression(LogicalExpression.Operator.AND, terms); + analyzeExpression(mask, inputScope, CorrelationSupport.DISALLOWED); + String prefix = String.join("_", names); + for (int i = 0; i < aggregates.size(); i++) { + PivotRelation.UsingItem using = node.getUsingItems().get(i); + String base = prefix; + if (aggregates.size() != 1 || using.alias().isPresent()) { + base += + "_" + + using + .alias() + .map(Identifier::getValue) + .orElseGet( + () -> + org.apache.iotdb.commons.queryengine.plan.relational.sql.util + .ExpressionFormatter.formatExpression(using.expression()) + .toLowerCase(Locale.ENGLISH)); + } + String unique = base; + for (int suffix = 1; !usedNames.add(unique.toLowerCase(Locale.ENGLISH)); suffix++) { + unique = base + "_" + suffix; + } + fields.add( + Field.newUnqualified( + unique, analysis.getType(finalExpressions.get(i)), TsTableColumnCategory.FIELD)); + outputs.add(new PivotBinding.Output(mask, i)); + } + } + + private String pivotValueName(Expression expression) { + if (expression instanceof NullLiteral) { + return "NULL"; + } + if (expression instanceof StringLiteral) { + return ((StringLiteral) expression).getValue(); + } + return org.apache.iotdb.commons.queryengine.plan.relational.sql.util.ExpressionFormatter + .formatExpression(expression); + } + + @Override + public Scope visitUnpivotRelation(UnpivotRelation node, Optional scope) { + Scope inputScope = process(node.getInput(), scope); + RelationType inputType = inputScope.getRelationType(); + if (node.isSimplified() && node.isIncludeNulls()) { + throw new SemanticException( + DataNodeQueryMessages + .EXCEPTION_INCLUDE_NULLS_IS_ONLY_SUPPORTED_IN_SQL_STYLE_UNPIVOT_055D9EEA); + } + if (node.getItems().stream().anyMatch(item -> item.excluded().isPresent()) + && node.getValueColumns().size() != 1) { + throw new SemanticException( + DataNodeQueryMessages + .EXCEPTION_COLUMNS_EXPRESSIONS_CANNOT_BE_USED_TO_INFER_SOURCE_COLUMN_GROUPS_IN_A_MULTI_VALUE_UNPIVOT_D780C590); + } + List items = new ArrayList<>(); + // COLUMNS(*) items keep their input field index: duplicate names introduced by a join + // cannot be resolved back to a single field by name. + Map, Integer> expandedFieldIndexes = new HashMap<>(); + for (UnpivotRelation.Item item : node.getItems()) { + if (!item.excluded().isPresent()) { + items.add(item); + continue; + } + Set excluded = new HashSet<>(); + for (Identifier identifier : item.excluded().get()) { + excluded.add(resolveUnpivotColumn(inputType, identifier)); + } + int countBeforeSelector = items.size(); + for (Field field : inputType.getVisibleFields()) { + int index = inputType.indexOf(field); + if (!excluded.contains(index)) { + Expression source = new Identifier(field.getName().orElseThrow()); + expandedFieldIndexes.put(NodeRef.of(source), index); + items.add( + new UnpivotRelation.Item( + ImmutableList.of(source), Optional.empty(), Optional.empty())); + } + } + if (items.size() == countBeforeSelector) { + throw new SemanticException( + DataNodeQueryMessages + .EXCEPTION_COLUMNS_EXPRESSION_IN_UNPIVOT_DID_NOT_SELECT_ANY_SOURCE_COLUMNS_933A605D); + } + } + List> sources = new ArrayList<>(); + List> sourceFieldIndexes = new ArrayList<>(); + List names = new ArrayList<>(); + List valueTypes = new ArrayList<>(); + Set consumed = new HashSet<>(); + for (UnpivotRelation.Item item : items) { + List expressions = item.expressions(); + if (!sources.isEmpty() && expressions.size() != sources.get(0).size()) { + throw new SemanticException( + DataNodeQueryMessages + .EXCEPTION_ALL_SOURCE_COLUMN_GROUPS_IN_A_MULTI_VALUE_UNPIVOT_MUST_CONTAIN_THE_SAME_NUMBER_OF_COLUMNS_3B42B00F); + } + if (expressions.size() != node.getValueColumns().size()) { + throw new SemanticException( + DataNodeQueryMessages + .EXCEPTION_THE_NUMBER_OF_SOURCE_COLUMNS_IN_EACH_UNPIVOT_GROUP_MUST_MATCH_THE_NUMBER_OF_VALUE_COLUMNS_B6681F40); + } + List sourceNames = new ArrayList<>(); + List groupFieldIndexes = new ArrayList<>(); + for (int i = 0; i < expressions.size(); i++) { + Expression expression = expressions.get(i); + Integer expandedFieldIndex = expandedFieldIndexes.get(NodeRef.of(expression)); + Type type; + int fieldIndex; + if (expandedFieldIndex != null) { + fieldIndex = expandedFieldIndex; + type = inputType.getFieldByIndex(fieldIndex).getType(); + } else { + if (expressions.size() > 1 + && !(expression instanceof Identifier) + && !(expression instanceof DereferenceExpression)) { + throw new SemanticException( + DataNodeQueryMessages + .EXCEPTION_SOURCE_COLUMN_GROUPS_IN_A_MULTI_VALUE_UNPIVOT_DO_NOT_SUPPORT_EXPRESSIONS_OR_CASTS_2234733C); + } + if (!extractAggregateFunctions(ImmutableList.of(expression)).isEmpty() + || !extractWindowFunctions(ImmutableList.of(expression)).isEmpty() + || preOrder(expression).anyMatch(SubqueryExpression.class::isInstance)) { + throw new SemanticException( + DataNodeQueryMessages + .EXCEPTION_UNPIVOT_SOURCE_EXPRESSIONS_CANNOT_CONTAIN_AGGREGATE_WINDOW_OR_SUBQUERY_EXPRESSIONS_D0BF754B); + } + if (expression instanceof Identifier) { + List candidates = + inputType.resolveFields(QualifiedName.of(((Identifier) expression).getValue())); + if (candidates.size() > 1) { + throw new SemanticException( + String.format( + DataNodeQueryMessages + .EXCEPTION_UNPIVOT_SOURCE_COLUMN_IS_AMBIGUOUS_ARG_8533957A, + ((Identifier) expression).getValue())); + } + } + type = + analyzeExpression(expression, inputScope, CorrelationSupport.DISALLOWED) + .getType(expression); + Set references = new HashSet<>(); + preOrder(expression) + .filter(Expression.class::isInstance) + .map(Expression.class::cast) + .map(ref -> analysis.getColumnReferenceFields().get(NodeRef.of(ref))) + .filter(java.util.Objects::nonNull) + .forEach( + ref -> { + if (ref.isLocal()) { + references.add(ref.getRelationFieldIndex()); + } + }); + if (references.size() != 1) { + throw new SemanticException( + DataNodeQueryMessages + .EXCEPTION_EACH_SOURCE_EXPRESSION_IN_A_SINGLE_VALUE_UNPIVOT_MUST_REFERENCE_EXACTLY_ONE_INPUT_COLUMN_8A926C8E); + } + fieldIndex = references.iterator().next(); + } + groupFieldIndexes.add(expandedFieldIndex == null ? -1 : expandedFieldIndex); + consumed.add(fieldIndex); + sourceNames.add(inputType.getFieldByIndex(fieldIndex).getName().orElseThrow()); + if (valueTypes.size() <= i) { + valueTypes.add(type); + } else { + valueTypes.set( + i, + UnpivotTypeUnifier.getCommonType(valueTypes.get(i), type) + .orElseThrow( + () -> + new SemanticException( + DataNodeQueryMessages + .EXCEPTION_UNPIVOT_SOURCE_TYPES_ARE_NOT_COMPATIBLE_C171107C))); + } + } + sources.add(expressions); + sourceFieldIndexes.add(groupFieldIndexes); + names.add(item.alias().map(Identifier::getValue).orElse(String.join("_", sourceNames))); + } + List retained = new ArrayList<>(); + List output = new ArrayList<>(); + for (Field field : inputType.getVisibleFields()) { + int index = inputType.indexOf(field); + if (!consumed.contains(index)) { + retained.add(index); + output.add( + Field.newUnqualified( + field.getName(), + field.getType(), + field.getColumnCategory(), + field.getOriginTable(), + field.getOriginColumnName(), + field.isAliased())); + } + } + output.add( + Field.newUnqualified( + node.getNameColumn().getValue(), StringType.STRING, TsTableColumnCategory.FIELD)); + for (int i = 0; i < valueTypes.size(); i++) { + output.add( + Field.newUnqualified( + node.getValueColumns().get(i).getValue(), + valueTypes.get(i), + TsTableColumnCategory.FIELD)); + } + Set outputNames = new HashSet<>(); + for (Field field : output) { + String name = field.getName().orElseThrow(); + if (!outputNames.add(name.toLowerCase(Locale.ENGLISH))) { + throw new SemanticException( + String.format( + DataNodeQueryMessages + .EXCEPTION_DUPLICATE_COLUMN_NAME_IN_UNPIVOT_OUTPUT_ARG_75EC57F1, + name)); + } + } + analysis.setUnpivotBinding( + node, new UnpivotBinding(retained, sources, sourceFieldIndexes, names, valueTypes)); + return createAndAssignScope(node, scope, output); + } + + private int resolveUnpivotColumn(RelationType inputType, Identifier identifier) { + List fields = inputType.resolveFields(QualifiedName.of(identifier.getValue())); + if (fields.isEmpty()) { + throw new SemanticException( + String.format( + DataNodeQueryMessages.EXCEPTION_UNPIVOT_SOURCE_COLUMN_DOES_NOT_EXIST_ARG_F62BA0EC, + identifier.getValue())); + } + if (fields.size() > 1) { + throw new SemanticException( + String.format( + DataNodeQueryMessages.EXCEPTION_UNPIVOT_SOURCE_COLUMN_IS_AMBIGUOUS_ARG_8533957A, + identifier.getValue())); + } + return inputType.indexOf(fields.get(0)); + } + @Override public Scope visitAliasedRelation(AliasedRelation relation, Optional scope) { analysis.setRelationName(relation, QualifiedName.of(ImmutableList.of(relation.getAlias()))); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/UnpivotBinding.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/UnpivotBinding.java new file mode 100644 index 0000000000000..bdacffe1c7406 --- /dev/null +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/UnpivotBinding.java @@ -0,0 +1,74 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.db.queryengine.plan.relational.analyzer; + +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Expression; + +import com.google.common.collect.ImmutableList; +import org.apache.tsfile.read.common.type.Type; + +import java.util.List; + +/** Resolved, query-local UNPIVOT schema; source expressions are evaluated before expansion. */ +public final class UnpivotBinding { + private final List retained; + private final List> sources; + private final List> sourceFieldIndexes; + private final List names; + private final List valueTypes; + + public UnpivotBinding( + List retained, + List> sources, + List> sourceFieldIndexes, + List names, + List valueTypes) { + this.retained = ImmutableList.copyOf(retained); + this.sources = + sources.stream().map(ImmutableList::copyOf).collect(ImmutableList.toImmutableList()); + this.sourceFieldIndexes = + sourceFieldIndexes.stream() + .map(ImmutableList::copyOf) + .collect(ImmutableList.toImmutableList()); + this.names = ImmutableList.copyOf(names); + this.valueTypes = ImmutableList.copyOf(valueTypes); + } + + public List getRetained() { + return retained; + } + + public List> getSources() { + return sources; + } + + /** Input field index for a source, or -1 when the source is an explicit expression. */ + public List> getSourceFieldIndexes() { + return sourceFieldIndexes; + } + + public List getNames() { + return names; + } + + public List getValueTypes() { + return valueTypes; + } +} diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/CoordinatorPivotInputPreparer.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/CoordinatorPivotInputPreparer.java new file mode 100644 index 0000000000000..aadbb79096000 --- /dev/null +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/CoordinatorPivotInputPreparer.java @@ -0,0 +1,457 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.db.queryengine.plan.relational.planner; + +import org.apache.iotdb.commons.conf.CommonDescriptor; +import org.apache.iotdb.commons.exception.IoTDBRuntimeException; +import org.apache.iotdb.commons.exception.SemanticException; +import org.apache.iotdb.commons.queryengine.common.SessionInfo; +import org.apache.iotdb.commons.queryengine.plan.relational.analyzer.NodeRef; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.AllColumns; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.BooleanLiteral; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.DereferenceExpression; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.DoubleLiteral; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Expression; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.GenericLiteral; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Identifier; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.LongLiteral; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Node; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Parameter; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.PivotRelation; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Query; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Select; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.SelectItem; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.SingleColumn; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Statement; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.StringLiteral; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.SubqueryExpression; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Table; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.With; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.WithQuery; +import org.apache.iotdb.commons.queryengine.utils.cte.CteDataStore; +import org.apache.iotdb.db.exception.query.QueryTimeoutRuntimeException; +import org.apache.iotdb.db.i18n.DataNodeQueryMessages; +import org.apache.iotdb.db.protocol.session.SessionManager; +import org.apache.iotdb.db.queryengine.common.MPPQueryContext; +import org.apache.iotdb.db.queryengine.common.PivotInputStore; +import org.apache.iotdb.db.queryengine.common.header.DatasetHeader; +import org.apache.iotdb.db.queryengine.execution.warnings.WarningCollector; +import org.apache.iotdb.db.queryengine.plan.Coordinator; +import org.apache.iotdb.db.queryengine.plan.execution.ExecutionResult; +import org.apache.iotdb.db.queryengine.plan.execution.QueryExecution; +import org.apache.iotdb.db.queryengine.plan.planner.LocalExecutionPlanner; +import org.apache.iotdb.db.queryengine.plan.planner.memory.NotThreadSafeMemoryReservationManager; +import org.apache.iotdb.db.queryengine.plan.relational.analyzer.PivotInputPreparer; +import org.apache.iotdb.db.queryengine.plan.relational.analyzer.StatementAnalyzerFactory; +import org.apache.iotdb.db.queryengine.plan.relational.sql.util.QueryUtil; +import org.apache.iotdb.rpc.TSStatusCode; + +import org.apache.tsfile.block.column.Column; +import org.apache.tsfile.enums.TSDataType; +import org.apache.tsfile.read.common.block.TsBlock; +import org.apache.tsfile.utils.DateUtils; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.stream.IntStream; + +/** Discovers dynamic ON values while buffering the *same* input used by the final aggregation. */ +public final class CoordinatorPivotInputPreparer implements PivotInputPreparer { + private static final long PIVOT_VALUE_MAP_ENTRY_OVERHEAD = 64L; + private static final long PIVOT_VALUE_EXPRESSION_OVERHEAD = 128L; + + private final SessionManager sessions = SessionManager.getInstance(); + + @Override + public void prepare( + Statement statement, + StatementAnalyzerFactory factory, + MPPQueryContext context, + SessionInfo session, + List parameters, + Map, Expression> lookup, + WarningCollector warnings) { + prepareNode(statement, null, 0, context, session, parameters, lookup); + } + + private void prepareNode( + Node node, + With inheritedWith, + int depth, + MPPQueryContext context, + SessionInfo session, + List parameters, + Map, Expression> lookup) { + // A CTE definition can only reference definitions preceding it; a nested query can also + // reference outer WITH definitions. Reattaching the entire WITH clause to a discovery query + // would include the pivot being discovered and recurse, so merge only the visible definitions. + if (node instanceof Query) { + Query query = (Query) node; + With ownWith = query.getWith().orElse(null); + if (ownWith != null && ownWith.isRecursive()) { + // Recursive CTEs are rejected by the analyzer; fail before a discovery query reports a + // misleading missing-table error for the CTE being defined. + throw new SemanticException(DataNodeQueryMessages.RECURSIVE_CTE_IS_NOT_SUPPORTED_YET); + } + if (ownWith != null) { + List preceding = new ArrayList<>(); + for (WithQuery definition : ownWith.getQueries()) { + With visible = mergeVisibleWith(inheritedWith, preceding, ownWith.isRecursive()); + prepareNode(definition.getQuery(), visible, depth, context, session, parameters, lookup); + preceding.add(definition); + } + } + With visible = + ownWith == null + ? inheritedWith + : mergeVisibleWith(inheritedWith, ownWith.getQueries(), ownWith.isRecursive()); + for (Node child : query.getChildren()) { + if (child != ownWith) { + prepareNode(child, visible, depth, context, session, parameters, lookup); + } + } + return; + } + With with = inheritedWith; + int nextDepth = + depth + (node instanceof PivotRelation && ((PivotRelation) node).isDynamic() ? 1 : 0); + if (nextDepth > 8) { + throw new SemanticException( + DataNodeQueryMessages.EXCEPTION_DYNAMIC_PIVOT_NESTING_DEPTH_EXCEEDS_EIGHT_A3F4F166); + } + List children = node.getChildren(); + if (children != null) { + for (Node child : children) { + prepareNode(child, with, nextDepth, context, session, parameters, lookup); + } + } + if (node instanceof PivotRelation + && ((PivotRelation) node).isDynamic() + && context.getPivotInputStore((PivotRelation) node) == null) { + materialize((PivotRelation) node, with, context, session, parameters, lookup); + } + } + + /** + * Combines an outer WITH with the definitions visible at the current nesting level. Definitions + * from the current level shadow outer definitions with the same (case-insensitive) name. + */ + static With mergeVisibleWith( + With inheritedWith, List localQueries, boolean recursive) { + boolean effectiveRecursive = + recursive || (inheritedWith != null && inheritedWith.isRecursive()); + if (localQueries.isEmpty()) { + return inheritedWith; + } + List visible = new ArrayList<>(); + if (inheritedWith != null) { + Set shadowed = new HashSet<>(); + for (WithQuery query : localQueries) { + shadowed.add(query.getName().getValue().toLowerCase(Locale.ENGLISH)); + } + for (WithQuery query : inheritedWith.getQueries()) { + if (!shadowed.contains(query.getName().getValue().toLowerCase(Locale.ENGLISH))) { + visible.add(query); + } + } + } + visible.addAll(localQueries); + return new With(effectiveRecursive, visible); + } + + private void materialize( + PivotRelation pivot, + With with, + MPPQueryContext context, + SessionInfo session, + List parameters, + Map, Expression> lookup) { + List items = buildDiscoverySelectItems(pivot); + Query source = QueryUtil.simpleQuery(new Select(false, items), pivot.getInput()); + Query query = + with == null + ? source + : new Query( + Optional.of(with), + source.getQueryBody(), + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty()); + Coordinator coordinator = Coordinator.getInstance(); + long queryId = sessions.requestQueryId(); + CteDataStore store = null; + // Front-end reservations are automatically released when Coordinator returns. Keep the + // materialized input in its own reservation until the owning query releases its store. + NotThreadSafeMemoryReservationManager reservation = + new NotThreadSafeMemoryReservationManager( + context.getQueryId(), PivotInputStore.class.getName()); + Throwable failure = null; + try { + context.checkTimeOut(); + long remainingTimeOut = + context.getTimeOut() - (System.currentTimeMillis() - context.getStartTime()); + if (remainingTimeOut <= 0) { + throw new QueryTimeoutRuntimeException( + context.getStartTime(), System.currentTimeMillis(), context.getTimeOut()); + } + ExecutionResult result = + coordinator.executeForTableModel( + query, + new org.apache.iotdb.db.queryengine.plan.relational.sql.parser.SqlParser(), + sessions.getCurrSession(), + queryId, + session, + DataNodeQueryMessages.MESSAGE_DISCOVER_DYNAMIC_PIVOT_INPUT_5EBD15BB, + LocalExecutionPlanner.getInstance().metadata, + context.getCteQueries(), + context.getPivotInputStores(), + MPPQueryContext.ExplainType.NONE, + context.getExplainOutputFormat(), + remainingTimeOut, + false, + context.isDebug(), + context.isVerbose(), + context, + parameters, + lookup); + if (result.status.getCode() != TSStatusCode.SUCCESS_STATUS.getStatusCode()) { + throw new IoTDBRuntimeException(result.status); + } + QueryExecution execution = (QueryExecution) coordinator.getQueryExecution(queryId); + DatasetHeader header = execution.getDatasetHeader(); + List columns = header.getRespColumns(); + int originalCount = columns.size() - pivot.getOnItems().size(); + if (originalCount < 0) { + throw new SemanticException( + DataNodeQueryMessages.EXCEPTION_DYNAMIC_PIVOT_INPUT_SCHEMA_CHANGED_6A26E6B0); + } + List mapping = header.getColumnIndex2TsBlockColumnIndexList(); + if (mapping == null) { + mapping = IntStream.range(0, columns.size()).boxed().toList(); + } + List inputColumnNames = new ArrayList<>(columns.subList(0, originalCount)); + store = + new CteDataStore( + CteMaterializer.getTableSchema(header, "__pivot_input"), + mapping, + CommonDescriptor.getInstance().getConfig().getPivotInputBufferSizeInBytes(), + CommonDescriptor.getInstance().getConfig().getPivotInputMaxRows()); + List> values = new ArrayList<>(); + for (PivotRelation.OnItem on : pivot.getOnItems()) { + values.add(on.values().isPresent() ? null : new LinkedHashMap<>()); + } + while (execution.hasNextResult()) { + context.checkTimeOut(); + Optional batch; + try { + batch = execution.getBatchResult(); + } catch (org.apache.iotdb.commons.exception.IoTDBException e) { + throw new IoTDBRuntimeException(e.getMessage(), e, e.getErrorCode()); + } + if (batch.isEmpty() || batch.get().isEmpty()) { + continue; + } + TsBlock block = batch.get(); + CteDataStore.AddResult added = store.tryAddTsBlock(block); + if (added != CteDataStore.AddResult.SUCCESS) { + throw new IoTDBRuntimeException( + added == CteDataStore.AddResult.BYTES_EXCEEDED + ? DataNodeQueryMessages + .EXCEPTION_DYNAMIC_PIVOT_INPUT_EXCEEDS_PIVOT_INPUT_BUFFER_SIZE_IN_BYTES_9E2FA334 + : DataNodeQueryMessages + .EXCEPTION_DYNAMIC_PIVOT_INPUT_EXCEEDS_PIVOT_INPUT_MAX_ROWS_BC1F0F40, + TSStatusCode.QUERY_EXECUTION_MEMORY_NOT_ENOUGH.getStatusCode(), + true); + } + reservation.reserveMemoryCumulatively(block.getRetainedSizeInBytes()); + for (int i = 0; i < values.size(); i++) { + if (values.get(i) == null) { + continue; + } + Column column = block.getColumn(mapping.get(originalCount + i)); + TSDataType type = header.getRespDataTypes().get(originalCount + i); + Map discoveredValues = values.get(i); + for (int row = 0; row < block.getPositionCount(); row++) { + if (!column.isNull(row)) { + PivotRelation.Value value = valueOf(column, row, type); + String key = value.alias().map(Identifier::getValue).orElse(""); + if (!discoveredValues.containsKey(key)) { + long valueBytes = + PIVOT_VALUE_MAP_ENTRY_OVERHEAD + + PIVOT_VALUE_EXPRESSION_OVERHEAD + + 2L * key.length(); + if (!store.tryReserveExtraBytes(valueBytes)) { + throw new IoTDBRuntimeException( + DataNodeQueryMessages + .EXCEPTION_DYNAMIC_PIVOT_INPUT_EXCEEDS_PIVOT_INPUT_BUFFER_SIZE_IN_BYTES_9E2FA334, + TSStatusCode.QUERY_EXECUTION_MEMORY_NOT_ENOUGH.getStatusCode(), + true); + } + reservation.reserveMemoryCumulatively(valueBytes); + discoveredValues.put(key, value); + } + } + } + } + } + List> discovered = new ArrayList<>(); + for (Map set : values) { + discovered.add( + set == null + ? List.of() + : set.entrySet().stream() + .sorted(Map.Entry.comparingByKey(Comparator.naturalOrder())) + .map(Map.Entry::getValue) + .toList()); + } + reservation.reserveMemoryImmediately(); + context.addPivotInputStore( + pivot, + new PivotInputStore(store, discovered, inputColumnNames, originalCount, reservation)); + } catch (RuntimeException | Error t) { + failure = t; + if (store != null) { + store.clear(); + } + reservation.releaseAllReservedMemory(); + throw t; + } finally { + coordinator.cleanupQueryExecution(queryId, (org.apache.thrift.TBase) null, failure); + } + } + + /** + * Builds the discovery query projection. For an explicit GROUP BY, only the columns referenced by + * grouping, ON and USING expressions are needed; materializing the whole input can otherwise make + * a legal query exceed the PIVOT input budget. Implicit grouping still needs all columns because + * every unconsumed column becomes a grouping column. + */ + List buildDiscoverySelectItems(PivotRelation pivot) { + LinkedHashSet inputColumns = new LinkedHashSet<>(); + boolean canProject = pivot.getGroupBy().isPresent() && pivot.getInput() instanceof Table; + if (canProject) { + boolean[] unsupported = {false}; + pivot.getGroupBy().get().forEach(e -> collectDiscoveryColumns(e, inputColumns, unsupported)); + for (PivotRelation.OnItem item : pivot.getOnItems()) { + collectDiscoveryColumns(item.expression(), inputColumns, unsupported); + } + for (PivotRelation.UsingItem item : pivot.getUsingItems()) { + collectDiscoveryColumns(item.expression(), inputColumns, unsupported); + } + canProject = !unsupported[0] && !inputColumns.isEmpty(); + } + + List items = new ArrayList<>(); + if (canProject) { + for (String column : inputColumns) { + items.add(new SingleColumn(new Identifier(column))); + } + } else { + items.add(new AllColumns()); + } + for (int i = 0; i < pivot.getOnItems().size(); i++) { + items.add( + new SingleColumn( + pivot.getOnItems().get(i).expression(), new Identifier("__pivot_on_" + i))); + } + return items; + } + + private void collectDiscoveryColumns(Node node, Set inputColumns, boolean[] unsupported) { + if (unsupported[0]) { + return; + } + // Qualified references, parameters and subqueries need the original input shape to resolve; + // fall back to SELECT * instead of risking an ambiguous discovery projection. + if (node instanceof DereferenceExpression + || node instanceof Parameter + || node instanceof SubqueryExpression) { + unsupported[0] = true; + return; + } + if (node instanceof Identifier) { + inputColumns.add(((Identifier) node).getValue()); + return; + } + List children = node.getChildren(); + if (children != null) { + for (Node child : children) { + collectDiscoveryColumns(child, inputColumns, unsupported); + } + } + } + + static PivotRelation.Value valueOf(Column column, int row, TSDataType type) { + String name; + Expression literal; + switch (type) { + case BOOLEAN: + name = Boolean.toString(column.getBoolean(row)); + literal = new BooleanLiteral(name); + break; + case INT32: + name = Integer.toString(column.getInt(row)); + literal = new LongLiteral(name); + break; + case INT64: + name = Long.toString(column.getLong(row)); + literal = new LongLiteral(name); + break; + case FLOAT: + name = Float.toString(column.getFloat(row)); + literal = new DoubleLiteral(name); + break; + case DOUBLE: + name = Double.toString(column.getDouble(row)); + literal = new DoubleLiteral(name); + break; + case DATE: + name = DateUtils.parseIntToLocalDate(column.getInt(row)).toString(); + literal = new GenericLiteral("DATE", name); + break; + case TIMESTAMP: + name = Long.toString(column.getLong(row)); + literal = new LongLiteral(name); + break; + case TEXT: + case STRING: + name = + column + .getBinary(row) + .getStringValue(org.apache.tsfile.common.conf.TSFileConfig.STRING_CHARSET); + literal = new StringLiteral(name); + break; + default: + throw new SemanticException( + DataNodeQueryMessages.EXCEPTION_DYNAMIC_PIVOT_ON_TYPE_IS_NOT_SUPPORTED_A8F057D9); + } + return new PivotRelation.Value( + literal, name.isEmpty() ? Optional.empty() : Optional.of(new Identifier(name))); + } +} diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/CteMaterializer.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/CteMaterializer.java index 322e0777b22b1..dfe4c70e51875 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/CteMaterializer.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/CteMaterializer.java @@ -209,7 +209,7 @@ public CteDataStore fetchCteQueryResult( return null; } - private TableSchema getTableSchema(DatasetHeader datasetHeader, String cteName) { + static TableSchema getTableSchema(DatasetHeader datasetHeader, String cteName) { final List columnNames = datasetHeader.getRespColumns(); final List columnDataTypes = datasetHeader.getRespDataTypes(); if (columnNames.size() != columnDataTypes.size()) { @@ -251,7 +251,7 @@ private TableSchema getTableSchema(DatasetHeader datasetHeader, String cteName) * @param originalIndexList original column index list * @return adjusted column index list with sorted values preserving original positions */ - private List adjustColumnIndexMapping(List originalIndexList) { + private static List adjustColumnIndexMapping(List originalIndexList) { if (originalIndexList == null || originalIndexList.isEmpty()) { return originalIndexList; } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/RelationPlanner.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/RelationPlanner.java index 6f5f3c278ed3d..53b2bf1b764a1 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/RelationPlanner.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/RelationPlanner.java @@ -32,6 +32,7 @@ import org.apache.iotdb.commons.queryengine.plan.relational.planner.OrderingScheme; import org.apache.iotdb.commons.queryengine.plan.relational.planner.SortOrder; import org.apache.iotdb.commons.queryengine.plan.relational.planner.Symbol; +import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.AggregationNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.ExceptNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.FilterNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.IntersectNode; @@ -43,6 +44,7 @@ import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.SkipToPosition; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.TableFunctionNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.UnionNode; +import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.UnpivotNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.rowpattern.AggregationLabelSet; import org.apache.iotdb.commons.queryengine.plan.relational.planner.rowpattern.AggregationValuePointer; import org.apache.iotdb.commons.queryengine.plan.relational.planner.rowpattern.ClassifierValuePointer; @@ -55,11 +57,13 @@ import org.apache.iotdb.commons.queryengine.plan.relational.planner.rowpattern.ScalarValuePointer; import org.apache.iotdb.commons.queryengine.plan.relational.planner.rowpattern.ValuePointer; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.AliasedRelation; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Cast; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.CoalesceExpression; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.ComparisonExpression; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.DereferenceExpression; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Except; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Expression; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.FunctionCall; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Identifier; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Intersect; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Join; @@ -70,6 +74,7 @@ import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.MeasureDefinition; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Node; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.PatternRecognitionRelation; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.PivotRelation; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.QualifiedName; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Query; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.QuerySpecification; @@ -84,6 +89,7 @@ import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.TableFunctionInvocation; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.TableSubquery; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Union; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.UnpivotRelation; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Values; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.VariableDefinition; import org.apache.iotdb.commons.queryengine.plan.relational.type.InternalTypeManager; @@ -91,6 +97,7 @@ import org.apache.iotdb.commons.schema.table.column.TsTableColumnCategory; import org.apache.iotdb.db.i18n.DataNodeQueryMessages; import org.apache.iotdb.db.queryengine.common.MPPQueryContext; +import org.apache.iotdb.db.queryengine.common.PivotInputStore; import org.apache.iotdb.db.queryengine.common.QueryId; import org.apache.iotdb.db.queryengine.plan.planner.plan.node.WritePlanNode; import org.apache.iotdb.db.queryengine.plan.planner.plan.node.load.LoadTsFileNode; @@ -111,8 +118,10 @@ import org.apache.iotdb.db.queryengine.plan.relational.analyzer.PatternRecognitionAnalysis.MatchNumberDescriptor; import org.apache.iotdb.db.queryengine.plan.relational.analyzer.PatternRecognitionAnalysis.Navigation; import org.apache.iotdb.db.queryengine.plan.relational.analyzer.PatternRecognitionAnalysis.ScalarInputDescriptor; +import org.apache.iotdb.db.queryengine.plan.relational.analyzer.PivotBinding; import org.apache.iotdb.db.queryengine.plan.relational.analyzer.RelationType; import org.apache.iotdb.db.queryengine.plan.relational.analyzer.Scope; +import org.apache.iotdb.db.queryengine.plan.relational.analyzer.UnpivotBinding; import org.apache.iotdb.db.queryengine.plan.relational.analyzer.tablefunction.TableArgumentAnalysis; import org.apache.iotdb.db.queryengine.plan.relational.analyzer.tablefunction.TableFunctionInvocationAnalysis; import org.apache.iotdb.db.queryengine.plan.relational.function.DataNodeTableBuiltinTableFunction; @@ -176,6 +185,7 @@ import static org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Join.Type.RIGHT; import static org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.PatternRecognitionRelation.RowsPerMatch.ONE; import static org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.SkipTo.Position.PAST_LAST; +import static org.apache.iotdb.commons.queryengine.plan.relational.type.TypeSignatureTranslator.toSqlType; import static org.apache.iotdb.commons.schema.table.InformationSchema.INFORMATION_DATABASE; import static org.apache.iotdb.db.queryengine.plan.relational.analyzer.PatternRecognitionAnalysis.NavigationAnchor.LAST; import static org.apache.iotdb.db.queryengine.plan.relational.analyzer.PatternRecognitionAnalysis.NavigationMode.RUNNING; @@ -441,6 +451,236 @@ public RelationPlan visitNode(final Node node, final Void context) { DataNodeQueryMessages.UNSUPPORTED_NODE_TYPE + node.getClass().getName()); } + @Override + public RelationPlan visitPivotRelation(PivotRelation node, Void context) { + PivotInputStore dynamicInput = node.isDynamic() ? queryContext.getPivotInputStore(node) : null; + RelationPlan input = + dynamicInput == null + ? process(node.getInput(), context) + : planMaterializedPivotInput(node, dynamicInput); + PivotBinding binding = analysis.getPivotBinding(node); + Map, Symbol> onMappings = new LinkedHashMap<>(); + if (dynamicInput != null) { + List columns = dynamicInput.getData().getColumnIndex2TsBlockColumnIndexList(); + List symbols = input.getRoot().getOutputSymbols(); + for (int i = 0; i < node.getOnItems().size(); i++) { + onMappings.put( + NodeRef.of(node.getOnItems().get(i).expression()), + symbols.get(columns.get(dynamicInput.getInputColumnCount() + i))); + } + } + List projections = new ArrayList<>(binding.getOnExpressions()); + for (FunctionCall aggregate : binding.getAggregates()) { + projections.addAll(aggregate.getArguments()); + } + PlanBuilder prepared = + newPlanBuilder(input, analysis) + .withAdditionalIdentityMappings(onMappings) + .appendProjections(projections, symbolAllocator, queryContext); + List masks = + binding.getOutputs().stream() + .map(PivotBinding.Output::mask) + .distinct() + .collect(Collectors.toList()); + PlanBuilder withMasks = prepared.appendProjections(masks, symbolAllocator, queryContext); + List grouping = + binding.getGroupingFields().stream().map(input::getSymbol).collect(Collectors.toList()); + Map aggregations = new LinkedHashMap<>(); + List results = new ArrayList<>(); + for (PivotBinding.Output output : binding.getOutputs()) { + FunctionCall call = binding.getAggregates().get(output.aggregateIndex()); + Symbol result = symbolAllocator.newSymbol(call, analysis.getType(call)); + aggregations.put( + result, + new AggregationNode.Aggregation( + analysis.getResolvedFunction(call), + call.getArguments().stream() + .map(withMasks::translate) + .map(Symbol::toSymbolReference) + .collect(Collectors.toList()), + false, + Optional.empty(), + Optional.empty(), + Optional.of(withMasks.translate(output.mask())))); + results.add(result); + } + PlanNode aggregate = + AggregationNode.singleAggregation( + idAllocator.genPlanNodeId(), + withMasks.getRoot(), + aggregations, + AggregationNode.singleGroupingSet(grouping)); + Assignments.Builder assignments = Assignments.builder(); + List outputSymbols = new ArrayList<>(); + for (Symbol group : grouping) { + assignments.put(group, group.toSymbolReference()); + outputSymbols.add(group); + } + for (int i = 0; i < binding.getOutputs().size(); i++) { + PivotBinding.Output output = binding.getOutputs().get(i); + FunctionCall call = binding.getAggregates().get(output.aggregateIndex()); + Expression expression = binding.getFinalExpressions().get(output.aggregateIndex()); + PlanBuilder finalPlan = + new PlanBuilder( + withMasks + .getTranslations() + .withAdditionalMappings( + Collections.singletonMap( + ScopeAware.scopeAwareKey(call, analysis, withMasks.getScope()), + results.get(i))), + aggregate); + Symbol result = + symbolAllocator.newSymbol( + analysis.getScope(node).getRelationType().getFieldByIndex(outputSymbols.size())); + assignments.put(result, finalPlan.rewrite(expression)); + outputSymbols.add(result); + } + return new RelationPlan( + new ProjectNode(idAllocator.genPlanNodeId(), aggregate, assignments.build()), + analysis.getScope(node), + outputSymbols, + outerContext); + } + + private RelationPlan planMaterializedPivotInput(PivotRelation node, PivotInputStore input) { + CteDataStore data = input.getData(); + List symbols = + data.getTableSchema().getColumns().stream() + .map(column -> symbolAllocator.newSymbol(column.getName(), column.getType())) + .collect(Collectors.toList()); + CteScanNode scan = + new CteScanNode( + idAllocator.genPlanNodeId(), QualifiedName.of("__pivot_input"), symbols, data); + RelationType inputType = analysis.getScope(node.getInput()).getRelationType(); + List fields = new ArrayList<>(); + if (hasSameInputColumns(input, inputType)) { + for (int i = 0; i < input.getInputColumnCount(); i++) { + fields.add(symbols.get(data.getColumnIndex2TsBlockColumnIndexList().get(i))); + } + } else { + // The discovery query projected only the columns the PIVOT can read. Keep the field mapping + // indexed by the original input relation so the analyzer's grouping/ON/USING indexes still + // translate correctly; unused fields get symbols that never appear in the scan. + for (int i = 0; i < inputType.getAllFieldCount(); i++) { + Field field = inputType.getFieldByIndex(i); + int logicalIndex = + findInputColumn(input.getInputColumnNames(), field.getName().orElse(null)); + if (logicalIndex >= 0) { + fields.add(symbols.get(data.getColumnIndex2TsBlockColumnIndexList().get(logicalIndex))); + } else { + fields.add( + symbolAllocator.newSymbol( + field.getName().orElse("__pivot_unused_" + i), field.getType())); + } + } + } + return new RelationPlan(scan, analysis.getScope(node.getInput()), fields, outerContext); + } + + private boolean hasSameInputColumns(PivotInputStore input, RelationType inputType) { + if (input.getInputColumnCount() != inputType.getVisibleFields().size() + || input.getInputColumnNames().size() != input.getInputColumnCount()) { + return false; + } + for (int i = 0; i < input.getInputColumnCount(); i++) { + Optional name = inputType.getFieldByIndex(i).getName(); + if (!name.isPresent() || !name.get().equals(input.getInputColumnNames().get(i))) { + return false; + } + } + return true; + } + + private int findInputColumn(List inputColumnNames, String name) { + if (name == null) { + return -1; + } + int found = -1; + for (int i = 0; i < inputColumnNames.size(); i++) { + if (inputColumnNames.get(i).equalsIgnoreCase(name)) { + if (found >= 0) { + return -1; + } + found = i; + } + } + return found; + } + + @Override + public RelationPlan visitUnpivotRelation(UnpivotRelation node, Void context) { + RelationPlan input = process(node.getInput(), context); + UnpivotBinding binding = analysis.getUnpivotBinding(node); + List expressions = new ArrayList<>(); + for (int sourceIndex = 0; sourceIndex < binding.getSources().size(); sourceIndex++) { + for (int valueIndex = 0; + valueIndex < binding.getSources().get(sourceIndex).size(); + valueIndex++) { + if (binding.getSourceFieldIndexes().get(sourceIndex).get(valueIndex) < 0) { + expressions.add(binding.getSources().get(sourceIndex).get(valueIndex)); + } + } + } + PlanBuilder plan = + newPlanBuilder(input, analysis) + .appendProjections(expressions, symbolAllocator, queryContext); + Assignments.Builder assignments = Assignments.builder(); + assignments.putIdentities(plan.getRoot().getOutputSymbols()); + List> groups = new ArrayList<>(); + for (int sourceIndex = 0; sourceIndex < binding.getSources().size(); sourceIndex++) { + List group = new ArrayList<>(); + for (int valueIndex = 0; valueIndex < binding.getValueTypes().size(); valueIndex++) { + int sourceFieldIndex = binding.getSourceFieldIndexes().get(sourceIndex).get(valueIndex); + Symbol symbol; + Type actualType; + if (sourceFieldIndex >= 0) { + symbol = input.getSymbol(sourceFieldIndex); + actualType = + analysis + .getScope(node.getInput()) + .getRelationType() + .getFieldByIndex(sourceFieldIndex) + .getType(); + } else { + Expression expression = binding.getSources().get(sourceIndex).get(valueIndex); + symbol = plan.translate(expression); + actualType = analysis.getType(expression); + } + Type expectedType = binding.getValueTypes().get(valueIndex); + if (!actualType.equals(expectedType)) { + Symbol coerced = symbolAllocator.newSymbol(symbol.getName(), expectedType); + assignments.put(coerced, new Cast(symbol.toSymbolReference(), toSqlType(expectedType))); + symbol = coerced; + } + group.add(symbol); + } + groups.add(group); + } + PlanNode projected = + new ProjectNode(idAllocator.genPlanNodeId(), plan.getRoot(), assignments.build()); + List retained = + binding.getRetained().stream().map(input::getSymbol).collect(Collectors.toList()); + List output = new ArrayList<>(retained); + output.add(symbolAllocator.newSymbol(node.getNameColumn().getValue(), STRING)); + for (int i = 0; i < binding.getValueTypes().size(); i++) { + output.add( + symbolAllocator.newSymbol( + node.getValueColumns().get(i).getValue(), binding.getValueTypes().get(i))); + } + return new RelationPlan( + new UnpivotNode( + idAllocator.genPlanNodeId(), + projected, + retained, + groups, + binding.getNames(), + output, + node.isIncludeNulls()), + analysis.getScope(node), + output, + outerContext); + } + @Override public RelationPlan visitTableSubquery(final TableSubquery node, final Void context) { final RelationPlan plan = process(node.getQuery(), context); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/TableModelPlanner.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/TableModelPlanner.java index cca616e0a3b17..bb580c1d2b5de 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/TableModelPlanner.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/TableModelPlanner.java @@ -139,7 +139,8 @@ public IAnalysis analyze(final MPPQueryContext context) { parameters, parameterLookup, statementRewrite, - warningCollector) + warningCollector, + new CoordinatorPivotInputPreparer()) .analyze(statement); } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/distribute/TableDistributedPlanGenerator.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/distribute/TableDistributedPlanGenerator.java index 1ead17632aaf1..5d3c13f75de57 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/distribute/TableDistributedPlanGenerator.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/distribute/TableDistributedPlanGenerator.java @@ -69,6 +69,7 @@ import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.TopKNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.TopKRankingNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.UnionNode; +import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.UnpivotNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.ValueFillNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.ValuesNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.WindowNode; @@ -518,6 +519,32 @@ public List visitOffset(OffsetNode node, PlanContext context) { return dealWithPlainSingleChildNode(node, context); } + @Override + public List visitUnpivot(UnpivotNode node, PlanContext context) { + List childrenNodes = node.getChild().accept(this, context); + if (childrenNodes.size() == 1) { + node.setChild(childrenNodes.get(0)); + return Collections.singletonList(node); + } + + // Unpivot expands rows locally, so keep one copy per input fragment and let the parent collect + // the per-region results. Adding several children to the original single-child node would keep + // only the last child and silently drop the other regions. + List resultNodeList = new ArrayList<>(childrenNodes.size()); + for (PlanNode child : childrenNodes) { + resultNodeList.add( + new UnpivotNode( + queryId.genPlanNodeId(), + child, + node.getRetained(), + node.getSources(), + node.getNames(), + node.getOutputSymbols(), + node.isIncludeNulls())); + } + return resultNodeList; + } + @Override public List visitProject(ProjectNode node, PlanContext context) { boolean containsDiff = diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/optimizations/PushAggregationIntoTableScan.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/optimizations/PushAggregationIntoTableScan.java index 984a711cc1e76..5538e09a45512 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/optimizations/PushAggregationIntoTableScan.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/optimizations/PushAggregationIntoTableScan.java @@ -111,6 +111,11 @@ public PlanNode visitAggregation(AggregationNode node, Context context) { } } + // Masked PIVOT aggregates must remain single-stage; a table scan cannot evaluate masks. + if (node.getAggregations().values().stream().anyMatch(AggregationNode.Aggregation::hasMask)) { + return node; + } + // only optimize AggregationNode with raw DeviceTableScanNode if (tableScanNode == null || tableScanNode instanceof AggregationTableScanNode) { // no need to optimize diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/optimizations/PushLimitOffsetIntoTableScan.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/optimizations/PushLimitOffsetIntoTableScan.java index 4449a6e60e6dd..5b5a47b4a9070 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/optimizations/PushLimitOffsetIntoTableScan.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/optimizations/PushLimitOffsetIntoTableScan.java @@ -38,6 +38,7 @@ import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.StreamSortNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.TableFunctionProcessorNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.TopKNode; +import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.UnpivotNode; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Expression; import org.apache.iotdb.commons.schema.table.InformationSchema; import org.apache.iotdb.commons.schema.table.column.TsTableColumnCategory; @@ -165,6 +166,13 @@ public PlanNode visitPreviousFill(PreviousFillNode node, Context context) { } } + @Override + public PlanNode visitUnpivot(UnpivotNode node, Context context) { + context.enablePushDown = false; + node.setChild(node.getChild().accept(this, new Context())); + return node; + } + @Override public PlanNode visitLimit(LimitNode node, Context context) { Context subContext = new Context(); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/optimizations/TransformSortToStreamSort.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/optimizations/TransformSortToStreamSort.java index 90c2c91931d13..f661962925913 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/optimizations/TransformSortToStreamSort.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/optimizations/TransformSortToStreamSort.java @@ -29,6 +29,7 @@ import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.StreamSortNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.TableFunctionProcessorNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.UnionNode; +import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.UnpivotNode; import org.apache.iotdb.commons.schema.table.column.TsTableColumnCategory; import org.apache.iotdb.db.queryengine.common.MPPQueryContext; import org.apache.iotdb.db.queryengine.plan.planner.plan.node.PlanVisitor; @@ -84,6 +85,13 @@ public PlanNode visitPlan(PlanNode node, Context context) { return newNode; } + @Override + public PlanNode visitUnpivot(UnpivotNode node, Context context) { + context.setCanTransform(false); + return node.replaceChildren( + java.util.Collections.singletonList(node.getChild().accept(this, new Context()))); + } + @Override public PlanNode visitSort(SortNode node, Context context) { diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/optimizations/UnaliasSymbolReferences.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/optimizations/UnaliasSymbolReferences.java index 89e377bcffe05..a565b5e580540 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/optimizations/UnaliasSymbolReferences.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/optimizations/UnaliasSymbolReferences.java @@ -53,6 +53,7 @@ import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.TopKNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.TopKRankingNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.UnionNode; +import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.UnpivotNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.ValueFillNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.ValuesNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.WindowNode; @@ -439,6 +440,25 @@ public PlanAndMappings visitValueFill(ValueFillNode node, UnaliasContext context rewrittenSource.getMappings()); } + @Override + public PlanAndMappings visitUnpivot(UnpivotNode node, UnaliasContext context) { + PlanAndMappings rewritten = node.getChild().accept(this, context); + Map mapping = new HashMap<>(rewritten.getMappings()); + SymbolMapper mapper = symbolMapper(mapping); + List> sources = + node.getSources().stream().map(mapper::map).collect(ImmutableList.toImmutableList()); + return new PlanAndMappings( + new UnpivotNode( + node.getPlanNodeId(), + rewritten.getRoot(), + mapper.map(node.getRetained()), + sources, + node.getNames(), + mapper.map(node.getOutputSymbols()), + node.isIncludeNulls()), + mapping); + } + @Override public PlanAndMappings visitOffset(OffsetNode node, UnaliasContext context) { PlanAndMappings rewrittenSource = node.getChild().accept(this, context); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/ast/DefaultTraversalVisitor.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/ast/DefaultTraversalVisitor.java index 9b1c48f37994a..1fc8958cb4c36 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/ast/DefaultTraversalVisitor.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/ast/DefaultTraversalVisitor.java @@ -56,6 +56,7 @@ import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.PatternConcatenation; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.PatternPermutation; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.PatternVariable; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.PivotRelation; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.QuantifiedComparisonExpression; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.QuantifiedPattern; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Query; @@ -74,6 +75,7 @@ import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.SubqueryExpression; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.TableSubquery; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Trim; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.UnpivotRelation; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Values; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.WhenClause; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.With; @@ -210,6 +212,18 @@ public Void visitLimit(Limit node, C context) { return null; } + @Override + public Void visitPivotRelation(PivotRelation node, C context) { + node.getChildren().forEach(child -> process(child, context)); + return null; + } + + @Override + public Void visitUnpivotRelation(UnpivotRelation node, C context) { + node.getChildren().forEach(child -> process(child, context)); + return null; + } + @Override public Void visitQuerySpecification(QuerySpecification node, C context) { process(node.getSelect(), context); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/parser/AstBuilder.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/parser/AstBuilder.java index 71686b52cf7ac..0caa67e526690 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/parser/AstBuilder.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/parser/AstBuilder.java @@ -96,6 +96,7 @@ import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.PatternRecognitionRelation; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.PatternRecognitionRelation.RowsPerMatch; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.PatternVariable; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.PivotRelation; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.ProcessingMode; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.QualifiedName; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.QuantifiedComparisonExpression; @@ -129,6 +130,7 @@ import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Trim; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.TypeParameter; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Union; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.UnpivotRelation; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Values; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.VariableDefinition; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.WhenClause; @@ -2926,6 +2928,121 @@ private static List flatten( return result; } + // PIVOT and UNPIVOT use the same relation AST in both query-body and FROM forms. + private Relation pivotInput(RelationalSqlParser.PivotInputRelationContext ctx) { + Relation input = (Relation) visit(ctx.relationPrimary()); + return ctx.identifier() == null + ? input + : new AliasedRelation(getLocation(ctx), input, (Identifier) visit(ctx.identifier()), null); + } + + private PivotRelation.Value pivotValue(RelationalSqlParser.PivotValueContext ctx) { + return new PivotRelation.Value( + (Expression) visit(ctx.valueExpression()), + Optional.ofNullable(ctx.identifier()).map(identifier -> (Identifier) visit(identifier))); + } + + private PivotRelation.OnItem pivotOnItem(RelationalSqlParser.PivotOnItemContext ctx) { + return new PivotRelation.OnItem( + (Expression) visit(ctx.valueExpression()), + ctx.IN() == null + ? Optional.empty() + : Optional.of(ctx.pivotValue().stream().map(this::pivotValue).collect(toList()))); + } + + private PivotRelation.OnItem pivotOnItem(RelationalSqlParser.PivotStaticOnItemContext ctx) { + return new PivotRelation.OnItem( + (Expression) visit(ctx.valueExpression()), + Optional.of(ctx.pivotValue().stream().map(this::pivotValue).collect(toList()))); + } + + private PivotRelation.UsingItem pivotUsingItem(RelationalSqlParser.PivotUsingItemContext ctx) { + return new PivotRelation.UsingItem( + (Expression) visit(ctx.valueExpression()), + Optional.ofNullable(ctx.identifier()).map(identifier -> (Identifier) visit(identifier))); + } + + private Optional> pivotGroupBy( + List items) { + return items.isEmpty() + ? Optional.empty() + : Optional.of( + items.stream().map(item -> (Expression) visit(item.expression())).collect(toList())); + } + + @Override + public Node visitPivotQueryBody(RelationalSqlParser.PivotQueryBodyContext ctx) { + return new PivotRelation( + getLocation(ctx), + pivotInput(ctx.pivotInputRelation()), + ctx.pivotOnItem().stream().map(this::pivotOnItem).collect(toList()), + ctx.pivotUsingItem().stream().map(this::pivotUsingItem).collect(toList()), + pivotGroupBy(ctx.pivotGroupItem()), + true); + } + + @Override + public Node visitPivotClauseRelation(RelationalSqlParser.PivotClauseRelationContext ctx) { + PivotRelation pivot = + new PivotRelation( + getLocation(ctx), + (Relation) visit(ctx.left), + ctx.pivotStaticOnItem().stream().map(this::pivotOnItem).collect(toList()), + ctx.pivotUsingItem().stream().map(this::pivotUsingItem).collect(toList()), + pivotGroupBy(ctx.pivotGroupItem()), + false); + return ctx.identifier() == null + ? pivot + : new AliasedRelation(getLocation(ctx), pivot, (Identifier) visit(ctx.identifier()), null); + } + + private UnpivotRelation.Item unpivotItem(RelationalSqlParser.UnpivotItemContext ctx) { + Optional> excluded = Optional.empty(); + if (ctx.unpivotColumnsSelector() != null) { + excluded = Optional.of(visit(ctx.unpivotColumnsSelector().identifier(), Identifier.class)); + } + List expressions = visit(ctx.expression(), Expression.class); + return new UnpivotRelation.Item( + expressions, + excluded, + Optional.ofNullable(ctx.identifier()).map(identifier -> (Identifier) visit(identifier))); + } + + @Override + public Node visitUnpivotQueryBody(RelationalSqlParser.UnpivotQueryBodyContext ctx) { + List columns = visit(ctx.identifier(), Identifier.class); + boolean explicitInto = ctx.INTO() != null; + return new UnpivotRelation( + getLocation(ctx), + pivotInput(ctx.pivotInputRelation()), + explicitInto + ? columns.subList(1, columns.size()) + : ImmutableList.of(new Identifier("value")), + explicitInto ? columns.get(0) : new Identifier("name"), + ctx.unpivotItem().stream().map(this::unpivotItem).collect(toList()), + ctx.INCLUDE() != null, + true, + explicitInto); + } + + @Override + public Node visitUnpivotClauseRelation(RelationalSqlParser.UnpivotClauseRelationContext ctx) { + UnpivotRelation unpivot = + new UnpivotRelation( + getLocation(ctx), + (Relation) visit(ctx.left), + visit(ctx.unpivotValueSpec().identifier(), Identifier.class), + (Identifier) visit(ctx.identifier(0)), + ctx.unpivotItem().stream().map(this::unpivotItem).collect(toList()), + ctx.INCLUDE() != null, + false, + true); + return ctx.identifier().size() == 1 + ? unpivot + : new AliasedRelation( + getLocation(ctx), unpivot, (Identifier) visit(ctx.identifier(1)), null); + } + // *************** from clause ***************** @Override public Node visitJoinRelation(RelationalSqlParser.JoinRelationContext ctx) { diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/type/UnpivotTypeUnifier.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/type/UnpivotTypeUnifier.java new file mode 100644 index 0000000000000..ad8bbd9f38efb --- /dev/null +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/type/UnpivotTypeUnifier.java @@ -0,0 +1,53 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.db.queryengine.plan.relational.type; + +import org.apache.tsfile.read.common.type.Type; + +import java.util.Optional; + +import static org.apache.tsfile.read.common.type.BinaryType.TEXT; +import static org.apache.tsfile.read.common.type.DoubleType.DOUBLE; +import static org.apache.tsfile.read.common.type.FloatType.FLOAT; +import static org.apache.tsfile.read.common.type.IntType.INT32; +import static org.apache.tsfile.read.common.type.LongType.INT64; +import static org.apache.tsfile.read.common.type.StringType.STRING; + +/** UNPIVOT permits a smaller set of coercions than the general expression resolver. */ +public final class UnpivotTypeUnifier { + private UnpivotTypeUnifier() {} + + public static Optional getCommonType(Type left, Type right) { + if (left.equals(right)) { + return Optional.of(left); + } + if ((left == TEXT && right == STRING) || (left == STRING && right == TEXT)) { + return CompatibleResolver.getCommonSuperType(left, right); + } + if (isNumeric(left) && isNumeric(right)) { + return CompatibleResolver.getCommonSuperType(left, right); + } + return Optional.empty(); + } + + private static boolean isNumeric(Type type) { + return type == INT32 || type == INT64 || type == FLOAT || type == DOUBLE; + } +} diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/conf/PivotConfigurationTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/conf/PivotConfigurationTest.java new file mode 100644 index 0000000000000..6ef82bf381ed1 --- /dev/null +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/conf/PivotConfigurationTest.java @@ -0,0 +1,90 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.db.conf; + +import org.apache.iotdb.commons.conf.CommonConfig; +import org.apache.iotdb.commons.conf.CommonDescriptor; +import org.apache.iotdb.commons.conf.ConfigurationFileUtils; +import org.apache.iotdb.commons.conf.TrimProperties; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class PivotConfigurationTest { + @Test + public void testStartupAndReloadRetainEffectiveValues() throws Exception { + CommonConfig config = CommonDescriptor.getInstance().getConfig(); + int oldLimit = config.getPivotLimit(); + long oldBytes = config.getPivotInputBufferSizeInBytes(); + int oldRows = config.getPivotInputMaxRows(); + IoTDBDescriptor descriptor = IoTDBDescriptor.getInstance(); + try { + assertEquals("100000", ConfigurationFileUtils.getConfigurationDefaultValue("pivot_limit")); + assertEquals( + "67108864", + ConfigurationFileUtils.getConfigurationDefaultValue("pivot_input_buffer_size_in_bytes")); + assertEquals( + "1000000", ConfigurationFileUtils.getConfigurationDefaultValue("pivot_input_max_rows")); + + TrimProperties properties = new TrimProperties(); + properties.setProperty("pivot_limit", "11"); + properties.setProperty("pivot_input_buffer_size_in_bytes", "1024"); + properties.setProperty("pivot_input_max_rows", "9"); + descriptor.loadProperties(properties); + assertEquals(11, config.getPivotLimit()); + assertEquals(1024, config.getPivotInputBufferSizeInBytes()); + assertEquals(9, config.getPivotInputMaxRows()); + + properties.setProperty("pivot_limit", "12"); + properties.setProperty("pivot_input_buffer_size_in_bytes", "2048"); + properties.setProperty("pivot_input_max_rows", "10"); + descriptor.loadHotModifiedProps(properties); + assertEquals(12, config.getPivotLimit()); + assertEquals(2048, config.getPivotInputBufferSizeInBytes()); + assertEquals(10, config.getPivotInputMaxRows()); + + properties.setProperty("pivot_limit", "2147483648"); + properties.setProperty("pivot_input_buffer_size_in_bytes", "9223372036854775808"); + properties.setProperty("pivot_input_max_rows", "not-a-number"); + descriptor.loadHotModifiedProps(properties); + assertEquals(12, config.getPivotLimit()); + assertEquals(2048, config.getPivotInputBufferSizeInBytes()); + assertEquals(10, config.getPivotInputMaxRows()); + assertEquals("12", ConfigurationFileUtils.getAppliedProperties().get("pivot_limit")); + assertEquals( + "2048", + ConfigurationFileUtils.getAppliedProperties().get("pivot_input_buffer_size_in_bytes")); + assertEquals("10", ConfigurationFileUtils.getAppliedProperties().get("pivot_input_max_rows")); + + properties.setProperty("pivot_limit", "0"); + properties.setProperty("pivot_input_buffer_size_in_bytes", "-1"); + properties.setProperty("pivot_input_max_rows", "0"); + descriptor.loadHotModifiedProps(properties); + assertEquals(12, config.getPivotLimit()); + assertEquals(2048, config.getPivotInputBufferSizeInBytes()); + assertEquals(10, config.getPivotInputMaxRows()); + } finally { + config.setPivotLimit(oldLimit); + config.setPivotInputBufferSizeInBytes(oldBytes); + config.setPivotInputMaxRows(oldRows); + } + } +} diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/common/MPPQueryContextTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/common/MPPQueryContextTest.java index fca6a3600cdf9..08b824e6cebf5 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/common/MPPQueryContextTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/common/MPPQueryContextTest.java @@ -20,7 +20,14 @@ package org.apache.iotdb.db.queryengine.common; import org.apache.iotdb.calc.exception.MemoryNotEnoughException; +import org.apache.iotdb.commons.exception.IoTDBRuntimeException; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Identifier; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.PivotRelation; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.QualifiedName; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Table; +import org.apache.iotdb.commons.queryengine.utils.cte.CteDataStore; import org.apache.iotdb.db.queryengine.plan.planner.LocalExecutionPlanner; +import org.apache.iotdb.db.queryengine.plan.planner.memory.NotThreadSafeMemoryReservationManager; import org.apache.iotdb.db.queryengine.plan.planner.memory.OperatorMemoryNotEnoughException; import org.apache.iotdb.rpc.TSStatusCode; @@ -28,10 +35,96 @@ import org.junit.Assume; import org.junit.Test; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicInteger; + public class MPPQueryContextTest { private static final long MEMORY_BATCH_THRESHOLD = 1024L * 1024L; + @Test + public void cancellationPropagatesToDiscoveryContextAndListenersRegisteredAfterCancel() { + MPPQueryContext parent = new MPPQueryContext(new QueryId("pivot_cancel_parent")); + MPPQueryContext discovery = new MPPQueryContext(new QueryId("pivot_cancel_discovery")); + AtomicInteger listenerCalls = new AtomicInteger(); + discovery.setParentQueryContext(parent); + + parent.cancelQuery(); + discovery.addCancellationListener(listenerCalls::incrementAndGet); + + Assert.assertTrue(discovery.isCancellationRequested()); + Assert.assertEquals(1, listenerCalls.get()); + IoTDBRuntimeException exception = + Assert.assertThrows(IoTDBRuntimeException.class, discovery::checkTimeOut); + Assert.assertEquals(TSStatusCode.QUERY_WAS_KILLED.getStatusCode(), exception.getErrorCode()); + } + + @Test + public void cancellationListenerIsInvokedOnceWhenRacingWithRegistration() { + MPPQueryContext context = new MPPQueryContext(new QueryId("pivot_cancel_listener")); + AtomicInteger listenerCalls = new AtomicInteger(); + + context.addCancellationListener(listenerCalls::incrementAndGet); + context.cancelQuery(); + context.cancelQuery(); + + Assert.assertEquals(1, listenerCalls.get()); + } + + @Test + public void borrowedDynamicPivotInputSurvivesChildQueryCleanup() { + Assume.assumeTrue(LocalExecutionPlanner.getInstance().getFreeMemoryForOperators() >= 128); + MPPQueryContext owner = new MPPQueryContext(new QueryId("pivot_owner")); + MPPQueryContext child = new MPPQueryContext(new QueryId("pivot_child")); + PivotRelation pivot = + new PivotRelation( + null, + new Table(QualifiedName.of("readings")), + List.of(new PivotRelation.OnItem(new Identifier("region"), Optional.empty())), + List.of(), + Optional.empty(), + true); + NotThreadSafeMemoryReservationManager reservation = + new NotThreadSafeMemoryReservationManager(owner.getQueryId(), "borrowed-pivot-test"); + reservation.reserveMemoryCumulatively(128); + reservation.reserveMemoryImmediately(); + PivotInputStore store = + new PivotInputStore( + new CteDataStore(null, List.of(), 1024, 1), List.of(), List.of(), 0, reservation); + owner.addPivotInputStore(pivot, store); + child.borrowPivotInputStores(owner.getPivotInputStores()); + Assert.assertSame(store, child.getPivotInputStore(pivot)); + child.releasePivotInputStores(); + Assert.assertNull(child.getPivotInputStore(pivot)); + Assert.assertSame(store, owner.getPivotInputStore(pivot)); + Assert.assertEquals(128, reservation.getReservedBytesInTotalForTest()); + owner.releasePivotInputStores(); + Assert.assertNull(owner.getPivotInputStore(pivot)); + Assert.assertEquals(0, reservation.getReservedBytesInTotalForTest()); + } + + @Test + public void dynamicPivotInputReservationOutlivesCoordinatorFrontEndCleanup() { + Assume.assumeTrue(LocalExecutionPlanner.getInstance().getFreeMemoryForOperators() >= 128); + MPPQueryContext owner = new MPPQueryContext(new QueryId("pivot_reservation")); + NotThreadSafeMemoryReservationManager reservation = + new NotThreadSafeMemoryReservationManager(owner.getQueryId(), "pivot-input-test"); + reservation.reserveMemoryCumulatively(128); + reservation.reserveMemoryImmediately(); + PivotInputStore store = + new PivotInputStore( + new CteDataStore(null, List.of(), 1024, 1), List.of(), List.of(), 0, reservation); + try { + owner.releaseAllMemoryReservedForFrontEnd(); + Assert.assertEquals(128, reservation.getReservedBytesInTotalForTest()); + } finally { + store.clear(); + } + store.clear(); + Assert.assertEquals(0, reservation.getReservedBytesInTotalForTest()); + } + @Test public void resultSetColumnMemoryNotEnoughExceptionContainsColumnDiagnostics() { MPPQueryContext context = new MPPQueryContext(new QueryId("result_column_oom_test")); diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/CteScanOperatorTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/CteScanOperatorTest.java index ab476f61ee9ea..41a68f37c8c70 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/CteScanOperatorTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/CteScanOperatorTest.java @@ -177,7 +177,7 @@ public void testMultipleCteScanOperators() throws Exception { new CteScanOperator(operatorContext, planNodeId, cteDataStore, queryId); assertEquals(2, cteDataStore.getCount()); - assertEquals(904, cteDataStore.ramBytesUsed()); + assertEquals(920, cteDataStore.ramBytesUsed()); // Both operators should be able to read data assertTrue(operator1.hasNext()); diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/AnalyzerTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/AnalyzerTest.java index bc4fd02b192d7..fa27e0c3c0bc7 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/AnalyzerTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/AnalyzerTest.java @@ -46,11 +46,14 @@ import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.ProjectNode; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Expression; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.LogicalExpression; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.PivotRelation; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.QualifiedName; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Query; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Statement; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.StringLiteral; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.SymbolReference; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Table; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.UnpivotRelation; import org.apache.iotdb.commons.queryengine.plan.relational.type.InternalTypeManager; import org.apache.iotdb.commons.schema.filter.SchemaFilter; import org.apache.iotdb.commons.schema.table.InsertNodeMeasurementInfo; @@ -1680,6 +1683,194 @@ public void fromFirstWithFilterTest() throws OperatorNotFoundException { .collect(Collectors.toSet())); } + @Test + public void staticPivotAnalysisAndPlanningTest() { + Analysis analysis = + analyzeSQL( + "PIVOT table1 ON tag1 IN ('a' AS north, NULL AS missing) " + + "USING COUNT(s1) AS count_s1, MAX(s2) AS max_s2 GROUP BY tag2", + TEST_MATADATA, + QUERY_CONTEXT); + PivotRelation pivot = (PivotRelation) ((Query) analysis.getStatement()).getQueryBody(); + assertEquals( + Arrays.asList( + "tag2", "north_count_s1", "north_max_s2", "missing_count_s1", "missing_max_s2"), + analysis.getScope(pivot).getRelationType().getVisibleFields().stream() + .map(field -> field.getName().orElse("")) + .collect(Collectors.toList())); + assertEquals(4, analysis.getPivotBinding(pivot).getOutputs().size()); + assertFalse(analysis.noAggregates()); + SymbolAllocator allocator = new SymbolAllocator(); + LogicalQueryPlan plan = + new TableLogicalPlanner( + QUERY_CONTEXT, TEST_MATADATA, SESSION_INFO, allocator, DEFAULT_WARNING) + .plan(analysis); + assertTrue(plan.getRootNode() instanceof OutputNode); + DistributedQueryPlan distributed = + new TableDistributedPlanner(analysis, allocator, plan, TEST_MATADATA, null).plan(); + assertFalse(distributed.getFragments().isEmpty()); + } + + @Test + public void staticPivotImplicitGroupingAndNameCollisionTest() { + Analysis analysis = + analyzeSQL( + "PIVOT table1 ON tag1 IN ('a' AS tag2, 'b' AS tag2) USING COUNT(s1)", + TEST_MATADATA, + QUERY_CONTEXT); + PivotRelation pivot = (PivotRelation) ((Query) analysis.getStatement()).getQueryBody(); + List names = + analysis.getScope(pivot).getRelationType().getVisibleFields().stream() + .map(field -> field.getName().orElse("")) + .collect(Collectors.toList()); + assertEquals("tag2_1", names.get(names.size() - 2)); + assertEquals("tag2_2", names.get(names.size() - 1)); + new TableLogicalPlanner( + QUERY_CONTEXT, TEST_MATADATA, SESSION_INFO, new SymbolAllocator(), DEFAULT_WARNING) + .plan(analysis); + } + + @Test + public void staticPivotRejectsInvalidValuesTest() { + assertThrows( + SemanticException.class, + () -> + analyzeSQL( + "PIVOT table1 ON tag1 IN ('a', 'a') USING COUNT(s1) GROUP BY tag2", + TEST_MATADATA, + QUERY_CONTEXT)); + assertThrows( + SemanticException.class, + () -> + analyzeSQL( + "PIVOT table1 ON tag1 IN (tag2) USING COUNT(s1) GROUP BY tag2", + TEST_MATADATA, + QUERY_CONTEXT)); + assertThrows( + SemanticException.class, + () -> + analyzeSQL( + "PIVOT table1 ON tag1 IN ('a') USING COUNT(DISTINCT s1) GROUP BY tag2", + TEST_MATADATA, + QUERY_CONTEXT)); + } + + @Test + public void unpivotAnalysisAndDistributedPlanTest() { + Analysis analysis = + analyzeSQL( + "SELECT * FROM table1 UNPIVOT INCLUDE NULLS " + + "(val FOR metric IN (s1 AS first, s2 AS second))", + TEST_MATADATA, + QUERY_CONTEXT); + UnpivotRelation unpivot = + (UnpivotRelation) + ((org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.QuerySpecification) + ((Query) analysis.getStatement()).getQueryBody()) + .getFrom() + .orElseThrow(); + assertEquals(INT64, analysis.getUnpivotBinding(unpivot).getValueTypes().get(0)); + assertTrue(unpivot.isIncludeNulls()); + SymbolAllocator allocator = new SymbolAllocator(); + LogicalQueryPlan plan = + new TableLogicalPlanner( + QUERY_CONTEXT, TEST_MATADATA, SESSION_INFO, allocator, DEFAULT_WARNING) + .plan(analysis); + assertFalse( + new TableDistributedPlanner(analysis, allocator, plan, TEST_MATADATA, null) + .plan() + .getFragments() + .isEmpty()); + } + + @Test + public void unpivotColumnsAndInvalidSourcesTest() { + Analysis analysis = + analyzeSQL( + "UNPIVOT (SELECT s1,s2 FROM table1) ON COLUMNS(*) INTO NAME metric VALUE val", + TEST_MATADATA, + QUERY_CONTEXT); + UnpivotRelation unpivot = (UnpivotRelation) ((Query) analysis.getStatement()).getQueryBody(); + assertEquals(2, analysis.getUnpivotBinding(unpivot).getSources().size()); + assertThrows( + SemanticException.class, + () -> + analyzeSQL( + "UNPIVOT table1 ON s1 INTO NAME tag1 VALUE val", TEST_MATADATA, QUERY_CONTEXT)); + assertThrows( + SemanticException.class, + () -> + analyzeSQL( + "UNPIVOT table1 ON s1,tag1 INTO NAME metric VALUE val", + TEST_MATADATA, + QUERY_CONTEXT)); + } + + @Test + public void unpivotMultiValueQualifiedSourceColumnsTest() { + Analysis analysis = + analyzeSQL( + "UNPIVOT table1 ON (table1.s1, table1.s2) AS g INTO NAME metric VALUES v1, v2", + TEST_MATADATA, + QUERY_CONTEXT); + UnpivotRelation unpivot = (UnpivotRelation) ((Query) analysis.getStatement()).getQueryBody(); + assertEquals(2, analysis.getUnpivotBinding(unpivot).getValueTypes().size()); + assertEquals(1, analysis.getUnpivotBinding(unpivot).getSources().size()); + } + + @Test + public void unpivotExcludeSourceColumnErrorsTest() { + SemanticException ambiguous = + assertThrows( + SemanticException.class, + () -> + analyzeSQL( + "UNPIVOT (SELECT * FROM table1 x JOIN table1 y ON x.tag1 = y.tag1) " + + "ON COLUMNS(* EXCLUDE (s1)) INTO NAME metric VALUE val", + TEST_MATADATA, + QUERY_CONTEXT)); + assertEquals("UNPIVOT source column is ambiguous: s1", ambiguous.getMessage()); + + SemanticException missing = + assertThrows( + SemanticException.class, + () -> + analyzeSQL( + "UNPIVOT table1 ON COLUMNS(* EXCLUDE (missing)) " + + "INTO NAME metric VALUE val", + TEST_MATADATA, + QUERY_CONTEXT)); + assertEquals("UNPIVOT source column does not exist: missing", missing.getMessage()); + } + + @Test + public void unpivotAmbiguousSourceExpressionTest() { + Analysis columnsStar = + analyzeSQL( + "UNPIVOT (SELECT * FROM (SELECT s1 FROM table1) x " + + "JOIN (SELECT s1 FROM table1) y ON x.s1 = y.s1) " + + "ON COLUMNS(*) INTO NAME metric VALUE val", + TEST_MATADATA, + QUERY_CONTEXT); + UnpivotRelation columnsStarUnpivot = + (UnpivotRelation) ((Query) columnsStar.getStatement()).getQueryBody(); + UnpivotBinding columnsStarBinding = columnsStar.getUnpivotBinding(columnsStarUnpivot); + assertEquals(2, columnsStarBinding.getSources().size()); + assertEquals(List.of(0), columnsStarBinding.getSourceFieldIndexes().get(0)); + assertEquals(List.of(1), columnsStarBinding.getSourceFieldIndexes().get(1)); + + SemanticException explicit = + assertThrows( + SemanticException.class, + () -> + analyzeSQL( + "UNPIVOT (SELECT * FROM table1 x JOIN table1 y ON x.tag1 = y.tag1) " + + "ON s1 INTO NAME metric VALUE val", + TEST_MATADATA, + QUERY_CONTEXT)); + assertEquals("UNPIVOT source column is ambiguous: s1", explicit.getMessage()); + } + public static Analysis analyzeSQL(String sql, Metadata metadata, final MPPQueryContext context) { SqlParser sqlParser = new SqlParser(); Statement statement = diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/planner/CoordinatorPivotInputPreparerTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/planner/CoordinatorPivotInputPreparerTest.java new file mode 100644 index 0000000000000..3d1da5b64eecb --- /dev/null +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/planner/CoordinatorPivotInputPreparerTest.java @@ -0,0 +1,157 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.db.queryengine.plan.relational.planner; + +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.GenericLiteral; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.PivotRelation; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Query; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.With; +import org.apache.iotdb.db.protocol.session.InternalClientSession; +import org.apache.iotdb.db.queryengine.plan.relational.sql.parser.SqlParser; + +import org.apache.tsfile.common.conf.TSFileConfig; +import org.apache.tsfile.enums.TSDataType; +import org.apache.tsfile.read.common.block.TsBlock; +import org.apache.tsfile.read.common.block.TsBlockBuilder; +import org.apache.tsfile.utils.Binary; +import org.junit.Test; + +import java.time.ZoneId; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +public class CoordinatorPivotInputPreparerTest { + @Test + public void testOrdinaryStatementDoesNotRequireAstChildren() { + new CoordinatorPivotInputPreparer() + .prepare( + new SqlParser() + .createStatement( + "CREATE DATABASE pivot_test", + ZoneId.systemDefault(), + new InternalClientSession("pivot-preparer-test")), + null, + null, + null, + List.of(), + Map.of(), + null); + } + + @Test + public void testExplicitGroupByDiscoveryProjectsReferencedColumns() { + PivotRelation pivot = parsePivot("PIVOT table1 ON tag1 USING COUNT(s1) GROUP BY tag2"); + List items = new CoordinatorPivotInputPreparer().buildDiscoverySelectItems(pivot); + assertEquals(4, items.size()); + assertTrue( + items.get(0) + instanceof org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.SingleColumn); + assertTrue( + items.get(3) + instanceof org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.SingleColumn); + } + + @Test + public void testNestedWithKeepsOuterDefinitions() { + With outer = parseWith("WITH outer_cte AS (SELECT s1 FROM table1) SELECT s1 FROM outer_cte"); + With inner = parseWith("WITH inner_cte AS (SELECT s1 FROM table1) SELECT s1 FROM inner_cte"); + With merged = CoordinatorPivotInputPreparer.mergeVisibleWith(outer, inner.getQueries(), false); + assertEquals( + List.of("outer_cte", "inner_cte"), + merged.getQueries().stream().map(query -> query.getName().getValue()).toList()); + } + + @Test + public void testNestedWithShadowingKeepsInnerDefinition() { + With outer = parseWith("WITH cte AS (SELECT s1 FROM table1) SELECT s1 FROM cte"); + With inner = parseWith("WITH cte AS (SELECT s2 FROM table1) SELECT s2 FROM cte"); + With merged = CoordinatorPivotInputPreparer.mergeVisibleWith(outer, inner.getQueries(), false); + assertEquals(1, merged.getQueries().size()); + assertSame(inner.getQueries().get(0), merged.getQueries().get(0)); + } + + @Test + public void testInheritedRecursiveWithIsNotDowngraded() { + With outer = + parseWith("WITH RECURSIVE outer_cte AS (SELECT s1 FROM table1) SELECT s1 FROM outer_cte"); + With local = parseWith("WITH local_cte AS (SELECT s2 FROM table1) SELECT s2 FROM local_cte"); + With merged = CoordinatorPivotInputPreparer.mergeVisibleWith(outer, local.getQueries(), false); + assertTrue(merged.isRecursive()); + assertEquals(2, merged.getQueries().size()); + } + + private With parseWith(String sql) { + return ((Query) + new SqlParser() + .createStatement( + sql, ZoneId.systemDefault(), new InternalClientSession("pivot-with-test"))) + .getWith() + .orElseThrow(); + } + + private PivotRelation parsePivot(String sql) { + return (PivotRelation) + ((org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Query) + new SqlParser() + .createStatement( + sql, + ZoneId.systemDefault(), + new InternalClientSession("pivot-projection-test"))) + .getQueryBody(); + } + + @Test + public void testDiscoveredValuesPreserveTypedLiteralsAndNames() { + TsBlockBuilder builder = new TsBlockBuilder(List.of(TSDataType.STRING, TSDataType.INT32)); + builder.getTimeColumnBuilder().writeLong(0); + builder.getColumnBuilder(0).writeBinary(new Binary("north", TSFileConfig.STRING_CHARSET)); + builder.getColumnBuilder(1).writeInt(20261028); + builder.declarePosition(); + TsBlock block = builder.build(); + PivotRelation.Value text = + CoordinatorPivotInputPreparer.valueOf(block.getColumn(0), 0, TSDataType.STRING); + assertEquals("north", text.alias().orElseThrow().getValue()); + assertTrue( + text.expression() + instanceof org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.StringLiteral); + TsBlockBuilder emptyBuilder = new TsBlockBuilder(List.of(TSDataType.STRING)); + emptyBuilder.getTimeColumnBuilder().writeLong(0); + emptyBuilder.getColumnBuilder(0).writeBinary(new Binary("", TSFileConfig.STRING_CHARSET)); + emptyBuilder.declarePosition(); + PivotRelation.Value empty = + CoordinatorPivotInputPreparer.valueOf( + emptyBuilder.build().getColumn(0), 0, TSDataType.STRING); + assertFalse(empty.alias().isPresent()); + assertEquals( + "", + ((org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.StringLiteral) + empty.expression()) + .getValue()); + PivotRelation.Value date = + CoordinatorPivotInputPreparer.valueOf(block.getColumn(1), 0, TSDataType.DATE); + assertTrue(date.expression() instanceof GenericLiteral); + assertEquals("2026-10-28", date.alias().orElseThrow().getValue()); + } +} diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/sql/parser/PivotUnpivotParserTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/sql/parser/PivotUnpivotParserTest.java new file mode 100644 index 0000000000000..4fced9d62e8b4 --- /dev/null +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/sql/parser/PivotUnpivotParserTest.java @@ -0,0 +1,111 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.db.queryengine.plan.relational.sql.parser; + +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.PivotRelation; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Query; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.QuerySpecification; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.UnpivotRelation; +import org.apache.iotdb.db.protocol.session.InternalClientSession; + +import org.junit.Test; + +import java.time.ZoneId; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class PivotUnpivotParserTest { + private final SqlParser parser = new SqlParser(); + private final InternalClientSession session = new InternalClientSession("parser-test"); + + private Query parse(String sql) { + return (Query) parser.createStatement(sql, ZoneId.systemDefault(), session); + } + + @Test + public void testSimplifiedPivotInCteAndLimit() { + Query query = + parse( + "WITH p AS (PIVOT metrics ON region IN ('north' AS n, NULL), status " + + "USING AVG(temperature) AS avg_temp GROUP BY device_id) " + + "SELECT * FROM p ORDER BY device_id LIMIT 1"); + PivotRelation pivot = + (PivotRelation) query.getWith().get().getQueries().get(0).getQuery().getQueryBody(); + assertTrue(pivot.isDynamic()); + assertEquals(2, pivot.getOnItems().size()); + assertEquals(2, pivot.getOnItems().get(0).values().get().size()); + assertEquals(1, pivot.getGroupBy().get().size()); + assertTrue(((QuerySpecification) query.getQueryBody()).getLimit().isPresent()); + } + + @Test + public void testSqlStylePivotAndUnpivot() { + Query pivotQuery = + parse( + "SELECT * FROM metrics PIVOT (AVG(temperature), MAX(temperature) FOR " + + "region IN ('north', 'south') status IN ('on', 'off') GROUP BY device_id)"); + PivotRelation pivot = + (PivotRelation) ((QuerySpecification) pivotQuery.getQueryBody()).getFrom().get(); + assertFalse(pivot.isDynamic()); + assertEquals(2, pivot.getUsingItems().size()); + assertEquals(2, pivot.getOnItems().size()); + + Query unpivotQuery = + parse( + "SELECT * FROM snapshots UNPIVOT INCLUDE NULLS " + + "((temperature, humidity) FOR sample IN " + + "((temperature_current, humidity_current) AS current, " + + "(temperature_previous, humidity_previous) AS previous))"); + UnpivotRelation unpivot = + (UnpivotRelation) ((QuerySpecification) unpivotQuery.getQueryBody()).getFrom().get(); + assertTrue(unpivot.isIncludeNulls()); + assertEquals(2, unpivot.getValueColumns().size()); + assertEquals(2, unpivot.getItems().size()); + } + + @Test + public void testSimplifiedUnpivotAndColumns() { + Query query = + parse( + "UNPIVOT (SELECT time, device_id, temperature FROM metrics) " + + "ON COLUMNS(* EXCLUDE (time, device_id)) " + + "INTO NAME measurement VALUE value ORDER BY measurement LIMIT 2"); + UnpivotRelation unpivot = (UnpivotRelation) query.getQueryBody(); + assertEquals(2, unpivot.getItems().get(0).excluded().get().size()); + assertEquals("measurement", unpivot.getNameColumn().getValue()); + assertTrue(query.getOrderBy().isPresent()); + assertTrue(query.getLimit().isPresent()); + } + + @Test + public void testNonReservedIdentifiers() { + parse("SELECT pivot, unpivot, include, exclude, name FROM pivot"); + parse("SELECT PiVoT, UnPiVoT, InClUdE, ExClUdE, NaMe FROM PiVoT"); + parse("SELECT * FROM metrics pivot"); + parse("SELECT * FROM metrics unpivot"); + parse("SELECT * FROM metrics AS UnPiVoT"); + parse("SELECT PiVoT AS InClUdE FROM metrics AS NaMe"); + parse("SELECT * FROM exclude(1)"); + parse("SELECT * FROM metrics AS PIVOT"); + parse("PIVOT(SELECT region,temp FROM metrics) ON region IN ('n') USING SUM(temp)"); + } +} diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/type/PivotUnpivotTypeAndLimitTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/type/PivotUnpivotTypeAndLimitTest.java new file mode 100644 index 0000000000000..ebb65535f4d03 --- /dev/null +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/type/PivotUnpivotTypeAndLimitTest.java @@ -0,0 +1,72 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.db.queryengine.plan.relational.type; + +import org.apache.iotdb.commons.exception.SemanticException; +import org.apache.iotdb.db.queryengine.plan.relational.analyzer.PivotLimitValidator; + +import org.apache.tsfile.read.common.type.Type; +import org.junit.Test; + +import java.math.BigInteger; +import java.util.List; + +import static org.apache.tsfile.read.common.type.BinaryType.TEXT; +import static org.apache.tsfile.read.common.type.DoubleType.DOUBLE; +import static org.apache.tsfile.read.common.type.FloatType.FLOAT; +import static org.apache.tsfile.read.common.type.IntType.INT32; +import static org.apache.tsfile.read.common.type.LongType.INT64; +import static org.apache.tsfile.read.common.type.StringType.STRING; +import static org.apache.tsfile.read.common.type.TimestampType.TIMESTAMP; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThrows; + +public class PivotUnpivotTypeAndLimitTest { + @Test + public void testOutputWidthAndEmptyDynamicValues() { + assertEquals(BigInteger.valueOf(13), PivotLimitValidator.validate(1, 3, List.of(2, 2), 13)); + assertThrows( + SemanticException.class, () -> PivotLimitValidator.validate(1, 3, List.of(2, 2), 12)); + assertEquals(BigInteger.ONE, PivotLimitValidator.validate(1, 3, List.of(1000, 0), 1)); + List huge = List.of(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); + assertThrows( + SemanticException.class, () -> PivotLimitValidator.validate(1, 2, huge, Integer.MAX_VALUE)); + } + + @Test + public void testOnlyWhitelistedTypeCombinations() { + assertEquals(INT64, common(INT32, INT64)); + assertEquals(FLOAT, common(INT32, FLOAT)); + assertEquals(DOUBLE, common(INT64, DOUBLE)); + assertEquals(DOUBLE, common(FLOAT, DOUBLE)); + assertEquals(STRING, common(TEXT, STRING)); + assertEquals(TIMESTAMP, common(TIMESTAMP, TIMESTAMP)); + assertFalse(UnpivotTypeUnifier.getCommonType(INT64, TIMESTAMP).isPresent()); + assertFalse(UnpivotTypeUnifier.getCommonType(INT32, STRING).isPresent()); + } + + private Type common(Type left, Type right) { + assertEquals( + UnpivotTypeUnifier.getCommonType(left, right), + UnpivotTypeUnifier.getCommonType(right, left)); + return UnpivotTypeUnifier.getCommonType(left, right).orElseThrow(); + } +} diff --git a/iotdb-core/node-commons/src/assembly/resources/conf/iotdb-system.properties.template b/iotdb-core/node-commons/src/assembly/resources/conf/iotdb-system.properties.template index 4db46c0cdbf34..a670c4f949850 100644 --- a/iotdb-core/node-commons/src/assembly/resources/conf/iotdb-system.properties.template +++ b/iotdb-core/node-commons/src/assembly/resources/conf/iotdb-system.properties.template @@ -1354,6 +1354,25 @@ cte_buffer_size_in_bytes=131072 # Privilege: SYSTEM max_rows_in_cte_buffer=1000 +# Maximum total output columns per PIVOT (including grouping columns). Non-positive values keep the effective default/current value. +# effectiveMode: hot_reload +# Datatype: int +# Privilege: SYSTEM +pivot_limit=100000 + +# Maximum bytes buffered for each dynamic PIVOT input. +# effectiveMode: hot_reload +# Datatype: long +# Privilege: SYSTEM +# Unit: bytes +pivot_input_buffer_size_in_bytes=67108864 + +# Maximum rows buffered for each dynamic PIVOT input. +# effectiveMode: hot_reload +# Datatype: int +# Privilege: SYSTEM +pivot_input_max_rows=1000000 + # The maximum mod entries size that each FragmentInstance can cache. # if mods_cache_size_limit_per_fi_in_bytes <= 0, default value will be used, default value = min(32MB, memory for query operators / query_thread_count / 2) # if mods_cache_size_limit_per_fi_in_bytes > 0, the specified value will be used. diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/conf/CommonConfig.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/conf/CommonConfig.java index d307e8bfa365f..a49e21dc424f5 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/conf/CommonConfig.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/conf/CommonConfig.java @@ -565,6 +565,10 @@ public class CommonConfig { /** Max number of rows for cte materialization */ private int maxRowsInCteBuffer = 1000; + private int pivotLimit = 100000; + private long pivotInputBufferSizeInBytes = 64L * 1024 * 1024; + private int pivotInputMaxRows = 1000000; + CommonConfig() { // Empty constructor } @@ -3314,4 +3318,28 @@ public void setMaxRowsInCteBuffer(int maxRowsInCteBuffer) { public int getMaxRowsInCteBuffer() { return maxRowsInCteBuffer; } + + public int getPivotLimit() { + return pivotLimit; + } + + public void setPivotLimit(int pivotLimit) { + this.pivotLimit = pivotLimit; + } + + public long getPivotInputBufferSizeInBytes() { + return pivotInputBufferSizeInBytes; + } + + public void setPivotInputBufferSizeInBytes(long pivotInputBufferSizeInBytes) { + this.pivotInputBufferSizeInBytes = pivotInputBufferSizeInBytes; + } + + public int getPivotInputMaxRows() { + return pivotInputMaxRows; + } + + public void setPivotInputMaxRows(int pivotInputMaxRows) { + this.pivotInputMaxRows = pivotInputMaxRows; + } } diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/planner/plan/node/CommonPlanNodeDeserializer.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/planner/plan/node/CommonPlanNodeDeserializer.java index 6219a053417e7..e0b182fb2cd7b 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/planner/plan/node/CommonPlanNodeDeserializer.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/planner/plan/node/CommonPlanNodeDeserializer.java @@ -143,6 +143,9 @@ public PlanNode deserialize(ByteBuffer buffer, short nodeType) { return ValuesNode.deserialize(buffer); case 1043: return NextFillNode.deserialize(buffer); + case 1046: + return org.apache.iotdb.commons.queryengine.plan.relational.planner.node.UnpivotNode + .deserialize(buffer); default: throw new IllegalArgumentException(QueryMessages.INVALID_NODE_TYPE + nodeType); } diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/planner/plan/node/ICoreQueryPlanVisitor.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/planner/plan/node/ICoreQueryPlanVisitor.java index ed429b227a9dd..2d8406d097052 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/planner/plan/node/ICoreQueryPlanVisitor.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/planner/plan/node/ICoreQueryPlanVisitor.java @@ -56,6 +56,7 @@ import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.TopKNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.TopKRankingNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.UnionNode; +import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.UnpivotNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.ValueFillNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.ValuesNode; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.WindowNode; @@ -123,6 +124,10 @@ default R visitLimit(LimitNode node, C context) { return visitSingleChildProcess(node, context); } + default R visitUnpivot(UnpivotNode node, C context) { + return visitSingleChildProcess(node, context); + } + default R visitOffset(OffsetNode node, C context) { return visitSingleChildProcess(node, context); } diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/planner/plan/node/PlanNodeType.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/planner/plan/node/PlanNodeType.java index 2cb87b94e39ec..1dfb8f3c26fd4 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/planner/plan/node/PlanNodeType.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/planner/plan/node/PlanNodeType.java @@ -204,6 +204,7 @@ public enum PlanNodeType { TABLE_NEXT_FILL_NODE((short) 1043), SESSION_SCAN_NODE((short) 1044), EVENT_SCAN_NODE((short) 1045), + TABLE_UNPIVOT_NODE((short) 1046), RELATIONAL_INSERT_TABLET((short) 2000), RELATIONAL_INSERT_ROW((short) 2001), diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/planner/node/UnpivotNode.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/planner/node/UnpivotNode.java new file mode 100644 index 0000000000000..1ef053aa2f2c2 --- /dev/null +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/planner/node/UnpivotNode.java @@ -0,0 +1,212 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.commons.queryengine.plan.relational.planner.node; + +import org.apache.iotdb.commons.queryengine.plan.planner.plan.node.ICoreQueryPlanVisitor; +import org.apache.iotdb.commons.queryengine.plan.planner.plan.node.IPlanVisitor; +import org.apache.iotdb.commons.queryengine.plan.planner.plan.node.PlanNode; +import org.apache.iotdb.commons.queryengine.plan.planner.plan.node.PlanNodeId; +import org.apache.iotdb.commons.queryengine.plan.planner.plan.node.PlanNodeType; +import org.apache.iotdb.commons.queryengine.plan.planner.plan.node.process.SingleChildProcessNode; +import org.apache.iotdb.commons.queryengine.plan.relational.planner.Symbol; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterables; +import org.apache.tsfile.utils.ReadWriteIOUtils; + +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * Expands each input row once for every source group, without consuming the dedicated time slot. + */ +public final class UnpivotNode extends SingleChildProcessNode { + private final List retained; + private final List> sources; + private final List names; + private final List outputs; + private final boolean includeNulls; + + public UnpivotNode( + PlanNodeId id, + PlanNode child, + List retained, + List> sources, + List names, + List outputs, + boolean includeNulls) { + super(id, child); + this.retained = ImmutableList.copyOf(retained); + this.sources = + sources.stream().map(ImmutableList::copyOf).collect(ImmutableList.toImmutableList()); + this.names = ImmutableList.copyOf(names); + this.outputs = ImmutableList.copyOf(outputs); + this.includeNulls = includeNulls; + if (sources.size() != names.size() + || sources.isEmpty() + || sources.stream() + .anyMatch(source -> source.size() != outputs.size() - retained.size() - 1)) { + throw new IllegalArgumentException(); + } + } + + public List getRetained() { + return retained; + } + + public List> getSources() { + return sources; + } + + public List getNames() { + return names; + } + + public boolean isIncludeNulls() { + return includeNulls; + } + + @Override + public PlanNodeType getType() { + return PlanNodeType.TABLE_UNPIVOT_NODE; + } + + @Override + public List getOutputSymbols() { + return outputs; + } + + @Override + public List getOutputColumnNames() { + return outputs.stream().map(Symbol::getName).collect(ImmutableList.toImmutableList()); + } + + @Override + public R accept(IPlanVisitor visitor, C context) { + return ((ICoreQueryPlanVisitor) visitor).visitUnpivot(this, context); + } + + @Override + public PlanNode clone() { + return new UnpivotNode(id, null, retained, sources, names, outputs, includeNulls); + } + + @Override + public PlanNode replaceChildren(List newChildren) { + return new UnpivotNode( + id, Iterables.getOnlyElement(newChildren), retained, sources, names, outputs, includeNulls); + } + + private void writeAttributes(ByteBuffer buffer) { + PlanNodeType.TABLE_UNPIVOT_NODE.serialize(buffer); + ReadWriteIOUtils.write(retained.size(), buffer); + retained.forEach(symbol -> Symbol.serialize(symbol, buffer)); + ReadWriteIOUtils.write(sources.size(), buffer); + for (int i = 0; i < sources.size(); i++) { + ReadWriteIOUtils.write(names.get(i), buffer); + ReadWriteIOUtils.write(sources.get(i).size(), buffer); + sources.get(i).forEach(symbol -> Symbol.serialize(symbol, buffer)); + } + ReadWriteIOUtils.write(outputs.size(), buffer); + outputs.forEach(symbol -> Symbol.serialize(symbol, buffer)); + ReadWriteIOUtils.write(includeNulls, buffer); + } + + @Override + protected void serializeAttributes(ByteBuffer buffer) { + writeAttributes(buffer); + } + + @Override + protected void serializeAttributes(DataOutputStream stream) throws IOException { + PlanNodeType.TABLE_UNPIVOT_NODE.serialize(stream); + ReadWriteIOUtils.write(retained.size(), stream); + for (Symbol symbol : retained) { + Symbol.serialize(symbol, stream); + } + ReadWriteIOUtils.write(sources.size(), stream); + for (int i = 0; i < sources.size(); i++) { + ReadWriteIOUtils.write(names.get(i), stream); + ReadWriteIOUtils.write(sources.get(i).size(), stream); + for (Symbol symbol : sources.get(i)) { + Symbol.serialize(symbol, stream); + } + } + ReadWriteIOUtils.write(outputs.size(), stream); + for (Symbol symbol : outputs) { + Symbol.serialize(symbol, stream); + } + ReadWriteIOUtils.write(includeNulls, stream); + } + + public static UnpivotNode deserialize(ByteBuffer buffer) { + int retainedSize = ReadWriteIOUtils.readInt(buffer); + List retained = new ArrayList<>(retainedSize); + for (int i = 0; i < retainedSize; i++) { + retained.add(Symbol.deserialize(buffer)); + } + int sourceCount = ReadWriteIOUtils.readInt(buffer); + List names = new ArrayList<>(sourceCount); + List> sources = new ArrayList<>(sourceCount); + for (int i = 0; i < sourceCount; i++) { + names.add(ReadWriteIOUtils.readString(buffer)); + int valueCount = ReadWriteIOUtils.readInt(buffer); + List group = new ArrayList<>(valueCount); + for (int j = 0; j < valueCount; j++) { + group.add(Symbol.deserialize(buffer)); + } + sources.add(group); + } + int outputCount = ReadWriteIOUtils.readInt(buffer); + List outputs = new ArrayList<>(outputCount); + for (int i = 0; i < outputCount; i++) { + outputs.add(Symbol.deserialize(buffer)); + } + boolean includeNulls = ReadWriteIOUtils.readBool(buffer); + return new UnpivotNode( + PlanNodeId.deserialize(buffer), null, retained, sources, names, outputs, includeNulls); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!(obj instanceof UnpivotNode)) { + return false; + } + UnpivotNode other = (UnpivotNode) obj; + return super.equals(other) + && retained.equals(other.retained) + && sources.equals(other.sources) + && names.equals(other.names) + && outputs.equals(other.outputs) + && includeNulls == other.includeNulls; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), retained, sources, names, outputs, includeNulls); + } +} diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/sql/ast/CommonQueryAstVisitor.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/sql/ast/CommonQueryAstVisitor.java index c4bf976eb87b4..993fa6747f5d3 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/sql/ast/CommonQueryAstVisitor.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/sql/ast/CommonQueryAstVisitor.java @@ -362,6 +362,14 @@ default R visitTable(Table node, C context) { return visitQueryBody(node, context); } + default R visitPivotRelation(PivotRelation node, C context) { + return visitQueryBody(node, context); + } + + default R visitUnpivotRelation(UnpivotRelation node, C context) { + return visitQueryBody(node, context); + } + default R visitQuerySpecification(QuerySpecification node, C context) { return visitQueryBody(node, context); } diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/sql/ast/PivotRelation.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/sql/ast/PivotRelation.java new file mode 100644 index 0000000000000..5e16df5674f43 --- /dev/null +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/sql/ast/PivotRelation.java @@ -0,0 +1,146 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.commons.queryengine.plan.relational.sql.ast; + +import com.google.common.collect.ImmutableList; +import org.apache.tsfile.utils.RamUsageEstimator; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +public final class PivotRelation extends QueryBody { + private static final long INSTANCE_SIZE = + RamUsageEstimator.shallowSizeOfInstance(PivotRelation.class); + + public record Value(Expression expression, Optional alias) {} + + // An absent list denotes a dynamically discovered ON item; an empty list is never parsed. + public record OnItem(Expression expression, Optional> values) {} + + public record UsingItem(Expression expression, Optional alias) {} + + private final Relation input; + private final List onItems; + private final List usingItems; + private final Optional> groupBy; + private final boolean simplified; + + public PivotRelation( + NodeLocation location, + Relation input, + List onItems, + List usingItems, + Optional> groupBy, + boolean simplified) { + super(location); + this.input = Objects.requireNonNull(input); + this.onItems = ImmutableList.copyOf(onItems); + this.usingItems = ImmutableList.copyOf(usingItems); + this.groupBy = groupBy.map(ImmutableList::copyOf); + this.simplified = simplified; + } + + public Relation getInput() { + return input; + } + + public List getOnItems() { + return onItems; + } + + public List getUsingItems() { + return usingItems; + } + + public Optional> getGroupBy() { + return groupBy; + } + + public boolean isSimplified() { + return simplified; + } + + public boolean isDynamic() { + return onItems.stream().anyMatch(item -> item.values().isEmpty()); + } + + @Override + public R accept(IAstVisitor visitor, C context) { + return ((CommonQueryAstVisitor) visitor).visitPivotRelation(this, context); + } + + @Override + public List getChildren() { + List children = new ArrayList<>(); + children.add(input); + for (OnItem item : onItems) { + children.add(item.expression()); + item.values() + .ifPresent( + values -> + values.forEach( + value -> { + children.add(value.expression()); + value.alias().ifPresent(children::add); + })); + } + for (UsingItem item : usingItems) { + children.add(item.expression()); + item.alias().ifPresent(children::add); + } + groupBy.ifPresent(children::addAll); + return ImmutableList.copyOf(children); + } + + @Override + public boolean shallowEquals(Node other) { + return sameClass(this, other); + } + + @Override + public long ramBytesUsed() { + return INSTANCE_SIZE; + } + + @Override + public String toString() { + return "PivotRelation{" + input + ", " + onItems + ", " + usingItems + "}"; + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof PivotRelation)) { + return false; + } + PivotRelation that = (PivotRelation) other; + return input.equals(that.input) + && onItems.equals(that.onItems) + && usingItems.equals(that.usingItems) + && groupBy.equals(that.groupBy) + && simplified == that.simplified; + } + + @Override + public int hashCode() { + return Objects.hash(input, onItems, usingItems, groupBy, simplified); + } +} diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/sql/ast/UnpivotRelation.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/sql/ast/UnpivotRelation.java new file mode 100644 index 0000000000000..e706522a21bb5 --- /dev/null +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/sql/ast/UnpivotRelation.java @@ -0,0 +1,155 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.commons.queryengine.plan.relational.sql.ast; + +import com.google.common.collect.ImmutableList; +import org.apache.tsfile.utils.RamUsageEstimator; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +public final class UnpivotRelation extends QueryBody { + private static final long INSTANCE_SIZE = + RamUsageEstimator.shallowSizeOfInstance(UnpivotRelation.class); + + // A selector is represented by an empty expressions list and a present excluded list. + // An empty excluded list selects all input columns. + public record Item( + List expressions, + Optional> excluded, + Optional alias) { + public Item { + expressions = ImmutableList.copyOf(expressions); + excluded = excluded.map(ImmutableList::copyOf); + } + } + + private final Relation input; + private final List valueColumns; + private final Identifier nameColumn; + private final List items; + private final boolean includeNulls; + private final boolean simplified; + private final boolean explicitInto; + + public UnpivotRelation( + NodeLocation location, + Relation input, + List valueColumns, + Identifier nameColumn, + List items, + boolean includeNulls, + boolean simplified, + boolean explicitInto) { + super(location); + this.input = Objects.requireNonNull(input); + this.valueColumns = ImmutableList.copyOf(valueColumns); + this.nameColumn = Objects.requireNonNull(nameColumn); + this.items = ImmutableList.copyOf(items); + this.includeNulls = includeNulls; + this.simplified = simplified; + this.explicitInto = explicitInto; + } + + public Relation getInput() { + return input; + } + + public List getValueColumns() { + return valueColumns; + } + + public Identifier getNameColumn() { + return nameColumn; + } + + public List getItems() { + return items; + } + + public boolean isIncludeNulls() { + return includeNulls; + } + + public boolean isSimplified() { + return simplified; + } + + public boolean hasExplicitInto() { + return explicitInto; + } + + @Override + public R accept(IAstVisitor visitor, C context) { + return ((CommonQueryAstVisitor) visitor).visitUnpivotRelation(this, context); + } + + @Override + public List getChildren() { + List children = new ArrayList<>(); + children.add(input); + children.add(nameColumn); + children.addAll(valueColumns); + for (Item item : items) { + children.addAll(item.expressions()); + item.excluded().ifPresent(children::addAll); + item.alias().ifPresent(children::add); + } + return ImmutableList.copyOf(children); + } + + @Override + public boolean shallowEquals(Node other) { + return sameClass(this, other); + } + + @Override + public long ramBytesUsed() { + return INSTANCE_SIZE; + } + + @Override + public String toString() { + return "UnpivotRelation{" + input + ", " + items + "}"; + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof UnpivotRelation)) { + return false; + } + UnpivotRelation that = (UnpivotRelation) other; + return input.equals(that.input) + && valueColumns.equals(that.valueColumns) + && nameColumn.equals(that.nameColumn) + && items.equals(that.items) + && includeNulls == that.includeNulls + && simplified == that.simplified + && explicitInto == that.explicitInto; + } + + @Override + public int hashCode() { + return Objects.hash( + input, valueColumns, nameColumn, items, includeNulls, simplified, explicitInto); + } +} diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/sql/util/CommonQuerySqlFormatter.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/sql/util/CommonQuerySqlFormatter.java index 139d501931b82..4e1648f613379 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/sql/util/CommonQuerySqlFormatter.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/sql/util/CommonQuerySqlFormatter.java @@ -38,6 +38,7 @@ import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Offset; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.OrderBy; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.PatternRecognitionRelation; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.PivotRelation; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.QualifiedName; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Query; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.QuerySpecification; @@ -52,6 +53,7 @@ import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.TableFunctionTableArgument; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.TableSubquery; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Union; +import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.UnpivotRelation; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Values; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.WithQuery; import org.apache.iotdb.commons.queryengine.plan.statement.component.FillPolicy; @@ -388,6 +390,144 @@ public Void visitRowPattern(RowPattern node, Integer indent) { return null; } + @Override + public Void visitPivotRelation(PivotRelation node, Integer indent) { + if (node.isSimplified()) { + builder.append("PIVOT "); + process(node.getInput(), indent); + builder.append(" ON "); + } else { + process(node.getInput(), indent); + builder.append(" PIVOT ("); + appendPivotUsing(node); + builder.append(" FOR "); + } + for (int i = 0; i < node.getOnItems().size(); i++) { + if (i > 0) { + builder.append(node.isSimplified() ? ", " : " "); + } + PivotRelation.OnItem item = node.getOnItems().get(i); + builder.append(formatExpression(item.expression())); + item.values() + .ifPresent( + values -> { + builder.append(" IN ("); + for (int j = 0; j < values.size(); j++) { + if (j > 0) { + builder.append(", "); + } + PivotRelation.Value value = values.get(j); + builder.append(formatExpression(value.expression())); + value + .alias() + .ifPresent(alias -> builder.append(" AS ").append(formatName(alias))); + } + builder.append(')'); + }); + } + if (node.isSimplified()) { + builder.append(" USING "); + appendPivotUsing(node); + } + node.getGroupBy() + .ifPresent( + groups -> { + builder.append(" GROUP BY "); + for (int i = 0; i < groups.size(); i++) { + if (i > 0) { + builder.append(", "); + } + builder.append(formatExpression(groups.get(i))); + } + }); + if (!node.isSimplified()) { + builder.append(')'); + } + return null; + } + + private void appendPivotUsing(PivotRelation node) { + for (int i = 0; i < node.getUsingItems().size(); i++) { + if (i > 0) { + builder.append(", "); + } + PivotRelation.UsingItem item = node.getUsingItems().get(i); + builder.append(formatExpression(item.expression())); + item.alias().ifPresent(alias -> builder.append(" AS ").append(formatName(alias))); + } + } + + @Override + public Void visitUnpivotRelation(UnpivotRelation node, Integer indent) { + if (node.isSimplified()) { + builder.append("UNPIVOT "); + process(node.getInput(), indent); + builder.append(" ON "); + } else { + process(node.getInput(), indent); + builder.append(node.isIncludeNulls() ? " UNPIVOT INCLUDE NULLS (" : " UNPIVOT ("); + if (node.getValueColumns().size() > 1) { + builder.append('('); + } + appendIdentifiers(node.getValueColumns()); + if (node.getValueColumns().size() > 1) { + builder.append(')'); + } + builder.append(" FOR ").append(formatName(node.getNameColumn())).append(" IN ("); + } + for (int i = 0; i < node.getItems().size(); i++) { + if (i > 0) { + builder.append(", "); + } + UnpivotRelation.Item item = node.getItems().get(i); + if (item.excluded().isPresent()) { + builder.append("COLUMNS(*"); + if (!item.excluded().get().isEmpty()) { + builder.append(" EXCLUDE ("); + appendIdentifiers(item.excluded().get()); + builder.append(')'); + } + builder.append(')'); + } else { + if (item.expressions().size() > 1) { + builder.append('('); + } + for (int j = 0; j < item.expressions().size(); j++) { + if (j > 0) { + builder.append(", "); + } + builder.append(formatExpression(item.expressions().get(j))); + } + if (item.expressions().size() > 1) { + builder.append(')'); + } + } + item.alias().ifPresent(alias -> builder.append(" AS ").append(formatName(alias))); + } + if (node.isSimplified()) { + if (node.isIncludeNulls()) { + builder.append(" INCLUDE NULLS"); + } + if (node.hasExplicitInto()) { + builder.append(" INTO NAME ").append(formatName(node.getNameColumn())); + builder.append(node.getValueColumns().size() > 1 ? " VALUES " : " VALUE "); + appendIdentifiers(node.getValueColumns()); + } + } else { + builder.append("))"); + } + return null; + } + + private void appendIdentifiers(List identifiers) { + for (int i = 0; i < identifiers.size(); i++) { + if (i > 0) { + builder.append(", "); + } + builder.append(formatName(identifiers.get(i))); + } + } + @Override public Void visitQuerySpecification(QuerySpecification node, Integer indent) { process(node.getSelect(), indent); diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/utils/cte/CteDataStore.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/utils/cte/CteDataStore.java index 81484abfe0b3f..fea949a60e169 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/utils/cte/CteDataStore.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/utils/cte/CteDataStore.java @@ -21,7 +21,6 @@ package org.apache.iotdb.commons.queryengine.utils.cte; -import org.apache.iotdb.commons.conf.CommonConfig; import org.apache.iotdb.commons.conf.CommonDescriptor; import org.apache.iotdb.commons.queryengine.plan.relational.metadata.TableSchema; import org.apache.iotdb.commons.utils.TestOnly; @@ -44,6 +43,15 @@ public class CteDataStore implements Accountable { private final List cachedData; private long cachedBytes; private int cachedRows; + private final long maxBytes; + private final int maxRows; + private final boolean inclusiveLimit; + + public enum AddResult { + SUCCESS, + BYTES_EXCEEDED, + ROWS_EXCEEDED + } // reference count by CteScanReader private final AtomicInteger count; @@ -55,28 +63,71 @@ public class CteDataStore implements Accountable { private long actualReservedBytes; public CteDataStore(TableSchema tableSchema, List columnIndex2TsBlockColumnIndexList) { + this( + tableSchema, + columnIndex2TsBlockColumnIndexList, + CommonDescriptor.getInstance().getConfig().getCteBufferSize(), + CommonDescriptor.getInstance().getConfig().getMaxRowsInCteBuffer(), + false); + } + + /** A query-level PIVOT input store uses independent, inclusive budgets fixed at creation. */ + public CteDataStore( + TableSchema tableSchema, + List columnIndex2TsBlockColumnIndexList, + long maxBytes, + int maxRows) { + this(tableSchema, columnIndex2TsBlockColumnIndexList, maxBytes, maxRows, true); + } + + private CteDataStore( + TableSchema tableSchema, + List columnIndex2TsBlockColumnIndexList, + long maxBytes, + int maxRows, + boolean inclusiveLimit) { this.tableSchema = tableSchema; this.columnIndex2TsBlockColumnIndexList = columnIndex2TsBlockColumnIndexList; + this.maxBytes = maxBytes; + this.maxRows = maxRows; + this.inclusiveLimit = inclusiveLimit; this.cachedData = new ArrayList<>(); - this.cachedBytes = 0L; - this.cachedRows = 0; this.count = new AtomicInteger(0); } - public boolean addTsBlock(TsBlock tsBlock) { - CommonConfig config = CommonDescriptor.getInstance().getConfig(); - long bytesSize = tsBlock.getRetainedSizeInBytes(); + public AddResult tryAddTsBlock(TsBlock tsBlock) { + long bytes = tsBlock.getRetainedSizeInBytes(); int rows = tsBlock.getPositionCount(); - if (bytesSize + cachedBytes >= config.getCteBufferSize() - || rows + cachedRows >= config.getMaxRowsInCteBuffer()) { - return false; + // Compare against the remaining budget rather than adding counters, to avoid overflow. + if (bytes > maxBytes - cachedBytes || (!inclusiveLimit && bytes == maxBytes - cachedBytes)) { + return AddResult.BYTES_EXCEEDED; + } + if (rows > maxRows - cachedRows || (!inclusiveLimit && rows == maxRows - cachedRows)) { + return AddResult.ROWS_EXCEEDED; } cachedData.add(tsBlock); - cachedBytes += bytesSize; + cachedBytes += bytes; cachedRows += rows; + return AddResult.SUCCESS; + } + + /** + * Charges memory held outside cached TsBlocks, such as discovered dynamic PIVOT values, to the + * same byte budget. Only stores with an inclusive limit use this path. + */ + public boolean tryReserveExtraBytes(long bytes) { + // Compare against the remaining budget rather than adding counters, to avoid overflow. + if (bytes > maxBytes - cachedBytes || (!inclusiveLimit && bytes == maxBytes - cachedBytes)) { + return false; + } + cachedBytes += bytes; return true; } + public boolean addTsBlock(TsBlock tsBlock) { + return tryAddTsBlock(tsBlock) == AddResult.SUCCESS; + } + public void clear() { cachedData.clear(); cachedBytes = 0L; diff --git a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/queryengine/plan/relational/planner/node/UnpivotNodeTest.java b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/queryengine/plan/relational/planner/node/UnpivotNodeTest.java new file mode 100644 index 0000000000000..3491b519132ce --- /dev/null +++ b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/queryengine/plan/relational/planner/node/UnpivotNodeTest.java @@ -0,0 +1,75 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.commons.queryengine.plan.relational.planner.node; + +import org.apache.iotdb.commons.queryengine.plan.planner.plan.node.CommonPlanNodeDeserializer; +import org.apache.iotdb.commons.queryengine.plan.planner.plan.node.PlanNodeId; +import org.apache.iotdb.commons.queryengine.plan.planner.plan.node.PlanNodeType; +import org.apache.iotdb.commons.queryengine.plan.relational.planner.Symbol; + +import org.junit.Test; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.nio.ByteBuffer; +import java.util.Arrays; +import java.util.Collections; + +import static org.junit.Assert.assertEquals; + +public class UnpivotNodeTest { + private UnpivotNode node() { + return new UnpivotNode( + new PlanNodeId("unpivot"), + null, + Collections.singletonList(new Symbol("time")), + Arrays.asList( + Arrays.asList(new Symbol("a"), new Symbol("b")), + Arrays.asList(new Symbol("c"), new Symbol("d"))), + Arrays.asList("first", "second"), + Arrays.asList( + new Symbol("time"), new Symbol("name"), new Symbol("value1"), new Symbol("value2")), + true); + } + + @Test + public void testByteBufferRoundTrip() { + UnpivotNode expected = node(); + assertEquals(PlanNodeType.TABLE_UNPIVOT_NODE, expected.getType()); + ByteBuffer buffer = ByteBuffer.allocate(4096); + expected.serialize(buffer); + buffer.flip(); + UnpivotNode actual = (UnpivotNode) CommonPlanNodeDeserializer.INSTANCE.deserialize(buffer); + assertEquals(expected, actual); + assertEquals(expected.getNames(), actual.getNames()); + assertEquals(expected.isIncludeNulls(), actual.isIncludeNulls()); + } + + @Test + public void testStreamRoundTrip() throws Exception { + UnpivotNode expected = node(); + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + expected.serialize(new DataOutputStream(bytes)); + UnpivotNode actual = + (UnpivotNode) + CommonPlanNodeDeserializer.INSTANCE.deserialize(ByteBuffer.wrap(bytes.toByteArray())); + assertEquals(expected, actual); + } +} diff --git a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/queryengine/utils/cte/CteDataStoreBudgetTest.java b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/queryengine/utils/cte/CteDataStoreBudgetTest.java new file mode 100644 index 0000000000000..d24f0f768fef8 --- /dev/null +++ b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/queryengine/utils/cte/CteDataStoreBudgetTest.java @@ -0,0 +1,72 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.commons.queryengine.utils.cte; + +import org.apache.tsfile.enums.TSDataType; +import org.apache.tsfile.read.common.block.TsBlock; +import org.apache.tsfile.read.common.block.TsBlockBuilder; +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class CteDataStoreBudgetTest { + private TsBlock block(int rows) { + TsBlockBuilder builder = new TsBlockBuilder(List.of(TSDataType.INT32)); + for (int i = 0; i < rows; i++) { + builder.getTimeColumnBuilder().writeLong(i); + builder.getColumnBuilder(0).writeInt(i); + builder.declarePosition(); + } + return builder.build(); + } + + @Test + public void testIndependentBudgetsAndExactBoundaries() { + TsBlock one = block(1); + long bytes = one.getRetainedSizeInBytes(); + CteDataStore first = new CteDataStore(null, List.of(0), bytes * 2, 2); + CteDataStore second = new CteDataStore(null, List.of(0), bytes, 1); + assertEquals(CteDataStore.AddResult.SUCCESS, first.tryAddTsBlock(one)); + assertEquals(CteDataStore.AddResult.SUCCESS, first.tryAddTsBlock(one)); + assertEquals(CteDataStore.AddResult.BYTES_EXCEEDED, first.tryAddTsBlock(one)); + assertEquals(CteDataStore.AddResult.SUCCESS, second.tryAddTsBlock(one)); + CteDataStore rowsLimited = new CteDataStore(null, List.of(0), Long.MAX_VALUE, 1); + assertEquals(CteDataStore.AddResult.ROWS_EXCEEDED, rowsLimited.tryAddTsBlock(block(2))); + first.clear(); + assertEquals(CteDataStore.AddResult.SUCCESS, first.tryAddTsBlock(one)); + } + + @Test + public void testExtraBytesShareTheByteBudget() { + TsBlock one = block(1); + long bytes = one.getRetainedSizeInBytes(); + CteDataStore store = new CteDataStore(null, List.of(0), bytes + 100, 1); + assertEquals(CteDataStore.AddResult.SUCCESS, store.tryAddTsBlock(one)); + assertTrue(store.tryReserveExtraBytes(100)); + assertFalse(store.tryReserveExtraBytes(1)); + store.clear(); + assertTrue(store.tryReserveExtraBytes(bytes + 100)); + assertFalse(store.tryReserveExtraBytes(1)); + } +} diff --git a/iotdb-core/relational-grammar/src/main/antlr4/org/apache/iotdb/db/relational/grammar/sql/RelationalSql.g4 b/iotdb-core/relational-grammar/src/main/antlr4/org/apache/iotdb/db/relational/grammar/sql/RelationalSql.g4 index 706b464f9ffc1..52abc3772e36a 100644 --- a/iotdb-core/relational-grammar/src/main/antlr4/org/apache/iotdb/db/relational/grammar/sql/RelationalSql.g4 +++ b/iotdb-core/relational-grammar/src/main/antlr4/org/apache/iotdb/db/relational/grammar/sql/RelationalSql.g4 @@ -1055,6 +1055,8 @@ queryPrimary | VALUES expression (',' expression)* #inlineTable | '(' queryNoWith ')' #subquery | fromFirstQuerySpecification #fromFirstQueryPrimary + | PIVOT pivotInputRelation ON pivotOnItem (',' pivotOnItem)* USING pivotUsingItem (',' pivotUsingItem)* (GROUP BY pivotGroupItem (',' pivotGroupItem)*)? #pivotQueryBody + | UNPIVOT pivotInputRelation ON unpivotItem (',' unpivotItem)* (INCLUDE NULLS)? (INTO NAME identifier (VALUE | VALUES) identifier (',' identifier)*)? #unpivotQueryBody ; sortItem @@ -1137,6 +1139,8 @@ relation | NATURAL joinType JOIN right=aliasedRelation | ASOF ('(' TOLERANCE timeDuration ')')? joinType JOIN rightRelation=relation joinCriteria ) #joinRelation + | left=relation PIVOT '(' pivotUsingItem (',' pivotUsingItem)* FOR pivotStaticOnItem pivotStaticOnItem* (GROUP BY pivotGroupItem (',' pivotGroupItem)*)? ')' (AS identifier)? #pivotClauseRelation + | left=relation UNPIVOT (INCLUDE NULLS)? '(' unpivotValueSpec FOR identifier IN '(' unpivotItem (',' unpivotItem)* ')' ')' (AS identifier)? #unpivotClauseRelation | aliasedRelation #relationDefault | patternRecognition #patternRecognitionRelation ; @@ -1201,6 +1205,45 @@ variableDefinition : identifier AS expression ; +pivotInputRelation + : relationPrimary (AS identifier)? + ; + +pivotOnItem + : valueExpression (IN '(' pivotValue (',' pivotValue)* ')')? + ; + +pivotStaticOnItem + : valueExpression IN '(' pivotValue (',' pivotValue)* ')' + ; + +pivotValue + : valueExpression (AS identifier)? + ; + +pivotUsingItem + : valueExpression (AS identifier)? + ; + +pivotGroupItem + : expression + ; + +unpivotValueSpec + : identifier + | '(' identifier (',' identifier)+ ')' + ; + +unpivotItem + : unpivotColumnsSelector (AS identifier)? + | '(' expression (',' expression)+ ')' (AS identifier)? + | expression (AS identifier)? + ; + +unpivotColumnsSelector + : COLUMNS '(' ASTERISK (EXCLUDE '(' identifier (',' identifier)* ')')? ')' + ; + aliasedRelation : relationPrimary (AS? identifier columnAliases?)? ; @@ -1523,24 +1566,24 @@ nonReserved | BEGIN | BERNOULLI | BOTH | CACHE | CALL | CALLED | CASCADE | CATALOG | CATALOGS | CHAR | CHARACTER | CHARSET | CLEAR | CLUSTER | CLUSTERID | COLUMN | COLUMNS | COMMENT | COMMIT | COMMITTED | CONDITION | CONDITIONAL | CONFIGNODES | CONFIGNODE | CONFIGURATION | CONNECTOR | CONSTANT | COPARTITION | COPY | COUNT | CURRENT | DATA | DATABASE | DATABASES | DATANODE | DATANODES | DATASET | DATE | DAY | DEBUG | DECLARE | DEFAULT | DEFINE | DEFINER | DENY | DESC | DESCRIPTOR | DETAILS| DETERMINISTIC | DEVICES | DISTRIBUTED | DO | DOUBLE - | ELSEIF | EMPTY | ENCODING | ERROR | EXCLUDING | EXPLAIN | EXTRACTOR + | ELSEIF | EMPTY | ENCODING | ERROR | EXCLUDE | EXCLUDING | EXPLAIN | EXTRACTOR | FETCH | FIELD | FILTER | FINAL | FIRST | FLUSH | FOLLOWING | FORCEDLY | FORMAT | FUNCTION | FUNCTIONS | GRACE | GRANT | GRANTED | GRANTS | GRAPHVIZ | GROUPS | HOUR | HYPERPARAMETERS - | INDEX | INDEXES | IF | IGNORE | IMMEDIATE | INCLUDING | INITIAL | INPUT | INTERVAL | INVOKER | IO | ITERATE | ISOLATION + | INDEX | INDEXES | IF | IGNORE | IMMEDIATE | INCLUDE | INCLUDING | INITIAL | INPUT | INTERVAL | INVOKER | IO | ITERATE | ISOLATION | JSON | KEEP | KEY | KEYS | KILL | LANGUAGE | LAST | LATERAL | LEADING | LEAVE | LEVEL | LIMIT | LINEAR | LOAD | LOCAL | LOGICAL | LOOP | MANAGE_ROLE | MANAGE_USER | MAP | MATCH | MATCHED | MATCHES | MATCH_RECOGNIZE | MATERIALIZED | MEASURES | MEMORY | MEMORY_THRESHOLD | METHOD | MERGE | MICROSECOND | MIGRATE | MILLISECOND | MINUTE | MODEL | MODELS | MODIFY | MONTH - | NANOSECOND | NESTED | NEXT | NFC | NFD | NFKC | NFKD | NO | NODEID | NONE | NULLIF | NULLS + | NAME | NANOSECOND | NESTED | NEXT | NFC | NFD | NFKC | NFKD | NO | NODEID | NONE | NULLIF | NULLS | OBJECT | OF | OFFSET | OMIT | ONE | ONLY | OPTION | ORDINALITY | OUTPUT | OVER | OVERFLOW - | PARTITION | PARTITIONS | PASSING | PAST | PATH | PATTERN | PER | PERIOD | PERMUTE | PIPE | PIPEPLUGIN | PIPEPLUGINS | PIPES | PLAN | POSITION | PRECEDING | PRECISION | PRIVILEGES | PREVIOUS | PROCESSLIST | PROCESSOR | PROPERTIES | PRUNE + | PARTITION | PARTITIONS | PASSING | PAST | PATH | PATTERN | PER | PERIOD | PERMUTE | PIVOT | PIPE | PIPEPLUGIN | PIPEPLUGINS | PIPES | PLAN | POSITION | PRECEDING | PRECISION | PRIVILEGES | PREVIOUS | PROCESSLIST | PROCESSOR | PROPERTIES | PRUNE | QUERIES | QUERY | QUOTES | RANGE | READ | READONLY | RECEIVERS | RECONSTRUCT | REFRESH | REGION | REGIONID | REGIONS | REMOVE | RENAME | REPAIR | REPEAT | REPEATABLE | REPLACE | RESET | RESPECT | RESTRICT | RETURN | RETURNING | RETURNS | REVOKE | ROLE | ROLES | ROLLBACK | ROOT | ROW | ROWS | RPR_FIRST | RPR_LAST | RUNNING | SERIESSLOTID | SERVICE | SERVICES | SCALAR | SCHEMA | SCHEMAS | SECOND | SECURITY | SEEK | SERIALIZABLE | SESSION | SET | SETS | SECURITY | SHOW | SINK | SOME | SOURCE | START | STATS | STOP | STREAMS | SUBSCRIPTION | SUBSCRIPTIONS | SUBSET | SUBSTRING | SYSTEM | TABLES | TABLESAMPLE | TAG | TAGS | TEXT | TEXT_STRING | TIES | TIME | TIMEPARTITION | TIMER | TIMER_XL | TIMESERIES | TIMESLOTID | TIMESTAMP | TO | TOPIC | TOPICS | TRAILING | TRANSACTION | TRUNCATE | TRY_CAST | TYPE - | UNBOUNDED | UNCOMMITTED | UNCONDITIONAL | UNIQUE | UNKNOWN | UNMATCHED | UNTIL | UPDATE | URI | URLS | USE | USED | USER | UTF16 | UTF32 | UTF8 + | UNBOUNDED | UNCOMMITTED | UNCONDITIONAL | UNPIVOT | UNIQUE | UNKNOWN | UNMATCHED | UNTIL | UPDATE | URI | URLS | USE | USED | USER | UTF16 | UTF32 | UTF8 | VALIDATE | VALUE | VARIABLES | VARIATION | VERBOSE | VERSION | VIEW | WEEK | WHILE | WINDOW | WITHIN | WITHOUT | WORK | WRAPPER | WRITE | YEAR @@ -1657,6 +1700,7 @@ END: 'END'; ERROR: 'ERROR'; ESCAPE: 'ESCAPE'; EXCEPT: 'EXCEPT'; +EXCLUDE: 'EXCLUDE'; EXCLUDING: 'EXCLUDING'; EXECUTE: 'EXECUTE'; EXISTS: 'EXISTS'; @@ -1698,6 +1742,7 @@ IF: 'IF'; IGNORE: 'IGNORE'; IMMEDIATE: 'IMMEDIATE'; IN: 'IN'; +INCLUDE: 'INCLUDE'; INCLUDING: 'INCLUDING'; INFERENCE: 'INFERENCE'; INITIAL: 'INITIAL'; @@ -1764,6 +1809,7 @@ MODEL: 'MODEL'; MODELS: 'MODELS'; MODIFY: 'MODIFY'; MONTH: 'MONTH' | 'MO'; +NAME: 'NAME'; NANOSECOND: 'NS'; NATURAL: 'NATURAL'; NESTED: 'NESTED'; @@ -1807,6 +1853,7 @@ PER: 'PER'; PERIOD: 'PERIOD'; PERMUTE: 'PERMUTE'; PIPE: 'PIPE'; +PIVOT: 'PIVOT'; PIPEPLUGIN: 'PIPEPLUGIN'; PIPEPLUGINS: 'PIPEPLUGINS'; PIPES: 'PIPES'; @@ -1929,6 +1976,7 @@ UNLOAD: 'UNLOAD'; UNLOCK: 'UNLOCK'; UNMATCHED: 'UNMATCHED'; UNNEST: 'UNNEST'; +UNPIVOT: 'UNPIVOT'; UNTIL: 'UNTIL'; UPDATE: 'UPDATE'; URI: 'URI'; From 4498aeda1fa08ee51ff1457cd6df9cb8316ba9a1 Mon Sep 17 00:00:00 2001 From: zxq <3322351820@qq.com> Date: Tue, 10 Nov 2026 11:21:17 +0800 Subject: [PATCH 2/2] Fix empty string column names in PIVOT --- .../it/query/recent/IoTDBPivotIT.java | 66 +++++++++++++++++++ .../analyzer/StatementAnalyzer.java | 3 +- 2 files changed, 68 insertions(+), 1 deletion(-) diff --git a/integration-test/src/test/java/org/apache/iotdb/relational/it/query/recent/IoTDBPivotIT.java b/integration-test/src/test/java/org/apache/iotdb/relational/it/query/recent/IoTDBPivotIT.java index a569c03435aaa..1310fb72b2ceb 100644 --- a/integration-test/src/test/java/org/apache/iotdb/relational/it/query/recent/IoTDBPivotIT.java +++ b/integration-test/src/test/java/org/apache/iotdb/relational/it/query/recent/IoTDBPivotIT.java @@ -63,6 +63,18 @@ public static void setUp() throws Exception { + "(1,'d1','north','on',10),(2,'d1','south','off',20)," + "(3,'d1',NULL,'on',30)"); statement.execute("FLUSH"); + statement.execute( + "CREATE TABLE cc (device_id STRING TAG, region STRING FIELD, v INT32 FIELD)"); + statement.execute( + "INSERT INTO cc (time,device_id,region,v) VALUES " + "(1,'d1','',8),(2,'d1','x-y',16)"); + statement.execute("FLUSH"); + statement.execute( + "CREATE TABLE cc_name_collision " + + "(device_id STRING TAG, region STRING FIELD, v INT32 FIELD)"); + statement.execute( + "INSERT INTO cc_name_collision (time,device_id,region,v) VALUES " + + "(1,'d1','',8),(2,'d1','empty_string',16)"); + statement.execute("FLUSH"); statement.execute( "CREATE TABLE ranked (device STRING TAG, region STRING FIELD, temp INT32 FIELD)"); statement.execute( @@ -106,6 +118,20 @@ public void testStaticPivotNullAndPostTransformLimit() { DATABASE); } + @Test + public void testStaticPivotEmptyStringAndNullValues() { + tableResultSetEqualTest( + "PIVOT cc ON region IN ('', NULL) USING SUM(v) GROUP BY device_id", + new String[] {"device_id", "empty_string", "NULL"}, + new String[] {"d1,8.0,null,"}, + DATABASE); + tableResultSetEqualTest( + "PIVOT cc ON region IN ('' AS blank_region) USING SUM(v) GROUP BY device_id", + new String[] {"device_id", "blank_region"}, + new String[] {"d1,8.0,"}, + DATABASE); + } + @Test public void testSqlStyleCartesianProductAndAliases() { tableResultSetEqualTest( @@ -151,6 +177,35 @@ public void testDynamicPivotDiscoversFromMaterializedInput() { DATABASE); } + @Test + public void testDynamicPivotWithEmptyStringValue() { + tableResultSetEqualTest( + "PIVOT cc ON region USING SUM(v) GROUP BY device_id", + new String[] {"device_id", "empty_string", "x-y"}, + new String[] {"d1,8.0,16.0,"}, + DATABASE); + tableResultSetEqualTest( + "SELECT empty_string FROM (PIVOT cc ON region USING SUM(v) GROUP BY device_id)", + new String[] {"empty_string"}, + new String[] {"8.0,"}, + DATABASE); + } + + @Test + public void testPivotGeneratedNameCollisionWithEmptyString() { + tableResultSetEqualTest( + "PIVOT cc_name_collision ON region IN ('','empty_string') " + + "USING SUM(v) GROUP BY device_id", + new String[] {"device_id", "empty_string", "empty_string_1"}, + new String[] {"d1,8.0,16.0,"}, + DATABASE); + tableResultSetEqualTest( + "PIVOT cc_name_collision ON region USING SUM(v) GROUP BY device_id", + new String[] {"device_id", "empty_string", "empty_string_1"}, + new String[] {"d1,8.0,16.0,"}, + DATABASE); + } + @Test public void testDynamicPivotInsideLaterCteCanReadEarlierCte() { tableResultSetEqualTest( @@ -536,6 +591,17 @@ public void testRequirementStaticDynamicAndMixedPivot() { DATABASE); } + @Test + public void testMixedStaticPivotValuesCanBeReferencedInSubquery() { + tableResultSetEqualTest( + "SELECT device_id,north,\"1\",\"NULL\" FROM (" + + "PIVOT device_metrics ON region IN ('north',1,NULL) " + + "USING AVG(temperature) GROUP BY device_id) ORDER BY device_id", + new String[] {"device_id", "north", "1", "NULL"}, + new String[] {"device_1,21.0,null,26.0,", "device_2,17.0,null,24.0,"}, + DATABASE); + } + @Test public void testRequirementOnExpressionNullSemantics() { tableResultSetEqualTest( diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/StatementAnalyzer.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/StatementAnalyzer.java index 370cbe25a5c70..93460042f59d5 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/StatementAnalyzer.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/StatementAnalyzer.java @@ -4845,7 +4845,8 @@ private String pivotValueName(Expression expression) { return "NULL"; } if (expression instanceof StringLiteral) { - return ((StringLiteral) expression).getValue(); + String value = ((StringLiteral) expression).getValue(); + return value.isEmpty() ? "empty_string" : value; } return org.apache.iotdb.commons.queryengine.plan.relational.sql.util.ExpressionFormatter .formatExpression(expression);