/
AbstractHANADialect.java
1553 lines (1302 loc) · 49.1 KB
/
AbstractHANADialect.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.LockMode;
import org.hibernate.LockOptions;
import org.hibernate.ScrollMode;
import org.hibernate.boot.model.TypeContributions;
import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.dialect.function.CommonFunctionFactory;
import org.hibernate.dialect.identity.HANAIdentityColumnSupport;
import org.hibernate.dialect.identity.IdentityColumnSupport;
import org.hibernate.dialect.pagination.LimitHandler;
import org.hibernate.dialect.pagination.LimitOffsetLimitHandler;
import org.hibernate.dialect.sequence.HANASequenceSupport;
import org.hibernate.dialect.sequence.SequenceSupport;
import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.engine.config.spi.ConfigurationService.Converter;
import org.hibernate.engine.config.spi.StandardConverters;
import org.hibernate.engine.jdbc.*;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.engine.jdbc.env.spi.*;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.exception.LockAcquisitionException;
import org.hibernate.exception.LockTimeoutException;
import org.hibernate.exception.SQLGrammarException;
import org.hibernate.exception.spi.SQLExceptionConversionDelegate;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.JdbcExceptionHelper;
import org.hibernate.mapping.Table;
import org.hibernate.procedure.internal.StandardCallableStatementSupport;
import org.hibernate.procedure.spi.CallableStatementSupport;
import org.hibernate.query.TemporalUnit;
import org.hibernate.query.spi.QueryEngine;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.sql.ast.SqlAstTranslator;
import org.hibernate.sql.ast.SqlAstTranslatorFactory;
import org.hibernate.sql.ast.spi.StandardSqlAstTranslatorFactory;
import org.hibernate.sql.exec.spi.JdbcOperation;
import org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorHANADatabaseImpl;
import org.hibernate.tool.schema.extract.spi.SequenceInformationExtractor;
import org.hibernate.tool.schema.internal.StandardTableExporter;
import org.hibernate.tool.schema.spi.Exporter;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.type.descriptor.ValueBinder;
import org.hibernate.type.descriptor.ValueExtractor;
import org.hibernate.type.descriptor.WrapperOptions;
import org.hibernate.type.descriptor.java.DataHelper;
import org.hibernate.type.descriptor.java.JavaTypeDescriptor;
import org.hibernate.type.descriptor.sql.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.sql.*;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* An abstract base class for SAP HANA dialects.
* <p>
* For more information on interacting with the SAP HANA database, refer to the
* <a href="https://help.sap.com/viewer/4fe29514fd584807ac9f2a04f6754767/">SAP HANA SQL and System Views Reference</a>
* and the <a href=
* "https://help.sap.com/viewer/0eec0d68141541d1b07893a39944924e/latest/en-US/434e2962074540e18c802fd478de86d6.html">SAP
* HANA Client Interface Programming Reference</a>.
* <p>
* Note: This dialect is configured to create foreign keys with {@code on update cascade}.
*
* @author <a href="mailto:andrew.clemons@sap.com">Andrew Clemons</a>
* @author <a href="mailto:jonathan.bregler@sap.com">Jonathan Bregler</a>
*/
public abstract class AbstractHANADialect extends Dialect {
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( AbstractHANADialect.class );
private static class CloseSuppressingReader extends FilterReader {
protected CloseSuppressingReader(final Reader in) {
super( in );
}
@Override
public void close() {
// do not close
}
}
private static class CloseSuppressingInputStream extends FilterInputStream {
protected CloseSuppressingInputStream(final InputStream in) {
super( in );
}
@Override
public void close() {
// do not close
}
}
private static class MaterializedBlob implements Blob {
private byte[] bytes = null;
public MaterializedBlob(byte[] bytes) {
this.setBytes( bytes );
}
@Override
public long length() throws SQLException {
return this.getBytes().length;
}
@Override
public byte[] getBytes(long pos, int length) throws SQLException {
return Arrays.copyOfRange( this.bytes, (int) ( pos - 1 ), (int) ( pos - 1 + length ) );
}
@Override
public InputStream getBinaryStream() throws SQLException {
return new ByteArrayInputStream( this.getBytes() );
}
@Override
public long position(byte[] pattern, long start) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public long position(Blob pattern, long start) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public int setBytes(long pos, byte[] bytes) throws SQLException {
int bytesSet = 0;
if ( this.bytes.length < pos - 1 + bytes.length ) {
this.bytes = Arrays.copyOf( this.bytes, (int) ( pos - 1 + bytes.length ) );
}
for ( int i = 0; i < bytes.length && i < this.bytes.length; i++, bytesSet++ ) {
this.bytes[(int) ( i + pos - 1 )] = bytes[i];
}
return bytesSet;
}
@Override
public int setBytes(long pos, byte[] bytes, int offset, int len) throws SQLException {
int bytesSet = 0;
if ( this.bytes.length < pos - 1 + len ) {
this.bytes = Arrays.copyOf( this.bytes, (int) ( pos - 1 + len ) );
}
for ( int i = offset; i < len && i < this.bytes.length; i++, bytesSet++ ) {
this.bytes[(int) ( i + pos - 1 )] = bytes[i];
}
return bytesSet;
}
@Override
public OutputStream setBinaryStream(long pos) throws SQLException {
return new ByteArrayOutputStream() {
{
this.buf = getBytes();
}
};
}
@Override
public void truncate(long len) throws SQLException {
this.setBytes( Arrays.copyOf( this.getBytes(), (int) len ) );
}
@Override
public void free() throws SQLException {
this.setBytes( null );
}
@Override
public InputStream getBinaryStream(long pos, long length) throws SQLException {
return new ByteArrayInputStream( this.getBytes(), (int) ( pos - 1 ), (int) length );
}
byte[] getBytes() {
return this.bytes;
}
void setBytes(byte[] bytes) {
this.bytes = bytes;
}
}
private static class MaterializedNClob implements NClob {
private String data = null;
public MaterializedNClob(String data) {
this.data = data;
}
@Override
public void truncate(long len) throws SQLException {
this.data = "";
}
@Override
public int setString(long pos, String str, int offset, int len) throws SQLException {
this.data = this.data.substring( 0, (int) ( pos - 1 ) ) + str.substring( offset, offset + len )
+ this.data.substring( (int) ( pos - 1 + len ) );
return len;
}
@Override
public int setString(long pos, String str) throws SQLException {
this.data = this.data.substring( 0, (int) ( pos - 1 ) ) + str + this.data.substring( (int) ( pos - 1 + str.length() ) );
return str.length();
}
@Override
public Writer setCharacterStream(long pos) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public OutputStream setAsciiStream(long pos) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public long position(Clob searchstr, long start) throws SQLException {
return this.data.indexOf( DataHelper.extractString( searchstr ), (int) ( start - 1 ) );
}
@Override
public long position(String searchstr, long start) throws SQLException {
return this.data.indexOf( searchstr, (int) ( start - 1 ) );
}
@Override
public long length() throws SQLException {
return this.data.length();
}
@Override
public String getSubString(long pos, int length) throws SQLException {
return this.data.substring( (int) ( pos - 1 ), (int) ( pos - 1 + length ) );
}
@Override
public Reader getCharacterStream(long pos, long length) throws SQLException {
return new StringReader( this.data.substring( (int) ( pos - 1 ), (int) ( pos - 1 + length ) ) );
}
@Override
public Reader getCharacterStream() throws SQLException {
return new StringReader( this.data );
}
@Override
public InputStream getAsciiStream() throws SQLException {
return new ByteArrayInputStream( this.data.getBytes( StandardCharsets.ISO_8859_1 ) );
}
@Override
public void free() throws SQLException {
this.data = null;
}
}
private static class HANAStreamBlobTypeDescriptor implements SqlTypeDescriptor {
private static final long serialVersionUID = -2476600722093442047L;
final int maxLobPrefetchSize;
public HANAStreamBlobTypeDescriptor(int maxLobPrefetchSize) {
this.maxLobPrefetchSize = maxLobPrefetchSize;
}
@Override
public String getFriendlyName() {
return "BLOB (hana-stream)";
}
@Override
public String toString() {
return "HANAStreamBlobTypeDescriptor";
}
@Override
public int getSqlType() {
return Types.BLOB;
}
@Override
public boolean canBeRemapped() {
return true;
}
@Override
public <X> ValueBinder<X> getBinder(JavaTypeDescriptor<X> javaTypeDescriptor) {
return new BasicBinder<X>( javaTypeDescriptor, this ) {
@Override
protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException {
final BinaryStream binaryStream = javaTypeDescriptor.unwrap( value, BinaryStream.class, options );
if ( value instanceof BlobImplementer ) {
try ( InputStream is = new CloseSuppressingInputStream( binaryStream.getInputStream() ) ) {
st.setBinaryStream( index, is, binaryStream.getLength() );
}
catch (IOException e) {
// can't happen => ignore
}
}
else {
st.setBinaryStream( index, binaryStream.getInputStream(), binaryStream.getLength() );
}
}
@Override
protected void doBind(CallableStatement st, X value, String name, WrapperOptions options) throws SQLException {
final BinaryStream binaryStream = javaTypeDescriptor.unwrap( value, BinaryStream.class, options );
if ( value instanceof BlobImplementer ) {
try ( InputStream is = new CloseSuppressingInputStream( binaryStream.getInputStream() ) ) {
st.setBinaryStream( name, is, binaryStream.getLength() );
}
catch (IOException e) {
// can't happen => ignore
}
}
else {
st.setBinaryStream( name, binaryStream.getInputStream(), binaryStream.getLength() );
}
}
};
}
@Override
public <X> ValueExtractor<X> getExtractor(JavaTypeDescriptor<X> javaTypeDescriptor) {
return new BasicExtractor<X>( javaTypeDescriptor, this ) {
@Override
protected X doExtract(ResultSet rs, int paramIndex, WrapperOptions options) throws SQLException {
Blob rsBlob = rs.getBlob( paramIndex );
if ( rsBlob == null || rsBlob.length() < HANAStreamBlobTypeDescriptor.this.maxLobPrefetchSize ) {
return javaTypeDescriptor.wrap( rsBlob, options );
}
Blob blob = new MaterializedBlob( DataHelper.extractBytes( rsBlob.getBinaryStream() ) );
return javaTypeDescriptor.wrap( blob, options );
}
@Override
protected X doExtract(CallableStatement statement, int index, WrapperOptions options) throws SQLException {
return javaTypeDescriptor.wrap( statement.getBlob( index ), options );
}
@Override
protected X doExtract(CallableStatement statement, String name, WrapperOptions options) throws SQLException {
return javaTypeDescriptor.wrap( statement.getBlob( name ), options );
}
};
}
}
// the ClobTypeDescriptor and NClobTypeDescriptor for HANA are slightly
// changed from the standard ones. The HANA JDBC driver currently closes any
// stream passed in via
// PreparedStatement.setCharacterStream(int,Reader,long)
// after the stream has been processed. this causes problems later if we are
// using non-contextual lob creation and HANA then closes our StringReader.
// see test case LobLocatorTest
private static class HANAClobTypeDescriptor extends ClobTypeDescriptor {
@Override
public String toString() {
return "HANAClobTypeDescriptor";
}
/** serial version uid. */
private static final long serialVersionUID = -379042275442752102L;
final int maxLobPrefetchSize;
final boolean useUnicodeStringTypes;
public HANAClobTypeDescriptor(int maxLobPrefetchSize, boolean useUnicodeStringTypes) {
this.maxLobPrefetchSize = maxLobPrefetchSize;
this.useUnicodeStringTypes = useUnicodeStringTypes;
}
@Override
public <X> BasicBinder<X> getClobBinder(final JavaTypeDescriptor<X> javaTypeDescriptor) {
return new BasicBinder<X>( javaTypeDescriptor, this ) {
@Override
protected void doBind(final PreparedStatement st, final X value, final int index, final WrapperOptions options) throws SQLException {
final CharacterStream characterStream = javaTypeDescriptor.unwrap( value, CharacterStream.class, options );
if ( value instanceof ClobImplementer ) {
try ( Reader r = new CloseSuppressingReader( characterStream.asReader() ) ) {
st.setCharacterStream( index, r, characterStream.getLength() );
}
catch (IOException e) {
// can't happen => ignore
}
}
else {
st.setCharacterStream( index, characterStream.asReader(), characterStream.getLength() );
}
}
@Override
protected void doBind(CallableStatement st, X value, String name, WrapperOptions options) throws SQLException {
final CharacterStream characterStream = javaTypeDescriptor.unwrap( value, CharacterStream.class, options );
if ( value instanceof ClobImplementer ) {
try ( Reader r = new CloseSuppressingReader( characterStream.asReader() ) ) {
st.setCharacterStream( name, r, characterStream.getLength() );
}
catch (IOException e) {
// can't happen => ignore
}
}
else {
st.setCharacterStream( name, characterStream.asReader(), characterStream.getLength() );
}
}
};
}
@Override
public <X> ValueExtractor<X> getExtractor(JavaTypeDescriptor<X> javaTypeDescriptor) {
return new BasicExtractor<X>( javaTypeDescriptor, this ) {
@Override
protected X doExtract(ResultSet rs, int paramIndex, WrapperOptions options) throws SQLException {
Clob rsClob;
if ( HANAClobTypeDescriptor.this.useUnicodeStringTypes ) {
rsClob = rs.getNClob( paramIndex );
}
else {
rsClob = rs.getClob( paramIndex );
}
if ( rsClob == null || rsClob.length() < HANAClobTypeDescriptor.this.maxLobPrefetchSize ) {
return javaTypeDescriptor.wrap( rsClob, options );
}
Clob clob = new MaterializedNClob( DataHelper.extractString( rsClob ) );
return javaTypeDescriptor.wrap( clob, options );
}
@Override
protected X doExtract(CallableStatement statement, int index, WrapperOptions options) throws SQLException {
return javaTypeDescriptor.wrap( statement.getClob( index ), options );
}
@Override
protected X doExtract(CallableStatement statement, String name, WrapperOptions options) throws SQLException {
return javaTypeDescriptor.wrap( statement.getClob( name ), options );
}
};
}
public int getMaxLobPrefetchSize() {
return this.maxLobPrefetchSize;
}
public boolean isUseUnicodeStringTypes() {
return this.useUnicodeStringTypes;
}
}
private static class HANANClobTypeDescriptor extends NClobTypeDescriptor {
/** serial version uid. */
private static final long serialVersionUID = 5651116091681647859L;
final int maxLobPrefetchSize;
public HANANClobTypeDescriptor(int maxLobPrefetchSize) {
this.maxLobPrefetchSize = maxLobPrefetchSize;
}
@Override
public String toString() {
return "HANANClobTypeDescriptor";
}
@Override
public <X> BasicBinder<X> getNClobBinder(final JavaTypeDescriptor<X> javaTypeDescriptor) {
return new BasicBinder<X>( javaTypeDescriptor, this ) {
@Override
protected void doBind(final PreparedStatement st, final X value, final int index, final WrapperOptions options) throws SQLException {
final CharacterStream characterStream = javaTypeDescriptor.unwrap( value, CharacterStream.class, options );
if ( value instanceof NClobImplementer ) {
try ( Reader r = new CloseSuppressingReader( characterStream.asReader() ) ) {
st.setCharacterStream( index, r, characterStream.getLength() );
}
catch (IOException e) {
// can't happen => ignore
}
}
else {
st.setCharacterStream( index, characterStream.asReader(), characterStream.getLength() );
}
}
@Override
protected void doBind(CallableStatement st, X value, String name, WrapperOptions options) throws SQLException {
final CharacterStream characterStream = javaTypeDescriptor.unwrap( value, CharacterStream.class, options );
if ( value instanceof NClobImplementer ) {
try ( Reader r = new CloseSuppressingReader( characterStream.asReader() ) ) {
st.setCharacterStream( name, r, characterStream.getLength() );
}
catch (IOException e) {
// can't happen => ignore
}
}
else {
st.setCharacterStream( name, characterStream.asReader(), characterStream.getLength() );
}
}
};
}
@Override
public <X> ValueExtractor<X> getExtractor(JavaTypeDescriptor<X> javaTypeDescriptor) {
return new BasicExtractor<X>( javaTypeDescriptor, this ) {
@Override
protected X doExtract(ResultSet rs, int paramIndex, WrapperOptions options) throws SQLException {
NClob rsNClob = rs.getNClob( paramIndex );
if ( rsNClob == null || rsNClob.length() < HANANClobTypeDescriptor.this.maxLobPrefetchSize ) {
return javaTypeDescriptor.wrap( rsNClob, options );
}
NClob nClob = new MaterializedNClob( DataHelper.extractString( rsNClob ) );
return javaTypeDescriptor.wrap( nClob, options );
}
@Override
protected X doExtract(CallableStatement statement, int index, WrapperOptions options) throws SQLException {
return javaTypeDescriptor.wrap( statement.getNClob( index ), options );
}
@Override
protected X doExtract(CallableStatement statement, String name, WrapperOptions options) throws SQLException {
return javaTypeDescriptor.wrap( statement.getNClob( name ), options );
}
};
}
public int getMaxLobPrefetchSize() {
return this.maxLobPrefetchSize;
}
}
public static class HANABlobTypeDescriptor implements SqlTypeDescriptor {
private static final long serialVersionUID = 5874441715643764323L;
final int maxLobPrefetchSize;
final HANAStreamBlobTypeDescriptor hanaStreamBlobTypeDescriptor;
public HANABlobTypeDescriptor(int maxLobPrefetchSize) {
this.maxLobPrefetchSize = maxLobPrefetchSize;
this.hanaStreamBlobTypeDescriptor = new HANAStreamBlobTypeDescriptor( maxLobPrefetchSize );
}
@Override
public int getSqlType() {
return Types.BLOB;
}
@Override
public String getFriendlyName() {
return "BLOB (hana)";
}
@Override
public String toString() {
return "HANABlobTypeDescriptor";
}
@Override
public boolean canBeRemapped() {
return true;
}
@Override
public <X> ValueExtractor<X> getExtractor(final JavaTypeDescriptor<X> javaTypeDescriptor) {
return new BasicExtractor<X>( javaTypeDescriptor, this ) {
@Override
protected X doExtract(ResultSet rs, int paramIndex, WrapperOptions options) throws SQLException {
Blob rsBlob = rs.getBlob( paramIndex );
if ( rsBlob == null || rsBlob.length() < HANABlobTypeDescriptor.this.maxLobPrefetchSize ) {
return javaTypeDescriptor.wrap( rsBlob, options );
}
Blob blob = new MaterializedBlob( DataHelper.extractBytes( rsBlob.getBinaryStream() ) );
return javaTypeDescriptor.wrap( blob, options );
}
@Override
protected X doExtract(CallableStatement statement, int index, WrapperOptions options) throws SQLException {
return javaTypeDescriptor.wrap( statement.getBlob( index ), options );
}
@Override
protected X doExtract(CallableStatement statement, String name, WrapperOptions options) throws SQLException {
return javaTypeDescriptor.wrap( statement.getBlob( name ), options );
}
};
}
@Override
public <X> BasicBinder<X> getBinder(final JavaTypeDescriptor<X> javaTypeDescriptor) {
return new BasicBinder<X>( javaTypeDescriptor, this ) {
@Override
protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException {
SqlTypeDescriptor descriptor = BlobTypeDescriptor.BLOB_BINDING;
if ( byte[].class.isInstance( value ) ) {
// performance shortcut for binding BLOB data in byte[] format
descriptor = BlobTypeDescriptor.PRIMITIVE_ARRAY_BINDING;
}
else if ( options.useStreamForLobBinding() ) {
descriptor = HANABlobTypeDescriptor.this.hanaStreamBlobTypeDescriptor;
}
descriptor.getBinder( javaTypeDescriptor ).bind( st, value, index, options );
}
@Override
protected void doBind(CallableStatement st, X value, String name, WrapperOptions options) throws SQLException {
SqlTypeDescriptor descriptor = BlobTypeDescriptor.BLOB_BINDING;
if ( byte[].class.isInstance( value ) ) {
// performance shortcut for binding BLOB data in byte[] format
descriptor = BlobTypeDescriptor.PRIMITIVE_ARRAY_BINDING;
}
else if ( options.useStreamForLobBinding() ) {
descriptor = HANABlobTypeDescriptor.this.hanaStreamBlobTypeDescriptor;
}
descriptor.getBinder( javaTypeDescriptor ).bind( st, value, name, options );
}
};
}
public int getMaxLobPrefetchSize() {
return this.maxLobPrefetchSize;
}
}
// Set the LOB prefetch size. LOBs larger than this value will be read into memory as the HANA JDBC driver closes
// the LOB when the result set is closed.
private static final String MAX_LOB_PREFETCH_SIZE_PARAMETER_NAME = "hibernate.dialect.hana.max_lob_prefetch_size";
// Use TINYINT instead of the native BOOLEAN type
private static final String USE_LEGACY_BOOLEAN_TYPE_PARAMETER_NAME = "hibernate.dialect.hana.use_legacy_boolean_type";
// Use unicode (NVARCHAR, NCLOB, etc.) instead of non-unicode (VARCHAR, CLOB) string types
private static final String USE_UNICODE_STRING_TYPES_PARAMETER_NAME = "hibernate.dialect.hana.use_unicode_string_types";
// Read and write double-typed fields as BigDecimal instead of Double to get around precision issues of the HANA
// JDBC driver (https://service.sap.com/sap/support/notes/2590160)
private static final String TREAT_DOUBLE_TYPED_FIELDS_AS_DECIMAL_PARAMETER_NAME = "hibernate.dialect.hana.treat_double_typed_fields_as_decimal";
private static final int MAX_LOB_PREFETCH_SIZE_DEFAULT_VALUE = 1024;
private static final Boolean USE_LEGACY_BOOLEAN_TYPE_DEFAULT_VALUE = Boolean.FALSE;
private static final Boolean TREAT_DOUBLE_TYPED_FIELDS_AS_DECIMAL_DEFAULT_VALUE = Boolean.FALSE;
private HANANClobTypeDescriptor nClobTypeDescriptor = new HANANClobTypeDescriptor( MAX_LOB_PREFETCH_SIZE_DEFAULT_VALUE );
private HANABlobTypeDescriptor blobTypeDescriptor = new HANABlobTypeDescriptor( MAX_LOB_PREFETCH_SIZE_DEFAULT_VALUE );
private HANAClobTypeDescriptor clobTypeDescriptor;
private boolean useLegacyBooleanType = USE_LEGACY_BOOLEAN_TYPE_DEFAULT_VALUE.booleanValue();
private boolean useUnicodeStringTypes;
private boolean treatDoubleTypedFieldsAsDecimal = TREAT_DOUBLE_TYPED_FIELDS_AS_DECIMAL_DEFAULT_VALUE.booleanValue();
/*
* Tables named "TYPE" need to be quoted
*/
private final StandardTableExporter hanaTableExporter = new StandardTableExporter( this ) {
@Override
public String[] getSqlCreateStrings(org.hibernate.mapping.Table table, org.hibernate.boot.Metadata metadata) {
String[] sqlCreateStrings = super.getSqlCreateStrings( table, metadata );
return quoteTypeIfNecessary( table, sqlCreateStrings, getCreateTableString() );
}
@Override
public String[] getSqlDropStrings(Table table, org.hibernate.boot.Metadata metadata) {
String[] sqlDropStrings = super.getSqlDropStrings( table, metadata );
return quoteTypeIfNecessary( table, sqlDropStrings, "drop table" );
}
private String[] quoteTypeIfNecessary(org.hibernate.mapping.Table table, String[] strings, String prefix) {
if ( table.getNameIdentifier() == null || table.getNameIdentifier().isQuoted()
|| !"type".equals( table.getNameIdentifier().getText().toLowerCase() ) ) {
return strings;
}
Pattern createTableTypePattern = Pattern.compile( "(" + prefix + "\\s+)(" + table.getNameIdentifier().getText() + ")(.+)" );
Pattern commentOnTableTypePattern = Pattern.compile( "(comment\\s+on\\s+table\\s+)(" + table.getNameIdentifier().getText() + ")(.+)" );
for ( int i = 0; i < strings.length; i++ ) {
Matcher createTableTypeMatcher = createTableTypePattern.matcher( strings[i] );
Matcher commentOnTableTypeMatcher = commentOnTableTypePattern.matcher( strings[i] );
if ( createTableTypeMatcher.matches() ) {
strings[i] = createTableTypeMatcher.group( 1 ) + "\"TYPE\"" + createTableTypeMatcher.group( 3 );
}
if ( commentOnTableTypeMatcher.matches() ) {
strings[i] = commentOnTableTypeMatcher.group( 1 ) + "\"TYPE\"" + commentOnTableTypeMatcher.group( 3 );
}
}
return strings;
}
};
public AbstractHANADialect() {
super();
this.useUnicodeStringTypes = useUnicodeStringTypesDefault().booleanValue();
this.clobTypeDescriptor = new HANAClobTypeDescriptor( MAX_LOB_PREFETCH_SIZE_DEFAULT_VALUE,
useUnicodeStringTypesDefault().booleanValue() );
registerColumnType( Types.DECIMAL, "decimal($p, $s)" );
//there is no 'numeric' type in HANA
registerColumnType( Types.NUMERIC, "decimal($p, $s)" );
//'double precision' syntax not supported
registerColumnType( Types.DOUBLE, "double" );
//no explicit precision
registerColumnType(Types.TIMESTAMP, "timestamp");
registerColumnType(Types.TIMESTAMP_WITH_TIMEZONE, "timestamp");
// varbinary max length 5000
registerColumnType( Types.BINARY, 5000, "varbinary($l)" );
registerColumnType( Types.VARBINARY, 5000, "varbinary($l)" );
// for longer values, map to blob
registerColumnType( Types.BINARY, "blob" );
registerColumnType( Types.VARBINARY, "blob" );
//there is no 'char' or 'nchar' type in HANA
registerColumnType( Types.CHAR, "varchar($l)" );
registerColumnType( Types.NCHAR, "nvarchar($l)" );
registerColumnType( Types.VARCHAR, 5000, "varchar($l)" );
registerColumnType( Types.NVARCHAR, 5000, "nvarchar($l)" );
// for longer values map to clob/nclob
registerColumnType( Types.VARCHAR, "clob" );
registerColumnType( Types.NVARCHAR, "nclob" );
// map tinyint to smallint since tinyint is unsigned on HANA
registerColumnType( Types.TINYINT, "smallint" );
registerHibernateType( Types.NCLOB, StandardBasicTypes.MATERIALIZED_NCLOB.getName() );
registerHibernateType( Types.CLOB, StandardBasicTypes.MATERIALIZED_CLOB.getName() );
registerHibernateType( Types.BLOB, StandardBasicTypes.MATERIALIZED_BLOB.getName() );
registerHibernateType( Types.NVARCHAR, StandardBasicTypes.NSTRING.getName() );
registerHanaKeywords();
// createBlob() and createClob() are not supported by the HANA JDBC driver
getDefaultProperties().setProperty( AvailableSettings.NON_CONTEXTUAL_LOB_CREATION, "true" );
// getGeneratedKeys() is not supported by the HANA JDBC driver
getDefaultProperties().setProperty( AvailableSettings.USE_GET_GENERATED_KEYS, "false" );
}
public int getDefaultDecimalPrecision() {
//the maximum on HANA
return 34;
}
@Override
public void initializeFunctionRegistry(QueryEngine queryEngine) {
super.initializeFunctionRegistry( queryEngine );
queryEngine.getSqmFunctionRegistry().registerBinaryTernaryPattern(
"locate",
StandardBasicTypes.INTEGER,
"locate(?2, ?1)",
"locate(?2, ?1, ?3)"
).setArgumentListSignature("(pattern, string[, start])");
CommonFunctionFactory.ceiling_ceil( queryEngine );
CommonFunctionFactory.concat_pipeOperator( queryEngine );
CommonFunctionFactory.trim2( queryEngine );
CommonFunctionFactory.cot( queryEngine );
CommonFunctionFactory.cosh( queryEngine );
CommonFunctionFactory.sinh( queryEngine );
CommonFunctionFactory.tanh( queryEngine );
CommonFunctionFactory.bitand( queryEngine );
CommonFunctionFactory.hourMinuteSecond( queryEngine );
CommonFunctionFactory.yearMonthDay( queryEngine );
CommonFunctionFactory.dayofweekmonthyear( queryEngine );
CommonFunctionFactory.weekQuarter( queryEngine );
CommonFunctionFactory.daynameMonthname( queryEngine );
CommonFunctionFactory.lastDay( queryEngine );
CommonFunctionFactory.characterLength_length( queryEngine );
CommonFunctionFactory.ascii( queryEngine );
CommonFunctionFactory.chr_char( queryEngine );
CommonFunctionFactory.addYearsMonthsDaysHoursMinutesSeconds( queryEngine );
CommonFunctionFactory.daysBetween( queryEngine );
CommonFunctionFactory.secondsBetween( queryEngine );
CommonFunctionFactory.format_toVarchar( queryEngine );
CommonFunctionFactory.currentUtcdatetimetimestamp( queryEngine );
}
@Override
public SqlAstTranslatorFactory getSqlAstTranslatorFactory() {
return new StandardSqlAstTranslatorFactory() {
@Override
protected <T extends JdbcOperation> SqlAstTranslator<T> buildTranslator(
SessionFactoryImplementor sessionFactory, org.hibernate.sql.ast.tree.Statement statement) {
return new HANASqlAstTranslator<>( sessionFactory, statement );
}
};
}
/**
* HANA has no extract() function, but we can emulate
* it using the appropriate named functions instead of
* extract().
*
* The supported fields are
* {@link TemporalUnit#YEAR},
* {@link TemporalUnit#MONTH}
* {@link TemporalUnit#DAY},
* {@link TemporalUnit#HOUR},
* {@link TemporalUnit#MINUTE},
* {@link TemporalUnit#SECOND}
* {@link TemporalUnit#WEEK},
* {@link TemporalUnit#DAY_OF_WEEK},
* {@link TemporalUnit#DAY_OF_MONTH},
* {@link TemporalUnit#DAY_OF_YEAR}.
*/
@Override
public String extractPattern(TemporalUnit unit) {
switch (unit) {
case DAY_OF_WEEK:
return "(mod(weekday(?2)+1,7)+1)";
case DAY:
case DAY_OF_MONTH:
return "dayofmonth(?2)";
case DAY_OF_YEAR:
return "dayofyear(?2)";
default:
//I think week() returns the ISO week number
return "?1(?2)";
}
}
@Override
public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() {
return (sqlException, message, sql) -> {
final int errorCode = JdbcExceptionHelper.extractErrorCode( sqlException );
if ( errorCode == 131 ) {
// 131 - Transaction rolled back by lock wait timeout
return new LockTimeoutException( message, sqlException, sql );
}
if ( errorCode == 146 ) {
// 146 - Resource busy and acquire with NOWAIT specified
return new LockTimeoutException( message, sqlException, sql );
}
if ( errorCode == 132 ) {
// 132 - Transaction rolled back due to unavailable resource
return new LockAcquisitionException( message, sqlException, sql );
}
if ( errorCode == 133 ) {
// 133 - Transaction rolled back by detected deadlock
return new LockAcquisitionException( message, sqlException, sql );
}
// 259 - Invalid table name
// 260 - Invalid column name
// 261 - Invalid index name
// 262 - Invalid query name
// 263 - Invalid alias name
if ( errorCode == 257 || ( errorCode >= 259 && errorCode <= 263 ) ) {
throw new SQLGrammarException( message, sqlException, sql );
}
// 257 - Cannot insert NULL or update to NULL
// 301 - Unique constraint violated
// 461 - foreign key constraint violation
// 462 - failed on update or delete by foreign key constraint violation
if ( errorCode == 287 || errorCode == 301 || errorCode == 461 || errorCode == 462 ) {
final String constraintName = getViolatedConstraintNameExtractor()
.extractConstraintName( sqlException );
return new ConstraintViolationException( message, sqlException, sql, constraintName );
}
return null;
};
}
@Override
public boolean forUpdateOfColumns() {
return true;
}
@Override
public String getAddColumnString() {
return "add (";
}
@Override
public String getAddColumnSuffixString() {
return ")";
}
@Override
public String getCascadeConstraintsString() {
return " cascade";
}
@Override
public String getCurrentTimestampSelectString() {
return "select current_timestamp from sys.dummy";
}
@Override
public String getForUpdateString(final String aliases) {
return getForUpdateString() + " of " + aliases;
}
@Override
public String getForUpdateString(final String aliases, final LockOptions lockOptions) {
LockMode lockMode = lockOptions.findGreatestLockMode();
lockOptions.setLockMode( lockMode );
// not sure why this is sometimes empty
if ( aliases == null || aliases.isEmpty() ) {
return getForUpdateString( lockOptions );
}
return getForUpdateString( aliases, lockMode, lockOptions.getTimeOut() );
}
@SuppressWarnings({ "deprecation" })
private String getForUpdateString(String aliases, LockMode lockMode, int timeout) {
switch ( lockMode ) {
case UPGRADE:
return getForUpdateString( aliases );
case PESSIMISTIC_READ:
return getReadLockString( aliases, timeout );
case PESSIMISTIC_WRITE:
return getWriteLockString( aliases, timeout );
case UPGRADE_NOWAIT:
case FORCE:
case PESSIMISTIC_FORCE_INCREMENT:
return getForUpdateNowaitString( aliases );
case UPGRADE_SKIPLOCKED:
return getForUpdateSkipLockedString( aliases );
default:
return "";
}
}
@Override
public String getForUpdateNowaitString() {
return getForUpdateString() + " nowait";
}
@Override
public String getNotExpression(final String expression) {
return "not (" + expression + ")";
}
@Override
public String getQuerySequencesString() {
return "select * from sys.sequences";
}
@Override
public SequenceInformationExtractor getSequenceInformationExtractor() {
return SequenceInformationExtractorHANADatabaseImpl.INSTANCE;