lsyldliu commented on code in PR #19520:
URL: https://github.com/apache/flink/pull/19520#discussion_r890798373


##########
flink-connectors/flink-connector-hive/src/test/java/org/apache/flink/connectors/hive/HiveDialectQueryITCase.java:
##########
@@ -330,6 +333,59 @@ public void testJoinInvolvingComplexType() throws 
Exception {
         }
     }
 
+    @Test
+    public void testInsertDirectory() throws Exception {

Review Comment:
   We should also test insert overwrite local directory?



##########
flink-connectors/flink-connector-hive/src/test/java/org/apache/flink/connectors/hive/HiveDialectQueryITCase.java:
##########
@@ -330,6 +333,59 @@ public void testJoinInvolvingComplexType() throws 
Exception {
         }
     }
 
+    @Test
+    public void testInsertDirectory() throws Exception {
+        String warehouse = 
hiveCatalog.getHiveConf().getVar(HiveConf.ConfVars.METASTOREWAREHOUSE);
+
+        // test insert overwrite directory with row format parameters
+        tableEnv.executeSql("create table map_table (foo STRING , bar 
MAP<STRING, INT>)");
+        tableEnv.executeSql(
+                "insert into map_table select 'A', 
map('math',100,'english',90,'history',85)");
+
+        String dataDir = warehouse + "/map_table_dir";
+        tableEnv.executeSql(
+                        String.format(
+                                "INSERT OVERWRITE DIRECTORY '%s'"
+                                        + "ROW FORMAT DELIMITED \n"
+                                        + "FIELDS TERMINATED BY ':'\n"
+                                        + "COLLECTION ITEMS TERMINATED BY '#' 
\n"
+                                        + "MAP KEYS TERMINATED BY '=' select * 
from map_table",
+                                dataDir))
+                .await();
+        java.nio.file.Path[] files =
+                FileUtils.listFilesInDirectory(
+                                Paths.get(dataDir), (path) -> 
!path.toFile().isHidden())
+                        .toArray(new Path[0]);
+        assertEquals(1, files.length);
+        String actualString = FileUtils.readFileUtf8(files[0].toFile());

Review Comment:
   Why here doesn't through a external table and read it?



##########
flink-connectors/flink-connector-hive/src/main/java/org/apache/flink/table/planner/delegation/hive/copy/HiveParserSemanticAnalyzer.java:
##########
@@ -1792,61 +1791,42 @@ private void getMetaData(HiveParserQB qb, ReadEntity 
parentInput) throws HiveExc
                             }
                         }
 
-                        boolean isDfsFile = true;
-                        if (ast.getChildCount() >= 2
-                                && 
ast.getChild(1).getText().toLowerCase().equals("local")) {
-                            isDfsFile = false;
-                        }
+                        boolean isDfsFile =
+                                ast.getChildCount() < 2

Review Comment:
   I can't understand this judge logic, can you help explain it?



##########
flink-connectors/flink-connector-hive/src/main/java/org/apache/flink/table/planner/delegation/hive/copy/HiveParserSemanticAnalyzer.java:
##########
@@ -1792,61 +1791,42 @@ private void getMetaData(HiveParserQB qb, ReadEntity 
parentInput) throws HiveExc
                             }
                         }
 
-                        boolean isDfsFile = true;
-                        if (ast.getChildCount() >= 2
-                                && 
ast.getChild(1).getText().toLowerCase().equals("local")) {
-                            isDfsFile = false;
-                        }
+                        boolean isDfsFile =
+                                ast.getChildCount() < 2
+                                        || 
!ast.getChild(1).getText().equalsIgnoreCase("local");
                         // Set the destination for the SELECT query inside the 
CTAS
                         qb.getMetaData().setDestForAlias(name, fname, 
isDfsFile);
 
-                        CreateTableDesc directoryDesc = new CreateTableDesc();
-                        boolean directoryDescIsSet = false;
+                        HiveParserDirectoryDesc directoryDesc =

Review Comment:
   Add some annotation about why use HiveParserDirectoryDesc instead of 
CreateTableDesc



