1+ package com .dtstack .flink .sql .exec ;
2+
3+ import org .apache .calcite .sql .SqlIdentifier ;
4+ import org .apache .calcite .sql .SqlInsert ;
5+ import org .apache .calcite .sql .SqlNode ;
6+ import org .apache .flink .table .api .Table ;
7+ import org .apache .flink .table .api .TableEnvironment ;
8+ import org .apache .flink .table .api .TableException ;
9+ import org .apache .flink .table .api .java .StreamTableEnvironment ;
10+ import org .apache .flink .table .calcite .FlinkPlannerImpl ;
11+ import org .apache .flink .table .plan .logical .LogicalRelNode ;
12+ import org .apache .flink .table .plan .schema .TableSinkTable ;
13+
14+ import java .lang .reflect .Method ;
15+
16+ /**
17+ * @description: mapping by name when insert into sink table
18+ * @author: maqi
19+ * @create: 2019/08/15 11:09
20+ */
21+ public class FlinkSQLExec {
22+
23+ public static void sqlUpdate (StreamTableEnvironment tableEnv , String stmt ) throws Exception {
24+
25+ FlinkPlannerImpl planner = new FlinkPlannerImpl (tableEnv .getFrameworkConfig (), tableEnv .getPlanner (), tableEnv .getTypeFactory ());
26+ SqlNode insert = planner .parse (stmt );
27+
28+ if (!(insert instanceof SqlInsert )) {
29+ throw new TableException (
30+ "Unsupported SQL query! sqlUpdate() only accepts SQL statements of type INSERT." );
31+ }
32+ SqlNode query = ((SqlInsert ) insert ).getSource ();
33+
34+ SqlNode validatedQuery = planner .validate (query );
35+
36+ Table queryResult = new Table (tableEnv , new LogicalRelNode (planner .rel (validatedQuery ).rel ));
37+ String targetTableName = ((SqlIdentifier ) ((SqlInsert ) insert ).getTargetTable ()).names .get (0 );
38+
39+ try {
40+ Method method = TableEnvironment .class .getDeclaredMethod ("getTable" , String .class );
41+ method .setAccessible (true );
42+
43+ TableSinkTable targetTable = (TableSinkTable ) method .invoke (tableEnv , targetTableName );
44+ String [] fieldNames = targetTable .tableSink ().getFieldNames ();
45+ Table newTable = queryResult .select (String .join ("," , fieldNames ));
46+ // insert query result into sink table
47+ tableEnv .insertInto (newTable , targetTableName , tableEnv .queryConfig ());
48+ } catch (Exception e ) {
49+ throw e ;
50+ }
51+ }
52+ }
0 commit comments