Timm0 commented on code in PR #29936:
URL: https://github.com/apache/flink/pull/29936#discussion_r4599173446


##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/internal/materializedtable/DescriptorMaterializedTableMergeContext.java:
##########
@@ -0,0 +1,280 @@
+/*
+ * 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.api.internal.materializedtable;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.table.api.MaterializedTableDescriptor;
+import org.apache.flink.table.api.Schema;
+import org.apache.flink.table.api.Schema.UnresolvedColumn;
+import org.apache.flink.table.api.Schema.UnresolvedMetadataColumn;
+import org.apache.flink.table.api.Schema.UnresolvedPhysicalColumn;
+import org.apache.flink.table.api.Schema.UnresolvedWatermarkSpec;
+import org.apache.flink.table.api.TableException;
+import org.apache.flink.table.api.ValidationException;
+import org.apache.flink.table.catalog.CatalogManager;
+import 
org.apache.flink.table.catalog.CatalogMaterializedTable.LogicalRefreshMode;
+import org.apache.flink.table.catalog.Column;
+import org.apache.flink.table.catalog.DataTypeFactory;
+import org.apache.flink.table.catalog.IntervalFreshness;
+import org.apache.flink.table.catalog.ResolvedCatalogMaterializedTable;
+import org.apache.flink.table.catalog.ResolvedSchema;
+import org.apache.flink.table.catalog.StartMode;
+import org.apache.flink.table.catalog.TableDistribution;
+import org.apache.flink.table.operations.QueryOperation;
+import 
org.apache.flink.table.operations.materializedtable.MaterializedTableMergeContext;
+import org.apache.flink.table.operations.utils.AsQuerySchemaMerger;
+import org.apache.flink.table.types.AbstractDataType;
+import org.apache.flink.table.types.DataType;
+
+import javax.annotation.Nullable;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import static 
org.apache.flink.table.operations.materializedtable.MaterializedTableSchemaUtils.METADATA_PERSISTED_COLUMN_KIND;
+import static 
org.apache.flink.table.operations.materializedtable.MaterializedTableSchemaUtils.PHYSICAL_COLUMN_KIND;
+import static 
org.apache.flink.table.operations.materializedtable.MaterializedTableSchemaUtils.checkPersistedColumnProducedByQuery;
+import static 
org.apache.flink.table.types.utils.TypeConversions.fromLogicalToDataType;
+
+/**
+ * The {@link MaterializedTableMergeContext} of {@code Table#materializeInto}, 
with the semantics of
+ * the equivalent {@code CREATE [OR ALTER] MATERIALIZED TABLE} statement.
+ */
+@Internal
+final class DescriptorMaterializedTableMergeContext implements 
MaterializedTableMergeContext {
+
+    private static final String OPERATION_NAME = "CREATE OR ALTER MATERIALIZED 
TABLE";
+
+    private final MaterializedTableDescriptor descriptor;
+    private final QueryOperation queryOperation;
+    private final String serializedQuery;
+    private final DataTypeFactory dataTypeFactory;
+    private final ResolvedSchema querySchema;
+
+    DescriptorMaterializedTableMergeContext(
+            MaterializedTableDescriptor descriptor,
+            QueryOperation queryOperation,
+            String serializedQuery,
+            CatalogManager catalogManager) {
+        this.descriptor = descriptor;
+        this.queryOperation = queryOperation;
+        this.serializedQuery = serializedQuery;
+        this.dataTypeFactory = catalogManager.getDataTypeFactory();
+        this.querySchema = 
toPhysicalSchema(queryOperation.getResolvedSchema());
+    }
+
+    @Override
+    public boolean hasSchemaDefinition() {
+        // A column list defines the schema only if it starts with a physical 
column.
+        return descriptor
+                .getSchema()
+                .map(
+                        schema ->
+                                !schema.getColumns().isEmpty()
+                                        && schema.getColumns().get(0)
+                                                instanceof 
UnresolvedPhysicalColumn)
+                .orElse(false);
+    }
+
+    @Override
+    public boolean hasConstraintDefinition() {
+        return 
descriptor.getSchema().flatMap(Schema::getPrimaryKey).isPresent()
+                || hasSchemaDefinition();
+    }
+
+    @Override
+    public Schema getMergedSchema() {
+        final Schema querySchemaDeclaration =
+                Schema.newBuilder().fromResolvedSchema(querySchema).build();
+        final Schema declaredSchema = descriptor.getSchema().orElse(null);
+        if (declaredSchema == null) {
+            return querySchemaDeclaration;
+        }
+        rejectUnsupportedSchemaParts(declaredSchema);
+        checkPersistedColumnsProducedByQuery(declaredSchema);
+
+        final AsQuerySchemaMerger merger =
+                new AsQuerySchemaMerger(querySchemaDeclaration.getColumns(), 
dataTypeFactory);
+        final List<UnresolvedColumn> declaredColumns = 
declaredSchema.getColumns();
+        // Schema.Builder accepts repeated names, and the merger only rejects 
a repeat of a column
+        // the query doesn't produce.
+        final Set<String> declaredNames = new HashSet<>();
+        for (int position = 0; position < declaredColumns.size(); position++) {
+            final UnresolvedColumn column = declaredColumns.get(position);
+            if (!declaredNames.add(column.getName())) {
+                throw new ValidationException(
+                        String.format(
+                                "A column named '%s' already exists in the 
schema.",
+                                column.getName()));
+            }
+            merger.addDeclaredColumn(withDefaultConversionClass(column), 
position);
+        }
+
+        final Schema.Builder mergedSchema =
+                Schema.newBuilder().fromColumns(merger.getMergedColumns());
+        for (UnresolvedWatermarkSpec watermark : 
declaredSchema.getWatermarkSpecs()) {
+            mergedSchema.watermark(watermark.getColumnName(), 
watermark.getWatermarkExpression());
+        }
+        declaredSchema
+                .getPrimaryKey()
+                .ifPresent(
+                        primaryKey ->
+                                mergedSchema.primaryKeyNamed(

Review Comment:
   Good question, after having a second thought here I'd like to keep it as is. 
The descriptor takes declared columns as written, like `Schema` does for 
`createTable`/`TableDescriptor`, where a nullable primary key column is 
rejected too. Making declared primary key columns `NOT NULL` is a SQL rule that 
also applies to every `CREATE TABLE`.
   Therefore I would like to keep the current Table API convention to not 
confuse a user why they can create a Materialized Table in a certain way but 
not a Table. Since table conversion also promises that a Materialized Table can 
just be suspended and be used as a regular Table, this makes it even more 
important imo.  I updated the docs to say that a re-declared primary key column 
needs `.notNull()`.



-- 
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]

Reply via email to