##########
flink-connectors/flink-connector-hive/src/main/java/org/apache/flink/table/planner/delegation/hive/HiveParserDMLHelper.java:
##########
@@ -285,6 +305,81 @@ public Operation 
createInsertOperation(HiveParserCalcitePlanner analyzer, RelNod
                 Collections.emptyMap());
     }
 
+    private SinkModifyOperation createInsertIntoDirectoryOperation(
+            HiveParserQB topQB, QBMetaData qbMetaData, RelNode queryRelNode, 
HiveConf hiveConf) {
+        String dest = 
topQB.getParseInfo().getClauseNamesForDest().iterator().next();
+        // get the location for insert into directory
+        String location = qbMetaData.getDestFileForAlias(dest);
+        // get whether it's for insert local directory
+        boolean isToLocal = qbMetaData.getDestTypeForAlias(dest) == 
QBMetaData.DEST_LOCAL_FILE;
+        HiveParserDirectoryDesc directoryDesc = topQB.getDirectoryDesc();
+
+        // set row format / stored as / location
+        Map<String, String> props = new HashMap<>();
+        
HiveParserDDLSemanticAnalyzer.encodeRowFormat(directoryDesc.getRowFormatParams(),
 props);
+        
HiveParserDDLSemanticAnalyzer.encodeStorageFormat(directoryDesc.getStorageFormat(),
 props);
+        props.put(TABLE_LOCATION_URI, location);
+
+        props.put(FactoryUtil.CONNECTOR.key(), 
HiveCatalogFactoryOptions.IDENTIFIER);
+        // mark it's for insert into directory
+        props.put(CatalogPropertiesUtil.FLINK_PROPERTY_PREFIX + 
IS_INSERT_DIRECTORY, "true");
+        // mark it's for insert into local directory or not
+        props.put(
+                CatalogPropertiesUtil.FLINK_PROPERTY_PREFIX + 
IS_TO_LOCAL_DIRECTORY,
+                String.valueOf(isToLocal));
+
+        List<RelDataTypeField> fieldList = 
queryRelNode.getRowType().getFieldList();
+        String[] colNameArr = new String[fieldList.size()];
+        String[] colTypeArr = new String[fieldList.size()];
+        for (int i = 0; i < fieldList.size(); i++) {
+            colNameArr[i] = fieldList.get(i).getName();
+            TypeInfo typeInfo = 
HiveParserTypeConverter.convert(fieldList.get(i).getType());
+            if (typeInfo.equals(TypeInfoFactory.voidTypeInfo)) {
+                colTypeArr[i] = TypeInfoFactory.stringTypeInfo.getTypeName();
+            } else {
+                colTypeArr[i] = typeInfo.getTypeName();
+            }
+        }
+
+        String colNames = String.join(",", colNameArr);
+        String colTypes = String.join(":", colTypeArr);
+        props.put("columns", colNames);
+        props.put("columns.types", colTypes);
+
+        PlannerQueryOperation plannerQueryOperation = new 
PlannerQueryOperation(queryRelNode);
+        return new SinkModifyOperation(
+                createDummyTableForInsertDirectory(
+                        plannerQueryOperation.getResolvedSchema(), props),
+                new PlannerQueryOperation(queryRelNode),
+                Collections.emptyMap(),
+                true, // insert into directory is always for overwrite
+                Collections.emptyMap());
+    }
+
+    private ContextResolvedTable createDummyTableForInsertDirectory(
+            ResolvedSchema resolvedSchema, Map<String, String> props) {
+        Schema.Builder schemaBuilder = Schema.newBuilder();
+        for (Column column : resolvedSchema.getColumns()) {
+            schemaBuilder.column(column.getName(), column.getDataType());
+        }
+        CatalogTable catalogTable =
+                CatalogTable.of(
+                        schemaBuilder.build(),
+                        "a dummy table for the case of insert into directory ",
+                        Collections.emptyList(),
+                        props);
+        ResolvedCatalogTable resolvedCatalogTable =
+                new ResolvedCatalogTable(catalogTable, resolvedSchema);
+        String currentCatalog = catalogManager.getCurrentCatalog();
+        // the object name means nothing, it's just for placeholder and won't 
be used actually
+        String objectName = "insert_directory_tbl";

Review Comment:
   Add an UUID suffix to avoid conflict?



##########
flink-connectors/flink-connector-files/pom.xml:
##########
@@ -65,6 +65,12 @@ under the License.
                        <scope>provided</scope>
                </dependency>
 
+               <dependency>

Review Comment:
   We should not dependent it.



##########
flink-connectors/flink-connector-hive/src/main/java/org/apache/flink/table/planner/delegation/hive/HiveParserDMLHelper.java:
##########
@@ -285,6 +305,81 @@ public Operation 
createInsertOperation(HiveParserCalcitePlanner analyzer, RelNod
                 Collections.emptyMap());
     }
 
