Unverified Commit 26c0f9d0 authored by Wink's avatar Wink Committed by GitHub

[Feature-3332][Flink] Support Flink 1.19 (#3414)

parent b099de0d
...@@ -89,7 +89,7 @@ jobs: ...@@ -89,7 +89,7 @@ jobs:
fail-fast: true fail-fast: true
matrix: matrix:
jdk: [8, 11] jdk: [8, 11]
flink: [1.14, 1.15, 1.16, 1.17, 1.18] flink: [1.14, 1.15, 1.16, 1.17, 1.18, 1.19]
timeout-minutes: 30 timeout-minutes: 30
env: env:
......
...@@ -153,7 +153,7 @@ jobs: ...@@ -153,7 +153,7 @@ jobs:
fail-fast: true fail-fast: true
matrix: matrix:
url: [ registry.cn-hangzhou.aliyuncs.com ,docker.io ] url: [ registry.cn-hangzhou.aliyuncs.com ,docker.io ]
FLINK_VERSION: [1.14.6 , 1.15.4 , 1.16.3, 1.17.2, 1.18.1] FLINK_VERSION: [1.14.6 , 1.15.4 , 1.16.3, 1.17.2, 1.18.1, 1.19.0]
include: include:
- url: registry.cn-hangzhou.aliyuncs.com - url: registry.cn-hangzhou.aliyuncs.com
namespace: dinky namespace: dinky
...@@ -169,6 +169,8 @@ jobs: ...@@ -169,6 +169,8 @@ jobs:
FLINK_BIG_VERSION: 1.17 FLINK_BIG_VERSION: 1.17
- FLINK_VERSION: 1.18.1 - FLINK_VERSION: 1.18.1
FLINK_BIG_VERSION: 1.18 FLINK_BIG_VERSION: 1.18
- FLINK_VERSION: 1.19.0
FLINK_BIG_VERSION: 1.19
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
- name: Move Dockerfile - name: Move Dockerfile
......
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.dinky</groupId>
<artifactId>dinky-app</artifactId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>dinky-app-1.19</artifactId>
<packaging>jar</packaging>
<name>Dinky : App 1.19</name>
<properties>
<mainClass>org.dinky.app.MainApp</mainClass>
</properties>
<dependencies>
<dependency>
<groupId>org.dinky</groupId>
<artifactId>dinky-app-base</artifactId>
</dependency>
<dependency>
<groupId>org.dinky</groupId>
<artifactId>dinky-client-1.19</artifactId>
</dependency>
<dependency>
<groupId>org.dinky</groupId>
<artifactId>dinky-flink-1.19</artifactId>
<scope>${scope.runtime}</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>*.properties</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>${maven-assembly-plugin.version}</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<!-- 可以设置jar包的入口类(可选) -->
<mainClass>org.dinky.app.MainApp</mainClass>
</manifest>
</archive>
<outputDirectory>${project.parent.parent.basedir}/build/extends</outputDirectory>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<goals>
<goal>single</goal>
</goals>
<phase>package</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
/*
*
* 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.app;
import org.dinky.app.constant.AppParamConstant;
import org.dinky.app.db.DBUtil;
import org.dinky.app.flinksql.Submitter;
import org.dinky.data.app.AppParamConfig;
import org.dinky.utils.JsonUtils;
import org.apache.flink.api.java.utils.ParameterTool;
import java.util.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* MainApp
*
* @since 2022/11/05
*/
public class MainApp {
private static final Logger log = LoggerFactory.getLogger(Submitter.class);
public static void main(String[] args) throws Exception {
log.info("=========================Start run dinky app job===============================");
ParameterTool parameters = ParameterTool.fromArgs(args);
boolean isEncrypt = parameters.getBoolean(AppParamConstant.isEncrypt, true);
String config = parameters.get(AppParamConstant.config);
config = isEncrypt ? new String(Base64.getDecoder().decode(config)) : config;
AppParamConfig appConfig = JsonUtils.toJavaBean(config, AppParamConfig.class);
log.info("dinky app is Ready to run, config is {}", appConfig);
DBUtil.init(appConfig);
Submitter.submit(appConfig);
}
}
...@@ -303,6 +303,17 @@ ...@@ -303,6 +303,17 @@
<artifactId>dinky-flink-1.18</artifactId> <artifactId>dinky-flink-1.18</artifactId>
<scope>${scope.runtime}</scope> <scope>${scope.runtime}</scope>
</dependency> </dependency>
<dependency>
<groupId>org.dinky</groupId>
<artifactId>dinky-client-1.19</artifactId>
<scope>${scope.runtime}</scope>
</dependency>
<dependency>
<groupId>org.dinky</groupId>
<artifactId>dinky-flink-1.19</artifactId>
<scope>${scope.runtime}</scope>
</dependency>
</dependencies> </dependencies>
</profile> </profile>
</profiles> </profiles>
......
...@@ -32,6 +32,7 @@ ...@@ -32,6 +32,7 @@
<module>dinky-app-1.16</module> <module>dinky-app-1.16</module>
<module>dinky-app-1.17</module> <module>dinky-app-1.17</module>
<module>dinky-app-1.18</module> <module>dinky-app-1.18</module>
<module>dinky-app-1.19</module>
</modules> </modules>
</profile> </profile>
......
...@@ -108,6 +108,14 @@ ...@@ -108,6 +108,14 @@
<include>dinky-client-1.18-${project.version}.jar</include> <include>dinky-client-1.18-${project.version}.jar</include>
</includes> </includes>
</fileSet> </fileSet>
<fileSet>
<directory>${project.parent.basedir}/build/extends/</directory>
<outputDirectory>extends/flink1.19/dinky</outputDirectory>
<includes>
<include>dinky-catalog-mysql-1.19-${project.version}.jar</include>
<include>dinky-client-1.19-${project.version}.jar</include>
</includes>
</fileSet>
<fileSet> <fileSet>
<directory>${project.parent.basedir}/build/extends/</directory> <directory>${project.parent.basedir}/build/extends/</directory>
<outputDirectory>extends</outputDirectory> <outputDirectory>extends</outputDirectory>
......
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.dinky</groupId>
<artifactId>dinky-catalog-mysql</artifactId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>dinky-catalog-mysql-1.19</artifactId>
<packaging>jar</packaging>
<name>Dinky : Catalog : Mysql 1.19</name>
<dependencies>
<dependency>
<groupId>org.dinky</groupId>
<artifactId>dinky-common</artifactId>
</dependency>
<dependency>
<groupId>org.dinky</groupId>
<artifactId>dinky-flink-1.19</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<!-- 指定打包的jar包输出路径 -->
<outputDirectory>${project.parent.parent.parent.basedir}/build/extends</outputDirectory>
</configuration>
</plugin>
</plugins>
</build>
</project>
/*
*
* 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.flink.catalog.factory;
import static org.apache.flink.table.factories.FactoryUtil.PROPERTY_VERSION;
import static org.dinky.flink.catalog.factory.DinkyMysqlCatalogFactoryOptions.PASSWORD;
import static org.dinky.flink.catalog.factory.DinkyMysqlCatalogFactoryOptions.URL;
import static org.dinky.flink.catalog.factory.DinkyMysqlCatalogFactoryOptions.USERNAME;
import org.dinky.flink.catalog.DinkyMysqlCatalog;
import org.apache.flink.configuration.ConfigOption;
import org.apache.flink.table.catalog.Catalog;
import org.apache.flink.table.factories.CatalogFactory;
import org.apache.flink.table.factories.FactoryUtil;
import java.util.HashSet;
import java.util.Set;
/** Factory for {@link DinkyMysqlCatalog}. */
public class DinkyMysqlCatalogFactory implements CatalogFactory {
@Override
public String factoryIdentifier() {
return DinkyMysqlCatalogFactoryOptions.IDENTIFIER;
}
@Override
public Set<ConfigOption<?>> requiredOptions() {
final Set<ConfigOption<?>> options = new HashSet<>();
return options;
}
@Override
public Set<ConfigOption<?>> optionalOptions() {
final Set<ConfigOption<?>> options = new HashSet<>();
options.add(USERNAME);
options.add(PASSWORD);
options.add(URL);
options.add(PROPERTY_VERSION);
return options;
}
@Override
public Catalog createCatalog(Context context) {
final FactoryUtil.CatalogFactoryHelper helper = FactoryUtil.createCatalogFactoryHelper(this, context);
helper.validate();
return new DinkyMysqlCatalog(
context.getName(),
helper.getOptions().get(URL),
helper.getOptions().get(USERNAME),
helper.getOptions().get(PASSWORD));
}
}
/*
*
* 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.flink.catalog.factory;
import org.dinky.flink.catalog.DinkyMysqlCatalog;
import org.apache.flink.annotation.Internal;
import org.apache.flink.configuration.ConfigOption;
import org.apache.flink.configuration.ConfigOptions;
/** {@link ConfigOption}s for {@link DinkyMysqlCatalog}. */
@Internal
public class DinkyMysqlCatalogFactoryOptions {
public static final String IDENTIFIER = "dinky_mysql";
public static final ConfigOption<String> USERNAME =
ConfigOptions.key("username").stringType().noDefaultValue();
public static final ConfigOption<String> PASSWORD =
ConfigOptions.key("password").stringType().noDefaultValue();
public static final ConfigOption<String> URL =
ConfigOptions.key("url").stringType().noDefaultValue();
private DinkyMysqlCatalogFactoryOptions() {}
}
# 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.
org.dinky.flink.catalog.factory.DinkyMysqlCatalogFactory
...@@ -45,6 +45,7 @@ ...@@ -45,6 +45,7 @@
<module>dinky-catalog-mysql-1.16</module> <module>dinky-catalog-mysql-1.16</module>
<module>dinky-catalog-mysql-1.17</module> <module>dinky-catalog-mysql-1.17</module>
<module>dinky-catalog-mysql-1.18</module> <module>dinky-catalog-mysql-1.18</module>
<module>dinky-catalog-mysql-1.19</module>
</modules> </modules>
</profile> </profile>
</profiles> </profiles>
......
...@@ -47,5 +47,11 @@ ...@@ -47,5 +47,11 @@
<module>dinky-cdc-plus</module> <module>dinky-cdc-plus</module>
</modules> </modules>
</profile> </profile>
<profile>
<id>flink-1.19</id>
<modules>
<module>dinky-cdc-plus</module>
</modules>
</profile>
</profiles> </profiles>
</project> </project>
/*
*
* 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.executor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.kubernetes.KubernetesClusterDescriptor;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClient;
import org.apache.flink.yarn.YarnClusterDescriptor;
import java.io.File;
import java.util.List;
public class ClusterDescriptorAdapterImpl extends ClusterDescriptorAdapter {
public ClusterDescriptorAdapterImpl() {}
public ClusterDescriptorAdapterImpl(YarnClusterDescriptor yarnClusterDescriptor) {
super(yarnClusterDescriptor);
}
@Override
public void addShipFiles(List<File> shipFiles) {
yarnClusterDescriptor.addShipFiles(shipFiles);
}
@Override
public KubernetesClusterDescriptor createKubernetesClusterDescriptor(
Configuration configuration, FlinkKubeClient flinkKubeClient) {
return new KubernetesClusterDescriptor(configuration, flinkKubeClient);
}
}
/*
*
* 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.executor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.kubernetes.KubernetesClusterDescriptor;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClient;
import org.apache.flink.yarn.YarnClusterDescriptor;
import java.io.File;
import java.util.List;
public class ClusterDescriptorAdapterImpl extends ClusterDescriptorAdapter {
public ClusterDescriptorAdapterImpl() {}
public ClusterDescriptorAdapterImpl(YarnClusterDescriptor yarnClusterDescriptor) {
super(yarnClusterDescriptor);
}
@Override
public void addShipFiles(List<File> shipFiles) {
yarnClusterDescriptor.addShipFiles(shipFiles);
}
@Override
public KubernetesClusterDescriptor createKubernetesClusterDescriptor(
Configuration configuration, FlinkKubeClient flinkKubeClient) {
return new KubernetesClusterDescriptor(configuration, flinkKubeClient);
}
}
/*
*
* 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.executor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.kubernetes.KubernetesClusterDescriptor;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClient;
import org.apache.flink.yarn.YarnClusterDescriptor;
import java.io.File;
import java.util.List;
public class ClusterDescriptorAdapterImpl extends ClusterDescriptorAdapter {
public ClusterDescriptorAdapterImpl() {}
public ClusterDescriptorAdapterImpl(YarnClusterDescriptor yarnClusterDescriptor) {
super(yarnClusterDescriptor);
}
@Override
public void addShipFiles(List<File> shipFiles) {
yarnClusterDescriptor.addShipFiles(shipFiles);
}
@Override
public KubernetesClusterDescriptor createKubernetesClusterDescriptor(
Configuration configuration, FlinkKubeClient flinkKubeClient) {
return new KubernetesClusterDescriptor(configuration, flinkKubeClient);
}
}
/*
*
* 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.executor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.kubernetes.KubernetesClusterDescriptor;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClient;
import org.apache.flink.yarn.YarnClusterDescriptor;
import java.io.File;
import java.util.List;
public class ClusterDescriptorAdapterImpl extends ClusterDescriptorAdapter {
public ClusterDescriptorAdapterImpl() {}
public ClusterDescriptorAdapterImpl(YarnClusterDescriptor yarnClusterDescriptor) {
super(yarnClusterDescriptor);
}
@Override
public void addShipFiles(List<File> shipFiles) {
yarnClusterDescriptor.addShipFiles(shipFiles);
}
@Override
public KubernetesClusterDescriptor createKubernetesClusterDescriptor(
Configuration configuration, FlinkKubeClient flinkKubeClient) {
return new KubernetesClusterDescriptor(configuration, flinkKubeClient);
}
}
/*
*
* 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.executor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.kubernetes.KubernetesClusterDescriptor;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClient;
import org.apache.flink.yarn.YarnClusterDescriptor;
import java.io.File;
import java.util.List;
public class ClusterDescriptorAdapterImpl extends ClusterDescriptorAdapter {
public ClusterDescriptorAdapterImpl() {}
public ClusterDescriptorAdapterImpl(YarnClusterDescriptor yarnClusterDescriptor) {
super(yarnClusterDescriptor);
}
@Override
public void addShipFiles(List<File> shipFiles) {
yarnClusterDescriptor.addShipFiles(shipFiles);
}
@Override
public KubernetesClusterDescriptor createKubernetesClusterDescriptor(
Configuration configuration, FlinkKubeClient flinkKubeClient) {
return new KubernetesClusterDescriptor(configuration, flinkKubeClient);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.dinky</groupId>
<artifactId>dinky-client</artifactId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>dinky-client-1.19</artifactId>
<packaging>jar</packaging>
<name>Dinky : Client 1.19</name>
<dependencies>
<dependency>
<groupId>org.dinky</groupId>
<artifactId>dinky-client-base</artifactId>
</dependency>
<dependency>
<groupId>org.dinky</groupId>
<artifactId>dinky-flink-1.19</artifactId>
<scope>${scope.runtime}</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven-jar-plugin.version}</version>
<configuration>
<outputDirectory>${project.parent.parent.basedir}/build/extends</outputDirectory>
</configuration>
</plugin>
</plugins>
</build>
</project>
/*
*
* 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.apache.calcite.rel.metadata;
import org.apache.calcite.plan.RelOptTable;
/**
* Modified based on calcite's source code org.apache.calcite.rel.metadata.RelColumnOrigin
* <p>
* Modification point:
* <ol>
* <li>add transform field and related code.
* </ol>
*
* @description: RelColumnOrigin is a data structure describing one of the origins of an
* output column produced by a relational expression.
* @author: HamaWhite
*/
public class RelColumnOrigin {
// ~ Instance fields --------------------------------------------------------
private final RelOptTable originTable;
private final int iOriginColumn;
private final boolean isDerived;
/**
* Stores the expression for data conversion,
* which source table fields are transformed by which expression the target field
*/
private String transform;
// ~ Constructors -----------------------------------------------------------
public RelColumnOrigin(RelOptTable originTable, int iOriginColumn, boolean isDerived) {
this.originTable = originTable;
this.iOriginColumn = iOriginColumn;
this.isDerived = isDerived;
}
public RelColumnOrigin(RelOptTable originTable, int iOriginColumn, boolean isDerived, String transform) {
this.originTable = originTable;
this.iOriginColumn = iOriginColumn;
this.isDerived = isDerived;
this.transform = transform;
}
// ~ Methods ----------------------------------------------------------------
/**
* Returns table of origin.
*/
public RelOptTable getOriginTable() {
return originTable;
}
/**
* Returns the 0-based index of column in origin table; whether this ordinal
* is flattened or unflattened depends on whether UDT flattening has already
* been performed on the relational expression which produced this
* description.
*/
public int getOriginColumnOrdinal() {
return iOriginColumn;
}
/**
* Consider the query <code>select a+b as c, d as e from t</code>. The
* output column c has two origins (a and b), both of them derived. The
* output column d as one origin (c), which is not derived.
*
* @return false if value taken directly from column in origin table; true
* otherwise
*/
public boolean isDerived() {
return isDerived;
}
public String getTransform() {
return transform;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof RelColumnOrigin)) {
return false;
}
RelColumnOrigin other = (RelColumnOrigin) obj;
return originTable.getQualifiedName().equals(other.originTable.getQualifiedName())
&& (iOriginColumn == other.iOriginColumn)
&& (isDerived == other.isDerived);
}
@Override
public int hashCode() {
return originTable.getQualifiedName().hashCode() + iOriginColumn + (isDerived ? 313 : 0);
}
}
/*
*
* 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.executor;
import org.dinky.data.model.LineageRel;
import org.dinky.data.result.SqlExplainResult;
import org.dinky.utils.LineageContext;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.ExplainDetail;
import org.apache.flink.table.api.ExplainFormat;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.table.api.TableException;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.api.bridge.java.internal.StreamTableEnvironmentImpl;
import org.apache.flink.table.delegation.Planner;
import org.apache.flink.table.operations.ExplainOperation;
import org.apache.flink.table.operations.ModifyOperation;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.operations.QueryOperation;
import java.util.List;
import cn.hutool.core.util.ReflectUtil;
/** */
public abstract class AbstractCustomTableEnvironment
implements CustomTableEnvironment, DefaultTableEnvironmentInternal, DefaultStreamTableEnvironment {
protected StreamTableEnvironment streamTableEnvironment;
protected ClassLoader userClassLoader;
protected AbstractCustomTableEnvironment() {}
protected AbstractCustomTableEnvironment(StreamTableEnvironment streamTableEnvironment) {
this.streamTableEnvironment = streamTableEnvironment;
}
@Override
public TableEnvironment getTableEnvironment() {
return streamTableEnvironment;
}
public StreamExecutionEnvironment getStreamExecutionEnvironment() {
return ((StreamTableEnvironmentImpl) streamTableEnvironment).execEnv();
}
@Override
public ClassLoader getUserClassLoader() {
return userClassLoader;
}
public Planner getPlanner() {
return ((StreamTableEnvironmentImpl) streamTableEnvironment).getPlanner();
}
@Override
public void injectParser(CustomParser parser) {
ReflectUtil.setFieldValue(getPlanner(), "parser", new ParserWrapper(parser));
}
@Override
public void injectExtendedExecutor(CustomExtendedOperationExecutor extendedExecutor) {}
@Override
public Configuration getRootConfiguration() {
return (Configuration) this.getConfig().getRootConfiguration();
}
@Override
public SqlExplainResult explainSqlRecord(String statement, ExplainDetail... extraDetails) {
List<Operation> operations = getParser().parse(statement);
if (operations.size() != 1) {
throw new TableException("Unsupported SQL query! explainSql() only accepts a single SQL query.");
}
Operation operation = operations.get(0);
SqlExplainResult data = new SqlExplainResult();
data.setParseTrue(true);
data.setExplainTrue(true);
if (operation instanceof ModifyOperation) {
data.setType("Modify DML");
} else if (operation instanceof ExplainOperation) {
data.setType("Explain DML");
} else if (operation instanceof QueryOperation) {
data.setType("Query DML");
} else {
data.setExplain(operation.asSummaryString());
data.setType("DDL");
// data.setExplain("DDL statement needn't comment。");
return data;
}
data.setExplain(getPlanner().explain(operations, ExplainFormat.TEXT, extraDetails));
return data;
}
@Override
public List<LineageRel> getLineage(String statement) {
LineageContext lineageContext = new LineageContext(this);
return lineageContext.analyzeLineage(statement);
}
}
/*
*
* 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.executor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.kubernetes.KubernetesClusterDescriptor;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClient;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClientFactory;
import org.apache.flink.yarn.YarnClusterDescriptor;
import org.apache.hadoop.fs.Path;
import java.io.File;
import java.util.List;
import java.util.stream.Collectors;
public class ClusterDescriptorAdapterImpl extends ClusterDescriptorAdapter {
public ClusterDescriptorAdapterImpl() {}
public ClusterDescriptorAdapterImpl(YarnClusterDescriptor yarnClusterDescriptor) {
super(yarnClusterDescriptor);
}
@Override
public void addShipFiles(List<File> shipFiles) {
yarnClusterDescriptor.addShipFiles(shipFiles.stream()
.map(file -> {
return new Path(file.getPath());
})
.collect(Collectors.toList()));
}
@Override
public KubernetesClusterDescriptor createKubernetesClusterDescriptor(
Configuration configuration, FlinkKubeClient flinkKubeClient) {
return new KubernetesClusterDescriptor(configuration, FlinkKubeClientFactory.getInstance());
}
}
/*
*
* 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.executor;
import org.dinky.operations.CustomNewParserImpl;
import org.apache.flink.api.dag.Transformation;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.PipelineOptions;
import org.apache.flink.runtime.jobgraph.jsonplan.JsonPlanGenerator;
import org.apache.flink.runtime.rest.messages.JobPlanInfo;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.JSONGenerator;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.table.api.EnvironmentSettings;
import org.apache.flink.table.api.TableException;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.api.internal.CachedPlan;
import org.apache.flink.table.api.internal.TableResultInternal;
import org.apache.flink.table.catalog.CatalogDescriptor;
import org.apache.flink.table.operations.ModifyOperation;
import org.apache.flink.table.operations.Operation;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* CustomTableEnvironmentImpl
*
* @since 2022/05/08
*/
public class CustomTableEnvironmentImpl extends AbstractCustomTableEnvironment {
private static final Logger log = LoggerFactory.getLogger(CustomTableEnvironmentImpl.class);
private static final ObjectMapper mapper = new ObjectMapper();
public CustomTableEnvironmentImpl(StreamTableEnvironment streamTableEnvironment) {
super(streamTableEnvironment);
injectParser(new CustomNewParserImpl(this, getPlanner().getParser()));
}
public static CustomTableEnvironmentImpl create(
StreamExecutionEnvironment executionEnvironment, ClassLoader classLoader) {
return create(
executionEnvironment,
EnvironmentSettings.newInstance().withClassLoader(classLoader).build());
}
public static CustomTableEnvironmentImpl createBatch(
StreamExecutionEnvironment executionEnvironment, ClassLoader classLoader) {
return create(
executionEnvironment,
EnvironmentSettings.newInstance()
.withClassLoader(classLoader)
.inBatchMode()
.build());
}
public static CustomTableEnvironmentImpl create(
StreamExecutionEnvironment executionEnvironment, EnvironmentSettings settings) {
StreamTableEnvironment streamTableEnvironment = StreamTableEnvironment.create(executionEnvironment, settings);
return new CustomTableEnvironmentImpl(streamTableEnvironment);
}
@Override
public ObjectNode getStreamGraph(String statement) {
List<Operation> operations = super.getParser().parse(statement);
if (operations.size() != 1) {
throw new TableException("Unsupported SQL query! explainSql() only accepts a single SQL query.");
}
List<ModifyOperation> modifyOperations = operations.stream()
.filter(ModifyOperation.class::isInstance)
.map(ModifyOperation.class::cast)
.collect(Collectors.toList());
StreamGraph streamGraph = transOperatoinsToStreamGraph(modifyOperations);
JSONGenerator jsonGenerator = new JSONGenerator(streamGraph);
try {
return (ObjectNode) mapper.readTree(jsonGenerator.getJSON());
} catch (JsonProcessingException e) {
log.error("read streamGraph configure error: ", e);
return mapper.createObjectNode();
}
}
private StreamGraph transOperatoinsToStreamGraph(List<ModifyOperation> modifyOperations) {
List<Transformation<?>> trans = getPlanner().translate(modifyOperations);
final StreamExecutionEnvironment environment = getStreamExecutionEnvironment();
trans.forEach(environment::addOperator);
StreamGraph streamGraph = environment.getStreamGraph();
final Configuration configuration = getConfig().getConfiguration();
if (configuration.containsKey(PipelineOptions.NAME.key())) {
streamGraph.setJobName(configuration.getString(PipelineOptions.NAME));
}
return streamGraph;
}
@Override
public JobPlanInfo getJobPlanInfo(List<String> statements) {
return new JobPlanInfo(JsonPlanGenerator.generatePlan(getJobGraphFromInserts(statements)));
}
@Override
public StreamGraph getStreamGraphFromInserts(List<String> statements) {
List<ModifyOperation> modifyOperations = new ArrayList<>();
statements.stream().map(statement -> getParser().parse(statement)).forEach(operations -> {
if (operations.size() != 1) {
throw new TableException("Only single statement is supported.");
}
Operation operation = operations.get(0);
if (operation instanceof ModifyOperation) {
modifyOperations.add((ModifyOperation) operation);
} else {
throw new TableException("Only insert statement is supported now.");
}
});
return transOperatoinsToStreamGraph(modifyOperations);
}
@Override
public void createCatalog(String catalogName, CatalogDescriptor catalogDescriptor) {
getCatalogManager().createCatalog(catalogName, catalogDescriptor);
}
@Override
public TableResultInternal executeCachedPlanInternal(CachedPlan cachedPlan) {
return null;
}
}
/*
*
* 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.executor;
import org.apache.flink.annotation.Internal;
import org.apache.flink.core.execution.JobClient;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.ResultKind;
import org.apache.flink.table.api.TableException;
import org.apache.flink.table.api.TableResult;
import org.apache.flink.table.api.internal.CachedPlan;
import org.apache.flink.table.api.internal.ResultProvider;
import org.apache.flink.table.api.internal.TableResultInternal;
import org.apache.flink.table.catalog.Column;
import org.apache.flink.table.catalog.ResolvedSchema;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.types.DataType;
import org.apache.flink.table.utils.print.PrintStyle;
import org.apache.flink.table.utils.print.RowDataToStringConverter;
import org.apache.flink.table.utils.print.TableauStyle;
import org.apache.flink.types.Row;
import org.apache.flink.util.CloseableIterator;
import org.apache.flink.util.Preconditions;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.Nullable;
/** Implementation for {@link TableResult}. */
@Internal
public class CustomTableResultImpl implements TableResultInternal {
public static final TableResult TABLE_RESULT_OK = CustomTableResultImpl.builder()
.resultKind(ResultKind.SUCCESS)
.schema(ResolvedSchema.of(Column.physical("result", DataTypes.STRING())))
.data(Collections.singletonList(Row.of("OK")))
.build();
private final JobClient jobClient;
private final ResolvedSchema resolvedSchema;
private final ResultKind resultKind;
private final ResultProvider resultProvider;
private final PrintStyle printStyle;
private CustomTableResultImpl(
@Nullable JobClient jobClient,
ResolvedSchema resolvedSchema,
ResultKind resultKind,
ResultProvider resultProvider,
PrintStyle printStyle) {
this.jobClient = jobClient;
this.resolvedSchema = Preconditions.checkNotNull(resolvedSchema, "resolvedSchema should not be null");
this.resultKind = Preconditions.checkNotNull(resultKind, "resultKind should not be null");
Preconditions.checkNotNull(resultProvider, "result provider should not be null");
this.resultProvider = resultProvider;
this.printStyle = Preconditions.checkNotNull(printStyle, "printStyle should not be null");
}
public static TableResult buildTableResult(List<TableSchemaField> fields, List<Row> rows) {
Builder builder = builder().resultKind(ResultKind.SUCCESS);
if (fields.size() > 0) {
List<String> columnNames = new ArrayList<>();
List<DataType> columnTypes = new ArrayList<>();
for (int i = 0; i < fields.size(); i++) {
columnNames.add(fields.get(i).getName());
columnTypes.add(fields.get(i).getType());
}
builder.schema(ResolvedSchema.physical(columnNames, columnTypes)).data(rows);
}
return builder.build();
}
@Override
public Optional<JobClient> getJobClient() {
return Optional.ofNullable(jobClient);
}
@Override
public void await() throws InterruptedException, ExecutionException {
try {
awaitInternal(-1, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
// do nothing
}
}
@Override
public void await(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
awaitInternal(timeout, unit);
}
private void awaitInternal(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
if (jobClient == null) {
return;
}
ExecutorService executor = Executors.newFixedThreadPool(1, r -> new Thread(r, "TableResult-await-thread"));
try {
CompletableFuture<Void> future = CompletableFuture.runAsync(
() -> {
while (!resultProvider.isFirstRowReady()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new TableException("Thread is interrupted");
}
}
},
executor);
if (timeout >= 0) {
future.get(timeout, unit);
} else {
future.get();
}
} finally {
executor.shutdown();
}
}
@Override
public ResolvedSchema getResolvedSchema() {
return resolvedSchema;
}
@Override
public ResultKind getResultKind() {
return resultKind;
}
@Override
public CloseableIterator<Row> collect() {
return resultProvider.toExternalIterator();
}
@Override
public CloseableIterator<RowData> collectInternal() {
return resultProvider.toInternalIterator();
}
@Override
public RowDataToStringConverter getRowDataToStringConverter() {
return resultProvider.getRowDataStringConverter();
}
@Nullable
public CachedPlan getCachedPlan() {
return null;
}
@Override
public void print() {
Iterator<RowData> it = resultProvider.toInternalIterator();
printStyle.print(it, new PrintWriter(System.out));
}
public static Builder builder() {
return new Builder();
}
/** Builder for creating a {@link CustomTableResultImpl}. */
public static class Builder {
private JobClient jobClient = null;
private ResolvedSchema resolvedSchema = null;
private ResultKind resultKind = null;
private ResultProvider resultProvider = null;
private PrintStyle printStyle = null;
private Builder() {}
/**
* Specifies job client which associates the submitted Flink job.
*
* @param jobClient a {@link JobClient} for the submitted Flink job.
*/
public Builder jobClient(JobClient jobClient) {
this.jobClient = jobClient;
return this;
}
/**
* Specifies schema of the execution result.
*
* @param resolvedSchema a {@link ResolvedSchema} for the execution result.
*/
public Builder schema(ResolvedSchema resolvedSchema) {
Preconditions.checkNotNull(resolvedSchema, "resolvedSchema should not be null");
this.resolvedSchema = resolvedSchema;
return this;
}
/**
* Specifies result kind of the execution result.
*
* @param resultKind a {@link ResultKind} for the execution result.
*/
public Builder resultKind(ResultKind resultKind) {
Preconditions.checkNotNull(resultKind, "resultKind should not be null");
this.resultKind = resultKind;
return this;
}
public Builder resultProvider(ResultProvider resultProvider) {
Preconditions.checkNotNull(resultProvider, "resultProvider should not be null");
this.resultProvider = resultProvider;
return this;
}
/**
* Specifies an row list as the execution result.
*
* @param rowList a row list as the execution result.
*/
public Builder data(List<Row> rowList) {
Preconditions.checkNotNull(rowList, "listRows should not be null");
this.resultProvider = new StaticResultProvider(rowList);
return this;
}
/** Specifies print style. Default is {@link TableauStyle} with max integer column width. */
public Builder setPrintStyle(PrintStyle printStyle) {
Preconditions.checkNotNull(printStyle, "printStyle should not be null");
this.printStyle = printStyle;
return this;
}
/** Returns a {@link TableResult} instance. */
public TableResultInternal build() {
if (printStyle == null) {
printStyle = PrintStyle.rawContent(resultProvider.getRowDataStringConverter());
}
return new CustomTableResultImpl(jobClient, resolvedSchema, resultKind, resultProvider, printStyle);
}
}
}
/*
*
* 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.executor;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.table.api.Schema;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamStatementSet;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.connector.ChangelogMode;
import org.apache.flink.table.expressions.Expression;
import org.apache.flink.table.functions.AggregateFunction;
import org.apache.flink.table.functions.TableAggregateFunction;
import org.apache.flink.table.functions.TableFunction;
import org.apache.flink.table.types.AbstractDataType;
import org.apache.flink.types.Row;
/** */
public interface DefaultStreamTableEnvironment
extends StreamTableEnvironment, DefaultTableEnvironment, TableEnvironmentInstance {
default StreamTableEnvironment getStreamTableEnvironment() {
return (StreamTableEnvironment) getTableEnvironment();
}
@Override // region StreamTableEnvironment interface
default <T> void registerFunction(String s, TableFunction<T> tableFunction) {
getStreamTableEnvironment().registerFunction(s, tableFunction);
}
@Override
default <T, A> void registerFunction(String s, AggregateFunction<T, A> aggregateFunction) {
getStreamTableEnvironment().registerFunction(s, aggregateFunction);
}
@Override
default <T, A> void registerFunction(String s, TableAggregateFunction<T, A> tableAggregateFunction) {
getStreamTableEnvironment().registerFunction(s, tableAggregateFunction);
}
@Override
default <T> Table fromDataStream(DataStream<T> dataStream) {
return getStreamTableEnvironment().fromDataStream(dataStream);
}
@Override
default <T> Table fromDataStream(DataStream<T> dataStream, Schema schema) {
return getStreamTableEnvironment().fromDataStream(dataStream, schema);
}
@Override
default Table fromChangelogStream(DataStream<Row> dataStream) {
return getStreamTableEnvironment().fromChangelogStream(dataStream);
}
@Override
default Table fromChangelogStream(DataStream<Row> dataStream, Schema schema) {
return getStreamTableEnvironment().fromChangelogStream(dataStream, schema);
}
@Override
default Table fromChangelogStream(DataStream<Row> dataStream, Schema schema, ChangelogMode changelogMode) {
return getStreamTableEnvironment().fromChangelogStream(dataStream, schema, changelogMode);
}
@Override
default <T> void createTemporaryView(String s, DataStream<T> dataStream) {
getStreamTableEnvironment().createTemporaryView(s, dataStream);
}
@Override
default <T> void createTemporaryView(String s, DataStream<T> dataStream, Schema schema) {
getStreamTableEnvironment().createTemporaryView(s, dataStream, schema);
}
@Override
default DataStream<Row> toDataStream(Table table) {
return getStreamTableEnvironment().toDataStream(table);
}
@Override
default <T> DataStream<T> toDataStream(Table table, Class<T> aClass) {
return getStreamTableEnvironment().toDataStream(table, aClass);
}
@Override
default <T> DataStream<T> toDataStream(Table table, AbstractDataType<?> abstractDataType) {
return getStreamTableEnvironment().toDataStream(table, abstractDataType);
}
@Override
default DataStream<Row> toChangelogStream(Table table) {
return getStreamTableEnvironment().toChangelogStream(table);
}
@Override
default DataStream<Row> toChangelogStream(Table table, Schema schema) {
return getStreamTableEnvironment().toChangelogStream(table, schema);
}
@Override
default DataStream<Row> toChangelogStream(Table table, Schema schema, ChangelogMode changelogMode) {
return getStreamTableEnvironment().toChangelogStream(table, schema, changelogMode);
}
@Override
default StreamStatementSet createStatementSet() {
return getStreamTableEnvironment().createStatementSet();
}
@Override
default <T> Table fromDataStream(DataStream<T> dataStream, Expression... expressions) {
return getStreamTableEnvironment().fromDataStream(dataStream, expressions);
}
@Override
default <T> void registerDataStream(String s, DataStream<T> dataStream) {
getStreamTableEnvironment().registerDataStream(s, dataStream);
}
@Override
default <T> void createTemporaryView(String s, DataStream<T> dataStream, Expression... expressions) {
getStreamTableEnvironment().createTemporaryView(s, dataStream, expressions);
}
@Override
default <T> DataStream<T> toAppendStream(Table table, Class<T> aClass) {
return getStreamTableEnvironment().toAppendStream(table, aClass);
}
@Override
default <T> DataStream<T> toAppendStream(Table table, TypeInformation<T> typeInformation) {
return getStreamTableEnvironment().toAppendStream(table, typeInformation);
}
@Override
default <T> DataStream<Tuple2<Boolean, T>> toRetractStream(Table table, Class<T> aClass) {
return getStreamTableEnvironment().toRetractStream(table, aClass);
}
@Override
default <T> DataStream<Tuple2<Boolean, T>> toRetractStream(Table table, TypeInformation<T> typeInformation) {
return getStreamTableEnvironment().toRetractStream(table, typeInformation);
}
// endregion
}
/*
*
* 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.executor;
import org.apache.flink.table.api.CompiledPlan;
import org.apache.flink.table.api.ExplainDetail;
import org.apache.flink.table.api.ExplainFormat;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.internal.TableEnvironmentInternal;
import org.apache.flink.table.api.internal.TableResultInternal;
import org.apache.flink.table.catalog.CatalogManager;
import org.apache.flink.table.delegation.InternalPlan;
import org.apache.flink.table.delegation.Parser;
import org.apache.flink.table.operations.ModifyOperation;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.operations.utils.OperationTreeBuilder;
import org.apache.flink.table.sinks.TableSink;
import org.apache.flink.table.sources.TableSource;
import java.util.List;
/** */
public interface DefaultTableEnvironmentInternal extends TableEnvironmentInternal, TableEnvironmentInstance {
default TableEnvironmentInternal getTableEnvironmentInternal() {
return (TableEnvironmentInternal) getTableEnvironment();
}
// region TableEnvironmentInternal interface
@Override
default Parser getParser() {
return getTableEnvironmentInternal().getParser();
}
@Override
default CatalogManager getCatalogManager() {
return getTableEnvironmentInternal().getCatalogManager();
}
@Override
default OperationTreeBuilder getOperationTreeBuilder() {
return getTableEnvironmentInternal().getOperationTreeBuilder();
}
@Override
default Table fromTableSource(TableSource<?> tableSource) {
return getTableEnvironmentInternal().fromTableSource(tableSource);
}
@Override
default TableResultInternal executeInternal(List<ModifyOperation> list) {
return getTableEnvironmentInternal().executeInternal(list);
}
@Override
default TableResultInternal executeInternal(Operation operation) {
return getTableEnvironmentInternal().executeInternal(operation);
}
@Override
default String explainInternal(List<Operation> list, ExplainDetail... explainDetails) {
return getTableEnvironmentInternal().explainInternal(list, explainDetails);
}
@Override
default void registerTableSourceInternal(String s, TableSource<?> tableSource) {
getTableEnvironmentInternal().registerTableSourceInternal(s, tableSource);
}
@Override
default void registerTableSinkInternal(String s, TableSink<?> tableSink) {
getTableEnvironmentInternal().registerTableSinkInternal(s, tableSink);
}
@Override
default CompiledPlan compilePlan(List<ModifyOperation> list) {
return getTableEnvironmentInternal().compilePlan(list);
}
@Override
default TableResultInternal executePlan(InternalPlan internalPlan) {
return getTableEnvironmentInternal().executePlan(internalPlan);
}
@Override
default String explainPlan(InternalPlan internalPlan, ExplainDetail... explainDetails) {
return getTableEnvironmentInternal().explainPlan(internalPlan, explainDetails);
}
@Override
default String explainInternal(List<Operation> operations, ExplainFormat format, ExplainDetail... extraDetails) {
return getTableEnvironmentInternal().explainInternal(operations, format, extraDetails);
}
// endregion
}
/*
*
* 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.executor;
import org.apache.flink.table.delegation.Parser;
/** */
public interface ExtendedParser extends Parser {
CustomParser getCustomParser();
}
/*
*
* 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.executor;
import org.apache.flink.table.catalog.UnresolvedIdentifier;
import org.apache.flink.table.expressions.ResolvedExpression;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.RowType;
import java.util.List;
import javax.annotation.Nullable;
public class ParserWrapper implements ExtendedParser {
private CustomParser customParser;
public ParserWrapper(CustomParser customParser) {
this.customParser = customParser;
}
@Override
public List<Operation> parse(String statement) {
List<Operation> result = customParser.parse(statement);
if (result != null) {
return result;
}
return customParser.getParser().parse(statement);
}
@Override
public UnresolvedIdentifier parseIdentifier(String identifier) {
return customParser.getParser().parseIdentifier(identifier);
}
@Override
public ResolvedExpression parseSqlExpression(
String sqlExpression, RowType inputRowType, @Nullable LogicalType outputType) {
return customParser.getParser().parseSqlExpression(sqlExpression, inputRowType, outputType);
}
@Override
public String[] getCompletionHints(String statement, int position) {
return customParser.getParser().getCompletionHints(statement, position);
}
@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.executor;
import org.apache.flink.annotation.Internal;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.core.execution.JobClient;
import org.apache.flink.table.api.TableException;
import org.apache.flink.table.api.internal.ResultProvider;
import org.apache.flink.table.data.GenericRowData;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.data.StringData;
import org.apache.flink.table.utils.print.PrintStyle;
import org.apache.flink.table.utils.print.RowDataToStringConverter;
import org.apache.flink.types.Row;
import org.apache.flink.util.CloseableIterator;
import java.util.List;
import java.util.function.Function;
/** Create result provider from a static set of data using external types. */
@Internal
public class StaticResultProvider implements ResultProvider {
/**
* This converter supports only String, long, int and boolean fields. Moreover, this converter
* works only with {@link GenericRowData}.
*/
public static final RowDataToStringConverter SIMPLE_ROW_DATA_TO_STRING_CONVERTER = rowData -> {
GenericRowData genericRowData = (GenericRowData) rowData;
String[] results = new String[rowData.getArity()];
for (int i = 0; i < results.length; i++) {
Object value = genericRowData.getField(i);
if (Boolean.TRUE.equals(value)) {
results[i] = "TRUE";
} else if (Boolean.FALSE.equals(value)) {
results[i] = "FALSE";
} else {
results[i] = value == null ? PrintStyle.NULL_VALUE : "" + value;
}
}
return results;
};
private final List<Row> rows;
private final Function<Row, RowData> externalToInternalConverter;
public StaticResultProvider(List<Row> rows) {
this(rows, StaticResultProvider::rowToInternalRow);
}
public StaticResultProvider(List<Row> rows, Function<Row, RowData> externalToInternalConverter) {
this.rows = rows;
this.externalToInternalConverter = externalToInternalConverter;
}
@Override
public StaticResultProvider setJobClient(JobClient jobClient) {
return this;
}
@Override
public CloseableIterator<RowData> toInternalIterator() {
return CloseableIterator.adapterForIterator(
this.rows.stream().map(this.externalToInternalConverter).iterator());
}
@Override
public CloseableIterator<Row> toExternalIterator() {
return CloseableIterator.adapterForIterator(this.rows.iterator());
}
@Override
public RowDataToStringConverter getRowDataStringConverter() {
return SIMPLE_ROW_DATA_TO_STRING_CONVERTER;
}
@Override
public boolean isFirstRowReady() {
return true;
}
/** This function supports only String, long, int and boolean fields. */
@VisibleForTesting
static RowData rowToInternalRow(Row row) {
Object[] values = new Object[row.getArity()];
for (int i = 0; i < row.getArity(); i++) {
Object value = row.getField(i);
if (value == null) {
values[i] = null;
} else if (value instanceof String) {
values[i] = StringData.fromString((String) value);
} else if (value instanceof Boolean || value instanceof Long || value instanceof Integer) {
values[i] = value;
} else {
throw new TableException("Cannot convert row type");
}
}
return GenericRowData.of(values);
}
}
/*
*
* 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.executor;
import org.apache.flink.table.types.DataType;
/** @since 2022/11/04 */
public class TableSchemaField {
private String name;
private DataType type;
public TableSchemaField(String name, DataType type) {
this.name = name;
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public DataType getType() {
return type;
}
public void setType(DataType type) {
this.type = type;
}
}
/*
*
* 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.operations;
import org.dinky.parser.CustomParserImpl;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.table.delegation.Parser;
import org.apache.flink.table.planner.parse.ExtendedParser;
public class CustomNewParserImpl extends CustomParserImpl {
private final DinkyParser dinkyParser;
public CustomNewParserImpl(TableEnvironment tableEnvironment, Parser parser) {
super(parser);
this.dinkyParser = new DinkyParser(tableEnvironment);
}
@Override
public ExtendedParser getDinkyParser() {
return this.dinkyParser;
}
}
/*
*
* 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.operations;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.table.api.internal.TableResultInternal;
import org.apache.flink.table.operations.ExecutableOperation;
import org.apache.flink.table.operations.Operation;
public class DinkyExecutableOperation implements ExecutableOperation {
private final Operation innerOperation;
private final TableEnvironment tableEnvironment;
public DinkyExecutableOperation(TableEnvironment tableEnvironment, Operation innerOperation) {
this.tableEnvironment = tableEnvironment;
this.innerOperation = innerOperation;
}
@Override
public TableResultInternal execute(Context ctx) {
DinkyOperationExecutor operationExecutor = new DinkyOperationExecutor(tableEnvironment, ctx);
return operationExecutor.executeOperation(innerOperation).get();
}
public Operation getInnerOperation() {
return innerOperation;
}
@Override
public String asSummaryString() {
return innerOperation.asSummaryString();
}
}
/*
*
* 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.operations;
import org.dinky.executor.CustomTableEnvironment;
import org.dinky.trans.ExtendOperation;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.table.api.internal.TableResultInternal;
import org.apache.flink.table.operations.ExecutableOperation;
import org.apache.flink.table.operations.Operation;
import java.util.Optional;
public class DinkyOperationExecutor {
private final ExecutableOperation.Context context;
private final TableEnvironment tableEnvironment;
public DinkyOperationExecutor(TableEnvironment tableEnvironment, ExecutableOperation.Context context) {
this.tableEnvironment = tableEnvironment;
this.context = context;
}
public Optional<TableResultInternal> executeOperation(Operation operation) {
ExtendOperation extendOperation = (ExtendOperation) operation;
return Optional.of((TableResultInternal) extendOperation
.execute((CustomTableEnvironment) tableEnvironment)
.get());
}
}
/*
*
* 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.operations;
import org.dinky.parser.DinkyExtendedParser;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.planner.parse.ExtendedParseStrategy;
import java.util.Optional;
public class DinkyParser extends DinkyExtendedParser {
private final TableEnvironment tableEnvironment;
public DinkyParser(TableEnvironment tableEnvironment) {
this.tableEnvironment = tableEnvironment;
}
@Override
public Optional<Operation> parse(String statement) {
for (ExtendedParseStrategy strategy : PARSE_STRATEGIES) {
if (strategy.match(statement)) {
return Optional.of(new DinkyExecutableOperation(this.tableEnvironment, strategy.convert(statement)));
}
}
return Optional.empty();
}
}
/*
*
* 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.api.common.JobID;
import org.apache.flink.client.program.ClusterClient;
import org.apache.flink.core.execution.SavepointFormatType;
import org.apache.flink.table.api.TableResult;
import org.apache.flink.table.catalog.CatalogManager;
import org.apache.flink.table.catalog.ContextResolvedTable;
import org.apache.flink.table.catalog.ObjectIdentifier;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
/**
* FlinkUtil
*
* @since 2022/05/08
*/
public class FlinkUtil {
public static List<String> getFieldNamesFromCatalogManager(
CatalogManager catalogManager, String catalog, String database, String table) {
Optional<ContextResolvedTable> tableOpt =
catalogManager.getTable(ObjectIdentifier.of(catalog, database, table));
if (tableOpt.isPresent()) {
return tableOpt.get().getResolvedSchema().getColumnNames();
} else {
return new ArrayList<String>();
}
}
public static List<String> catchColumn(TableResult tableResult) {
return tableResult.getResolvedSchema().getColumnNames();
}
public static String triggerSavepoint(ClusterClient clusterClient, String jobId, String savePoint)
throws ExecutionException, InterruptedException {
return clusterClient
.triggerSavepoint(JobID.fromHexString(jobId), savePoint, SavepointFormatType.DEFAULT)
.get()
.toString();
}
public static String stopWithSavepoint(ClusterClient clusterClient, String jobId, String savePoint)
throws ExecutionException, InterruptedException {
return clusterClient
.stopWithSavepoint(JobID.fromHexString(jobId), true, savePoint, SavepointFormatType.DEFAULT)
.get()
.toString();
}
public static String cancelWithSavepoint(ClusterClient clusterClient, String jobId, String savePoint)
throws ExecutionException, InterruptedException {
return clusterClient
.cancelWithSavepoint(JobID.fromHexString(jobId), savePoint, SavepointFormatType.DEFAULT)
.get()
.toString();
}
}
/*
*
* 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;
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;
}
}
/*
*
* 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.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.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
*
* @since 2022/11/22
*/
public class LineageContext {
private static final Logger LOG = LoggerFactory.getLogger(LineageContext.class);
private final CustomTableEnvironment tableEnv;
public LineageContext(CustomTableEnvironment tableEnv) {
this.tableEnv = tableEnv;
}
public List<LineageRel> analyzeLineage(String statement) {
// 1. Generate original relNode tree
Tuple2<String, RelNode> parsed = parseStatement(statement);
String sinkTable = parsed.getField(0);
RelNode oriRelNode = parsed.getField(1);
// 2. Build lineage based from RelMetadataQuery
return buildFiledLineageResult(sinkTable, oriRelNode);
}
private Tuple2<String, RelNode> parseStatement(String sql) {
List<Operation> operations = tableEnv.getParser().parse(sql);
if (operations.size() != 1) {
throw new TableException("Unsupported SQL query! only accepts a single SQL statement.");
}
Operation operation = operations.get(0);
if (operation instanceof SinkModifyOperation) {
SinkModifyOperation sinkOperation = (SinkModifyOperation) operation;
PlannerQueryOperation queryOperation = (PlannerQueryOperation) sinkOperation.getChild();
RelNode relNode = queryOperation.getCalciteTree();
return new Tuple2<>(
sinkOperation.getContextResolvedTable().getIdentifier().asSummaryString(), relNode);
} else {
throw new TableException("Only insert is supported now.");
}
}
/** Check the size of query and sink fields match */
private void validateSchema(String sinkTable, RelNode relNode, List<String> sinkFieldList) {
List<String> queryFieldList = relNode.getRowType().getFieldNames();
if (queryFieldList.size() != sinkFieldList.size()) {
throw new ValidationException(String.format(
"Column types of query result and sink for %s do not match.\n"
+ "Query schema: %s\n"
+ "Sink schema: %s",
sinkTable, queryFieldList, sinkFieldList));
}
}
private List<LineageRel> buildFiledLineageResult(String sinkTable, RelNode optRelNode) {
// target columns
List<String> targetColumnList =
tableEnv.from(sinkTable).getResolvedSchema().getColumnNames();
// check the size of query and sink fields match
validateSchema(sinkTable, optRelNode, targetColumnList);
RelMetadataQuery metadataQuery = optRelNode.getCluster().getMetadataQuery();
List<LineageRel> resultList = new ArrayList<>();
for (int index = 0; index < targetColumnList.size(); index++) {
String targetColumn = targetColumnList.get(index);
Set<RelColumnOrigin> relColumnOriginSet = metadataQuery.getColumnOrigins(optRelNode, index);
if (CollectionUtils.isNotEmpty(relColumnOriginSet)) {
for (RelColumnOrigin relColumnOrigin : relColumnOriginSet) {
// table
RelOptTable table = relColumnOrigin.getOriginTable();
String sourceTable = String.join(".", table.getQualifiedName());
// filed
int ordinal = relColumnOrigin.getOriginColumnOrdinal();
List<String> fieldNames = ((TableSourceTable) table)
.contextResolvedTable()
.getResolvedSchema()
.getColumnNames();
String sourceColumn = fieldNames.get(ordinal);
// add record
resultList.add(LineageRel.build(
sourceTable, sourceColumn, sinkTable, targetColumn, relColumnOrigin.getTransform()));
}
}
}
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();
}
}
/*
*
* 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.types.logical.BigIntType;
import org.apache.flink.table.types.logical.DateType;
import org.apache.flink.table.types.logical.DecimalType;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.TimestampType;
import org.apache.flink.table.types.logical.VarBinaryType;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.ZoneId;
import javax.xml.bind.DatatypeConverter;
/** @className: org.dinky.utils.ObjectConvertUtil @Description: */
public class ObjectConvertUtil {
public static Object convertValue(Object value, LogicalType logicalType) {
return ObjectConvertUtil.convertValue(value, logicalType, null);
}
public static Object convertValue(Object value, LogicalType logicalType, ZoneId sinkTimeZone) {
if (value == null) {
return null;
}
if (sinkTimeZone == null) {
sinkTimeZone = ZoneId.of("UTC");
}
if (logicalType instanceof DateType) {
if (value instanceof Integer) {
return Instant.ofEpochMilli(((Integer) value).longValue())
.atZone(sinkTimeZone)
.toLocalDate();
} else {
return Instant.ofEpochMilli((long) value)
.atZone(ZoneId.systemDefault())
.toLocalDate();
}
} else if (logicalType instanceof TimestampType) {
if (value instanceof Integer) {
return Instant.ofEpochMilli(((Integer) value).longValue())
.atZone(sinkTimeZone)
.toLocalDateTime();
} else if (value instanceof String) {
return Instant.parse((String) value)
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
} else {
return Instant.ofEpochMilli((long) value).atZone(sinkTimeZone).toLocalDateTime();
}
} else if (logicalType instanceof DecimalType) {
return new BigDecimal(String.valueOf(value));
} else if (logicalType instanceof BigIntType) {
if (value instanceof Integer) {
return ((Integer) value).longValue();
} else {
return value;
}
} else if (logicalType instanceof VarBinaryType) {
// VARBINARY AND BINARY is converted to String with encoding base64 in FlinkCDC.
if (value instanceof String) {
return DatatypeConverter.parseBase64Binary((String) value);
} else {
return value;
}
} else {
return value;
}
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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