924060929 commented on code in PR #68853:
URL: https://github.com/apache/doris/pull/68853#discussion_r4665274211


##########
regression-test/suites/datatype_p0/complex_types/test_list_files.groovy:
##########
@@ -0,0 +1,159 @@
+// 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 com.amazonaws.auth.AWSStaticCredentialsProvider
+import com.amazonaws.auth.BasicAWSCredentials
+import com.amazonaws.client.builder.AwsClientBuilder
+import com.amazonaws.services.s3.AmazonS3ClientBuilder
+import com.amazonaws.services.s3.model.ObjectMetadata
+
+suite("test_list_files", "p0,external") {
+    boolean usePathStyle = getS3Provider().equalsIgnoreCase("S3")
+    def client = AmazonS3ClientBuilder.standard()
+            .withEndpointConfiguration(new 
AwsClientBuilder.EndpointConfiguration(getS3Endpoint(), getS3Region()))
+            .withCredentials(new AWSStaticCredentialsProvider(new 
BasicAWSCredentials(getS3AK(), getS3SK())))
+            .withPathStyleAccessEnabled(usePathStyle).build()
+    String bucket = getS3BucketName()
+    String prefix = "list-files/${UUID.randomUUID()}/"
+    String root = "s3://${bucket}/${prefix}"
+    def keys = []
+    def put = { String key, String contents ->
+        byte[] data = contents.getBytes("UTF-8")
+        def metadata = new ObjectMetadata()
+        metadata.setContentLength(data.length)
+        client.putObject(bucket, prefix + key, new ByteArrayInputStream(data), 
metadata)
+        keys.add(prefix + key)
+    }
+    try {
+        ["": "", "empty.txt": "", "a.json": "{}", "sub/": "", "sub/c.png": 
"abc",
+         "sub/deep/d.txt": "abcd", "empty/": "", "empty/deep/": "", "marker/": 
"marker"]
+                .each { key, contents -> put(key, contents) }
+        sql "DROP RESOURCE IF EXISTS list_files_s3"
+        sql """CREATE RESOURCE list_files_s3 PROPERTIES(
+            "type"="s3", "s3.endpoint"="${getS3Endpoint()}", 
"s3.region"="${getS3Region()}",
+            "s3.access_key"="${getS3AK()}", "s3.secret_key"="${getS3SK()}",
+            "s3.bucket"="${bucket}", "s3.root.path"="unused", 
"use_path_style"="${usePathStyle}")"""
+        def listing = { String path, String recursive ->
+            """list_files("resource"="list_files_s3", 
"uri"="${path}"${recursive})"""
+        }
+        String direct = listing(root, ', "recursive"="false"')
+        String recursive = listing(root, ', "recursive"="true"')
+        String defaults = listing(root, '')
+        qt_schema "DESC FUNCTION ${direct}"
+        for (def entry : [direct: direct, recursive: recursive, defaults: 
defaults]) {
+            "qt_${entry.key}" """SELECT substring(path, ${root.length() + 1}), 
size,
+                file IS NULL, ELEMENT_AT(file, 'size'), ELEMENT_AT(file, 
'content_type')
+                FROM ${entry.value} ORDER BY path"""
+            "qt_${entry.key}_counts" "SELECT count(*), count(file), sum(size) 
FROM ${entry.value}"
+        }
+        qt_size_only "SELECT size FROM ${direct} ORDER BY path"
+        qt_path_only "SELECT substring(path, ${root.length() + 1}) FROM 
${direct} ORDER BY path"
+        qt_file_only "SELECT file IS NULL FROM ${direct} ORDER BY path"
+        qt_limit "SELECT count(*) FROM (SELECT * FROM ${direct} LIMIT 2) t"
+        qt_roundtrip """SELECT substring(path, ${root.length() + 1}),
+            ELEMENT_AT(TO_FILE('list_files_s3', path), 'size') = size,
+            ELEMENT_AT(file, 'checksum') = ELEMENT_AT(TO_FILE('list_files_s3', 
path), 'checksum')
+            FROM ${recursive} ORDER BY path"""
+        for (def fold in [false, true]) {
+            quickTest("file_json_${fold}", """
+                SELECT /*+ SET_VAR(enable_fold_constant_by_be=${fold}) */
+                    substring(path, ${root.length() + 1}),
+                    JSON_EXTRACT_STRING(TO_JSON(file), '\$.uri') = path,
+                    JSON_EXTRACT_BIGINT(TO_JSON(file), '\$.size') = size,
+                    JSON_EXTRACT_STRING(TO_JSON(ARRAY(file)), '\$[0].uri') = 
path,
+                    JSON_EXTRACT_STRING(TO_JSON(NAMED_STRUCT('f', file)), 
'\$.f.uri') = path,
+                    JSON_EXTRACT_STRING(TO_JSON(MAP('f', file)), '\$.f.uri') = 
path,
+                    FL_GET_BINARY(file) IS NULL
+                FROM ${direct} ORDER BY path
+            """)
+        }
+        def fileRows = """
+            WITH file_scan AS (
+                SELECT number AS id, file AS f
+                FROM NUMBERS('number'='8') CROSS JOIN ${recursive}
+                WHERE path = '${root}a.json'
+            )
+        """
+        for (boolean spill : [false, true]) {
+            String hint = """/*+ SET_VAR(enable_spill=${spill}, 
enable_force_spill=${spill},
+                spill_min_revocable_mem=1, force_sort_algorithm='full',
+                topn_lazy_materialization_threshold=-1) */"""
+            sql """${fileRows}
+                SELECT ${hint} a.id, a.f, ARRAY(b.f, NULL)
+                FROM file_scan a JOIN [shuffle] file_scan b ON a.id = b.id
+                ORDER BY a.id DESC LIMIT 4 OFFSET 2
+            """
+            quickTest("file_aggregate_${spill}", """${fileRows}
+                SELECT ${hint} id % 2 AS category, COUNT(f), 
ARRAY_SIZE(COLLECT_LIST(f)),
+                    SUM(ELEMENT_AT(f, 'size'))
+                FROM file_scan GROUP BY category ORDER BY category
+            """)
+            sql """${fileRows}
+                SELECT ${hint} id, f, FIRST_VALUE(f) OVER (PARTITION BY id % 2 
ORDER BY id)
+                FROM file_scan ORDER BY id
+            """
+        }
+        for (String query : [
+            "SELECT f, COUNT(*) FROM file_scan GROUP BY f",
+            "SELECT DISTINCT f FROM file_scan",
+            "SELECT f FROM file_scan UNION SELECT f FROM file_scan"
+        ]) {
+            test {
+                sql "${fileRows} ${query}"
+                exception "FILE"
+            }
+        }
+        test {
+            sql "${fileRows} SELECT (SELECT i.f FROM file_scan i WHERE 
i.id=o.id) FROM file_scan o"
+            exception "Agg Function any_value(FILE) is not implemented"

Review Comment:
   [P1] Could we make this correlated scalar subquery return the file? 
`SubqueryToApply` introduces `ANY_VALUE(i.f)` to carry the selected value. The 
user only asked to project `i.f`, and the same query already works with 
`ARRAY(i.f)` below. Please add FILE support to the value-carrying `ANY_VALUE` 
path and replace this expected error with result checks for zero and one match. 
Two matches should still raise the scalar-subquery cardinality error.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/CheckAnalysis.java:
##########
@@ -144,6 +148,26 @@ public List<Rule> buildRules() {
         );
     }
 
+    /** Validate operator keys after expression binding. */
+    public static void checkFilePlan(Plan plan) {
+        if (plan instanceof LogicalSort) {
+            ((LogicalSort<?>) plan).getOrderKeys()
+                    .forEach(key -> 
ExpressionUtils.checkFileKey(key.getExpr(), "ORDER BY"));
+        }
+        if (plan instanceof LogicalAggregate) {
+            ((LogicalAggregate<?>) plan).getGroupByExpressions()
+                    .forEach(key -> ExpressionUtils.checkFileKey(key, "GROUP 
BY"));

Review Comment:
   [P2] `GROUP_CONCAT(path ORDER BY file)` from `LIST_FILES` gets past this 
check. Its sort key is an `OrderExpression` inside the aggregate, so it appears 
in neither a `LogicalSort` nor `getGroupByExpressions()`. The BE then tries to 
sort a `ColumnFile` and throws. Could we check the bound aggregate order key 
and add an analysis test with `ORDER BY file` rejected and `ORDER BY size` 
accepted? `MIN(ARRAY(file))` and `COLLECT_SET(file)` also admit FILE operands 
that their BE comparison and deduplication paths cannot handle.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/AccessPathExpressionCollector.java:
##########
@@ -437,6 +437,12 @@ && isUnderIsNull(context.accessPathBuilder.getPathList())) 
{
                 return continueCollectAccessPath(first, context);
             }
             return visit(elementAt, context);
+        } else if (first.getDataType().isFileType()) {
+            // Analysis restricts FILE selectors to constant public field 
names. Physical FILE
+            // children stay in their canonical positions even when only one 
path is requested.
+            context.accessPathBuilder.addPrefix(
+                    ((Literal) 
arguments.get(1)).getStringValue().toLowerCase(Locale.ROOT));
+            return continueCollectAccessPath(first, context);

Review Comment:
   [P2] Could we also collect `f.inline` for `FL_GET_BINARY(f)`? `ELEMENT_AT(f, 
'uri')` records the selected field here, but `FL_GET_BINARY` falls through to 
the default scalar visitor, which records the whole slot `f`. The BE getter 
reads only the inline child. A `visitFlGetBinary` override and two access-path 
tests should cover this: the getter alone requests `f.inline`, and projecting 
`f` alongside it still requests the whole file.



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