+    private SinkModifyOperation createInsertIntoDirectoryOperation(
+            HiveParserQB topQB, QBMetaData qbMetaData, RelNode queryRelNode, 
HiveConf hiveConf) {

Review Comment:
   `HiveConf hiveConf` is not used here, remove it?



##########
flink-connectors/flink-connector-hive/src/test/java/org/apache/flink/connectors/hive/HiveDialectQueryITCase.java:
##########
@@ -330,6 +333,59 @@ public void testJoinInvolvingComplexType() throws 
Exception {
         }
     }
 
+    @Test
+    public void testInsertDirectory() throws Exception {
+        String warehouse = 
hiveCatalog.getHiveConf().getVar(HiveConf.ConfVars.METASTOREWAREHOUSE);
+
+        // test insert overwrite directory with row format parameters
+        tableEnv.executeSql("create table map_table (foo STRING , bar 
MAP<STRING, INT>)");
+        tableEnv.executeSql(
+                "insert into map_table select 'A', 
map('math',100,'english',90,'history',85)");
+
+        String dataDir = warehouse + "/map_table_dir";

Review Comment:
   It will be better use a random dir such as add an UUID suffix.  
`FileUtils#getRandomFilename` maybe useful.



##########
flink-table/flink-sql-parser-hive/src/main/java/org/apache/flink/sql/parser/hive/ddl/SqlCreateHiveTable.java:
##########
@@ -50,7 +50,8 @@ public class SqlCreateHiveTable extends SqlCreateTable {
     public static final String PK_CONSTRAINT_TRAIT = 
"hive.pk.constraint.trait";
     public static final String NOT_NULL_CONSTRAINT_TRAITS = 
"hive.not.null.constraint.traits";
     public static final String NOT_NULL_COLS = "hive.not.null.cols";
-
+    public static final String IS_INSERT_DIRECTORY = "is-insert-directory";

Review Comment:
   In the long run, this module will be dropped, so I think we should add new 
code in here?



##########
flink-connectors/flink-connector-hive/src/main/java/org/apache/flink/table/planner/delegation/hive/copy/HiveParserQB.java:
##########
@@ -69,6 +69,10 @@ public class HiveParserQB {
      */
     private int numSubQueryPredicates;
 
+    private CreateTableDesc createTableDesc;

Review Comment:
   It seems that `createTableDesc` doesn't must require here, remove it?



##########
flink-table/flink-sql-parser-hive/src/main/java/org/apache/flink/sql/parser/hive/ddl/SqlCreateHiveTable.java:
##########
@@ -50,7 +50,8 @@ public class SqlCreateHiveTable extends SqlCreateTable {
     public static final String PK_CONSTRAINT_TRAIT = 
"hive.pk.constraint.trait";
     public static final String NOT_NULL_CONSTRAINT_TRAITS = 
"hive.not.null.constraint.traits";
     public static final String NOT_NULL_COLS = "hive.not.null.cols";
-
+    public static final String IS_INSERT_DIRECTORY = "is-insert-directory";
+    public static final String IS_TO_LOCAL_DIRECTORY = "is-to-local-directory";

Review Comment:
   IS_LOCAL_DIRECTORY = "is-local-directory"?



##########
flink-connectors/flink-connector-hive/src/main/java/org/apache/flink/table/planner/delegation/hive/HiveParserDMLHelper.java:
##########
@@ -285,6 +305,81 @@ public Operation 
createInsertOperation(HiveParserCalcitePlanner analyzer, RelNod
                 Collections.emptyMap());
     }
 
+    private SinkModifyOperation createInsertIntoDirectoryOperation(
+            HiveParserQB topQB, QBMetaData qbMetaData, RelNode queryRelNode, 
HiveConf hiveConf) {
+        String dest = 
topQB.getParseInfo().getClauseNamesForDest().iterator().next();
+        // get the location for insert into directory
+        String location = qbMetaData.getDestFileForAlias(dest);
+        // get whether it's for insert local directory
+        boolean isToLocal = qbMetaData.getDestTypeForAlias(dest) == 
QBMetaData.DEST_LOCAL_FILE;
+        HiveParserDirectoryDesc directoryDesc = topQB.getDirectoryDesc();
+
+        // set row format / stored as / location
+        Map<String, String> props = new HashMap<>();
+        
HiveParserDDLSemanticAnalyzer.encodeRowFormat(directoryDesc.getRowFormatParams(),
 props);
+        
HiveParserDDLSemanticAnalyzer.encodeStorageFormat(directoryDesc.getStorageFormat(),
 props);
+        props.put(TABLE_LOCATION_URI, location);
+
+        props.put(FactoryUtil.CONNECTOR.key(), 
HiveCatalogFactoryOptions.IDENTIFIER);
+        // mark it's for insert into directory
+        props.put(CatalogPropertiesUtil.FLINK_PROPERTY_PREFIX + 
IS_INSERT_DIRECTORY, "true");
+        // mark it's for insert into local directory or not
+        props.put(
+                CatalogPropertiesUtil.FLINK_PROPERTY_PREFIX + 
IS_TO_LOCAL_DIRECTORY,
+                String.valueOf(isToLocal));
+
+        List<RelDataTypeField> fieldList = 
queryRelNode.getRowType().getFieldList();
+        String[] colNameArr = new String[fieldList.size()];
+        String[] colTypeArr = new String[fieldList.size()];
+        for (int i = 0; i < fieldList.size(); i++) {
+            colNameArr[i] = fieldList.get(i).getName();
+            TypeInfo typeInfo = 
HiveParserTypeConverter.convert(fieldList.get(i).getType());
+            if (typeInfo.equals(TypeInfoFactory.voidTypeInfo)) {
+                colTypeArr[i] = TypeInfoFactory.stringTypeInfo.getTypeName();
+            } else {
+                colTypeArr[i] = typeInfo.getTypeName();
+            }
+        }
+
+        String colNames = String.join(",", colNameArr);
+        String colTypes = String.join(":", colTypeArr);
+        props.put("columns", colNames);
+        props.put("columns.types", colTypes);
+
+        PlannerQueryOperation plannerQueryOperation = new 
PlannerQueryOperation(queryRelNode);
+        return new SinkModifyOperation(
+                createDummyTableForInsertDirectory(
+                        plannerQueryOperation.getResolvedSchema(), props),
+                new PlannerQueryOperation(queryRelNode),
+                Collections.emptyMap(),
+                true, // insert into directory is always for overwrite
+                Collections.emptyMap());
+    }
+
+    private ContextResolvedTable createDummyTableForInsertDirectory(
+            ResolvedSchema resolvedSchema, Map<String, String> props) {
+        Schema.Builder schemaBuilder = Schema.newBuilder();
+        for (Column column : resolvedSchema.getColumns()) {
+            schemaBuilder.column(column.getName(), column.getDataType());
+        }
+        CatalogTable catalogTable =
+                CatalogTable.of(
+                        schemaBuilder.build(),

Review Comment:
   `Schema.newBuilder().fromResolvedSchema(resolvedSchema).build()`



##########
flink-connectors/flink-connector-hive/src/main/java/org/apache/flink/table/planner/delegation/hive/HiveParserDMLHelper.java:
##########
@@ -285,6 +305,81 @@ public Operation 
createInsertOperation(HiveParserCalcitePlanner analyzer, RelNod
                 Collections.emptyMap());
     }
 
+    private SinkModifyOperation createInsertIntoDirectoryOperation(
+            HiveParserQB topQB, QBMetaData qbMetaData, RelNode queryRelNode, 
HiveConf hiveConf) {
+        String dest = 
topQB.getParseInfo().getClauseNamesForDest().iterator().next();
+        // get the location for insert into directory
+        String location = qbMetaData.getDestFileForAlias(dest);
+        // get whether it's for insert local directory
+        boolean isToLocal = qbMetaData.getDestTypeForAlias(dest) == 
QBMetaData.DEST_LOCAL_FILE;
+        HiveParserDirectoryDesc directoryDesc = topQB.getDirectoryDesc();
+
+        // set row format / stored as / location
+        Map<String, String> props = new HashMap<>();
+        
HiveParserDDLSemanticAnalyzer.encodeRowFormat(directoryDesc.getRowFormatParams(),
 props);
+        
HiveParserDDLSemanticAnalyzer.encodeStorageFormat(directoryDesc.getStorageFormat(),
 props);
+        props.put(TABLE_LOCATION_URI, location);
+
+        props.put(FactoryUtil.CONNECTOR.key(), 
HiveCatalogFactoryOptions.IDENTIFIER);
+        // mark it's for insert into directory
+        props.put(CatalogPropertiesUtil.FLINK_PROPERTY_PREFIX + 
IS_INSERT_DIRECTORY, "true");
+        // mark it's for insert into local directory or not
+        props.put(
+                CatalogPropertiesUtil.FLINK_PROPERTY_PREFIX + 
IS_TO_LOCAL_DIRECTORY,
+                String.valueOf(isToLocal));
+
+        List<RelDataTypeField> fieldList = 
queryRelNode.getRowType().getFieldList();
+        String[] colNameArr = new String[fieldList.size()];
+        String[] colTypeArr = new String[fieldList.size()];
+        for (int i = 0; i < fieldList.size(); i++) {
+            colNameArr[i] = fieldList.get(i).getName();
+            TypeInfo typeInfo = 
HiveParserTypeConverter.convert(fieldList.get(i).getType());
+            if (typeInfo.equals(TypeInfoFactory.voidTypeInfo)) {
+                colTypeArr[i] = TypeInfoFactory.stringTypeInfo.getTypeName();
+            } else {
+                colTypeArr[i] = typeInfo.getTypeName();
+            }
+        }
+
+        String colNames = String.join(",", colNameArr);
+        String colTypes = String.join(":", colTypeArr);
+        props.put("columns", colNames);
+        props.put("columns.types", colTypes);
+
+        PlannerQueryOperation plannerQueryOperation = new 
PlannerQueryOperation(queryRelNode);
+        return new SinkModifyOperation(
+                createDummyTableForInsertDirectory(
+                        plannerQueryOperation.getResolvedSchema(), props),
+                new PlannerQueryOperation(queryRelNode),
+                Collections.emptyMap(),
+                true, // insert into directory is always for overwrite
+                Collections.emptyMap());
+    }
+
+    private ContextResolvedTable createDummyTableForInsertDirectory(
+            ResolvedSchema resolvedSchema, Map<String, String> props) {
+        Schema.Builder schemaBuilder = Schema.newBuilder();
+        for (Column column : resolvedSchema.getColumns()) {
+            schemaBuilder.column(column.getName(), column.getDataType());
+        }
+        CatalogTable catalogTable =
+                CatalogTable.of(
+                        schemaBuilder.build(),
+                        "a dummy table for the case of insert into directory ",

Review Comment:
   insert overwrite directory



##########
flink-connectors/flink-connector-hive/src/main/java/org/apache/flink/table/planner/delegation/hive/HiveParserDMLHelper.java:
##########
@@ -285,6 +305,81 @@ public Operation 
createInsertOperation(HiveParserCalcitePlanner analyzer, RelNod
                 Collections.emptyMap());
     }
 
+    private SinkModifyOperation createInsertIntoDirectoryOperation(
+            HiveParserQB topQB, QBMetaData qbMetaData, RelNode queryRelNode, 
HiveConf hiveConf) {
+        String dest = 
topQB.getParseInfo().getClauseNamesForDest().iterator().next();
+        // get the location for insert into directory
+        String location = qbMetaData.getDestFileForAlias(dest);
+        // get whether it's for insert local directory
+        boolean isToLocal = qbMetaData.getDestTypeForAlias(dest) == 
QBMetaData.DEST_LOCAL_FILE;
+        HiveParserDirectoryDesc directoryDesc = topQB.getDirectoryDesc();
+
+        // set row format / stored as / location
+        Map<String, String> props = new HashMap<>();
+        
HiveParserDDLSemanticAnalyzer.encodeRowFormat(directoryDesc.getRowFormatParams(),
 props);
+        
HiveParserDDLSemanticAnalyzer.encodeStorageFormat(directoryDesc.getStorageFormat(),
 props);
+        props.put(TABLE_LOCATION_URI, location);
+
+        props.put(FactoryUtil.CONNECTOR.key(), 
HiveCatalogFactoryOptions.IDENTIFIER);
+        // mark it's for insert into directory
+        props.put(CatalogPropertiesUtil.FLINK_PROPERTY_PREFIX + 
IS_INSERT_DIRECTORY, "true");
+        // mark it's for insert into local directory or not
+        props.put(
+                CatalogPropertiesUtil.FLINK_PROPERTY_PREFIX + 
IS_TO_LOCAL_DIRECTORY,
+                String.valueOf(isToLocal));
+
+        List<RelDataTypeField> fieldList = 
queryRelNode.getRowType().getFieldList();
+        String[] colNameArr = new String[fieldList.size()];
+        String[] colTypeArr = new String[fieldList.size()];
+        for (int i = 0; i < fieldList.size(); i++) {
+            colNameArr[i] = fieldList.get(i).getName();
+            TypeInfo typeInfo = 
HiveParserTypeConverter.convert(fieldList.get(i).getType());
+            if (typeInfo.equals(TypeInfoFactory.voidTypeInfo)) {
+                colTypeArr[i] = TypeInfoFactory.stringTypeInfo.getTypeName();
+            } else {
+                colTypeArr[i] = typeInfo.getTypeName();
+            }
+        }
+
+        String colNames = String.join(",", colNameArr);
+        String colTypes = String.join(":", colTypeArr);
+        props.put("columns", colNames);
+        props.put("columns.types", colTypes);
+
+        PlannerQueryOperation plannerQueryOperation = new 
PlannerQueryOperation(queryRelNode);
+        return new SinkModifyOperation(
+                createDummyTableForInsertDirectory(
+                        plannerQueryOperation.getResolvedSchema(), props),
+                new PlannerQueryOperation(queryRelNode),

Review Comment:
   Here can reuse the above `plannerQueryOperation` 



##########
flink-connectors/flink-connector-files/src/main/java/org/apache/flink/connector/file/table/PartitionLoader.java:
##########
@@ -99,15 +104,32 @@ private void overwrite(Path destDir) throws Exception {
     }
 
     /** Moves files from srcDir to destDir. */
-    private void renameFiles(List<Path> srcDirs, Path destDir) throws 
Exception {
+    private void moveFiles(List<Path> srcDirs, Path destDir) throws Exception {
         for (Path srcDir : srcDirs) {
             if (!srcDir.equals(destDir)) {
                 FileStatus[] srcFiles = listStatusWithoutHidden(fs, srcDir);
                 if (srcFiles != null) {
                     for (FileStatus srcFile : srcFiles) {
                         Path srcPath = srcFile.getPath();
                         Path destPath = new Path(destDir, srcPath.getName());
-                        fs.rename(srcPath, destPath);
+                        // if it's not to move to local file system, just 
rename it
+                        if (!isToLocal) {
+                            fs.rename(srcPath, destPath);
+                        } else {
+                            // need move to local file system
+                            if (fs instanceof HadoopFileSystem) {
+                                HadoopFileSystem hdfs = ((HadoopFileSystem) 
fs);

Review Comment:
   We don't need to use HadoopFileSystem, the logic is specialized. Here can 
use `                            FileUtils.copy(srcPath, destPath, true);` copy 
file to local simply. Moreover, you should add an insert local directory 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]

Reply via email to