/
Dialect.java
4645 lines (4200 loc) · 150 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
*
* 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 java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.temporal.TemporalAccessor;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.TimeZone;
import java.util.UUID;
import java.util.regex.Pattern;
import org.hibernate.Incubating;
import org.hibernate.LockMode;
import org.hibernate.LockOptions;
import org.hibernate.ScrollMode;
import org.hibernate.boot.TempTableDdlTransactionHandling;
import org.hibernate.boot.model.TypeContributions;
import org.hibernate.boot.model.relational.AuxiliaryDatabaseObject;
import org.hibernate.boot.model.relational.Sequence;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.dialect.aggregate.AggregateSupport;
import org.hibernate.dialect.aggregate.AggregateSupportImpl;
import org.hibernate.dialect.function.CastFunction;
import org.hibernate.dialect.function.CastStrEmulation;
import org.hibernate.dialect.function.CoalesceIfnullEmulation;
import org.hibernate.dialect.function.CommonFunctionFactory;
import org.hibernate.dialect.function.CurrentFunction;
import org.hibernate.dialect.function.ExtractFunction;
import org.hibernate.dialect.function.InsertSubstringOverlayEmulation;
import org.hibernate.dialect.function.LocatePositionEmulation;
import org.hibernate.dialect.function.LpadRpadPadEmulation;
import org.hibernate.dialect.function.SqlFunction;
import org.hibernate.dialect.function.TimestampaddFunction;
import org.hibernate.dialect.function.TimestampdiffFunction;
import org.hibernate.dialect.function.TrimFunction;
import org.hibernate.dialect.identity.IdentityColumnSupport;
import org.hibernate.dialect.identity.IdentityColumnSupportImpl;
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.LimitHandler;
import org.hibernate.dialect.sequence.NoSequenceSupport;
import org.hibernate.dialect.sequence.SequenceSupport;
import org.hibernate.dialect.temptable.StandardTemporaryTableExporter;
import org.hibernate.dialect.temptable.TemporaryTable;
import org.hibernate.dialect.temptable.TemporaryTableExporter;
import org.hibernate.dialect.temptable.TemporaryTableKind;
import org.hibernate.dialect.unique.AlterTableUniqueDelegate;
import org.hibernate.dialect.unique.UniqueDelegate;
import org.hibernate.engine.jdbc.LobCreator;
import org.hibernate.engine.jdbc.Size;
import org.hibernate.engine.jdbc.dialect.spi.DialectResolutionInfo;
import org.hibernate.engine.jdbc.env.internal.DefaultSchemaNameResolver;
import org.hibernate.engine.jdbc.env.spi.AnsiSqlKeywords;
import org.hibernate.engine.jdbc.env.spi.IdentifierHelper;
import org.hibernate.engine.jdbc.env.spi.IdentifierHelperBuilder;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.hibernate.engine.jdbc.env.spi.NameQualifierSupport;
import org.hibernate.engine.jdbc.env.spi.SchemaNameResolver;
import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.exception.spi.ConversionContext;
import org.hibernate.exception.spi.SQLExceptionConversionDelegate;
import org.hibernate.exception.spi.SQLExceptionConverter;
import org.hibernate.exception.spi.ViolatedConstraintNameExtractor;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.MathHelper;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.collections.ArrayHelper;
import org.hibernate.internal.util.io.StreamCopier;
import org.hibernate.loader.BatchLoadSizingStrategy;
import org.hibernate.mapping.Column;
import org.hibernate.mapping.Constraint;
import org.hibernate.mapping.ForeignKey;
import org.hibernate.mapping.Index;
import org.hibernate.mapping.Table;
import org.hibernate.mapping.UserDefinedType;
import org.hibernate.metamodel.mapping.EntityMappingType;
import org.hibernate.metamodel.spi.RuntimeModelCreationContext;
import org.hibernate.persister.entity.Lockable;
import org.hibernate.persister.entity.mutation.EntityMutationTarget;
import org.hibernate.procedure.internal.StandardCallableStatementSupport;
import org.hibernate.procedure.spi.CallableStatementSupport;
import org.hibernate.query.Query;
import org.hibernate.query.hql.HqlTranslator;
import org.hibernate.query.spi.QueryEngine;
import org.hibernate.query.spi.QueryOptions;
import org.hibernate.query.sqm.CastType;
import org.hibernate.query.sqm.FetchClauseType;
import org.hibernate.query.sqm.IntervalType;
import org.hibernate.query.sqm.NullOrdering;
import org.hibernate.query.sqm.TemporalUnit;
import org.hibernate.query.sqm.TrimSpec;
import org.hibernate.query.sqm.mutation.internal.temptable.AfterUseAction;
import org.hibernate.query.sqm.mutation.internal.temptable.BeforeUseAction;
import org.hibernate.query.sqm.mutation.internal.temptable.PersistentTableInsertStrategy;
import org.hibernate.query.sqm.mutation.internal.temptable.PersistentTableMutationStrategy;
import org.hibernate.query.sqm.mutation.spi.SqmMultiTableInsertStrategy;
import org.hibernate.query.sqm.mutation.spi.SqmMultiTableMutationStrategy;
import org.hibernate.query.sqm.sql.SqmTranslatorFactory;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.spi.ServiceRegistryImplementor;
import org.hibernate.sql.ForUpdateFragment;
import org.hibernate.sql.ast.SqlAstNodeRenderingMode;
import org.hibernate.sql.ast.SqlAstTranslatorFactory;
import org.hibernate.sql.ast.spi.SqlAppender;
import org.hibernate.sql.ast.spi.StandardSqlAstTranslatorFactory;
import org.hibernate.sql.ast.spi.StringBuilderSqlAppender;
import org.hibernate.sql.model.MutationOperation;
import org.hibernate.sql.model.internal.TableUpsert;
import org.hibernate.sql.model.jdbc.OptionalTableUpdateOperation;
import org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorLegacyImpl;
import org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorNoOpImpl;
import org.hibernate.tool.schema.extract.spi.SequenceInformationExtractor;
import org.hibernate.tool.schema.internal.HibernateSchemaManagementTool;
import org.hibernate.tool.schema.internal.StandardAuxiliaryDatabaseObjectExporter;
import org.hibernate.tool.schema.internal.StandardForeignKeyExporter;
import org.hibernate.tool.schema.internal.StandardIndexExporter;
import org.hibernate.tool.schema.internal.StandardSequenceExporter;
import org.hibernate.tool.schema.internal.StandardTableCleaner;
import org.hibernate.tool.schema.internal.StandardTableExporter;
import org.hibernate.tool.schema.internal.StandardTableMigrator;
import org.hibernate.tool.schema.internal.StandardUniqueKeyExporter;
import org.hibernate.tool.schema.internal.StandardUserDefinedTypeExporter;
import org.hibernate.tool.schema.internal.TableMigrator;
import org.hibernate.tool.schema.spi.Cleaner;
import org.hibernate.tool.schema.spi.Exporter;
import org.hibernate.tool.schema.spi.SchemaManagementTool;
import org.hibernate.type.BasicType;
import org.hibernate.type.BasicTypeRegistry;
import org.hibernate.type.SqlTypes;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.type.descriptor.WrapperOptions;
import org.hibernate.type.descriptor.java.JavaType;
import org.hibernate.type.descriptor.java.PrimitiveByteArrayJavaType;
import org.hibernate.type.descriptor.jdbc.ArrayJdbcType;
import org.hibernate.type.descriptor.jdbc.BlobJdbcType;
import org.hibernate.type.descriptor.jdbc.ClobJdbcType;
import org.hibernate.type.descriptor.jdbc.InstantAsTimestampJdbcType;
import org.hibernate.type.descriptor.jdbc.InstantAsTimestampWithTimeZoneJdbcType;
import org.hibernate.type.descriptor.jdbc.JdbcLiteralFormatter;
import org.hibernate.type.descriptor.jdbc.JdbcType;
import org.hibernate.type.descriptor.jdbc.LongNVarcharJdbcType;
import org.hibernate.type.descriptor.jdbc.NCharJdbcType;
import org.hibernate.type.descriptor.jdbc.NClobJdbcType;
import org.hibernate.type.descriptor.jdbc.NVarcharJdbcType;
import org.hibernate.type.descriptor.jdbc.spi.JdbcTypeRegistry;
import org.hibernate.type.descriptor.sql.internal.CapacityDependentDdlType;
import org.hibernate.type.descriptor.sql.internal.DdlTypeImpl;
import org.hibernate.type.descriptor.sql.spi.DdlTypeRegistry;
import org.hibernate.type.spi.TypeConfiguration;
import org.jboss.logging.Logger;
import jakarta.persistence.TemporalType;
import static java.lang.Math.ceil;
import static java.lang.Math.log;
import static org.hibernate.cfg.AvailableSettings.NON_CONTEXTUAL_LOB_CREATION;
import static org.hibernate.cfg.AvailableSettings.STATEMENT_BATCH_SIZE;
import static org.hibernate.cfg.AvailableSettings.USE_GET_GENERATED_KEYS;
import static org.hibernate.internal.util.StringHelper.parseCommaSeparatedString;
import static org.hibernate.type.SqlTypes.ARRAY;
import static org.hibernate.type.SqlTypes.BIGINT;
import static org.hibernate.type.SqlTypes.BINARY;
import static org.hibernate.type.SqlTypes.BLOB;
import static org.hibernate.type.SqlTypes.BOOLEAN;
import static org.hibernate.type.SqlTypes.CHAR;
import static org.hibernate.type.SqlTypes.CLOB;
import static org.hibernate.type.SqlTypes.DATE;
import static org.hibernate.type.SqlTypes.DECIMAL;
import static org.hibernate.type.SqlTypes.DOUBLE;
import static org.hibernate.type.SqlTypes.FLOAT;
import static org.hibernate.type.SqlTypes.INTEGER;
import static org.hibernate.type.SqlTypes.LONG32NVARCHAR;
import static org.hibernate.type.SqlTypes.LONG32VARBINARY;
import static org.hibernate.type.SqlTypes.LONG32VARCHAR;
import static org.hibernate.type.SqlTypes.NCHAR;
import static org.hibernate.type.SqlTypes.NCLOB;
import static org.hibernate.type.SqlTypes.NUMERIC;
import static org.hibernate.type.SqlTypes.NVARCHAR;
import static org.hibernate.type.SqlTypes.REAL;
import static org.hibernate.type.SqlTypes.ROWID;
import static org.hibernate.type.SqlTypes.SMALLINT;
import static org.hibernate.type.SqlTypes.TIME;
import static org.hibernate.type.SqlTypes.TIMESTAMP;
import static org.hibernate.type.SqlTypes.TIMESTAMP_UTC;
import static org.hibernate.type.SqlTypes.TIMESTAMP_WITH_TIMEZONE;
import static org.hibernate.type.SqlTypes.TIME_WITH_TIMEZONE;
import static org.hibernate.type.SqlTypes.TINYINT;
import static org.hibernate.type.SqlTypes.VARBINARY;
import static org.hibernate.type.SqlTypes.VARCHAR;
import static org.hibernate.type.SqlTypes.isFloatOrRealOrDouble;
import static org.hibernate.type.SqlTypes.isNumericOrDecimal;
import static org.hibernate.type.SqlTypes.isVarbinaryType;
import static org.hibernate.type.SqlTypes.isVarcharType;
import static org.hibernate.type.descriptor.DateTimeUtils.JDBC_ESCAPE_END;
import static org.hibernate.type.descriptor.DateTimeUtils.JDBC_ESCAPE_START_DATE;
import static org.hibernate.type.descriptor.DateTimeUtils.JDBC_ESCAPE_START_TIME;
import static org.hibernate.type.descriptor.DateTimeUtils.JDBC_ESCAPE_START_TIMESTAMP;
import static org.hibernate.type.descriptor.DateTimeUtils.appendAsDate;
import static org.hibernate.type.descriptor.DateTimeUtils.appendAsTime;
import static org.hibernate.type.descriptor.DateTimeUtils.appendAsTimestampWithMillis;
import static org.hibernate.type.descriptor.DateTimeUtils.appendAsTimestampWithNanos;
/**
* Represents a dialect of SQL implemented by a particular RDBMS. Every
* subclass of this class implements support for a certain database
* platform. For example, {@link PostgreSQLDialect} implements support
* for PostgreSQL, and {@link MySQLDialect} implements support for MySQL.
* <p>
* A subclass must provide a public constructor with a single parameter
* of type {@link DialectResolutionInfo}. Alternatively, for purposes of
* backward compatibility with older versions of Hibernate, a constructor
* with no parameters is also allowed.
* <p>
* Almost every subclass must, as a bare minimum, override at least:
* <ul>
* <li>{@link #columnType(int)} to define a mapping from SQL
* {@linkplain SqlTypes type codes} to database column types, and
* <li>{@link #initializeFunctionRegistry(QueryEngine)} to register
* mappings for standard HQL functions with the
* {@link org.hibernate.query.sqm.function.SqmFunctionRegistry}.
* </ul>
* <p>
* A subclass representing a dialect of SQL which deviates significantly
* from ANSI SQL will certainly override many additional operations.
* <p>
* Subclasses should be threadsafe and immutable.
* <p>
* Since Hibernate 6, a single subclass of {@code Dialect} represents all
* releases of a given product-specific SQL dialect. The version of the
* database is exposed at runtime via the {@link DialectResolutionInfo}
* passed to the constructor, and by the {@link #getVersion()} property.
* <p>
* Programs using Hibernate should migrate away from the use of versioned
* dialect classes like, for example, {@link PostgreSQL95Dialect}. These
* classes are now deprecated and will be removed in a future release.
* <p>
* A custom {@code Dialect} may be specified using the configuration
* property {@value org.hibernate.cfg.AvailableSettings#DIALECT}, but
* for supported databases this property is unnecessary, and Hibernate
* will select the correct {@code Dialect} based on the JDBC URL and
* {@link DialectResolutionInfo}.
*
* @author Gavin King, David Channon
*/
public abstract class Dialect implements ConversionContext {
/**
* Characters used as opening for quoting SQL identifiers
*/
public static final String QUOTE = "`\"[";
/**
* Characters used as closing for quoting SQL identifiers
*/
public static final String CLOSED_QUOTE = "`\"]";
private static final Pattern ESCAPE_CLOSING_COMMENT_PATTERN = Pattern.compile( "\\*/" );
private static final Pattern ESCAPE_OPENING_COMMENT_PATTERN = Pattern.compile( "/\\*" );
private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, Dialect.class.getName() );
//needed for converting precision from decimal to binary digits
protected static final double LOG_BASE2OF10 = log(10)/log(2);
private final Properties properties = new Properties();
private final Set<String> sqlKeywords = new HashSet<>();
private final SizeStrategy sizeStrategy = new SizeStrategyImpl();
private final DatabaseVersion version;
// constructors and factory methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
* @deprecated provide a {@link DatabaseVersion}
*/
@Deprecated(since = "6.0")
protected Dialect() {
this( (DatabaseVersion) null );
}
protected Dialect(DatabaseVersion version) {
this.version = version;
checkVersion();
registerDefaultKeywords();
initDefaultProperties();
}
protected Dialect(DialectResolutionInfo info) {
this.version = info.makeCopy();
checkVersion();
registerDefaultKeywords();
registerKeywords(info);
initDefaultProperties();
}
protected void checkVersion() {
final DatabaseVersion version = getVersion();
final DatabaseVersion minimumVersion = getMinimumSupportedVersion();
if ( version != null && version.isBefore( minimumVersion.getMajor(), minimumVersion.getMinor(), minimumVersion.getMicro() ) ) {
LOG.unsupportedDatabaseVersion(
getClass().getName(),
version.getMajor() + "." + version.getMinor() + "." + version.getMicro(),
minimumVersion.getMajor() + "." + minimumVersion.getMinor() + "." + minimumVersion.getMicro()
);
}
}
/**
* Set appropriate default values for configuration properties.
*/
protected void initDefaultProperties() {
getDefaultProperties().setProperty( STATEMENT_BATCH_SIZE,
Integer.toString( getDefaultStatementBatchSize() ) );
getDefaultProperties().setProperty( NON_CONTEXTUAL_LOB_CREATION,
Boolean.toString( getDefaultNonContextualLobCreation() ) );
getDefaultProperties().setProperty( USE_GET_GENERATED_KEYS,
Boolean.toString( getDefaultUseGetGeneratedKeys() ) );
}
/**
* Register ANSI-standard column types using the length limits defined
* by {@link #getMaxVarcharLength()}, {@link #getMaxNVarcharLength()},
* and {@link #getMaxVarbinaryLength()}.
* <p>
* This method is always called when a {@code Dialect} is instantiated.
*/
protected void registerColumnTypes(TypeContributions typeContributions, ServiceRegistry serviceRegistry) {
final DdlTypeRegistry ddlTypeRegistry = typeContributions.getTypeConfiguration().getDdlTypeRegistry();
ddlTypeRegistry.addDescriptor( simpleSqlType( BOOLEAN ) );
ddlTypeRegistry.addDescriptor( simpleSqlType( TINYINT ) );
ddlTypeRegistry.addDescriptor( simpleSqlType( SMALLINT ) );
ddlTypeRegistry.addDescriptor( simpleSqlType( INTEGER ) );
ddlTypeRegistry.addDescriptor( simpleSqlType( BIGINT ) );
ddlTypeRegistry.addDescriptor( simpleSqlType( FLOAT ) );
ddlTypeRegistry.addDescriptor( simpleSqlType( REAL ) );
ddlTypeRegistry.addDescriptor( simpleSqlType( DOUBLE ) );
ddlTypeRegistry.addDescriptor( simpleSqlType( NUMERIC ) );
ddlTypeRegistry.addDescriptor( simpleSqlType( DECIMAL ) );
ddlTypeRegistry.addDescriptor( simpleSqlType( DATE ) );
ddlTypeRegistry.addDescriptor( simpleSqlType( TIME ) );
ddlTypeRegistry.addDescriptor( simpleSqlType( TIME_WITH_TIMEZONE ) );
ddlTypeRegistry.addDescriptor( simpleSqlType( TIMESTAMP ) );
ddlTypeRegistry.addDescriptor( simpleSqlType( TIMESTAMP_WITH_TIMEZONE ) );
ddlTypeRegistry.addDescriptor( simpleSqlType( TIMESTAMP_UTC ) );
ddlTypeRegistry.addDescriptor( simpleSqlType( CHAR ) );
ddlTypeRegistry.addDescriptor(
sqlTypeBuilder( VARCHAR, LONG32VARCHAR, VARCHAR )
.withTypeCapacity( getMaxVarcharLength(), columnType( VARCHAR ) )
.build()
);
ddlTypeRegistry.addDescriptor( simpleSqlType( CLOB ) );
ddlTypeRegistry.addDescriptor( simpleSqlType( NCHAR ) );
ddlTypeRegistry.addDescriptor(
sqlTypeBuilder( NVARCHAR, LONG32NVARCHAR, NVARCHAR )
.withTypeCapacity( getMaxNVarcharLength(), columnType( NVARCHAR ) )
.build()
);
ddlTypeRegistry.addDescriptor( simpleSqlType( NCLOB ) );
ddlTypeRegistry.addDescriptor( simpleSqlType( BINARY ) );
ddlTypeRegistry.addDescriptor(
sqlTypeBuilder( VARBINARY, LONG32VARBINARY, VARBINARY )
.withTypeCapacity( getMaxVarbinaryLength(), columnType( VARBINARY ) )
.build()
);
ddlTypeRegistry.addDescriptor( simpleSqlType( BLOB ) );
// by default use the LOB mappings for the "long" types
ddlTypeRegistry.addDescriptor( simpleSqlType( LONG32VARCHAR ) );
ddlTypeRegistry.addDescriptor( simpleSqlType( LONG32NVARCHAR ) );
ddlTypeRegistry.addDescriptor( simpleSqlType( LONG32VARBINARY ) );
}
private DdlTypeImpl simpleSqlType(int sqlTypeCode) {
return new DdlTypeImpl( sqlTypeCode, columnType( sqlTypeCode ), castType( sqlTypeCode ), this );
}
private CapacityDependentDdlType.Builder sqlTypeBuilder(int sqlTypeCode, int biggestSqlTypeCode, int castTypeCode) {
return CapacityDependentDdlType.builder(
sqlTypeCode,
columnType( biggestSqlTypeCode ),
castType( castTypeCode ),
this
);
}
/**
* The database column type name for a given JDBC type code defined
* in {@link Types} or {@link SqlTypes}. This default implementation
* returns the ANSI-standard type name.
* <p>
* This method may be overridden by concrete {@code Dialect}s as an
* alternative to
* {@link #registerColumnTypes(TypeContributions, ServiceRegistry)}
* for simple registrations.
* <p>
* Note that:
* <ol>
* <li> Implementations of this method are expected to define a
* sensible mapping for{@link Types#NCLOB} {@link Types#NCHAR},
* and {@link Types#NVARCHAR}. On some database, these types
* are simply remapped to {@code CLOB}, {@code CHAR}, and
* {@code VARCHAR}.
* <li> Mappings for {@link Types#TIMESTAMP} and
* {@link Types#TIMESTAMP_WITH_TIMEZONE} should support explicit
* specification of precision if possible.
* <li> As specified by {@link DdlTypeRegistry#getDescriptor(int)},
* this method never receives {@link Types#LONGVARCHAR},
* {@link Types#LONGNVARCHAR}, nor {@link Types#LONGVARBINARY},
* which are considered synonyms for their non-{@code LONG}
* counterparts.
* <li> On the other hand, the types {@link SqlTypes#LONG32VARCHAR},
* {@link SqlTypes#LONG32NVARCHAR}, and
* {@link SqlTypes#LONG32VARBINARY} are <em>not</em> synonyms,
* and implementations of this method must define sensible
* mappings, for example to database-native {@code TEXT} or
* {@code CLOB} types.
* </ol>
*
* @param sqlTypeCode a SQL {@link SqlTypes type code}
* @return a column type name, with {@code $l}, {@code $p}, {@code $s}
* placeholders for length, precision, scale
*
* @see SqlTypes
*/
protected String columnType(int sqlTypeCode) {
switch ( sqlTypeCode ) {
case BOOLEAN:
return "boolean";
case TINYINT:
return "tinyint";
case SMALLINT:
return "smallint";
case INTEGER:
return "integer";
case BIGINT:
return "bigint";
case FLOAT:
// this is the floating point type we prefer!
return "float($p)";
case REAL:
// this type has very unclear semantics in ANSI SQL,
// so we avoid it and prefer float with an explicit
// precision
return "real";
case DOUBLE:
// this is just a more verbose way to write float(19)
return "double precision";
// these are pretty much synonyms, but are considered
// separate types by the ANSI spec, and in some dialects
case NUMERIC:
return "numeric($p,$s)";
case DECIMAL:
return "decimal($p,$s)";
case DATE:
return "date";
case TIME:
return "time";
case TIME_WITH_TIMEZONE:
// type included here for completeness but note that
// very few databases support it, and the general
// advice is to caution against its use (for reasons,
// check the comments in the Postgres documentation).
return "time with time zone";
case TIMESTAMP:
return "timestamp($p)";
case TIMESTAMP_WITH_TIMEZONE:
return "timestamp($p) with time zone";
case TIMESTAMP_UTC:
return getTimeZoneSupport() == TimeZoneSupport.NATIVE
? columnType( TIMESTAMP_WITH_TIMEZONE )
: columnType( TIMESTAMP );
case CHAR:
return "char($l)";
case VARCHAR:
return "varchar($l)";
case CLOB:
return "clob";
case NCHAR:
return "nchar($l)";
case NVARCHAR:
return "nvarchar($l)";
case NCLOB:
return "nclob";
case BINARY:
return "binary($l)";
case VARBINARY:
return "varbinary($l)";
case BLOB:
return "blob";
// by default use the LOB mappings for the "long" types
case LONG32VARCHAR:
return columnType( CLOB );
case LONG32NVARCHAR:
return columnType( NCLOB );
case LONG32VARBINARY:
return columnType( BLOB );
default:
throw new IllegalArgumentException( "unknown type: " + sqlTypeCode );
}
}
protected String castType(int sqlTypeCode) {
return columnType( sqlTypeCode );
}
protected void registerDefaultKeywords() {
for ( String keyword : AnsiSqlKeywords.INSTANCE.sql2003() ) {
registerKeyword( keyword );
}
}
protected void registerKeywords(DialectResolutionInfo info) {
for ( String keyword : parseCommaSeparatedString( info.getSQLKeywords() ) ) {
registerKeyword( keyword );
}
}
public DatabaseVersion getVersion() {
return version;
}
protected DatabaseVersion getMinimumSupportedVersion() {
return SimpleDatabaseVersion.ZERO_VERSION;
}
/**
* Resolves the {@link SqlTypes} type code for the given column
* type name as reported by the database, or <code>null</code>
* if it can't be resolved.
*/
protected Integer resolveSqlTypeCode(String columnTypeName, TypeConfiguration typeConfiguration) {
final int parenthesisIndex = columnTypeName.lastIndexOf( '(' );
final String baseTypeName;
if ( parenthesisIndex == -1 ) {
baseTypeName = columnTypeName;
}
else {
baseTypeName = columnTypeName.substring( 0, parenthesisIndex ).trim();
}
return resolveSqlTypeCode( columnTypeName, baseTypeName, typeConfiguration );
}
/**
* Resolves the {@link SqlTypes} type code for the given column
* type name as reported by the database and the base type name
* (i.e. without precision, length and scale), or <code>null</code>
* if it can't be resolved.
*/
protected Integer resolveSqlTypeCode(String typeName, String baseTypeName, TypeConfiguration typeConfiguration) {
return typeConfiguration.getDdlTypeRegistry().getSqlTypeCode( baseTypeName );
}
/**
* Assigns an appropriate {@link JdbcType} to a column of a JDBC
* result set based on the column type name, JDBC type code,
* precision, and scale.
*
* @param columnTypeName the column type name
* @param jdbcTypeCode the {@link SqlTypes type code}
* @param precision the precision or 0
* @param scale the scale or 0
* @return an appropriate instance of {@link JdbcType}
*/
public JdbcType resolveSqlTypeDescriptor(
String columnTypeName,
int jdbcTypeCode,
int precision,
int scale,
JdbcTypeRegistry jdbcTypeRegistry) {
final JdbcType jdbcType = jdbcTypeRegistry.getDescriptor( jdbcTypeCode );
if ( jdbcTypeCode == Types.ARRAY && jdbcType instanceof ArrayJdbcType ) {
// Special handling for array types, because we need the proper element/component type
// To determine the element JdbcType, we pass the database reported type to #resolveSqlTypeCode
final int arraySuffixIndex = columnTypeName.toLowerCase( Locale.ROOT ).indexOf( " array" );
if ( arraySuffixIndex != -1 ) {
final String componentTypeName = columnTypeName.substring( 0, arraySuffixIndex );
final Integer sqlTypeCode = resolveSqlTypeCode( componentTypeName, jdbcTypeRegistry.getTypeConfiguration() );
if ( sqlTypeCode != null ) {
return ( (ArrayJdbcType) jdbcType ).resolveType(
jdbcTypeRegistry.getTypeConfiguration(),
this,
jdbcTypeRegistry.getDescriptor( sqlTypeCode ),
null
);
}
}
}
return jdbcType;
}
public int resolveSqlTypeLength(
String columnTypeName,
int jdbcTypeCode,
int precision,
int scale,
int displaySize) {
// It seems MariaDB/MySQL return the precision in bytes depending on the charset,
// so to detect whether we have a single character here, we check the display size
if ( jdbcTypeCode == Types.CHAR && precision <= 4 ) {
return displaySize;
}
else {
return precision;
}
}
public String getEnumTypeDeclaration(String[] values) {
return null;
}
/**
* Render a SQL check condition for a column that represents an enumerated value.
*/
public String getCheckCondition(String columnName, String[] values) {
StringBuilder check = new StringBuilder();
check.append( columnName ).append( " in (" );
String separator = "";
for ( String value : values ) {
check.append( separator ).append('\'').append( value ).append('\'');
separator = ",";
}
return check.append( ')' ).toString();
}
/**
* Render a SQL check condition for a column that represents an enumerated value.
*/
public String getCheckCondition(String columnName, long min, long max) {
return columnName + " between " + min + " and " + max;
}
/**
* Initialize the given registry with any dialect-specific functions.
* <p>
* Support for certain SQL functions is required, and if the database
* does not support a required function, then the dialect must define
* a way to emulate it.
* <p>
* These required functions include the functions defined by the JPA
* query language specification:
*
* <ul>
* <li> <code>avg(arg)</code> - aggregate function
* <li> <code>count([distinct ]arg)</code> - aggregate function
* <li> <code>max(arg)</code> - aggregate function
* <li> <code>min(arg)</code> - aggregate function
* <li> <code>sum(arg)</code> - aggregate function
* </ul>
*
* <ul>
* <li> <code>coalesce(arg0, arg1, ...)</code>
* <li> <code>nullif(arg0, arg1)</code>
* </ul>
*
* <ul>
* <li> <code>lower(arg)</code>
* <li> <code>upper(arg)</code>
* <li> <code>length(arg)</code>
* <li> <code>concat(arg0, arg1, ...)</code>
* <li> <code>locate(pattern, string[, start])</code>
* <li> <code>substring(string, start[, length])</code>
* <li> <code>trim([[spec ][character ]from] string)</code>
* </ul>
*
* <ul>
* <li> <code>abs(arg)</code>
* <li> <code>mod(arg0, arg1)</code>
* <li> <code>sqrt(arg)</code>
* </ul>
*
* <ul>
* <li> <code>current date</code>
* <li> <code>current time</code>
* <li> <code>current timestamp</code>
* </ul>
*
* Along with an additional set of functions defined by ANSI SQL:
*
* <ul>
* <li> <code>any(arg)</code> - aggregate function
* <li> <code>every(arg)</code> - aggregate function
* </ul>
* <ul>
* <li> <code>var_samp(arg)</code> - aggregate function
* <li> <code>var_pop(arg)</code> - aggregate function
* <li> <code>stddev_samp(arg)</code> - aggregate function
* <li> <code>stddev_pop(arg)</code> - aggregate function
* </ul>
*
* <ul>
* <li> <code>cast(arg as Type)</code>
* <li> <code>extract(field from arg)</code>
* </ul>
*
* <ul>
* <li> <code>ln(arg)</code>
* <li> <code>exp(arg)</code>
* <li> <code>power(arg0, arg1)</code>
* <li> <code>floor(arg)</code>
* <li> <code>ceiling(arg)</code>
* </ul>
*
* <ul>
* <li> <code>position(pattern in string)</code>
* <li> <code>substring(string from start[ for length])</code>
* <li> <code>overlay(string placing replacement from start[ for length])</code>
* </ul>
*
* And the following functions for working with <code>java.time</code>
* types:
*
* <ul>
* <li> <code>local date</code>
* <li> <code>local time</code>
* <li> <code>local datetime</code>
* <li> <code>offset datetime</code>
* <li> <code>instant</code>
* </ul>
*
* And a number of additional "standard" functions:
*
* <ul>
* <li> <code>left(string, length)</code>
* <li> <code>right(string, length)</code>
* <li> <code>replace(string, pattern, replacement)</code>
* <li> <code>pad(string with length spec[ character])</code>
* </ul>
*
* <ul>
* <li> <code>pi</code>
* <li> <code>log10(arg)</code>
* <li> <code>log(base, arg)</code>
* <li> <code>sign(arg)</code>
* <li> <code>sin(arg)</code>
* <li> <code>cos(arg)</code>
* <li> <code>tan(arg)</code>
* <li> <code>asin(arg)</code>
* <li> <code>acos(arg)</code>
* <li> <code>atan(arg)</code>
* <li> <code>atan2(arg0, arg1)</code>
* <li> <code>round(arg0[, arg1])</code>
* <li> <code>truncate(arg0[, arg1])</code>
* <li> <code>sinh(arg)</code>
* <li> <code>tanh(arg)</code>
* <li> <code>cosh(arg)</code>
* <li> <code>least(arg0, arg1, ...)</code>
* <li> <code>greatest(arg0, arg1, ...)</code>
* <li> <code>degrees(arg)</code>
* <li> <code>radians(arg)</code>
* </ul>
*
* <ul>
* <li> <code>format(datetime as pattern)</code>
* <li> <code>collate(string as collation)</code>
* <li> <code>str(arg)</code> - synonym of <code>cast(a as String)</code>
* <li> <code>ifnull(arg0, arg1)</code> - synonym of <code>coalesce(a, b)</code>
* </ul>
*
* Finally, the following functions are defined as abbreviations for
* <code>extract()</code>, and desugared by the parser:
*
* <ul>
* <li> <code>second(arg)</code> - synonym of <code>extract(second from a)</code>
* <li> <code>minute(arg)</code> - synonym of <code>extract(minute from a)</code>
* <li> <code>hour(arg)</code> - synonym of <code>extract(hour from a)</code>
* <li> <code>day(arg)</code> - synonym of <code>extract(day from a)</code>
* <li> <code>month(arg)</code> - synonym of <code>extract(month from a)</code>
* <li> <code>year(arg)</code> - synonym of <code>extract(year from a)</code>
* </ul>
*
* Note that according to this definition, the <code>second()</code>
* function returns a floating point value, contrary to the integer
* type returned by the native function with this name on many databases.
* Thus, we don't just naively map these HQL functions to the native SQL
* functions with the same names.
*/
public void initializeFunctionRegistry(QueryEngine queryEngine) {
final TypeConfiguration typeConfiguration = queryEngine.getTypeConfiguration();
final BasicTypeRegistry basicTypeRegistry = typeConfiguration.getBasicTypeRegistry();
final BasicType<Date> timestampType = basicTypeRegistry.resolve( StandardBasicTypes.TIMESTAMP );
final BasicType<Date> dateType = basicTypeRegistry.resolve( StandardBasicTypes.DATE );
final BasicType<Date> timeType = basicTypeRegistry.resolve( StandardBasicTypes.TIME );
final BasicType<Instant> instantType = basicTypeRegistry.resolve( StandardBasicTypes.INSTANT );
final BasicType<OffsetDateTime> offsetDateTimeType = basicTypeRegistry.resolve( StandardBasicTypes.OFFSET_DATE_TIME );
final BasicType<LocalDateTime> localDateTimeType = basicTypeRegistry.resolve( StandardBasicTypes.LOCAL_DATE_TIME );
final BasicType<LocalTime> localTimeType = basicTypeRegistry.resolve( StandardBasicTypes.LOCAL_TIME );
final BasicType<LocalDate> localDateType = basicTypeRegistry.resolve( StandardBasicTypes.LOCAL_DATE );
CommonFunctionFactory functionFactory = new CommonFunctionFactory(queryEngine);
//standard aggregate functions count(), sum(), max(), min(), avg(),
//supported on every database
//Note that we don't include median() in this list, since it's difficult
//to implement on MySQL and Sybase ASE
functionFactory.aggregates( this, SqlAstNodeRenderingMode.DEFAULT );
//the ANSI SQL-defined aggregate functions any() and every() are only
//supported on one database, but can be emulated using sum() and case,
//though there is a more natural mapping on some databases
functionFactory.everyAny_sumCase( supportsPredicateAsExpression() );
//math functions supported on almost every database
//Note that while certain mathematical functions return the same type
//as their arguments, this is not the case in general - any function
//involving exponentiation by a non-integer power, logarithms,
//trigonometric functions, etc., should be considered to be of type
//Double. In particular, there is no meaningful concept of an "exact
//decimal" version of these functions, and if any database attempted
//to implement such a silly thing, it would be dog slow.
functionFactory.math();
functionFactory.round();
//trig functions supported on almost every database
functionFactory.trigonometry();
//hyperbolic sinh and tanh are very useful but not supported on most
//databases, so emulate them here (cosh along for the ride)
functionFactory.sinh_exp();
functionFactory.cosh_exp();
functionFactory.tanh_exp();
//pi supported on most databases, but emulate it here
functionFactory.pi_acos();
//log(base, arg) supported on most databases, but emulate it here
functionFactory.log_ln();
//coalesce() function, supported by most databases, must be emulated
//in terms of nvl() for platforms which don't support it natively
functionFactory.coalesce();
//nullif() function, supported on almost every database
functionFactory.nullif();
//string functions, must be emulated where not supported
functionFactory.leftRight();
functionFactory.replace();
functionFactory.concat();
functionFactory.lowerUpper();
//there are two forms of substring(), the JPA standard syntax, which
//separates arguments using commas, and the ANSI SQL standard syntax
//with named arguments (we support both)
functionFactory.substring();
//the JPA locate() function is especially tricky to emulate, calling
//for lots of Dialect-specific customization
functionFactory.locate();
//JPA string length() function, a synonym for ANSI SQL character_length()
functionFactory.length_characterLength();
//only some databases support the ANSI SQL-style position() function, so
//define it here as an alias for locate()
queryEngine.getSqmFunctionRegistry().register( "position",
new LocatePositionEmulation( typeConfiguration ) );
//very few databases support ANSI-style overlay() function, so emulate
//it here in terms of either insert() or concat()/substring()
queryEngine.getSqmFunctionRegistry().register( "overlay",
new InsertSubstringOverlayEmulation( typeConfiguration, false ) );
//ANSI SQL trim() function is supported on almost all of the databases
//we care about, but on some it must be emulated using ltrim(), rtrim(),
//and replace()
queryEngine.getSqmFunctionRegistry().register( "trim",
new TrimFunction( this, typeConfiguration ) );
//ANSI SQL cast() function is supported on the databases we care most
//about but in certain cases it doesn't allow some useful typecasts,
//which must be emulated in a dialect-specific way
//Note that two case are especially tricky to make portable:
// - casts to and from Boolean, and
// - casting Double or Float to String.
queryEngine.getSqmFunctionRegistry().register(
"cast",
new CastFunction(
this,
queryEngine.getPreferredSqlTypeCodeForBoolean()
)
);
//There is a 'collate' operator in a number of major databases
functionFactory.collate();
//ANSI SQL extract() function is supported on the databases we care most
//about (though it is called datepart() in some of them) but HQL defines
//additional non-standard temporal field types, which must be emulated in
//a very dialect-specific way
queryEngine.getSqmFunctionRegistry().register( "extract",
new ExtractFunction( this, typeConfiguration ) );
//comparison functions supported on most databases, emulated on others
//using a case expression
functionFactory.leastGreatest();
//two-argument synonym for coalesce() supported on most but not every
//database, so define it here as an alias for coalesce(arg1,arg2)
queryEngine.getSqmFunctionRegistry().register( "ifnull",
new CoalesceIfnullEmulation() );
//rpad() and pad() are supported on almost every database, and emulated
//where not supported, but they're not considered "standard" ... instead
//they're used to implement pad()
functionFactory.pad();
//pad() is a function we've designed to look like ANSI trim()
queryEngine.getSqmFunctionRegistry().register( "pad",
new LpadRpadPadEmulation( typeConfiguration ) );
//legacy Hibernate convenience function for casting to string, defined
//here as an alias for cast(arg as String)
queryEngine.getSqmFunctionRegistry().register( "str",
new CastStrEmulation( typeConfiguration ) );
//format() function for datetimes, emulated on many databases using the