-
Notifications
You must be signed in to change notification settings - Fork 848
/
PgPreparedStatement.java
1817 lines (1633 loc) · 60.3 KB
/
PgPreparedStatement.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
/*
* Copyright (c) 2004, PostgreSQL Global Development Group
* See the LICENSE file in the project root for more information.
*/
package org.postgresql.jdbc;
import static org.postgresql.util.internal.Nullness.castNonNull;
import org.postgresql.Driver;
import org.postgresql.core.BaseConnection;
import org.postgresql.core.CachedQuery;
import org.postgresql.core.Oid;
import org.postgresql.core.ParameterList;
import org.postgresql.core.Query;
import org.postgresql.core.QueryExecutor;
import org.postgresql.core.ServerVersion;
import org.postgresql.core.TypeInfo;
import org.postgresql.core.v3.BatchedQuery;
import org.postgresql.largeobject.LargeObject;
import org.postgresql.largeobject.LargeObjectManager;
import org.postgresql.util.ByteConverter;
import org.postgresql.util.ByteStreamWriter;
import org.postgresql.util.GT;
import org.postgresql.util.HStoreConverter;
import org.postgresql.util.PGBinaryObject;
import org.postgresql.util.PGTime;
import org.postgresql.util.PGTimestamp;
import org.postgresql.util.PGobject;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
import org.postgresql.util.ReaderInputStream;
import org.checkerframework.checker.index.qual.NonNegative;
import org.checkerframework.checker.index.qual.Positive;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.common.value.qual.IntRange;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.net.URL;
import java.nio.charset.Charset;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Date;
import java.sql.NClob;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.Ref;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLType;
import java.sql.SQLXML;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Map;
import java.util.TimeZone;
import java.util.UUID;
class PgPreparedStatement extends PgStatement implements PreparedStatement {
protected final CachedQuery preparedQuery; // Query fragments for prepared statement.
protected final ParameterList preparedParameters; // Parameter values for prepared statement.
private @Nullable TimeZone defaultTimeZone;
PgPreparedStatement(PgConnection connection, String sql, int rsType, int rsConcurrency,
int rsHoldability) throws SQLException {
this(connection, connection.borrowQuery(sql), rsType, rsConcurrency, rsHoldability);
}
@SuppressWarnings("method.invocation")
PgPreparedStatement(PgConnection connection, CachedQuery query, int rsType,
int rsConcurrency, int rsHoldability) throws SQLException {
super(connection, rsType, rsConcurrency, rsHoldability);
this.preparedQuery = query;
this.preparedParameters = this.preparedQuery.query.createParameterList();
int parameterCount = preparedParameters.getParameterCount();
int maxSupportedParameters = maximumNumberOfParameters();
if (parameterCount > maxSupportedParameters) {
throw new PSQLException(
GT.tr("PreparedStatement can have at most {0} parameters. Please consider using arrays, or splitting the query in several ones, or using COPY. Given query has {1} parameters",
maxSupportedParameters,
parameterCount),
PSQLState.INVALID_PARAMETER_VALUE);
}
// TODO: this.wantsGeneratedKeysAlways = true;
setPoolable(true); // As per JDBC spec: prepared and callable statements are poolable by
}
final int maximumNumberOfParameters() {
return connection.getPreferQueryMode() == PreferQueryMode.SIMPLE ? Integer.MAX_VALUE : 65535;
}
@Override
public ResultSet executeQuery(String sql) throws SQLException {
throw new PSQLException(
GT.tr("Can''t use query methods that take a query string on a PreparedStatement."),
PSQLState.WRONG_OBJECT_TYPE);
}
/*
* A Prepared SQL query is executed and its ResultSet is returned
*
* @return a ResultSet that contains the data produced by the * query - never null
*
* @exception SQLException if a database access error occurs
*/
@Override
public ResultSet executeQuery() throws SQLException {
try (ResourceLock ignore = lock.obtain()) {
if (!executeWithFlags(0)) {
throw new PSQLException(GT.tr("No results were returned by the query."), PSQLState.NO_DATA);
}
return getSingleResultSet();
}
}
@Override
public int executeUpdate(String sql) throws SQLException {
throw new PSQLException(
GT.tr("Can''t use query methods that take a query string on a PreparedStatement."),
PSQLState.WRONG_OBJECT_TYPE);
}
@Override
public int executeUpdate() throws SQLException {
try (ResourceLock ignore = lock.obtain()) {
executeWithFlags(QueryExecutor.QUERY_NO_RESULTS);
checkNoResultUpdate();
return getUpdateCount();
}
}
@Override
public long executeLargeUpdate() throws SQLException {
try (ResourceLock ignore = lock.obtain()) {
executeWithFlags(QueryExecutor.QUERY_NO_RESULTS);
checkNoResultUpdate();
return getLargeUpdateCount();
}
}
@Override
public boolean execute(String sql) throws SQLException {
throw new PSQLException(
GT.tr("Can''t use query methods that take a query string on a PreparedStatement."),
PSQLState.WRONG_OBJECT_TYPE);
}
@Override
public boolean execute() throws SQLException {
try (ResourceLock ignore = lock.obtain()) {
return executeWithFlags(0);
}
}
@Override
public boolean executeWithFlags(int flags) throws SQLException {
try {
try (ResourceLock ignore = lock.obtain()) {
checkClosed();
if (connection.getPreferQueryMode() == PreferQueryMode.SIMPLE) {
flags |= QueryExecutor.QUERY_EXECUTE_AS_SIMPLE;
}
execute(preparedQuery, preparedParameters, flags);
checkClosed();
return result != null && result.getResultSet() != null;
}
} finally {
defaultTimeZone = null;
}
}
@Override
protected boolean isOneShotQuery(@Nullable CachedQuery cachedQuery) {
if (cachedQuery == null) {
cachedQuery = preparedQuery;
}
return super.isOneShotQuery(cachedQuery);
}
@Override
public void closeImpl() throws SQLException {
if (preparedQuery != null) {
((PgConnection) connection).releaseQuery(preparedQuery);
}
}
@Override
public void setNull(int parameterIndex, int sqlType) throws SQLException {
checkClosed();
if (parameterIndex < 1 || parameterIndex > preparedParameters.getParameterCount()) {
throw new PSQLException(
GT.tr("The column index is out of range: {0}, number of columns: {1}.",
parameterIndex, preparedParameters.getParameterCount()),
PSQLState.INVALID_PARAMETER_VALUE);
}
int oid;
switch (sqlType) {
case Types.SQLXML:
oid = Oid.XML;
break;
case Types.INTEGER:
oid = Oid.INT4;
break;
case Types.TINYINT:
case Types.SMALLINT:
oid = Oid.INT2;
break;
case Types.BIGINT:
oid = Oid.INT8;
break;
case Types.REAL:
oid = Oid.FLOAT4;
break;
case Types.DOUBLE:
case Types.FLOAT:
oid = Oid.FLOAT8;
break;
case Types.DECIMAL:
case Types.NUMERIC:
oid = Oid.NUMERIC;
break;
case Types.CHAR:
oid = Oid.BPCHAR;
break;
case Types.VARCHAR:
case Types.LONGVARCHAR:
oid = connection.getStringVarcharFlag() ? Oid.VARCHAR : Oid.UNSPECIFIED;
break;
case Types.DATE:
oid = Oid.DATE;
break;
case Types.TIME:
case Types.TIME_WITH_TIMEZONE:
case Types.TIMESTAMP_WITH_TIMEZONE:
case Types.TIMESTAMP:
oid = Oid.UNSPECIFIED;
break;
case Types.BOOLEAN:
case Types.BIT:
oid = Oid.BOOL;
break;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
oid = Oid.BYTEA;
break;
case Types.BLOB:
case Types.CLOB:
oid = Oid.OID;
break;
case Types.REF_CURSOR:
oid = Oid.REF_CURSOR;
break;
case Types.ARRAY:
case Types.DISTINCT:
case Types.STRUCT:
case Types.NULL:
case Types.OTHER:
oid = Oid.UNSPECIFIED;
break;
default:
// Bad Types value.
throw new PSQLException(GT.tr("Unknown Types value."), PSQLState.INVALID_PARAMETER_TYPE);
}
preparedParameters.setNull(parameterIndex, oid);
}
@Override
public void setBoolean(@Positive int parameterIndex, boolean x) throws SQLException {
checkClosed();
// The key words TRUE and FALSE are the preferred (SQL-compliant) usage.
bindLiteral(parameterIndex, x ? "TRUE" : "FALSE", Oid.BOOL);
}
@Override
public void setByte(@Positive int parameterIndex, byte x) throws SQLException {
setShort(parameterIndex, x);
}
@Override
public void setShort(@Positive int parameterIndex, short x) throws SQLException {
checkClosed();
if (connection.binaryTransferSend(Oid.INT2)) {
byte[] val = new byte[2];
ByteConverter.int2(val, 0, x);
bindBytes(parameterIndex, val, Oid.INT2);
return;
}
bindLiteral(parameterIndex, Integer.toString(x), Oid.INT2);
}
@Override
public void setInt(@Positive int parameterIndex, int x) throws SQLException {
checkClosed();
if (connection.binaryTransferSend(Oid.INT4)) {
byte[] val = new byte[4];
ByteConverter.int4(val, 0, x);
bindBytes(parameterIndex, val, Oid.INT4);
return;
}
bindLiteral(parameterIndex, Integer.toString(x), Oid.INT4);
}
@Override
public void setLong(@Positive int parameterIndex, long x) throws SQLException {
checkClosed();
if (connection.binaryTransferSend(Oid.INT8)) {
byte[] val = new byte[8];
ByteConverter.int8(val, 0, x);
bindBytes(parameterIndex, val, Oid.INT8);
return;
}
bindLiteral(parameterIndex, Long.toString(x), Oid.INT8);
}
@Override
public void setFloat(@Positive int parameterIndex, float x) throws SQLException {
checkClosed();
if (connection.binaryTransferSend(Oid.FLOAT4)) {
byte[] val = new byte[4];
ByteConverter.float4(val, 0, x);
bindBytes(parameterIndex, val, Oid.FLOAT4);
return;
}
bindLiteral(parameterIndex, Float.toString(x), Oid.FLOAT8);
}
@Override
public void setDouble(@Positive int parameterIndex, double x) throws SQLException {
checkClosed();
if (connection.binaryTransferSend(Oid.FLOAT8)) {
byte[] val = new byte[8];
ByteConverter.float8(val, 0, x);
bindBytes(parameterIndex, val, Oid.FLOAT8);
return;
}
bindLiteral(parameterIndex, Double.toString(x), Oid.FLOAT8);
}
@Override
public void setBigDecimal(@Positive int parameterIndex, @Nullable BigDecimal x)
throws SQLException {
if (x != null && connection.binaryTransferSend(Oid.NUMERIC)) {
final byte[] bytes = ByteConverter.numeric(x);
bindBytes(parameterIndex, bytes, Oid.NUMERIC);
return;
}
setNumber(parameterIndex, x);
}
@Override
public void setString(@Positive int parameterIndex, @Nullable String x) throws SQLException {
checkClosed();
setString(parameterIndex, x, getStringType());
}
private int getStringType() {
return connection.getStringVarcharFlag() ? Oid.VARCHAR : Oid.UNSPECIFIED;
}
protected void setString(@Positive int parameterIndex,
@Nullable String x, int oid) throws SQLException {
// if the passed string is null, then set this column to null
checkClosed();
if (x == null) {
preparedParameters.setNull(parameterIndex, oid);
} else {
bindString(parameterIndex, x, oid);
}
}
@Override
public void setBytes(@Positive int parameterIndex, byte @Nullable[] x) throws SQLException {
checkClosed();
if (null == x) {
setNull(parameterIndex, Types.VARBINARY);
return;
}
// Version 7.2 supports the bytea datatype for byte arrays
byte[] copy = new byte[x.length];
System.arraycopy(x, 0, copy, 0, x.length);
preparedParameters.setBytea(parameterIndex, copy, 0, x.length);
}
private void setByteStreamWriter(@Positive int parameterIndex,
ByteStreamWriter x) throws SQLException {
preparedParameters.setBytea(parameterIndex, x);
}
@Override
public void setDate(@Positive int parameterIndex,
@Nullable Date x) throws SQLException {
setDate(parameterIndex, x, null);
}
@Override
public void setTime(@Positive int parameterIndex, @Nullable Time x) throws SQLException {
setTime(parameterIndex, x, null);
}
@Override
public void setTimestamp(@Positive int parameterIndex, @Nullable Timestamp x) throws SQLException {
setTimestamp(parameterIndex, x, null);
}
private void setCharacterStreamPost71(@Positive int parameterIndex,
@Nullable InputStream x, int length,
String encoding) throws SQLException {
if (x == null) {
setNull(parameterIndex, Types.VARCHAR);
return;
}
if (length < 0) {
throw new PSQLException(GT.tr("Invalid stream length {0}.", length),
PSQLState.INVALID_PARAMETER_VALUE);
}
// Version 7.2 supports AsciiStream for all PG text types (char, varchar, text)
// As the spec/javadoc for this method indicate this is to be used for
// large String values (i.e. LONGVARCHAR) PG doesn't have a separate
// long varchar datatype, but with toast all text datatypes are capable of
// handling very large values. Thus the implementation ends up calling
// setString() since there is no current way to stream the value to the server
try {
InputStreamReader inStream = new InputStreamReader(x, encoding);
char[] chars = new char[length];
int charsRead = 0;
while (true) {
int n = inStream.read(chars, charsRead, length - charsRead);
if (n == -1) {
break;
}
charsRead += n;
if (charsRead == length) {
break;
}
}
setString(parameterIndex, new String(chars, 0, charsRead), Oid.VARCHAR);
} catch (UnsupportedEncodingException uee) {
throw new PSQLException(GT.tr("The JVM claims not to support the {0} encoding.", encoding),
PSQLState.UNEXPECTED_ERROR, uee);
} catch (IOException ioe) {
throw new PSQLException(GT.tr("Provided InputStream failed."), PSQLState.UNEXPECTED_ERROR,
ioe);
}
}
@Override
public void setAsciiStream(@Positive int parameterIndex, @Nullable InputStream x,
@NonNegative int length) throws SQLException {
checkClosed();
setCharacterStreamPost71(parameterIndex, x, length, "ASCII");
}
@Override
@SuppressWarnings("deprecation")
public void setUnicodeStream(@Positive int parameterIndex, @Nullable InputStream x,
@NonNegative int length) throws SQLException {
checkClosed();
setCharacterStreamPost71(parameterIndex, x, length, "UTF-8");
}
@Override
public void setBinaryStream(@Positive int parameterIndex, @Nullable InputStream x,
@NonNegative int length) throws SQLException {
// Version 7.2 supports BinaryStream for the PG bytea type
// As the spec/javadoc for this method indicate this is to be used for
// large binary values (i.e. LONGVARBINARY) PG doesn't have a separate
// long binary datatype, but with toast the bytea datatype is capable of
// handling very large values.
setBinaryStream(parameterIndex, x, (long) length);
}
@Override
public void clearParameters() throws SQLException {
preparedParameters.clear();
}
// Helper method for setting parameters to PGobject subclasses.
private void setPGobject(@Positive int parameterIndex, PGobject x) throws SQLException {
String typename = x.getType();
int oid = connection.getTypeInfo().getPGType(typename);
if (oid == Oid.UNSPECIFIED) {
throw new PSQLException(GT.tr("Unknown type {0}.", typename),
PSQLState.INVALID_PARAMETER_TYPE);
}
if ((x instanceof PGBinaryObject) && connection.binaryTransferSend(oid)) {
PGBinaryObject binObj = (PGBinaryObject) x;
int length = binObj.lengthInBytes();
if (length == 0) {
preparedParameters.setNull(parameterIndex, oid);
return;
}
byte[] data = new byte[length];
binObj.toBytes(data, 0);
bindBytes(parameterIndex, data, oid);
} else {
setString(parameterIndex, x.getValue(), oid);
}
}
private void setMap(@Positive int parameterIndex, Map<?, ?> x) throws SQLException {
int oid = connection.getTypeInfo().getPGType("hstore");
if (oid == Oid.UNSPECIFIED) {
throw new PSQLException(GT.tr("No hstore extension installed."),
PSQLState.INVALID_PARAMETER_TYPE);
}
if (connection.binaryTransferSend(oid)) {
byte[] data = HStoreConverter.toBytes(x, connection.getEncoding());
bindBytes(parameterIndex, data, oid);
} else {
setString(parameterIndex, HStoreConverter.toString(x), oid);
}
}
private void setNumber(@Positive int parameterIndex, @Nullable Number x) throws SQLException {
checkClosed();
if (x == null) {
setNull(parameterIndex, Types.DECIMAL);
} else {
bindLiteral(parameterIndex, x.toString(), Oid.NUMERIC);
}
}
@Override
public void setObject(@Positive int parameterIndex, @Nullable Object in,
int targetSqlType, int scale)
throws SQLException {
checkClosed();
if (in == null) {
setNull(parameterIndex, targetSqlType);
return;
}
if (targetSqlType == Types.OTHER && in instanceof UUID
&& connection.haveMinimumServerVersion(ServerVersion.v8_3)) {
setUuid(parameterIndex, (UUID) in);
return;
}
switch (targetSqlType) {
case Types.SQLXML:
if (in instanceof SQLXML) {
setSQLXML(parameterIndex, (SQLXML) in);
} else {
setSQLXML(parameterIndex, new PgSQLXML(connection, in.toString()));
}
break;
case Types.INTEGER:
setInt(parameterIndex, castToInt(in));
break;
case Types.TINYINT:
case Types.SMALLINT:
setShort(parameterIndex, castToShort(in));
break;
case Types.BIGINT:
setLong(parameterIndex, castToLong(in));
break;
case Types.REAL:
setFloat(parameterIndex, castToFloat(in));
break;
case Types.DOUBLE:
case Types.FLOAT:
setDouble(parameterIndex, castToDouble(in));
break;
case Types.DECIMAL:
case Types.NUMERIC:
setBigDecimal(parameterIndex, castToBigDecimal(in, scale));
break;
case Types.CHAR:
setString(parameterIndex, castToString(in), Oid.BPCHAR);
break;
case Types.VARCHAR:
setString(parameterIndex, castToString(in), getStringType());
break;
case Types.LONGVARCHAR:
if (in instanceof InputStream) {
preparedParameters.setText(parameterIndex, (InputStream) in);
} else {
setString(parameterIndex, castToString(in), getStringType());
}
break;
case Types.DATE:
if (in instanceof Date) {
setDate(parameterIndex, (Date) in);
} else {
Date tmpd;
if (in instanceof java.util.Date) {
tmpd = new Date(((java.util.Date) in).getTime());
} else if (in instanceof LocalDate) {
setDate(parameterIndex, (LocalDate) in);
break;
} else {
tmpd = getTimestampUtils().toDate(getDefaultCalendar(), in.toString().getBytes());
}
setDate(parameterIndex, tmpd);
}
break;
case Types.TIME:
if (in instanceof Time) {
setTime(parameterIndex, (Time) in);
} else {
Time tmpt;
if (in instanceof java.util.Date) {
tmpt = new Time(((java.util.Date) in).getTime());
} else if (in instanceof LocalTime) {
setTime(parameterIndex, (LocalTime) in);
break;
} else if (in instanceof OffsetTime) {
setTime(parameterIndex, (OffsetTime) in);
break;
} else {
tmpt = getTimestampUtils().toTime(getDefaultCalendar(), in.toString().getBytes());
}
setTime(parameterIndex, tmpt);
}
break;
case Types.TIMESTAMP:
if (in instanceof PGTimestamp) {
setObject(parameterIndex, in);
} else if (in instanceof Timestamp) {
setTimestamp(parameterIndex, (Timestamp) in);
} else {
Timestamp tmpts;
if (in instanceof java.util.Date) {
tmpts = new Timestamp(((java.util.Date) in).getTime());
} else if (in instanceof LocalDateTime) {
setTimestamp(parameterIndex, (LocalDateTime) in);
break;
} else {
tmpts = getTimestampUtils().toTimestamp(getDefaultCalendar(), in.toString().getBytes());
}
setTimestamp(parameterIndex, tmpts);
}
break;
case Types.TIMESTAMP_WITH_TIMEZONE:
if (in instanceof OffsetDateTime) {
setTimestamp(parameterIndex, (OffsetDateTime) in);
} else if (in instanceof PGTimestamp) {
setObject(parameterIndex, in);
} else {
throw new PSQLException(
GT.tr("Cannot cast an instance of {0} to type {1}",
in.getClass().getName(), "Types.TIMESTAMP_WITH_TIMEZONE"),
PSQLState.INVALID_PARAMETER_TYPE);
}
break;
case Types.BOOLEAN:
case Types.BIT:
setBoolean(parameterIndex, BooleanTypeUtil.castToBoolean(in));
break;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
setObject(parameterIndex, in);
break;
case Types.BLOB:
if (in instanceof Blob) {
setBlob(parameterIndex, (Blob) in);
} else if (in instanceof InputStream) {
long oid = createBlob(parameterIndex, (InputStream) in, Long.MAX_VALUE);
setLong(parameterIndex, oid);
} else {
throw new PSQLException(
GT.tr("Cannot cast an instance of {0} to type {1}",
in.getClass().getName(), "Types.BLOB"),
PSQLState.INVALID_PARAMETER_TYPE);
}
break;
case Types.CLOB:
if (in instanceof Clob) {
setClob(parameterIndex, (Clob) in);
} else {
throw new PSQLException(
GT.tr("Cannot cast an instance of {0} to type {1}",
in.getClass().getName(), "Types.CLOB"),
PSQLState.INVALID_PARAMETER_TYPE);
}
break;
case Types.ARRAY:
if (in instanceof Array) {
setArray(parameterIndex, (Array) in);
} else {
try {
setObjectArray(parameterIndex, in);
} catch (Exception e) {
throw new PSQLException(
GT.tr("Cannot cast an instance of {0} to type {1}", in.getClass().getName(), "Types.ARRAY"),
PSQLState.INVALID_PARAMETER_TYPE, e);
}
}
break;
case Types.DISTINCT:
bindString(parameterIndex, in.toString(), Oid.UNSPECIFIED);
break;
case Types.OTHER:
if (in instanceof PGobject) {
setPGobject(parameterIndex, (PGobject) in);
} else if (in instanceof Map) {
setMap(parameterIndex, (Map<?, ?>) in);
} else {
bindString(parameterIndex, in.toString(), Oid.UNSPECIFIED);
}
break;
default:
throw new PSQLException(GT.tr("Unsupported Types value: {0}", targetSqlType),
PSQLState.INVALID_PARAMETER_TYPE);
}
}
private Class<?> getArrayType(Class<?> type) {
Class<?> subType = type.getComponentType();
while (subType != null) {
type = subType;
subType = type.getComponentType();
}
return type;
}
private <A extends @NonNull Object> void setObjectArray(int parameterIndex, A in) throws SQLException {
final ArrayEncoding.ArrayEncoder<A> arraySupport = ArrayEncoding.getArrayEncoder(in);
final TypeInfo typeInfo = connection.getTypeInfo();
int oid = arraySupport.getDefaultArrayTypeOid();
if (arraySupport.supportBinaryRepresentation(oid) && connection.getPreferQueryMode() != PreferQueryMode.SIMPLE) {
bindBytes(parameterIndex, arraySupport.toBinaryRepresentation(connection, in, oid), oid);
} else {
if (oid == Oid.UNSPECIFIED) {
Class<?> arrayType = getArrayType(in.getClass());
oid = typeInfo.getJavaArrayType(arrayType.getName());
if (oid == Oid.UNSPECIFIED) {
throw new SQLFeatureNotSupportedException();
}
}
final int baseOid = typeInfo.getPGArrayElement(oid);
final String baseType = castNonNull(typeInfo.getPGType(baseOid));
final Array array = getPGConnection().createArrayOf(baseType, in);
this.setArray(parameterIndex, array);
}
}
private static String asString(final Clob in) throws SQLException {
return in.getSubString(1, (int) in.length());
}
private static int castToInt(final Object in) throws SQLException {
try {
if (in instanceof String) {
return Integer.parseInt((String) in);
}
if (in instanceof Number) {
return ((Number) in).intValue();
}
if (in instanceof java.util.Date) {
return (int) ((java.util.Date) in).getTime();
}
if (in instanceof Boolean) {
return (Boolean) in ? 1 : 0;
}
if (in instanceof Clob) {
return Integer.parseInt(asString((Clob) in));
}
if (in instanceof Character) {
return Integer.parseInt(in.toString());
}
} catch (final Exception e) {
throw cannotCastException(in.getClass().getName(), "int", e);
}
throw cannotCastException(in.getClass().getName(), "int");
}
private static short castToShort(final Object in) throws SQLException {
try {
if (in instanceof String) {
return Short.parseShort((String) in);
}
if (in instanceof Number) {
return ((Number) in).shortValue();
}
if (in instanceof java.util.Date) {
return (short) ((java.util.Date) in).getTime();
}
if (in instanceof Boolean) {
return (Boolean) in ? (short) 1 : (short) 0;
}
if (in instanceof Clob) {
return Short.parseShort(asString((Clob) in));
}
if (in instanceof Character) {
return Short.parseShort(in.toString());
}
} catch (final Exception e) {
throw cannotCastException(in.getClass().getName(), "short", e);
}
throw cannotCastException(in.getClass().getName(), "short");
}
private static long castToLong(final Object in) throws SQLException {
try {
if (in instanceof String) {
return Long.parseLong((String) in);
}
if (in instanceof Number) {
return ((Number) in).longValue();
}
if (in instanceof java.util.Date) {
return ((java.util.Date) in).getTime();
}
if (in instanceof Boolean) {
return (Boolean) in ? 1L : 0L;
}
if (in instanceof Clob) {
return Long.parseLong(asString((Clob) in));
}
if (in instanceof Character) {
return Long.parseLong(in.toString());
}
} catch (final Exception e) {
throw cannotCastException(in.getClass().getName(), "long", e);
}
throw cannotCastException(in.getClass().getName(), "long");
}
private static float castToFloat(final Object in) throws SQLException {
try {
if (in instanceof String) {
return Float.parseFloat((String) in);
}
if (in instanceof Number) {
return ((Number) in).floatValue();
}
if (in instanceof java.util.Date) {
return ((java.util.Date) in).getTime();
}
if (in instanceof Boolean) {
return (Boolean) in ? 1f : 0f;
}
if (in instanceof Clob) {
return Float.parseFloat(asString((Clob) in));
}
if (in instanceof Character) {
return Float.parseFloat(in.toString());
}
} catch (final Exception e) {
throw cannotCastException(in.getClass().getName(), "float", e);
}
throw cannotCastException(in.getClass().getName(), "float");
}
private static double castToDouble(final Object in) throws SQLException {
try {
if (in instanceof String) {
return Double.parseDouble((String) in);
}
if (in instanceof Number) {
return ((Number) in).doubleValue();
}
if (in instanceof java.util.Date) {
return ((java.util.Date) in).getTime();
}
if (in instanceof Boolean) {
return (Boolean) in ? 1d : 0d;
}
if (in instanceof Clob) {
return Double.parseDouble(asString((Clob) in));
}
if (in instanceof Character) {
return Double.parseDouble(in.toString());
}
} catch (final Exception e) {
throw cannotCastException(in.getClass().getName(), "double", e);
}
throw cannotCastException(in.getClass().getName(), "double");
}
private static BigDecimal castToBigDecimal(final Object in, final int scale) throws SQLException {
try {
BigDecimal rc = null;
if (in instanceof String) {
rc = new BigDecimal((String) in);
} else if (in instanceof BigDecimal) {
rc = (BigDecimal) in;
} else if (in instanceof BigInteger) {
rc = new BigDecimal((BigInteger) in);
} else if (in instanceof Long || in instanceof Integer || in instanceof Short
|| in instanceof Byte) {
rc = BigDecimal.valueOf(((Number) in).longValue());
} else if (in instanceof Double || in instanceof Float) {
rc = BigDecimal.valueOf(((Number) in).doubleValue());
} else if (in instanceof java.util.Date) {
rc = BigDecimal.valueOf(((java.util.Date) in).getTime());
} else if (in instanceof Boolean) {
rc = (Boolean) in ? BigDecimal.ONE : BigDecimal.ZERO;
} else if (in instanceof Clob) {
rc = new BigDecimal(asString((Clob) in));
} else if (in instanceof Character) {
rc = new BigDecimal(new char[]{(Character) in});
}
if (rc != null) {
if (scale >= 0) {
rc = rc.setScale(scale, RoundingMode.HALF_UP);
}
return rc;
}
} catch (final Exception e) {
throw cannotCastException(in.getClass().getName(), "BigDecimal", e);
}
throw cannotCastException(in.getClass().getName(), "BigDecimal");
}
private static String castToString(final Object in) throws SQLException {
try {
if (in instanceof String) {
return (String) in;
}
if (in instanceof Clob) {
return asString((Clob) in);
}
// convert any unknown objects to string.
return in.toString();
} catch (final Exception e) {
throw cannotCastException(in.getClass().getName(), "String", e);
}
}
private static PSQLException cannotCastException(final String fromType, final String toType) {
return cannotCastException(fromType, toType, null);
}
private static PSQLException cannotCastException(final String fromType, final String toType,
final @Nullable Exception cause) {
return new PSQLException(
GT.tr("Cannot convert an instance of {0} to type {1}", fromType, toType),
PSQLState.INVALID_PARAMETER_TYPE, cause);
}
@Override
public void setObject(@Positive int parameterIndex, @Nullable Object x,
int targetSqlType) throws SQLException {
setObject(parameterIndex, x, targetSqlType, -1);
}
/*
* This stores an Object into a parameter.
*/
@Override
public void setObject(@Positive int parameterIndex, @Nullable Object x) throws SQLException {
checkClosed();
if (x == null) {
setNull(parameterIndex, Types.OTHER);
} else if (x instanceof UUID && connection.haveMinimumServerVersion(ServerVersion.v8_3)) {
setUuid(parameterIndex, (UUID) x);
} else if (x instanceof SQLXML) {