-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
H2Dialect.java
362 lines (308 loc) · 11.4 KB
/
H2Dialect.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
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.dialect;
import org.hibernate.JDBCException;
import org.hibernate.PessimisticLockException;
import org.hibernate.boot.TempTableDdlTransactionHandling;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.dialect.function.CommonFunctionFactory;
import org.hibernate.dialect.hint.IndexQueryHintHandler;
import org.hibernate.dialect.identity.H2IdentityColumnSupport;
import org.hibernate.dialect.identity.IdentityColumnSupport;
import org.hibernate.dialect.pagination.LimitHandler;
import org.hibernate.dialect.pagination.LimitOffsetLimitHandler;
import org.hibernate.dialect.pagination.OffsetFetchLimitHandler;
import org.hibernate.dialect.sequence.H2SequenceSupport;
import org.hibernate.dialect.sequence.SequenceSupport;
import org.hibernate.engine.jdbc.dialect.spi.DialectResolutionInfo;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.exception.LockAcquisitionException;
import org.hibernate.exception.spi.SQLExceptionConversionDelegate;
import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtractor;
import org.hibernate.exception.spi.ViolatedConstraintNameExtractor;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.JdbcExceptionHelper;
import org.hibernate.metamodel.mapping.EntityMappingType;
import org.hibernate.metamodel.spi.RuntimeModelCreationContext;
import org.hibernate.query.TemporalUnit;
import org.hibernate.query.spi.QueryEngine;
import org.hibernate.query.sqm.mutation.internal.idtable.AfterUseAction;
import org.hibernate.query.sqm.mutation.internal.idtable.IdTable;
import org.hibernate.query.sqm.mutation.internal.idtable.LocalTemporaryTableStrategy;
import org.hibernate.query.sqm.mutation.spi.SqmMultiTableMutationStrategy;
import org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorH2DatabaseImpl;
import org.hibernate.tool.schema.extract.spi.SequenceInformationExtractor;
import org.jboss.logging.Logger;
import java.sql.SQLException;
import static org.hibernate.query.TemporalUnit.SECOND;
/**
* A dialect compatible with the H2 database.
*
* @author Thomas Mueller
*/
public class H2Dialect extends Dialect {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(
CoreMessageLogger.class,
H2Dialect.class.getName()
);
private final LimitHandler limitHandler;
private final boolean cascadeConstraints;
public H2Dialect() {
this(0, 0);
}
public H2Dialect(int version, int buildId) {
super();
//TODO: actually I think all builds of 1.4 support OFFSET FETCH
limitHandler = version > 140 || version == 140 && buildId >= 199
? OffsetFetchLimitHandler.INSTANCE
: LimitOffsetLimitHandler.INSTANCE;
//Note: H2 'bit' is a synonym for 'boolean', not a proper bit type
// registerColumnType( Types.BIT, "bit" );
if ( version < 120 || version == 120 && buildId < 139 ) {
LOG.unsupportedMultiTableBulkHqlJpaql( version / 100, version % 100 / 10, buildId );
}
// Prior to 1.4.200 the 'cascade' in 'drop table' was implicit
cascadeConstraints = version > 140 || version == 140 && buildId >= 200;
getDefaultProperties().setProperty( AvailableSettings.STATEMENT_BATCH_SIZE, DEFAULT_BATCH_SIZE );
// http://code.google.com/p/h2database/issues/detail?id=235
getDefaultProperties().setProperty( AvailableSettings.NON_CONTEXTUAL_LOB_CREATION, "true" );
}
private static int parseBuildId(DialectResolutionInfo info) {
String[] bits = info.getDatabaseVersion().split("[. ]");
return bits.length > 2 ? Integer.parseInt( bits[2] ) : 0;
}
public H2Dialect(DialectResolutionInfo info) {
this(
info.getDatabaseMajorVersion()*100
+ info.getDatabaseMinorVersion()*10,
parseBuildId( info )
);
}
@Override
public void initializeFunctionRegistry(QueryEngine queryEngine) {
super.initializeFunctionRegistry( queryEngine );
CommonFunctionFactory.pi( queryEngine );
CommonFunctionFactory.cot( queryEngine );
CommonFunctionFactory.radians( queryEngine );
CommonFunctionFactory.degrees( queryEngine );
CommonFunctionFactory.log10( queryEngine );
CommonFunctionFactory.rand( queryEngine );
CommonFunctionFactory.truncate( queryEngine );
CommonFunctionFactory.soundex( queryEngine );
CommonFunctionFactory.translate( queryEngine );
CommonFunctionFactory.bitand( queryEngine );
CommonFunctionFactory.bitor( queryEngine );
CommonFunctionFactory.bitxor( queryEngine );
CommonFunctionFactory.bitAndOr( queryEngine );
CommonFunctionFactory.yearMonthDay( queryEngine );
CommonFunctionFactory.hourMinuteSecond( queryEngine );
CommonFunctionFactory.dayOfWeekMonthYear( queryEngine );
CommonFunctionFactory.weekQuarter( queryEngine );
CommonFunctionFactory.daynameMonthname( queryEngine );
CommonFunctionFactory.localtimeLocaltimestamp( queryEngine );
CommonFunctionFactory.bitLength( queryEngine );
CommonFunctionFactory.octetLength( queryEngine );
CommonFunctionFactory.ascii( queryEngine );
CommonFunctionFactory.octetLength( queryEngine );
CommonFunctionFactory.space( queryEngine );
CommonFunctionFactory.repeat( queryEngine );
CommonFunctionFactory.chr_char( queryEngine );
CommonFunctionFactory.instr( queryEngine );
CommonFunctionFactory.substr( queryEngine );
//also natively supports ANSI-style substring()
CommonFunctionFactory.position( queryEngine );
CommonFunctionFactory.trim1( queryEngine );
CommonFunctionFactory.concat_pipeOperator( queryEngine );
CommonFunctionFactory.nowCurdateCurtime( queryEngine );
CommonFunctionFactory.sysdate( queryEngine );
CommonFunctionFactory.insert( queryEngine );
// CommonFunctionFactory.everyAny( queryEngine ); //this would work too
CommonFunctionFactory.everyAny_boolAndOr( queryEngine );
CommonFunctionFactory.median( queryEngine );
CommonFunctionFactory.stddevPopSamp( queryEngine );
CommonFunctionFactory.varPopSamp( queryEngine );
CommonFunctionFactory.format_formatdatetime( queryEngine );
CommonFunctionFactory.rownum( queryEngine );
}
/**
* In H2, the extract() function does not return
* fractional seconds for the the field
* {@link TemporalUnit#SECOND}. We work around
* this here with two calls to extract().
*/
@Override
public String extractPattern(TemporalUnit unit) {
return unit == SECOND
? "(" + super.extractPattern(unit) + "+extract(nanosecond from ?2)/1e9)"
: super.extractPattern(unit);
}
@Override
public String timestampaddPattern(TemporalUnit unit, boolean timestamp) {
return "dateadd(?1, ?2, ?3)";
}
@Override
public String timestampdiffPattern(TemporalUnit unit, boolean fromTimestamp, boolean toTimestamp) {
return "datediff(?1, ?2, ?3)";
}
@Override
public String toBooleanValueString(boolean bool) {
return String.valueOf( bool );
}
@Override
public LimitHandler getLimitHandler() {
return limitHandler;
}
@Override
public boolean supportsIfExistsAfterTableName() {
return !supportsIfExistsBeforeTableName();
}
@Override
public boolean supportsIfExistsBeforeTableName() {
return cascadeConstraints;
}
@Override
public boolean supportsIfExistsAfterAlterTable() {
return cascadeConstraints;
}
@Override
public boolean supportsIfExistsBeforeConstraintName() {
return true;
}
@Override
public String getCascadeConstraintsString() {
return cascadeConstraints ? " cascade "
: super.getCascadeConstraintsString();
}
@Override
public boolean dropConstraints() {
return false;
}
@Override
public SequenceSupport getSequenceSupport() {
return H2SequenceSupport.INSTANCE;
}
@Override
public String getQuerySequencesString() {
return "select * from information_schema.sequences";
}
@Override
public SequenceInformationExtractor getSequenceInformationExtractor() {
return SequenceInformationExtractorH2DatabaseImpl.INSTANCE;
}
@Override
public String getFromDual() {
return "from dual";
}
@Override
public SqmMultiTableMutationStrategy getFallbackSqmMutationStrategy(
EntityMappingType entityDescriptor,
RuntimeModelCreationContext runtimeModelCreationContext) {
return new LocalTemporaryTableStrategy(
new IdTable( entityDescriptor, basename -> "HT_" + basename ),
this::getTypeName,
AfterUseAction.CLEAN,
TempTableDdlTransactionHandling.NONE,
runtimeModelCreationContext.getSessionFactory()
);
}
@Override
public ViolatedConstraintNameExtractor getViolatedConstraintNameExtracter() {
return EXTRACTOR;
}
private static final ViolatedConstraintNameExtractor EXTRACTOR =
new TemplatedViolatedConstraintNameExtractor( sqle -> {
// 23000: Check constraint violation: {0}
// 23001: Unique index or primary key violation: {0}
if ( sqle.getSQLState().startsWith( "23" ) ) {
final String message = sqle.getMessage();
final int idx = message.indexOf( "violation: " );
if ( idx > 0 ) {
return message.substring( idx + "violation: ".length() );
}
}
return null;
} );
@Override
public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() {
SQLExceptionConversionDelegate delegate = super.buildSQLExceptionConversionDelegate();
if (delegate == null) {
delegate = new SQLExceptionConversionDelegate() {
@Override
public JDBCException convert(SQLException sqlException, String message, String sql) {
final int errorCode = JdbcExceptionHelper.extractErrorCode( sqlException );
switch (errorCode) {
case 40001:
// DEADLOCK DETECTED
return new LockAcquisitionException(message, sqlException, sql);
case 50200:
// LOCK NOT AVAILABLE
return new PessimisticLockException(message, sqlException, sql);
case 90006:
// NULL not allowed for column [90006-145]
final String constraintName = getViolatedConstraintNameExtracter().extractConstraintName(sqlException);
return new ConstraintViolationException(message, sqlException, sql, constraintName);
}
return null;
}
};
}
return delegate;
}
@Override
public boolean supportsCurrentTimestampSelection() {
return true;
}
@Override
public boolean isCurrentTimestampSelectStringCallable() {
return false;
}
@Override
public String getCurrentTimestampSelectString() {
return "call current_timestamp()";
}
@Override
public boolean supportsUnionAll() {
return true;
}
// Overridden informational metadata ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@Override
public boolean supportsLobValueChangePropagation() {
return false;
}
@Override
public boolean requiresParensForTupleDistinctCounts() {
return true;
}
@Override
public boolean doesReadCommittedCauseWritersToBlockReaders() {
// see http://groups.google.com/group/h2-database/browse_thread/thread/562d8a49e2dabe99?hl=en
return true;
}
@Override
public boolean supportsTuplesInSubqueries() {
return false;
}
@Override
public IdentityColumnSupport getIdentityColumnSupport() {
return new H2IdentityColumnSupport();
}
@Override
public String getQueryHintString(String query, String hints) {
return IndexQueryHintHandler.INSTANCE.addQueryHints( query, hints );
}
@Override
public String translateDatetimeFormat(String format) {
return new Replacer( format, "'", "''" ).replace("e", "u").result(); //NICE!!
}
public String translateExtractField(TemporalUnit unit) {
switch ( unit ) {
case DAY_OF_MONTH: return "day";
case WEEK: return "iso_week";
default: return unit.toString();
}
}
}