-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
SqlServerDialect.java
262 lines (236 loc) · 10.8 KB
/
SqlServerDialect.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
/*
* 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.seatunnel.connectors.seatunnel.jdbc.internal.dialect.sqlserver;
import org.apache.seatunnel.api.table.catalog.TablePath;
import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.converter.JdbcRowConverter;
import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.dialect.DatabaseIdentifier;
import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.dialect.JdbcDialect;
import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.dialect.JdbcDialectTypeMapper;
import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.dialect.SQLUtils;
import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.dialect.dialectenum.FieldIdeEnum;
import org.apache.seatunnel.connectors.seatunnel.jdbc.source.JdbcSourceTable;
import org.apache.commons.lang3.StringUtils;
import lombok.extern.slf4j.Slf4j;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Slf4j
public class SqlServerDialect implements JdbcDialect {
public String fieldIde = FieldIdeEnum.ORIGINAL.getValue();
public SqlServerDialect() {}
public SqlServerDialect(String fieldIde) {
this.fieldIde = fieldIde;
}
@Override
public String dialectName() {
return DatabaseIdentifier.SQLSERVER;
}
@Override
public JdbcRowConverter getRowConverter() {
return new SqlserverJdbcRowConverter();
}
@Override
public JdbcDialectTypeMapper getJdbcDialectTypeMapper() {
return new SqlserverTypeMapper();
}
@Override
public String hashModForField(String fieldName, int mod) {
return "ABS(HASHBYTES('MD5', " + quoteIdentifier(fieldName) + ") % " + mod + ")";
}
@Override
public Optional<String> getUpsertStatement(
String database, String tableName, String[] fieldNames, String[] uniqueKeyFields) {
List<String> nonUniqueKeyFields =
Arrays.stream(fieldNames)
.filter(fieldName -> !Arrays.asList(uniqueKeyFields).contains(fieldName))
.collect(Collectors.toList());
String valuesBinding =
Arrays.stream(fieldNames)
.map(fieldName -> ":" + fieldName + " " + quoteIdentifier(fieldName))
.collect(Collectors.joining(", "));
String usingClause = String.format("SELECT %s", valuesBinding);
String onConditions =
Arrays.stream(uniqueKeyFields)
.map(
fieldName ->
String.format(
"[TARGET].%s=[SOURCE].%s",
quoteIdentifier(fieldName),
quoteIdentifier(fieldName)))
.collect(Collectors.joining(" AND "));
String updateSetClause =
nonUniqueKeyFields.stream()
.map(
fieldName ->
String.format(
"[TARGET].%s=[SOURCE].%s",
quoteIdentifier(fieldName),
quoteIdentifier(fieldName)))
.collect(Collectors.joining(", "));
String insertFields =
Arrays.stream(fieldNames)
.map(this::quoteIdentifier)
.collect(Collectors.joining(", "));
String insertValues =
Arrays.stream(fieldNames)
.map(fieldName -> "[SOURCE]." + quoteIdentifier(fieldName))
.collect(Collectors.joining(", "));
String upsertSQL =
String.format(
"MERGE INTO %s.%s AS [TARGET]"
+ " USING (%s) AS [SOURCE]"
+ " ON (%s)"
+ " WHEN MATCHED THEN"
+ " UPDATE SET %s"
+ " WHEN NOT MATCHED THEN"
+ " INSERT (%s) VALUES (%s);",
quoteDatabaseIdentifier(database),
quoteIdentifier(tableName),
usingClause,
onConditions,
updateSetClause,
insertFields,
insertValues);
return Optional.of(upsertSQL);
}
@Override
public String quoteIdentifier(String identifier) {
if (identifier.contains(".")) {
String[] parts = identifier.split("\\.");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < parts.length - 1; i++) {
sb.append("[").append(parts[i]).append("]").append(".");
}
return sb.append("[")
.append(getFieldIde(parts[parts.length - 1], fieldIde))
.append("]")
.toString();
}
return "[" + getFieldIde(identifier, fieldIde) + "]";
}
@Override
public String quoteDatabaseIdentifier(String identifier) {
return "[" + identifier + "]";
}
@Override
public String tableIdentifier(TablePath tablePath) {
return quoteIdentifier(tablePath.getFullName());
}
@Override
public TablePath parse(String tablePath) {
return TablePath.of(tablePath, true);
}
@Override
public Long approximateRowCntStatement(Connection connection, JdbcSourceTable table)
throws SQLException {
// 1. If no query is configured, use TABLE STATUS.
// 2. If a query is configured but does not contain a WHERE clause and tablePath is
// configured, use TABLE STATUS.
// 3. If a query is configured with a WHERE clause, or a query statement is configured but
// tablePath is TablePath.DEFAULT, use COUNT(*).
boolean useTableStats =
StringUtils.isBlank(table.getQuery())
|| (!table.getQuery().toLowerCase().contains("where")
&& table.getTablePath() != null
&& !TablePath.DEFAULT
.getFullName()
.equals(table.getTablePath().getFullName()));
if (useTableStats) {
TablePath tablePath = table.getTablePath();
try (Statement stmt = connection.createStatement()) {
if (StringUtils.isNotBlank(tablePath.getDatabaseName())) {
String useDatabaseStatement =
String.format(
"USE %s;",
quoteDatabaseIdentifier(tablePath.getDatabaseName()));
log.info("Split Chunk, approximateRowCntStatement: {}", useDatabaseStatement);
stmt.execute(useDatabaseStatement);
}
String rowCountQuery =
String.format(
"SELECT Total_Rows = SUM(st.row_count) FROM sys"
+ ".dm_db_partition_stats st WHERE object_name(object_id) = '%s' AND index_id < 2;",
tablePath.getTableName());
log.info("Split Chunk, approximateRowCntStatement: {}", rowCountQuery);
try (ResultSet rs = stmt.executeQuery(rowCountQuery)) {
if (!rs.next()) {
throw new SQLException(
String.format(
"No result returned after running query [%s]",
rowCountQuery));
}
return rs.getLong(1);
}
}
}
return SQLUtils.countForSubquery(connection, table.getQuery());
}
@Override
public Object queryNextChunkMax(
Connection connection,
JdbcSourceTable table,
String columnName,
int chunkSize,
Object includedLowerBound)
throws SQLException {
String quotedColumn = quoteIdentifier(columnName);
String sqlQuery;
if (StringUtils.isNotBlank(table.getQuery())) {
sqlQuery =
String.format(
"SELECT MAX(%s) FROM ("
+ "SELECT TOP (%s) %s FROM (%s) AS T1 WHERE %s >= ? ORDER BY %s ASC"
+ ") AS T2",
quotedColumn,
chunkSize,
quotedColumn,
table.getQuery(),
quotedColumn,
quotedColumn);
} else {
sqlQuery =
String.format(
"SELECT MAX(%s) FROM ("
+ "SELECT TOP (%s) %s FROM %s WHERE %s >= ? ORDER BY %s ASC "
+ ") AS T",
quotedColumn,
chunkSize,
quotedColumn,
tableIdentifier(table.getTablePath()),
quotedColumn,
quotedColumn);
}
try (PreparedStatement ps = connection.prepareStatement(sqlQuery)) {
ps.setObject(1, includedLowerBound);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return rs.getObject(1);
} else {
// this should never happen
throw new SQLException(
String.format("No result returned after running query [%s]", sqlQuery));
}
}
}
}
}