/
MySqlSymmetricDialect.java
293 lines (250 loc) · 16 KB
/
MySqlSymmetricDialect.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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
/**
* Licensed to JumpMind Inc under one or more contributor
* license agreements. See the NOTICE file distributed
* with this work for additional information regarding
* copyright ownership. JumpMind Inc licenses this file
* to you under the GNU General Public License, version 3.0 (GPLv3)
* (the "License"); you may not use this file except in compliance
* with the License.
*
* You should have received a copy of the GNU General Public License,
* version 3.0 (GPLv3) along with this library; if not, see
* <http://www.gnu.org/licenses/>.
*
* 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.jumpmind.symmetric.db.mysql;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.lang3.StringUtils;
import org.jumpmind.db.model.Table;
import org.jumpmind.db.platform.IDatabasePlatform;
import org.jumpmind.db.platform.PermissionType;
import org.jumpmind.db.sql.ISqlTransaction;
import org.jumpmind.db.sql.JdbcSqlTransaction;
import org.jumpmind.db.sql.SqlException;
import org.jumpmind.db.util.BasicDataSourcePropertyConstants;
import org.jumpmind.db.util.BinaryEncoding;
import org.jumpmind.symmetric.Version;
import org.jumpmind.symmetric.common.ParameterConstants;
import org.jumpmind.symmetric.db.AbstractSymmetricDialect;
import org.jumpmind.symmetric.db.ISymmetricDialect;
import org.jumpmind.symmetric.db.SequenceIdentifier;
import org.jumpmind.symmetric.model.Trigger;
import org.jumpmind.symmetric.service.IParameterService;
import org.jumpmind.symmetric.util.SymmetricUtils;
import org.jumpmind.util.FormatUtils;
public class MySqlSymmetricDialect extends AbstractSymmetricDialect implements ISymmetricDialect {
private static final String PRE_5_1_23 = "_pre_5_1_23";
private static final String PRE_5_7_6 = "_pre_5_7_6";
private static final String POST_5_7_6 = "_post_5_7_6";
private static final String TRANSACTION_ID = "transaction_id";
static final String SYNC_TRIGGERS_DISABLED_USER_VARIABLE = "@sync_triggers_disabled";
static final String SYNC_TRIGGERS_DISABLED_NODE_VARIABLE = "@sync_node_disabled";
static final String SQL_DROP_FUNCTION = "drop function $(functionName)";
static final String SQL_FUNCTION_INSTALLED = "select count(*) from information_schema.routines where routine_name='$(functionName)' and routine_schema in (select database())" ;
static final String SQL_FUNCTION_EQUALS = "select count(*) from information_schema.routines where routine_name='$(functionName)' and routine_schema in (select database())"
+ " and trim(routine_definition)=trim('$(functionBody)')";
private String functionTemplateKeySuffix = null;
private boolean isConvertZeroDateToNull;
private String characterSet;
public MySqlSymmetricDialect(IParameterService parameterService, IDatabasePlatform platform) {
super(parameterService, platform);
this.parameterService = parameterService;
if (parameterService.getString(BasicDataSourcePropertyConstants.DB_POOL_URL).contains("zeroDateTimeBehavior=convertToNull")) {
try {
String sqlMode = platform.getSqlTemplate().queryForString("select @@sql_mode");
isConvertZeroDateToNull = sqlMode == null || (!sqlMode.contains("NO_ZERO_DATE") && !sqlMode.contains("NO_ZERO_IN_DATE"));
if (isConvertZeroDateToNull) {
log.info("Zero dates will be converted to null");
}
} catch (Exception e) {
log.warn("Cannot convert zero dates to null because unable to verify sql_mode: {}", e.getMessage());
}
}
int[] versions = Version.parseVersion(getProductVersion());
if (getMajorVersion() == 5 && (getMinorVersion() == 0 || (getMinorVersion() == 1 && versions[2] < 23))) {
this.functionTemplateKeySuffix = PRE_5_1_23;
} else if (getMajorVersion() == 5 && (getMinorVersion() < 7 || (getMinorVersion() == 7 && versions[2] < 6))) {
this.functionTemplateKeySuffix = PRE_5_7_6;
} else {
this.functionTemplateKeySuffix = POST_5_7_6;
}
characterSet = parameterService.getString(ParameterConstants.DB_MASTER_COLLATION, Version.isOlderThanVersion(getProductVersion(), "5.5.3") ? "utf8" : "utf8mb4");
this.triggerTemplate = new MySqlTriggerTemplate(this, isConvertZeroDateToNull, characterSet);
}
@Override
public boolean supportsTransactionId() {
return true;
}
@Override
public void createRequiredDatabaseObjects() {
String function = null;
String functionBody = null;
String sql = null;
if (this.functionTemplateKeySuffix.equals(PRE_5_1_23)) {
function = this.parameterService.getTablePrefix() + "_" + TRANSACTION_ID + this.functionTemplateKeySuffix;
functionBody =
" begin " +
" declare comm_name varchar(50); " +
" declare comm_value varchar(50); " +
" declare comm_cur cursor for show status like 'Com_commit'; " +
" if @@autocommit = 0 then " +
" open comm_cur; " +
" fetch comm_cur into comm_name, comm_value; " +
" close comm_cur; " +
" return concat(concat(connection_id(), '.'), comm_value); " +
" else " +
" return null; " +
" end if; " +
" end ";
sql = "create function $(functionName)() " +
" returns varchar(50) NOT DETERMINISTIC READS SQL DATA " +
functionBody;
} else if (this.functionTemplateKeySuffix.equals(PRE_5_7_6)){
function = this.parameterService.getTablePrefix() + "_" + TRANSACTION_ID + this.functionTemplateKeySuffix;
functionBody =
" begin \n" +
" declare comm_value varchar(50); \n" +
" declare comm_cur cursor for select VARIABLE_VALUE from INFORMATION_SCHEMA.SESSION_STATUS where VARIABLE_NAME='COM_COMMIT'; \n" +
" open comm_cur; \n" +
" fetch comm_cur into comm_value; \n" +
" close comm_cur; \n" +
" return concat(concat(connection_id(), '.'), comm_value); \n" +
" end ";
sql = "create function $(functionName)() \n" +
" returns varchar(50) NOT DETERMINISTIC READS SQL DATA \n" +
functionBody;
} else {
function = this.parameterService.getTablePrefix() + "_" + TRANSACTION_ID + this.functionTemplateKeySuffix;
functionBody =
" begin \n" +
" declare done int default 0; \n" +
" declare comm_value varchar(50); \n" +
" declare comm_cur cursor for select TRX_ID from INFORMATION_SCHEMA.INNODB_TRX where TRX_MYSQL_THREAD_ID = CONNECTION_ID(); \n" +
" declare continue handler for not found set done = 1; \n" +
" open comm_cur; \n" +
" fetch comm_cur into comm_value; \n" +
" close comm_cur; \n" +
" return concat(concat(connection_id(), '.'), comm_value); \n" +
" end ";
sql = "create function $(functionName)() \n" +
" returns varchar(50) NOT DETERMINISTIC READS SQL DATA \n" +
functionBody;
}
if (!functionEquals(SQL_FUNCTION_EQUALS, function, functionBody)) {
if (installed(SQL_FUNCTION_INSTALLED, function)) {
uninstall(SQL_DROP_FUNCTION, function);
}
install(sql, function);
}
}
private boolean functionEquals(String sqlFunctionEquals, String functionName, String functionBody) {
return platform.getSqlTemplate().queryForInt(replaceTokens(sqlFunctionEquals, functionName, functionBody)) > 0;
}
private String replaceTokens(String sql, String objectName, String functionBody) {
String ddl = super.replaceTokens(sql, objectName);
ddl = FormatUtils.replace("functionBody", StringUtils.replace(functionBody, "'", "''"), ddl);
return ddl;
}
@Override
public void dropRequiredDatabaseObjects() {
String function = this.parameterService.getTablePrefix() + "_" + TRANSACTION_ID + this.functionTemplateKeySuffix;
if (installed(SQL_FUNCTION_INSTALLED, function)) {
uninstall(SQL_DROP_FUNCTION, function);
}
}
@Override
protected boolean doesTriggerExistOnPlatform(String catalog, String schema, String tableName,
String triggerName) {
catalog = catalog == null ? (platform.getDefaultCatalog() == null ? null : platform
.getDefaultCatalog()) : catalog;
String checkCatalogSql = (catalog != null && catalog.length() > 0) ? " and trigger_schema='"
+ catalog + "'"
: "";
return platform
.getSqlTemplate()
.queryForInt(
"select count(*) from information_schema.triggers where trigger_name like ? and event_object_table like ?"
+ checkCatalogSql, new Object[] { triggerName, tableName }) > 0;
}
@Override
public void removeTrigger(StringBuilder sqlBuffer, String catalogName, String schemaName,
String triggerName, String tableName, ISqlTransaction transaction) {
String quote = platform.getDatabaseInfo().getDelimiterToken();
String catalogPrefix = StringUtils.isBlank(catalogName) ? "" : (quote + catalogName + quote + ".");
String sql = "drop trigger if exists " + catalogPrefix + triggerName;
if (getMajorVersion() < 5 || (getMajorVersion() == 5 && getMinorVersion() == 0 && Version.parseVersion(getProductVersion())[2] < 32)) {
sql = "drop trigger " + catalogPrefix + triggerName;
}
logSql(sql, sqlBuffer);
if (parameterService.is(ParameterConstants.AUTO_SYNC_TRIGGERS)) {
log.info("Dropping {} trigger for {}", triggerName, Table.getFullyQualifiedTableName(catalogName, schemaName, tableName));
transaction.execute(sql);
}
}
public void disableSyncTriggers(ISqlTransaction transaction, String nodeId) {
transaction.prepareAndExecute("set " + SYNC_TRIGGERS_DISABLED_USER_VARIABLE + "=1");
if (nodeId != null) {
transaction
.prepareAndExecute("set " + SYNC_TRIGGERS_DISABLED_NODE_VARIABLE + "='" + nodeId + "'");
}
}
public void enableSyncTriggers(ISqlTransaction transaction) {
transaction.prepareAndExecute("set " + SYNC_TRIGGERS_DISABLED_USER_VARIABLE + "=null");
transaction.prepareAndExecute("set " + SYNC_TRIGGERS_DISABLED_NODE_VARIABLE + "=null");
}
public String getSyncTriggersExpression() {
return SYNC_TRIGGERS_DISABLED_USER_VARIABLE + " is null";
}
private final String getTransactionFunctionName() {
return SymmetricUtils.quote(this, platform.getDefaultCatalog()) + "." + parameterService.getTablePrefix() + "_"
+ TRANSACTION_ID + this.functionTemplateKeySuffix;
}
@Override
public String getTransactionTriggerExpression(String defaultCatalog, String defaultSchema,
Trigger trigger) {
return getTransactionFunctionName() + "()";
}
public void cleanDatabase() {
}
@Override
protected String switchCatalogForTriggerInstall(String catalog, ISqlTransaction transaction) {
if (catalog != null) {
Connection c = ((JdbcSqlTransaction) transaction).getConnection();
String previousCatalog;
try {
previousCatalog = c.getCatalog();
c.setCatalog(catalog);
return previousCatalog;
} catch (SQLException e) {
throw new SqlException(e);
}
} else {
return null;
}
}
@Override
public BinaryEncoding getBinaryEncoding() {
return BinaryEncoding.HEX;
}
@Override
protected String getDbSpecificDataHasChangedCondition(Trigger trigger) {
return "var_old_data is null or var_row_data != var_old_data";
}
@Override
public long getCurrentSequenceValue(SequenceIdentifier identifier) {
return platform.getSqlTemplate().queryForLong("select auto_increment from information_schema.tables where table_schema = ? and table_name = ?",
platform.getDefaultCatalog(), parameterService.getTablePrefix() + "_" + identifier.toString());
}
@Override
public PermissionType[] getSymTablePermissions() {
PermissionType[] permissions = { PermissionType.CREATE_TABLE, PermissionType.DROP_TABLE, PermissionType.CREATE_TRIGGER, PermissionType.DROP_TRIGGER, PermissionType.CREATE_ROUTINE};
return permissions;
}
}