|
| 1 | +package com.dtstack.flink.sql.sink.ocean; |
| 2 | + |
| 3 | +import com.dtstack.flink.sql.sink.rdb.dialect.JDBCDialect; |
| 4 | + |
| 5 | +import java.util.Arrays; |
| 6 | +import java.util.Optional; |
| 7 | +import java.util.stream.Collectors; |
| 8 | + |
| 9 | +/** |
| 10 | + * @author : tiezhu |
| 11 | + * @date : 2020/3/24 |
| 12 | + */ |
| 13 | +public class OceanbaseDialect implements JDBCDialect { |
| 14 | + @Override |
| 15 | + public boolean canHandle(String url) { |
| 16 | + return url.startsWith("jdbc:mysql:"); |
| 17 | + } |
| 18 | + |
| 19 | + @Override |
| 20 | + public Optional<String> defaultDriverName() { |
| 21 | + return Optional.of("com.mysql.jdbc.Driver"); |
| 22 | + } |
| 23 | + |
| 24 | + @Override |
| 25 | + public String quoteIdentifier(String identifier) { |
| 26 | + return "`" + identifier + "`"; |
| 27 | + } |
| 28 | + |
| 29 | + @Override |
| 30 | + public Optional<String> getUpsertStatement(String schema, |
| 31 | + String tableName, |
| 32 | + String[] fieldNames, |
| 33 | + String[] uniqueKeyFields, |
| 34 | + boolean allReplace) { |
| 35 | + return allReplace ? |
| 36 | + buildReplaceIntoStatement(tableName, fieldNames) : |
| 37 | + buildDuplicateUpsertStatement(tableName, fieldNames); |
| 38 | + } |
| 39 | + |
| 40 | + private Optional<String> buildDuplicateUpsertStatement(String tableName, String[] fieldsName) { |
| 41 | + String updateClause = Arrays.stream(fieldsName).map(f -> quoteIdentifier(f) |
| 42 | + + "IFNULL(VALUES(" + quoteIdentifier(f) + ")," + quoteIdentifier(f) + ")") |
| 43 | + .collect(Collectors.joining(",")); |
| 44 | + return Optional.of(getInsertIntoStatement("", tableName, fieldsName, null) + |
| 45 | + " ON DUPLICATE KEY UPDATE " + updateClause |
| 46 | + ); |
| 47 | + } |
| 48 | + |
| 49 | + private Optional<String> buildReplaceIntoStatement(String tableName, String[] fieldsNames) { |
| 50 | + String columns = Arrays.stream(fieldsNames) |
| 51 | + .map(this::quoteIdentifier) |
| 52 | + .collect(Collectors.joining(",")); |
| 53 | + String placeholders = Arrays.stream(fieldsNames) |
| 54 | + .map(f -> "?") |
| 55 | + .collect(Collectors.joining(",")); |
| 56 | + return Optional.of("REPLACE INTO " + quoteIdentifier(tableName) + |
| 57 | + "(" + columns + ") VALUES (" + placeholders + ")"); |
| 58 | + } |
| 59 | +} |
0 commit comments