/
PgStatement.java
1382 lines (1186 loc) · 43.8 KB
/
PgStatement.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.BaseStatement;
import org.postgresql.core.CachedQuery;
import org.postgresql.core.Field;
import org.postgresql.core.ParameterList;
import org.postgresql.core.Provider;
import org.postgresql.core.Query;
import org.postgresql.core.QueryExecutor;
import org.postgresql.core.ResultCursor;
import org.postgresql.core.ResultHandlerBase;
import org.postgresql.core.SqlCommand;
import org.postgresql.core.Tuple;
import org.postgresql.util.GT;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
import org.checkerframework.checker.index.qual.NonNegative;
import org.checkerframework.checker.lock.qual.GuardedBy;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.checker.nullness.qual.RequiresNonNull;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
public class PgStatement implements Statement, BaseStatement {
private static final String[] NO_RETURNING_COLUMNS = new String[0];
/**
* Default state for use or not binary transfers. Can use only for testing purposes
*/
private static final boolean DEFAULT_FORCE_BINARY_TRANSFERS =
Boolean.getBoolean("org.postgresql.forceBinary");
// only for testing purposes. even single shot statements will use binary transfers
private boolean forceBinaryTransfers = DEFAULT_FORCE_BINARY_TRANSFERS;
protected final ResourceLock lock = new ResourceLock();
protected @Nullable ArrayList<Query> batchStatements;
protected @Nullable ArrayList<@Nullable ParameterList> batchParameters;
protected final int resultsettype; // the resultset type to return (ResultSet.TYPE_xxx)
protected final int concurrency; // is it updateable or not? (ResultSet.CONCUR_xxx)
private final int rsHoldability;
private boolean poolable;
private boolean closeOnCompletion;
protected int fetchdirection = ResultSet.FETCH_FORWARD;
// fetch direction hint (currently ignored)
/**
* Protects current statement from cancelTask starting, waiting for a bit, and waking up exactly
* on subsequent query execution. The idea is to atomically compare and swap the reference to the
* task, so the task can detect that statement executes different query than the one the
* cancelTask was created. Note: the field must be set/get/compareAndSet via
* {@link #CANCEL_TIMER_UPDATER} as per {@link AtomicReferenceFieldUpdater} javadoc.
*/
private volatile @Nullable TimerTask cancelTimerTask;
@SuppressWarnings("RedundantCast")
// Cast is needed for checkerframework to accept the code
private static final AtomicReferenceFieldUpdater<PgStatement, @Nullable TimerTask> CANCEL_TIMER_UPDATER =
AtomicReferenceFieldUpdater.newUpdater(
PgStatement.class, (Class<@Nullable TimerTask>) TimerTask.class, "cancelTimerTask");
/**
* Protects statement from out-of-order cancels. It protects from both
* {@link #setQueryTimeout(int)} and {@link #cancel()} induced ones.
*
* {@link #execute(String)} and friends change the field to
* {@link StatementCancelState#IN_QUERY} during execute. {@link #cancel()}
* ignores cancel request if state is {@link StatementCancelState#IDLE}.
* In case {@link #execute(String)} observes non-{@link StatementCancelState#IDLE} state as it
* completes the query, it waits till {@link StatementCancelState#CANCELLED}. Note: the field must be
* set/get/compareAndSet via {@link #STATE_UPDATER} as per {@link AtomicIntegerFieldUpdater}
* javadoc.
*/
private volatile StatementCancelState statementState = StatementCancelState.IDLE;
private static final AtomicReferenceFieldUpdater<PgStatement, StatementCancelState> STATE_UPDATER =
AtomicReferenceFieldUpdater.newUpdater(PgStatement.class, StatementCancelState.class, "statementState");
/**
* Does the caller of execute/executeUpdate want generated keys for this execution? This is set by
* Statement methods that have generated keys arguments and cleared after execution is complete.
*/
protected boolean wantsGeneratedKeysOnce;
/**
* Was this PreparedStatement created to return generated keys for every execution? This is set at
* creation time and never cleared by execution.
*/
public boolean wantsGeneratedKeysAlways;
// The connection who created us
protected final PgConnection connection;
/**
* The warnings chain.
*/
protected volatile @Nullable PSQLWarningWrapper warnings;
/**
* Maximum number of rows to return, 0 = unlimited.
*/
protected int maxrows;
/**
* Number of rows to get in a batch.
*/
protected int fetchSize;
/**
* Timeout (in milliseconds) for a query.
*/
protected long timeout;
protected boolean replaceProcessingEnabled = true;
/**
* The current results.
*/
protected @Nullable ResultWrapper result;
/**
* The first unclosed result.
*/
protected @Nullable @GuardedBy("<self>") ResultWrapper firstUnclosedResult;
/**
* Results returned by a statement that wants generated keys.
*/
protected @Nullable ResultWrapper generatedKeys;
protected int mPrepareThreshold; // Reuse threshold to enable use of PREPARE
protected int maxFieldSize;
protected boolean adaptiveFetch;
private @Nullable TimestampUtils timestampUtils; // our own Object because it's not thread safe
@SuppressWarnings("method.invocation")
PgStatement(PgConnection c, int rsType, int rsConcurrency, int rsHoldability)
throws SQLException {
this.connection = c;
forceBinaryTransfers |= c.getForceBinary();
// validation check for allowed values of resultset type
if (rsType != ResultSet.TYPE_FORWARD_ONLY && rsType != ResultSet.TYPE_SCROLL_INSENSITIVE && rsType != ResultSet.TYPE_SCROLL_SENSITIVE) {
throw new PSQLException(GT.tr("Unknown value for ResultSet type"),
PSQLState.INVALID_PARAMETER_VALUE);
}
resultsettype = rsType;
// validation check for allowed values of resultset concurrency
if (rsConcurrency != ResultSet.CONCUR_READ_ONLY && rsConcurrency != ResultSet.CONCUR_UPDATABLE) {
throw new PSQLException(GT.tr("Unknown value for ResultSet concurrency"),
PSQLState.INVALID_PARAMETER_VALUE);
}
concurrency = rsConcurrency;
setFetchSize(c.getDefaultFetchSize());
setPrepareThreshold(c.getPrepareThreshold());
setAdaptiveFetch(c.getAdaptiveFetch());
// validation check for allowed values of resultset holdability
if (rsHoldability != ResultSet.HOLD_CURSORS_OVER_COMMIT && rsHoldability != ResultSet.CLOSE_CURSORS_AT_COMMIT) {
throw new PSQLException(GT.tr("Unknown value for ResultSet holdability"),
PSQLState.INVALID_PARAMETER_VALUE);
}
this.rsHoldability = rsHoldability;
}
@Override
@SuppressWarnings("method.invocation")
public ResultSet createResultSet(@Nullable Query originalQuery, Field[] fields, List<Tuple> tuples,
@Nullable ResultCursor cursor) throws SQLException {
PgResultSet newResult = new PgResultSet(originalQuery, this, fields, tuples, cursor,
getMaxRows(), getMaxFieldSize(), getResultSetType(), getResultSetConcurrency(),
getResultSetHoldability(), getAdaptiveFetch());
newResult.setFetchSize(getFetchSize());
newResult.setFetchDirection(getFetchDirection());
return newResult;
}
public BaseConnection getPGConnection() {
return connection;
}
public @Nullable String getFetchingCursorName() {
return null;
}
@Override
public @NonNegative int getFetchSize() {
return fetchSize;
}
protected boolean wantsScrollableResultSet() {
return resultsettype != ResultSet.TYPE_FORWARD_ONLY;
}
protected boolean wantsHoldableResultSet() {
// FIXME: false if not supported
return rsHoldability == ResultSet.HOLD_CURSORS_OVER_COMMIT;
}
/**
* ResultHandler implementations for updates, queries, and either-or.
*/
public class StatementResultHandler extends ResultHandlerBase {
private @Nullable ResultWrapper results;
private @Nullable ResultWrapper lastResult;
@Nullable ResultWrapper getResults() {
return results;
}
private void append(ResultWrapper newResult) {
if (results == null) {
lastResult = results = newResult;
} else {
castNonNull(lastResult).append(newResult);
}
}
@Override
public void handleResultRows(Query fromQuery, Field[] fields, List<Tuple> tuples,
@Nullable ResultCursor cursor) {
try {
ResultSet rs = PgStatement.this.createResultSet(fromQuery, fields, tuples, cursor);
append(new ResultWrapper(rs));
} catch (SQLException e) {
handleError(e);
}
}
@Override
public void handleCommandStatus(String status, long updateCount, long insertOID) {
append(new ResultWrapper(updateCount, insertOID));
}
@Override
public void handleWarning(SQLWarning warning) {
PgStatement.this.addWarning(warning);
}
}
@Override
public ResultSet executeQuery(String sql) throws SQLException {
try (ResourceLock ignore = lock.obtain()) {
if (!executeWithFlags(sql, 0)) {
throw new PSQLException(GT.tr("No results were returned by the query."), PSQLState.NO_DATA);
}
return getSingleResultSet();
}
}
protected ResultSet getSingleResultSet() throws SQLException {
try (ResourceLock ignore = lock.obtain()) {
checkClosed();
ResultWrapper result = castNonNull(this.result);
if (result.getNext() != null) {
throw new PSQLException(GT.tr("Multiple ResultSets were returned by the query."),
PSQLState.TOO_MANY_RESULTS);
}
return castNonNull(result.getResultSet(), "result.getResultSet()");
}
}
@Override
public int executeUpdate(String sql) throws SQLException {
try (ResourceLock ignore = lock.obtain()) {
executeWithFlags(sql, QueryExecutor.QUERY_NO_RESULTS);
checkNoResultUpdate();
return getUpdateCount();
}
}
protected final void checkNoResultUpdate() throws SQLException {
try (ResourceLock ignore = lock.obtain()) {
checkClosed();
ResultWrapper iter = result;
while (iter != null) {
if (iter.getResultSet() != null) {
throw new PSQLException(GT.tr("A result was returned when none was expected."),
PSQLState.TOO_MANY_RESULTS);
}
iter = iter.getNext();
}
}
}
@Override
public boolean execute(String sql) throws SQLException {
return executeWithFlags(sql, 0);
}
@Override
public boolean executeWithFlags(String sql, int flags) throws SQLException {
return executeCachedSql(sql, flags, NO_RETURNING_COLUMNS);
}
private boolean executeCachedSql(String sql, int flags,
String @Nullable [] columnNames) throws SQLException {
PreferQueryMode preferQueryMode = connection.getPreferQueryMode();
// Simple statements should not replace ?, ? with $1, $2
boolean shouldUseParameterized = false;
QueryExecutor queryExecutor = connection.getQueryExecutor();
Object key = queryExecutor
.createQueryKey(sql, replaceProcessingEnabled, shouldUseParameterized, columnNames);
CachedQuery cachedQuery;
boolean shouldCache = preferQueryMode == PreferQueryMode.EXTENDED_CACHE_EVERYTHING;
if (shouldCache) {
cachedQuery = queryExecutor.borrowQueryByKey(key);
} else {
cachedQuery = queryExecutor.createQueryByKey(key);
}
if (wantsGeneratedKeysOnce) {
SqlCommand sqlCommand = cachedQuery.query.getSqlCommand();
wantsGeneratedKeysOnce = sqlCommand != null && sqlCommand.isReturningKeywordPresent();
}
boolean res;
try {
res = executeWithFlags(cachedQuery, flags);
} finally {
if (shouldCache) {
queryExecutor.releaseQuery(cachedQuery);
}
}
return res;
}
@Override
public boolean executeWithFlags(CachedQuery simpleQuery, int flags) throws SQLException {
checkClosed();
if (connection.getPreferQueryMode().compareTo(PreferQueryMode.EXTENDED) < 0) {
flags |= QueryExecutor.QUERY_EXECUTE_AS_SIMPLE;
}
execute(simpleQuery, null, flags);
try (ResourceLock ignore = lock.obtain()) {
checkClosed();
return result != null && result.getResultSet() != null;
}
}
@Override
public boolean executeWithFlags(int flags) throws SQLException {
checkClosed();
throw new PSQLException(GT.tr("Can''t use executeWithFlags(int) on a Statement."),
PSQLState.WRONG_OBJECT_TYPE);
}
/*
If there are multiple result sets we close any that have been processed and left open
by the client.
*/
private void closeUnclosedProcessedResults() throws SQLException {
try (ResourceLock ignore = lock.obtain()) {
ResultWrapper resultWrapper = this.firstUnclosedResult;
ResultWrapper currentResult = this.result;
for (; resultWrapper != currentResult && resultWrapper != null;
resultWrapper = resultWrapper.getNext()) {
PgResultSet rs = (PgResultSet) resultWrapper.getResultSet();
if (rs != null) {
rs.closeInternally();
}
}
firstUnclosedResult = resultWrapper;
}
}
protected void closeForNextExecution() throws SQLException {
// Every statement execution clears any previous warnings.
clearWarnings();
// Close any existing resultsets associated with this statement.
try (ResourceLock ignore = lock.obtain()) {
closeUnclosedProcessedResults();
if ( this.result != null && this.result.getResultSet() != null ) {
this.result.getResultSet().close();
}
result = null;
ResultWrapper generatedKeys = this.generatedKeys;
if (generatedKeys != null) {
ResultSet resultSet = generatedKeys.getResultSet();
if (resultSet != null) {
resultSet.close();
}
this.generatedKeys = null;
}
}
}
/**
* Returns true if query is unlikely to be reused.
*
* @param cachedQuery to check (null if current query)
* @return true if query is unlikely to be reused
*/
protected boolean isOneShotQuery(@Nullable CachedQuery cachedQuery) {
if (cachedQuery == null) {
return true;
}
cachedQuery.increaseExecuteCount();
return (mPrepareThreshold == 0 || cachedQuery.getExecuteCount() < mPrepareThreshold)
&& !getForceBinaryTransfer();
}
protected final void execute(CachedQuery cachedQuery,
@Nullable ParameterList queryParameters, int flags)
throws SQLException {
try (ResourceLock ignore = lock.obtain()) {
try {
executeInternal(cachedQuery, queryParameters, flags);
} catch (SQLException e) {
// Don't retry composite queries as it might get partially executed
if (cachedQuery.query.getSubqueries() != null
|| !connection.getQueryExecutor().willHealOnRetry(e)) {
throw e;
}
cachedQuery.query.close();
// Execute the query one more time
executeInternal(cachedQuery, queryParameters, flags);
}
}
}
private void executeInternal(CachedQuery cachedQuery,
@Nullable ParameterList queryParameters, int flags)
throws SQLException {
closeForNextExecution();
// Enable cursor-based resultset if possible.
if (fetchSize > 0 && !wantsScrollableResultSet() && !connection.getAutoCommit()
&& !wantsHoldableResultSet()) {
flags |= QueryExecutor.QUERY_FORWARD_CURSOR;
}
if (wantsGeneratedKeysOnce || wantsGeneratedKeysAlways) {
flags |= QueryExecutor.QUERY_BOTH_ROWS_AND_STATUS;
// If the no results flag is set (from executeUpdate)
// clear it so we get the generated keys results.
//
if ((flags & QueryExecutor.QUERY_NO_RESULTS) != 0) {
flags &= ~(QueryExecutor.QUERY_NO_RESULTS);
}
}
// Only use named statements after we hit the threshold. Note that only
// named statements can be transferred in binary format.
// isOneShotQuery will check to see if we have hit the prepareThreshold count
if (isOneShotQuery(cachedQuery)) {
flags |= QueryExecutor.QUERY_ONESHOT;
}
if (connection.getAutoCommit()) {
flags |= QueryExecutor.QUERY_SUPPRESS_BEGIN;
}
if (connection.hintReadOnly()) {
flags |= QueryExecutor.QUERY_READ_ONLY_HINT;
}
// updateable result sets do not yet support binary updates
if (concurrency != ResultSet.CONCUR_READ_ONLY) {
flags |= QueryExecutor.QUERY_NO_BINARY_TRANSFER;
}
Query queryToExecute = cachedQuery.query;
if (queryToExecute.isEmpty()) {
flags |= QueryExecutor.QUERY_SUPPRESS_BEGIN;
}
if (!queryToExecute.isStatementDescribed() && forceBinaryTransfers
&& (flags & QueryExecutor.QUERY_EXECUTE_AS_SIMPLE) == 0) {
// Simple 'Q' execution does not need to know parameter types
// When binaryTransfer is forced, then we need to know resulting parameter and column types,
// thus sending a describe request.
int flags2 = flags | QueryExecutor.QUERY_DESCRIBE_ONLY;
StatementResultHandler handler2 = new StatementResultHandler();
connection.getQueryExecutor().execute(queryToExecute, queryParameters, handler2, 0, 0,
flags2);
ResultWrapper result2 = handler2.getResults();
if (result2 != null) {
castNonNull(result2.getResultSet(), "result2.getResultSet()").close();
}
}
StatementResultHandler handler = new StatementResultHandler();
try (ResourceLock ignore = lock.obtain()) {
result = null;
}
try {
startTimer();
connection.getQueryExecutor().execute(queryToExecute, queryParameters, handler, maxrows,
fetchSize, flags, adaptiveFetch);
} finally {
killTimerTask();
}
try (ResourceLock ignore = lock.obtain()) {
checkClosed();
ResultWrapper currentResult = handler.getResults();
result = firstUnclosedResult = currentResult;
if (wantsGeneratedKeysOnce || wantsGeneratedKeysAlways) {
generatedKeys = currentResult;
result = castNonNull(currentResult, "handler.getResults()").getNext();
if (wantsGeneratedKeysOnce) {
wantsGeneratedKeysOnce = false;
}
}
}
}
@Override
public void setCursorName(String name) throws SQLException {
checkClosed();
// No-op.
}
private volatile int isClosed;
private static final AtomicIntegerFieldUpdater<PgStatement> IS_CLOSED_UPDATER =
AtomicIntegerFieldUpdater.newUpdater(
PgStatement.class, "isClosed");
@Override
public int getUpdateCount() throws SQLException {
try (ResourceLock ignore = lock.obtain()) {
checkClosed();
if (result == null || result.getResultSet() != null) {
return -1;
}
long count = result.getUpdateCount();
return count > Integer.MAX_VALUE ? Statement.SUCCESS_NO_INFO : (int) count;
}
}
@Override
public boolean getMoreResults() throws SQLException {
return getMoreResults(CLOSE_ALL_RESULTS);
}
@Override
public int getMaxRows() throws SQLException {
checkClosed();
return maxrows;
}
@Override
public void setMaxRows(int max) throws SQLException {
checkClosed();
if (max < 0) {
throw new PSQLException(
GT.tr("Maximum number of rows must be a value greater than or equal to 0."),
PSQLState.INVALID_PARAMETER_VALUE);
}
maxrows = max;
}
@Override
public void setEscapeProcessing(boolean enable) throws SQLException {
checkClosed();
replaceProcessingEnabled = enable;
}
@Override
public int getQueryTimeout() throws SQLException {
checkClosed();
long seconds = timeout / 1000;
if (seconds >= Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
return (int) seconds;
}
@Override
public void setQueryTimeout(int seconds) throws SQLException {
setQueryTimeoutMs(seconds * 1000L);
}
/**
* The queryTimeout limit is the number of milliseconds the driver will wait for a Statement to
* execute. If the limit is exceeded, a SQLException is thrown.
*
* @return the current query timeout limit in milliseconds; 0 = unlimited
* @throws SQLException if a database access error occurs
*/
public long getQueryTimeoutMs() throws SQLException {
checkClosed();
return timeout;
}
/**
* Sets the queryTimeout limit.
*
* @param millis - the new query timeout limit in milliseconds
* @throws SQLException if a database access error occurs
*/
public void setQueryTimeoutMs(long millis) throws SQLException {
checkClosed();
if (millis < 0) {
throw new PSQLException(GT.tr("Query timeout must be a value greater than or equals to 0."),
PSQLState.INVALID_PARAMETER_VALUE);
}
timeout = millis;
}
/**
* <p>Either initializes new warning wrapper, or adds warning onto the chain.</p>
*
* <p>Although warnings are expected to be added sequentially, the warnings chain may be cleared
* concurrently at any time via {@link #clearWarnings()}, therefore it is possible that a warning
* added via this method is placed onto the end of the previous warning chain</p>
*
* @param warn warning to add
*/
public void addWarning(SQLWarning warn) {
//copy reference to avoid NPE from concurrent modification of this.warnings
final PSQLWarningWrapper warnWrap = this.warnings;
if (warnWrap == null) {
this.warnings = new PSQLWarningWrapper(warn);
} else {
warnWrap.addWarning(warn);
}
}
@Override
public @Nullable SQLWarning getWarnings() throws SQLException {
checkClosed();
//copy reference to avoid NPE from concurrent modification of this.warnings
final PSQLWarningWrapper warnWrap = this.warnings;
return warnWrap != null ? warnWrap.getFirstWarning() : null;
}
@Override
public int getMaxFieldSize() throws SQLException {
return maxFieldSize;
}
@Override
public void setMaxFieldSize(int max) throws SQLException {
checkClosed();
if (max < 0) {
throw new PSQLException(
GT.tr("The maximum field size must be a value greater than or equal to 0."),
PSQLState.INVALID_PARAMETER_VALUE);
}
maxFieldSize = max;
}
/**
* <p>Clears the warning chain.</p>
* <p>Note that while it is safe to clear warnings while the query is executing, warnings that are
* added between calls to {@link #getWarnings()} and #clearWarnings() may be missed.
* Therefore you should hold a reference to the tail of the previous warning chain
* and verify if its {@link SQLWarning#getNextWarning()} value is holds any new value.</p>
*/
@Override
public void clearWarnings() throws SQLException {
warnings = null;
}
@Override
public @Nullable ResultSet getResultSet() throws SQLException {
try (ResourceLock ignore = lock.obtain()) {
checkClosed();
if (result == null) {
return null;
}
return result.getResultSet();
}
}
/**
* <B>Note:</B> even though {@code Statement} is automatically closed when it is garbage
* collected, it is better to close it explicitly to lower resource consumption.
*
* {@inheritDoc}
*/
@Override
public final void close() throws SQLException {
// closing an already closed Statement is a no-op.
if (!IS_CLOSED_UPDATER.compareAndSet(this, 0, 1)) {
return;
}
cancel();
closeForNextExecution();
closeImpl();
}
/**
* This is guaranteed to be called exactly once even in case of concurrent {@link #close()} calls.
* @throws SQLException in case of error
*/
protected void closeImpl() throws SQLException {
}
/*
*
* The following methods are postgres extensions and are defined in the interface BaseStatement
*
*/
@Override
public long getLastOID() throws SQLException {
try (ResourceLock ignore = lock.obtain()) {
checkClosed();
if (result == null) {
return 0;
}
return result.getInsertOID();
}
}
@Override
public void setPrepareThreshold(int newThreshold) throws SQLException {
checkClosed();
if (newThreshold < 0) {
forceBinaryTransfers = true;
newThreshold = 1;
}
this.mPrepareThreshold = newThreshold;
}
@Override
public int getPrepareThreshold() {
return mPrepareThreshold;
}
@Override
@SuppressWarnings("deprecation")
public void setUseServerPrepare(boolean flag) throws SQLException {
setPrepareThreshold(flag ? 1 : 0);
}
@Override
public boolean isUseServerPrepare() {
return false;
}
protected void checkClosed() throws SQLException {
if (isClosed()) {
throw new PSQLException(GT.tr("This statement has been closed."),
PSQLState.OBJECT_NOT_IN_STATE);
}
}
// ** JDBC 2 Extensions **
@Override
public void addBatch(String sql) throws SQLException {
checkClosed();
ArrayList<Query> batchStatements = this.batchStatements;
if (batchStatements == null) {
this.batchStatements = batchStatements = new ArrayList<>();
}
ArrayList<@Nullable ParameterList> batchParameters = this.batchParameters;
if (batchParameters == null) {
this.batchParameters = batchParameters = new ArrayList<@Nullable ParameterList>();
}
// Simple statements should not replace ?, ? with $1, $2
boolean shouldUseParameterized = false;
CachedQuery cachedQuery = connection.createQuery(sql, replaceProcessingEnabled, shouldUseParameterized);
batchStatements.add(cachedQuery.query);
batchParameters.add(null);
}
@Override
public void clearBatch() throws SQLException {
if (batchStatements != null) {
batchStatements.clear();
}
if (batchParameters != null) {
batchParameters.clear();
}
}
protected BatchResultHandler createBatchHandler(Query[] queries,
@Nullable ParameterList[] parameterLists) {
return new BatchResultHandler(this, queries, parameterLists,
wantsGeneratedKeysAlways);
}
@RequiresNonNull({"batchStatements", "batchParameters"})
private BatchResultHandler internalExecuteBatch() throws SQLException {
// Construct query/parameter arrays.
transformQueriesAndParameters();
ArrayList<Query> batchStatements = castNonNull(this.batchStatements);
ArrayList<@Nullable ParameterList> batchParameters = castNonNull(this.batchParameters);
// Empty arrays should be passed to toArray
// see http://shipilev.net/blog/2016/arrays-wisdom-ancients/
Query[] queries = batchStatements.toArray(new Query[0]);
@Nullable ParameterList[] parameterLists = batchParameters.toArray(new ParameterList[0]);
batchStatements.clear();
batchParameters.clear();
int flags;
// Force a Describe before any execution? We need to do this if we're going
// to send anything dependent on the Describe results, e.g. binary parameters.
boolean preDescribe = false;
if (wantsGeneratedKeysAlways) {
/*
* This batch will return generated keys, tell the executor to expect result rows. We also
* force a Describe later so we know the size of the results to expect.
*
* If the parameter type(s) change between batch entries and the default binary-mode changes
* we might get mixed binary and text in a single result set column, which we cannot handle.
* To prevent this, disable binary transfer mode in batches that return generated keys. See
* GitHub issue #267
*/
flags = QueryExecutor.QUERY_BOTH_ROWS_AND_STATUS | QueryExecutor.QUERY_NO_BINARY_TRANSFER;
} else {
// If a batch hasn't specified that it wants generated keys, using the appropriate
// Connection.createStatement(...) interfaces, disallow any result set.
flags = QueryExecutor.QUERY_NO_RESULTS;
}
PreferQueryMode preferQueryMode = connection.getPreferQueryMode();
if (preferQueryMode == PreferQueryMode.SIMPLE
|| (preferQueryMode == PreferQueryMode.EXTENDED_FOR_PREPARED
&& parameterLists[0] == null)) {
flags |= QueryExecutor.QUERY_EXECUTE_AS_SIMPLE;
}
boolean sameQueryAhead = queries.length > 1 && queries[0] == queries[1];
if (!sameQueryAhead
// If executing the same query twice in a batch, make sure the statement
// is server-prepared. In other words, "oneshot" only if the query is one in the batch
// or the queries are different
|| isOneShotQuery(null)) {
flags |= QueryExecutor.QUERY_ONESHOT;
} else {
// If a batch requests generated keys and isn't already described,
// force a Describe of the query before proceeding. That way we can
// determine the appropriate size of each batch by estimating the
// maximum data returned. Without that, we don't know how many queries
// we'll be able to queue up before we risk a deadlock.
// (see v3.QueryExecutorImpl's MAX_BUFFERED_RECV_BYTES)
// SameQueryAhead is just a quick way to issue pre-describe for batch execution
// TODO: It should be reworked into "pre-describe if query has unknown parameter
// types and same query is ahead".
preDescribe = (wantsGeneratedKeysAlways || sameQueryAhead)
&& !queries[0].isStatementDescribed();
/*
* It's also necessary to force a Describe on the first execution of the new statement, even
* though we already described it, to work around bug #267.
*/
flags |= QueryExecutor.QUERY_FORCE_DESCRIBE_PORTAL;
}
if (connection.getAutoCommit()) {
flags |= QueryExecutor.QUERY_SUPPRESS_BEGIN;
}
if (connection.hintReadOnly()) {
flags |= QueryExecutor.QUERY_READ_ONLY_HINT;
}
BatchResultHandler handler;
handler = createBatchHandler(queries, parameterLists);
if ((preDescribe || forceBinaryTransfers)
&& (flags & QueryExecutor.QUERY_EXECUTE_AS_SIMPLE) == 0) {
// Do a client-server round trip, parsing and describing the query so we
// can determine its result types for use in binary parameters, batch sizing,
// etc.
int flags2 = flags | QueryExecutor.QUERY_DESCRIBE_ONLY;
StatementResultHandler handler2 = new StatementResultHandler();
try {
connection.getQueryExecutor().execute(queries[0], parameterLists[0], handler2, 0, 0, flags2);
} catch (SQLException e) {
// Unable to parse the first statement -> throw BatchUpdateException
handler.handleError(e);
handler.handleCompletion();
// Will not reach here (see above)
}
ResultWrapper result2 = handler2.getResults();
if (result2 != null) {
castNonNull(result2.getResultSet(), "result2.getResultSet()").close();
}
}
try (ResourceLock ignore = lock.obtain()) {
result = null;
}
try {
startTimer();
connection.getQueryExecutor().execute(queries, parameterLists, handler, maxrows, fetchSize,
flags, adaptiveFetch);
} finally {
killTimerTask();
// There might be some rows generated even in case of failures
try (ResourceLock ignore = lock.obtain()) {
checkClosed();
if (wantsGeneratedKeysAlways) {
generatedKeys = new ResultWrapper(handler.getGeneratedKeys());
}
}
}
return handler;
}
@Override
public int[] executeBatch() throws SQLException {
checkClosed();
closeForNextExecution();
if (batchStatements == null || batchStatements.isEmpty() || batchParameters == null) {
return new int[0];
}
return internalExecuteBatch().getUpdateCount();
}
@Override
public void cancel() throws SQLException {
if (statementState == StatementCancelState.IDLE) {
return;
}
if (!STATE_UPDATER.compareAndSet(this, StatementCancelState.IN_QUERY,
StatementCancelState.CANCELING)) {
// Not in query, there's nothing to cancel
return;
}
// Use connection lock to avoid spinning in killTimerTask
try (ResourceLock connectionLock = connection.obtainLock()) {
try {
connection.cancelQuery();
} finally {
STATE_UPDATER.set(this, StatementCancelState.CANCELLED);
connection.lockCondition().signalAll(); // wake-up killTimerTask
}
}
}
@Override
public Connection getConnection() throws SQLException {
return connection;
}
@Override
public int getFetchDirection() {
return fetchdirection;
}
@Override
public int getResultSetConcurrency() {
return concurrency;
}
@Override
public int getResultSetType() {
return resultsettype;
}
@Override
public void setFetchDirection(int direction) throws SQLException {
switch (direction) {
case ResultSet.FETCH_FORWARD:
case ResultSet.FETCH_REVERSE:
case ResultSet.FETCH_UNKNOWN: