-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
H2Database.java
405 lines (361 loc) · 12 KB
/
H2Database.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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
package liquibase.database.core;
import liquibase.CatalogAndSchema;
import liquibase.Scope;
import liquibase.database.AbstractJdbcDatabase;
import liquibase.database.DatabaseConnection;
import liquibase.database.OfflineConnection;
import liquibase.database.jvm.JdbcConnection;
import liquibase.exception.DatabaseException;
import liquibase.exception.DateParseException;
import liquibase.exception.UnexpectedLiquibaseException;
import liquibase.statement.DatabaseFunction;
import liquibase.util.ISODateFormat;
import liquibase.util.JdbcUtil;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class H2Database extends AbstractJdbcDatabase {
private static String START_CONCAT = "CONCAT(";
private static String END_CONCAT = ")";
private static String SEP_CONCAT = ", ";
private static List keywords = Arrays.asList(
"ALL",
"AND",
"ANY",
"ARRAY",
"AS",
"ASYMMETRIC",
"AUTHORIZATION",
"BETWEEN",
"BOTH",
"CASE",
"CAST",
"CHECK",
"CONSTRAINT",
"CROSS",
"CURRENT_CATALOG",
"CURRENT_DATE",
"CURRENT_PATH",
"CURRENT_ROLE",
"CURRENT_SCHEMA",
"CURRENT_TIME",
"CURRENT_TIMESTAMP",
"CURRENT_USER",
"DAY",
"DEFAULT",
"DISTINCT",
"ELSE",
"END",
"EXCEPT",
"EXISTS",
"FALSE",
"FETCH",
"FILTER",
"FOR",
"FOREIGN",
"FROM",
"FULL",
"GROUP",
"GROUPS",
"HAVING",
"HOUR",
"IF",
"ILIKE",
"IN",
"ILIKE",
"IN",
"INNER",
"INTERSECT",
"INTERSECTS",
"INTERVAL",
"IS",
"JOIN",
"KEY",
"LEADING",
"LEFT",
"LIKE",
"LIMIT",
"LOCALTIME",
"LOCALTIMESTAMP",
"MINUS",
"MINUTE",
"MONTH",
"NATURAL",
"NOT",
"NULL",
"OFFSET",
"ON",
"OR",
"ORDER",
"OVER",
"PARTITION",
"PRIMARY",
"QUALIFY",
"RANGE",
"REGEXP",
"RIGHT",
"ROW",
"ROWNUM",
"ROWS",
"SELECT",
"SESSION_USER",
"SET",
"SOME",
"SYMMETRIC",
"SYSTEM_USER",
"SYSDATE",
"SYSTIME",
"SYSTIMESTAMP",
"TABLE",
"TO",
"TODAY",
"TOP",
"TRAILING",
"TRUE",
"UNESCAPE",
"UNION",
"UNIQUE",
"UNKNOWN",
"USER",
"USING",
"VALUE",
"VALUES",
"WHEN",
"WHERE",
"WINDOW",
"WITH",
"YEAR",
"_ROWID_"
);
private String connectionSchemaName = "PUBLIC";
private static final int MAJOR_VERSION_FOR_MINMAX_IN_SEQUENCES = 1;
private static final int MINOR_VERSION_FOR_MINMAX_IN_SEQUENCES = 3;
private static final int BUILD_VERSION_FOR_MINMAX_IN_SEQUENCES = 175;
public H2Database() {
super.unquotedObjectsAreUppercased=true;
super.setCurrentDateTimeFunction("NOW()");
// for current date
this.dateFunctions.add(new DatabaseFunction("CURRENT_DATE"));
this.dateFunctions.add(new DatabaseFunction("CURDATE"));
this.dateFunctions.add(new DatabaseFunction("SYSDATE"));
this.dateFunctions.add(new DatabaseFunction("TODAY"));
// for current time
this.dateFunctions.add(new DatabaseFunction("CURRENT_TIME"));
this.dateFunctions.add(new DatabaseFunction("CURTIME"));
// for current timestamp
this.dateFunctions.add(new DatabaseFunction("CURRENT_TIMESTAMP"));
this.dateFunctions.add(new DatabaseFunction("NOW"));
super.sequenceNextValueFunction = "NEXTVAL('%s')";
super.sequenceCurrentValueFunction = "CURRVAL('%s')";
// According to http://www.h2database.com/html/datatypes.html, retrieved on 2017-06-05
super.unmodifiableDataTypes.addAll(Arrays.asList("int", "integer", "mediumint", "int4", "signed", "boolean",
"bit", "bool", "tinyint", "smallint", "int2", "year", "bigint", "int8", "identity", "float", "float8",
"real", "float4", "time", "date", "timestamp", "datetime", "smalldatetime", "timestamp with time zone",
"other", "uuid", "array", "geometry"));
}
@Override
public String getShortName() {
return "h2";
}
@Override
public Integer getDefaultPort() {
return 8082;
}
@Override
protected String getDefaultDatabaseProductName() {
return "H2";
}
@Override
public String getDefaultDriver(String url) {
if (url.startsWith("jdbc:h2")) {
return "org.h2.Driver";
}
return null;
}
@Override
public int getPriority() {
return PRIORITY_DATABASE;
}
@Override
public boolean isCorrectDatabaseImplementation(DatabaseConnection conn) throws DatabaseException {
return "H2".equals(conn.getDatabaseProductName());
}
@Override
public boolean supportsTablespaces() {
return false;
}
@Override
public String getViewDefinition(CatalogAndSchema schema, String name) throws DatabaseException {
String definition = super.getViewDefinition(schema, name);
if (!definition.startsWith("SELECT")) {
definition = definition.replaceFirst(".*?\\n", ""); //some h2 versions return "create view....as\nselect
}
definition = definition.replaceFirst("/\\*.*",""); //sometimes includes comments at the end
return definition;
}
@Override
public Date parseDate(String dateAsString) throws DateParseException {
try {
return new ISODateFormat().parse(dateAsString);
} catch (ParseException e) {
throw new DateParseException(dateAsString);
}
}
@Override
public boolean isSafeToRunUpdate() throws DatabaseException {
if (getConnection() == null) {
return true;
}
String url = getConnection().getURL();
boolean isLocalURL = (
super.isSafeToRunUpdate()
|| (!url.startsWith("jdbc:h2:tcp:") && (!url.startsWith("jdbc:h2:ssl:"))) // exclude remote URLs
);
return isLocalURL;
}
@Override
public boolean supportsSequences() {
return true;
}
@Override
protected String getConnectionSchemaName() {
return connectionSchemaName;
}
@Override
public String getConcatSql(String... values) {
if (values == null) {
return null;
}
return getConcatSql(Arrays.asList(values));
}
/**
* Recursive way of building CONCAT instruction
*
* @param values a non null List of String
* @return a String containing the CONCAT instruction with all elements, or only a value if there is only one element in the list
*/
private String getConcatSql(List<String> values) {
if (values.size() == 1) {
return values.get(0);
} else {
return START_CONCAT + values.get(0) + SEP_CONCAT + getConcatSql(values.subList(1, values.size())) + END_CONCAT;
}
}
@Override
public String getDateLiteral(String isoDate) {
return "'" + isoDate.replace('T', ' ') + "'";
}
@Override
public boolean isReservedWord(String objectName) {
return keywords.contains(objectName.toUpperCase(Locale.US));
}
@Override
public boolean supportsInitiallyDeferrableColumns() {
return false;
}
@Override
protected String getAutoIncrementClause() {
try {
if (getDatabaseMajorVersion() == 1) {
return "AUTO_INCREMENT";
} else {
return "GENERATED BY DEFAULT AS IDENTITY";
}
} catch (DatabaseException e) {
return "AUTO_INCREMENT";
}
}
@Override
protected String getAutoIncrementStartWithClause() {
return "%d";
}
@Override
protected String getAutoIncrementByClause() {
return "%d";
}
@Override
public boolean createsIndexesForForeignKeys() {
return true;
}
@Override
public boolean supportsDropTableCascadeConstraints() {
return true;
}
@Override
public void setConnection(DatabaseConnection conn) {
Connection sqlConn = null;
if (!(conn instanceof OfflineConnection)) {
try {
if (conn instanceof JdbcConnection) {
Method wrappedConn = conn.getClass().getMethod("getWrappedConnection");
wrappedConn.setAccessible(true);
sqlConn = (Connection) wrappedConn.invoke(conn);
}
} catch (Exception e) {
throw new UnexpectedLiquibaseException(e);
}
if (sqlConn != null) {
Statement statement = null;
ResultSet resultSet = null;
try {
statement = sqlConn.createStatement();
resultSet = statement.executeQuery("SELECT SCHEMA()");
String schemaName = null;
if (resultSet.next()) {
schemaName = resultSet.getString(1);
}
if (schemaName != null) {
this.connectionSchemaName = schemaName;
}
} catch (SQLException e) {
Scope.getCurrentScope().getLog(getClass()).info("Could not read current schema name: "+e.getMessage());
} finally {
JdbcUtil.close(resultSet, statement);
}
}
}
super.setConnection(conn);
}
public boolean supportsMinMaxForSequences() {
try {
if (getDatabaseMajorVersion() > MAJOR_VERSION_FOR_MINMAX_IN_SEQUENCES) {
return true;
} else if (getDatabaseMajorVersion() == MAJOR_VERSION_FOR_MINMAX_IN_SEQUENCES
&& getDatabaseMinorVersion() > MINOR_VERSION_FOR_MINMAX_IN_SEQUENCES) {
return true;
} else if (getDatabaseMajorVersion() == MAJOR_VERSION_FOR_MINMAX_IN_SEQUENCES
&& getDatabaseMinorVersion() == MINOR_VERSION_FOR_MINMAX_IN_SEQUENCES
&& getBuildVersion() >= BUILD_VERSION_FOR_MINMAX_IN_SEQUENCES) {
return true;
}
} catch (DatabaseException e) {
Scope.getCurrentScope().getLog(getClass()).warning("Failed to determine database version, reported error: " + e.getMessage());
}
return false;
}
private int getBuildVersion() throws DatabaseException {
Pattern patchVersionPattern = Pattern.compile("^(?:\\d+\\.)(?:\\d+\\.)(\\d+).*$");
Matcher matcher = patchVersionPattern.matcher(getDatabaseProductVersion());
if (matcher.matches()) {
return Integer.parseInt(matcher.group(1));
}
else {
Scope.getCurrentScope().getLog(getClass()).warning("Failed to determine H2 build number from product version: " + getDatabaseProductVersion());
return -1;
}
}
@Override
public int getMaxFractionalDigitsForTimestamp() {
// http://www.h2database.com/html/datatypes.html seems to imply 9 digits
return 9;
}
}