hello-stephen commented on code in PR #70370:
URL: https://github.com/apache/doris/pull/70370#discussion_r4703130391


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/BindRelation.java:
##########
@@ -904,12 +905,21 @@ private LogicalPlan getLogicalPlan(TableIf table, 
UnboundRelation unboundRelatio
                                 "view not supported with snapshot time/version 
travel");
                         }
                         isView = true;
-                        String pluginCatalog = 
pluginViewTable.getCatalog().getName();
-                        String pluginDb = 
pluginViewTable.getDatabase().getFullName();
-                        String ddlSql = pluginViewTable.getViewText();
-                        Plan pluginViewPlan = 
parseAndAnalyzeExternalView(pluginViewTable,
-                                pluginCatalog, pluginDb, ddlSql, 
cascadesContext);
-                        return new LogicalSubQueryAlias<>(qualifiedTableName, 
pluginViewPlan);
+                        ConnectorViewDefinition definition = 
pluginViewTable.getViewDefinition();
+                        String pluginCatalog = definition.getDefaultCatalog()
+                                
.orElse(pluginViewTable.getCatalog().getName());
+                        String pluginDb = 
definition.getDefaultNamespace().map(levels -> String.join(".", levels))
+                                
.orElse(pluginViewTable.getDatabase().getFullName());
+                        ExternalView externalView = new 
ExternalView(pluginViewTable, definition.getSql(),
+                                pluginViewTable.getViewSchema(definition));
+                        Plan pluginViewPlan = 
parseAndAnalyzeExternalView(externalView,
+                                pluginCatalog, pluginDb, cascadesContext);
+                        List<NamedExpression> viewOutputs = new ArrayList<>();
+                        for (Slot output : pluginViewPlan.getOutput()) {
+                            viewOutputs.add(new Alias(output, 
output.getName()));
+                        }
+                        return new LogicalSubQueryAlias<>(qualifiedTableName,
+                                new LogicalProject<>(viewOutputs, 
pluginViewPlan));

Review Comment:
   [P1] Preserve the view boundary recognized by policy checking
   
   Binding a plugin view now produces this shape:
   
   ```text
   CheckPolicy
     SubQueryAlias(catalog.db.v)
       Project(fresh aliases)
         View(v)
           body
   ```
   
   `CheckPolicy.isView()` only recognizes `View` or `SubQueryAlias(View)`, so 
its guard now returns the child before calling `findPolicy()`. Consequently, a 
non-system user querying a Hive or Iceberg view with a view-level row filter or 
column mask receives unfiltered or unmasked view output. Policies on the 
underlying tables use different identities and do not replace the policy on 
`v`; the separately analyzed body never checks the view itself. Preserve a 
recognized policy boundary or update policy traversal and slot mapping for this 
projection, and cover both view filters and masks with a non-system-user test.



