Unverified Commit 628cc539 authored by aiwenmo's avatar aiwenmo Committed by GitHub

[Feature-1930][dlink-client] Analyze custom functions from Flink SQL (#2502)

* [Feature-1930][dlink-client] Analyze custom functions from Flink SQL * fix error --------- Co-authored-by: 's avatarwenmo <32723967+wenmo@users.noreply.github.com>
parent ded5ae68
......@@ -89,4 +89,21 @@ public interface Parser {
* @throws SqlParserException if an exception is thrown when parsing the statement
*/
SqlNode parseExpression(String sqlExpression);
/**
* Entry point for parsing SQL and return the abstract syntax tree
*
* @param statement the SQL statement to evaluate
* @return abstract syntax tree
* @throws org.apache.flink.table.api.SqlParserException when failed to parse the statement
*/
SqlNode parseSql(String statement);
/**
* validate the query
*
* @param sqlNode SqlNode to execute on
* @return validated sqlNode
*/
SqlNode validate(SqlNode sqlNode);
}
......@@ -148,4 +148,18 @@ public class ParserImpl implements Parser {
public SqlNode parseExpression(String sqlExpression) {
return calciteParserSupplier.get().parseExpression(sqlExpression);
}
@Override
public SqlNode parseSql(String statement) {
CalciteParser parser = calciteParserSupplier.get();
// parse the sql query
return parser.parse(statement);
}
@Override
public SqlNode validate(SqlNode sqlNode) {
FlinkPlannerImpl flinkPlanner = validatorSupplier.get();
return flinkPlanner.validate(sqlNode);
}
}
......@@ -360,7 +360,7 @@ public class CustomTableEnvironmentImpl extends AbstractCustomTableEnvironment {
@Override
public List<LineageRel> getLineage(String statement) {
LineageContext lineageContext = new LineageContext((TableEnvironmentImpl) streamTableEnvironment);
return lineageContext.getLineage(statement);
return lineageContext.analyzeLineage(statement);
}
@Override
......
/*
*
* 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.dinky.utils;
import org.apache.calcite.sql.SqlBasicCall;
import org.apache.calcite.sql.SqlCall;
import org.apache.calcite.sql.SqlFunction;
import org.apache.calcite.sql.SqlIdentifier;
import org.apache.calcite.sql.util.SqlBasicVisitor;
import org.apache.flink.table.catalog.UnresolvedIdentifier;
import java.util.ArrayList;
import java.util.List;
/**
* @description: FunctionVisitor
* @author: HamaWhite
*/
public class FunctionVisitor extends SqlBasicVisitor<Void> {
private final List<UnresolvedIdentifier> functionList = new ArrayList<>();
@Override
public Void visit(SqlCall call) {
if (call instanceof SqlBasicCall && call.getOperator() instanceof SqlFunction) {
SqlFunction function = (SqlFunction) call.getOperator();
SqlIdentifier opName = function.getNameAsId();
functionList.add(UnresolvedIdentifier.of(opName.names));
}
return super.visit(call);
}
public List<UnresolvedIdentifier> getFunctionList() {
return functionList;
}
}
......@@ -19,26 +19,36 @@
package org.dinky.utils;
import org.dinky.data.model.FunctionResult;
import org.dinky.data.model.LineageRel;
import org.apache.calcite.plan.RelOptTable;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.metadata.RelColumnOrigin;
import org.apache.calcite.rel.metadata.RelMetadataQuery;
import org.apache.calcite.sql.SqlNode;
import org.apache.commons.collections.CollectionUtils;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.table.api.TableException;
import org.apache.flink.table.api.ValidationException;
import org.apache.flink.table.api.internal.TableEnvironmentImpl;
import org.apache.flink.table.catalog.FunctionCatalog;
import org.apache.flink.table.catalog.UnresolvedIdentifier;
import org.apache.flink.table.operations.CatalogSinkModifyOperation;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.planner.delegation.ParserImpl;
import org.apache.flink.table.planner.delegation.PlannerBase;
import org.apache.flink.table.planner.operations.PlannerQueryOperation;
import org.apache.flink.table.planner.plan.schema.TableSourceTable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* LineageContext
*
......@@ -46,13 +56,15 @@ import java.util.Set;
*/
public class LineageContext {
private static final Logger LOG = LoggerFactory.getLogger(LineageContext.class);
private final TableEnvironmentImpl tableEnv;
public LineageContext(TableEnvironmentImpl tableEnv) {
this.tableEnv = tableEnv;
}
public List<LineageRel> getLineage(String statement) {
public List<LineageRel> analyzeLineage(String statement) {
// 1. Generate original relNode tree
Tuple2<String, RelNode> parsed = parseStatement(statement);
String sinkTable = parsed.getField(0);
......@@ -130,4 +142,49 @@ public class LineageContext {
}
return resultList;
}
/**
* Analyze custom functions from SQL, does not contain system functions.
*
* @param singleSql the SQL statement to analyze
* @return custom functions set
*/
public Set<FunctionResult> analyzeFunction(String singleSql) {
LOG.info("Analyze function Sql: \n {}", singleSql);
ParserImpl parser = (ParserImpl) tableEnv.getParser();
// parsing sql and return the abstract syntax tree
SqlNode sqlNode = parser.parseSql(singleSql);
// validate the query
SqlNode validated = parser.validate(sqlNode);
// look for all functions
FunctionVisitor visitor = new FunctionVisitor();
validated.accept(visitor);
List<UnresolvedIdentifier> fullFunctionList = visitor.getFunctionList();
// filter custom functions
Set<FunctionResult> resultSet = new HashSet<>();
for (UnresolvedIdentifier unresolvedIdentifier : fullFunctionList) {
getFunctionCatalog()
.lookupFunction(unresolvedIdentifier)
// the objectIdentifier of the built-in function is null
.flatMap(e -> e.getFunctionIdentifier().getIdentifier())
.ifPresent(identifier -> {
FunctionResult functionResult = new FunctionResult()
.setCatalogName(identifier.getCatalogName())
.setDatabase(identifier.getDatabaseName())
.setFunctionName(identifier.getObjectName());
LOG.debug("analyzed function: {}", functionResult);
resultSet.add(functionResult);
});
}
return resultSet;
}
private FunctionCatalog getFunctionCatalog() {
PlannerBase planner = (PlannerBase) tableEnv.getPlanner();
return planner.getFlinkContext().getFunctionCatalog();
}
}
......@@ -21,6 +21,7 @@ package org.dinky.utils;
import static org.junit.Assert.assertEquals;
import org.dinky.data.model.FunctionResult;
import org.dinky.data.model.LineageRel;
import org.apache.flink.configuration.Configuration;
......@@ -30,8 +31,7 @@ import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.api.internal.TableEnvironmentImpl;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.Set;
import org.junit.Before;
import org.junit.BeforeClass;
......@@ -43,7 +43,12 @@ import org.junit.Test;
*/
public class LineageContextTest {
private static final String CATALOG_NAME = "default_catalog";
private static final String DEFAULT_DATABASE = "default_database";
private static TableEnvironmentImpl tableEnv;
private static LineageContext context;
@BeforeClass
......@@ -76,11 +81,14 @@ public class LineageContextTest {
+ ") WITH ( "
+ " 'connector' = 'print' "
+ ")");
// Create custom function my_suffix_udf
tableEnv.executeSql("DROP FUNCTION IF EXISTS my_suffix_udf");
tableEnv.executeSql("CREATE FUNCTION IF NOT EXISTS my_suffix_udf " + "AS 'org.dinky.utils.MySuffixFunction'");
}
@Test
public void testGetLineage() {
List<LineageRel> actualList = context.getLineage("INSERT INTO TT select a||c A ,b||c B from ST");
public void testAnalyzeLineage() {
String sql = "INSERT INTO TT SELECT a||c A ,b||c B FROM ST";
String[][] expectedArray = {
{"ST", "a", "TT", "A", "||(a, c)"},
{"ST", "c", "TT", "A", "||(a, c)"},
......@@ -88,25 +96,32 @@ public class LineageContextTest {
{"ST", "c", "TT", "B", "||(b, c)"}
};
List<LineageRel> expectedList = buildResult(expectedArray);
analyzeLineage(sql, expectedArray);
}
@Test
public void testAnalyzeLineageAndFunction() {
String sql = "INSERT INTO TT SELECT LOWER(a) , my_suffix_udf(b) FROM ST";
String[][] expectedArray = {
{"ST", "a", "TT", "A", "LOWER(a)"},
{"ST", "b", "TT", "B", "my_suffix_udf(b)"}
};
analyzeLineage(sql, expectedArray);
analyzeFunction(sql, new String[] {"my_suffix_udf"});
}
private void analyzeLineage(String sql, String[][] expectedArray) {
List<LineageRel> actualList = context.analyzeLineage(sql);
List<LineageRel> expectedList = LineageRel.build(CATALOG_NAME, DEFAULT_DATABASE, expectedArray);
assertEquals(expectedList, actualList);
}
private List<LineageRel> buildResult(String[][] expectedArray) {
return Stream.of(expectedArray)
.map(e -> {
String transform = e.length == 5 ? e[4] : null;
return new LineageRel(
"default_catalog",
"default_database",
e[0],
e[1],
"default_catalog",
"default_database",
e[2],
e[3],
transform);
})
.collect(Collectors.toList());
private void analyzeFunction(String sql, String[] expectedArray) {
Set<FunctionResult> actualSet = context.analyzeFunction(sql);
Set<FunctionResult> expectedSet = FunctionResult.build(CATALOG_NAME, DEFAULT_DATABASE, expectedArray);
assertEquals(expectedSet, actualSet);
}
}
/*
*
* 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.dinky.utils;
import org.apache.flink.table.functions.ScalarFunction;
/**
* @description: MySuffixFunction
* @author: HamaWhite
*/
public class MySuffixFunction extends ScalarFunction {
public String eval(String input) {
return input.concat("-HamaWhite");
}
}
......@@ -89,4 +89,21 @@ public interface Parser {
* @throws SqlParserException if an exception is thrown when parsing the statement
*/
SqlNode parseExpression(String sqlExpression);
/**
* Entry point for parsing SQL and return the abstract syntax tree
*
* @param statement the SQL statement to evaluate
* @return abstract syntax tree
* @throws org.apache.flink.table.api.SqlParserException when failed to parse the statement
*/
SqlNode parseSql(String statement);
/**
* validate the query
*
* @param sqlNode SqlNode to execute on
* @return validated sqlNode
*/
SqlNode validate(SqlNode sqlNode);
}
......@@ -151,4 +151,18 @@ public class ParserImpl implements Parser {
public SqlNode parseExpression(String sqlExpression) {
return calciteParserSupplier.get().parseExpression(sqlExpression);
}
@Override
public SqlNode parseSql(String statement) {
CalciteParser parser = calciteParserSupplier.get();
// parse the sql query
return parser.parse(statement);
}
@Override
public SqlNode validate(SqlNode sqlNode) {
FlinkPlannerImpl flinkPlanner = validatorSupplier.get();
return flinkPlanner.validate(sqlNode);
}
}
......@@ -319,7 +319,7 @@ public class CustomTableEnvironmentImpl extends AbstractCustomTableEnvironment {
@Override
public List<LineageRel> getLineage(String statement) {
LineageContext lineageContext = new LineageContext((TableEnvironmentImpl) streamTableEnvironment);
return lineageContext.getLineage(statement);
return lineageContext.analyzeLineage(statement);
}
@Override
......
/*
*
* 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.dinky.utils;
import org.apache.calcite.sql.SqlBasicCall;
import org.apache.calcite.sql.SqlCall;
import org.apache.calcite.sql.SqlFunction;
import org.apache.calcite.sql.SqlIdentifier;
import org.apache.calcite.sql.util.SqlBasicVisitor;
import org.apache.flink.table.catalog.UnresolvedIdentifier;
import java.util.ArrayList;
import java.util.List;
/**
* @description: FunctionVisitor
* @author: HamaWhite
*/
public class FunctionVisitor extends SqlBasicVisitor<Void> {
private final List<UnresolvedIdentifier> functionList = new ArrayList<>();
@Override
public Void visit(SqlCall call) {
if (call instanceof SqlBasicCall && call.getOperator() instanceof SqlFunction) {
SqlFunction function = (SqlFunction) call.getOperator();
SqlIdentifier opName = function.getNameAsId();
functionList.add(UnresolvedIdentifier.of(opName.names));
}
return super.visit(call);
}
public List<UnresolvedIdentifier> getFunctionList() {
return functionList;
}
}
......@@ -19,26 +19,38 @@
package org.dinky.utils;
import org.dinky.data.model.FunctionResult;
import org.dinky.data.model.LineageRel;
import org.apache.calcite.plan.RelOptTable;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.metadata.RelColumnOrigin;
import org.apache.calcite.rel.metadata.RelMetadataQuery;
import org.apache.calcite.sql.SqlNode;
import org.apache.commons.collections.CollectionUtils;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.table.api.TableException;
import org.apache.flink.table.api.ValidationException;
import org.apache.flink.table.api.internal.TableEnvironmentImpl;
import org.apache.flink.table.catalog.ContextResolvedFunction;
import org.apache.flink.table.catalog.FunctionCatalog;
import org.apache.flink.table.catalog.UnresolvedIdentifier;
import org.apache.flink.table.functions.FunctionIdentifier;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.operations.SinkModifyOperation;
import org.apache.flink.table.planner.delegation.ParserImpl;
import org.apache.flink.table.planner.delegation.PlannerBase;
import org.apache.flink.table.planner.operations.PlannerQueryOperation;
import org.apache.flink.table.planner.plan.schema.TableSourceTable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* LineageContext
*
......@@ -46,13 +58,15 @@ import java.util.Set;
*/
public class LineageContext {
private static final Logger LOG = LoggerFactory.getLogger(LineageContext.class);
private final TableEnvironmentImpl tableEnv;
public LineageContext(TableEnvironmentImpl tableEnv) {
this.tableEnv = tableEnv;
}
public List<LineageRel> getLineage(String statement) {
public List<LineageRel> analyzeLineage(String statement) {
// 1. Generate original relNode tree
Tuple2<String, RelNode> parsed = parseStatement(statement);
String sinkTable = parsed.getField(0);
......@@ -131,4 +145,50 @@ public class LineageContext {
}
return resultList;
}
/**
* Analyze custom functions from SQL, does not contain system functions.
*
* @param singleSql the SQL statement to analyze
* @return custom functions set
*/
public Set<FunctionResult> analyzeFunction(String singleSql) {
LOG.info("Analyze function Sql: \n {}", singleSql);
ParserImpl parser = (ParserImpl) tableEnv.getParser();
// parsing sql and return the abstract syntax tree
SqlNode sqlNode = parser.parseSql(singleSql);
// validate the query
SqlNode validated = parser.validate(sqlNode);
// look for all functions
FunctionVisitor visitor = new FunctionVisitor();
validated.accept(visitor);
List<UnresolvedIdentifier> fullFunctionList = visitor.getFunctionList();
// filter custom functions
Set<FunctionResult> resultSet = new HashSet<>();
for (UnresolvedIdentifier unresolvedIdentifier : fullFunctionList) {
getFunctionCatalog()
.lookupFunction(unresolvedIdentifier)
.flatMap(ContextResolvedFunction::getIdentifier)
// the objectIdentifier of the built-in function is null
.flatMap(FunctionIdentifier::getIdentifier)
.ifPresent(identifier -> {
FunctionResult functionResult = new FunctionResult()
.setCatalogName(identifier.getCatalogName())
.setDatabase(identifier.getDatabaseName())
.setFunctionName(identifier.getObjectName());
LOG.debug("analyzed function: {}", functionResult);
resultSet.add(functionResult);
});
}
return resultSet;
}
private FunctionCatalog getFunctionCatalog() {
PlannerBase planner = (PlannerBase) tableEnv.getPlanner();
return planner.getFlinkContext().getFunctionCatalog();
}
}
......@@ -21,6 +21,7 @@ package org.dinky.utils;
import static org.junit.Assert.assertEquals;
import org.dinky.data.model.FunctionResult;
import org.dinky.data.model.LineageRel;
import org.apache.flink.configuration.Configuration;
......@@ -30,8 +31,7 @@ import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.api.internal.TableEnvironmentImpl;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.Set;
import org.junit.Before;
import org.junit.BeforeClass;
......@@ -43,7 +43,12 @@ import org.junit.Test;
*/
public class LineageContextTest {
private static final String CATALOG_NAME = "default_catalog";
private static final String DEFAULT_DATABASE = "default_database";
private static TableEnvironmentImpl tableEnv;
private static LineageContext context;
@BeforeClass
......@@ -76,11 +81,14 @@ public class LineageContextTest {
+ ") WITH ( "
+ " 'connector' = 'print' "
+ ")");
// Create custom function my_suffix_udf
tableEnv.executeSql("DROP FUNCTION IF EXISTS my_suffix_udf");
tableEnv.executeSql("CREATE FUNCTION IF NOT EXISTS my_suffix_udf " + "AS 'org.dinky.utils.MySuffixFunction'");
}
@Test
public void testGetLineage() {
List<LineageRel> actualList = context.getLineage("INSERT INTO TT select a||c A ,b||c B from ST");
public void testAnalyzeLineage() {
String sql = "INSERT INTO TT SELECT a||c A ,b||c B FROM ST";
String[][] expectedArray = {
{"ST", "a", "TT", "A", "||(a, c)"},
{"ST", "c", "TT", "A", "||(a, c)"},
......@@ -88,25 +96,32 @@ public class LineageContextTest {
{"ST", "c", "TT", "B", "||(b, c)"}
};
List<LineageRel> expectedList = buildResult(expectedArray);
analyzeLineage(sql, expectedArray);
}
@Test
public void testAnalyzeLineageAndFunction() {
String sql = "INSERT INTO TT SELECT LOWER(a) , my_suffix_udf(b) FROM ST";
String[][] expectedArray = {
{"ST", "a", "TT", "A", "LOWER(a)"},
{"ST", "b", "TT", "B", "my_suffix_udf(b)"}
};
analyzeLineage(sql, expectedArray);
analyzeFunction(sql, new String[] {"my_suffix_udf"});
}
private void analyzeLineage(String sql, String[][] expectedArray) {
List<LineageRel> actualList = context.analyzeLineage(sql);
List<LineageRel> expectedList = LineageRel.build(CATALOG_NAME, DEFAULT_DATABASE, expectedArray);
assertEquals(expectedList, actualList);
}
private List<LineageRel> buildResult(String[][] expectedArray) {
return Stream.of(expectedArray)
.map(e -> {
String transform = e.length == 5 ? e[4] : null;
return new LineageRel(
"default_catalog",
"default_database",
e[0],
e[1],
"default_catalog",
"default_database",
e[2],
e[3],
transform);
})
.collect(Collectors.toList());
private void analyzeFunction(String sql, String[] expectedArray) {
Set<FunctionResult> actualSet = context.analyzeFunction(sql);
Set<FunctionResult> expectedSet = FunctionResult.build(CATALOG_NAME, DEFAULT_DATABASE, expectedArray);
assertEquals(expectedSet, actualSet);
}
}
/*
*
* 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.dinky.utils;
import org.apache.flink.table.functions.ScalarFunction;
/**
* @description: MySuffixFunction
* @author: HamaWhite
*/
public class MySuffixFunction extends ScalarFunction {
public String eval(String input) {
return input.concat("-HamaWhite");
}
}
......@@ -39,7 +39,6 @@ import org.apache.flink.table.api.EnvironmentSettings;
import org.apache.flink.table.api.ExplainDetail;
import org.apache.flink.table.api.TableException;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.api.internal.TableEnvironmentImpl;
import org.apache.flink.table.operations.CreateTableASOperation;
import org.apache.flink.table.operations.ExplainOperation;
import org.apache.flink.table.operations.ModifyOperation;
......@@ -255,8 +254,8 @@ public class CustomTableEnvironmentImpl extends AbstractCustomTableEnvironment {
@Override
public List<LineageRel> getLineage(String statement) {
LineageContext lineageContext = new LineageContext((TableEnvironmentImpl) streamTableEnvironment);
return lineageContext.getLineage(statement);
LineageContext lineageContext = new LineageContext(this);
return lineageContext.analyzeLineage(statement);
}
@Override
......
......@@ -19,9 +19,17 @@
package org.dinky.executor;
import org.apache.calcite.sql.SqlNode;
import org.apache.flink.table.delegation.Parser;
/** */
public interface ExtendedParser extends Parser {
SqlNode parseExpression(String sqlExpression);
SqlNode parseSql(String statement);
SqlNode validate(SqlNode sqlNode);
CustomParser getCustomParser();
}
......@@ -19,6 +19,7 @@
package org.dinky.executor;
import org.apache.calcite.sql.SqlNode;
import org.apache.flink.table.catalog.UnresolvedIdentifier;
import org.apache.flink.table.expressions.ResolvedExpression;
import org.apache.flink.table.operations.Operation;
......@@ -63,6 +64,21 @@ public class ParserWrapper implements ExtendedParser {
return customParser.getParser().getCompletionHints(statement, position);
}
@Override
public SqlNode parseExpression(String sqlExpression) {
return customParser.parseExpression(sqlExpression);
}
@Override
public SqlNode parseSql(String statement) {
return customParser.parseSql(statement);
}
@Override
public SqlNode validate(SqlNode sqlNode) {
return customParser.validate(sqlNode);
}
@Override
public CustomParser getCustomParser() {
return customParser;
......
/*
*
* 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.dinky.utils;
import org.apache.calcite.sql.SqlBasicCall;
import org.apache.calcite.sql.SqlCall;
import org.apache.calcite.sql.SqlFunction;
import org.apache.calcite.sql.SqlIdentifier;
import org.apache.calcite.sql.util.SqlBasicVisitor;
import org.apache.flink.table.catalog.UnresolvedIdentifier;
import java.util.ArrayList;
import java.util.List;
/**
* @description: FunctionVisitor
* @author: HamaWhite
*/
public class FunctionVisitor extends SqlBasicVisitor<Void> {
private final List<UnresolvedIdentifier> functionList = new ArrayList<>();
@Override
public Void visit(SqlCall call) {
if (call instanceof SqlBasicCall && call.getOperator() instanceof SqlFunction) {
SqlFunction function = (SqlFunction) call.getOperator();
SqlIdentifier opName = function.getNameAsId();
functionList.add(UnresolvedIdentifier.of(opName.names));
}
return super.visit(call);
}
public List<UnresolvedIdentifier> getFunctionList() {
return functionList;
}
}
......@@ -19,26 +19,40 @@
package org.dinky.utils;
import org.dinky.context.CustomTableEnvironmentContext;
import org.dinky.data.model.FunctionResult;
import org.dinky.data.model.LineageRel;
import org.dinky.executor.CustomParser;
import org.dinky.executor.CustomTableEnvironment;
import org.dinky.executor.ExtendedParser;
import org.apache.calcite.plan.RelOptTable;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.metadata.RelColumnOrigin;
import org.apache.calcite.rel.metadata.RelMetadataQuery;
import org.apache.calcite.sql.SqlNode;
import org.apache.commons.collections.CollectionUtils;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.table.api.TableException;
import org.apache.flink.table.api.ValidationException;
import org.apache.flink.table.api.internal.TableEnvironmentImpl;
import org.apache.flink.table.catalog.ContextResolvedFunction;
import org.apache.flink.table.catalog.FunctionCatalog;
import org.apache.flink.table.catalog.UnresolvedIdentifier;
import org.apache.flink.table.functions.FunctionIdentifier;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.operations.SinkModifyOperation;
import org.apache.flink.table.planner.delegation.PlannerBase;
import org.apache.flink.table.planner.operations.PlannerQueryOperation;
import org.apache.flink.table.planner.plan.schema.TableSourceTable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* LineageContext
*
......@@ -46,13 +60,15 @@ import java.util.Set;
*/
public class LineageContext {
private final TableEnvironmentImpl tableEnv;
private static final Logger LOG = LoggerFactory.getLogger(LineageContext.class);
private final CustomTableEnvironment tableEnv;
public LineageContext(TableEnvironmentImpl tableEnv) {
public LineageContext(CustomTableEnvironment tableEnv) {
this.tableEnv = tableEnv;
}
public List<LineageRel> getLineage(String statement) {
public List<LineageRel> analyzeLineage(String statement) {
// 1. Generate original relNode tree
Tuple2<String, RelNode> parsed = parseStatement(statement);
String sinkTable = parsed.getField(0);
......@@ -131,4 +147,59 @@ public class LineageContext {
}
return resultList;
}
/**
* Analyze custom functions from SQL, does not contain system functions.
*
* @param singleSql the SQL statement to analyze
* @return custom functions set
*/
public Set<FunctionResult> analyzeFunction(String singleSql) {
LOG.info("Analyze function Sql: \n {}", singleSql);
CustomParser parser = null;
// ((ExtendedParser) tableEnv.getParser()).getCustomParser();
if (CustomTableEnvironmentContext.get().getParser() instanceof ExtendedParser) {
ExtendedParser extendedParser =
(ExtendedParser) CustomTableEnvironmentContext.get().getParser();
parser = extendedParser.getCustomParser();
} else {
throw new RuntimeException("CustomParser is not set");
}
// parsing sql and return the abstract syntax tree
SqlNode sqlNode = parser.parseSql(singleSql);
// validate the query
SqlNode validated = parser.validate(sqlNode);
// look for all functions
FunctionVisitor visitor = new FunctionVisitor();
validated.accept(visitor);
List<UnresolvedIdentifier> fullFunctionList = visitor.getFunctionList();
// filter custom functions
Set<FunctionResult> resultSet = new HashSet<>();
for (UnresolvedIdentifier unresolvedIdentifier : fullFunctionList) {
getFunctionCatalog()
.lookupFunction(unresolvedIdentifier)
.flatMap(ContextResolvedFunction::getIdentifier)
// the objectIdentifier of the built-in function is null
.flatMap(FunctionIdentifier::getIdentifier)
.ifPresent(identifier -> {
FunctionResult functionResult = new FunctionResult()
.setCatalogName(identifier.getCatalogName())
.setDatabase(identifier.getDatabaseName())
.setFunctionName(identifier.getObjectName());
LOG.debug("analyzed function: {}", functionResult);
resultSet.add(functionResult);
});
}
return resultSet;
}
private FunctionCatalog getFunctionCatalog() {
PlannerBase planner = (PlannerBase) tableEnv.getPlanner();
return planner.getFlinkContext().getFunctionCatalog();
}
}
......@@ -21,20 +21,20 @@ package org.dinky.utils;
import static org.junit.Assert.assertEquals;
import org.dinky.data.model.FunctionResult;
import org.dinky.data.model.LineageRel;
import org.dinky.executor.CustomTableEnvironmentImpl;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.EnvironmentSettings;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.api.internal.TableEnvironmentImpl;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.Set;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
/**
......@@ -43,7 +43,12 @@ import org.junit.Test;
*/
public class LineageContextTest {
private static TableEnvironmentImpl tableEnv;
private static final String CATALOG_NAME = "default_catalog";
private static final String DEFAULT_DATABASE = "default_database";
private static CustomTableEnvironmentImpl tableEnv;
private static LineageContext context;
@BeforeClass
......@@ -52,7 +57,7 @@ public class LineageContextTest {
EnvironmentSettings settings =
EnvironmentSettings.newInstance().inStreamingMode().build();
tableEnv = (TableEnvironmentImpl) StreamTableEnvironment.create(env, settings);
tableEnv = CustomTableEnvironmentImpl.create(env, settings);
context = new LineageContext(tableEnv);
}
......@@ -76,11 +81,14 @@ public class LineageContextTest {
+ ") WITH ( "
+ " 'connector' = 'print' "
+ ")");
// Create custom function my_suffix_udf
tableEnv.executeSql("DROP FUNCTION IF EXISTS my_suffix_udf");
tableEnv.executeSql("CREATE FUNCTION IF NOT EXISTS my_suffix_udf " + "AS 'org.dinky.utils.MySuffixFunction'");
}
@Test
public void testGetLineage() {
List<LineageRel> actualList = context.getLineage("INSERT INTO TT select a||c A ,b||c B from ST");
public void testAnalyzeLineage() {
String sql = "INSERT INTO TT SELECT a||c A ,b||c B FROM ST";
String[][] expectedArray = {
{"ST", "a", "TT", "A", "||(a, c)"},
{"ST", "c", "TT", "A", "||(a, c)"},
......@@ -88,25 +96,33 @@ public class LineageContextTest {
{"ST", "c", "TT", "B", "||(b, c)"}
};
List<LineageRel> expectedList = buildResult(expectedArray);
analyzeLineage(sql, expectedArray);
}
@Ignore
@Test
public void testAnalyzeLineageAndFunction() {
String sql = "INSERT INTO TT SELECT LOWER(a) , my_suffix_udf(b) FROM ST";
String[][] expectedArray = {
{"ST", "a", "TT", "A", "LOWER(a)"},
{"ST", "b", "TT", "B", "my_suffix_udf(b)"}
};
analyzeLineage(sql, expectedArray);
analyzeFunction(sql, new String[] {"my_suffix_udf"});
}
private void analyzeLineage(String sql, String[][] expectedArray) {
List<LineageRel> actualList = context.analyzeLineage(sql);
List<LineageRel> expectedList = LineageRel.build(CATALOG_NAME, DEFAULT_DATABASE, expectedArray);
assertEquals(expectedList, actualList);
}
private List<LineageRel> buildResult(String[][] expectedArray) {
return Stream.of(expectedArray)
.map(e -> {
String transform = e.length == 5 ? e[4] : null;
return new LineageRel(
"default_catalog",
"default_database",
e[0],
e[1],
"default_catalog",
"default_database",
e[2],
e[3],
transform);
})
.collect(Collectors.toList());
private void analyzeFunction(String sql, String[] expectedArray) {
Set<FunctionResult> actualSet = context.analyzeFunction(sql);
Set<FunctionResult> expectedSet = FunctionResult.build(CATALOG_NAME, DEFAULT_DATABASE, expectedArray);
assertEquals(expectedSet, actualSet);
}
}
/*
*
* 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.dinky.utils;
import org.apache.flink.table.functions.ScalarFunction;
/**
* @description: MySuffixFunction
* @author: HamaWhite
*/
public class MySuffixFunction extends ScalarFunction {
public String eval(String input) {
return input.concat("-HamaWhite");
}
}
......@@ -40,7 +40,6 @@ import org.apache.flink.table.api.ExplainDetail;
import org.apache.flink.table.api.ExplainFormat;
import org.apache.flink.table.api.TableException;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.api.internal.TableEnvironmentImpl;
import org.apache.flink.table.operations.CreateTableASOperation;
import org.apache.flink.table.operations.ExplainOperation;
import org.apache.flink.table.operations.ModifyOperation;
......@@ -251,8 +250,8 @@ public class CustomTableEnvironmentImpl extends AbstractCustomTableEnvironment {
@Override
public List<LineageRel> getLineage(String statement) {
LineageContext lineageContext = new LineageContext((TableEnvironmentImpl) streamTableEnvironment);
return lineageContext.getLineage(statement);
LineageContext lineageContext = new LineageContext(this);
return lineageContext.analyzeLineage(statement);
}
@Override
......
......@@ -19,9 +19,17 @@
package org.dinky.executor;
import org.apache.calcite.sql.SqlNode;
import org.apache.flink.table.delegation.Parser;
/** */
public interface ExtendedParser extends Parser {
SqlNode parseExpression(String sqlExpression);
SqlNode parseSql(String statement);
SqlNode validate(SqlNode sqlNode);
CustomParser getCustomParser();
}
......@@ -19,6 +19,7 @@
package org.dinky.executor;
import org.apache.calcite.sql.SqlNode;
import org.apache.flink.table.catalog.UnresolvedIdentifier;
import org.apache.flink.table.expressions.ResolvedExpression;
import org.apache.flink.table.operations.Operation;
......@@ -63,6 +64,21 @@ public class ParserWrapper implements ExtendedParser {
return customParser.getParser().getCompletionHints(statement, position);
}
@Override
public SqlNode parseExpression(String sqlExpression) {
return customParser.parseExpression(sqlExpression);
}
@Override
public SqlNode parseSql(String statement) {
return customParser.parseSql(statement);
}
@Override
public SqlNode validate(SqlNode sqlNode) {
return customParser.validate(sqlNode);
}
@Override
public CustomParser getCustomParser() {
return customParser;
......
/*
*
* 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.dinky.utils;
import org.apache.calcite.sql.SqlBasicCall;
import org.apache.calcite.sql.SqlCall;
import org.apache.calcite.sql.SqlFunction;
import org.apache.calcite.sql.SqlIdentifier;
import org.apache.calcite.sql.util.SqlBasicVisitor;
import org.apache.flink.table.catalog.UnresolvedIdentifier;
import java.util.ArrayList;
import java.util.List;
/**
* @description: FunctionVisitor
* @author: HamaWhite
*/
public class FunctionVisitor extends SqlBasicVisitor<Void> {
private final List<UnresolvedIdentifier> functionList = new ArrayList<>();
@Override
public Void visit(SqlCall call) {
if (call instanceof SqlBasicCall && call.getOperator() instanceof SqlFunction) {
SqlFunction function = (SqlFunction) call.getOperator();
SqlIdentifier opName = function.getNameAsId();
functionList.add(UnresolvedIdentifier.of(opName.names));
}
return super.visit(call);
}
public List<UnresolvedIdentifier> getFunctionList() {
return functionList;
}
}
......@@ -19,26 +19,38 @@
package org.dinky.utils;
import org.dinky.data.model.FunctionResult;
import org.dinky.data.model.LineageRel;
import org.dinky.executor.CustomParser;
import org.dinky.executor.CustomTableEnvironment;
import org.apache.calcite.plan.RelOptTable;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.metadata.RelColumnOrigin;
import org.apache.calcite.rel.metadata.RelMetadataQuery;
import org.apache.calcite.sql.SqlNode;
import org.apache.commons.collections.CollectionUtils;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.table.api.TableException;
import org.apache.flink.table.api.ValidationException;
import org.apache.flink.table.api.internal.TableEnvironmentImpl;
import org.apache.flink.table.catalog.ContextResolvedFunction;
import org.apache.flink.table.catalog.FunctionCatalog;
import org.apache.flink.table.catalog.UnresolvedIdentifier;
import org.apache.flink.table.functions.FunctionIdentifier;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.operations.SinkModifyOperation;
import org.apache.flink.table.planner.delegation.PlannerBase;
import org.apache.flink.table.planner.operations.PlannerQueryOperation;
import org.apache.flink.table.planner.plan.schema.TableSourceTable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* LineageContext
*
......@@ -46,13 +58,15 @@ import java.util.Set;
*/
public class LineageContext {
private final TableEnvironmentImpl tableEnv;
private static final Logger LOG = LoggerFactory.getLogger(LineageContext.class);
private final CustomTableEnvironment tableEnv;
public LineageContext(TableEnvironmentImpl tableEnv) {
public LineageContext(CustomTableEnvironment tableEnv) {
this.tableEnv = tableEnv;
}
public List<LineageRel> getLineage(String statement) {
public List<LineageRel> analyzeLineage(String statement) {
// 1. Generate original relNode tree
Tuple2<String, RelNode> parsed = parseStatement(statement);
String sinkTable = parsed.getField(0);
......@@ -131,4 +145,50 @@ public class LineageContext {
}
return resultList;
}
/**
* Analyze custom functions from SQL, does not contain system functions.
*
* @param singleSql the SQL statement to analyze
* @return custom functions set
*/
public Set<FunctionResult> analyzeFunction(String singleSql) {
LOG.info("Analyze function Sql: \n {}", singleSql);
CustomParser parser = (CustomParser) tableEnv.getParser();
// parsing sql and return the abstract syntax tree
SqlNode sqlNode = parser.parseSql(singleSql);
// validate the query
SqlNode validated = parser.validate(sqlNode);
// look for all functions
FunctionVisitor visitor = new FunctionVisitor();
validated.accept(visitor);
List<UnresolvedIdentifier> fullFunctionList = visitor.getFunctionList();
// filter custom functions
Set<FunctionResult> resultSet = new HashSet<>();
for (UnresolvedIdentifier unresolvedIdentifier : fullFunctionList) {
getFunctionCatalog()
.lookupFunction(unresolvedIdentifier)
.flatMap(ContextResolvedFunction::getIdentifier)
// the objectIdentifier of the built-in function is null
.flatMap(FunctionIdentifier::getIdentifier)
.ifPresent(identifier -> {
FunctionResult functionResult = new FunctionResult()
.setCatalogName(identifier.getCatalogName())
.setDatabase(identifier.getDatabaseName())
.setFunctionName(identifier.getObjectName());
LOG.debug("analyzed function: {}", functionResult);
resultSet.add(functionResult);
});
}
return resultSet;
}
private FunctionCatalog getFunctionCatalog() {
PlannerBase planner = (PlannerBase) tableEnv.getPlanner();
return planner.getFlinkContext().getFunctionCatalog();
}
}
......@@ -21,20 +21,20 @@ package org.dinky.utils;
import static org.junit.Assert.assertEquals;
import org.dinky.data.model.FunctionResult;
import org.dinky.data.model.LineageRel;
import org.dinky.executor.CustomTableEnvironmentImpl;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.EnvironmentSettings;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.api.internal.TableEnvironmentImpl;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.Set;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
/**
......@@ -43,7 +43,12 @@ import org.junit.Test;
*/
public class LineageContextTest {
private static TableEnvironmentImpl tableEnv;
private static final String CATALOG_NAME = "default_catalog";
private static final String DEFAULT_DATABASE = "default_database";
private static CustomTableEnvironmentImpl tableEnv;
private static LineageContext context;
@BeforeClass
......@@ -52,7 +57,7 @@ public class LineageContextTest {
EnvironmentSettings settings =
EnvironmentSettings.newInstance().inStreamingMode().build();
tableEnv = (TableEnvironmentImpl) StreamTableEnvironment.create(env, settings);
tableEnv = CustomTableEnvironmentImpl.create(env, settings);
context = new LineageContext(tableEnv);
}
......@@ -76,11 +81,14 @@ public class LineageContextTest {
+ ") WITH ( "
+ " 'connector' = 'print' "
+ ")");
// Create custom function my_suffix_udf
tableEnv.executeSql("DROP FUNCTION IF EXISTS my_suffix_udf");
tableEnv.executeSql("CREATE FUNCTION IF NOT EXISTS my_suffix_udf " + "AS 'org.dinky.utils.MySuffixFunction'");
}
@Test
public void testGetLineage() {
List<LineageRel> actualList = context.getLineage("INSERT INTO TT select a||c A ,b||c B from ST");
public void testAnalyzeLineage() {
String sql = "INSERT INTO TT SELECT a||c A ,b||c B FROM ST";
String[][] expectedArray = {
{"ST", "a", "TT", "A", "||(a, c)"},
{"ST", "c", "TT", "A", "||(a, c)"},
......@@ -88,25 +96,33 @@ public class LineageContextTest {
{"ST", "c", "TT", "B", "||(b, c)"}
};
List<LineageRel> expectedList = buildResult(expectedArray);
analyzeLineage(sql, expectedArray);
}
@Ignore
@Test
public void testAnalyzeLineageAndFunction() {
String sql = "INSERT INTO TT SELECT LOWER(a) , my_suffix_udf(b) FROM ST";
String[][] expectedArray = {
{"ST", "a", "TT", "A", "LOWER(a)"},
{"ST", "b", "TT", "B", "my_suffix_udf(b)"}
};
analyzeLineage(sql, expectedArray);
analyzeFunction(sql, new String[] {"my_suffix_udf"});
}
private void analyzeLineage(String sql, String[][] expectedArray) {
List<LineageRel> actualList = context.analyzeLineage(sql);
List<LineageRel> expectedList = LineageRel.build(CATALOG_NAME, DEFAULT_DATABASE, expectedArray);
assertEquals(expectedList, actualList);
}
private List<LineageRel> buildResult(String[][] expectedArray) {
return Stream.of(expectedArray)
.map(e -> {
String transform = e.length == 5 ? e[4] : null;
return new LineageRel(
"default_catalog",
"default_database",
e[0],
e[1],
"default_catalog",
"default_database",
e[2],
e[3],
transform);
})
.collect(Collectors.toList());
private void analyzeFunction(String sql, String[] expectedArray) {
Set<FunctionResult> actualSet = context.analyzeFunction(sql);
Set<FunctionResult> expectedSet = FunctionResult.build(CATALOG_NAME, DEFAULT_DATABASE, expectedArray);
assertEquals(expectedSet, actualSet);
}
}
/*
*
* 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.dinky.utils;
import org.apache.flink.table.functions.ScalarFunction;
/**
* @description: MySuffixFunction
* @author: HamaWhite
*/
public class MySuffixFunction extends ScalarFunction {
public String eval(String input) {
return input.concat("-HamaWhite");
}
}
/*
*
* 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.dinky.data.model;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
/**
* @description: FunctionResult
* @author: HamaWhite
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class FunctionResult {
private String catalogName;
private String database;
private String functionName;
public static Set<FunctionResult> build(String catalog, String database, String[] expectedArray) {
return Stream.of(expectedArray)
.map(e -> new FunctionResult(catalog, database, e))
.collect(Collectors.toSet());
}
}
......@@ -19,7 +19,10 @@
package org.dinky.data.model;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* LineageResult
......@@ -73,6 +76,23 @@ public class LineageRel {
this.transform = transform;
}
public LineageRel(
String catalog,
String database,
String sourceTable,
String sourceColumn,
String targetTable,
String targetColumn) {
this.sourceCatalog = catalog;
this.sourceDatabase = database;
this.sourceTable = sourceTable;
this.sourceColumn = sourceColumn;
this.targetCatalog = catalog;
this.targetDatabase = database;
this.targetTable = targetTable;
this.targetColumn = targetColumn;
}
public static LineageRel build(
String sourceTablePath,
String sourceColumn,
......@@ -94,26 +114,17 @@ public class LineageRel {
transform);
}
public static LineageRel build(
String sourceCatalog,
String sourceDatabase,
String sourceTable,
String sourceColumn,
String targetCatalog,
String targetDatabase,
String targetTable,
String targetColumn,
String transform) {
return new LineageRel(
sourceCatalog,
sourceDatabase,
sourceTable,
sourceColumn,
targetCatalog,
targetDatabase,
targetTable,
targetColumn,
transform);
public static List<LineageRel> build(String catalog, String database, String[][] expectedArray) {
return Stream.of(expectedArray)
.map(e -> {
LineageRel lineageRel = new LineageRel(catalog, database, e[0], e[1], e[2], e[3]);
// transform field is optional
if (e.length == 5) {
lineageRel.setTransform(e[4]);
}
return lineageRel;
})
.collect(Collectors.toList());
}
public String getSourceCatalog() {
......@@ -160,6 +171,10 @@ public class LineageRel {
return transform;
}
public void setTransform(String transform) {
this.transform = transform;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
......
......@@ -31,4 +31,21 @@ public interface CustomParser {
Parser getParser();
SqlNode parseExpression(String sqlExpression);
/**
* Entry point for parsing a SQL and return the abstract syntax tree
*
* @param statement the SQL statement to evaluate
* @return abstract syntax tree
* @throws org.apache.flink.table.api.SqlParserException when failed to parse the statement
*/
SqlNode parseSql(String statement);
/**
* validate the query
*
* @param sqlNode SqlNode to execute on
* @return validated sqlNode
*/
SqlNode validate(SqlNode sqlNode);
}
......@@ -25,6 +25,7 @@ import org.dinky.trans.CreateTemporalTableFunctionParseStrategy;
import org.apache.calcite.sql.SqlNode;
import org.apache.flink.table.delegation.Parser;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.planner.calcite.FlinkPlannerImpl;
import org.apache.flink.table.planner.delegation.ParserImpl;
import org.apache.flink.table.planner.parse.CalciteParser;
import org.apache.flink.table.planner.parse.ExtendedParseStrategy;
......@@ -42,11 +43,13 @@ public class CustomParserImpl implements CustomParser {
private static final DinkyExtendedParser DINKY_EXTENDED_PARSER = DinkyExtendedParser.INSTANCE;
private final Parser parser;
private final Supplier<FlinkPlannerImpl> validatorSupplier;
private final Supplier<CalciteParser> calciteParserSupplier;
public CustomParserImpl(Parser parser) {
this.parser = parser;
this.calciteParserSupplier = getCalciteParserSupplier(this.parser);
this.validatorSupplier = getValidatorSupplier(this.parser);
}
public static Supplier<CalciteParser> getCalciteParserSupplier(Parser parser) {
......@@ -59,6 +62,16 @@ public class CustomParserImpl implements CustomParser {
}
}
public static Supplier<FlinkPlannerImpl> getValidatorSupplier(Parser parser) {
if (parser instanceof ParserImpl) {
ParserImpl parserImpl = (ParserImpl) parser;
return (Supplier<FlinkPlannerImpl>) ReflectUtil.getFieldValue(parserImpl, "validatorSupplier");
} else {
throw new RuntimeException("Unsupported parser type for getValidatorSupplier: "
+ parser.getClass().getName());
}
}
@Override
public List<Operation> parse(String statement) {
Optional<Operation> command = DINKY_EXTENDED_PARSER.parse(statement);
......@@ -77,6 +90,17 @@ public class CustomParserImpl implements CustomParser {
return calciteParserSupplier.get().parseExpression(sqlExpression);
}
@Override
public SqlNode parseSql(String statement) {
return calciteParserSupplier.get().parse(statement);
}
@Override
public SqlNode validate(SqlNode sqlNode) {
FlinkPlannerImpl flinkPlanner = validatorSupplier.get();
return flinkPlanner.validate(sqlNode);
}
public static class DinkyExtendedParser extends ExtendedParser {
public static final DinkyExtendedParser INSTANCE = new DinkyExtendedParser();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment