-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
CacheDialect.java
376 lines (318 loc) · 11.7 KB
/
CacheDialect.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
/*
* 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.LockMode;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.function.CommonFunctionFactory;
import org.hibernate.dialect.identity.CacheIdentityColumnSupport;
import org.hibernate.dialect.identity.IdentityColumnSupport;
import org.hibernate.dialect.lock.*;
import org.hibernate.dialect.pagination.LimitHandler;
import org.hibernate.dialect.pagination.TopLimitHandler;
import org.hibernate.dialect.sequence.CacheSequenceSupport;
import org.hibernate.dialect.sequence.SequenceSupport;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.exception.DataException;
import org.hibernate.exception.spi.SQLExceptionConversionDelegate;
import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtractor;
import org.hibernate.exception.spi.ViolatedConstraintNameExtractor;
import org.hibernate.internal.util.JdbcExceptionHelper;
import org.hibernate.persister.entity.Lockable;
import org.hibernate.query.TemporalUnit;
import org.hibernate.query.spi.QueryEngine;
import org.hibernate.sql.CacheJoinFragment;
import org.hibernate.sql.JoinFragment;
import org.hibernate.type.StandardBasicTypes;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import static org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtractor.extractUsingTemplate;
/**
* Dialect for Intersystems Caché SQL 2007.1 and above.
*
* @author Jonathan Levinson
*/
public class CacheDialect extends Dialect {
public CacheDialect() {
super();
// Note: For object <-> SQL datatype mappings see:
// Configuration Manager > Advanced > SQL > System DDL Datatype Mappings
registerColumnType( Types.BOOLEAN, "bit" );
//no explicit precision
registerColumnType(Types.TIMESTAMP, "timestamp");
registerColumnType(Types.TIMESTAMP_WITH_TIMEZONE, "timestamp");
registerColumnType( Types.BLOB, "image" );
registerColumnType( Types.CLOB, "text" );
getDefaultProperties().setProperty( Environment.USE_STREAMS_FOR_BINARY, "false" );
getDefaultProperties().setProperty( Environment.STATEMENT_BATCH_SIZE, DEFAULT_BATCH_SIZE );
getDefaultProperties().setProperty( Environment.USE_SQL_COMMENTS, "false" );
}
private static void useJdbcEscape(QueryEngine queryEngine, String name) {
//Yep, this seems to be truly necessary for certain functions
queryEngine.getSqmFunctionRegistry().wrapInJdbcEscape(
name,
queryEngine.getSqmFunctionRegistry().findFunctionDescriptor(name)
);
}
@Override
public int getPreferredSqlTypeCodeForBoolean() {
return Types.BIT;
}
@Override
public int getDefaultDecimalPrecision() {
//the largest *meaningful* value
return 19;
}
@Override
public void initializeFunctionRegistry(QueryEngine queryEngine) {
super.initializeFunctionRegistry( queryEngine );
CommonFunctionFactory.repeat( queryEngine );
CommonFunctionFactory.trim2( queryEngine );
CommonFunctionFactory.substr( queryEngine );
//also natively supports ANSI-style substring()
CommonFunctionFactory.concat_pipeOperator( queryEngine );
CommonFunctionFactory.cot( queryEngine );
CommonFunctionFactory.log10( queryEngine );
CommonFunctionFactory.log( queryEngine );
CommonFunctionFactory.pi( queryEngine );
CommonFunctionFactory.space( queryEngine );
CommonFunctionFactory.hourMinuteSecond( queryEngine );
CommonFunctionFactory.yearMonthDay( queryEngine );
CommonFunctionFactory.weekQuarter( queryEngine );
CommonFunctionFactory.daynameMonthname( queryEngine );
CommonFunctionFactory.toCharNumberDateTimestamp( queryEngine );
CommonFunctionFactory.truncate( queryEngine );
CommonFunctionFactory.dayofweekmonthyear( queryEngine );
CommonFunctionFactory.repeat_replicate( queryEngine );
CommonFunctionFactory.datepartDatename( queryEngine );
CommonFunctionFactory.ascii( queryEngine );
CommonFunctionFactory.chr_char( queryEngine );
CommonFunctionFactory.nowCurdateCurtime( queryEngine );
CommonFunctionFactory.sysdate( queryEngine );
CommonFunctionFactory.stddev( queryEngine );
CommonFunctionFactory.stddevPopSamp( queryEngine );
CommonFunctionFactory.variance( queryEngine );
CommonFunctionFactory.varPopSamp( queryEngine );
CommonFunctionFactory.lastDay( queryEngine );
queryEngine.getSqmFunctionRegistry().registerBinaryTernaryPattern(
"locate",
StandardBasicTypes.INTEGER,
"$find(?2, ?1)",
"$find(?2, ?1, ?3)"
).setArgumentListSignature("(pattern, string[, start])");
useJdbcEscape(queryEngine, "sin");
useJdbcEscape(queryEngine, "cos");
useJdbcEscape(queryEngine, "tan");
useJdbcEscape(queryEngine, "asin");
useJdbcEscape(queryEngine, "acos");
useJdbcEscape(queryEngine, "atan");
useJdbcEscape(queryEngine, "atan2");
useJdbcEscape(queryEngine, "exp");
useJdbcEscape(queryEngine, "log");
useJdbcEscape(queryEngine, "log10");
useJdbcEscape(queryEngine, "pi");
useJdbcEscape(queryEngine, "truncate");
useJdbcEscape(queryEngine, "left");
useJdbcEscape(queryEngine, "right");
useJdbcEscape(queryEngine, "hour");
useJdbcEscape(queryEngine, "minute");
useJdbcEscape(queryEngine, "second");
useJdbcEscape(queryEngine, "week");
useJdbcEscape(queryEngine, "quarter");
useJdbcEscape(queryEngine, "dayname");
useJdbcEscape(queryEngine, "monthname");
useJdbcEscape(queryEngine, "dayofweek");
useJdbcEscape(queryEngine, "dayofmonth");
useJdbcEscape(queryEngine, "dayofyear");
}
@Override
public String extractPattern(TemporalUnit unit) {
return "datepart(?1, ?2)";
}
@Override
public String timestampaddPattern(TemporalUnit unit, boolean timestamp) {
switch (unit) {
case NANOSECOND:
case NATIVE:
return "dateadd(millisecond, (?2)/1e6, ?3)";
default:
return "dateadd(?1, ?2, ?3)";
}
}
@Override
public String timestampdiffPattern(TemporalUnit unit, boolean fromTimestamp, boolean toTimestamp) {
switch (unit) {
case NANOSECOND:
case NATIVE:
return "datediff(millisecond, ?2, ?3)*1e6";
default:
return "datediff(?1, ?2, ?3)";
}
}
// DDL support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@Override
public boolean qualifyIndexName() {
// Do we need to qualify index names with the schema name?
return false;
}
@Override
@SuppressWarnings("StringBufferReplaceableByString")
public String getAddForeignKeyConstraintString(
String constraintName,
String[] foreignKey,
String referencedTable,
String[] primaryKey,
boolean referencesPrimaryKey) {
// The syntax used to add a foreign key constraint to a table.
return new StringBuilder( 300 )
.append( " ADD CONSTRAINT " )
.append( constraintName )
.append( " FOREIGN KEY " )
.append( constraintName )
.append( " (" )
.append( String.join( ", ", foreignKey ) )
.append( ") REFERENCES " )
.append( referencedTable )
.append( " (" )
.append( String.join( ", ", primaryKey ) )
.append( ") " )
.toString();
}
@Override
public boolean hasSelfReferentialForeignKeyBug() {
return true;
}
@Override
public String getNativeIdentifierGeneratorStrategy() {
return "identity";
}
// IDENTITY support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@Override
public IdentityColumnSupport getIdentityColumnSupport() {
return new CacheIdentityColumnSupport();
}
// SEQUENCE support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@Override
public SequenceSupport getSequenceSupport() {
return CacheSequenceSupport.INSTANCE;
}
public String getQuerySequencesString() {
return "select name from InterSystems.Sequences";
}
// lock acquisition support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@Override
public boolean supportsOuterJoinForUpdate() {
return false;
}
@Override
public LockingStrategy getLockingStrategy(Lockable lockable, LockMode lockMode) {
// InterSystems Cache' does not current support "SELECT ... FOR UPDATE" syntax...
// Set your transaction mode to READ_COMMITTED before using
switch (lockMode) {
case PESSIMISTIC_FORCE_INCREMENT:
return new PessimisticForceIncrementLockingStrategy(lockable, lockMode);
case PESSIMISTIC_WRITE:
return new PessimisticWriteUpdateLockingStrategy(lockable, lockMode);
case PESSIMISTIC_READ:
return new PessimisticReadUpdateLockingStrategy(lockable, lockMode);
case OPTIMISTIC:
return new OptimisticLockingStrategy(lockable, lockMode);
case OPTIMISTIC_FORCE_INCREMENT:
return new OptimisticForceIncrementLockingStrategy(lockable, lockMode);
}
if ( lockMode.greaterThan( LockMode.READ ) ) {
return new UpdateLockingStrategy( lockable, lockMode );
}
else {
return new SelectLockingStrategy( lockable, lockMode );
}
}
// LIMIT support (ala TOP) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@Override
public LimitHandler getLimitHandler() {
return TopLimitHandler.INSTANCE;
}
// callable statement support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@Override
public int registerResultSetOutParameter(CallableStatement statement, int col) throws SQLException {
return col;
}
@Override
public ResultSet getResultSet(CallableStatement ps) throws SQLException {
ps.execute();
return (ResultSet) ps.getObject( 1 );
}
// miscellaneous support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@Override
public String getLowercaseFunction() {
// The name of the SQL function that transforms a string to lowercase
return "lower";
}
@Override
public String getNullColumnString() {
// The keyword used to specify a nullable column.
return " null";
}
@Override
@SuppressWarnings("deprecation")
public JoinFragment createOuterJoinFragment() {
// Create an OuterJoinGenerator for this dialect.
return new CacheJoinFragment();
}
@Override
public String getNoColumnsInsertString() {
// The keyword used to insert a row without specifying
// any column values
return " default values";
}
@Override
public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() {
return (sqlException, message, sql) -> {
String sqlStateClassCode = JdbcExceptionHelper.extractSqlStateClassCode( sqlException );
if ( sqlStateClassCode != null ) {
int errorCode = JdbcExceptionHelper.extractErrorCode( sqlException );
if ( errorCode >= 119 && errorCode <= 127 && errorCode != 126 ) {
final String constraintName = getViolatedConstraintNameExtractor().extractConstraintName(sqlException);
return new ConstraintViolationException( message, sqlException, sql, constraintName );
}
if ( sqlStateClassCode.equals("22")
|| sqlStateClassCode.equals("21")
|| sqlStateClassCode.equals("02") ) {
return new DataException( message, sqlException, sql );
}
}
return null; // allow other delegates the chance to look
};
}
@Override
public ViolatedConstraintNameExtractor getViolatedConstraintNameExtractor() {
return EXTRACTOR;
}
private static final ViolatedConstraintNameExtractor EXTRACTOR =
new TemplatedViolatedConstraintNameExtractor( sqle ->
extractUsingTemplate( "constraint (", ") violated", sqle.getMessage() )
);
// Overridden informational metadata ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@Override
public boolean supportsEmptyInList() {
return false;
}
@Override
public boolean areStringComparisonsCaseInsensitive() {
return true;
}
@Override
public boolean supportsResultSetPositionQueryMethodsOnForwardOnlyCursor() {
return false;
}
@Override
public String translateDatetimeFormat(String format) {
//I don't think Cache needs FM
return OracleDialect.datetimeFormat( format, false ).result();
}
}