##########
regression-test/suites/external_table_p0/iceberg/test_iceberg_rest_view_binding.groovy:
##########
@@ -0,0 +1,395 @@
+// 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.
+
+import groovy.json.JsonOutput
+import groovy.json.JsonSlurper
+
+suite("test_iceberg_rest_view_binding", 
"p0,external,iceberg,external_docker,external_docker_iceberg") {
+    if 
(!"true".equalsIgnoreCase(context.config.otherConfigs.get("enableIcebergViewTest")))
 {
+        return
+    }
+    def config = context.config.otherConfigs
+    String host = config.get("externalEnvIp")
+    String rest = "http://${host}:${config.get('iceberg_rest_uri_port')}"
+    String sourceDb = config.get("iceberg_view_source_namespace") ?: 
"iceberg_rest_view_source"
+    String storeDb = config.get("iceberg_view_store_namespace") ?: 
"iceberg_rest_view_store"
+    String catalog = config.get("iceberg_view_catalog") ?: 
"iceberg_rest_view_binding"
+    String accessKey = config.get("iceberg_view_access_key")
+    String secretKey = config.get("iceberg_view_secret_key")
+
+    if (!accessKey || !secretKey) {
+        throw new IllegalArgumentException("Configure iceberg_view_access_key 
and iceberg_view_secret_key")
+    }
+
+    // Create real Iceberg view metadata through the REST API; no mock catalog 
is involved.
+    def request = { String method, String path, Object body, List<Integer> 
expected ->
+        def connection = new URL(rest + path).openConnection(Proxy.NO_PROXY)
+        connection.requestMethod = method
+        connection.connectTimeout = 20000
+        connection.readTimeout = 20000
+        try {
+            if (body != null) {
+                connection.doOutput = true
+                connection.setRequestProperty("Content-Type", 
"application/json")
+                connection.outputStream.withCloseable { 
it.write(JsonOutput.toJson(body).getBytes("UTF-8")) }
+            }
+            int status = connection.responseCode
+            def stream = status < 400 ? connection.inputStream : 
connection.errorStream
+            String response = stream == null ? "" : stream.withCloseable { 
it.getText("UTF-8") }
+            if (!expected.contains(status)) {
+                throw new IllegalStateException("${method} ${path}: ${status} 
${response}")
+            }
+            return response ? new JsonSlurper().parseText(response) : [:]
+        } finally {
+            connection.disconnect()
+        }
+    }
+    for (String namespace : [sourceDb, storeDb]) {
+        request("POST", "/v1/namespaces", [namespace: [namespace], properties: 
[:]], [200, 409])
+    }
+    def version = { String text, Map summary, String defaultCatalog, List 
namespace, List representations ->
+        def result = ["version-id": 1, "timestamp-ms": 
System.currentTimeMillis(), "schema-id": 0,
+                      summary: summary, "default-namespace": namespace,
+                      representations: representations ?: [[type: "sql", 
dialect: "doris", sql: text]]]
+        if (defaultCatalog != null) {
+            result["default-catalog"] = defaultCatalog
+        }
+        return result
+    }
+    def createView = { String name, String text, List<String> names, Map 
summary = [:],
+                       String defaultCatalog = catalog, String namespace = 
sourceDb, List representations = [],
+                       List parent = [] ->
+        String path = "/v1/namespaces/${(parent + 
[storeDb]).join('%1F')}/views"
+        List savedNamespace = namespace == null ? [] : parent + [namespace]
+        request("DELETE", "${path}/${name}", null, [200, 204, 404])
+        def fields = names.withIndex().collect { String column, int index ->
+            [id: index + 1, name: column, required: false, type: "int"]
+        }
+        def created = request("POST", path,
+                [name: name, schema: [type: "struct", "schema-id": 0, fields: 
fields],
+                 "view-version": version(text, summary, defaultCatalog, 
savedNamespace, representations),
+                 properties: [:]], [200]).metadata
+        // CREATE may stamp a server-generated summary. Commit the required 
summary explicitly,
+        // then load it back so engine-name cases exercise the metadata they 
claim to test.
+        def current = created.versions.find { it["version-id"] == 
created["current-version-id"] }
+        def next = new LinkedHashMap(current)
+        next["version-id"] = current["version-id"] + 1
+        next["timestamp-ms"] = System.currentTimeMillis()
+        next.summary = summary
+        request("POST", "${path}/${name}",
+                [requirements: [[type: "assert-view-uuid", uuid: 
created["view-uuid"]]],
+                 updates: [[action: "add-view-version", "view-version": next],
+                           [action: "set-current-view-version", 
"view-version-id": next["version-id"]]]], [200])
+        def loaded = request("GET", "${path}/${name}", null, [200]).metadata
+        def persisted = loaded.versions.find { it["version-id"] == 
loaded["current-version-id"] }
+        assertEquals(summary, persisted.summary)
+        assertEquals(names, loaded.schemas.find { it["schema-id"] == 
persisted["schema-id"] }.fields*.name)
+        assertEquals(defaultCatalog, persisted["default-catalog"])
+        assertEquals(savedNamespace, persisted["default-namespace"])
+        def expectedSql = representations ?: [[type: "sql", dialect: "doris", 
sql: text]]
+        assertEquals(new 
JsonSlurper().parseText(JsonOutput.toJson(expectedSql)), 
persisted.representations)
+    }
+    def representation = { String dialect, int value ->
+        [type: "sql", dialect: dialect, sql: "SELECT CAST(${value} AS INT) AS 
x"]
+    }
+
+    request("POST", "/v1/namespaces", [namespace: [storeDb, storeDb], 
properties: [:]], [200, 409])
+    spark_iceberg_multi """
+        DROP TABLE IF EXISTS demo.${storeDb}.${storeDb}.rooted_base;
+        CREATE TABLE demo.${storeDb}.${storeDb}.rooted_base (x INT) USING 
iceberg;
+        CREATE NAMESPACE IF NOT EXISTS demo.${sourceDb};
+        CREATE NAMESPACE IF NOT EXISTS demo.${storeDb};
+        DROP TABLE IF EXISTS demo.${sourceDb}.t;
+        CREATE TABLE demo.${sourceDb}.t (x INT, y INT) USING iceberg;
+        INSERT INTO demo.${sourceDb}.t VALUES (10, 20), (11, 21);
+        DROP TABLE IF EXISTS demo.${storeDb}.t;
+        CREATE TABLE demo.${storeDb}.t (x INT, y INT) USING iceberg;
+        INSERT INTO demo.${storeDb}.t VALUES (100, 200), (101, 201);
+        DROP TABLE IF EXISTS demo.${sourceDb}.t_filter_unpartitioned;
+        CREATE TABLE demo.${sourceDb}.t_filter_unpartitioned (id INT, p INT, v 
INT, n INT) USING iceberg;
+        INSERT INTO demo.${sourceDb}.t_filter_unpartitioned VALUES
+            (1, 10, 100, 1), (2, 10, 200, NULL), (3, 20, 300, 3),
+            (4, 20, NULL, 4), (5, 30, 500, NULL), (6, NULL, 600, 6), (7, NULL, 
NULL, NULL);
+        DROP TABLE IF EXISTS demo.${sourceDb}.t_filter_partitioned;
+        CREATE TABLE demo.${sourceDb}.t_filter_partitioned (id INT, p INT, v 
INT, n INT)
+            USING iceberg PARTITIONED BY (p);
+        INSERT INTO demo.${sourceDb}.t_filter_partitioned SELECT * FROM 
demo.${sourceDb}.t_filter_unpartitioned;
+        USE demo.${sourceDb};
+        DROP VIEW IF EXISTS demo.${storeDb}.v_spark_created;
+        CREATE VIEW demo.${storeDb}.v_spark_created (declared_name) AS SELECT 
x FROM t;
+    """
+    createView("v_rooted", "SELECT x FROM rooted_base", ["x"], [:], null, 
storeDb, [], [storeDb])
+    createView("v_engine_doris", "SELECT CAST(10 AS INT) AS x", ["x"], 
["engine-name": "doris"])
+    createView("v_engine_missing", "SELECT CAST(10 AS INT) AS x", ["x"])
+    createView("v_engine_empty", "SELECT CAST(10 AS INT) AS x", ["x"], 
["engine-name": ""])
+    createView("v_engine_spark", "", ["x"], ["engine-name": "spark"], catalog, 
sourceDb,
+            [representation("spark", 10), representation("doris", 20)])
+    createView("v_engine_unknown", "", ["x"], ["engine-name": "unknown"], 
catalog, sourceDb,
+            [representation("spark", 30), representation("doris", 40)])
+    createView("v_prefer_doris", "", ["x"], [:], catalog, sourceDb,
+            [representation("spark", 50), representation("doris", 60)])
+    createView("v_fallback", "", ["x"], [:], catalog, sourceDb, 
[representation("spark", 70)])
+    createView("v_rename", "SELECT x FROM t", ["declared_name"])
+    createView("v_swap", "SELECT x, y FROM t", ["y", "x"])
+    createView("v_repeat", "SELECT x, x FROM t", ["a", "b"])
+    createView("v_computed", "SELECT x + 1, y + 2 FROM t", ["declared_a", 
"declared_b"])
+    createView("v_nested", "SELECT a, b FROM v_repeat", ["nested_a", 
"nested_b"], [:], catalog, storeDb)
+    createView("v_no_default_catalog", "SELECT x FROM t", ["x"], [:], null)
+    createView("v_missing_default_constant", "SELECT CAST(10 AS INT) AS x", 
["x"], [:], "missing_view_catalog")
+    createView("v_missing_default_qualified", "SELECT x FROM 
${catalog}.${sourceDb}.t", ["x"],
+            [:], "missing_view_catalog")
+    createView("v_missing_default_cte", "WITH c AS (SELECT CAST(80 AS INT) AS 
x) SELECT x FROM c", ["x"],
+            [:], "missing_view_catalog")
+    createView("v_missing_default_subquery", "SELECT (SELECT MAX(x) FROM 
${catalog}.${sourceDb}.t) AS x", ["x"],
+            [:], "missing_view_catalog")
+    createView("v_missing_default_unqualified", "SELECT x FROM t", ["x"], [:], 
"missing_view_catalog")
+    createView("v_missing_default_db_qualified", "SELECT x FROM 
${sourceDb}.t", ["x"], [:], "missing_view_catalog")
+    createView("v_missing_default_nested", "SELECT a, b FROM 
${catalog}.${storeDb}.v_repeat", ["a", "b"],
+            [:], "missing_view_catalog", null)
+    createView("v_refresh", "SELECT CAST(10 AS INT) AS x", ["a"])
+    for (String layout : ["partitioned", "unpartitioned"]) {
+        def metadata = request("GET", 
"/v1/namespaces/${sourceDb}/tables/t_filter_${layout}", null, [200]).metadata
+        def spec = metadata["partition-specs"].find { it["spec-id"] == 
metadata["default-spec-id"] }
+        assertEquals(layout == "partitioned" ? ["identity"] : [], 
spec.fields*.transform)
+        assertEquals(layout == "partitioned" ? [2] : [], 
spec.fields*.get("source-id"))
+        createView("v_filter_${layout}", "SELECT id, p, v, n FROM 
t_filter_${layout}", ["id", "p", "v", "n"])
+        createView("v_filter_${layout}_inner", """SELECT id, p, v, n FROM 
t_filter_${layout}
+            WHERE (p IN (10, 20) OR p IS NULL) AND id >= 2""", ["id", "p", 
"v", "n"])
+        createView("v_filter_${layout}_renamed", "SELECT id, p, v, n FROM 
t_filter_${layout}",
+                ["row_id", "part_key", "metric", "nullable_metric"])
+        createView("v_filter_${layout}_swapped", "SELECT id, p, v, n FROM 
t_filter_${layout}", ["id", "p", "n", "v"])
+        createView("v_filter_${layout}_computed", "SELECT id, p, v + 1, 
COALESCE(n, -1) FROM t_filter_${layout}",
+                ["id", "p", "v_plus_one", "n_filled"])
+        createView("v_filter_${layout}_repeat", "SELECT id, p, v, v FROM 
t_filter_${layout}", ["id", "p", "a", "b"])
+        createView("v_filter_${layout}_nested", """SELECT row_id, part_key, 
metric, nullable_metric
+            FROM v_filter_${layout}_renamed WHERE metric >= 200 OR metric IS 
NULL""",
+                ["id", "p", "v", "n"], [:], catalog, storeDb)
+    }
+    // An empty namespace is valid Iceberg metadata; omitting the namespace 
field is not.
+    for (String mode : ["empty_namespace", "no_defaults"]) {
+        String defaultCatalog = mode == "empty_namespace" ? catalog : null
+        createView("v_${mode}_constant", "SELECT CAST(10 AS INT) AS x", ["x"], 
[:], defaultCatalog, null)
+        createView("v_${mode}_qualified", "SELECT x FROM 
${catalog}.${sourceDb}.t", ["x"], [:], defaultCatalog, null)
+        createView("v_${mode}_db_qualified", "SELECT x FROM ${sourceDb}.t", 
["x"], [:], defaultCatalog, null)
+        createView("v_${mode}_unqualified", "SELECT x FROM t", ["x"], [:], 
defaultCatalog, null)
+    }
+    createView("v_no_defaults_partitioned", "SELECT id, p, v, n FROM 
${catalog}.${sourceDb}.t_filter_partitioned",
+            ["id", "p", "v", "n"], [:], null, null)
+    createView("v_no_defaults_partitioned_db_qualified", "SELECT id, p, v, n 
FROM ${sourceDb}.t_filter_partitioned",
+            ["id", "p", "v", "n"], [:], null, null)
+    createView("v_no_defaults_nested", "SELECT x FROM 
${catalog}.${storeDb}.v_empty_namespace_qualified",
+            ["x"], [:], null, null)
+
+    def catalogProperties = """
+        'type' = 'iceberg', 'iceberg.catalog.type' = 'rest', 'uri' = '${rest}',
+        's3.access_key' = '${accessKey}', 's3.secret_key' = '${secretKey}',
+        's3.endpoint' = 'http://${host}:${config.get('iceberg_minio_port')}',
+        's3.region' = 'us-east-1', 'use_path_style' = 'true'"""
+    String rootedCatalog = "${catalog}_rooted"
+    sql """DROP CATALOG IF EXISTS ${rootedCatalog}"""
+    sql """CREATE CATALOG ${rootedCatalog} PROPERTIES (${catalogProperties}, 
'external_catalog.name' = '${storeDb}')"""
+    // Binding the view must find its unqualified table in the one-level 
database exposed by this catalog.
+    sql """SELECT x FROM ${rootedCatalog}.${storeDb}.v_rooted LIMIT 0"""
+    sql """DROP CATALOG IF EXISTS ${catalog}"""
+    sql """CREATE CATALOG ${catalog} PROPERTIES (${catalogProperties})"""
+    sql """USE ${catalog}.${storeDb}"""
+
+    order_qt_table_control "SELECT x, y FROM ${catalog}.${sourceDb}.t"
+    order_qt_spark_created "SELECT declared_name FROM v_spark_created"

Review Comment:
   [P2] Set up the catalog saved by the Spark fixture
   
   `v_spark_created` is created after `USE demo.${sourceDb}`, so its saved 
default catalog is `demo` and its body is the unqualified `SELECT x FROM t`. 
This suite creates only `${catalog}` (default `iceberg_rest_view_binding`) in 
Doris. Since the new binder honors the saved catalog, this query fails with 
`Unknown catalog 'demo'` on a clean FE and prevents the remaining cases from 
running. The rewritten `test_iceberg_view_query_p0` has the same mismatch: 
`run14.sql` creates views under Spark's `demo`, but the FE catalog is 
`test_iceberg_view_query_p0`. Make the fixture's saved default and FE catalog 
setup agree in both suites, without depending on a catalog left by another test.



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


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to