-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
OracleDialect.java
1094 lines (949 loc) · 29.9 KB
/
OracleDialect.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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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.LockOptions;
import org.hibernate.QueryTimeoutException;
import org.hibernate.boot.model.TypeContributions;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.function.CommonFunctionFactory;
import org.hibernate.dialect.function.NvlCoalesceEmulation;
import org.hibernate.dialect.identity.IdentityColumnSupport;
import org.hibernate.dialect.identity.Oracle12cIdentityColumnSupport;
import org.hibernate.dialect.pagination.LegacyOracleLimitHandler;
import org.hibernate.dialect.pagination.LimitHandler;
import org.hibernate.dialect.pagination.OffsetFetchLimitHandler;
import org.hibernate.dialect.sequence.OracleSequenceSupport;
import org.hibernate.dialect.sequence.SequenceSupport;
import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.engine.config.spi.StandardConverters;
import org.hibernate.engine.jdbc.dialect.spi.DialectResolutionInfo;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.exception.LockAcquisitionException;
import org.hibernate.exception.LockTimeoutException;
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.internal.util.StringHelper;
import org.hibernate.procedure.internal.StandardCallableStatementSupport;
import org.hibernate.procedure.spi.CallableStatementSupport;
import org.hibernate.query.CastType;
import org.hibernate.query.SemanticException;
import org.hibernate.query.TemporalUnit;
import org.hibernate.query.spi.QueryEngine;
import org.hibernate.query.spi.QueryOptions;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.sql.*;
import org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorOracleDatabaseImpl;
import org.hibernate.tool.schema.extract.spi.SequenceInformationExtractor;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.type.descriptor.sql.BitTypeDescriptor;
import org.hibernate.type.descriptor.sql.BlobTypeDescriptor;
import org.hibernate.type.descriptor.sql.SqlTypeDescriptor;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtractor.extractUsingTemplate;
import static org.hibernate.query.CastType.STRING;
import static org.hibernate.query.TemporalUnit.*;
/**
* A dialect for Oracle 8i and above.
*
* @author Steve Ebersole
* @author Gavin King
*/
public class OracleDialect extends Dialect {
private final int version;
int getVersion() {
return version;
}
public OracleDialect(DialectResolutionInfo info) {
this( info.getDatabaseMajorVersion() );
}
private static final Pattern DISTINCT_KEYWORD_PATTERN = Pattern.compile( "\\bdistinct\\b" );
private static final Pattern GROUP_BY_KEYWORD_PATTERN = Pattern.compile( "\\bgroup\\sby\\b" );
private static final Pattern ORDER_BY_KEYWORD_PATTERN = Pattern.compile( "\\border\\sby\\b" );
private static final Pattern UNION_KEYWORD_PATTERN = Pattern.compile( "\\bunion\\b" );
private static final Pattern SQL_STATEMENT_TYPE_PATTERN = Pattern.compile("^(?:/\\*.*?\\*/)?\\s*(select|insert|update|delete)\\s+.*?");
private static final int PARAM_LIST_SIZE_LIMIT = 1000;
public static final String PREFER_LONG_RAW = "hibernate.dialect.oracle.prefer_long_raw";
private final LimitHandler limitHandler;
public OracleDialect() {
this(8);
}
public OracleDialect(int version) {
super();
this.version = version;
registerCharacterTypeMappings();
registerNumericTypeMappings();
registerDateTimeTypeMappings();
registerBinaryTypeMappings();
registerReverseHibernateTypeMappings();
registerDefaultProperties();
limitHandler = getVersion() < 12
? new LegacyOracleLimitHandler( getVersion() )
: OffsetFetchLimitHandler.INSTANCE;
}
@Override
public int getPreferredSqlTypeCodeForBoolean() {
return Types.BIT;
}
@Override
public void initializeFunctionRegistry(QueryEngine queryEngine) {
super.initializeFunctionRegistry( queryEngine );
CommonFunctionFactory.cosh( queryEngine );
CommonFunctionFactory.sinh( queryEngine );
CommonFunctionFactory.tanh( queryEngine );
CommonFunctionFactory.trunc( queryEngine );
CommonFunctionFactory.log( queryEngine );
CommonFunctionFactory.soundex( queryEngine );
CommonFunctionFactory.trim2( queryEngine );
CommonFunctionFactory.initcap( queryEngine );
CommonFunctionFactory.instr( queryEngine );
CommonFunctionFactory.substr( queryEngine );
CommonFunctionFactory.substring_substr( queryEngine );
CommonFunctionFactory.leftRight_substr( queryEngine );
CommonFunctionFactory.translate( queryEngine );
CommonFunctionFactory.bitand( queryEngine );
CommonFunctionFactory.lastDay( queryEngine );
CommonFunctionFactory.toCharNumberDateTimestamp( queryEngine );
CommonFunctionFactory.ceiling_ceil( queryEngine );
CommonFunctionFactory.concat_pipeOperator( queryEngine );
CommonFunctionFactory.rownumRowid( queryEngine );
CommonFunctionFactory.sysdate( queryEngine );
CommonFunctionFactory.systimestamp( queryEngine );
CommonFunctionFactory.characterLength_length( queryEngine );
CommonFunctionFactory.addMonths( queryEngine );
CommonFunctionFactory.monthsBetween( queryEngine );
CommonFunctionFactory.everyAny_sumCaseCase( queryEngine );
CommonFunctionFactory.median( queryEngine );
CommonFunctionFactory.stddev( queryEngine );
CommonFunctionFactory.stddevPopSamp( queryEngine );
CommonFunctionFactory.variance( queryEngine );
CommonFunctionFactory.varPopSamp( queryEngine );
if ( getVersion() < 9 ) {
queryEngine.getSqmFunctionRegistry().register( "coalesce", new NvlCoalesceEmulation() );
}
else {
//Oracle has had coalesce() since 9.0.1
CommonFunctionFactory.coalesce( queryEngine );
}
queryEngine.getSqmFunctionRegistry().registerBinaryTernaryPattern(
"locate",
StandardBasicTypes.INTEGER,
"instr(?2, ?1)",
"instr(?2, ?1, ?3)"
).setArgumentListSignature("(pattern, string[, start])");
}
@Override
public String currentDate() {
return getVersion() < 9 ? currentTimestamp() : "current_date";
}
@Override
public String currentTime() {
return currentTimestamp();
}
@Override
public String currentTimestamp() {
return getVersion() < 9 ? "sysdate" : currentTimestampWithTimeZone();
}
@Override
public String currentLocalTime() {
return currentLocalTimestamp();
}
@Override
public String currentLocalTimestamp() {
return getVersion() < 9 ? currentTimestamp() : "localtimestamp";
}
@Override
public String currentTimestampWithTimeZone() {
return getVersion() < 9 ? currentTimestamp() : "current_timestamp";
}
/**
* Oracle doesn't have any sort of {@link java.sql.Types#BOOLEAN}
* type or {@link java.sql.Types#TIME} type, and its default behavior
* for casting dates and timestamps to and from strings is just awful.
*/
@Override
public String castPattern(CastType from, CastType to) {
switch (to) {
case BOOLEAN:
switch (from) {
case STRING:
return "decode(lower(?1),'t',1,'f',0,'true',1,'false',0)";
case LONG:
case INTEGER:
return "abs(sign(?1))";
}
case STRING:
switch (from) {
case BOOLEAN:
return "decode(?1,0,'false','true')";
case DATE:
return "to_char(?1,'YYYY-MM-DD')";
case TIME:
return "to_char(?1,'HH24:MI:SS')";
case TIMESTAMP:
return "to_char(?1,'YYYY-MM-DD HH24:MI:SS.FF9')";
case OFFSET_TIMESTAMP:
return "to_char(?1,'YYYY-MM-DD HH24:MI:SS.FF9TZH:TZM')";
case ZONE_TIMESTAMP:
return "to_char(?1,'YYYY-MM-DD HH24:MI:SS.FF9 TZR')";
}
case DATE:
if (from == STRING) {
return "to_date(?1,'YYYY-MM-DD')";
}
case TIME:
if (from == STRING) {
return "to_date(?1,'HH24:MI:SS')";
}
case TIMESTAMP:
if (from == STRING) {
return "to_timestamp(?1,'YYYY-MM-DD HH24:MI:SS.FF9')";
}
case OFFSET_TIMESTAMP:
if (from == STRING) {
return "to_timestamp_tz(?1,'YYYY-MM-DD HH24:MI:SS.FF9TZH:TZM')";
}
case ZONE_TIMESTAMP:
if (from == STRING) {
return "to_timestamp_tz(?1,'YYYY-MM-DD HH24:MI:SS.FF9 TZR')";
}
default:
return super.castPattern(from, to);
}
}
/**
* We minimize multiplicative factors by using seconds
* (with fractional part) as the "native" precision for
* duration arithmetic.
*/
@Override
public long getFractionalSecondPrecisionInNanos() {
return 1_000_000_000; //seconds
}
/**
* Oracle supports a limited list of temporal fields in the
* extract() function, but we can emulate some of them by
* using to_char() with a format string instead of extract().
*
* Thus, the additional supported fields are
* {@link TemporalUnit#DAY_OF_YEAR},
* {@link TemporalUnit#DAY_OF_MONTH},
* {@link TemporalUnit#DAY_OF_YEAR},
* and {@link TemporalUnit#WEEK}.
*/
@Override
public String extractPattern(TemporalUnit unit) {
switch (unit) {
case DAY_OF_WEEK:
return "to_number(to_char(?2,'D'))";
case DAY_OF_MONTH:
return "to_number(to_char(?2,'DD'))";
case DAY_OF_YEAR:
return "to_number(to_char(?2,'DDD'))";
case WEEK:
return "to_number(to_char(?2,'IW'))"; //the ISO week number
default:
return super.extractPattern(unit);
}
}
@Override
public String timestampaddPattern(TemporalUnit unit, boolean timestamp) {
StringBuilder pattern = new StringBuilder();
pattern.append("(?3 + ");
switch ( unit ) {
case YEAR:
case QUARTER:
case MONTH:
pattern.append("numtoyminterval");
break;
case WEEK:
case DAY:
case HOUR:
case MINUTE:
case SECOND:
case NANOSECOND:
case NATIVE:
pattern.append("numtodsinterval");
break;
default:
throw new SemanticException(unit + " is not a legal field");
}
pattern.append("(");
switch ( unit ) {
case NANOSECOND:
case QUARTER:
case WEEK:
pattern.append("(");
break;
}
pattern.append("?2");
switch ( unit ) {
case QUARTER:
pattern.append(")*3");
break;
case WEEK:
pattern.append(")*7");
break;
case NANOSECOND:
pattern.append(")/1e9");
break;
}
pattern.append(",'");
switch ( unit ) {
case QUARTER:
pattern.append("month");
break;
case WEEK:
pattern.append("day");
break;
case NANOSECOND:
case NATIVE:
pattern.append("second");
break;
default:
pattern.append("?1");
}
pattern.append("')");
pattern.append(")");
return pattern.toString();
}
@Override
public String timestampdiffPattern(
TemporalUnit unit,
boolean fromTimestamp, boolean toTimestamp) {
StringBuilder pattern = new StringBuilder();
boolean timestamp = toTimestamp || fromTimestamp;
switch (unit) {
case YEAR:
extractField(pattern, YEAR, unit);
break;
case QUARTER:
case MONTH:
pattern.append("(");
extractField(pattern, YEAR, unit);
pattern.append("+");
extractField(pattern, MONTH, unit);
pattern.append(")");
break;
case WEEK:
case DAY:
extractField(pattern, DAY, unit);
break;
case HOUR:
pattern.append("(");
extractField(pattern, DAY, unit);
if (timestamp) {
pattern.append("+");
extractField(pattern, HOUR, unit);
}
pattern.append(")");
break;
case MINUTE:
pattern.append("(");
extractField(pattern, DAY, unit);
if (timestamp) {
pattern.append("+");
extractField(pattern, HOUR, unit);
pattern.append("+");
extractField(pattern, MINUTE, unit);
}
pattern.append(")");
break;
case NATIVE:
case NANOSECOND:
case SECOND:
pattern.append("(");
extractField(pattern, DAY, unit);
if (timestamp) {
pattern.append("+");
extractField(pattern, HOUR, unit);
pattern.append("+");
extractField(pattern, MINUTE, unit);
pattern.append("+");
extractField(pattern, SECOND, unit);
}
pattern.append(")");
break;
default:
throw new SemanticException("unrecognized field: " + unit);
}
return pattern.toString();
}
private void extractField(
StringBuilder pattern,
TemporalUnit unit, TemporalUnit toUnit) {
pattern.append("extract(");
pattern.append( translateExtractField(unit) );
pattern.append(" from (?3-?2) ");
switch (unit) {
case YEAR:
case MONTH:
pattern.append("year to month");
break;
case DAY:
case HOUR:
case MINUTE:
case SECOND:
pattern.append("day to second");
break;
default:
throw new SemanticException(unit + " is not a legal field");
}
pattern.append(")");
pattern.append( unit.conversionFactor( toUnit, this ) );
}
protected void registerCharacterTypeMappings() {
if ( getVersion() < 9) {
registerColumnType( Types.VARCHAR, 4000, "varchar2($l)" );
registerColumnType( Types.VARCHAR, "clob" );
}
else {
registerColumnType( Types.CHAR, "char($l char)" );
registerColumnType( Types.VARCHAR, 4000, "varchar2($l char)" );
registerColumnType( Types.VARCHAR, "clob" );
registerColumnType( Types.NVARCHAR, 4000, "nvarchar2($l)" );
registerColumnType( Types.NVARCHAR, "nclob" );
}
}
protected void registerNumericTypeMappings() {
registerColumnType( Types.BIT, 1, "number(1,0)" );
registerColumnType( Types.BIT, "number(3,0)" );
registerColumnType( Types.BOOLEAN, "number(1,0)" );
registerColumnType( Types.BIGINT, "number(19,0)" );
registerColumnType( Types.SMALLINT, "number(5,0)" );
registerColumnType( Types.TINYINT, "number(3,0)" );
registerColumnType( Types.INTEGER, "number(10,0)" );
registerColumnType( Types.NUMERIC, "number($p,$s)" );
registerColumnType( Types.DECIMAL, "number($p,$s)" );
}
protected void registerDateTimeTypeMappings() {
if ( getVersion() < 9 ) {
registerColumnType( Types.DATE, "date" );
registerColumnType( Types.TIME, "date" );
registerColumnType( Types.TIMESTAMP, "date" );
registerColumnType( Types.TIMESTAMP_WITH_TIMEZONE, "date" );
}
else {
//the only difference between date and timestamp
//on Oracle is that date has no fractional seconds
registerColumnType( Types.DATE, "date" );
registerColumnType( Types.TIME, "date" );
registerColumnType( Types.TIMESTAMP, "timestamp($p)" );
registerColumnType( Types.TIMESTAMP_WITH_TIMEZONE, "timestamp($p) with time zone" );
}
}
protected void registerBinaryTypeMappings() {
registerColumnType( Types.BINARY, 2000, "raw($l)" );
registerColumnType( Types.BINARY, "blob" );
registerColumnType( Types.VARBINARY, 2000, "raw($l)" );
registerColumnType( Types.VARBINARY, "blob" );
}
protected void registerReverseHibernateTypeMappings() {
}
protected void registerDefaultProperties() {
getDefaultProperties().setProperty( Environment.USE_STREAMS_FOR_BINARY, "true" );
getDefaultProperties().setProperty( Environment.STATEMENT_BATCH_SIZE, DEFAULT_BATCH_SIZE );
if ( getVersion() < 12 ) {
// Oracle driver reports to support getGeneratedKeys(), but they only
// support the version taking an array of the names of the columns to
// be returned (via its RETURNING clause). No other driver seems to
// support this overloaded version.
getDefaultProperties().setProperty( Environment.USE_GET_GENERATED_KEYS, "false" );
getDefaultProperties().setProperty( Environment.BATCH_VERSIONED_DATA, "false" );
}
else {
getDefaultProperties().setProperty( Environment.USE_GET_GENERATED_KEYS, "true" );
getDefaultProperties().setProperty( Environment.BATCH_VERSIONED_DATA, "true" );
}
}
/**
* Oracle has neither {@code BIT} nor {@code BOOLEAN}.
*
* @return false
*/
@Override
public boolean supportsBitType() {
return false;
}
@Override
protected SqlTypeDescriptor getSqlTypeDescriptorOverride(int sqlCode) {
return sqlCode == Types.BOOLEAN
? BitTypeDescriptor.INSTANCE
: super.getSqlTypeDescriptorOverride( sqlCode );
}
@Override
public void contributeTypes(TypeContributions typeContributions, ServiceRegistry serviceRegistry) {
super.contributeTypes( typeContributions, serviceRegistry );
if ( getVersion() >= 12 ) {
// account for Oracle's deprecated support for LONGVARBINARY
// prefer BLOB, unless the user explicitly opts out
boolean preferLong = serviceRegistry.getService( ConfigurationService.class ).getSetting(
PREFER_LONG_RAW,
StandardConverters.BOOLEAN,
false
);
BlobTypeDescriptor descriptor = preferLong ?
BlobTypeDescriptor.PRIMITIVE_ARRAY_BINDING :
BlobTypeDescriptor.DEFAULT;
typeContributions.contributeSqlTypeDescriptor( descriptor );
}
}
@Override
public String getNativeIdentifierGeneratorStrategy() {
return "sequence";
}
@Override
public String getTableAliasSeparator() {
return " ";
}
// features which change between 8i, 9i, and 10g ~~~~~~~~~~~~~~~~~~~~~~~~~~
@Override
public IdentityColumnSupport getIdentityColumnSupport() {
return getVersion() < 12
? super.getIdentityColumnSupport()
: new Oracle12cIdentityColumnSupport();
}
@Override
@SuppressWarnings("deprecation")
public JoinFragment createOuterJoinFragment() {
return getVersion() < 10 ? new OracleJoinFragment() : new ANSIJoinFragment();
}
@Override
public String getCrossJoinSeparator() {
return getVersion() < 10 ? ", " : " cross join ";
}
/**
* Map case support to the Oracle DECODE function. Oracle did not
* add support for CASE until 9i.
* <p/>
* {@inheritDoc}
*/
@Override
@SuppressWarnings("deprecation")
public CaseFragment createCaseFragment() {
return getVersion() < 9
? new DecodeCaseFragment()
// Oracle did add support for ANSI CASE statements in 9i
: new ANSICaseFragment();
}
@Override
public LimitHandler getLimitHandler() {
return limitHandler;
}
@Override
public String getSelectClauseNullString(int sqlType) {
if ( getVersion() >= 9 ) {
return super.getSelectClauseNullString(sqlType);
}
else {
switch(sqlType) {
case Types.VARCHAR:
case Types.CHAR:
return "to_char(null)";
case Types.DATE:
case Types.TIME:
case Types.TIMESTAMP:
case Types.TIMESTAMP_WITH_TIMEZONE:
return "to_date(null)";
default:
return "to_number(null)";
}
}
}
@Override
public String getCurrentTimestampSelectString() {
return getVersion() < 9
? "select sysdate from dual"
: "select systimestamp from dual";
}
@Override
@SuppressWarnings("deprecation")
public String getCurrentTimestampSQLFunctionName() {
return getVersion() < 9
? "sysdate"
// the standard SQL function name is current_timestamp...
: "current_timestamp";
}
// features which remain constant across 8i, 9i, and 10g ~~~~~~~~~~~~~~~~~~
@Override
public String getAddColumnString() {
return "add";
}
@Override
public String getCascadeConstraintsString() {
return " cascade constraints";
}
@Override
public boolean dropConstraints() {
return false;
}
@Override
public String getForUpdateNowaitString() {
return " for update nowait";
}
@Override
public String getForUpdateString(String aliases) {
return getForUpdateString() + " of " + aliases;
}
@Override
public String getForUpdateNowaitString(String aliases) {
return getForUpdateString() + " of " + aliases + " nowait";
}
@Override
public boolean forUpdateOfColumns() {
return true;
}
@Override
public String getFromDual() {
return "from dual";
}
@Override
public SequenceSupport getSequenceSupport() {
return OracleSequenceSupport.INSTANCE;
}
@Override
public String getQuerySequencesString() {
return "select * from user_sequences";
}
public SequenceInformationExtractor getSequenceInformationExtractor() {
return SequenceInformationExtractorOracleDatabaseImpl.INSTANCE;
}
@Override
public String getSelectGUIDString() {
return "select rawtohex(sys_guid()) from dual";
}
@Override
public ViolatedConstraintNameExtractor getViolatedConstraintNameExtractor() {
return EXTRACTOR;
}
private static final ViolatedConstraintNameExtractor EXTRACTOR =
new TemplatedViolatedConstraintNameExtractor( sqle -> {
switch ( JdbcExceptionHelper.extractErrorCode( sqle ) ) {
case 1:
case 2291:
case 2292:
return extractUsingTemplate( "(", ")", sqle.getMessage() );
case 1400:
// simple nullability constraint
return null;
default:
return null;
}
} );
@Override
public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() {
return (sqlException, message, sql) -> {
// interpreting Oracle exceptions is much much more precise based on their specific vendor codes.
switch ( JdbcExceptionHelper.extractErrorCode( sqlException ) ) {
// lock timeouts ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 30006:
// ORA-30006: resource busy; acquire with WAIT timeout expired
throw new LockTimeoutException(message, sqlException, sql);
case 54:
// ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired
throw new LockTimeoutException(message, sqlException, sql);
case 4021:
// ORA-04021 timeout occurred while waiting to lock object
throw new LockTimeoutException(message, sqlException, sql);
// deadlocks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 60:
// ORA-00060: deadlock detected while waiting for resource
return new LockAcquisitionException( message, sqlException, sql );
case 4020:
// ORA-04020 deadlock detected while trying to lock object
return new LockAcquisitionException( message, sqlException, sql );
// query cancelled ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 1013:
// ORA-01013: user requested cancel of current operation
throw new QueryTimeoutException( message, sqlException, sql );
// data integrity violation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 1407:
// ORA-01407: cannot update column to NULL
final String constraintName = getViolatedConstraintNameExtractor().extractConstraintName( sqlException );
return new ConstraintViolationException( message, sqlException, sql, constraintName );
default:
return null;
}
};
}
@Override
public int registerResultSetOutParameter(CallableStatement statement, int col) throws SQLException {
// register the type of the out param - an Oracle specific type
statement.registerOutParameter( col, OracleTypesHelper.INSTANCE.getOracleCursorTypeSqlType() );
col++;
return col;
}
@Override
public ResultSet getResultSet(CallableStatement ps) throws SQLException {
ps.execute();
return (ResultSet) ps.getObject( 1 );
}
@Override
public boolean supportsUnionAll() {
return true;
}
@Override
public boolean supportsCommentOn() {
return true;
}
@Override
public boolean supportsCurrentTimestampSelection() {
return true;
}
@Override
public boolean isCurrentTimestampSelectStringCallable() {
return false;
}
@Override
public boolean supportsEmptyInList() {
return false;
}
@Override
public boolean supportsExistsInSelect() {
return false;
}
@Override
public int getInExpressionCountLimit() {
return PARAM_LIST_SIZE_LIMIT;
}
@Override
public boolean forceLobAsLastValue() {
return true;
}
@Override
public boolean isEmptyStringTreatedAsNull() {
return true;
}
/**
* For Oracle, the FOR UPDATE clause cannot be applied when using ORDER BY, DISTINCT or views.
*
* @see <a href="https://docs.oracle.com/database/121/SQLRF/statements_10002.htm#SQLRF01702">Oracle FOR UPDATE restrictions</a>
*/
@Override
public boolean useFollowOnLocking(String sql, QueryOptions queryOptions) {
if ( StringHelper.isEmpty( sql ) || queryOptions == null ) {
return true;
}
sql = sql.toLowerCase( Locale.ROOT );
return DISTINCT_KEYWORD_PATTERN.matcher( sql ).find()
|| GROUP_BY_KEYWORD_PATTERN.matcher( sql ).find()
|| UNION_KEYWORD_PATTERN.matcher( sql ).find()
|| (
queryOptions.hasLimit()
&& (
ORDER_BY_KEYWORD_PATTERN.matcher( sql ).find()
|| queryOptions.getLimit().getFirstRow() != null
)
);
}
@Override
public String getNotExpression( String expression ) {
return "not (" + expression + ")";
}
@Override
public String getQueryHintString(String sql, String hints) {
String statementType = statementType(sql);
final int pos = sql.indexOf( statementType );
if ( pos > -1 ) {
final StringBuilder buffer = new StringBuilder( sql.length() + hints.length() + 8 );
if ( pos > 0 ) {
buffer.append( sql, 0, pos );
}
buffer
.append( statementType )
.append( " /*+ " )
.append( hints )
.append( " */" )
.append( sql.substring( pos + statementType.length() ) );
sql = buffer.toString();
}
return sql;
}
@Override
public int getMaxAliasLength() {
// Oracle's max identifier length is 30, but Hibernate needs to add "uniqueing info" so we account for that,
return 20;
}
@Override
public CallableStatementSupport getCallableStatementSupport() {
// Oracle supports returning cursors
return StandardCallableStatementSupport.REF_CURSOR_INSTANCE;
}
@Override
public boolean canCreateSchema() {
return false;
}
@Override
public String getCurrentSchemaCommand() {
return "SELECT SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA') FROM DUAL";
}
@Override
public boolean supportsPartitionBy() {
return true;
}
private String statementType(String sql) {
Matcher matcher = SQL_STATEMENT_TYPE_PATTERN.matcher( sql );
if ( matcher.matches() && matcher.groupCount() == 1 ) {
return matcher.group(1);
}
throw new IllegalArgumentException( "Can't determine SQL statement type for statement: " + sql );
}
/**
* HHH-4907, I don't know if oracle 8 supports this syntax, so I'd think it is better add this
* method here. Reopen this issue if you found/know 8 supports it.
* <p/>
* {@inheritDoc}
*/
@Override
public boolean supportsRowValueConstructorSyntaxInInList() {
return getVersion() >= 9;
}
@Override
public boolean supportsTupleDistinctCounts() {
return false;
}
@Override
public boolean supportsNoWait() {
return true;
}
@Override
public String getForUpdateSkipLockedString() {
return " for update skip locked";
}
@Override
public String getForUpdateSkipLockedString(String aliases) {
return getForUpdateString() + " of " + aliases + " skip locked";
}
@Override
public boolean supportsSkipLocked() {
return true;
}
@Override
public String getWriteLockString(int timeout) {
if ( getVersion() >= 10 && timeout == LockOptions.SKIP_LOCKED ) {
return getForUpdateSkipLockedString();
}
else if ( getVersion() >= 9 && timeout == LockOptions.NO_WAIT ) {
return " for update nowait";
}
else if ( getVersion() >= 9 && timeout > 0 ) {
// convert from milliseconds to seconds
final float seconds = timeout / 1e3f;
return " for update wait " + Math.round( seconds );
}
else {
return super.getWriteLockString( timeout );
}
}
@Override
public String getWriteLockString(String aliases, int timeout) {
if ( getVersion() >= 10 && timeout == LockOptions.SKIP_LOCKED ) {
return getForUpdateSkipLockedString( aliases );
}
else {
return super.getWriteLockString( aliases, timeout );
}
}
@Override
public String getReadLockString(int timeout) {
return getWriteLockString( timeout );
}
public static Replacer datetimeFormat(String format, boolean useFm) {
String fm = useFm ? "fm" : "";
return new Replacer( format, "'", "\"" )
//era
.replace("GG", "AD")
.replace("G", "AD")
//year
.replace("yyyy", "YYYY")
.replace("yyy", fm + "YYYY")
.replace("yy", "YY")
.replace("y", fm + "YYYY")