Unverified Commit 4cb57f87 authored by ZackYoung's avatar ZackYoung Committed by GitHub

[Fix][Flink dedependency]Flink version compatible (#1249)

* 1. fix flink11 compatible 2. spotless exec * 3. fix flink11 compatible 4. flink 12 fix checkstyle 5. flink 12 spotless exec * 6. fix flink16 compatible * fix cdc bug * fix 11 cdcsource add 11 CdcSourceTests * fix 12 cdcsource * fix 13 cdcsource update 13 mysqlcdc 2.2.1->2.3.0 * fix 14 cdcsource update 14 mysqlcdc 2.2.1->2.3.0 * fix 15-16 cdcsource update 15-16 mysqlcdc 2.2.1->2.3.0 * add protocol header
parent e740150e
......@@ -19,15 +19,15 @@
package com.dlink.app;
import java.io.IOException;
import java.util.Map;
import com.dlink.app.db.DBConfig;
import com.dlink.app.flinksql.Submiter;
import com.dlink.assertion.Asserts;
import com.dlink.constant.FlinkParamConstant;
import com.dlink.utils.FlinkBaseUtil;
import java.io.IOException;
import java.util.Map;
/**
* MainApp
*
......
......@@ -22,6 +22,8 @@ package com.dlink.flink.catalog;
import static org.apache.flink.util.Preconditions.checkArgument;
import static org.apache.flink.util.Preconditions.checkNotNull;
import com.dlink.flink.catalog.factory.DlinkMysqlCatalogFactoryOptions;
import org.apache.flink.table.api.Schema;
import org.apache.flink.table.catalog.AbstractCatalog;
import org.apache.flink.table.catalog.CatalogBaseTable;
......@@ -71,8 +73,6 @@ import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.dlink.flink.catalog.factory.DlinkMysqlCatalogFactoryOptions;
/**
* 自定义 catalog
* 检查connection done.
......@@ -105,6 +105,7 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
* 对象类型,例如 库、表、视图等
*/
protected static class ObjectType {
/**
* 数据库
*/
......@@ -125,6 +126,7 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
* 对象类型,例如 库、表、视图等
*/
protected static class ColumnType {
/**
* 物理字段
*/
......@@ -215,8 +217,7 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
Integer defaultDbId = getDatabaseId(defaultDatabase);
if (defaultDbId == null) {
try {
createDatabase(defaultDatabase, new CatalogDatabaseImpl(new HashMap<>(), "")
, true);
createDatabase(defaultDatabase, new CatalogDatabaseImpl(new HashMap<>(), ""), true);
} catch (DatabaseAlreadyExistException a) {
logger.info("重复创建默认库");
}
......@@ -280,15 +281,14 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
return myDatabases;
} catch (Exception e) {
throw new CatalogException(
String.format("Failed listing database in catalog %s", getName()), e);
String.format("Failed listing database in catalog %s", getName()), e);
}
}
@Override
public CatalogDatabase getDatabase(String databaseName)
throws DatabaseNotExistException, CatalogException {
public CatalogDatabase getDatabase(String databaseName) throws DatabaseNotExistException, CatalogException {
String querySql = "SELECT id, database_name,description "
+ " FROM metadata_database where database_name=?";
+ " FROM metadata_database where database_name=?";
Connection conn = getConnection();
try (PreparedStatement ps = conn.prepareStatement(querySql)) {
ps.setString(1, databaseName);
......@@ -301,8 +301,8 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
Map<String, String> map = new HashMap<>();
String sql = "select `key`,`value` "
+ "from metadata_database_property "
+ "where database_id=? ";
+ "from metadata_database_property "
+ "where database_id=? ";
try (PreparedStatement pStat = conn.prepareStatement(sql)) {
pStat.setInt(1, id);
ResultSet prs = pStat.executeQuery();
......@@ -312,7 +312,7 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
} catch (SQLException e) {
sqlExceptionHappened = true;
throw new CatalogException(
String.format("Failed get database properties in catalog %s", getName()), e);
String.format("Failed get database properties in catalog %s", getName()), e);
}
return new CatalogDatabaseImpl(map, description);
......@@ -322,7 +322,7 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
} catch (SQLException e) {
sqlExceptionHappened = true;
throw new CatalogException(
String.format("Failed get database in catalog %s", getName()), e);
String.format("Failed get database in catalog %s", getName()), e);
}
}
......@@ -355,8 +355,8 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
}
@Override
public void createDatabase(String databaseName, CatalogDatabase db, boolean ignoreIfExists)
throws DatabaseAlreadyExistException, CatalogException {
public void createDatabase(String databaseName, CatalogDatabase db,
boolean ignoreIfExists) throws DatabaseAlreadyExistException, CatalogException {
checkArgument(!StringUtils.isNullOrWhitespaceOnly(databaseName));
checkNotNull(db);
......@@ -379,7 +379,7 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
if (idRs.next() && db.getProperties() != null && db.getProperties().size() > 0) {
int id = idRs.getInt(1);
String propInsertSql = "insert into metadata_database_property(database_id, "
+ "`key`,`value`) values (?,?,?)";
+ "`key`,`value`) values (?,?,?)";
PreparedStatement pstat = conn.prepareStatement(propInsertSql);
for (Map.Entry<String, String> entry : db.getProperties().entrySet()) {
pstat.setInt(1, id);
......@@ -399,8 +399,8 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
}
@Override
public void dropDatabase(String name, boolean ignoreIfNotExists, boolean cascade)
throws DatabaseNotExistException, DatabaseNotEmptyException, CatalogException {
public void dropDatabase(String name, boolean ignoreIfNotExists,
boolean cascade) throws DatabaseNotExistException, DatabaseNotEmptyException, CatalogException {
if (name.equals(defaultDatabase)) {
throw new CatalogException("默认 database 不可以删除");
}
......@@ -450,8 +450,8 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
}
@Override
public void alterDatabase(String name, CatalogDatabase newDb, boolean ignoreIfNotExists)
throws DatabaseNotExistException, CatalogException {
public void alterDatabase(String name, CatalogDatabase newDb,
boolean ignoreIfNotExists) throws DatabaseNotExistException, CatalogException {
if (name.equals(defaultDatabase)) {
throw new CatalogException("默认 database 不可以修改");
}
......@@ -475,8 +475,8 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
uState.close();
if (newDb.getProperties() != null && newDb.getProperties().size() > 0) {
String upsertSql = "insert into metadata_database_property (database_id, `key`,`value`) \n"
+ "values (?,?,?)\n"
+ "on duplicate key update `value` =?, update_time = sysdate()\n";
+ "values (?,?,?)\n"
+ "on duplicate key update `value` =?, update_time = sysdate()\n";
PreparedStatement pstat = conn.prepareStatement(upsertSql);
for (Map.Entry<String, String> entry : newDb.getProperties().entrySet()) {
pstat.setInt(1, id);
......@@ -496,19 +496,17 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
}
@Override
public List<String> listTables(String databaseName)
throws DatabaseNotExistException, CatalogException {
public List<String> listTables(String databaseName) throws DatabaseNotExistException, CatalogException {
return listTablesViews(databaseName, ObjectType.TABLE);
}
@Override
public List<String> listViews(String databaseName)
throws DatabaseNotExistException, CatalogException {
public List<String> listViews(String databaseName) throws DatabaseNotExistException, CatalogException {
return listTablesViews(databaseName, ObjectType.VIEW);
}
protected List<String> listTablesViews(String databaseName, String tableType)
throws DatabaseNotExistException, CatalogException {
protected List<String> listTablesViews(String databaseName,
String tableType) throws DatabaseNotExistException, CatalogException {
Integer databaseId = getDatabaseId(databaseName);
if (null == databaseId) {
throw new DatabaseNotExistException(getName(), databaseName);
......@@ -532,7 +530,7 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
return tables;
} catch (Exception e) {
throw new CatalogException(
String.format("Failed listing %s in catalog %s", tableType, getName()), e);
String.format("Failed listing %s in catalog %s", tableType, getName()), e);
}
}
......@@ -551,9 +549,9 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
Connection conn = getConnection();
try {
String queryTable = "SELECT table_name "
+ " ,description, table_type "
+ " FROM metadata_table "
+ " where id=?";
+ " ,description, table_type "
+ " FROM metadata_table "
+ " where id=?";
PreparedStatement ps = conn.prepareStatement(queryTable);
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
......@@ -570,7 +568,7 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
if (tableType.equals(ObjectType.TABLE)) {
// 这个是 table
String propSql = "SELECT `key`, `value` from metadata_table_property "
+ "WHERE table_id=?";
+ "WHERE table_id=?";
PreparedStatement pState = conn.prepareStatement(propSql);
pState.setInt(1, id);
ResultSet prs = pState.executeQuery();
......@@ -587,8 +585,8 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
// 1、从库中取出table信息。(前面已做)
// 2、取出字段。
String colSql = "SELECT column_name, column_type, data_type, description "
+ " FROM metadata_column WHERE "
+ " table_id=?";
+ " FROM metadata_column WHERE "
+ " table_id=?";
PreparedStatement cStat = conn.prepareStatement(colSql);
cStat.setInt(1, id);
ResultSet crs = cStat.executeQuery();
......@@ -607,7 +605,7 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
cStat.close();
// 3、取出query
String qSql = "SELECT `key`, value FROM metadata_table_property"
+ " WHERE table_id=? ";
+ " WHERE table_id=? ";
PreparedStatement qStat = conn.prepareStatement(qSql);
qStat.setInt(1, id);
ResultSet qrs = qStat.executeQuery();
......@@ -626,8 +624,7 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
}
}
// 合成view
return CatalogView.of(builder.build(), description
, originalQuery, expandedQuery, options);
return CatalogView.of(builder.build(), description, originalQuery, expandedQuery, options);
} else {
throw new CatalogException("不支持的数据类型。" + tableType);
}
......@@ -651,7 +648,7 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
}
// 获取id
String getIdSql = "select id from metadata_table "
+ " where table_name=? and database_id=?";
+ " where table_name=? and database_id=?";
Connection conn = getConnection();
try (PreparedStatement gStat = conn.prepareStatement(getIdSql)) {
gStat.setString(1, tablePath.getObjectName());
......@@ -669,8 +666,8 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
}
@Override
public void dropTable(ObjectPath tablePath, boolean ignoreIfNotExists)
throws TableNotExistException, CatalogException {
public void dropTable(ObjectPath tablePath,
boolean ignoreIfNotExists) throws TableNotExistException, CatalogException {
Integer id = getTableId(tablePath);
if (id == null) {
......@@ -681,19 +678,19 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
// todo: 现在是真实删除,后续设计是否做记录保留。
conn.setAutoCommit(false);
String deletePropSql = "delete from metadata_table_property "
+ " where table_id=?";
+ " where table_id=?";
PreparedStatement dStat = conn.prepareStatement(deletePropSql);
dStat.setInt(1, id);
dStat.executeUpdate();
dStat.close();
String deleteColSql = "delete from metadata_column "
+ " where table_id=?";
+ " where table_id=?";
dStat = conn.prepareStatement(deleteColSql);
dStat.setInt(1, id);
dStat.executeUpdate();
dStat.close();
String deleteDbSql = "delete from metadata_table "
+ " where id=?";
+ " where id=?";
dStat = conn.prepareStatement(deleteDbSql);
dStat.setInt(1, id);
dStat.executeUpdate();
......@@ -707,8 +704,8 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
}
@Override
public void renameTable(ObjectPath tablePath, String newTableName, boolean ignoreIfNotExists)
throws TableNotExistException, TableAlreadyExistException, CatalogException {
public void renameTable(ObjectPath tablePath, String newTableName,
boolean ignoreIfNotExists) throws TableNotExistException, TableAlreadyExistException, CatalogException {
Integer id = getTableId(tablePath);
if (id == null) {
......@@ -731,8 +728,8 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
}
@Override
public void createTable(ObjectPath tablePath, CatalogBaseTable table, boolean ignoreIfExists)
throws TableAlreadyExistException, DatabaseNotExistException, CatalogException {
public void createTable(ObjectPath tablePath, CatalogBaseTable table,
boolean ignoreIfExists) throws TableAlreadyExistException, DatabaseNotExistException, CatalogException {
Integer dbId = getDatabaseId(tablePath.getDatabaseName());
if (null == dbId) {
throw new DatabaseNotExistException(getName(), tablePath.getDatabaseName());
......@@ -757,11 +754,11 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
CatalogBaseTable.TableKind kind = table.getTableKind();
String insertSql = "insert into metadata_table(\n"
+ " table_name,"
+ " table_type,"
+ " database_id,"
+ " description)"
+ " values(?,?,?,?)";
+ " table_name,"
+ " table_type,"
+ " database_id,"
+ " description)"
+ " values(?,?,?,?)";
PreparedStatement iStat = conn.prepareStatement(insertSql, Statement.RETURN_GENERATED_KEYS);
iStat.setString(1, tablePath.getObjectName());
iStat.setString(2, kind.toString());
......@@ -780,7 +777,7 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
// table 就可以直接拿properties了。
Map<String, String> props = ((ResolvedCatalogTable) table).toProperties();
String propInsertSql = "insert into metadata_table_property(table_id,"
+ "`key`,`value`) values (?,?,?)";
+ "`key`,`value`) values (?,?,?)";
PreparedStatement pStat = conn.prepareStatement(propInsertSql);
for (Map.Entry<String, String> entry : props.entrySet()) {
pStat.setInt(1, id);
......@@ -798,31 +795,28 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
List<Schema.UnresolvedColumn> cols = view.getUnresolvedSchema().getColumns();
if (cols.size() > 0) {
String colInsertSql = "insert into metadata_column("
+ " column_name, column_type, data_type"
+ " , `expr`"
+ " , description"
+ " , table_id"
+ " , `primary`) "
+ " values(?,?,?,?,?,?,?)";
+ " column_name, column_type, data_type"
+ " , `expr`"
+ " , description"
+ " , table_id"
+ " , `primary`) "
+ " values(?,?,?,?,?,?,?)";
PreparedStatement colIStat = conn.prepareStatement(colInsertSql);
for (Schema.UnresolvedColumn col : cols) {
if (col instanceof Schema.UnresolvedPhysicalColumn) {
Schema.UnresolvedPhysicalColumn pCol = (Schema.UnresolvedPhysicalColumn) col;
if (!(pCol.getDataType() instanceof DataType)) {
throw new UnsupportedOperationException(String.format(
"类型识别失败,该列不是有效类型:%s.%s.%s : %s"
, tablePath.getDatabaseName()
, tablePath.getObjectName()
, pCol.getName(),
pCol.getDataType()
));
"类型识别失败,该列不是有效类型:%s.%s.%s : %s", tablePath.getDatabaseName(),
tablePath.getObjectName(), pCol.getName(),
pCol.getDataType()));
}
DataType dataType = (DataType) pCol.getDataType();
colIStat.setString(1, pCol.getName());
colIStat.setString(2, ColumnType.PHYSICAL);
colIStat.setString(3,
dataType.getLogicalType().asSerializableString());
dataType.getLogicalType().asSerializableString());
colIStat.setObject(4, null);
colIStat.setString(5, pCol.getComment().orElse(""));
colIStat.setInt(6, id);
......@@ -843,7 +837,7 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
option.put("OriginalQuery", view.getOriginalQuery());
option.put("ExpandedQuery", view.getExpandedQuery());
String propInsertSql = "insert into metadata_table_property(table_id,"
+ "`key`,`value`) values (?,?,?)";
+ "`key`,`value`) values (?,?,?)";
PreparedStatement pStat = conn.prepareStatement(propInsertSql);
for (Map.Entry<String, String> entry : option.entrySet()) {
pStat.setInt(1, id);
......@@ -864,8 +858,8 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
}
@Override
public void alterTable(ObjectPath tablePath, CatalogBaseTable newTable, boolean ignoreIfNotExists)
throws TableNotExistException, CatalogException {
public void alterTable(ObjectPath tablePath, CatalogBaseTable newTable,
boolean ignoreIfNotExists) throws TableNotExistException, CatalogException {
Integer id = getTableId(tablePath);
if (id == null) {
......@@ -875,8 +869,8 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
Map<String, String> opts = newTable.getOptions();
if (opts != null && opts.size() > 0) {
String updateSql = "INSERT INTO metadata_table_property(table_id,"
+ "`key`,`value`) values (?,?,?) "
+ "on duplicate key update `value` =?, update_time = sysdate()";
+ "`key`,`value`) values (?,?,?) "
+ "on duplicate key update `value` =?, update_time = sysdate()";
Connection conn = getConnection();
try (PreparedStatement ps = conn.prepareStatement(updateSql)) {
for (Map.Entry<String, String> entry : opts.entrySet()) {
......@@ -896,55 +890,55 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
/************************ partition *************************/
@Override
public List<CatalogPartitionSpec> listPartitions(ObjectPath tablePath)
throws TableNotExistException, TableNotPartitionedException, CatalogException {
public List<CatalogPartitionSpec> listPartitions(ObjectPath tablePath) throws TableNotExistException, TableNotPartitionedException, CatalogException {
// todo: 补充完成该方法。
throw new UnsupportedOperationException("该方法尚未完成");
}
@Override
public List<CatalogPartitionSpec> listPartitions(ObjectPath tablePath, CatalogPartitionSpec partitionSpec)
throws TableNotExistException, TableNotPartitionedException, PartitionSpecInvalidException, CatalogException {
public List<CatalogPartitionSpec> listPartitions(ObjectPath tablePath,
CatalogPartitionSpec partitionSpec) throws TableNotExistException, TableNotPartitionedException, PartitionSpecInvalidException, CatalogException {
// todo: 补充完成该方法。
throw new UnsupportedOperationException("该方法尚未完成");
}
@Override
public List<CatalogPartitionSpec> listPartitionsByFilter(ObjectPath tablePath, List<Expression> filters)
throws TableNotExistException, TableNotPartitionedException, CatalogException {
public List<CatalogPartitionSpec> listPartitionsByFilter(ObjectPath tablePath,
List<Expression> filters) throws TableNotExistException, TableNotPartitionedException, CatalogException {
// todo: 补充完成该方法。
throw new UnsupportedOperationException("该方法尚未完成");
}
@Override
public CatalogPartition getPartition(ObjectPath tablePath, CatalogPartitionSpec partitionSpec)
throws PartitionNotExistException, CatalogException {
public CatalogPartition getPartition(ObjectPath tablePath,
CatalogPartitionSpec partitionSpec) throws PartitionNotExistException, CatalogException {
// todo: 补充完成该方法。
throw new UnsupportedOperationException("该方法尚未完成");
}
@Override
public boolean partitionExists(ObjectPath tablePath, CatalogPartitionSpec partitionSpec)
throws CatalogException {
public boolean partitionExists(ObjectPath tablePath, CatalogPartitionSpec partitionSpec) throws CatalogException {
// todo: 补充完成该方法。
throw new UnsupportedOperationException("该方法尚未完成");
}
@Override
public void createPartition(ObjectPath tablePath, CatalogPartitionSpec partitionSpec, CatalogPartition partition, boolean ignoreIfExists)
throws TableNotExistException, TableNotPartitionedException, PartitionSpecInvalidException, PartitionAlreadyExistsException, CatalogException {
public void createPartition(ObjectPath tablePath, CatalogPartitionSpec partitionSpec, CatalogPartition partition,
boolean ignoreIfExists) throws TableNotExistException, TableNotPartitionedException, PartitionSpecInvalidException, PartitionAlreadyExistsException, CatalogException {
// todo: 补充完成该方法。
throw new UnsupportedOperationException("该方法尚未完成");
}
@Override
public void dropPartition(ObjectPath tablePath, CatalogPartitionSpec partitionSpec, boolean ignoreIfNotExists) throws PartitionNotExistException, CatalogException {
public void dropPartition(ObjectPath tablePath, CatalogPartitionSpec partitionSpec,
boolean ignoreIfNotExists) throws PartitionNotExistException, CatalogException {
// todo: 补充完成该方法。
throw new UnsupportedOperationException("该方法尚未完成");
}
@Override
public void alterPartition(ObjectPath tablePath, CatalogPartitionSpec partitionSpec, CatalogPartition newPartition, boolean ignoreIfNotExists) throws PartitionNotExistException, CatalogException {
public void alterPartition(ObjectPath tablePath, CatalogPartitionSpec partitionSpec, CatalogPartition newPartition,
boolean ignoreIfNotExists) throws PartitionNotExistException, CatalogException {
// todo: 补充完成该方法。
throw new UnsupportedOperationException("该方法尚未完成");
}
......@@ -958,7 +952,7 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
throw new DatabaseNotExistException(getName(), dbName);
}
String querySql = "SELECT function_name from metadata_function "
+ " WHERE database_id=?";
+ " WHERE database_id=?";
Connection conn = getConnection();
try (PreparedStatement gStat = conn.prepareStatement(querySql)) {
......@@ -977,15 +971,14 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
}
@Override
public CatalogFunction getFunction(ObjectPath functionPath)
throws FunctionNotExistException, CatalogException {
public CatalogFunction getFunction(ObjectPath functionPath) throws FunctionNotExistException, CatalogException {
Integer id = getFunctionId(functionPath);
if (null == id) {
throw new FunctionNotExistException(getName(), functionPath);
}
String querySql = "SELECT class_name,function_language from metadata_function "
+ " WHERE id=?";
+ " WHERE id=?";
Connection conn = getConnection();
try (PreparedStatement gStat = conn.prepareStatement(querySql)) {
gStat.setInt(1, id);
......@@ -1001,8 +994,8 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
} catch (SQLException e) {
sqlExceptionHappened = true;
throw new CatalogException("获取 UDF 失败:"
+ functionPath.getDatabaseName() + "."
+ functionPath.getObjectName());
+ functionPath.getDatabaseName() + "."
+ functionPath.getObjectName());
}
}
......@@ -1019,7 +1012,7 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
}
// 获取id
String getIdSql = "select id from metadata_function "
+ " where function_name=? and database_id=?";
+ " where function_name=? and database_id=?";
Connection conn = getConnection();
try (PreparedStatement gStat = conn.prepareStatement(getIdSql)) {
gStat.setString(1, functionPath.getObjectName());
......@@ -1038,8 +1031,8 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
}
@Override
public void createFunction(ObjectPath functionPath, CatalogFunction function, boolean ignoreIfExists)
throws FunctionAlreadyExistException, DatabaseNotExistException, CatalogException {
public void createFunction(ObjectPath functionPath, CatalogFunction function,
boolean ignoreIfExists) throws FunctionAlreadyExistException, DatabaseNotExistException, CatalogException {
Integer dbId = getDatabaseId(functionPath.getDatabaseName());
if (null == dbId) {
throw new DatabaseNotExistException(getName(), functionPath.getDatabaseName());
......@@ -1052,8 +1045,8 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
Connection conn = getConnection();
String insertSql = "Insert into metadata_function "
+ "(function_name,class_name,database_id,function_language) "
+ " values (?,?,?,?)";
+ "(function_name,class_name,database_id,function_language) "
+ " values (?,?,?,?)";
try (PreparedStatement ps = conn.prepareStatement(insertSql)) {
ps.setString(1, functionPath.getObjectName());
ps.setString(2, function.getClassName());
......@@ -1067,8 +1060,8 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
}
@Override
public void alterFunction(ObjectPath functionPath, CatalogFunction newFunction, boolean ignoreIfNotExists)
throws FunctionNotExistException, CatalogException {
public void alterFunction(ObjectPath functionPath, CatalogFunction newFunction,
boolean ignoreIfNotExists) throws FunctionNotExistException, CatalogException {
Integer id = getFunctionId(functionPath);
if (null == id) {
if (!ignoreIfNotExists) {
......@@ -1079,8 +1072,8 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
Connection conn = getConnection();
String insertSql = "update metadata_function "
+ "set (class_name =?, function_language=?) "
+ " where id=?";
+ "set (class_name =?, function_language=?) "
+ " where id=?";
try (PreparedStatement ps = conn.prepareStatement(insertSql)) {
ps.setString(1, newFunction.getClassName());
ps.setString(2, newFunction.getFunctionLanguage().toString());
......@@ -1093,8 +1086,8 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
}
@Override
public void dropFunction(ObjectPath functionPath, boolean ignoreIfNotExists)
throws FunctionNotExistException, CatalogException {
public void dropFunction(ObjectPath functionPath,
boolean ignoreIfNotExists) throws FunctionNotExistException, CatalogException {
Integer id = getFunctionId(functionPath);
if (null == id) {
if (!ignoreIfNotExists) {
......@@ -1105,7 +1098,7 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
Connection conn = getConnection();
String insertSql = "delete from metadata_function "
+ " where id=?";
+ " where id=?";
try (PreparedStatement ps = conn.prepareStatement(insertSql)) {
ps.setInt(1, id);
ps.executeUpdate();
......@@ -1123,12 +1116,11 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
if (!tableExists(tablePath)) {
throw new TableNotExistException(getName(), tablePath);
}
/*if (!isPartitionedTable(tablePath)) {
CatalogTableStatistics result = tableStats.get(tablePath);
return result != null ? result.copy() : CatalogTableStatistics.UNKNOWN;
} else {
return CatalogTableStatistics.UNKNOWN;
}*/
/*
* if (!isPartitionedTable(tablePath)) { CatalogTableStatistics result = tableStats.get(tablePath); return
* result != null ? result.copy() : CatalogTableStatistics.UNKNOWN; } else { return
* CatalogTableStatistics.UNKNOWN; }
*/
return CatalogTableStatistics.UNKNOWN;
}
......@@ -1147,40 +1139,45 @@ public class DlinkMysqlCatalog extends AbstractCatalog {
}
@Override
public CatalogTableStatistics getPartitionStatistics(ObjectPath tablePath, CatalogPartitionSpec partitionSpec) throws PartitionNotExistException, CatalogException {
public CatalogTableStatistics getPartitionStatistics(ObjectPath tablePath,
CatalogPartitionSpec partitionSpec) throws PartitionNotExistException, CatalogException {
// todo: 补充完成该方法。
throw new UnsupportedOperationException("该方法尚未完成");
}
@Override
public CatalogColumnStatistics getPartitionColumnStatistics(ObjectPath tablePath, CatalogPartitionSpec partitionSpec) throws PartitionNotExistException, CatalogException {
public CatalogColumnStatistics getPartitionColumnStatistics(ObjectPath tablePath,
CatalogPartitionSpec partitionSpec) throws PartitionNotExistException, CatalogException {
// todo: 补充完成该方法。
throw new UnsupportedOperationException("该方法尚未完成");
}
@Override
public void alterTableStatistics(ObjectPath tablePath, CatalogTableStatistics tableStatistics, boolean ignoreIfNotExists) throws TableNotExistException, CatalogException {
public void alterTableStatistics(ObjectPath tablePath, CatalogTableStatistics tableStatistics,
boolean ignoreIfNotExists) throws TableNotExistException, CatalogException {
// todo: 补充完成该方法。
throw new UnsupportedOperationException("该方法尚未完成");
}
@Override
public void alterTableColumnStatistics(ObjectPath tablePath, CatalogColumnStatistics columnStatistics, boolean ignoreIfNotExists)
throws TableNotExistException, CatalogException, TablePartitionedException {
public void alterTableColumnStatistics(ObjectPath tablePath, CatalogColumnStatistics columnStatistics,
boolean ignoreIfNotExists) throws TableNotExistException, CatalogException, TablePartitionedException {
// todo: 补充完成该方法。
throw new UnsupportedOperationException("该方法尚未完成");
}
@Override
public void alterPartitionStatistics(ObjectPath tablePath, CatalogPartitionSpec partitionSpec, CatalogTableStatistics partitionStatistics, boolean ignoreIfNotExists)
throws PartitionNotExistException, CatalogException {
public void alterPartitionStatistics(ObjectPath tablePath, CatalogPartitionSpec partitionSpec,
CatalogTableStatistics partitionStatistics,
boolean ignoreIfNotExists) throws PartitionNotExistException, CatalogException {
// todo: 补充完成该方法。
throw new UnsupportedOperationException("该方法尚未完成");
}
@Override
public void alterPartitionColumnStatistics(ObjectPath tablePath, CatalogPartitionSpec partitionSpec, CatalogColumnStatistics columnStatistics, boolean ignoreIfNotExists)
throws PartitionNotExistException, CatalogException {
public void alterPartitionColumnStatistics(ObjectPath tablePath, CatalogPartitionSpec partitionSpec,
CatalogColumnStatistics columnStatistics,
boolean ignoreIfNotExists) throws PartitionNotExistException, CatalogException {
// todo: 补充完成该方法。
throw new UnsupportedOperationException("该方法尚未完成");
}
......
......@@ -22,8 +22,11 @@ package com.dlink.flink.catalog.factory;
import static com.dlink.flink.catalog.factory.DlinkMysqlCatalogFactoryOptions.PASSWORD;
import static com.dlink.flink.catalog.factory.DlinkMysqlCatalogFactoryOptions.URL;
import static com.dlink.flink.catalog.factory.DlinkMysqlCatalogFactoryOptions.USERNAME;
import static org.apache.flink.table.factories.FactoryUtil.PROPERTY_VERSION;
import com.dlink.flink.catalog.DlinkMysqlCatalog;
import org.apache.flink.configuration.ConfigOption;
import org.apache.flink.table.catalog.Catalog;
import org.apache.flink.table.factories.CatalogFactory;
......@@ -32,8 +35,6 @@ import org.apache.flink.table.factories.FactoryUtil;
import java.util.HashSet;
import java.util.Set;
import com.dlink.flink.catalog.DlinkMysqlCatalog;
/**
* Factory for {@link DlinkMysqlCatalog}.
*/
......@@ -63,13 +64,13 @@ public class DlinkMysqlCatalogFactory implements CatalogFactory {
@Override
public Catalog createCatalog(Context context) {
final FactoryUtil.CatalogFactoryHelper helper =
FactoryUtil.createCatalogFactoryHelper(this, context);
FactoryUtil.createCatalogFactoryHelper(this, context);
helper.validate();
return new DlinkMysqlCatalog(
context.getName(),
helper.getOptions().get(URL),
helper.getOptions().get(USERNAME),
helper.getOptions().get(PASSWORD));
context.getName(),
helper.getOptions().get(URL),
helper.getOptions().get(USERNAME),
helper.getOptions().get(PASSWORD));
}
}
......@@ -19,12 +19,12 @@
package com.dlink.flink.catalog.factory;
import com.dlink.flink.catalog.DlinkMysqlCatalog;
import org.apache.flink.annotation.Internal;
import org.apache.flink.configuration.ConfigOption;
import org.apache.flink.configuration.ConfigOptions;
import com.dlink.flink.catalog.DlinkMysqlCatalog;
/**
* {@link ConfigOption}s for {@link DlinkMysqlCatalog}.
*/
......
......@@ -77,7 +77,7 @@ import org.slf4j.LoggerFactory;
* @author wenmo
* @since 2022/4/12 21:28
**/
public abstract class AbstractSinkBuilder {
public abstract class AbstractSinkBuilder implements SinkBuilder {
protected static final Logger logger = LoggerFactory.getLogger(AbstractSinkBuilder.class);
......@@ -103,8 +103,9 @@ public abstract class AbstractSinkBuilder {
Properties properties = new Properties();
Map<String, String> sink = config.getSink();
for (Map.Entry<String, String> entry : sink.entrySet()) {
if (Asserts.isNotNullString(entry.getKey()) && entry.getKey().startsWith("properties") && Asserts.isNotNullString(entry.getValue())) {
properties.setProperty(entry.getKey().replace("properties.",""), entry.getValue());
if (Asserts.isNotNullString(entry.getKey()) && entry.getKey().startsWith("properties")
&& Asserts.isNotNullString(entry.getValue())) {
properties.setProperty(entry.getKey().replace("properties.", ""), entry.getValue());
}
}
return properties;
......@@ -112,6 +113,7 @@ public abstract class AbstractSinkBuilder {
protected SingleOutputStreamOperator<Map> deserialize(DataStreamSource<String> dataStreamSource) {
return dataStreamSource.map(new MapFunction<String, Map>() {
@Override
public Map map(String value) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
......@@ -121,97 +123,105 @@ public abstract class AbstractSinkBuilder {
}
protected SingleOutputStreamOperator<Map> shunt(
SingleOutputStreamOperator<Map> mapOperator,
Table table,
String schemaFieldName) {
SingleOutputStreamOperator<Map> mapOperator,
Table table,
String schemaFieldName) {
final String tableName = table.getName();
final String schemaName = table.getSchema();
return mapOperator.filter(new FilterFunction<Map>() {
@Override
public boolean filter(Map value) throws Exception {
LinkedHashMap source = (LinkedHashMap) value.get("source");
return tableName.equals(source.get("table").toString())
&& schemaName.equals(source.get(schemaFieldName).toString());
&& schemaName.equals(source.get(schemaFieldName).toString());
}
});
}
protected DataStream<Map> shunt(
SingleOutputStreamOperator<Map> processOperator,
Table table,
OutputTag<Map> tag) {
SingleOutputStreamOperator<Map> processOperator,
Table table,
OutputTag<Map> tag) {
return processOperator.getSideOutput(tag);
}
protected DataStream<RowData> buildRowData(
SingleOutputStreamOperator<Map> filterOperator,
List<String> columnNameList,
List<LogicalType> columnTypeList,
String schemaTableName) {
SingleOutputStreamOperator<Map> filterOperator,
List<String> columnNameList,
List<LogicalType> columnTypeList,
String schemaTableName) {
return filterOperator
.flatMap(new FlatMapFunction<Map, RowData>() {
@Override
public void flatMap(Map value, Collector<RowData> out) throws Exception {
try {
switch (value.get("op").toString()) {
case "r":
case "c":
GenericRowData igenericRowData = new GenericRowData(columnNameList.size());
igenericRowData.setRowKind(RowKind.INSERT);
Map idata = (Map) value.get("after");
for (int i = 0; i < columnNameList.size(); i++) {
igenericRowData.setField(i, convertValue(idata.get(columnNameList.get(i)), columnTypeList.get(i)));
}
out.collect(igenericRowData);
break;
case "d":
GenericRowData dgenericRowData = new GenericRowData(columnNameList.size());
dgenericRowData.setRowKind(RowKind.DELETE);
Map ddata = (Map) value.get("before");
for (int i = 0; i < columnNameList.size(); i++) {
dgenericRowData.setField(i, convertValue(ddata.get(columnNameList.get(i)), columnTypeList.get(i)));
}
out.collect(dgenericRowData);
break;
case "u":
GenericRowData ubgenericRowData = new GenericRowData(columnNameList.size());
ubgenericRowData.setRowKind(RowKind.UPDATE_BEFORE);
Map ubdata = (Map) value.get("before");
for (int i = 0; i < columnNameList.size(); i++) {
ubgenericRowData.setField(i, convertValue(ubdata.get(columnNameList.get(i)), columnTypeList.get(i)));
}
out.collect(ubgenericRowData);
GenericRowData uagenericRowData = new GenericRowData(columnNameList.size());
uagenericRowData.setRowKind(RowKind.UPDATE_AFTER);
Map uadata = (Map) value.get("after");
for (int i = 0; i < columnNameList.size(); i++) {
uagenericRowData.setField(i, convertValue(uadata.get(columnNameList.get(i)), columnTypeList.get(i)));
}
out.collect(uagenericRowData);
break;
default:
.flatMap(new FlatMapFunction<Map, RowData>() {
@Override
public void flatMap(Map value, Collector<RowData> out) throws Exception {
try {
switch (value.get("op").toString()) {
case "r":
case "c":
GenericRowData igenericRowData = new GenericRowData(columnNameList.size());
igenericRowData.setRowKind(RowKind.INSERT);
Map idata = (Map) value.get("after");
for (int i = 0; i < columnNameList.size(); i++) {
igenericRowData.setField(i,
convertValue(idata.get(columnNameList.get(i)), columnTypeList.get(i)));
}
out.collect(igenericRowData);
break;
case "d":
GenericRowData dgenericRowData = new GenericRowData(columnNameList.size());
dgenericRowData.setRowKind(RowKind.DELETE);
Map ddata = (Map) value.get("before");
for (int i = 0; i < columnNameList.size(); i++) {
dgenericRowData.setField(i,
convertValue(ddata.get(columnNameList.get(i)), columnTypeList.get(i)));
}
out.collect(dgenericRowData);
break;
case "u":
GenericRowData ubgenericRowData = new GenericRowData(columnNameList.size());
ubgenericRowData.setRowKind(RowKind.UPDATE_BEFORE);
Map ubdata = (Map) value.get("before");
for (int i = 0; i < columnNameList.size(); i++) {
ubgenericRowData.setField(i,
convertValue(ubdata.get(columnNameList.get(i)), columnTypeList.get(i)));
}
out.collect(ubgenericRowData);
GenericRowData uagenericRowData = new GenericRowData(columnNameList.size());
uagenericRowData.setRowKind(RowKind.UPDATE_AFTER);
Map uadata = (Map) value.get("after");
for (int i = 0; i < columnNameList.size(); i++) {
uagenericRowData.setField(i,
convertValue(uadata.get(columnNameList.get(i)), columnTypeList.get(i)));
}
out.collect(uagenericRowData);
break;
default:
}
} catch (Exception e) {
logger.error("SchameTable: {} - Row: {} - Exception:", schemaTableName,
JSONUtil.toJsonString(value), e);
throw e;
}
} catch (Exception e) {
logger.error("SchameTable: {} - Row: {} - Exception:", schemaTableName, JSONUtil.toJsonString(value), e);
throw e;
}
}
});
});
}
public abstract void addSink(
StreamExecutionEnvironment env,
DataStream<RowData> rowDataDataStream,
Table table,
List<String> columnNameList,
List<LogicalType> columnTypeList);
StreamExecutionEnvironment env,
DataStream<RowData> rowDataDataStream,
Table table,
List<String> columnNameList,
List<LogicalType> columnTypeList);
@Override
public DataStreamSource build(
CDCBuilder cdcBuilder,
StreamExecutionEnvironment env,
CustomTableEnvironment customTableEnvironment,
DataStreamSource<String> dataStreamSource) {
CDCBuilder cdcBuilder,
StreamExecutionEnvironment env,
CustomTableEnvironment customTableEnvironment,
DataStreamSource<String> dataStreamSource) {
final List<Schema> schemaList = config.getSchemaList();
final String schemaFieldName = config.getSchemaFieldName();
......@@ -227,7 +237,8 @@ public abstract class AbstractSinkBuilder {
buildColumn(columnNameList, columnTypeList, table.getColumns());
DataStream<RowData> rowDataDataStream = buildRowData(filterOperator, columnNameList, columnTypeList, table.getSchemaTableName());
DataStream<RowData> rowDataDataStream =
buildRowData(filterOperator, columnNameList, columnTypeList, table.getSchemaTableName());
addSink(env, rowDataDataStream, table, columnNameList, columnTypeList);
}
......@@ -294,7 +305,8 @@ public abstract class AbstractSinkBuilder {
if (logicalType instanceof VarCharType) {
return StringData.fromString((String) value);
} else if (logicalType instanceof DateType) {
return StringData.fromString(Instant.ofEpochMilli((long) value).atZone(ZoneId.systemDefault()).toLocalDate().toString());
return StringData.fromString(
Instant.ofEpochMilli((long) value).atZone(ZoneId.systemDefault()).toLocalDate().toString());
} else if (logicalType instanceof TimestampType) {
return TimestampData.fromTimestamp(Timestamp.from(Instant.ofEpochMilli((long) value)));
} else if (logicalType instanceof DecimalType) {
......@@ -307,7 +319,8 @@ public abstract class AbstractSinkBuilder {
}
}
protected String getSinkSchemaName(Table table) {
@Override
public String getSinkSchemaName(Table table) {
String schemaName = table.getSchema();
if (config.getSink().containsKey("sink.db")) {
schemaName = config.getSink().get("sink.db");
......@@ -315,7 +328,8 @@ public abstract class AbstractSinkBuilder {
return schemaName;
}
protected String getSinkTableName(Table table) {
@Override
public String getSinkTableName(Table table) {
String tableName = table.getName();
if (config.getSink().containsKey("table.prefix.schema")) {
if (Boolean.valueOf(config.getSink().get("table.prefix.schema"))) {
......
......@@ -19,6 +19,7 @@
package com.dlink.cdc;
import com.dlink.exception.SplitTableException;
import com.dlink.model.FlinkCDCConfig;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
......@@ -48,4 +49,8 @@ public interface CDCBuilder {
Map<String, Map<String, String>> parseMetaDataConfigs();
String getSchemaFieldName();
default Map<String, String> parseMetaDataConfig() {
throw new SplitTableException("此数据源并未实现分库分表");
}
}
......@@ -21,6 +21,7 @@ package com.dlink.cdc;
import com.dlink.executor.CustomTableEnvironment;
import com.dlink.model.FlinkCDCConfig;
import com.dlink.model.Table;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
......@@ -37,5 +38,11 @@ public interface SinkBuilder {
SinkBuilder create(FlinkCDCConfig config);
DataStreamSource build(CDCBuilder cdcBuilder, StreamExecutionEnvironment env, CustomTableEnvironment customTableEnvironment, DataStreamSource<String> dataStreamSource);
DataStreamSource build(CDCBuilder cdcBuilder, StreamExecutionEnvironment env,
CustomTableEnvironment customTableEnvironment, DataStreamSource<String> dataStreamSource);
String getSinkSchemaName(Table table);
String getSinkTableName(Table table);
}
......@@ -22,6 +22,7 @@ package com.dlink.cdc;
import com.dlink.assertion.Asserts;
import com.dlink.cdc.doris.DorisSinkBuilder;
import com.dlink.cdc.kafka.KafkaSinkBuilder;
import com.dlink.cdc.sql.SQLSinkBuilder;
import com.dlink.exception.FlinkClientException;
import com.dlink.model.FlinkCDCConfig;
......@@ -47,6 +48,6 @@ public class SinkBuilderFactory {
return sinkBuilders[i].create(config);
}
}
throw new FlinkClientException("未匹配到对应 Sink 类型的【" + config.getSink().get("connector") + "】。");
return new SQLSinkBuilder().create(config);
}
}
......@@ -45,7 +45,7 @@ import java.util.Properties;
* @author wenmo
* @since 2022/4/20 19:20
**/
public class DorisSinkBuilder extends AbstractSinkBuilder implements SinkBuilder, Serializable {
public class DorisSinkBuilder extends AbstractSinkBuilder implements Serializable {
private static final String KEY_WORD = "datastream-doris";
private static final long serialVersionUID = 8330362249137471854L;
......@@ -69,11 +69,11 @@ public class DorisSinkBuilder extends AbstractSinkBuilder implements SinkBuilder
@Override
public void addSink(
StreamExecutionEnvironment env,
DataStream<RowData> rowDataDataStream,
Table table,
List<String> columnNameList,
List<LogicalType> columnTypeList) {
StreamExecutionEnvironment env,
DataStream<RowData> rowDataDataStream,
Table table,
List<String> columnNameList,
List<LogicalType> columnTypeList) {
DorisExecutionOptions.Builder dorisExecutionOptionsBuilder = DorisExecutionOptions.builder();
Map<String, String> sink = config.getSink();
......@@ -95,17 +95,16 @@ public class DorisSinkBuilder extends AbstractSinkBuilder implements SinkBuilder
final LogicalType[] columnTypes = columnTypeList.toArray(new LogicalType[columnTypeList.size()]);
rowDataDataStream.addSink(
DorisSink.sink(
columnNames,
columnTypes,
DorisReadOptions.builder().build(),
dorisExecutionOptionsBuilder.build(),
DorisOptions.builder()
.setFenodes(config.getSink().get("fenodes"))
.setTableIdentifier(getSinkSchemaName(table) + "." + getSinkTableName(table))
.setUsername(config.getSink().get("username"))
.setPassword(config.getSink().get("password")).build()
));
DorisSink.sink(
columnNames,
columnTypes,
DorisReadOptions.builder().build(),
dorisExecutionOptionsBuilder.build(),
DorisOptions.builder()
.setFenodes(config.getSink().get("fenodes"))
.setTableIdentifier(getSinkSchemaName(table) + "." + getSinkTableName(table))
.setUsername(config.getSink().get("username"))
.setPassword(config.getSink().get("password")).build()));
}
@Override
......@@ -113,7 +112,8 @@ public class DorisSinkBuilder extends AbstractSinkBuilder implements SinkBuilder
Properties properties = new Properties();
Map<String, String> sink = config.getSink();
for (Map.Entry<String, String> entry : sink.entrySet()) {
if (Asserts.isNotNullString(entry.getKey()) && entry.getKey().startsWith("sink.properties") && Asserts.isNotNullString(entry.getValue())) {
if (Asserts.isNotNullString(entry.getKey()) && entry.getKey().startsWith("sink.properties")
&& Asserts.isNotNullString(entry.getValue())) {
properties.setProperty(entry.getKey().replace("sink.properties.", ""), entry.getValue());
}
}
......
......@@ -37,7 +37,6 @@ import java.util.Map;
import java.util.Properties;
import com.alibaba.ververica.cdc.connectors.mysql.MySQLSource;
import com.alibaba.ververica.cdc.debezium.StringDebeziumDeserializationSchema;
/**
* MysqlCDCBuilder
......@@ -76,10 +75,10 @@ public class MysqlCDCBuilder extends AbstractCDCBuilder implements CDCBuilder {
}
}
MySQLSource.Builder<String> sourceBuilder = MySQLSource.<String>builder()
.hostname(config.getHostname())
.port(config.getPort())
.username(config.getUsername())
.password(config.getPassword());
.hostname(config.getHostname())
.port(config.getPort())
.username(config.getUsername())
.password(config.getPassword());
String database = config.getDatabase();
if (Asserts.isNotNullString(database)) {
String[] databases = database.split(FlinkParamConstant.SPLIT);
......@@ -93,7 +92,7 @@ public class MysqlCDCBuilder extends AbstractCDCBuilder implements CDCBuilder {
} else {
sourceBuilder.tableList(new String[0]);
}
sourceBuilder.deserializer(new StringDebeziumDeserializationSchema());
sourceBuilder.deserializer(new MysqlJsonDebeziumDeserializationSchema());
sourceBuilder.debeziumProperties(properties);
return env.addSource(sourceBuilder.build(), "MySQL CDC Source");
}
......
/*
*
* 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 com.dlink.cdc.mysql;
import org.apache.flink.api.common.typeinfo.BasicTypeInfo;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.util.Collector;
import org.apache.kafka.connect.json.JsonConverter;
import org.apache.kafka.connect.source.SourceRecord;
import org.apache.kafka.connect.storage.ConverterType;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.ververica.cdc.debezium.DebeziumDeserializationSchema;
/**
* @version 1.0
* @className: com.dlink.cdc.mysql.MysqlJsonDebeziumDeserializationSchema
* @Description:
* @author: jack zhong
*/
public class MysqlJsonDebeziumDeserializationSchema implements DebeziumDeserializationSchema<String> {
private static final long serialVersionUID = 1L;
private transient JsonConverter jsonConverter;
private final Boolean includeSchema;
private Map<String, Object> customConverterConfigs;
public MysqlJsonDebeziumDeserializationSchema() {
this(false);
}
public MysqlJsonDebeziumDeserializationSchema(Boolean includeSchema) {
this.includeSchema = includeSchema;
}
public MysqlJsonDebeziumDeserializationSchema(Boolean includeSchema, Map<String, Object> customConverterConfigs) {
this.includeSchema = includeSchema;
this.customConverterConfigs = customConverterConfigs;
}
public void deserialize(SourceRecord record, Collector<String> out) throws Exception {
if (this.jsonConverter == null) {
this.initializeJsonConverter();
}
byte[] bytes = this.jsonConverter.fromConnectData(record.topic(), record.valueSchema(), record.value());
out.collect(new String(bytes, StandardCharsets.UTF_8));
}
private void initializeJsonConverter() {
this.jsonConverter = new JsonConverter();
HashMap<String, Object> configs = new HashMap(2);
configs.put("converter.type", ConverterType.VALUE.getName());
configs.put("schemas.enable", this.includeSchema);
if (this.customConverterConfigs != null) {
configs.putAll(this.customConverterConfigs);
}
this.jsonConverter.configure(configs);
}
public TypeInformation<String> getProducedType() {
return BasicTypeInfo.STRING_TYPE_INFO;
}
}
/*
*
* 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.flink.kubernetes.kubeclient;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions;
import org.apache.flink.runtime.util.ExecutorThreadFactory;
import org.apache.flink.util.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClientException;
/**
* Factory class to create {@link FlinkKubeClient}.
*/
public class FlinkKubeClientFactory {
private static final Logger LOG = LoggerFactory.getLogger(KubeClientFactory.class);
private static final FlinkKubeClientFactory INSTANCE = new FlinkKubeClientFactory();
public static FlinkKubeClientFactory getInstance() {
return INSTANCE;
}
public static FlinkKubeClient fromConfiguration(Configuration flinkConfig, String useCase) {
final Config config;
final String kubeContext = flinkConfig.getString(KubernetesConfigOptions.CONTEXT);
if (kubeContext != null) {
LOG.info("Configuring kubernetes client to use context {}.", kubeContext);
}
final String kubeConfigFile =
flinkConfig.getString(KubernetesConfigOptions.KUBE_CONFIG_FILE);
if (kubeConfigFile != null) {
LOG.debug("Trying to load kubernetes config from file: {}.", kubeConfigFile);
try {
// If kubeContext is null, the default context in the kubeConfigFile will be used.
// Note: the third parameter kubeconfigPath is optional and is set to null. It is
// only used to rewrite
// relative tls asset paths inside kubeconfig when a file is passed, and in the case
// that the kubeconfig
// references some assets via relative paths.
config =
Config.fromKubeconfig(
kubeContext,
FileUtils.readFileUtf8(new File(kubeConfigFile)),
null);
} catch (IOException e) {
throw new KubernetesClientException("Load kubernetes config failed.", e);
}
} else {
LOG.debug("Trying to load default kubernetes config.");
config = Config.autoConfigure(kubeContext);
}
final KubernetesClient client = new DefaultKubernetesClient(config);
return new Fabric8FlinkKubeClient(
flinkConfig, client, FlinkKubeClientFactory::createThreadPoolForAsyncIO);
}
private static ExecutorService createThreadPoolForAsyncIO() {
return Executors.newFixedThreadPool(2, new ExecutorThreadFactory("FlinkKubeClient-IO"));
}
}
/*
*
* 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.flink.streaming.api.environment;
import org.apache.flink.annotation.PublicEvolving;
import org.apache.flink.configuration.Configuration;
/** Factory class for stream execution environments. */
@PublicEvolving
public interface StreamExecutionEnvironmentFactory {
/**
* Creates a StreamExecutionEnvironment from this factory.
*
* @return A StreamExecutionEnvironment.
*/
StreamExecutionEnvironment createExecutionEnvironment();
StreamExecutionEnvironment createExecutionEnvironment(Configuration configuration);
}
/*
*
* 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.flink.table.api;
import org.apache.flink.annotation.PublicEvolving;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.table.annotation.DataTypeHint;
import org.apache.flink.table.catalog.DataTypeFactory;
import org.apache.flink.table.catalog.ObjectIdentifier;
import org.apache.flink.table.types.AbstractDataType;
import org.apache.flink.table.types.AtomicDataType;
import org.apache.flink.table.types.CollectionDataType;
import org.apache.flink.table.types.DataType;
import org.apache.flink.table.types.FieldsDataType;
import org.apache.flink.table.types.KeyValueDataType;
import org.apache.flink.table.types.UnresolvedDataType;
import org.apache.flink.table.types.extraction.ExtractionUtils;
import org.apache.flink.table.types.logical.ArrayType;
import org.apache.flink.table.types.logical.BigIntType;
import org.apache.flink.table.types.logical.BinaryType;
import org.apache.flink.table.types.logical.BooleanType;
import org.apache.flink.table.types.logical.CharType;
import org.apache.flink.table.types.logical.DateType;
import org.apache.flink.table.types.logical.DayTimeIntervalType;
import org.apache.flink.table.types.logical.DayTimeIntervalType.DayTimeResolution;
import org.apache.flink.table.types.logical.DecimalType;
import org.apache.flink.table.types.logical.DoubleType;
import org.apache.flink.table.types.logical.FloatType;
import org.apache.flink.table.types.logical.IntType;
import org.apache.flink.table.types.logical.LocalZonedTimestampType;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.MapType;
import org.apache.flink.table.types.logical.MultisetType;
import org.apache.flink.table.types.logical.NullType;
import org.apache.flink.table.types.logical.RawType;
import org.apache.flink.table.types.logical.RowType;
import org.apache.flink.table.types.logical.RowType.RowField;
import org.apache.flink.table.types.logical.SmallIntType;
import org.apache.flink.table.types.logical.StructuredType;
import org.apache.flink.table.types.logical.StructuredType.StructuredAttribute;
import org.apache.flink.table.types.logical.TimeType;
import org.apache.flink.table.types.logical.TimestampType;
import org.apache.flink.table.types.logical.TinyIntType;
import org.apache.flink.table.types.logical.VarBinaryType;
import org.apache.flink.table.types.logical.VarCharType;
import org.apache.flink.table.types.logical.YearMonthIntervalType;
import org.apache.flink.table.types.logical.YearMonthIntervalType.YearMonthResolution;
import org.apache.flink.table.types.logical.ZonedTimestampType;
import org.apache.flink.table.types.utils.TypeConversions;
import org.apache.flink.util.Preconditions;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.annotation.Nullable;
/**
* A {@link DataType} can be used to declare input and/or output types of operations. This class
* enumerates all pre-defined data types of the Table & SQL API.
*
* <p>For convenience, this class also contains methods for creating {@link UnresolvedDataType}s
* that need to be resolved at later stages. This is in particular useful for more complex types
* that are expressed as {@link Class} (see {@link #of(Class)}) or types that need to be looked up
* in a catalog (see {@link #of(String)}).
*
* <p>NOTE: Planners might not support every data type with the desired precision or parameter.
* Please see the planner compatibility and limitations section in the website documentation before
* using a data type.
*/
@PublicEvolving
public final class DataTypes {
/**
* Creates a {@link DataType} from a {@link LogicalType} with default conversion class.
*
* @return the {@link LogicalType} converted to a {@link DataType}.
* @see LogicalType#getDefaultConversion()
*/
public static DataType of(LogicalType logicalType) {
return TypeConversions.fromLogicalToDataType(logicalType);
}
/**
* Creates an unresolved type that will be resolved to a {@link DataType} by analyzing the given
* class later.
*
* <p>During the resolution, Java reflection is used which can be supported by {@link
* DataTypeHint} annotations for nested, structured types.
*
* <p>It will throw an {@link ValidationException} in cases where the reflective extraction
* needs more information or simply fails.
*
* <p>The following examples show how to use and enrich the extraction process:
*
* <pre>{@code
* // returns INT
* of(Integer.class)
*
* // returns TIMESTAMP(9)
* of(java.time.LocalDateTime.class)
*
* // returns an anonymous, unregistered structured type
* // that is deeply integrated into the API compared to opaque RAW types
* class User {
*
* // extract fields automatically
* public String name;
* public int age;
*
* // enrich the extraction with precision information
* public @DataTypeHint("DECIMAL(10,2)") BigDecimal accountBalance;
*
* // enrich the extraction with forcing using RAW types
* public @DataTypeHint(forceRawPattern = "scala.") Address address;
*
* // enrich the extraction by specifying defaults
* public @DataTypeHint(defaultSecondPrecision = 3) Log log;
* }
* of(User.class)
* }</pre>
*
* <p>Note: In most of the cases, the {@link UnresolvedDataType} will be automatically resolved
* by the API. At other locations, a {@link DataTypeFactory} is provided.
*/
public static UnresolvedDataType of(Class<?> unresolvedClass) {
Preconditions.checkNotNull(unresolvedClass, "Unresolved class name must not be null.");
return new UnresolvedDataType(
() -> String.format("'%s'", unresolvedClass.getName()),
(factory) -> factory.createDataType(unresolvedClass));
}
/**
* Creates an unresolved type that will be resolved to a {@link DataType} by using a fully or
* partially defined name.
*
* <p>It includes both built-in types (e.g. "INT") as well as user-defined types (e.g.
* "mycat.mydb.Money").
*
* <p>Note: In most of the cases, the {@link UnresolvedDataType} will be automatically resolved
* by the API. At other locations, a {@link DataTypeFactory} is provided.
*/
public static UnresolvedDataType of(String unresolvedName) {
Preconditions.checkNotNull(unresolvedName, "Unresolved name must not be null.");
return new UnresolvedDataType(
() -> unresolvedName, (factory) -> factory.createDataType(unresolvedName));
}
// we use SQL-like naming for data types and avoid Java keyword clashes
// CHECKSTYLE.OFF: MethodName
/**
* Data type of a fixed-length character string {@code CHAR(n)} where {@code n} is the number of
* code points. {@code n} must have a value between 1 and {@link Integer#MAX_VALUE} (both
* inclusive).
*
* @see CharType
*/
public static DataType CHAR(int n) {
return new AtomicDataType(new CharType(n));
}
/**
* Data type of a variable-length character string {@code VARCHAR(n)} where {@code n} is the
* maximum number of code points. {@code n} must have a value between 1 and {@link
* Integer#MAX_VALUE} (both inclusive).
*
* @see VarCharType
*/
public static DataType VARCHAR(int n) {
return new AtomicDataType(new VarCharType(n));
}
/**
* Data type of a variable-length character string with defined maximum length. This is a
* shortcut for {@code VARCHAR(2147483647)} for representing JVM strings.
*
* @see VarCharType
*/
public static DataType STRING() {
return VARCHAR(Integer.MAX_VALUE);
}
/**
* Data type of a boolean with a (possibly) three-valued logic of {@code TRUE, FALSE, UNKNOWN}.
*
* @see BooleanType
*/
public static DataType BOOLEAN() {
return new AtomicDataType(new BooleanType());
}
/**
* Data type of a fixed-length binary string (=a sequence of bytes) {@code BINARY(n)} where
* {@code n} is the number of bytes. {@code n} must have a value between 1 and {@link
* Integer#MAX_VALUE} (both inclusive).
*
* @see BinaryType
*/
public static DataType BINARY(int n) {
return new AtomicDataType(new BinaryType(n));
}
/**
* Data type of a variable-length binary string (=a sequence of bytes) {@code VARBINARY(n)}
* where {@code n} is the maximum number of bytes. {@code n} must have a value between 1 and
* {@link Integer#MAX_VALUE} (both inclusive).
*
* @see VarBinaryType
*/
public static DataType VARBINARY(int n) {
return new AtomicDataType(new VarBinaryType(n));
}
/**
* Data type of a variable-length binary string (=a sequence of bytes) with defined maximum
* length. This is a shortcut for {@code VARBINARY(2147483647)} for representing JVM byte
* arrays.
*
* @see VarBinaryType
*/
public static DataType BYTES() {
return VARBINARY(Integer.MAX_VALUE);
}
/**
* Data type of a decimal number with fixed precision and scale {@code DECIMAL(p, s)} where
* {@code p} is the number of digits in a number (=precision) and {@code s} is the number of
* digits to the right of the decimal point in a number (=scale). {@code p} must have a value
* between 1 and 38 (both inclusive). {@code s} must have a value between 0 and {@code p} (both
* inclusive).
*
* @see DecimalType
*/
public static DataType DECIMAL(int precision, int scale) {
return new AtomicDataType(new DecimalType(precision, scale));
}
/**
* Data type of a 1-byte signed integer with values from -128 to 127.
*
* @see TinyIntType
*/
public static DataType TINYINT() {
return new AtomicDataType(new TinyIntType());
}
/**
* Data type of a 2-byte signed integer with values from -32,768 to 32,767.
*
* @see SmallIntType
*/
public static DataType SMALLINT() {
return new AtomicDataType(new SmallIntType());
}
/**
* Data type of a 4-byte signed integer with values from -2,147,483,648 to 2,147,483,647.
*
* @see IntType
*/
public static DataType INT() {
return new AtomicDataType(new IntType());
}
/**
* Data type of an 8-byte signed integer with values from -9,223,372,036,854,775,808 to
* 9,223,372,036,854,775,807.
*
* @see BigIntType
*/
public static DataType BIGINT() {
return new AtomicDataType(new BigIntType());
}
/**
* Data type of a 4-byte single precision floating point number.
*
* @see FloatType
*/
public static DataType FLOAT() {
return new AtomicDataType(new FloatType());
}
/**
* Data type of an 8-byte double precision floating point number.
*
* @see DoubleType
*/
public static DataType DOUBLE() {
return new AtomicDataType(new DoubleType());
}
/**
* Data type of a date consisting of {@code year-month-day} with values ranging from {@code
* 0000-01-01} to {@code 9999-12-31}.
*
* <p>Compared to the SQL standard, the range starts at year {@code 0000}.
*
* @see DataType
*/
public static DataType DATE() {
return new AtomicDataType(new DateType());
}
/**
* Data type of a time WITHOUT time zone {@code TIME(p)} where {@code p} is the number of digits
* of fractional seconds (=precision). {@code p} must have a value between 0 and 9 (both
* inclusive).
*
* <p>An instance consists of {@code hour:minute:second[.fractional]} with up to nanosecond
* precision and values ranging from {@code 00:00:00.000000000} to {@code 23:59:59.999999999}.
*
* <p>Compared to the SQL standard, leap seconds (23:59:60 and 23:59:61) are not supported as
* the semantics are closer to {@link java.time.LocalTime}. A time WITH time zone is not
* provided.
*
* @see #TIME()
* @see TimeType
*/
public static DataType TIME(int precision) {
return new AtomicDataType(new TimeType(precision));
}
/**
* Data type of a time WITHOUT time zone {@code TIME} with no fractional seconds by default.
*
* <p>An instance consists of {@code hour:minute:second} with up to second precision and values
* ranging from {@code 00:00:00} to {@code 23:59:59}.
*
* <p>Compared to the SQL standard, leap seconds (23:59:60 and 23:59:61) are not supported as
* the semantics are closer to {@link java.time.LocalTime}. A time WITH time zone is not
* provided.
*
* @see #TIME(int)
* @see TimeType
*/
public static DataType TIME() {
return new AtomicDataType(new TimeType());
}
/**
* Data type of a timestamp WITHOUT time zone {@code TIMESTAMP(p)} where {@code p} is the number
* of digits of fractional seconds (=precision). {@code p} must have a value between 0 and 9
* (both inclusive).
*
* <p>An instance consists of {@code year-month-day hour:minute:second[.fractional]} with up to
* nanosecond precision and values ranging from {@code 0000-01-01 00:00:00.000000000} to {@code
* 9999-12-31 23:59:59.999999999}.
*
* <p>Compared to the SQL standard, leap seconds (23:59:60 and 23:59:61) are not supported as
* the semantics are closer to {@link java.time.LocalDateTime}.
*
* @see #TIMESTAMP_WITH_TIME_ZONE(int)
* @see #TIMESTAMP_WITH_LOCAL_TIME_ZONE(int)
* @see TimestampType
*/
public static DataType TIMESTAMP(int precision) {
return new AtomicDataType(new TimestampType(precision));
}
/**
* Data type of a timestamp WITHOUT time zone {@code TIMESTAMP} with 6 digits of fractional
* seconds by default.
*
* <p>An instance consists of {@code year-month-day hour:minute:second[.fractional]} with up to
* microsecond precision and values ranging from {@code 0000-01-01 00:00:00.000000} to {@code
* 9999-12-31 23:59:59.999999}.
*
* <p>Compared to the SQL standard, leap seconds (23:59:60 and 23:59:61) are not supported as
* the semantics are closer to {@link java.time.LocalDateTime}.
*
* @see #TIMESTAMP(int)
* @see #TIMESTAMP_WITH_TIME_ZONE(int)
* @see #TIMESTAMP_WITH_LOCAL_TIME_ZONE(int)
* @see TimestampType
*/
public static DataType TIMESTAMP() {
return new AtomicDataType(new TimestampType());
}
/**
* Data type of a timestamp WITH time zone {@code TIMESTAMP(p) WITH TIME ZONE} where {@code p}
* is the number of digits of fractional seconds (=precision). {@code p} must have a value
* between 0 and 9 (both inclusive).
*
* <p>An instance consists of {@code year-month-day hour:minute:second[.fractional] zone} with
* up to nanosecond precision and values ranging from {@code 0000-01-01 00:00:00.000000000
* +14:59} to {@code 9999-12-31 23:59:59.999999999 -14:59}.
*
* <p>Compared to the SQL standard, leap seconds (23:59:60 and 23:59:61) are not supported as
* the semantics are closer to {@link java.time.OffsetDateTime}.
*
* @see #TIMESTAMP(int)
* @see #TIMESTAMP_WITH_LOCAL_TIME_ZONE(int)
* @see ZonedTimestampType
*/
public static DataType TIMESTAMP_WITH_TIME_ZONE(int precision) {
return new AtomicDataType(new ZonedTimestampType(precision));
}
/**
* Data type of a timestamp WITH time zone {@code TIMESTAMP WITH TIME ZONE} with 6 digits of
* fractional seconds by default.
*
* <p>An instance consists of {@code year-month-day hour:minute:second[.fractional] zone} with
* up to microsecond precision and values ranging from {@code 0000-01-01 00:00:00.000000 +14:59}
* to {@code 9999-12-31 23:59:59.999999 -14:59}.
*
* <p>Compared to the SQL standard, leap seconds (23:59:60 and 23:59:61) are not supported as
* the semantics are closer to {@link java.time.OffsetDateTime}.
*
* @see #TIMESTAMP_WITH_TIME_ZONE(int)
* @see #TIMESTAMP(int)
* @see #TIMESTAMP_WITH_LOCAL_TIME_ZONE(int)
* @see ZonedTimestampType
*/
public static DataType TIMESTAMP_WITH_TIME_ZONE() {
return new AtomicDataType(new ZonedTimestampType());
}
/**
* Data type of a timestamp WITH LOCAL time zone {@code TIMESTAMP(p) WITH LOCAL TIME ZONE} where
* {@code p} is the number of digits of fractional seconds (=precision). {@code p} must have a
* value between 0 and 9 (both inclusive).
*
* <p>An instance consists of {@code year-month-day hour:minute:second[.fractional] zone} with
* up to nanosecond precision and values ranging from {@code 0000-01-01 00:00:00.000000000
* +14:59} to {@code 9999-12-31 23:59:59.999999999 -14:59}. Leap seconds (23:59:60 and 23:59:61)
* are not supported as the semantics are closer to {@link java.time.OffsetDateTime}.
*
* <p>Compared to {@link ZonedTimestampType}, the time zone offset information is not stored
* physically in every datum. Instead, the type assumes {@link java.time.Instant} semantics in
* UTC time zone at the edges of the table ecosystem. Every datum is interpreted in the local
* time zone configured in the current session for computation and visualization.
*
* <p>This type fills the gap between time zone free and time zone mandatory timestamp types by
* allowing the interpretation of UTC timestamps according to the configured session timezone.
*
* @see #TIMESTAMP(int)
* @see #TIMESTAMP_WITH_TIME_ZONE(int)
* @see LocalZonedTimestampType
*/
public static DataType TIMESTAMP_WITH_LOCAL_TIME_ZONE(int precision) {
return new AtomicDataType(new LocalZonedTimestampType(precision));
}
/**
* Data type of a timestamp WITH LOCAL time zone. This is a synonym for {@link
* DataTypes#TIMESTAMP_WITH_LOCAL_TIME_ZONE(int)}.
*/
public static DataType TIMESTAMP_LTZ(int precision) {
return new AtomicDataType(new LocalZonedTimestampType(precision));
}
/**
* Data type of a timestamp WITH LOCAL time zone {@code TIMESTAMP WITH LOCAL TIME ZONE} with 6
* digits of fractional seconds by default.
*
* <p>An instance consists of {@code year-month-day hour:minute:second[.fractional] zone} with
* up to microsecond precision and values ranging from {@code 0000-01-01 00:00:00.000000 +14:59}
* to {@code 9999-12-31 23:59:59.999999 -14:59}. Leap seconds (23:59:60 and 23:59:61) are not
* supported as the semantics are closer to {@link java.time.OffsetDateTime}.
*
* <p>Compared to {@link ZonedTimestampType}, the time zone offset information is not stored
* physically in every datum. Instead, the type assumes {@link java.time.Instant} semantics in
* UTC time zone at the edges of the table ecosystem. Every datum is interpreted in the local
* time zone configured in the current session for computation and visualization.
*
* <p>This type fills the gap between time zone free and time zone mandatory timestamp types by
* allowing the interpretation of UTC timestamps according to the configured session timezone.
*
* @see #TIMESTAMP_WITH_LOCAL_TIME_ZONE(int)
* @see #TIMESTAMP(int)
* @see #TIMESTAMP_WITH_TIME_ZONE(int)
* @see LocalZonedTimestampType
*/
public static DataType TIMESTAMP_WITH_LOCAL_TIME_ZONE() {
return new AtomicDataType(new LocalZonedTimestampType());
}
/**
* Data type of a timestamp WITH LOCAL time zone. This is a synonym for {@link
* DataTypes#TIMESTAMP_WITH_LOCAL_TIME_ZONE()}.
*/
public static DataType TIMESTAMP_LTZ() {
return new AtomicDataType(new LocalZonedTimestampType());
}
/**
* Data type of a temporal interval. There are two types of temporal intervals: day-time
* intervals with up to nanosecond granularity or year-month intervals with up to month
* granularity.
*
* <p>An interval of day-time consists of {@code +days hours:months:seconds.fractional} with
* values ranging from {@code -999999 23:59:59.999999999} to {@code +999999 23:59:59.999999999}.
* The type must be parameterized to one of the following resolutions: interval of days,
* interval of days to hours, interval of days to minutes, interval of days to seconds, interval
* of hours, interval of hours to minutes, interval of hours to seconds, interval of minutes,
* interval of minutes to seconds, or interval of seconds. The value representation is the same
* for all types of resolutions. For example, an interval of seconds of 70 is always represented
* in an interval-of-days-to-seconds format (with default precisions): {@code +00
* 00:01:10.000000}).
*
* <p>An interval of year-month consists of {@code +years-months} with values ranging from
* {@code -9999-11} to {@code +9999-11}. The type must be parameterized to one of the following
* resolutions: interval of years, interval of years to months, or interval of months. The value
* representation is the same for all types of resolutions. For example, an interval of months
* of 50 is always represented in an interval-of-years-to-months format (with default year
* precision): {@code +04-02}.
*
* <p>Examples: {@code INTERVAL(DAY(2))} for a day-time interval or {@code INTERVAL(YEAR(4))}
* for a year-month interval.
*
* @see DayTimeIntervalType
* @see YearMonthIntervalType
*/
public static DataType INTERVAL(Resolution resolution) {
Preconditions.checkNotNull(resolution, "Interval resolution must not be null.");
return new AtomicDataType(Resolution.resolveInterval(resolution, null));
}
/**
* Data type of a temporal interval. There are two types of temporal intervals: day-time
* intervals with up to nanosecond granularity or year-month intervals with up to month
* granularity.
*
* <p>An interval of day-time consists of {@code +days hours:months:seconds.fractional} with
* values ranging from {@code -999999 23:59:59.999999999} to {@code +999999 23:59:59.999999999}.
* The type must be parameterized to one of the following resolutions: interval of days,
* interval of days to hours, interval of days to minutes, interval of days to seconds, interval
* of hours, interval of hours to minutes, interval of hours to seconds, interval of minutes,
* interval of minutes to seconds, or interval of seconds. The value representation is the same
* for all types of resolutions. For example, an interval of seconds of 70 is always represented
* in an interval-of-days-to-seconds format (with default precisions): {@code +00
* 00:01:10.000000}.
*
* <p>An interval of year-month consists of {@code +years-months} with values ranging from
* {@code -9999-11} to {@code +9999-11}. The type must be parameterized to one of the following
* resolutions: interval of years, interval of years to months, or interval of months. The value
* representation is the same for all types of resolutions. For example, an interval of months
* of 50 is always represented in an interval-of-years-to-months format (with default year
* precision): {@code +04-02}.
*
* <p>Examples: {@code INTERVAL(DAY(2), SECOND(9))} for a day-time interval or {@code
* INTERVAL(YEAR(4), MONTH())} for a year-month interval.
*
* @see DayTimeIntervalType
* @see YearMonthIntervalType
*/
public static DataType INTERVAL(Resolution upperResolution, Resolution lowerResolution) {
Preconditions.checkNotNull(upperResolution, "Upper interval resolution must not be null.");
Preconditions.checkNotNull(lowerResolution, "Lower interval resolution must not be null.");
return new AtomicDataType(Resolution.resolveInterval(upperResolution, lowerResolution));
}
/**
* Data type of an array of elements with same subtype.
*
* <p>Compared to the SQL standard, the maximum cardinality of an array cannot be specified but
* is fixed at {@link Integer#MAX_VALUE}. Also, any valid type is supported as a subtype.
*
* @see ArrayType
*/
public static DataType ARRAY(DataType elementDataType) {
Preconditions.checkNotNull(elementDataType, "Element data type must not be null.");
return new CollectionDataType(
new ArrayType(elementDataType.getLogicalType()), elementDataType);
}
/**
* Unresolved data type of an array of elements with same subtype.
*
* <p>Compared to the SQL standard, the maximum cardinality of an array cannot be specified but
* is fixed at {@link Integer#MAX_VALUE}. Also, any valid type is supported as a subtype.
*
* <p>Note: Compared to {@link #ARRAY(DataType)}, this method produces an {@link
* UnresolvedDataType}. In most of the cases, the {@link UnresolvedDataType} will be
* automatically resolved by the API. At other locations, a {@link DataTypeFactory} is provided.
*
* @see ArrayType
*/
public static UnresolvedDataType ARRAY(AbstractDataType<?> elementDataType) {
Preconditions.checkNotNull(elementDataType, "Element data type must not be null.");
return new UnresolvedDataType(
() -> String.format(ArrayType.FORMAT, elementDataType),
factory -> ARRAY(factory.createDataType(elementDataType)));
}
/**
* Data type of a multiset (=bag). Unlike a set, it allows for multiple instances for each of
* its elements with a common subtype. Each unique value (including {@code NULL}) is mapped to
* some multiplicity.
*
* <p>There is no restriction of element types; it is the responsibility of the user to ensure
* uniqueness.
*
* @see MultisetType
*/
public static DataType MULTISET(DataType elementDataType) {
Preconditions.checkNotNull(elementDataType, "Element data type must not be null.");
return new CollectionDataType(
new MultisetType(elementDataType.getLogicalType()), elementDataType);
}
/**
* Unresolved data type of a multiset (=bag). Unlike a set, it allows for multiple instances for
* each of its elements with a common subtype. Each unique value (including {@code NULL}) is
* mapped to some multiplicity.
*
* <p>There is no restriction of element types; it is the responsibility of the user to ensure
* uniqueness.
*
* <p>Note: Compared to {@link #MULTISET(DataType)}, this method produces an {@link
* UnresolvedDataType}. In most of the cases, the {@link UnresolvedDataType} will be
* automatically resolved by the API. At other locations, a {@link DataTypeFactory} is provided.
*
* @see MultisetType
*/
public static UnresolvedDataType MULTISET(AbstractDataType<?> elementDataType) {
Preconditions.checkNotNull(elementDataType, "Element data type must not be null.");
return new UnresolvedDataType(
() -> String.format(MultisetType.FORMAT, elementDataType),
factory -> MULTISET(factory.createDataType(elementDataType)));
}
/**
* Data type of an associative array that maps keys (including {@code NULL}) to values
* (including {@code NULL}). A map cannot contain duplicate keys; each key can map to at most
* one value.
*
* <p>There is no restriction of key types; it is the responsibility of the user to ensure
* uniqueness. The map type is an extension to the SQL standard.
*
* @see MapType
*/
public static DataType MAP(DataType keyDataType, DataType valueDataType) {
Preconditions.checkNotNull(keyDataType, "Key data type must not be null.");
Preconditions.checkNotNull(valueDataType, "Value data type must not be null.");
return new KeyValueDataType(
new MapType(keyDataType.getLogicalType(), valueDataType.getLogicalType()),
keyDataType,
valueDataType);
}
/**
* Unresolved data type of an associative array that maps keys (including {@code NULL}) to
* values (including {@code NULL}). A map cannot contain duplicate keys; each key can map to at
* most one value.
*
* <p>There is no restriction of key types; it is the responsibility of the user to ensure
* uniqueness. The map type is an extension to the SQL standard.
*
* <p>Note: Compared to {@link #MAP(DataType, DataType)}, this method produces an {@link
* UnresolvedDataType}. In most of the cases, the {@link UnresolvedDataType} will be
* automatically resolved by the API. At other locations, a {@link DataTypeFactory} is provided.
*
* @see MapType
*/
public static UnresolvedDataType MAP(
AbstractDataType<?> keyDataType, AbstractDataType<?> valueDataType) {
Preconditions.checkNotNull(keyDataType, "Key data type must not be null.");
Preconditions.checkNotNull(valueDataType, "Value data type must not be null.");
return new UnresolvedDataType(
() -> String.format(MapType.FORMAT, keyDataType, valueDataType),
factory -> MAP(
factory.createDataType(keyDataType),
factory.createDataType(valueDataType)));
}
/**
* Data type of a sequence of fields. A field consists of a field name, field type, and an
* optional description. The most specific type of a row of a table is a row type. In this case,
* each column of the row corresponds to the field of the row type that has the same ordinal
* position as the column.
*
* <p>Compared to the SQL standard, an optional field description simplifies the handling with
* complex structures.
*
* <p>Use {@link #FIELD(String, DataType)} or {@link #FIELD(String, DataType, String)} to
* construct fields.
*
* @see RowType
*/
public static DataType ROW(Field... fields) {
final List<RowField> logicalFields =
Stream.of(fields)
.map(
f -> Preconditions.checkNotNull(
f, "Field definition must not be null."))
.map(f -> new RowField(f.name, f.dataType.getLogicalType(), f.description))
.collect(Collectors.toList());
final List<DataType> fieldDataTypes =
Stream.of(fields).map(f -> f.dataType).collect(Collectors.toList());
return new FieldsDataType(new RowType(logicalFields), fieldDataTypes);
}
/** @see #ROW(Field...) */
public static DataType ROW(List<Field> fields) {
return ROW(fields.toArray(new Field[0]));
}
/**
* Data type of a sequence of fields.
*
* <p>This is shortcut for {@link #ROW(Field...)} where the field names will be generated using
* {@code f0, f1, f2, ...}.
*/
public static DataType ROW(DataType... fieldDataTypes) {
return ROW(
IntStream.range(0, fieldDataTypes.length)
.mapToObj(idx -> FIELD("f" + idx, fieldDataTypes[idx]))
.toArray(Field[]::new));
}
/**
* Data type of a row type with no fields. It only exists for completeness.
*
* @see #ROW(Field...)
*/
public static DataType ROW() {
return ROW(new Field[0]);
}
/**
* Unresolved data type of a sequence of fields. A field consists of a field name, field type,
* and an optional description. The most specific type of a row of a table is a row type. In
* this case, each column of the row corresponds to the field of the row type that has the same
* ordinal position as the column.
*
* <p>Compared to the SQL standard, an optional field description simplifies the handling with
* complex structures.
*
* <p>Use {@link #FIELD(String, AbstractDataType)} or {@link #FIELD(String, AbstractDataType,
* String)} to construct fields.
*
* <p>Note: Compared to {@link #ROW(Field...)} )}, this method produces an {@link
* UnresolvedDataType} with {@link UnresolvedField}s. In most of the cases, the {@link
* UnresolvedDataType} will be automatically resolved by the API. At other locations, a {@link
* DataTypeFactory} is provided.
*
* @see RowType
*/
public static UnresolvedDataType ROW(AbstractField... fields) {
Stream.of(fields)
.forEach(f -> Preconditions.checkNotNull(f, "Field definition must not be null."));
return new UnresolvedDataType(
() -> String.format(
RowType.FORMAT,
Stream.of(fields)
.map(Object::toString)
.collect(Collectors.joining(", "))),
factory -> {
final Field[] fieldsArray =
Stream.of(fields)
.map(
f -> new Field(
f.name,
factory.createDataType(
f.getAbstractDataType()),
f.description))
.toArray(Field[]::new);
return ROW(fieldsArray);
});
}
/**
* Data type of a sequence of fields.
*
* <p>This is shortcut for {@link #ROW(AbstractField...)} where the field names will be
* generated using {@code f0, f1, f2, ...}.
*/
public static UnresolvedDataType ROW(AbstractDataType<?>... fieldDataTypes) {
return ROW(
IntStream.range(0, fieldDataTypes.length)
.mapToObj(idx -> FIELD("f" + idx, fieldDataTypes[idx]))
.toArray(AbstractField[]::new));
}
/**
* Data type for representing untyped {@code NULL} values. A null type has no other value except
* {@code NULL}, thus, it can be cast to any nullable type similar to JVM semantics.
*
* <p>This type helps in representing unknown types in API calls that use a {@code NULL} literal
* as well as bridging to formats such as JSON or Avro that define such a type as well.
*
* <p>The null type is an extension to the SQL standard.
*
* <p>Note: The runtime does not support this type. It is a pure helper type during translation
* and planning. Table columns cannot be declared with this type. Functions cannot declare
* return types of this type.
*
* @see NullType
*/
public static DataType NULL() {
return new AtomicDataType(new NullType());
}
/**
* Data type of an arbitrary serialized type. This type is a black box within the table
* ecosystem and is only deserialized at the edges.
*
* <p>The raw type is an extension to the SQL standard.
*
* <p>This method assumes that a {@link TypeSerializer} instance is present. Use {@link
* #RAW(Class)} for automatically generating a serializer.
*
* @param clazz originating value class
* @param serializer type serializer
* @see RawType
*/
public static <T> DataType RAW(Class<T> clazz, TypeSerializer<T> serializer) {
return new AtomicDataType(new RawType<>(clazz, serializer));
}
/**
* Unresolved data type of an arbitrary serialized type. This type is a black box within the
* table ecosystem and is only deserialized at the edges.
*
* <p>The raw type is an extension to the SQL standard.
*
* <p>Compared to {@link #RAW(Class, TypeSerializer)}, this method produces an {@link
* UnresolvedDataType} where no serializer is known and a generic serializer should be used.
* During the resolution, a {@link DataTypes#RAW(Class, TypeSerializer)} with Flink's default
* RAW serializer is created and automatically configured.
*
* <p>Note: In most of the cases, the {@link UnresolvedDataType} will be automatically resolved
* by the API. At other locations, a {@link DataTypeFactory} is provided.
*
* @see RawType
*/
public static <T> UnresolvedDataType RAW(Class<T> clazz) {
return new UnresolvedDataType(
() -> String.format(RawType.FORMAT, clazz.getName(), "?"),
factory -> factory.createRawDataType(clazz));
}
/**
* Data type of a user-defined object structured type. Structured types contain zero, one or
* more attributes. Each attribute consists of a name and a type. A type cannot be defined so
* that one of its attribute types (transitively) uses itself.
*
* <p>There are two kinds of structured types. Types that are stored in a catalog and are
* identified by an {@link ObjectIdentifier} or anonymously defined, unregistered types (usually
* reflectively extracted) that are identified by an implementation {@link Class}.
*
* <p>This method helps in manually constructing anonymous, unregistered types. This is useful
* in cases where the reflective extraction using {@link DataTypes#of(Class)} is not applicable.
* However, {@link DataTypes#of(Class)} is the recommended way of creating inline structured
* types as it also considers {@link DataTypeHint}s.
*
* <p>Structured types are converted to internal data structures by the runtime. The given
* implementation class is only used at the edges of the table ecosystem (e.g. when bridging to
* a function or connector). Serialization and equality ({@code hashCode/equals}) are handled by
* the runtime based on the logical type. An implementation class must offer a default
* constructor with zero arguments or a full constructor that assigns all attributes.
*
* <p>Note: A caller of this method must make sure that the {@link
* DataType#getConversionClass()} of the given fields matches with the attributes of the given
* implementation class, otherwise an exception might be thrown during runtime.
*
* @see DataTypes#of(Class)
* @see StructuredType
*/
public static <T> DataType STRUCTURED(Class<T> implementationClass, Field... fields) {
// some basic validation of the class to prevent common mistakes
ExtractionUtils.validateStructuredClass(implementationClass);
final StructuredType.Builder builder = StructuredType.newBuilder(implementationClass);
final List<StructuredAttribute> attributes =
Stream.of(fields)
.map(
f -> new StructuredAttribute(
f.getName(),
f.getDataType().getLogicalType(),
f.getDescription().orElse(null)))
.collect(Collectors.toList());
builder.attributes(attributes);
builder.setFinal(true);
builder.setInstantiable(true);
final List<DataType> fieldDataTypes =
Stream.of(fields).map(DataTypes.Field::getDataType).collect(Collectors.toList());
return new FieldsDataType(builder.build(), implementationClass, fieldDataTypes);
}
// --------------------------------------------------------------------------------------------
// Helper functions
// --------------------------------------------------------------------------------------------
/**
* Resolution in seconds with 6 digits for fractional seconds by default.
*
* @see #SECOND(int)
*/
public static Resolution SECOND() {
return new Resolution(
Resolution.IntervalUnit.SECOND, DayTimeIntervalType.DEFAULT_FRACTIONAL_PRECISION);
}
/**
* Resolution in seconds and (possibly) fractional seconds. The precision is the number of
* digits of fractional seconds. It must have a value between 0 and 9 (both inclusive). If no
* fractional is specified, it is equal to 6 by default.
*
* @see #SECOND()
*/
public static Resolution SECOND(int precision) {
return new Resolution(Resolution.IntervalUnit.SECOND, precision);
}
/** Resolution in minutes. */
public static Resolution MINUTE() {
return new Resolution(Resolution.IntervalUnit.MINUTE);
}
/** Resolution in hours. */
public static Resolution HOUR() {
return new Resolution(Resolution.IntervalUnit.HOUR);
}
/**
* Resolution in days. The precision is the number of digits of days. It must have a value
* between 1 and 6 (both inclusive). If no precision is specified, it is equal to 2 by default.
*
* @see #DAY()
*/
public static Resolution DAY(int precision) {
return new Resolution(Resolution.IntervalUnit.DAY, precision);
}
/**
* Resolution in days with 2 digits for the number of days by default.
*
* @see #DAY(int)
*/
public static Resolution DAY() {
return new Resolution(
Resolution.IntervalUnit.DAY, DayTimeIntervalType.DEFAULT_DAY_PRECISION);
}
/** Resolution in months. */
public static Resolution MONTH() {
return new Resolution(Resolution.IntervalUnit.MONTH);
}
/**
* Resolution in years. The precision is the number of digits of years. It must have a value
* between 1 and 4 (both inclusive). If no precision is specified, it is equal to 2.
*
* @see #YEAR()
*/
public static Resolution YEAR(int precision) {
return new Resolution(Resolution.IntervalUnit.YEAR, precision);
}
/**
* Resolution in years with 2 digits for the number of years by default.
*
* @see #YEAR(int)
*/
public static Resolution YEAR() {
return new Resolution(
Resolution.IntervalUnit.YEAR, YearMonthIntervalType.DEFAULT_PRECISION);
}
/** Field definition with field name and data type. */
public static Field FIELD(String name, DataType dataType) {
return new Field(
Preconditions.checkNotNull(name, "Field name must not be null."),
Preconditions.checkNotNull(dataType, "Field data type must not be null."),
null);
}
/** Field definition with field name, data type, and a description. */
public static Field FIELD(String name, DataType dataType, String description) {
return new Field(
Preconditions.checkNotNull(name, "Field name must not be null."),
Preconditions.checkNotNull(dataType, "Field data type must not be null."),
Preconditions.checkNotNull(description, "Field description must not be null."));
}
/**
* Unresolved field definition with field name and data type.
*
* <p>Note: Compared to {@link #FIELD(String, DataType)}, this method produces an {@link
* UnresolvedField} that can contain an {@link UnresolvedDataType}.
*/
public static UnresolvedField FIELD(String name, AbstractDataType<?> fieldDataType) {
return new UnresolvedField(
Preconditions.checkNotNull(name, "Field name must not be null."),
Preconditions.checkNotNull(fieldDataType, "Field data type must not be null."),
null);
}
/**
* Unresolved field definition with field name, unresolved data type, and a description.
*
* <p>Note: Compared to {@link #FIELD(String, DataType, String)}, this method produces an {@link
* UnresolvedField} that can contain an {@link UnresolvedDataType}.
*/
public static UnresolvedField FIELD(
String name, AbstractDataType<?> fieldDataType, String description) {
return new UnresolvedField(
Preconditions.checkNotNull(name, "Field name must not be null."),
Preconditions.checkNotNull(fieldDataType, "Field data type must not be null."),
Preconditions.checkNotNull(description, "Field description must not be null."));
}
// --------------------------------------------------------------------------------------------
// Helper classes
// --------------------------------------------------------------------------------------------
/**
* Helper class for defining the resolution of an interval.
*
* @see #INTERVAL(Resolution)
*/
@PublicEvolving
public static final class Resolution {
private static final int EMPTY_PRECISION = -1;
private enum IntervalUnit {
SECOND,
MINUTE,
HOUR,
DAY,
MONTH,
YEAR
}
private static final Map<List<IntervalUnit>, BiFunction<Integer, Integer, LogicalType>> resolutionMapping =
new HashMap<>();
static {
addResolutionMapping(
IntervalUnit.YEAR,
null,
(p1, p2) -> new YearMonthIntervalType(YearMonthResolution.YEAR, p1));
addResolutionMapping(
IntervalUnit.MONTH,
null,
(p1, p2) -> new YearMonthIntervalType(YearMonthResolution.MONTH));
addResolutionMapping(
IntervalUnit.YEAR,
IntervalUnit.MONTH,
(p1, p2) -> new YearMonthIntervalType(YearMonthResolution.YEAR_TO_MONTH, p1));
addResolutionMapping(
IntervalUnit.DAY,
null,
(p1, p2) -> new DayTimeIntervalType(
DayTimeResolution.DAY,
p1,
DayTimeIntervalType.DEFAULT_FRACTIONAL_PRECISION));
addResolutionMapping(
IntervalUnit.DAY,
IntervalUnit.HOUR,
(p1, p2) -> new DayTimeIntervalType(
DayTimeResolution.DAY_TO_HOUR,
p1,
DayTimeIntervalType.DEFAULT_FRACTIONAL_PRECISION));
addResolutionMapping(
IntervalUnit.DAY,
IntervalUnit.MINUTE,
(p1, p2) -> new DayTimeIntervalType(
DayTimeResolution.DAY_TO_MINUTE,
p1,
DayTimeIntervalType.DEFAULT_FRACTIONAL_PRECISION));
addResolutionMapping(
IntervalUnit.DAY,
IntervalUnit.SECOND,
(p1, p2) -> new DayTimeIntervalType(DayTimeResolution.DAY_TO_SECOND, p1, p2));
addResolutionMapping(
IntervalUnit.HOUR,
null,
(p1, p2) -> new DayTimeIntervalType(DayTimeResolution.HOUR));
addResolutionMapping(
IntervalUnit.HOUR,
IntervalUnit.MINUTE,
(p1, p2) -> new DayTimeIntervalType(DayTimeResolution.HOUR_TO_MINUTE));
addResolutionMapping(
IntervalUnit.HOUR,
IntervalUnit.SECOND,
(p1, p2) -> new DayTimeIntervalType(
DayTimeResolution.HOUR_TO_SECOND,
DayTimeIntervalType.DEFAULT_DAY_PRECISION,
p2));
addResolutionMapping(
IntervalUnit.MINUTE,
null,
(p1, p2) -> new DayTimeIntervalType(DayTimeResolution.MINUTE));
addResolutionMapping(
IntervalUnit.MINUTE,
IntervalUnit.SECOND,
(p1, p2) -> new DayTimeIntervalType(
DayTimeResolution.MINUTE_TO_SECOND,
DayTimeIntervalType.DEFAULT_DAY_PRECISION,
p2));
addResolutionMapping(
IntervalUnit.SECOND,
null,
(p1, p2) -> new DayTimeIntervalType(
DayTimeResolution.SECOND,
DayTimeIntervalType.DEFAULT_DAY_PRECISION,
p1));
}
private static void addResolutionMapping(
IntervalUnit leftUnit,
IntervalUnit rightUnit,
BiFunction<Integer, Integer, LogicalType> typeProvider) {
resolutionMapping.put(Arrays.asList(leftUnit, rightUnit), typeProvider);
}
private static LogicalType resolveInterval(
Resolution fromResolution, @Nullable Resolution toResolution) {
final IntervalUnit toBoundary = toResolution == null ? null : toResolution.unit;
final int toPrecision = toResolution == null ? EMPTY_PRECISION : toResolution.precision;
final BiFunction<Integer, Integer, LogicalType> typeProvider =
resolutionMapping.get(Arrays.asList(fromResolution.unit, toBoundary));
if (typeProvider == null) {
throw new ValidationException(
String.format(
"Unsupported interval definition '%s TO %s'. "
+ "Please check the documentation for supported combinations for year-month and day-time intervals.",
fromResolution.unit, toBoundary));
}
return typeProvider.apply(fromResolution.precision, toPrecision);
}
private final int precision;
private final IntervalUnit unit;
private Resolution(IntervalUnit unit, int precision) {
this.unit = unit;
this.precision = precision;
}
private Resolution(IntervalUnit unit) {
this(unit, EMPTY_PRECISION);
}
@Override
public String toString() {
if (precision != EMPTY_PRECISION) {
return String.format("%s(%d)", unit, precision);
}
return unit.toString();
}
}
/**
* Common helper class for resolved and unresolved fields of a row or structured type.
*
* @see #FIELD(String, DataType)
* @see #FIELD(String, DataType, String)
* @see #FIELD(String, AbstractDataType)
* @see #FIELD(String, AbstractDataType, String)
*/
@PublicEvolving
public abstract static class AbstractField {
protected final String name;
protected final @Nullable String description;
private AbstractField(String name, @Nullable String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public Optional<String> getDescription() {
return Optional.ofNullable(description);
}
protected abstract AbstractDataType<?> getAbstractDataType();
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AbstractField that = (AbstractField) o;
return name.equals(that.name) && Objects.equals(description, that.description);
}
@Override
public int hashCode() {
return Objects.hash(name, description);
}
@Override
public String toString() {
if (description != null) {
return String.format(
RowField.FIELD_FORMAT_WITH_DESCRIPTION,
name,
getAbstractDataType(),
description);
}
return String.format(RowField.FIELD_FORMAT_NO_DESCRIPTION, name, getAbstractDataType());
}
}
/**
* Helper class for defining the field of a row or structured type.
*
* @see #FIELD(String, DataType)
* @see #FIELD(String, DataType, String)
*/
@PublicEvolving
public static final class Field extends AbstractField {
private final DataType dataType;
private Field(String name, DataType dataType, @Nullable String description) {
super(name, description);
this.dataType = dataType;
}
public DataType getDataType() {
return dataType;
}
@Override
protected AbstractDataType<?> getAbstractDataType() {
return dataType;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
Field field = (Field) o;
return dataType.equals(field.dataType);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), dataType);
}
}
/**
* Helper class for defining the unresolved field of a row or structured type.
*
* <p>Compared to {@link Field}, an unresolved field can contain an {@link UnresolvedDataType}.
*
* @see #FIELD(String, AbstractDataType)
* @see #FIELD(String, AbstractDataType, String)
*/
@PublicEvolving
public static final class UnresolvedField extends AbstractField {
private final AbstractDataType<?> dataType;
private UnresolvedField(
String name, AbstractDataType<?> dataType, @Nullable String description) {
super(name, description);
this.dataType = dataType;
}
@Override
protected AbstractDataType<?> getAbstractDataType() {
return dataType;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
UnresolvedField that = (UnresolvedField) o;
return dataType.equals(that.dataType);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), dataType);
}
}
private DataTypes() {
// no instances
}
// CHECKSTYLE.ON: MethodName
}
......@@ -77,7 +77,7 @@ import org.slf4j.LoggerFactory;
* @author wenmo
* @since 2022/4/12 21:28
**/
public abstract class AbstractSinkBuilder {
public abstract class AbstractSinkBuilder implements SinkBuilder {
protected static final Logger logger = LoggerFactory.getLogger(AbstractSinkBuilder.class);
......@@ -104,7 +104,7 @@ public abstract class AbstractSinkBuilder {
Map<String, String> sink = config.getSink();
for (Map.Entry<String, String> entry : sink.entrySet()) {
if (Asserts.isNotNullString(entry.getKey()) && entry.getKey().startsWith("properties") && Asserts.isNotNullString(entry.getValue())) {
properties.setProperty(entry.getKey().replace("properties.",""), entry.getValue());
properties.setProperty(entry.getKey().replace("properties.", ""), entry.getValue());
}
}
return properties;
......@@ -137,9 +137,9 @@ public abstract class AbstractSinkBuilder {
}
protected DataStream<Map> shunt(
SingleOutputStreamOperator<Map> processOperator,
Table table,
OutputTag<Map> tag) {
SingleOutputStreamOperator<Map> processOperator,
Table table,
OutputTag<Map> tag) {
return processOperator.getSideOutput(tag);
}
......@@ -207,6 +207,7 @@ public abstract class AbstractSinkBuilder {
List<String> columnNameList,
List<LogicalType> columnTypeList);
@Override
public DataStreamSource build(
CDCBuilder cdcBuilder,
StreamExecutionEnvironment env,
......@@ -307,7 +308,8 @@ public abstract class AbstractSinkBuilder {
}
}
protected String getSinkSchemaName(Table table) {
@Override
public String getSinkSchemaName(Table table) {
String schemaName = table.getSchema();
if (config.getSink().containsKey("sink.db")) {
schemaName = config.getSink().get("sink.db");
......@@ -315,7 +317,8 @@ public abstract class AbstractSinkBuilder {
return schemaName;
}
protected String getSinkTableName(Table table) {
@Override
public String getSinkTableName(Table table) {
String tableName = table.getName();
if (config.getSink().containsKey("table.prefix.schema")) {
if (Boolean.valueOf(config.getSink().get("table.prefix.schema"))) {
......
......@@ -19,6 +19,7 @@
package com.dlink.cdc;
import com.dlink.exception.SplitTableException;
import com.dlink.model.FlinkCDCConfig;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
......@@ -48,4 +49,8 @@ public interface CDCBuilder {
Map<String, Map<String, String>> parseMetaDataConfigs();
String getSchemaFieldName();
default Map<String, String> parseMetaDataConfig() {
throw new SplitTableException("此数据源并未实现分库分表");
}
}
......@@ -21,6 +21,7 @@ package com.dlink.cdc;
import com.dlink.executor.CustomTableEnvironment;
import com.dlink.model.FlinkCDCConfig;
import com.dlink.model.Table;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
......@@ -38,4 +39,8 @@ public interface SinkBuilder {
SinkBuilder create(FlinkCDCConfig config);
DataStreamSource build(CDCBuilder cdcBuilder, StreamExecutionEnvironment env, CustomTableEnvironment customTableEnvironment, DataStreamSource<String> dataStreamSource);
String getSinkSchemaName(Table table);
String getSinkTableName(Table table);
}
......@@ -45,7 +45,7 @@ import java.util.Properties;
* @author wenmo
* @since 2022/4/20 19:20
**/
public class DorisSinkBuilder extends AbstractSinkBuilder implements SinkBuilder, Serializable {
public class DorisSinkBuilder extends AbstractSinkBuilder implements Serializable {
private static final String KEY_WORD = "datastream-doris";
private static final long serialVersionUID = 8330362249137471854L;
......
......@@ -38,7 +38,6 @@ import java.util.Properties;
import com.alibaba.ververica.cdc.connectors.mysql.MySQLSource;
import com.alibaba.ververica.cdc.connectors.mysql.table.StartupOptions;
import com.alibaba.ververica.cdc.debezium.StringDebeziumDeserializationSchema;
/**
* MysqlCDCBuilder
......@@ -94,7 +93,7 @@ public class MysqlCDCBuilder extends AbstractCDCBuilder implements CDCBuilder {
} else {
sourceBuilder.tableList(new String[0]);
}
sourceBuilder.deserializer(new StringDebeziumDeserializationSchema());
sourceBuilder.deserializer(new MysqlJsonDebeziumDeserializationSchema());
sourceBuilder.debeziumProperties(properties);
if (Asserts.isNotNullString(config.getStartupMode())) {
switch (config.getStartupMode().toLowerCase()) {
......
/*
*
* 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 com.dlink.cdc.mysql;
import org.apache.flink.api.common.typeinfo.BasicTypeInfo;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.util.Collector;
import org.apache.kafka.connect.json.JsonConverter;
import org.apache.kafka.connect.source.SourceRecord;
import org.apache.kafka.connect.storage.ConverterType;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.ververica.cdc.debezium.DebeziumDeserializationSchema;
/**
* @version 1.0
* @className: com.dlink.cdc.mysql.MysqlJsonDebeziumDeserializationSchema
* @Description:
* @author: jack zhong
*/
public class MysqlJsonDebeziumDeserializationSchema implements DebeziumDeserializationSchema<String> {
private static final long serialVersionUID = 1L;
private transient JsonConverter jsonConverter;
private final Boolean includeSchema;
private Map<String, Object> customConverterConfigs;
public MysqlJsonDebeziumDeserializationSchema() {
this(false);
}
public MysqlJsonDebeziumDeserializationSchema(Boolean includeSchema) {
this.includeSchema = includeSchema;
}
public MysqlJsonDebeziumDeserializationSchema(Boolean includeSchema, Map<String, Object> customConverterConfigs) {
this.includeSchema = includeSchema;
this.customConverterConfigs = customConverterConfigs;
}
public void deserialize(SourceRecord record, Collector<String> out) throws Exception {
if (this.jsonConverter == null) {
this.initializeJsonConverter();
}
byte[] bytes = this.jsonConverter.fromConnectData(record.topic(), record.valueSchema(), record.value());
out.collect(new String(bytes, StandardCharsets.UTF_8));
}
private void initializeJsonConverter() {
this.jsonConverter = new JsonConverter();
HashMap<String, Object> configs = new HashMap(2);
configs.put("converter.type", ConverterType.VALUE.getName());
configs.put("schemas.enable", this.includeSchema);
if (this.customConverterConfigs != null) {
configs.putAll(this.customConverterConfigs);
}
this.jsonConverter.configure(configs);
}
public TypeInformation<String> getProducedType() {
return BasicTypeInfo.STRING_TYPE_INFO;
}
}
/*
*
* 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 com.dlink.cdc.mysql;
import org.apache.flink.api.common.typeinfo.BasicTypeInfo;
......
......@@ -34,8 +34,8 @@ import java.util.List;
import java.util.Map;
import java.util.Properties;
import com.ververica.cdc.connectors.base.options.StartupOptions;
import com.ververica.cdc.connectors.oracle.OracleSource;
import com.ververica.cdc.connectors.oracle.table.StartupOptions;
import com.ververica.cdc.debezium.JsonDebeziumDeserializationSchema;
/**
......
/*
*
* 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.flink.shaded.guava30.com.google.common.util.concurrent;
import org.apache.flink.shaded.guava30.com.google.common.base.Preconditions;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;
public final class ThreadFactoryBuilder {
private String nameFormat = null;
private Boolean daemon = null;
private Integer priority = null;
private Thread.UncaughtExceptionHandler uncaughtExceptionHandler = null;
private ThreadFactory backingThreadFactory = null;
public ThreadFactoryBuilder() {
}
public ThreadFactoryBuilder setNameFormat(String nameFormat) {
String.format(nameFormat, 0);
this.nameFormat = nameFormat;
return this;
}
public ThreadFactoryBuilder setDaemon(boolean daemon) {
this.daemon = daemon;
return this;
}
public ThreadFactoryBuilder setPriority(int priority) {
Preconditions.checkArgument(priority >= 1, "Thread priority (%s) must be >= %s", new Object[]{priority, 1});
Preconditions.checkArgument(priority <= 10, "Thread priority (%s) must be <= %s", new Object[]{priority, 10});
this.priority = priority;
return this;
}
public ThreadFactoryBuilder setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler uncaughtExceptionHandler) {
this.uncaughtExceptionHandler =
(Thread.UncaughtExceptionHandler) Preconditions.checkNotNull(uncaughtExceptionHandler);
return this;
}
public ThreadFactoryBuilder setThreadFactory(ThreadFactory backingThreadFactory) {
this.backingThreadFactory = (ThreadFactory) Preconditions.checkNotNull(backingThreadFactory);
return this;
}
public ThreadFactory build() {
return build(this);
}
private static ThreadFactory build(ThreadFactoryBuilder builder) {
final String nameFormat = builder.nameFormat;
final Boolean daemon = builder.daemon;
final Integer priority = builder.priority;
final Thread.UncaughtExceptionHandler uncaughtExceptionHandler = builder.uncaughtExceptionHandler;
final ThreadFactory backingThreadFactory =
builder.backingThreadFactory != null ? builder.backingThreadFactory : Executors.defaultThreadFactory();
final AtomicLong count = nameFormat != null ? new AtomicLong(0L) : null;
return new ThreadFactory() {
public Thread newThread(Runnable runnable) {
Thread thread = backingThreadFactory.newThread(runnable);
if (nameFormat != null) {
thread.setName(String.format(nameFormat, count.getAndIncrement()));
}
if (daemon != null) {
thread.setDaemon(daemon);
}
if (priority != null) {
thread.setPriority(priority);
}
if (uncaughtExceptionHandler != null) {
thread.setUncaughtExceptionHandler(uncaughtExceptionHandler);
}
return thread;
}
};
}
}
/*
*
* 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 com.dlink.cdc.mysql;
import org.apache.flink.api.common.typeinfo.BasicTypeInfo;
......
......@@ -34,8 +34,8 @@ import java.util.List;
import java.util.Map;
import java.util.Properties;
import com.ververica.cdc.connectors.base.options.StartupOptions;
import com.ververica.cdc.connectors.oracle.OracleSource;
import com.ververica.cdc.connectors.oracle.table.StartupOptions;
import com.ververica.cdc.debezium.JsonDebeziumDeserializationSchema;
/**
......
/*
*
* 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 com.dlink.cdc.mysql;
import org.apache.flink.api.common.typeinfo.BasicTypeInfo;
......
......@@ -34,8 +34,8 @@ import java.util.List;
import java.util.Map;
import java.util.Properties;
import com.ververica.cdc.connectors.base.options.StartupOptions;
import com.ververica.cdc.connectors.oracle.OracleSource;
import com.ververica.cdc.connectors.oracle.table.StartupOptions;
import com.ververica.cdc.debezium.JsonDebeziumDeserializationSchema;
/**
......
<?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"
<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>
<artifactId>dlink-client</artifactId>
<groupId>com.dlink</groupId>
<artifactId>dlink-client</artifactId>
<version>0.6.8-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>dlink-client-1.16</artifactId>
......@@ -44,6 +43,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven-jar-plugin.version}</version>
<configuration>
<!-- 指定打包的jar包输出路径 -->
<outputDirectory>${project.parent.parent.basedir}/build/extends</outputDirectory>
......@@ -51,4 +51,4 @@
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
</project>
......@@ -26,6 +26,7 @@ import com.dlink.model.FlinkCDCConfig;
import com.dlink.model.Schema;
import com.dlink.model.Table;
import com.dlink.utils.JSONUtil;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
......@@ -56,8 +57,6 @@ import org.apache.flink.table.types.logical.VarCharType;
import org.apache.flink.types.RowKind;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
import java.sql.Timestamp;
......@@ -69,6 +68,9 @@ import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* AbstractCDCBuilder
*
......@@ -101,8 +103,9 @@ public abstract class AbstractSinkBuilder implements SinkBuilder {
Properties properties = new Properties();
Map<String, String> sink = config.getSink();
for (Map.Entry<String, String> entry : sink.entrySet()) {
if (Asserts.isNotNullString(entry.getKey()) && entry.getKey().startsWith("properties") && Asserts.isNotNullString(entry.getValue())) {
properties.setProperty(entry.getKey().replace("properties.",""), entry.getValue());
if (Asserts.isNotNullString(entry.getKey()) && entry.getKey().startsWith("properties")
&& Asserts.isNotNullString(entry.getValue())) {
properties.setProperty(entry.getKey().replace("properties.", ""), entry.getValue());
}
}
return properties;
......@@ -110,6 +113,7 @@ public abstract class AbstractSinkBuilder implements SinkBuilder {
protected SingleOutputStreamOperator<Map> deserialize(DataStreamSource<String> dataStreamSource) {
return dataStreamSource.map(new MapFunction<String, Map>() {
@Override
public Map map(String value) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
......@@ -119,97 +123,105 @@ public abstract class AbstractSinkBuilder implements SinkBuilder {
}
protected SingleOutputStreamOperator<Map> shunt(
SingleOutputStreamOperator<Map> mapOperator,
Table table,
String schemaFieldName) {
SingleOutputStreamOperator<Map> mapOperator,
Table table,
String schemaFieldName) {
final String tableName = table.getName();
final String schemaName = table.getSchema();
return mapOperator.filter(new FilterFunction<Map>() {
@Override
public boolean filter(Map value) throws Exception {
LinkedHashMap source = (LinkedHashMap) value.get("source");
return tableName.equals(source.get("table").toString())
&& schemaName.equals(source.get(schemaFieldName).toString());
&& schemaName.equals(source.get(schemaFieldName).toString());
}
});
}
protected DataStream<Map> shunt(
SingleOutputStreamOperator<Map> processOperator,
Table table,
OutputTag<Map> tag) {
SingleOutputStreamOperator<Map> processOperator,
Table table,
OutputTag<Map> tag) {
return processOperator.getSideOutput(tag);
}
protected DataStream<RowData> buildRowData(
SingleOutputStreamOperator<Map> filterOperator,
List<String> columnNameList,
List<LogicalType> columnTypeList,
String schemaTableName) {
SingleOutputStreamOperator<Map> filterOperator,
List<String> columnNameList,
List<LogicalType> columnTypeList,
String schemaTableName) {
return filterOperator
.flatMap(new FlatMapFunction<Map, RowData>() {
@Override
public void flatMap(Map value, Collector<RowData> out) throws Exception {
try {
switch (value.get("op").toString()) {
case "r":
case "c":
GenericRowData igenericRowData = new GenericRowData(columnNameList.size());
igenericRowData.setRowKind(RowKind.INSERT);
Map idata = (Map) value.get("after");
for (int i = 0; i < columnNameList.size(); i++) {
igenericRowData.setField(i, convertValue(idata.get(columnNameList.get(i)), columnTypeList.get(i)));
}
out.collect(igenericRowData);
break;
case "d":
GenericRowData dgenericRowData = new GenericRowData(columnNameList.size());
dgenericRowData.setRowKind(RowKind.DELETE);
Map ddata = (Map) value.get("before");
for (int i = 0; i < columnNameList.size(); i++) {
dgenericRowData.setField(i, convertValue(ddata.get(columnNameList.get(i)), columnTypeList.get(i)));
}
out.collect(dgenericRowData);
break;
case "u":
GenericRowData ubgenericRowData = new GenericRowData(columnNameList.size());
ubgenericRowData.setRowKind(RowKind.UPDATE_BEFORE);
Map ubdata = (Map) value.get("before");
for (int i = 0; i < columnNameList.size(); i++) {
ubgenericRowData.setField(i, convertValue(ubdata.get(columnNameList.get(i)), columnTypeList.get(i)));
}
out.collect(ubgenericRowData);
GenericRowData uagenericRowData = new GenericRowData(columnNameList.size());
uagenericRowData.setRowKind(RowKind.UPDATE_AFTER);
Map uadata = (Map) value.get("after");
for (int i = 0; i < columnNameList.size(); i++) {
uagenericRowData.setField(i, convertValue(uadata.get(columnNameList.get(i)), columnTypeList.get(i)));
}
out.collect(uagenericRowData);
break;
default:
.flatMap(new FlatMapFunction<Map, RowData>() {
@Override
public void flatMap(Map value, Collector<RowData> out) throws Exception {
try {
switch (value.get("op").toString()) {
case "r":
case "c":
GenericRowData igenericRowData = new GenericRowData(columnNameList.size());
igenericRowData.setRowKind(RowKind.INSERT);
Map idata = (Map) value.get("after");
for (int i = 0; i < columnNameList.size(); i++) {
igenericRowData.setField(i,
convertValue(idata.get(columnNameList.get(i)), columnTypeList.get(i)));
}
out.collect(igenericRowData);
break;
case "d":
GenericRowData dgenericRowData = new GenericRowData(columnNameList.size());
dgenericRowData.setRowKind(RowKind.DELETE);
Map ddata = (Map) value.get("before");
for (int i = 0; i < columnNameList.size(); i++) {
dgenericRowData.setField(i,
convertValue(ddata.get(columnNameList.get(i)), columnTypeList.get(i)));
}
out.collect(dgenericRowData);
break;
case "u":
GenericRowData ubgenericRowData = new GenericRowData(columnNameList.size());
ubgenericRowData.setRowKind(RowKind.UPDATE_BEFORE);
Map ubdata = (Map) value.get("before");
for (int i = 0; i < columnNameList.size(); i++) {
ubgenericRowData.setField(i,
convertValue(ubdata.get(columnNameList.get(i)), columnTypeList.get(i)));
}
out.collect(ubgenericRowData);
GenericRowData uagenericRowData = new GenericRowData(columnNameList.size());
uagenericRowData.setRowKind(RowKind.UPDATE_AFTER);
Map uadata = (Map) value.get("after");
for (int i = 0; i < columnNameList.size(); i++) {
uagenericRowData.setField(i,
convertValue(uadata.get(columnNameList.get(i)), columnTypeList.get(i)));
}
out.collect(uagenericRowData);
break;
default:
}
} catch (Exception e) {
logger.error("SchameTable: {} - Row: {} - Exception:", schemaTableName,
JSONUtil.toJsonString(value), e);
throw e;
}
} catch (Exception e) {
logger.error("SchameTable: {} - Row: {} - Exception:", schemaTableName, JSONUtil.toJsonString(value), e);
throw e;
}
}
});
});
}
public abstract void addSink(
StreamExecutionEnvironment env,
DataStream<RowData> rowDataDataStream,
Table table,
List<String> columnNameList,
List<LogicalType> columnTypeList);
StreamExecutionEnvironment env,
DataStream<RowData> rowDataDataStream,
Table table,
List<String> columnNameList,
List<LogicalType> columnTypeList);
@Override
public DataStreamSource build(
CDCBuilder cdcBuilder,
StreamExecutionEnvironment env,
CustomTableEnvironment customTableEnvironment,
DataStreamSource<String> dataStreamSource) {
CDCBuilder cdcBuilder,
StreamExecutionEnvironment env,
CustomTableEnvironment customTableEnvironment,
DataStreamSource<String> dataStreamSource) {
final List<Schema> schemaList = config.getSchemaList();
final String schemaFieldName = config.getSchemaFieldName();
......@@ -225,7 +237,8 @@ public abstract class AbstractSinkBuilder implements SinkBuilder {
buildColumn(columnNameList, columnTypeList, table.getColumns());
DataStream<RowData> rowDataDataStream = buildRowData(filterOperator, columnNameList, columnTypeList, table.getSchemaTableName());
DataStream<RowData> rowDataDataStream =
buildRowData(filterOperator, columnNameList, columnTypeList, table.getSchemaTableName());
addSink(env, rowDataDataStream, table, columnNameList, columnTypeList);
}
......@@ -292,7 +305,8 @@ public abstract class AbstractSinkBuilder implements SinkBuilder {
if (logicalType instanceof VarCharType) {
return StringData.fromString((String) value);
} else if (logicalType instanceof DateType) {
return StringData.fromString(Instant.ofEpochMilli((long) value).atZone(ZoneId.systemDefault()).toLocalDate().toString());
return StringData.fromString(
Instant.ofEpochMilli((long) value).atZone(ZoneId.systemDefault()).toLocalDate().toString());
} else if (logicalType instanceof TimestampType) {
return TimestampData.fromTimestamp(Timestamp.from(Instant.ofEpochMilli((long) value)));
} else if (logicalType instanceof DecimalType) {
......
......@@ -21,6 +21,7 @@ package com.dlink.cdc;
import com.dlink.exception.SplitTableException;
import com.dlink.model.FlinkCDCConfig;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
......
......@@ -20,6 +20,7 @@
package com.dlink.cdc;
import com.dlink.assertion.Asserts;
import com.dlink.cdc.mysql.MysqlCDCBuilder;
import com.dlink.exception.FlinkClientException;
import com.dlink.model.FlinkCDCConfig;
......@@ -32,6 +33,7 @@ import com.dlink.model.FlinkCDCConfig;
public class CDCBuilderFactory {
private static CDCBuilder[] cdcBuilders = {
new MysqlCDCBuilder()
};
public static CDCBuilder buildCDCBuilder(FlinkCDCConfig config) {
......
......@@ -22,6 +22,7 @@ package com.dlink.cdc;
import com.dlink.executor.CustomTableEnvironment;
import com.dlink.model.FlinkCDCConfig;
import com.dlink.model.Table;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
......@@ -37,7 +38,8 @@ public interface SinkBuilder {
SinkBuilder create(FlinkCDCConfig config);
DataStreamSource build(CDCBuilder cdcBuilder, StreamExecutionEnvironment env, CustomTableEnvironment customTableEnvironment, DataStreamSource<String> dataStreamSource);
DataStreamSource build(CDCBuilder cdcBuilder, StreamExecutionEnvironment env,
CustomTableEnvironment customTableEnvironment, DataStreamSource<String> dataStreamSource);
String getSinkSchemaName(Table table);
......
......@@ -20,6 +20,7 @@
package com.dlink.cdc;
import com.dlink.assertion.Asserts;
import com.dlink.cdc.sql.SQLSinkBuilder;
import com.dlink.exception.FlinkClientException;
import com.dlink.model.FlinkCDCConfig;
......@@ -44,6 +45,6 @@ public class SinkBuilderFactory {
return sinkBuilders[i].create(config);
}
}
throw new FlinkClientException("未匹配到对应 Sink 类型的【" + config.getType() + "】。");
return new SQLSinkBuilder().create(config);
}
}
/*
*
* 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 com.dlink.cdc.mysql;
import com.dlink.assertion.Asserts;
import com.dlink.cdc.AbstractCDCBuilder;
import com.dlink.cdc.CDCBuilder;
import com.dlink.constant.ClientConstant;
import com.dlink.constant.FlinkParamConstant;
import com.dlink.model.FlinkCDCConfig;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import com.ververica.cdc.connectors.mysql.source.MySqlSource;
import com.ververica.cdc.connectors.mysql.source.MySqlSourceBuilder;
import com.ververica.cdc.connectors.mysql.table.StartupOptions;
/**
* MysqlCDCBuilder
*
* @author wenmo
* @since 2022/4/12 21:29
**/
public class MysqlCDCBuilder extends AbstractCDCBuilder {
private static final String KEY_WORD = "mysql-cdc";
private static final String METADATA_TYPE = "MySql";
public MysqlCDCBuilder() {
}
public MysqlCDCBuilder(FlinkCDCConfig config) {
super(config);
}
@Override
public String getHandle() {
return KEY_WORD;
}
@Override
public CDCBuilder create(FlinkCDCConfig config) {
return new MysqlCDCBuilder(config);
}
@Override
public DataStreamSource<String> build(StreamExecutionEnvironment env) {
String database = config.getDatabase();
String serverId = config.getSource().get("server-id");
String serverTimeZone = config.getSource().get("server-time-zone");
String fetchSize = config.getSource().get("scan.snapshot.fetch.size");
String connectTimeout = config.getSource().get("connect.timeout");
String connectMaxRetries = config.getSource().get("connect.max-retries");
String connectionPoolSize = config.getSource().get("connection.pool.size");
String heartbeatInterval = config.getSource().get("heartbeat.interval");
Properties debeziumProperties = new Properties();
// 为部分转换添加默认值
debeziumProperties.setProperty("bigint.unsigned.handling.mode","long");
debeziumProperties.setProperty("decimal.handling.mode","string");
for (Map.Entry<String, String> entry : config.getDebezium().entrySet()) {
if (Asserts.isNotNullString(entry.getKey()) && Asserts.isNotNullString(entry.getValue())) {
debeziumProperties.setProperty(entry.getKey(), entry.getValue());
}
}
// 添加jdbc参数注入
Properties jdbcProperties = new Properties();
for (Map.Entry<String, String> entry : config.getJdbc().entrySet()) {
if (Asserts.isNotNullString(entry.getKey()) && Asserts.isNotNullString(entry.getValue())) {
jdbcProperties.setProperty(entry.getKey(), entry.getValue());
}
}
MySqlSourceBuilder<String> sourceBuilder = MySqlSource.<String>builder()
.hostname(config.getHostname())
.port(config.getPort())
.username(config.getUsername())
.password(config.getPassword());
if (Asserts.isNotNullString(database)) {
String[] databases = database.split(FlinkParamConstant.SPLIT);
sourceBuilder.databaseList(databases);
} else {
sourceBuilder.databaseList(new String[0]);
}
List<String> schemaTableNameList = config.getSchemaTableNameList();
if (Asserts.isNotNullCollection(schemaTableNameList)) {
sourceBuilder.tableList(schemaTableNameList.toArray(new String[schemaTableNameList.size()]));
} else {
sourceBuilder.tableList(new String[0]);
}
sourceBuilder.deserializer(new MysqlJsonDebeziumDeserializationSchema());
sourceBuilder.debeziumProperties(debeziumProperties);
sourceBuilder.jdbcProperties(jdbcProperties);
if (Asserts.isNotNullString(config.getStartupMode())) {
switch (config.getStartupMode().toLowerCase()) {
case "initial":
sourceBuilder.startupOptions(StartupOptions.initial());
break;
case "latest-offset":
sourceBuilder.startupOptions(StartupOptions.latest());
break;
default:
}
} else {
sourceBuilder.startupOptions(StartupOptions.latest());
}
if (Asserts.isNotNullString(serverId)) {
sourceBuilder.serverId(serverId);
}
if (Asserts.isNotNullString(serverTimeZone)) {
sourceBuilder.serverTimeZone(serverTimeZone);
}
if (Asserts.isNotNullString(fetchSize)) {
sourceBuilder.fetchSize(Integer.valueOf(fetchSize));
}
if (Asserts.isNotNullString(connectTimeout)) {
sourceBuilder.connectTimeout(Duration.ofMillis(Long.valueOf(connectTimeout)));
}
if (Asserts.isNotNullString(connectMaxRetries)) {
sourceBuilder.connectMaxRetries(Integer.valueOf(connectMaxRetries));
}
if (Asserts.isNotNullString(connectionPoolSize)) {
sourceBuilder.connectionPoolSize(Integer.valueOf(connectionPoolSize));
}
if (Asserts.isNotNullString(heartbeatInterval)) {
sourceBuilder.heartbeatInterval(Duration.ofMillis(Long.valueOf(heartbeatInterval)));
}
return env.fromSource(sourceBuilder.build(), WatermarkStrategy.noWatermarks(), "MySQL CDC Source");
}
public List<String> getSchemaList() {
List<String> schemaList = new ArrayList<>();
String schema = config.getDatabase();
if (Asserts.isNotNullString(schema)) {
String[] schemas = schema.split(FlinkParamConstant.SPLIT);
Collections.addAll(schemaList, schemas);
}
List<String> tableList = getTableList();
for (String tableName : tableList) {
tableName = tableName.trim();
if (Asserts.isNotNullString(tableName) && tableName.contains(".")) {
String[] names = tableName.split("\\\\.");
if (!schemaList.contains(names[0])) {
schemaList.add(names[0]);
}
}
}
return schemaList;
}
public Map<String, Map<String, String>> parseMetaDataConfigs() {
Map<String, Map<String, String>> allConfigMap = new HashMap<>();
List<String> schemaList = getSchemaList();
for (String schema : schemaList) {
Map<String, String> configMap = new HashMap<>();
configMap.put(ClientConstant.METADATA_TYPE, METADATA_TYPE);
StringBuilder sb = new StringBuilder("jdbc:mysql://");
sb.append(config.getHostname());
sb.append(":");
sb.append(config.getPort());
sb.append("/");
sb.append(schema);
configMap.put(ClientConstant.METADATA_NAME, sb.toString());
configMap.put(ClientConstant.METADATA_URL, sb.toString());
configMap.put(ClientConstant.METADATA_USERNAME, config.getUsername());
configMap.put(ClientConstant.METADATA_PASSWORD, config.getPassword());
allConfigMap.put(schema, configMap);
}
return allConfigMap;
}
@Override
public String getSchemaFieldName() {
return "db";
}
}
/*
*
* 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 com.dlink.cdc.mysql;
import org.apache.flink.api.common.typeinfo.BasicTypeInfo;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.util.Collector;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import com.ververica.cdc.connectors.shaded.org.apache.kafka.connect.json.JsonConverter;
import com.ververica.cdc.connectors.shaded.org.apache.kafka.connect.source.SourceRecord;
import com.ververica.cdc.connectors.shaded.org.apache.kafka.connect.storage.ConverterType;
import com.ververica.cdc.debezium.DebeziumDeserializationSchema;
/**
* @version 1.0
* @className: com.dlink.cdc.mysql.MysqlJsonDebeziumDeserializationSchema
* @Description:
* @author: jack zhong
*/
public class MysqlJsonDebeziumDeserializationSchema implements DebeziumDeserializationSchema<String> {
private static final long serialVersionUID = 1L;
private transient JsonConverter jsonConverter;
private final Boolean includeSchema;
private Map<String, Object> customConverterConfigs;
public MysqlJsonDebeziumDeserializationSchema() {
this(false);
}
public MysqlJsonDebeziumDeserializationSchema(Boolean includeSchema) {
this.includeSchema = includeSchema;
}
public MysqlJsonDebeziumDeserializationSchema(Boolean includeSchema, Map<String, Object> customConverterConfigs) {
this.includeSchema = includeSchema;
this.customConverterConfigs = customConverterConfigs;
}
public void deserialize(SourceRecord record, Collector<String> out) throws Exception {
if (this.jsonConverter == null) {
this.initializeJsonConverter();
}
byte[] bytes = this.jsonConverter.fromConnectData(record.topic(), record.valueSchema(), record.value());
out.collect(new String(bytes, StandardCharsets.UTF_8));
}
private void initializeJsonConverter() {
this.jsonConverter = new JsonConverter();
HashMap<String, Object> configs = new HashMap(2);
configs.put("converter.type", ConverterType.VALUE.getName());
configs.put("schemas.enable", this.includeSchema);
if (this.customConverterConfigs != null) {
configs.putAll(this.customConverterConfigs);
}
this.jsonConverter.configure(configs);
}
public TypeInformation<String> getProducedType() {
return BasicTypeInfo.STRING_TYPE_INFO;
}
}
/*
*
* 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 com.dlink.cdc.sql;
import com.dlink.assertion.Asserts;
import com.dlink.cdc.AbstractSinkBuilder;
import com.dlink.cdc.CDCBuilder;
import com.dlink.cdc.SinkBuilder;
import com.dlink.executor.CustomTableEnvironment;
import com.dlink.model.FlinkCDCConfig;
import com.dlink.model.Schema;
import com.dlink.model.Table;
import com.dlink.utils.FlinkBaseUtil;
import com.dlink.utils.JSONUtil;
import com.dlink.utils.LogUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.dag.Transformation;
import org.apache.flink.api.java.typeutils.RowTypeInfo;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.operations.ModifyOperation;
import org.apache.flink.table.operations.Operation;
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 org.apache.flink.table.types.utils.TypeConversions;
import org.apache.flink.types.Row;
import org.apache.flink.types.RowKind;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.DatatypeConverter;
/**
* SQLSinkBuilder
*
* @author wenmo
* @since 2022/4/25 23:02
*/
public class SQLSinkBuilder extends AbstractSinkBuilder implements Serializable {
private static final String KEY_WORD = "sql";
private static final long serialVersionUID = -3699685106324048226L;
private ZoneId sinkTimeZone = ZoneId.of("UTC");
public SQLSinkBuilder() {
}
private SQLSinkBuilder(FlinkCDCConfig config) {
super(config);
}
@Override
public void addSink(StreamExecutionEnvironment env, DataStream<RowData> rowDataDataStream, Table table, List<String> columnNameList, List<LogicalType> columnTypeList) {
}
private DataStream<Row> buildRow(
DataStream<Map> filterOperator,
List<String> columnNameList,
List<LogicalType> columnTypeList,
String schemaTableName) {
final String[] columnNames = columnNameList.toArray(new String[columnNameList.size()]);
final LogicalType[] columnTypes = columnTypeList.toArray(new LogicalType[columnTypeList.size()]);
TypeInformation<?>[] typeInformations = TypeConversions.fromDataTypeToLegacyInfo(TypeConversions.fromLogicalToDataType(columnTypes));
RowTypeInfo rowTypeInfo = new RowTypeInfo(typeInformations, columnNames);
return filterOperator
.flatMap(new FlatMapFunction<Map, Row>() {
@Override
public void flatMap(Map value, Collector<Row> out) throws Exception {
try {
switch (value.get("op").toString()) {
case "r":
case "c":
Row irow = Row.withPositions(RowKind.INSERT, columnNameList.size());
Map idata = (Map) value.get("after");
for (int i = 0; i < columnNameList.size(); i++) {
irow.setField(i, convertValue(idata.get(columnNameList.get(i)), columnTypeList.get(i)));
}
out.collect(irow);
break;
case "d":
Row drow = Row.withPositions(RowKind.DELETE, columnNameList.size());
Map ddata = (Map) value.get("before");
for (int i = 0; i < columnNameList.size(); i++) {
drow.setField(i, convertValue(ddata.get(columnNameList.get(i)), columnTypeList.get(i)));
}
out.collect(drow);
break;
case "u":
Row ubrow = Row.withPositions(RowKind.UPDATE_BEFORE, columnNameList.size());
Map ubdata = (Map) value.get("before");
for (int i = 0; i < columnNameList.size(); i++) {
ubrow.setField(i, convertValue(ubdata.get(columnNameList.get(i)), columnTypeList.get(i)));
}
out.collect(ubrow);
Row uarow = Row.withPositions(RowKind.UPDATE_AFTER, columnNameList.size());
Map uadata = (Map) value.get("after");
for (int i = 0; i < columnNameList.size(); i++) {
uarow.setField(i, convertValue(uadata.get(columnNameList.get(i)), columnTypeList.get(i)));
}
out.collect(uarow);
break;
default:
}
} catch (Exception e) {
logger.error("SchameTable: {} - Row: {} - Exception:", schemaTableName, JSONUtil.toJsonString(value), e);
throw e;
}
}
}, rowTypeInfo);
}
private void addTableSink(
CustomTableEnvironment customTableEnvironment,
DataStream<Row> rowDataDataStream,
Table table,
List<String> columnNameList) {
String sinkSchemaName = getSinkSchemaName(table);
String sinkTableName = getSinkTableName(table);
String pkList = StringUtils.join(getPKList(table), ".");
String viewName = "VIEW_" + table.getSchemaTableNameWithUnderline();
customTableEnvironment.createTemporaryView(viewName, rowDataDataStream, StringUtils.join(columnNameList, ","));
logger.info("Create " + viewName + " temporaryView successful...");
String flinkDDL = FlinkBaseUtil.getFlinkDDL(table, sinkTableName, config, sinkSchemaName, sinkTableName, pkList);
logger.info(flinkDDL);
customTableEnvironment.executeSql(flinkDDL);
logger.info("Create " + sinkTableName + " FlinkSQL DDL successful...");
String cdcSqlInsert = FlinkBaseUtil.getCDCSqlInsert(table, sinkTableName, viewName, config);
logger.info(cdcSqlInsert);
List<Operation> operations = customTableEnvironment.getParser().parse(cdcSqlInsert);
logger.info("Create " + sinkTableName + " FlinkSQL insert into successful...");
try {
if (operations.size() > 0) {
Operation operation = operations.get(0);
if (operation instanceof ModifyOperation) {
modifyOperations.add((ModifyOperation) operation);
}
}
} catch (Exception e) {
logger.error("Translate to plan occur exception: {}", e);
throw e;
}
}
@Override
public String getHandle() {
return KEY_WORD;
}
@Override
public SinkBuilder create(FlinkCDCConfig config) {
return new SQLSinkBuilder(config);
}
@Override
public DataStreamSource build(
CDCBuilder cdcBuilder,
StreamExecutionEnvironment env,
CustomTableEnvironment customTableEnvironment,
DataStreamSource<String> dataStreamSource) {
final String timeZone = config.getSink().get("timezone");
config.getSink().remove("timezone");
if (Asserts.isNotNullString(timeZone)) {
sinkTimeZone = ZoneId.of(timeZone);
}
final List<Schema> schemaList = config.getSchemaList();
if (Asserts.isNotNullCollection(schemaList)) {
logger.info("Build deserialize successful...");
Map<Table, OutputTag<Map>> tagMap = new HashMap<>();
Map<String, Table> tableMap = new HashMap<>();
for (Schema schema : schemaList) {
for (Table table : schema.getTables()) {
String sinkTableName = getSinkTableName(table);
OutputTag<Map> outputTag = new OutputTag<Map>(sinkTableName) {
};
tagMap.put(table, outputTag);
tableMap.put(table.getSchemaTableName(), table);
}
}
final String schemaFieldName = config.getSchemaFieldName();
ObjectMapper objectMapper = new ObjectMapper();
SingleOutputStreamOperator<Map> mapOperator = dataStreamSource.map(x -> objectMapper.readValue(x,Map.class)).returns(Map.class);
SingleOutputStreamOperator<Map> processOperator = mapOperator.process(new ProcessFunction<Map, Map>() {
@Override
public void processElement(Map map, ProcessFunction<Map, Map>.Context ctx, Collector<Map> out) throws Exception {
LinkedHashMap source = (LinkedHashMap) map.get("source");
try {
Table table = tableMap.get(source.get(schemaFieldName).toString() + "." + source.get("table").toString());
OutputTag<Map> outputTag = tagMap.get(table);
ctx.output(outputTag, map);
} catch (Exception e) {
out.collect(map);
}
}
});
tagMap.forEach((table,tag) -> {
final String schemaTableName = table.getSchemaTableName();
try {
DataStream<Map> filterOperator = shunt(processOperator, table, tag);
logger.info("Build " + schemaTableName + " shunt successful...");
List<String> columnNameList = new ArrayList<>();
List<LogicalType> columnTypeList = new ArrayList<>();
buildColumn(columnNameList, columnTypeList, table.getColumns());
DataStream<Row> rowDataDataStream = buildRow(filterOperator, columnNameList, columnTypeList, schemaTableName).rebalance();
logger.info("Build " + schemaTableName + " flatMap successful...");
logger.info("Start build " + schemaTableName + " sink...");
addTableSink(customTableEnvironment, rowDataDataStream, table, columnNameList);
} catch (Exception e) {
logger.error("Build " + schemaTableName + " cdc sync failed...");
logger.error(LogUtil.getError(e));
}
});
List<Transformation<?>> trans = customTableEnvironment.getPlanner().translate(modifyOperations);
for (Transformation<?> item : trans) {
env.addOperator(item);
}
logger.info("A total of " + trans.size() + " table cdc sync were build successfull...");
}
return dataStreamSource;
}
protected Object convertValue(Object value, LogicalType logicalType) {
if (value == null) {
return null;
}
if (logicalType instanceof DateType) {
if (value instanceof Integer) {
return Instant.ofEpochMilli(((Integer) value).longValue()).atZone(sinkTimeZone).toLocalDate();
} else {
return Instant.ofEpochMilli((long) value).atZone(sinkTimeZone).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(sinkTimeZone).toLocalDateTime();
} else {
return Instant.ofEpochMilli((long) value).atZone(sinkTimeZone).toLocalDateTime();
}
} else if (logicalType instanceof DecimalType) {
return new BigDecimal((String) 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;
}
}
}
......@@ -22,9 +22,7 @@ package com.dlink.executor;
import com.dlink.assertion.Asserts;
import com.dlink.model.LineageRel;
import com.dlink.result.SqlExplainResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.dag.Transformation;
......@@ -40,12 +38,9 @@ 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.ExplainDetail;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.TableConfig;
import org.apache.flink.table.api.TableException;
import org.apache.flink.table.api.bridge.internal.AbstractStreamTableEnvironmentImpl;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.api.bridge.java.internal.StreamTableEnvironmentImpl;
import org.apache.flink.table.catalog.CatalogManager;
import org.apache.flink.table.catalog.FunctionCatalog;
import org.apache.flink.table.catalog.GenericInMemoryCatalog;
......@@ -53,8 +48,6 @@ import org.apache.flink.table.connector.ChangelogMode;
import org.apache.flink.table.delegation.Executor;
import org.apache.flink.table.delegation.Planner;
import org.apache.flink.table.expressions.Expression;
import org.apache.flink.table.expressions.ExpressionParserException;
import org.apache.flink.table.expressions.ExpressionUtils;
import org.apache.flink.table.factories.PlannerFactoryUtil;
import org.apache.flink.table.module.ModuleManager;
import org.apache.flink.table.operations.DataStreamQueryOperation;
......@@ -71,12 +64,15 @@ import org.apache.flink.util.MutableURLClassLoader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* CustomTableEnvironmentImpl
*
......@@ -84,28 +80,29 @@ import java.util.Optional;
* @since 2022/05/08
**/
public class CustomTableEnvironmentImpl extends AbstractStreamTableEnvironmentImpl
implements CustomTableEnvironment {
implements
CustomTableEnvironment {
public CustomTableEnvironmentImpl(
CatalogManager catalogManager,
ModuleManager moduleManager,
ResourceManager resourceManager,
FunctionCatalog functionCatalog,
TableConfig tableConfig,
StreamExecutionEnvironment executionEnvironment,
Planner planner,
Executor executor,
boolean isStreamingMode) {
CatalogManager catalogManager,
ModuleManager moduleManager,
ResourceManager resourceManager,
FunctionCatalog functionCatalog,
TableConfig tableConfig,
StreamExecutionEnvironment executionEnvironment,
Planner planner,
Executor executor,
boolean isStreamingMode) {
super(
catalogManager,
moduleManager,
resourceManager,
tableConfig,
executor,
functionCatalog,
planner,
isStreamingMode,
executionEnvironment);
catalogManager,
moduleManager,
resourceManager,
tableConfig,
executor,
functionCatalog,
planner,
isStreamingMode,
executionEnvironment);
}
public static CustomTableEnvironmentImpl create(StreamExecutionEnvironment executionEnvironment) {
......@@ -121,10 +118,11 @@ public class CustomTableEnvironmentImpl extends AbstractStreamTableEnvironmentIm
}
public static CustomTableEnvironmentImpl create(
StreamExecutionEnvironment executionEnvironment, EnvironmentSettings settings) {
StreamExecutionEnvironment executionEnvironment,
EnvironmentSettings settings) {
final MutableURLClassLoader userClassLoader =
FlinkUserCodeClassLoaders.create(
new URL[0], settings.getUserClassLoader(), settings.getConfiguration());
FlinkUserCodeClassLoaders.create(
new URL[0], settings.getUserClassLoader(), settings.getConfiguration());
final Executor executor = lookupExecutor(userClassLoader, executionEnvironment);
final TableConfig tableConfig = TableConfig.getDefault();
......@@ -132,43 +130,43 @@ public class CustomTableEnvironmentImpl extends AbstractStreamTableEnvironmentIm
tableConfig.addConfiguration(settings.getConfiguration());
final ResourceManager resourceManager =
new ResourceManager(settings.getConfiguration(), userClassLoader);
new ResourceManager(settings.getConfiguration(), userClassLoader);
final ModuleManager moduleManager = new ModuleManager();
final CatalogManager catalogManager =
CatalogManager.newBuilder()
.classLoader(userClassLoader)
.config(tableConfig)
.defaultCatalog(
settings.getBuiltInCatalogName(),
new GenericInMemoryCatalog(
settings.getBuiltInCatalogName(),
settings.getBuiltInDatabaseName()))
.executionConfig(executionEnvironment.getConfig())
.build();
CatalogManager.newBuilder()
.classLoader(userClassLoader)
.config(tableConfig)
.defaultCatalog(
settings.getBuiltInCatalogName(),
new GenericInMemoryCatalog(
settings.getBuiltInCatalogName(),
settings.getBuiltInDatabaseName()))
.executionConfig(executionEnvironment.getConfig())
.build();
final FunctionCatalog functionCatalog =
new FunctionCatalog(tableConfig, resourceManager, catalogManager, moduleManager);
new FunctionCatalog(tableConfig, resourceManager, catalogManager, moduleManager);
final Planner planner =
PlannerFactoryUtil.createPlanner(
executor,
tableConfig,
userClassLoader,
moduleManager,
catalogManager,
functionCatalog);
PlannerFactoryUtil.createPlanner(
executor,
tableConfig,
userClassLoader,
moduleManager,
catalogManager,
functionCatalog);
return new CustomTableEnvironmentImpl(
catalogManager,
moduleManager,
resourceManager,
functionCatalog,
tableConfig,
executionEnvironment,
planner,
executor,
settings.isStreamingMode());
catalogManager,
moduleManager,
resourceManager,
functionCatalog,
tableConfig,
executionEnvironment,
planner,
executor,
settings.isStreamingMode());
}
public ObjectNode getStreamGraph(String statement) {
......@@ -245,7 +243,7 @@ public class CustomTableEnvironmentImpl extends AbstractStreamTableEnvironmentIm
record.setParseTrue(true);
if (operations.size() != 1) {
throw new TableException(
"Unsupported SQL query! explainSql() only accepts a single SQL query.");
"Unsupported SQL query! explainSql() only accepts a single SQL query.");
}
Operation operation = operations.get(0);
if (operation instanceof ModifyOperation) {
......@@ -260,14 +258,15 @@ public class CustomTableEnvironmentImpl extends AbstractStreamTableEnvironmentIm
}
record.setExplainTrue(true);
if ("DDL".equals(record.getType())) {
//record.setExplain("DDL语句不进行解释。");
// record.setExplain("DDL语句不进行解释。");
return record;
}
record.setExplain(planner.explain(operations, extraDetails));
return record;
}
public boolean parseAndLoadConfiguration(String statement, StreamExecutionEnvironment environment, Map<String, Object> setMap) {
public boolean parseAndLoadConfiguration(String statement, StreamExecutionEnvironment environment,
Map<String, Object> setMap) {
List<Operation> operations = getParser().parse(statement);
for (Operation operation : operations) {
if (operation instanceof SetOperation) {
......@@ -281,7 +280,8 @@ public class CustomTableEnvironmentImpl extends AbstractStreamTableEnvironmentIm
return false;
}
private void callSet(SetOperation setOperation, StreamExecutionEnvironment environment, Map<String, Object> setMap) {
private void callSet(SetOperation setOperation, StreamExecutionEnvironment environment,
Map<String, Object> setMap) {
if (setOperation.getKey().isPresent() && setOperation.getValue().isPresent()) {
String key = setOperation.getKey().get().trim();
String value = setOperation.getValue().get().trim();
......@@ -297,7 +297,8 @@ public class CustomTableEnvironmentImpl extends AbstractStreamTableEnvironmentIm
}
}
private void callReset(ResetOperation resetOperation, StreamExecutionEnvironment environment, Map<String, Object> setMap) {
private void callReset(ResetOperation resetOperation, StreamExecutionEnvironment environment,
Map<String, Object> setMap) {
if (resetOperation.getKey().isPresent()) {
String key = resetOperation.getKey().get().trim();
if (Asserts.isNullString(key)) {
......@@ -314,14 +315,14 @@ public class CustomTableEnvironmentImpl extends AbstractStreamTableEnvironmentIm
}
}
/*public <T> Table fromDataStream(DataStream<T> dataStream, Expression... fields) {
return createTable(asQueryOperation(dataStream, Optional.of(Arrays.asList(fields))));
}
public <T> Table fromDataStream(DataStream<T> dataStream, String fields) {
List<Expression> expressions = ExpressionParser.INSTANCE.parseExpressionList(fields);
return fromDataStream(dataStream, expressions.toArray(new Expression[0]));
}*/
/*
* public <T> Table fromDataStream(DataStream<T> dataStream, Expression... fields) { return
* createTable(asQueryOperation(dataStream, Optional.of(Arrays.asList(fields)))); }
*
* public <T> Table fromDataStream(DataStream<T> dataStream, String fields) { List<Expression> expressions =
* ExpressionParser.INSTANCE.parseExpressionList(fields); return fromDataStream(dataStream, expressions.toArray(new
* Expression[0])); }
*/
@Override
public <T> void createTemporaryView(String path, DataStream<T> dataStream, String fields) {
......@@ -335,29 +336,30 @@ public class CustomTableEnvironmentImpl extends AbstractStreamTableEnvironmentIm
@Override
public <T> void createTemporaryView(
String path, DataStream<T> dataStream, Expression... fields) {
String path, DataStream<T> dataStream, Expression... fields) {
createTemporaryView(path, fromStreamInternal(dataStream, null, null, ChangelogMode.all()));
}
protected <T> DataStreamQueryOperation<T> asQueryOperation(
DataStream<T> dataStream, Optional<List<Expression>> fields) {
DataStream<T> dataStream,
Optional<List<Expression>> fields) {
TypeInformation<T> streamType = dataStream.getType();
// get field names and types for all non-replaced fields
FieldInfoUtils.TypeInfoSchema typeInfoSchema =
fields.map(
f -> {
FieldInfoUtils.TypeInfoSchema fieldsInfo =
FieldInfoUtils.getFieldsInfo(
streamType, f.toArray(new Expression[0]));
// check if event-time is enabled
validateTimeCharacteristic(fieldsInfo.isRowtimeDefined());
return fieldsInfo;
})
.orElseGet(() -> FieldInfoUtils.getFieldsInfo(streamType));
fields.map(
f -> {
FieldInfoUtils.TypeInfoSchema fieldsInfo =
FieldInfoUtils.getFieldsInfo(
streamType, f.toArray(new Expression[0]));
// check if event-time is enabled
validateTimeCharacteristic(fieldsInfo.isRowtimeDefined());
return fieldsInfo;
})
.orElseGet(() -> FieldInfoUtils.getFieldsInfo(streamType));
return new DataStreamQueryOperation<>(
dataStream, typeInfoSchema.getIndices(), typeInfoSchema.toResolvedSchema());
dataStream, typeInfoSchema.getIndices(), typeInfoSchema.toResolvedSchema());
}
}
......@@ -38,7 +38,6 @@ import org.apache.flink.types.Row;
import org.apache.flink.util.CloseableIterator;
import org.apache.flink.util.Preconditions;
import javax.annotation.Nullable;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
......@@ -52,16 +51,20 @@ import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/** Implementation for {@link TableResult}. */
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();
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;
......@@ -70,14 +73,14 @@ public class CustomTableResultImpl implements TableResultInternal {
private final PrintStyle printStyle;
private CustomTableResultImpl(
@Nullable JobClient jobClient,
ResolvedSchema resolvedSchema,
ResultKind resultKind,
ResultProvider resultProvider,
PrintStyle printStyle) {
@Nullable JobClient jobClient,
ResolvedSchema resolvedSchema,
ResultKind resultKind,
ResultProvider resultProvider,
PrintStyle printStyle) {
this.jobClient = jobClient;
this.resolvedSchema =
Preconditions.checkNotNull(resolvedSchema, "resolvedSchema should not be null");
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;
......@@ -113,32 +116,31 @@ public class CustomTableResultImpl implements TableResultInternal {
}
@Override
public void await(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
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 {
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"));
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);
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);
......@@ -185,15 +187,19 @@ public class CustomTableResultImpl implements TableResultInternal {
return new Builder();
}
/** Builder for creating a {@link CustomTableResultImpl}. */
/**
* 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() {}
private Builder() {
}
/**
* Specifies job client which associates the submitted Flink job.
......@@ -244,21 +250,24 @@ public class CustomTableResultImpl implements TableResultInternal {
return this;
}
/** Specifies print style. Default is {@link TableauStyle} with max integer column width. */
/**
* 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. */
/**
* Returns a {@link TableResult} instance.
*/
public TableResultInternal build() {
if (printStyle == null) {
printStyle = PrintStyle.rawContent(resultProvider.getRowDataStringConverter());
}
return new CustomTableResultImpl(
jobClient, resolvedSchema, resultKind, resultProvider, printStyle);
jobClient, resolvedSchema, resultKind, resultProvider, printStyle);
}
}
}
......@@ -26,6 +26,7 @@ import com.dlink.model.FlinkCDCConfig;
import com.dlink.model.Table;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.runtime.util.EnvironmentInformation;
import java.util.ArrayList;
import java.util.HashMap;
......@@ -70,7 +71,11 @@ public class FlinkBaseUtil {
public static String getFlinkDDL(Table table, String tableName, FlinkCDCConfig config, String sinkSchemaName, String sinkTableName, String pkList) {
StringBuilder sb = new StringBuilder();
sb.append("CREATE TABLE IF NOT EXISTS `");
if (Integer.parseInt(EnvironmentInformation.getVersion().split("\\.")[1]) < 13) {
sb.append("CREATE TABLE `");
} else {
sb.append("CREATE TABLE IF NOT EXISTS `");
}
sb.append(tableName);
sb.append("` (\n");
List<String> pks = new ArrayList<>();
......
......@@ -24,9 +24,7 @@ import org.apache.flink.connector.jdbc.internal.converter.OracleRowConverter;
import org.apache.flink.table.types.logical.LogicalTypeRoot;
import org.apache.flink.table.types.logical.RowType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
......@@ -75,56 +73,56 @@ public class OracleDialect extends AbstractDialect {
@Override
public Optional<String> getUpsertStatement(
String tableName, String[] fieldNames, String[] uniqueKeyFields) {
String tableName, String[] fieldNames, String[] uniqueKeyFields) {
String sourceFields =
Arrays.stream(fieldNames)
.map(f -> ":" + f + " " + quoteIdentifier(f))
.collect(Collectors.joining(", "));
Arrays.stream(fieldNames)
.map(f -> ":" + f + " " + quoteIdentifier(f))
.collect(Collectors.joining(", "));
String onClause =
Arrays.stream(uniqueKeyFields)
.map(f -> "t." + quoteIdentifier(f) + "=s." + quoteIdentifier(f))
.collect(Collectors.joining(" and "));
Arrays.stream(uniqueKeyFields)
.map(f -> "t." + quoteIdentifier(f) + "=s." + quoteIdentifier(f))
.collect(Collectors.joining(" and "));
final Set<String> uniqueKeyFieldsSet =
Arrays.stream(uniqueKeyFields).collect(Collectors.toSet());
Arrays.stream(uniqueKeyFields).collect(Collectors.toSet());
String updateClause =
Arrays.stream(fieldNames)
.filter(f -> !uniqueKeyFieldsSet.contains(f))
.map(f -> "t." + quoteIdentifier(f) + "=s." + quoteIdentifier(f))
.collect(Collectors.joining(", "));
Arrays.stream(fieldNames)
.filter(f -> !uniqueKeyFieldsSet.contains(f))
.map(f -> "t." + quoteIdentifier(f) + "=s." + quoteIdentifier(f))
.collect(Collectors.joining(", "));
String insertFields =
Arrays.stream(fieldNames)
.map(this::quoteIdentifier)
.collect(Collectors.joining(", "));
Arrays.stream(fieldNames)
.map(this::quoteIdentifier)
.collect(Collectors.joining(", "));
String valuesClause =
Arrays.stream(fieldNames)
.map(f -> "s." + quoteIdentifier(f))
.collect(Collectors.joining(", "));
Arrays.stream(fieldNames)
.map(f -> "s." + quoteIdentifier(f))
.collect(Collectors.joining(", "));
// if we can't divide schema and table-name is risky to call quoteIdentifier(tableName)
// for example [tbo].[sometable] is ok but [tbo.sometable] is not
String mergeQuery =
" MERGE INTO "
+ tableName
+ " t "
+ " USING (SELECT "
+ sourceFields
+ " FROM DUAL) s "
+ " ON ("
+ onClause
+ ") "
+ " WHEN MATCHED THEN UPDATE SET "
+ updateClause
+ " WHEN NOT MATCHED THEN INSERT ("
+ insertFields
+ ")"
+ " VALUES ("
+ valuesClause
+ ")";
" MERGE INTO "
+ tableName
+ " t "
+ " USING (SELECT "
+ sourceFields
+ " FROM DUAL) s "
+ " ON ("
+ onClause
+ ") "
+ " WHEN MATCHED THEN UPDATE SET "
+ updateClause
+ " WHEN NOT MATCHED THEN INSERT ("
+ insertFields
+ ")"
+ " VALUES ("
+ valuesClause
+ ")";
return Optional.of(mergeQuery);
}
......@@ -158,24 +156,24 @@ public class OracleDialect extends AbstractDialect {
public List<LogicalTypeRoot> unsupportedTypes() {
// TODO: We can't convert BINARY data type to
// PrimitiveArrayTypeInfo.BYTE_PRIMITIVE_ARRAY_TYPE_INFO in
// PrimitiveArrayTypeInfo.BYTE_PRIMITIVE_ARRAY_TYPE_INFO in
// LegacyTypeInfoDataTypeConverter.
return Arrays.asList(
LogicalTypeRoot.CHAR,
LogicalTypeRoot.VARCHAR,
LogicalTypeRoot.BOOLEAN,
LogicalTypeRoot.VARBINARY,
LogicalTypeRoot.DECIMAL,
LogicalTypeRoot.TINYINT,
LogicalTypeRoot.SMALLINT,
LogicalTypeRoot.INTEGER,
LogicalTypeRoot.BIGINT,
LogicalTypeRoot.FLOAT,
LogicalTypeRoot.DOUBLE,
LogicalTypeRoot.DATE,
LogicalTypeRoot.TIME_WITHOUT_TIME_ZONE,
LogicalTypeRoot.TIMESTAMP_WITHOUT_TIME_ZONE,
LogicalTypeRoot.TIMESTAMP_WITH_LOCAL_TIME_ZONE,
LogicalTypeRoot.ARRAY);
LogicalTypeRoot.CHAR,
LogicalTypeRoot.VARCHAR,
LogicalTypeRoot.BOOLEAN,
LogicalTypeRoot.VARBINARY,
LogicalTypeRoot.DECIMAL,
LogicalTypeRoot.TINYINT,
LogicalTypeRoot.SMALLINT,
LogicalTypeRoot.INTEGER,
LogicalTypeRoot.BIGINT,
LogicalTypeRoot.FLOAT,
LogicalTypeRoot.DOUBLE,
LogicalTypeRoot.DATE,
LogicalTypeRoot.TIME_WITHOUT_TIME_ZONE,
LogicalTypeRoot.TIMESTAMP_WITHOUT_TIME_ZONE,
LogicalTypeRoot.TIMESTAMP_WITH_LOCAL_TIME_ZONE,
LogicalTypeRoot.ARRAY);
}
}
......@@ -19,16 +19,6 @@
package org.apache.flink.connector.jdbc.internal.converter;
import oracle.jdbc.internal.OracleBlob;
import oracle.jdbc.internal.OracleClob;
import oracle.sql.BINARY_DOUBLE;
import oracle.sql.BINARY_FLOAT;
import oracle.sql.CHAR;
import oracle.sql.DATE;
import oracle.sql.NUMBER;
import oracle.sql.RAW;
import oracle.sql.TIMESTAMP;
import oracle.sql.TIMESTAMPTZ;
import org.apache.flink.table.data.DecimalData;
import org.apache.flink.table.data.StringData;
import org.apache.flink.table.data.TimestampData;
......@@ -43,6 +33,17 @@ import java.sql.Time;
import java.sql.Timestamp;
import java.time.ZonedDateTime;
import oracle.jdbc.internal.OracleBlob;
import oracle.jdbc.internal.OracleClob;
import oracle.sql.BINARY_DOUBLE;
import oracle.sql.BINARY_FLOAT;
import oracle.sql.CHAR;
import oracle.sql.DATE;
import oracle.sql.NUMBER;
import oracle.sql.RAW;
import oracle.sql.TIMESTAMP;
import oracle.sql.TIMESTAMPTZ;
/**
* Runtime converter that responsible to convert between JDBC object and Flink internal object for
* Oracle.
......@@ -71,94 +72,80 @@ public class OracleRowConverter extends AbstractJdbcRowConverter {
case BOOLEAN:
return val -> val instanceof NUMBER ? ((NUMBER) val).booleanValue() : val;
case FLOAT:
return val ->
val instanceof NUMBER
return val -> val instanceof NUMBER
? ((NUMBER) val).floatValue()
: val instanceof BINARY_FLOAT
? ((BINARY_FLOAT) val).floatValue()
: val instanceof BigDecimal
? ((BigDecimal) val).floatValue()
: val;
? ((BINARY_FLOAT) val).floatValue()
: val instanceof BigDecimal
? ((BigDecimal) val).floatValue()
: val;
case DOUBLE:
return val ->
val instanceof NUMBER
return val -> val instanceof NUMBER
? ((NUMBER) val).doubleValue()
: val instanceof BINARY_DOUBLE
? ((BINARY_DOUBLE) val).doubleValue()
: val instanceof BigDecimal
? ((BigDecimal) val).doubleValue()
: val;
? ((BINARY_DOUBLE) val).doubleValue()
: val instanceof BigDecimal
? ((BigDecimal) val).doubleValue()
: val;
case TINYINT:
return val ->
val instanceof NUMBER
return val -> val instanceof NUMBER
? ((NUMBER) val).byteValue()
: val instanceof BigDecimal ? ((BigDecimal) val).byteValue() : val;
case SMALLINT:
return val ->
val instanceof NUMBER
return val -> val instanceof NUMBER
? ((NUMBER) val).shortValue()
: val instanceof BigDecimal ? ((BigDecimal) val).shortValue() : val;
case INTEGER:
return val ->
val instanceof NUMBER
return val -> val instanceof NUMBER
? ((NUMBER) val).intValue()
: val instanceof BigDecimal ? ((BigDecimal) val).intValue() : val;
case BIGINT:
return val ->
val instanceof NUMBER
return val -> val instanceof NUMBER
? ((NUMBER) val).longValue()
: val instanceof BigDecimal ? ((BigDecimal) val).longValue() : val;
case DECIMAL:
final int precision = ((DecimalType) type).getPrecision();
final int scale = ((DecimalType) type).getScale();
return val ->
val instanceof BigInteger
return val -> val instanceof BigInteger
? DecimalData.fromBigDecimal(
new BigDecimal((BigInteger) val, 0), precision, scale)
new BigDecimal((BigInteger) val, 0), precision, scale)
: DecimalData.fromBigDecimal((BigDecimal) val, precision, scale);
case CHAR:
case VARCHAR:
return val ->
(val instanceof CHAR)
return val -> (val instanceof CHAR)
? StringData.fromString(((CHAR) val).getString())
: (val instanceof OracleClob)
? StringData.fromString(((OracleClob) val).stringValue())
: StringData.fromString((String) val);
? StringData.fromString(((OracleClob) val).stringValue())
: StringData.fromString((String) val);
case BINARY:
case VARBINARY:
case RAW:
return val ->
val instanceof RAW
return val -> val instanceof RAW
? ((RAW) val).getBytes()
: val instanceof OracleBlob
? ((OracleBlob) val)
.getBytes(1, (int) ((OracleBlob) val).length())
: val.toString().getBytes();
? ((OracleBlob) val)
.getBytes(1, (int) ((OracleBlob) val).length())
: val.toString().getBytes();
case INTERVAL_YEAR_MONTH:
case INTERVAL_DAY_TIME:
return val -> val instanceof NUMBER ? ((NUMBER) val).intValue() : val;
case DATE:
return val ->
val instanceof DATE
return val -> val instanceof DATE
? (int) (((DATE) val).dateValue().toLocalDate().toEpochDay())
: val instanceof Timestamp
? (int)
(((Timestamp) val)
.toLocalDateTime()
.toLocalDate()
.toEpochDay())
: (int) (((Date) val).toLocalDate().toEpochDay());
? (int) (((Timestamp) val)
.toLocalDateTime()
.toLocalDate()
.toEpochDay())
: (int) (((Date) val).toLocalDate().toEpochDay());
case TIME_WITHOUT_TIME_ZONE:
return val ->
val instanceof DATE
? (int)
(((DATE) val).timeValue().toLocalTime().toNanoOfDay()
/ 1_000_000L)
return val -> val instanceof DATE
? (int) (((DATE) val).timeValue().toLocalTime().toNanoOfDay()
/ 1_000_000L)
: (int) (((Time) val).toLocalTime().toNanoOfDay() / 1_000_000L);
case TIMESTAMP_WITHOUT_TIME_ZONE:
return val ->
val instanceof TIMESTAMP
return val -> val instanceof TIMESTAMP
? TimestampData.fromTimestamp(((TIMESTAMP) val).timestampValue())
: TimestampData.fromTimestamp((Timestamp) val);
case TIMESTAMP_WITH_TIME_ZONE:
......@@ -166,9 +153,9 @@ public class OracleRowConverter extends AbstractJdbcRowConverter {
if (val instanceof TIMESTAMPTZ) {
final TIMESTAMPTZ ts = (TIMESTAMPTZ) val;
final ZonedDateTime zdt =
ZonedDateTime.ofInstant(
ts.timestampValue().toInstant(),
ts.getTimeZone().toZoneId());
ZonedDateTime.ofInstant(
ts.timestampValue().toInstant(),
ts.getTimeZone().toZoneId());
return TimestampData.fromLocalDateTime(zdt.toLocalDateTime());
} else {
return TimestampData.fromTimestamp((Timestamp) val);
......
......@@ -24,9 +24,7 @@ import org.apache.flink.connector.jdbc.internal.converter.OracleRowConverter;
import org.apache.flink.table.types.logical.LogicalTypeRoot;
import org.apache.flink.table.types.logical.RowType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
......
......@@ -19,16 +19,6 @@
package org.apache.flink.connector.jdbc.internal.converter;
import oracle.jdbc.internal.OracleBlob;
import oracle.jdbc.internal.OracleClob;
import oracle.sql.BINARY_DOUBLE;
import oracle.sql.BINARY_FLOAT;
import oracle.sql.CHAR;
import oracle.sql.DATE;
import oracle.sql.NUMBER;
import oracle.sql.RAW;
import oracle.sql.TIMESTAMP;
import oracle.sql.TIMESTAMPTZ;
import org.apache.flink.table.data.DecimalData;
import org.apache.flink.table.data.StringData;
import org.apache.flink.table.data.TimestampData;
......@@ -43,6 +33,17 @@ import java.sql.Time;
import java.sql.Timestamp;
import java.time.ZonedDateTime;
import oracle.jdbc.internal.OracleBlob;
import oracle.jdbc.internal.OracleClob;
import oracle.sql.BINARY_DOUBLE;
import oracle.sql.BINARY_FLOAT;
import oracle.sql.CHAR;
import oracle.sql.DATE;
import oracle.sql.NUMBER;
import oracle.sql.RAW;
import oracle.sql.TIMESTAMP;
import oracle.sql.TIMESTAMPTZ;
/**
* Runtime converter that responsible to convert between JDBC object and Flink internal object for
* Oracle.
......@@ -114,7 +115,7 @@ public class OracleRowConverter extends AbstractJdbcRowConverter {
return val ->
val instanceof BigInteger
? DecimalData.fromBigDecimal(
new BigDecimal((BigInteger) val, 0), precision, scale)
new BigDecimal((BigInteger) val, 0), precision, scale)
: DecimalData.fromBigDecimal((BigDecimal) val, precision, scale);
case CHAR:
case VARCHAR:
......
......@@ -15,16 +15,14 @@
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<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>
<artifactId>dlink</artifactId>
<groupId>com.dlink</groupId>
<artifactId>dlink</artifactId>
<version>0.6.8-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>dlink-executor</artifactId>
<properties>
......@@ -49,11 +47,30 @@
<artifactId>dlink-metadata-base</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.dlink</groupId>
<artifactId>dlink-metadata-mysql</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<profiles>
<profile>
<id>flink-1.11</id>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>2.4.1</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.dlink</groupId>
......@@ -70,6 +87,15 @@
<profile>
<id>flink-1.12</id>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>2.4.1</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.dlink</groupId>
......@@ -97,6 +123,12 @@
<artifactId>dlink-flink-1.13</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-shaded-guava</artifactId>
<version>18.0-13.0</version>
<scope>test</scope>
</dependency>
</dependencies>
</profile>
......@@ -113,6 +145,11 @@
<artifactId>dlink-flink-1.14</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</profile>
......@@ -129,6 +166,11 @@
<artifactId>dlink-flink-1.15</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</profile>
......@@ -145,6 +187,11 @@
<artifactId>dlink-flink-1.16</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</profile>
</profiles>
......
/*
*
* 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 com.dlink.interceptor;
import com.dlink.executor.Executor;
import com.dlink.executor.ExecutorSetting;
import com.dlink.executor.LocalStreamExecutor;
import org.junit.Test;
/**
* @author ZackYoung
* @since 0.6.8
*/
public class CdcSourceTests {
@Test
public void printTest() throws Exception {
String statement =
new StringBuilder().append("EXECUTE CDCSOURCE jobname WITH (\n")
.append(" 'connector' = 'mysql-cdc',\n").append(" 'hostname' = '127.0.0.1',\n")
.append(" 'port' = '3306',\n")
.append(" 'username' = 'root',\n").append(" 'password' = '123456',\n")
.append(" 'checkpoint' = '3000',\n").append(" 'scan.startup.mode' = 'initial',\n")
.append(" 'parallelism' = '1',\n").append(" 'source.server-time-zone' = 'UTC',\n")
.append(" 'table-name' = 'dlink\\.dlink_flink_document',\n")
.append(" 'sink.connector'='print'\n").append(")").toString();
ExecutorSetting executorSetting = ExecutorSetting.DEFAULT;
Executor executor = LocalStreamExecutor.buildLocalExecutor(executorSetting);
executor.executeSql(statement);
executor.execute("");
}
}
......@@ -30,7 +30,7 @@
<properties>
<flink.version>1.11.6</flink.version>
<flinkcdc.version>1.1.0</flinkcdc.version>
<flinkcdc.version>1.1.1</flinkcdc.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>${target.java.version}</maven.compiler.source>
<maven.compiler.target>${target.java.version}</maven.compiler.target>
......@@ -109,7 +109,7 @@
</dependency>
<dependency>
<groupId>com.alibaba.ververica</groupId>
<artifactId>flink-connector-mysql-cdc</artifactId>
<artifactId>flink-sql-connector-mysql-cdc</artifactId>
<version>${flinkcdc.version}</version>
</dependency>
<dependency>
......@@ -127,4 +127,13 @@
<version>${flink.version}</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>2.4.1</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
\ No newline at end of file
......@@ -15,22 +15,20 @@
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<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>
<artifactId>dlink-flink</artifactId>
<groupId>com.dlink</groupId>
<artifactId>dlink-flink</artifactId>
<version>0.6.8-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>dlink-flink-1.13</artifactId>
<properties>
<flink.version>1.13.6</flink.version>
<flinkcdc.version>2.2.1</flinkcdc.version>
<flinkcdc.version>2.3.0</flinkcdc.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>${target.java.version}</maven.compiler.source>
<maven.compiler.target>${target.java.version}</maven.compiler.target>
......@@ -50,35 +48,35 @@
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-table-planner_${scala.binary.version}</artifactId>
<version>${flink.version}</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-table-planner-blink_${scala.binary.version}</artifactId>
<version>${flink.version}</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-clients_${scala.binary.version}</artifactId>
<version>${flink.version}</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
......@@ -152,4 +150,4 @@
<version>1.2.3_flink-1.13_${scala.binary.version}</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
</project>
......@@ -28,7 +28,7 @@
<properties>
<flink.version>1.14.6</flink.version>
<flinkcdc.version>2.2.1</flinkcdc.version>
<flinkcdc.version>2.3.0</flinkcdc.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<flink.guava.version>14.0</flink.guava.version>
<commons.version>1.3.1</commons.version>
......
......@@ -31,7 +31,7 @@
<properties>
<flink.version>1.15.2</flink.version>
<flink.guava.version>15.0</flink.guava.version>
<flinkcdc.version>2.2.1</flinkcdc.version>
<flinkcdc.version>2.3.0</flinkcdc.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<commons.version>1.3.1</commons.version>
<maven.compiler.source>${target.java.version}</maven.compiler.source>
......
......@@ -13,10 +13,9 @@
<properties>
<flink.version>1.16.0</flink.version>
<flink.guava.version>15.0</flink.guava.version>
<flinkcdc.version>2.2.1</flinkcdc.version>
<flink.guava.version>16.0</flink.guava.version>
<flinkcdc.version>2.3.0</flinkcdc.version>
<commons.version>1.3.1</commons.version>
<scala.binary.version>2.12</scala.binary.version>
<maven.compiler.source>${target.java.version}</maven.compiler.source>
<maven.compiler.target>${target.java.version}</maven.compiler.target>
</properties>
......
......@@ -566,6 +566,13 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-clean-plugin</artifactId>
<configuration>
<filesets>
<fileset>
<directory>${project.basedir}/extends</directory>
</fileset>
</filesets>
</configuration>
<executions>
<execution>
<goals>
......@@ -574,13 +581,6 @@
<phase>initialize</phase>
</execution>
</executions>
<configuration>
<filesets>
<fileset>
<directory>${project.basedir}/extends</directory>
</fileset>
</filesets>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
......@@ -605,7 +605,7 @@
<eclipse>
<file>style/spotless_dlink_formatter.xml</file>
</eclipse>
<removeUnusedImports/>
<removeUnusedImports />
<importOrder>
<order>\#,com.dlink,org.apache,java,javax,org,com,</order>
</importOrder>
......@@ -642,7 +642,7 @@
<includes>
<include>**/*.md</include>
</includes>
<flexmark/>
<flexmark />
</markdown>
</configuration>
<executions>
......@@ -871,8 +871,7 @@
<artifactId>maven-javadoc-plugin</artifactId>
<configuration>
<additionalJOptions>
<additionalJOption>--add-exports=java.base/sun.net.util=ALL-UNNAMED
</additionalJOption>
<additionalJOption>--add-exports=java.base/sun.net.util=ALL-UNNAMED</additionalJOption>
</additionalJOptions>
</configuration>
</plugin>
......
......@@ -41,6 +41,13 @@
</module>
<module name="TreeWalker">
<!-- Allow use of comment to suppress javadocstyle -->
<module name="SuppressionCommentFilter">
<property name="offCommentFormat" value="CHECKSTYLE.OFF\: ([\w\|]+)"/>
<property name="onCommentFormat" value="CHECKSTYLE.ON\: ([\w\|]+)"/>
<property name="checkFormat" value="$1"/>
</module>
<module name="OuterTypeFilename">
<property name="severity" value="error"/>
</module>
......
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