dianfu commented on code in PR #29070: URL: https://github.com/apache/flink/pull/29070#discussion_r3979954548
########## flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/operations/WindowTableFunctionQueryOperation.java: ########## @@ -0,0 +1,230 @@ +/* + * 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.flink.table.operations; + +import org.apache.flink.annotation.Internal; +import org.apache.flink.table.api.DataTypes; +import org.apache.flink.table.api.ValidationException; +import org.apache.flink.table.catalog.Column; +import org.apache.flink.table.catalog.ResolvedSchema; +import org.apache.flink.table.expressions.ApiExpressionUtils; +import org.apache.flink.table.expressions.SqlFactory; +import org.apache.flink.table.types.DataType; +import org.apache.flink.table.utils.EncodingUtils; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.apache.flink.table.types.logical.utils.LogicalTypeChecks.canBeTimeAttributeType; +import static org.apache.flink.table.types.logical.utils.LogicalTypeChecks.isTimeAttribute; + +/** + * Relational operation that assigns rows to windows using a windowing table-valued function + * (TUMBLE/HOP/CUMULATE/SESSION). Appends {@code window_start}, {@code window_end} and {@code + * window_time} to the input and returns the enriched relation. + */ +@Internal +public class WindowTableFunctionQueryOperation implements QueryOperation { + + private static final String INPUT_ALIAS = "$$T_WIN"; + + /** Window kind; the name maps to the SQL window operator. */ + @Internal + public enum WindowKind { + TUMBLE(1), + HOP(2), + CUMULATE(2), + SESSION(1); + + private final int expectedIntervalCount; + + WindowKind(int expectedIntervalCount) { + this.expectedIntervalCount = expectedIntervalCount; + } + + /** Number of interval operands this window kind requires. */ + public int expectedIntervalCount() { + return expectedIntervalCount; + } + } + + private final WindowKind windowKind; + private final String timeColumn; + private final List<Duration> intervals; + private final List<String> partitionKeys; + private final QueryOperation child; + private final ResolvedSchema resolvedSchema; + + public WindowTableFunctionQueryOperation( + WindowKind windowKind, + String timeColumn, + List<Duration> intervals, + QueryOperation child) { + this(windowKind, timeColumn, intervals, List.of(), child); + } + + public WindowTableFunctionQueryOperation( + WindowKind windowKind, + String timeColumn, + List<Duration> intervals, + List<String> partitionKeys, + QueryOperation child) { + if (intervals.size() != windowKind.expectedIntervalCount()) { + throw new ValidationException( + String.format( + "Window kind %s requires %d interval(s), but got %d.", + windowKind, windowKind.expectedIntervalCount(), intervals.size())); + } + final ResolvedSchema inputSchema = child.getResolvedSchema(); + final int timeIndex = inputSchema.getColumnNames().indexOf(timeColumn); + if (timeIndex < 0) { + throw new ValidationException( + String.format( + "Window time column '%s' does not exist. Available columns: %s", + timeColumn, inputSchema.getColumnNames())); + } + for (String partitionKey : partitionKeys) { + if (inputSchema.getColumnNames().indexOf(partitionKey) < 0) { + throw new ValidationException( + String.format( + "Window partition column '%s' does not exist. " + + "Available columns: %s", + partitionKey, inputSchema.getColumnNames())); + } + } + final DataType timeType = inputSchema.getColumnDataTypes().get(timeIndex); + if (!canBeTimeAttributeType(timeType.getLogicalType())) { + throw new ValidationException( + String.format( + "Window time column '%s' must be a TIMESTAMP or TIMESTAMP_LTZ column, " + + "but was %s.", + timeColumn, timeType.getLogicalType())); + } + if (!isTimeAttribute(timeType.getLogicalType())) { Review Comment: This check rejects regular TIMESTAMP/TIMESTAMP_LTZ columns in batch mode which is supported in existing SQL window TVFs. ########## flink-python/pyflink/dataframe/tests/test_dataframe.py: ########## @@ -2176,5 +2330,141 @@ def test_grouped_aggregation_with_batch_table_environment(self): ) +class DataFrameWindowITTests(PyFlinkStreamDataFrameTestCase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.t_env.get_config().set("table.exec.resource.default-parallelism", "1") + + def _rowtime_source(self): + return self._rowtime_source_from_rows( + "events.csv", ["1,10,0", "1,20,60000", "1,40,600000"] + ) + + def _multi_key_rowtime_source(self): + return self._rowtime_source_from_rows( + "multi_key_events.csv", ["1,10,0", "2,20,60000", "1,40,600000"] + ) + + def _rowtime_source_from_rows(self, filename, rows): + input_path = os.path.join(self.tempdir, filename) + with open(input_path, "w", encoding="utf-8") as events: + events.write("\n".join(rows) + "\n") + return pf.read_generic( + "filesystem", + schema={ + "id": DataType.int64(), + "amount": DataType.int64(), + "ts_millis": DataType.int64(), + }, + options={"path": input_path, "format": "csv"}, + computed_columns={"event_time": "TO_TIMESTAMP_LTZ(ts_millis, 3)"}, + watermark=("event_time", "event_time - INTERVAL '1' SECOND"), + ) + + def _proctime_source(self): + input_path = os.path.join(self.tempdir, "proctime_events.csv") + with open(input_path, "w", encoding="utf-8") as events: + events.write("1,10\n") + events.write("1,20\n") + events.write("1,40\n") + return pf.read_generic( + "filesystem", + schema={ + "id": DataType.int64(), + "amount": DataType.int64(), + }, + options={"path": input_path, "format": "csv"}, + computed_columns={"proc_time": "PROCTIME()"}, + ) + + def test_tumble_window_aggregation(self): + windowed = ( + self._rowtime_source() + .tumble(on="event_time", size=timedelta(minutes=10)) + .group_by("window_start", "window_end", "id") + .agg(pf.col("amount").sum.alias("total")) + ) + + self.assertEqual(sorted(row[-1] for row in windowed.collect()), [30, 40]) + + def test_hop_window_aggregation(self): + windowed = ( + self._rowtime_source() + .hop( + on="event_time", + slide=timedelta(minutes=5), + size=timedelta(minutes=10), + ) + .group_by("window_start", "window_end", "id") + .agg(pf.col("amount").sum.alias("total")) + ) + + self.assertEqual(sorted(row[-1] for row in windowed.collect()), [30, 30, 40, 40]) + + def test_cumulate_window_aggregation(self): + windowed = ( + self._rowtime_source() + .cumulate( + on="event_time", + step=timedelta(minutes=5), + size=timedelta(minutes=10), + ) + .group_by("window_start", "window_end", "id") + .agg(pf.col("amount").sum.alias("total")) + ) + + self.assertEqual(sorted(row[-1] for row in windowed.collect()), [30, 30, 40, 40]) + + def test_session_window_aggregation(self): + windowed = ( + self._rowtime_source() + .session(on="event_time", gap=timedelta(minutes=5)) + .group_by("window_start", "window_end", "id") + .agg(pf.col("amount").sum.alias("total")) + ) + rows = self._materialize(windowed, key=["window_start", "window_end", "id"]) + + self.assertEqual(sorted(row[-1] for row in rows), [30, 40]) + + def test_session_partition_by_computes_per_key_sessions(self): + partitioned = ( + self._multi_key_rowtime_source() + .session( + on="event_time", + gap=timedelta(seconds=90), + partition_by="id", + ) + .group_by("window_start", "window_end", "id") + .agg(pf.col("amount").sum.alias("total")) + ) + + partitioned_rows = self._materialize( + partitioned, key=["window_start", "window_end", "id"] + ) + + self.assertEqual(sorted(row[-1] for row in partitioned_rows), [10, 20, 40]) + + def test_tumble_processing_time_assigns_aligned_windows(self): + rows = ( + self._proctime_source() + .tumble(on="proc_time", size=timedelta(minutes=10)) + .select( + "window_start", + "window_end", + proc_time=pf.col("proc_time").cast(TableDataTypes.TIMESTAMP(3)), Review Comment: `proc_time` and the processing time used for window assignment are sampled at different points, so the containment assertion can still fail if a window boundary falls between them. Could we materialize `window_time` instead and assert that it equals `window_end - 1ms`? It is derived from the same assigned window and avoids relying on two wall-clock samples. For example: ``` def test_tumble_processing_time_assigns_aligned_windows(self): rows = ( self._proctime_source() .tumble(on="proc_time", size=timedelta(minutes=10)) .select( "window_start", "window_end", window_time=pf.col("window_time").cast( TableDataTypes.TIMESTAMP(3) ), ) .collect() ) self.assertEqual(len(rows), 3) for start, end, window_time in rows: self.assertEqual(end - start, timedelta(minutes=10)) self.assertEqual( (start.minute % 10, start.second, start.microsecond), (0, 0, 0), ) self.assertEqual( window_time, end - timedelta(milliseconds=1), ) ``` ########## flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/QueryOperationConverter.java: ########## @@ -593,6 +608,65 @@ else if (other instanceof DataStreamQueryOperation) { throw new TableException("Unknown table operation: " + other); } + private RelNode convertWindowTableFunction(WindowTableFunctionQueryOperation windowOp) { + final RexBuilder rexBuilder = relBuilder.getRexBuilder(); + + final RelNode input = relBuilder.build(); + final RelDataType inputRowType = input.getRowType(); + + final String timeColumn = windowOp.getTimeColumn(); + final RelDataType timeAttributeType = + inputRowType.getField(timeColumn, false, false).getType(); Review Comment: I guess we should use `getField(name, true, false)`? -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
