-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
Dialect.java
2318 lines (2084 loc) · 78.8 KB
/
Dialect.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
*
* Copyright (c) 2010, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.dialect;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.NClob;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.LockOptions;
import org.hibernate.MappingException;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.function.CastFunction;
import org.hibernate.dialect.function.SQLFunction;
import org.hibernate.dialect.function.SQLFunctionTemplate;
import org.hibernate.dialect.function.StandardAnsiSqlAggregationFunctions;
import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.dialect.lock.LockingStrategy;
import org.hibernate.dialect.lock.OptimisticForceIncrementLockingStrategy;
import org.hibernate.dialect.lock.OptimisticLockingStrategy;
import org.hibernate.dialect.lock.PessimisticForceIncrementLockingStrategy;
import org.hibernate.dialect.lock.PessimisticReadSelectLockingStrategy;
import org.hibernate.dialect.lock.PessimisticWriteSelectLockingStrategy;
import org.hibernate.dialect.lock.SelectLockingStrategy;
import org.hibernate.dialect.pagination.LegacyLimitHandler;
import org.hibernate.dialect.pagination.LimitHandler;
import org.hibernate.dialect.unique.DefaultUniqueDelegate;
import org.hibernate.dialect.unique.UniqueDelegate;
import org.hibernate.engine.jdbc.LobCreator;
import org.hibernate.engine.spi.RowSelection;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.exception.spi.ConversionContext;
import org.hibernate.exception.spi.SQLExceptionConversionDelegate;
import org.hibernate.exception.spi.SQLExceptionConverter;
import org.hibernate.exception.spi.ViolatedConstraintNameExtracter;
import org.hibernate.id.IdentityGenerator;
import org.hibernate.id.SequenceGenerator;
import org.hibernate.id.TableHiLoGenerator;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.ReflectHelper;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.collections.ArrayHelper;
import org.hibernate.internal.util.io.StreamCopier;
import org.hibernate.mapping.Column;
import org.hibernate.persister.entity.Lockable;
import org.hibernate.sql.ANSICaseFragment;
import org.hibernate.sql.ANSIJoinFragment;
import org.hibernate.sql.CaseFragment;
import org.hibernate.sql.ForUpdateFragment;
import org.hibernate.sql.JoinFragment;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.type.descriptor.sql.ClobTypeDescriptor;
import org.hibernate.type.descriptor.sql.SqlTypeDescriptor;
import org.jboss.logging.Logger;
/**
* Represents a dialect of SQL implemented by a particular RDBMS.
* Subclasses implement Hibernate compatibility with different systems.<br>
* <br>
* Subclasses should provide a public default constructor that <tt>register()</tt>
* a set of type mappings and default Hibernate properties.<br>
* <br>
* Subclasses should be immutable.
*
* @author Gavin King, David Channon
*/
public abstract class Dialect implements ConversionContext {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, Dialect.class.getName());
public static final String DEFAULT_BATCH_SIZE = "15";
public static final String NO_BATCH = "0";
/**
* Characters used for quoting SQL identifiers
*/
public static final String QUOTE = "`\"[";
public static final String CLOSED_QUOTE = "`\"]";
private final TypeNames typeNames = new TypeNames();
private final TypeNames hibernateTypeNames = new TypeNames();
private final Properties properties = new Properties();
private final Map<String, SQLFunction> sqlFunctions = new HashMap<String, SQLFunction>();
private final Set<String> sqlKeywords = new HashSet<String>();
private final UniqueDelegate uniqueDelegate;
// constructors and factory methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
protected Dialect() {
LOG.usingDialect( this );
StandardAnsiSqlAggregationFunctions.primeFunctionMap( sqlFunctions );
// standard sql92 functions (can be overridden by subclasses)
registerFunction( "substring", new SQLFunctionTemplate( StandardBasicTypes.STRING, "substring(?1, ?2, ?3)" ) );
registerFunction( "locate", new SQLFunctionTemplate( StandardBasicTypes.INTEGER, "locate(?1, ?2, ?3)" ) );
registerFunction( "trim", new SQLFunctionTemplate( StandardBasicTypes.STRING, "trim(?1 ?2 ?3 ?4)" ) );
registerFunction( "length", new StandardSQLFunction( "length", StandardBasicTypes.INTEGER ) );
registerFunction( "bit_length", new StandardSQLFunction( "bit_length", StandardBasicTypes.INTEGER ) );
registerFunction( "coalesce", new StandardSQLFunction( "coalesce" ) );
registerFunction( "nullif", new StandardSQLFunction( "nullif" ) );
registerFunction( "abs", new StandardSQLFunction( "abs" ) );
registerFunction( "mod", new StandardSQLFunction( "mod", StandardBasicTypes.INTEGER) );
registerFunction( "sqrt", new StandardSQLFunction( "sqrt", StandardBasicTypes.DOUBLE) );
registerFunction( "upper", new StandardSQLFunction("upper") );
registerFunction( "lower", new StandardSQLFunction("lower") );
registerFunction( "cast", new CastFunction() );
registerFunction( "extract", new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "extract(?1 ?2 ?3)") );
//map second/minute/hour/day/month/year to ANSI extract(), override on subclasses
registerFunction( "second", new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "extract(second from ?1)") );
registerFunction( "minute", new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "extract(minute from ?1)") );
registerFunction( "hour", new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "extract(hour from ?1)") );
registerFunction( "day", new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "extract(day from ?1)") );
registerFunction( "month", new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "extract(month from ?1)") );
registerFunction( "year", new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "extract(year from ?1)") );
registerFunction( "str", new SQLFunctionTemplate(StandardBasicTypes.STRING, "cast(?1 as char)") );
registerColumnType( Types.BIT, "bit" );
registerColumnType( Types.BOOLEAN, "boolean" );
registerColumnType( Types.TINYINT, "tinyint" );
registerColumnType( Types.SMALLINT, "smallint" );
registerColumnType( Types.INTEGER, "integer" );
registerColumnType( Types.BIGINT, "bigint" );
registerColumnType( Types.FLOAT, "float($p)" );
registerColumnType( Types.DOUBLE, "double precision" );
registerColumnType( Types.NUMERIC, "numeric($p,$s)" );
registerColumnType( Types.REAL, "real" );
registerColumnType( Types.DATE, "date" );
registerColumnType( Types.TIME, "time" );
registerColumnType( Types.TIMESTAMP, "timestamp" );
registerColumnType( Types.VARBINARY, "bit varying($l)" );
registerColumnType( Types.LONGVARBINARY, "bit varying($l)" );
registerColumnType( Types.BLOB, "blob" );
registerColumnType( Types.CHAR, "char($l)" );
registerColumnType( Types.VARCHAR, "varchar($l)" );
registerColumnType( Types.LONGVARCHAR, "varchar($l)" );
registerColumnType( Types.CLOB, "clob" );
registerColumnType( Types.NCHAR, "nchar($l)" );
registerColumnType( Types.NVARCHAR, "nvarchar($l)" );
registerColumnType( Types.LONGNVARCHAR, "nvarchar($l)" );
registerColumnType( Types.NCLOB, "nclob" );
// register hibernate types for default use in scalar sqlquery type auto detection
registerHibernateType( Types.BIGINT, StandardBasicTypes.BIG_INTEGER.getName() );
registerHibernateType( Types.BINARY, StandardBasicTypes.BINARY.getName() );
registerHibernateType( Types.BIT, StandardBasicTypes.BOOLEAN.getName() );
registerHibernateType( Types.BOOLEAN, StandardBasicTypes.BOOLEAN.getName() );
registerHibernateType( Types.CHAR, StandardBasicTypes.CHARACTER.getName() );
registerHibernateType( Types.CHAR, 1, StandardBasicTypes.CHARACTER.getName() );
registerHibernateType( Types.CHAR, 255, StandardBasicTypes.STRING.getName() );
registerHibernateType( Types.DATE, StandardBasicTypes.DATE.getName() );
registerHibernateType( Types.DOUBLE, StandardBasicTypes.DOUBLE.getName() );
registerHibernateType( Types.FLOAT, StandardBasicTypes.FLOAT.getName() );
registerHibernateType( Types.INTEGER, StandardBasicTypes.INTEGER.getName() );
registerHibernateType( Types.SMALLINT, StandardBasicTypes.SHORT.getName() );
registerHibernateType( Types.TINYINT, StandardBasicTypes.BYTE.getName() );
registerHibernateType( Types.TIME, StandardBasicTypes.TIME.getName() );
registerHibernateType( Types.TIMESTAMP, StandardBasicTypes.TIMESTAMP.getName() );
registerHibernateType( Types.VARCHAR, StandardBasicTypes.STRING.getName() );
registerHibernateType( Types.VARBINARY, StandardBasicTypes.BINARY.getName() );
registerHibernateType( Types.LONGVARCHAR, StandardBasicTypes.TEXT.getName() );
registerHibernateType( Types.LONGVARBINARY, StandardBasicTypes.IMAGE.getName() );
registerHibernateType( Types.NUMERIC, StandardBasicTypes.BIG_DECIMAL.getName() );
registerHibernateType( Types.DECIMAL, StandardBasicTypes.BIG_DECIMAL.getName() );
registerHibernateType( Types.BLOB, StandardBasicTypes.BLOB.getName() );
registerHibernateType( Types.CLOB, StandardBasicTypes.CLOB.getName() );
registerHibernateType( Types.REAL, StandardBasicTypes.FLOAT.getName() );
uniqueDelegate = new DefaultUniqueDelegate( this );
}
/**
* Get an instance of the dialect specified by the current <tt>System</tt> properties.
*
* @return The specified Dialect
* @throws HibernateException If no dialect was specified, or if it could not be instantiated.
*/
public static Dialect getDialect() throws HibernateException {
String dialectName = Environment.getProperties().getProperty( Environment.DIALECT );
return instantiateDialect( dialectName );
}
/**
* Get an instance of the dialect specified by the given properties or by
* the current <tt>System</tt> properties.
*
* @param props The properties to use for finding the dialect class to use.
* @return The specified Dialect
* @throws HibernateException If no dialect was specified, or if it could not be instantiated.
*/
public static Dialect getDialect(Properties props) throws HibernateException {
String dialectName = props.getProperty( Environment.DIALECT );
if ( dialectName == null ) {
return getDialect();
}
return instantiateDialect( dialectName );
}
private static Dialect instantiateDialect(String dialectName) throws HibernateException {
if ( dialectName == null ) {
throw new HibernateException( "The dialect was not set. Set the property hibernate.dialect." );
}
try {
return ( Dialect ) ReflectHelper.classForName( dialectName ).newInstance();
}
catch ( ClassNotFoundException cnfe ) {
throw new HibernateException( "Dialect class not found: " + dialectName );
}
catch ( Exception e ) {
throw new HibernateException( "Could not instantiate given dialect class: " + dialectName, e );
}
}
/**
* Retrieve a set of default Hibernate properties for this database.
*
* @return a set of Hibernate properties
*/
public final Properties getDefaultProperties() {
return properties;
}
@Override
public String toString() {
return getClass().getName();
}
// database type mapping support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
* Get the name of the database type associated with the given
* {@link java.sql.Types} typecode.
*
* @param code The {@link java.sql.Types} typecode
* @return the database type name
* @throws HibernateException If no mapping was specified for that type.
*/
public String getTypeName(int code) throws HibernateException {
String result = typeNames.get( code );
if ( result == null ) {
throw new HibernateException( "No default type mapping for (java.sql.Types) " + code );
}
return result;
}
/**
* Get the name of the database type associated with the given
* {@link java.sql.Types} typecode with the given storage specification
* parameters.
*
* @param code The {@link java.sql.Types} typecode
* @param length The datatype length
* @param precision The datatype precision
* @param scale The datatype scale
* @return the database type name
* @throws HibernateException If no mapping was specified for that type.
*/
public String getTypeName(int code, long length, int precision, int scale) throws HibernateException {
String result = typeNames.get( code, length, precision, scale );
if ( result == null ) {
throw new HibernateException(String.format( "No type mapping for java.sql.Types code: %s, length: %s", code, length ));
}
return result;
}
/**
* Get the name of the database type appropriate for casting operations
* (via the CAST() SQL function) for the given {@link java.sql.Types} typecode.
*
* @param code The {@link java.sql.Types} typecode
* @return The database type name
*/
public String getCastTypeName(int code) {
return getTypeName( code, Column.DEFAULT_LENGTH, Column.DEFAULT_PRECISION, Column.DEFAULT_SCALE );
}
public String cast(String value, int jdbcTypeCode, int length, int precision, int scale) {
if ( jdbcTypeCode == Types.CHAR ) {
return "cast(" + value + " as char(" + length + "))";
}
else {
return "cast(" + value + "as " + getTypeName( jdbcTypeCode, length, precision, scale ) + ")";
}
}
public String cast(String value, int jdbcTypeCode, int length) {
return cast( value, jdbcTypeCode, length, Column.DEFAULT_PRECISION, Column.DEFAULT_SCALE );
}
public String cast(String value, int jdbcTypeCode, int precision, int scale) {
return cast( value, jdbcTypeCode, Column.DEFAULT_LENGTH, precision, scale );
}
/**
* Subclasses register a type name for the given type code and maximum
* column length. <tt>$l</tt> in the type name with be replaced by the
* column length (if appropriate).
*
* @param code The {@link java.sql.Types} typecode
* @param capacity The maximum length of database type
* @param name The database type name
*/
protected void registerColumnType(int code, long capacity, String name) {
typeNames.put( code, capacity, name );
}
/**
* Subclasses register a type name for the given type code. <tt>$l</tt> in
* the type name with be replaced by the column length (if appropriate).
*
* @param code The {@link java.sql.Types} typecode
* @param name The database type name
*/
protected void registerColumnType(int code, String name) {
typeNames.put( code, name );
}
/**
* Allows the dialect to override a {@link SqlTypeDescriptor}.
* <p/>
* If the passed {@code sqlTypeDescriptor} allows itself to be remapped (per
* {@link org.hibernate.type.descriptor.sql.SqlTypeDescriptor#canBeRemapped()}), then this method uses
* {@link #getSqlTypeDescriptorOverride} to get an optional override based on the SQL code returned by
* {@link SqlTypeDescriptor#getSqlType()}.
* <p/>
* If this dialect does not provide an override or if the {@code sqlTypeDescriptor} doe not allow itself to be
* remapped, then this method simply returns the original passed {@code sqlTypeDescriptor}
*
* @param sqlTypeDescriptor The {@link SqlTypeDescriptor} to override
* @return The {@link SqlTypeDescriptor} that should be used for this dialect;
* if there is no override, then original {@code sqlTypeDescriptor} is returned.
* @throws IllegalArgumentException if {@code sqlTypeDescriptor} is null.
*
* @see #getSqlTypeDescriptorOverride
*/
public SqlTypeDescriptor remapSqlTypeDescriptor(SqlTypeDescriptor sqlTypeDescriptor) {
if ( sqlTypeDescriptor == null ) {
throw new IllegalArgumentException( "sqlTypeDescriptor is null" );
}
if ( ! sqlTypeDescriptor.canBeRemapped() ) {
return sqlTypeDescriptor;
}
final SqlTypeDescriptor overridden = getSqlTypeDescriptorOverride( sqlTypeDescriptor.getSqlType() );
return overridden == null ? sqlTypeDescriptor : overridden;
}
/**
* Returns the {@link SqlTypeDescriptor} that should be used to handle the given JDBC type code. Returns
* {@code null} if there is no override.
*
* @param sqlCode A {@link Types} constant indicating the SQL column type
* @return The {@link SqlTypeDescriptor} to use as an override, or {@code null} if there is no override.
*/
protected SqlTypeDescriptor getSqlTypeDescriptorOverride(int sqlCode) {
SqlTypeDescriptor descriptor;
switch ( sqlCode ) {
case Types.CLOB: {
descriptor = useInputStreamToInsertBlob() ? ClobTypeDescriptor.STREAM_BINDING : null;
break;
}
default: {
descriptor = null;
break;
}
}
return descriptor;
}
/**
* The legacy behavior of Hibernate. LOBs are not processed by merge
*/
@SuppressWarnings( {"UnusedDeclaration"})
protected static final LobMergeStrategy LEGACY_LOB_MERGE_STRATEGY = new LobMergeStrategy() {
@Override
public Blob mergeBlob(Blob original, Blob target, SessionImplementor session) {
return target;
}
@Override
public Clob mergeClob(Clob original, Clob target, SessionImplementor session) {
return target;
}
@Override
public NClob mergeNClob(NClob original, NClob target, SessionImplementor session) {
return target;
}
};
/**
* Merge strategy based on transferring contents based on streams.
*/
@SuppressWarnings( {"UnusedDeclaration"})
protected static final LobMergeStrategy STREAM_XFER_LOB_MERGE_STRATEGY = new LobMergeStrategy() {
@Override
public Blob mergeBlob(Blob original, Blob target, SessionImplementor session) {
if ( original != target ) {
try {
OutputStream connectedStream = target.setBinaryStream( 1L ); // the BLOB just read during the load phase of merge
InputStream detachedStream = original.getBinaryStream(); // the BLOB from the detached state
StreamCopier.copy( detachedStream, connectedStream );
return target;
}
catch (SQLException e ) {
throw session.getFactory().getSQLExceptionHelper().convert( e, "unable to merge BLOB data" );
}
}
else {
return NEW_LOCATOR_LOB_MERGE_STRATEGY.mergeBlob( original, target, session );
}
}
@Override
public Clob mergeClob(Clob original, Clob target, SessionImplementor session) {
if ( original != target ) {
try {
OutputStream connectedStream = target.setAsciiStream( 1L ); // the CLOB just read during the load phase of merge
InputStream detachedStream = original.getAsciiStream(); // the CLOB from the detached state
StreamCopier.copy( detachedStream, connectedStream );
return target;
}
catch (SQLException e ) {
throw session.getFactory().getSQLExceptionHelper().convert( e, "unable to merge CLOB data" );
}
}
else {
return NEW_LOCATOR_LOB_MERGE_STRATEGY.mergeClob( original, target, session );
}
}
@Override
public NClob mergeNClob(NClob original, NClob target, SessionImplementor session) {
if ( original != target ) {
try {
OutputStream connectedStream = target.setAsciiStream( 1L ); // the NCLOB just read during the load phase of merge
InputStream detachedStream = original.getAsciiStream(); // the NCLOB from the detached state
StreamCopier.copy( detachedStream, connectedStream );
return target;
}
catch (SQLException e ) {
throw session.getFactory().getSQLExceptionHelper().convert( e, "unable to merge NCLOB data" );
}
}
else {
return NEW_LOCATOR_LOB_MERGE_STRATEGY.mergeNClob( original, target, session );
}
}
};
/**
* Merge strategy based on creating a new LOB locator.
*/
protected static final LobMergeStrategy NEW_LOCATOR_LOB_MERGE_STRATEGY = new LobMergeStrategy() {
@Override
public Blob mergeBlob(Blob original, Blob target, SessionImplementor session) {
if ( original == null && target == null ) {
return null;
}
try {
LobCreator lobCreator = session.getFactory().getJdbcServices().getLobCreator( session );
return original == null
? lobCreator.createBlob( ArrayHelper.EMPTY_BYTE_ARRAY )
: lobCreator.createBlob( original.getBinaryStream(), original.length() );
}
catch (SQLException e) {
throw session.getFactory().getSQLExceptionHelper().convert( e, "unable to merge BLOB data" );
}
}
@Override
public Clob mergeClob(Clob original, Clob target, SessionImplementor session) {
if ( original == null && target == null ) {
return null;
}
try {
LobCreator lobCreator = session.getFactory().getJdbcServices().getLobCreator( session );
return original == null
? lobCreator.createClob( "" )
: lobCreator.createClob( original.getCharacterStream(), original.length() );
}
catch (SQLException e) {
throw session.getFactory().getSQLExceptionHelper().convert( e, "unable to merge CLOB data" );
}
}
@Override
public NClob mergeNClob(NClob original, NClob target, SessionImplementor session) {
if ( original == null && target == null ) {
return null;
}
try {
LobCreator lobCreator = session.getFactory().getJdbcServices().getLobCreator( session );
return original == null
? lobCreator.createNClob( "" )
: lobCreator.createNClob( original.getCharacterStream(), original.length() );
}
catch (SQLException e) {
throw session.getFactory().getSQLExceptionHelper().convert( e, "unable to merge NCLOB data" );
}
}
};
public LobMergeStrategy getLobMergeStrategy() {
return NEW_LOCATOR_LOB_MERGE_STRATEGY;
}
// hibernate type mapping support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
* Get the name of the Hibernate {@link org.hibernate.type.Type} associated with the given
* {@link java.sql.Types} type code.
*
* @param code The {@link java.sql.Types} type code
* @return The Hibernate {@link org.hibernate.type.Type} name.
* @throws HibernateException If no mapping was specified for that type.
*/
@SuppressWarnings( {"UnusedDeclaration"})
public String getHibernateTypeName(int code) throws HibernateException {
String result = hibernateTypeNames.get( code );
if ( result == null ) {
throw new HibernateException( "No Hibernate type mapping for java.sql.Types code: " + code );
}
return result;
}
/**
* Get the name of the Hibernate {@link org.hibernate.type.Type} associated
* with the given {@link java.sql.Types} typecode with the given storage
* specification parameters.
*
* @param code The {@link java.sql.Types} typecode
* @param length The datatype length
* @param precision The datatype precision
* @param scale The datatype scale
* @return The Hibernate {@link org.hibernate.type.Type} name.
* @throws HibernateException If no mapping was specified for that type.
*/
public String getHibernateTypeName(int code, int length, int precision, int scale) throws HibernateException {
String result = hibernateTypeNames.get( code, length, precision, scale );
if ( result == null ) {
throw new HibernateException(
"No Hibernate type mapping for java.sql.Types code: " +
code +
", length: " +
length
);
}
return result;
}
/**
* Registers a Hibernate {@link org.hibernate.type.Type} name for the given
* {@link java.sql.Types} type code and maximum column length.
*
* @param code The {@link java.sql.Types} typecode
* @param capacity The maximum length of database type
* @param name The Hibernate {@link org.hibernate.type.Type} name
*/
protected void registerHibernateType(int code, long capacity, String name) {
hibernateTypeNames.put( code, capacity, name);
}
/**
* Registers a Hibernate {@link org.hibernate.type.Type} name for the given
* {@link java.sql.Types} type code.
*
* @param code The {@link java.sql.Types} typecode
* @param name The Hibernate {@link org.hibernate.type.Type} name
*/
protected void registerHibernateType(int code, String name) {
hibernateTypeNames.put( code, name);
}
// function support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
protected void registerFunction(String name, SQLFunction function) {
// HHH-7721: SQLFunctionRegistry expects all lowercase. Enforce,
// just in case a user's customer dialect uses mixed cases.
sqlFunctions.put( name.toLowerCase(), function );
}
/**
* Retrieves a map of the dialect's registered functions
* (functionName => {@link org.hibernate.dialect.function.SQLFunction}).
*
* @return The map of registered functions.
*/
public final Map<String, SQLFunction> getFunctions() {
return sqlFunctions;
}
// keyword support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
protected void registerKeyword(String word) {
sqlKeywords.add(word);
}
public Set<String> getKeywords() {
return sqlKeywords;
}
// native identifier generation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
* The class (which implements {@link org.hibernate.id.IdentifierGenerator})
* which acts as this dialects native generation strategy.
* <p/>
* Comes into play whenever the user specifies the native generator.
*
* @return The native generator class.
*/
public Class getNativeIdentifierGeneratorClass() {
if ( supportsIdentityColumns() ) {
return IdentityGenerator.class;
}
else if ( supportsSequences() ) {
return SequenceGenerator.class;
}
else {
return TableHiLoGenerator.class;
}
}
// IDENTITY support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
* Does this dialect support identity column key generation?
*
* @return True if IDENTITY columns are supported; false otherwise.
*/
public boolean supportsIdentityColumns() {
return false;
}
/**
* Does the dialect support some form of inserting and selecting
* the generated IDENTITY value all in the same statement.
*
* @return True if the dialect supports selecting the just
* generated IDENTITY in the insert statement.
*/
public boolean supportsInsertSelectIdentity() {
return false;
}
/**
* Whether this dialect have an Identity clause added to the data type or a
* completely separate identity data type
*
* @return boolean
*/
public boolean hasDataTypeInIdentityColumn() {
return true;
}
/**
* Provided we {@link #supportsInsertSelectIdentity}, then attach the
* "select identity" clause to the insert statement.
* <p/>
* Note, if {@link #supportsInsertSelectIdentity} == false then
* the insert-string should be returned without modification.
*
* @param insertString The insert command
* @return The insert command with any necessary identity select
* clause attached.
*/
public String appendIdentitySelectToInsert(String insertString) {
return insertString;
}
/**
* Get the select command to use to retrieve the last generated IDENTITY
* value for a particular table
*
* @param table The table into which the insert was done
* @param column The PK column.
* @param type The {@link java.sql.Types} type code.
* @return The appropriate select command
* @throws MappingException If IDENTITY generation is not supported.
*/
public String getIdentitySelectString(String table, String column, int type) throws MappingException {
return getIdentitySelectString();
}
/**
* Get the select command to use to retrieve the last generated IDENTITY
* value.
*
* @return The appropriate select command
* @throws MappingException If IDENTITY generation is not supported.
*/
protected String getIdentitySelectString() throws MappingException {
throw new MappingException( getClass().getName() + " does not support identity key generation" );
}
/**
* The syntax used during DDL to define a column as being an IDENTITY of
* a particular type.
*
* @param type The {@link java.sql.Types} type code.
* @return The appropriate DDL fragment.
* @throws MappingException If IDENTITY generation is not supported.
*/
public String getIdentityColumnString(int type) throws MappingException {
return getIdentityColumnString();
}
/**
* The syntax used during DDL to define a column as being an IDENTITY.
*
* @return The appropriate DDL fragment.
* @throws MappingException If IDENTITY generation is not supported.
*/
protected String getIdentityColumnString() throws MappingException {
throw new MappingException( getClass().getName() + " does not support identity key generation" );
}
/**
* The keyword used to insert a generated value into an identity column (or null).
* Need if the dialect does not support inserts that specify no column values.
*
* @return The appropriate keyword.
*/
public String getIdentityInsertString() {
return null;
}
// SEQUENCE support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
* Does this dialect support sequences?
*
* @return True if sequences supported; false otherwise.
*/
public boolean supportsSequences() {
return false;
}
/**
* Does this dialect support "pooled" sequences. Not aware of a better
* name for this. Essentially can we specify the initial and increment values?
*
* @return True if such "pooled" sequences are supported; false otherwise.
* @see #getCreateSequenceStrings(String, int, int)
* @see #getCreateSequenceString(String, int, int)
*/
public boolean supportsPooledSequences() {
return false;
}
/**
* Generate the appropriate select statement to to retrieve the next value
* of a sequence.
* <p/>
* This should be a "stand alone" select statement.
*
* @param sequenceName the name of the sequence
* @return String The "nextval" select string.
* @throws MappingException If sequences are not supported.
*/
public String getSequenceNextValString(String sequenceName) throws MappingException {
throw new MappingException( getClass().getName() + " does not support sequences" );
}
/**
* Generate the select expression fragment that will retrieve the next
* value of a sequence as part of another (typically DML) statement.
* <p/>
* This differs from {@link #getSequenceNextValString(String)} in that this
* should return an expression usable within another statement.
*
* @param sequenceName the name of the sequence
* @return The "nextval" fragment.
* @throws MappingException If sequences are not supported.
*/
public String getSelectSequenceNextValString(String sequenceName) throws MappingException {
throw new MappingException( getClass().getName() + " does not support sequences" );
}
/**
* The multiline script used to create a sequence.
*
* @param sequenceName The name of the sequence
* @return The sequence creation commands
* @throws MappingException If sequences are not supported.
* @deprecated Use {@link #getCreateSequenceString(String, int, int)} instead
*/
@Deprecated
public String[] getCreateSequenceStrings(String sequenceName) throws MappingException {
return new String[] { getCreateSequenceString( sequenceName ) };
}
/**
* An optional multi-line form for databases which {@link #supportsPooledSequences()}.
*
* @param sequenceName The name of the sequence
* @param initialValue The initial value to apply to 'create sequence' statement
* @param incrementSize The increment value to apply to 'create sequence' statement
* @return The sequence creation commands
* @throws MappingException If sequences are not supported.
*/
public String[] getCreateSequenceStrings(String sequenceName, int initialValue, int incrementSize) throws MappingException {
return new String[] { getCreateSequenceString( sequenceName, initialValue, incrementSize ) };
}
/**
* Typically dialects which support sequences can create a sequence
* with a single command. This is convenience form of
* {@link #getCreateSequenceStrings} to help facilitate that.
* <p/>
* Dialects which support sequences and can create a sequence in a
* single command need *only* override this method. Dialects
* which support sequences but require multiple commands to create
* a sequence should instead override {@link #getCreateSequenceStrings}.
*
* @param sequenceName The name of the sequence
* @return The sequence creation command
* @throws MappingException If sequences are not supported.
*/
protected String getCreateSequenceString(String sequenceName) throws MappingException {
throw new MappingException( getClass().getName() + " does not support sequences" );
}
/**
* Overloaded form of {@link #getCreateSequenceString(String)}, additionally
* taking the initial value and increment size to be applied to the sequence
* definition.
* </p>
* The default definition is to suffix {@link #getCreateSequenceString(String)}
* with the string: " start with {initialValue} increment by {incrementSize}" where
* {initialValue} and {incrementSize} are replacement placeholders. Generally
* dialects should only need to override this method if different key phrases
* are used to apply the allocation information.
*
* @param sequenceName The name of the sequence
* @param initialValue The initial value to apply to 'create sequence' statement
* @param incrementSize The increment value to apply to 'create sequence' statement
* @return The sequence creation command
* @throws MappingException If sequences are not supported.
*/
protected String getCreateSequenceString(String sequenceName, int initialValue, int incrementSize) throws MappingException {
if ( supportsPooledSequences() ) {
return getCreateSequenceString( sequenceName ) + " start with " + initialValue + " increment by " + incrementSize;
}
throw new MappingException( getClass().getName() + " does not support pooled sequences" );
}
/**
* The multiline script used to drop a sequence.
*
* @param sequenceName The name of the sequence
* @return The sequence drop commands
* @throws MappingException If sequences are not supported.
*/
public String[] getDropSequenceStrings(String sequenceName) throws MappingException {
return new String[]{getDropSequenceString( sequenceName )};
}
/**
* Typically dialects which support sequences can drop a sequence
* with a single command. This is convenience form of
* {@link #getDropSequenceStrings} to help facilitate that.
* <p/>
* Dialects which support sequences and can drop a sequence in a
* single command need *only* override this method. Dialects
* which support sequences but require multiple commands to drop
* a sequence should instead override {@link #getDropSequenceStrings}.
*
* @param sequenceName The name of the sequence
* @return The sequence drop commands
* @throws MappingException If sequences are not supported.
*/
protected String getDropSequenceString(String sequenceName) throws MappingException {
throw new MappingException( getClass().getName() + " does not support sequences" );
}
/**
* Get the select command used retrieve the names of all sequences.
*
* @return The select command; or null if sequences are not supported.
* @see org.hibernate.tool.hbm2ddl.SchemaUpdate
*/
public String getQuerySequencesString() {
return null;
}
// GUID support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
* Get the command used to select a GUID from the underlying database.
* <p/>
* Optional operation.
*
* @return The appropriate command.
*/
public String getSelectGUIDString() {
throw new UnsupportedOperationException( getClass().getName() + " does not support GUIDs" );
}
// limit/offset support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
* Does this dialect support some form of limiting query results
* via a SQL clause?
*
* @return True if this dialect supports some form of LIMIT.
* @deprecated {@link #buildLimitHandler(String, RowSelection)} should be overridden instead.
*/
@Deprecated
public boolean supportsLimit() {
return false;
}
/**
* Does this dialect's LIMIT support (if any) additionally
* support specifying an offset?
*
* @return True if the dialect supports an offset within the limit support.
* @deprecated {@link #buildLimitHandler(String, RowSelection)} should be overridden instead.
*/
@Deprecated
public boolean supportsLimitOffset() {
return supportsLimit();
}
/**
* Does this dialect support bind variables (i.e., prepared statement
* parameters) for its limit/offset?
*
* @return True if bind variables can be used; false otherwise.
* @deprecated {@link #buildLimitHandler(String, RowSelection)} should be overridden instead.
*/
@Deprecated
public boolean supportsVariableLimit() {
return supportsLimit();
}
/**
* ANSI SQL defines the LIMIT clause to be in the form LIMIT offset, limit.
* Does this dialect require us to bind the parameters in reverse order?
*
* @return true if the correct order is limit, offset
* @deprecated {@link #buildLimitHandler(String, RowSelection)} should be overridden instead.
*/
@Deprecated
public boolean bindLimitParametersInReverseOrder() {
return false;