/
QueryExecutorImpl.java
2749 lines (2344 loc) · 96.1 KB
/
QueryExecutorImpl.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) 2003, PostgreSQL Global Development Group
* See the LICENSE file in the project root for more information.
*/
// Copyright (c) 2004, Open Cloud Limited.
package org.postgresql.core.v3;
import org.postgresql.PGProperty;
import org.postgresql.copy.CopyIn;
import org.postgresql.copy.CopyOperation;
import org.postgresql.copy.CopyOut;
import org.postgresql.core.CommandCompleteParser;
import org.postgresql.core.Encoding;
import org.postgresql.core.EncodingPredictor;
import org.postgresql.core.Field;
import org.postgresql.core.NativeQuery;
import org.postgresql.core.Oid;
import org.postgresql.core.PGBindException;
import org.postgresql.core.PGStream;
import org.postgresql.core.ParameterList;
import org.postgresql.core.Parser;
import org.postgresql.core.Query;
import org.postgresql.core.QueryExecutor;
import org.postgresql.core.QueryExecutorBase;
import org.postgresql.core.ReplicationProtocol;
import org.postgresql.core.ResultCursor;
import org.postgresql.core.ResultHandler;
import org.postgresql.core.ResultHandlerBase;
import org.postgresql.core.ResultHandlerDelegate;
import org.postgresql.core.SqlCommand;
import org.postgresql.core.SqlCommandType;
import org.postgresql.core.TransactionState;
import org.postgresql.core.Utils;
import org.postgresql.core.v3.replication.V3ReplicationProtocol;
import org.postgresql.jdbc.AutoSave;
import org.postgresql.jdbc.BatchResultHandler;
import org.postgresql.jdbc.TimestampUtils;
import org.postgresql.util.GT;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
import org.postgresql.util.PSQLWarning;
import org.postgresql.util.ServerErrorMessage;
import java.io.IOException;
import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* QueryExecutor implementation for the V3 protocol.
*/
public class QueryExecutorImpl extends QueryExecutorBase {
private static final Logger LOGGER = Logger.getLogger(QueryExecutorImpl.class.getName());
/**
* TimeZone of the current connection (TimeZone backend parameter).
*/
private TimeZone timeZone;
/**
* application_name connection property.
*/
private String applicationName;
/**
* True if server uses integers for date and time fields. False if server uses double.
*/
private boolean integerDateTimes;
/**
* Bit set that has a bit set for each oid which should be received using binary format.
*/
private final Set<Integer> useBinaryReceiveForOids = new HashSet<Integer>();
/**
* Bit set that has a bit set for each oid which should be sent using binary format.
*/
private final Set<Integer> useBinarySendForOids = new HashSet<Integer>();
/**
* This is a fake query object so processResults can distinguish "ReadyForQuery" messages
* from Sync messages vs from simple execute (aka 'Q').
*/
private final SimpleQuery sync = (SimpleQuery) createQuery("SYNC", false, true).query;
private short deallocateEpoch;
/**
* This caches the latest observed {@code set search_path} query so the reset of prepared
* statement cache can be skipped if using repeated calls for the same {@code set search_path}
* value.
*/
private String lastSetSearchPathQuery;
/**
* The exception that caused the last transaction to fail.
*/
private SQLException transactionFailCause;
private final ReplicationProtocol replicationProtocol;
/**
* {@code CommandComplete(B)} messages are quite common, so we reuse instance to parse those
*/
private final CommandCompleteParser commandCompleteParser = new CommandCompleteParser();
public QueryExecutorImpl(PGStream pgStream, String user, String database,
int cancelSignalTimeout, Properties info) throws SQLException, IOException {
super(pgStream, user, database, cancelSignalTimeout, info);
this.allowEncodingChanges = PGProperty.ALLOW_ENCODING_CHANGES.getBoolean(info);
this.replicationProtocol = new V3ReplicationProtocol(this, pgStream);
readStartupMessages();
}
@Override
public int getProtocolVersion() {
return 3;
}
/**
* <p>Supplement to synchronization of public methods on current QueryExecutor.</p>
*
* <p>Necessary for keeping the connection intact between calls to public methods sharing a state
* such as COPY subprotocol. waitOnLock() must be called at beginning of each connection access
* point.</p>
*
* <p>Public methods sharing that state must then be synchronized among themselves. Normal method
* synchronization typically suffices for that.</p>
*
* <p>See notes on related methods as well as currentCopy() below.</p>
*/
private Object lockedFor = null;
/**
* Obtain lock over this connection for given object, blocking to wait if necessary.
*
* @param obtainer object that gets the lock. Normally current thread.
* @throws PSQLException when already holding the lock or getting interrupted.
*/
private void lock(Object obtainer) throws PSQLException {
if (lockedFor == obtainer) {
throw new PSQLException(GT.tr("Tried to obtain lock while already holding it"),
PSQLState.OBJECT_NOT_IN_STATE);
}
waitOnLock();
lockedFor = obtainer;
}
/**
* Release lock on this connection presumably held by given object.
*
* @param holder object that holds the lock. Normally current thread.
* @throws PSQLException when this thread does not hold the lock
*/
private void unlock(Object holder) throws PSQLException {
if (lockedFor != holder) {
throw new PSQLException(GT.tr("Tried to break lock on database connection"),
PSQLState.OBJECT_NOT_IN_STATE);
}
lockedFor = null;
this.notify();
}
/**
* Wait until our lock is released. Execution of a single synchronized method can then continue
* without further ado. Must be called at beginning of each synchronized public method.
*/
private void waitOnLock() throws PSQLException {
while (lockedFor != null) {
try {
this.wait();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw new PSQLException(
GT.tr("Interrupted while waiting to obtain lock on database connection"),
PSQLState.OBJECT_NOT_IN_STATE, ie);
}
}
}
/**
* @param holder object assumed to hold the lock
* @return whether given object actually holds the lock
*/
boolean hasLock(Object holder) {
return lockedFor == holder;
}
//
// Query parsing
//
public Query createSimpleQuery(String sql) throws SQLException {
List<NativeQuery> queries = Parser.parseJdbcSql(sql,
getStandardConformingStrings(), false, true,
isReWriteBatchedInsertsEnabled());
return wrap(queries);
}
@Override
public Query wrap(List<NativeQuery> queries) {
if (queries.isEmpty()) {
// Empty query
return EMPTY_QUERY;
}
if (queries.size() == 1) {
NativeQuery firstQuery = queries.get(0);
if (isReWriteBatchedInsertsEnabled()
&& firstQuery.getCommand().isBatchedReWriteCompatible()) {
int valuesBraceOpenPosition =
firstQuery.getCommand().getBatchRewriteValuesBraceOpenPosition();
int valuesBraceClosePosition =
firstQuery.getCommand().getBatchRewriteValuesBraceClosePosition();
return new BatchedQuery(firstQuery, this, valuesBraceOpenPosition,
valuesBraceClosePosition, isColumnSanitiserDisabled());
} else {
return new SimpleQuery(firstQuery, this, isColumnSanitiserDisabled());
}
}
// Multiple statements.
SimpleQuery[] subqueries = new SimpleQuery[queries.size()];
int[] offsets = new int[subqueries.length];
int offset = 0;
for (int i = 0; i < queries.size(); ++i) {
NativeQuery nativeQuery = queries.get(i);
offsets[i] = offset;
subqueries[i] = new SimpleQuery(nativeQuery, this, isColumnSanitiserDisabled());
offset += nativeQuery.bindPositions.length;
}
return new CompositeQuery(subqueries, offsets);
}
//
// Query execution
//
private int updateQueryMode(int flags) {
switch (getPreferQueryMode()) {
case SIMPLE:
return flags | QUERY_EXECUTE_AS_SIMPLE;
case EXTENDED:
return flags & ~QUERY_EXECUTE_AS_SIMPLE;
default:
return flags;
}
}
public synchronized void execute(Query query, ParameterList parameters, ResultHandler handler,
int maxRows, int fetchSize, int flags) throws SQLException {
waitOnLock();
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.log(Level.FINEST, " simple execute, handler={0}, maxRows={1}, fetchSize={2}, flags={3}",
new Object[]{handler, maxRows, fetchSize, flags});
}
if (parameters == null) {
parameters = SimpleQuery.NO_PARAMETERS;
}
flags = updateQueryMode(flags);
boolean describeOnly = (QUERY_DESCRIBE_ONLY & flags) != 0;
((V3ParameterList) parameters).convertFunctionOutParameters();
// Check parameters are all set..
if (!describeOnly) {
((V3ParameterList) parameters).checkAllParametersSet();
}
boolean autosave = false;
try {
try {
handler = sendQueryPreamble(handler, flags);
autosave = sendAutomaticSavepoint(query, flags);
sendQuery(query, (V3ParameterList) parameters, maxRows, fetchSize, flags,
handler, null);
if ((flags & QueryExecutor.QUERY_EXECUTE_AS_SIMPLE) != 0) {
// Sync message is not required for 'Q' execution as 'Q' ends with ReadyForQuery message
// on its own
} else {
sendSync();
}
processResults(handler, flags);
estimatedReceiveBufferBytes = 0;
} catch (PGBindException se) {
// There are three causes of this error, an
// invalid total Bind message length, a
// BinaryStream that cannot provide the amount
// of data claimed by the length argument, and
// a BinaryStream that throws an Exception
// when reading.
//
// We simply do not send the Execute message
// so we can just continue on as if nothing
// has happened. Perhaps we need to
// introduce an error here to force the
// caller to rollback if there is a
// transaction in progress?
//
sendSync();
processResults(handler, flags);
estimatedReceiveBufferBytes = 0;
handler
.handleError(new PSQLException(GT.tr("Unable to bind parameter values for statement."),
PSQLState.INVALID_PARAMETER_VALUE, se.getIOException()));
}
} catch (IOException e) {
abort();
handler.handleError(
new PSQLException(GT.tr("An I/O error occurred while sending to the backend."),
PSQLState.CONNECTION_FAILURE, e));
}
try {
handler.handleCompletion();
} catch (SQLException e) {
rollbackIfRequired(autosave, e);
}
}
private boolean sendAutomaticSavepoint(Query query, int flags) throws IOException {
if (((flags & QueryExecutor.QUERY_SUPPRESS_BEGIN) == 0
|| getTransactionState() == TransactionState.OPEN)
&& query != restoreToAutoSave
&& getAutoSave() != AutoSave.NEVER
// If query has no resulting fields, it cannot fail with 'cached plan must not change result type'
// thus no need to set a safepoint before such query
&& (getAutoSave() == AutoSave.ALWAYS
// If CompositeQuery is observed, just assume it might fail and set the savepoint
|| !(query instanceof SimpleQuery)
|| ((SimpleQuery) query).getFields() != null)) {
sendOneQuery(autoSaveQuery, SimpleQuery.NO_PARAMETERS, 1, 0,
QUERY_NO_RESULTS | QUERY_NO_METADATA
// PostgreSQL does not support bind, exec, simple, sync message flow,
// so we force autosavepoint to use simple if the main query is using simple
| QUERY_EXECUTE_AS_SIMPLE);
return true;
}
return false;
}
private void rollbackIfRequired(boolean autosave, SQLException e) throws SQLException {
if (autosave
&& getTransactionState() == TransactionState.FAILED
&& (getAutoSave() == AutoSave.ALWAYS || willHealOnRetry(e))) {
try {
// ROLLBACK and AUTOSAVE are executed as simple always to overcome "statement no longer exists S_xx"
execute(restoreToAutoSave, SimpleQuery.NO_PARAMETERS, new ResultHandlerDelegate(null),
1, 0, QUERY_NO_RESULTS | QUERY_NO_METADATA | QUERY_EXECUTE_AS_SIMPLE);
} catch (SQLException e2) {
// That's O(N), sorry
e.setNextException(e2);
}
}
throw e;
}
// Deadlock avoidance:
//
// It's possible for the send and receive streams to get "deadlocked" against each other since
// we do not have a separate thread. The scenario is this: we have two streams:
//
// driver -> TCP buffering -> server
// server -> TCP buffering -> driver
//
// The server behaviour is roughly:
// while true:
// read message
// execute message
// write results
//
// If the server -> driver stream has a full buffer, the write will block.
// If the driver is still writing when this happens, and the driver -> server
// stream also fills up, we deadlock: the driver is blocked on write() waiting
// for the server to read some more data, and the server is blocked on write()
// waiting for the driver to read some more data.
//
// To avoid this, we guess at how much response data we can request from the
// server before the server -> driver stream's buffer is full (MAX_BUFFERED_RECV_BYTES).
// This is the point where the server blocks on write and stops reading data. If we
// reach this point, we force a Sync message and read pending data from the server
// until ReadyForQuery, then go back to writing more queries unless we saw an error.
//
// This is not 100% reliable -- it's only done in the batch-query case and only
// at a reasonably high level (per query, not per message), and it's only an estimate
// -- so it might break. To do it correctly in all cases would seem to require a
// separate send or receive thread as we can only do the Sync-and-read-results
// operation at particular points, and also as we don't really know how much data
// the server is sending.
//
// Our message size estimation is coarse, and disregards asynchronous
// notifications, warnings/info/debug messages, etc, so the response size may be
// quite different from the 250 bytes assumed here even for queries that don't
// return data.
//
// See github issue #194 and #195 .
//
// Assume 64k server->client buffering, which is extremely conservative. A typical
// system will have 200kb or more of buffers for its receive buffers, and the sending
// system will typically have the same on the send side, giving us 400kb or to work
// with. (We could check Java's receive buffer size, but prefer to assume a very
// conservative buffer instead, and we don't know how big the server's send
// buffer is.)
//
private static final int MAX_BUFFERED_RECV_BYTES = 64000;
private static final int NODATA_QUERY_RESPONSE_SIZE_BYTES = 250;
public synchronized void execute(Query[] queries, ParameterList[] parameterLists,
BatchResultHandler batchHandler, int maxRows, int fetchSize, int flags) throws SQLException {
waitOnLock();
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.log(Level.FINEST, " batch execute {0} queries, handler={1}, maxRows={2}, fetchSize={3}, flags={4}",
new Object[]{queries.length, batchHandler, maxRows, fetchSize, flags});
}
flags = updateQueryMode(flags);
boolean describeOnly = (QUERY_DESCRIBE_ONLY & flags) != 0;
// Check parameters and resolve OIDs.
if (!describeOnly) {
for (ParameterList parameterList : parameterLists) {
if (parameterList != null) {
((V3ParameterList) parameterList).checkAllParametersSet();
}
}
}
boolean autosave = false;
ResultHandler handler = batchHandler;
try {
handler = sendQueryPreamble(batchHandler, flags);
autosave = sendAutomaticSavepoint(queries[0], flags);
estimatedReceiveBufferBytes = 0;
for (int i = 0; i < queries.length; ++i) {
Query query = queries[i];
V3ParameterList parameters = (V3ParameterList) parameterLists[i];
if (parameters == null) {
parameters = SimpleQuery.NO_PARAMETERS;
}
sendQuery(query, parameters, maxRows, fetchSize, flags, handler, batchHandler);
if (handler.getException() != null) {
break;
}
}
if (handler.getException() == null) {
if ((flags & QueryExecutor.QUERY_EXECUTE_AS_SIMPLE) != 0) {
// Sync message is not required for 'Q' execution as 'Q' ends with ReadyForQuery message
// on its own
} else {
sendSync();
}
processResults(handler, flags);
estimatedReceiveBufferBytes = 0;
}
} catch (IOException e) {
abort();
handler.handleError(
new PSQLException(GT.tr("An I/O error occurred while sending to the backend."),
PSQLState.CONNECTION_FAILURE, e));
}
try {
handler.handleCompletion();
} catch (SQLException e) {
rollbackIfRequired(autosave, e);
}
}
private ResultHandler sendQueryPreamble(final ResultHandler delegateHandler, int flags)
throws IOException {
// First, send CloseStatements for finalized SimpleQueries that had statement names assigned.
processDeadParsedQueries();
processDeadPortals();
// Send BEGIN on first statement in transaction.
if ((flags & QueryExecutor.QUERY_SUPPRESS_BEGIN) != 0
|| getTransactionState() != TransactionState.IDLE) {
return delegateHandler;
}
int beginFlags = QueryExecutor.QUERY_NO_METADATA;
if ((flags & QueryExecutor.QUERY_ONESHOT) != 0) {
beginFlags |= QueryExecutor.QUERY_ONESHOT;
}
beginFlags |= QueryExecutor.QUERY_EXECUTE_AS_SIMPLE;
beginFlags = updateQueryMode(beginFlags);
sendOneQuery(beginTransactionQuery, SimpleQuery.NO_PARAMETERS, 0, 0, beginFlags);
// Insert a handler that intercepts the BEGIN.
return new ResultHandlerDelegate(delegateHandler) {
private boolean sawBegin = false;
public void handleResultRows(Query fromQuery, Field[] fields, List<byte[][]> tuples,
ResultCursor cursor) {
if (sawBegin) {
super.handleResultRows(fromQuery, fields, tuples, cursor);
}
}
public void handleCommandStatus(String status, int updateCount, long insertOID) {
if (!sawBegin) {
sawBegin = true;
if (!status.equals("BEGIN")) {
handleError(new PSQLException(GT.tr("Expected command status BEGIN, got {0}.", status),
PSQLState.PROTOCOL_VIOLATION));
}
} else {
super.handleCommandStatus(status, updateCount, insertOID);
}
}
};
}
//
// Fastpath
//
public synchronized byte[] fastpathCall(int fnid, ParameterList parameters, boolean suppressBegin)
throws SQLException {
waitOnLock();
if (!suppressBegin) {
doSubprotocolBegin();
}
try {
sendFastpathCall(fnid, (SimpleParameterList) parameters);
return receiveFastpathResult();
} catch (IOException ioe) {
abort();
throw new PSQLException(GT.tr("An I/O error occurred while sending to the backend."),
PSQLState.CONNECTION_FAILURE, ioe);
}
}
public void doSubprotocolBegin() throws SQLException {
if (getTransactionState() == TransactionState.IDLE) {
LOGGER.log(Level.FINEST, "Issuing BEGIN before fastpath or copy call.");
ResultHandler handler = new ResultHandlerBase() {
private boolean sawBegin = false;
public void handleCommandStatus(String status, int updateCount, long insertOID) {
if (!sawBegin) {
if (!status.equals("BEGIN")) {
handleError(
new PSQLException(GT.tr("Expected command status BEGIN, got {0}.", status),
PSQLState.PROTOCOL_VIOLATION));
}
sawBegin = true;
} else {
handleError(new PSQLException(GT.tr("Unexpected command status: {0}.", status),
PSQLState.PROTOCOL_VIOLATION));
}
}
public void handleWarning(SQLWarning warning) {
// we don't want to ignore warnings and it would be tricky
// to chain them back to the connection, so since we don't
// expect to get them in the first place, we just consider
// them errors.
handleError(warning);
}
};
try {
sendOneQuery(beginTransactionQuery, SimpleQuery.NO_PARAMETERS, 0, 0,
QueryExecutor.QUERY_NO_METADATA);
sendSync();
processResults(handler, 0);
estimatedReceiveBufferBytes = 0;
} catch (IOException ioe) {
throw new PSQLException(GT.tr("An I/O error occurred while sending to the backend."),
PSQLState.CONNECTION_FAILURE, ioe);
}
}
}
public ParameterList createFastpathParameters(int count) {
return new SimpleParameterList(count, this);
}
private void sendFastpathCall(int fnid, SimpleParameterList params)
throws SQLException, IOException {
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.log(Level.FINEST, " FE=> FunctionCall({0}, {1} params)", new Object[]{fnid, params.getParameterCount()});
}
//
// Total size = 4 (length)
// + 4 (function OID)
// + 2 (format code count) + N * 2 (format codes)
// + 2 (parameter count) + encodedSize (parameters)
// + 2 (result format)
int paramCount = params.getParameterCount();
int encodedSize = 0;
for (int i = 1; i <= paramCount; ++i) {
if (params.isNull(i)) {
encodedSize += 4;
} else {
encodedSize += 4 + params.getV3Length(i);
}
}
pgStream.sendChar('F');
pgStream.sendInteger4(4 + 4 + 2 + 2 * paramCount + 2 + encodedSize + 2);
pgStream.sendInteger4(fnid);
pgStream.sendInteger2(paramCount);
for (int i = 1; i <= paramCount; ++i) {
pgStream.sendInteger2(params.isBinary(i) ? 1 : 0);
}
pgStream.sendInteger2(paramCount);
for (int i = 1; i <= paramCount; i++) {
if (params.isNull(i)) {
pgStream.sendInteger4(-1);
} else {
pgStream.sendInteger4(params.getV3Length(i)); // Parameter size
params.writeV3Value(i, pgStream);
}
}
pgStream.sendInteger2(1); // Binary result format
pgStream.flush();
}
// Just for API compatibility with previous versions.
public synchronized void processNotifies() throws SQLException {
processNotifies(-1);
}
/**
* @param timeoutMillis when > 0, block for this time
* when =0, block forever
* when < 0, don't block
*/
public synchronized void processNotifies(int timeoutMillis) throws SQLException {
waitOnLock();
// Asynchronous notifies only arrive when we are not in a transaction
if (getTransactionState() != TransactionState.IDLE) {
return;
}
if (hasNotifications()) {
// No need to timeout when there are already notifications. We just check for more in this case.
timeoutMillis = -1;
}
boolean useTimeout = timeoutMillis > 0;
long startTime = 0;
int oldTimeout = 0;
if (useTimeout) {
startTime = System.currentTimeMillis();
try {
oldTimeout = pgStream.getSocket().getSoTimeout();
} catch (SocketException e) {
throw new PSQLException(GT.tr("An error occurred while trying to get the socket "
+ "timeout."), PSQLState.CONNECTION_FAILURE, e);
}
}
try {
while (timeoutMillis >= 0 || pgStream.hasMessagePending()) {
if (useTimeout && timeoutMillis >= 0) {
setSocketTimeout(timeoutMillis);
}
int c = pgStream.receiveChar();
if (useTimeout && timeoutMillis >= 0) {
setSocketTimeout(0); // Don't timeout after first char
}
switch (c) {
case 'A': // Asynchronous Notify
receiveAsyncNotify();
timeoutMillis = -1;
continue;
case 'E':
// Error Response (response to pretty much everything; backend then skips until Sync)
throw receiveErrorResponse();
case 'N': // Notice Response (warnings / info)
SQLWarning warning = receiveNoticeResponse();
addWarning(warning);
if (useTimeout) {
long newTimeMillis = System.currentTimeMillis();
timeoutMillis += startTime - newTimeMillis; // Overflows after 49 days, ignore that
startTime = newTimeMillis;
if (timeoutMillis == 0) {
timeoutMillis = -1; // Don't accidentially wait forever
}
}
break;
default:
throw new PSQLException(GT.tr("Unknown Response Type {0}.", (char) c),
PSQLState.CONNECTION_FAILURE);
}
}
} catch (SocketTimeoutException ioe) {
// No notifications this time...
} catch (IOException ioe) {
throw new PSQLException(GT.tr("An I/O error occurred while sending to the backend."),
PSQLState.CONNECTION_FAILURE, ioe);
} finally {
if (useTimeout) {
setSocketTimeout(oldTimeout);
}
}
}
private void setSocketTimeout(int millis) throws PSQLException {
try {
Socket s = pgStream.getSocket();
if (!s.isClosed()) { // Is this check required?
pgStream.getSocket().setSoTimeout(millis);
}
} catch (SocketException e) {
throw new PSQLException(GT.tr("An error occurred while trying to reset the socket timeout."),
PSQLState.CONNECTION_FAILURE, e);
}
}
private byte[] receiveFastpathResult() throws IOException, SQLException {
boolean endQuery = false;
SQLException error = null;
byte[] returnValue = null;
while (!endQuery) {
int c = pgStream.receiveChar();
switch (c) {
case 'A': // Asynchronous Notify
receiveAsyncNotify();
break;
case 'E':
// Error Response (response to pretty much everything; backend then skips until Sync)
SQLException newError = receiveErrorResponse();
if (error == null) {
error = newError;
} else {
error.setNextException(newError);
}
// keep processing
break;
case 'N': // Notice Response (warnings / info)
SQLWarning warning = receiveNoticeResponse();
addWarning(warning);
break;
case 'Z': // Ready For Query (eventual response to Sync)
receiveRFQ();
endQuery = true;
break;
case 'V': // FunctionCallResponse
int msgLen = pgStream.receiveInteger4();
int valueLen = pgStream.receiveInteger4();
LOGGER.log(Level.FINEST, " <=BE FunctionCallResponse({0} bytes)", valueLen);
if (valueLen != -1) {
byte[] buf = new byte[valueLen];
pgStream.receive(buf, 0, valueLen);
returnValue = buf;
}
break;
default:
throw new PSQLException(GT.tr("Unknown Response Type {0}.", (char) c),
PSQLState.CONNECTION_FAILURE);
}
}
// did we get an error during this query?
if (error != null) {
throw error;
}
return returnValue;
}
//
// Copy subprotocol implementation
//
/**
* Sends given query to BE to start, initialize and lock connection for a CopyOperation.
*
* @param sql COPY FROM STDIN / COPY TO STDOUT statement
* @return CopyIn or CopyOut operation object
* @throws SQLException on failure
*/
public synchronized CopyOperation startCopy(String sql, boolean suppressBegin)
throws SQLException {
waitOnLock();
if (!suppressBegin) {
doSubprotocolBegin();
}
byte[] buf = Utils.encodeUTF8(sql);
try {
LOGGER.log(Level.FINEST, " FE=> Query(CopyStart)");
pgStream.sendChar('Q');
pgStream.sendInteger4(buf.length + 4 + 1);
pgStream.send(buf);
pgStream.sendChar(0);
pgStream.flush();
return processCopyResults(null, true);
// expect a CopyInResponse or CopyOutResponse to our query above
} catch (IOException ioe) {
throw new PSQLException(GT.tr("Database connection failed when starting copy"),
PSQLState.CONNECTION_FAILURE, ioe);
}
}
/**
* Locks connection and calls initializer for a new CopyOperation Called via startCopy ->
* processCopyResults.
*
* @param op an uninitialized CopyOperation
* @throws SQLException on locking failure
* @throws IOException on database connection failure
*/
private synchronized void initCopy(CopyOperationImpl op) throws SQLException, IOException {
pgStream.receiveInteger4(); // length not used
int rowFormat = pgStream.receiveChar();
int numFields = pgStream.receiveInteger2();
int[] fieldFormats = new int[numFields];
for (int i = 0; i < numFields; i++) {
fieldFormats[i] = pgStream.receiveInteger2();
}
lock(op);
op.init(this, rowFormat, fieldFormats);
}
/**
* Finishes a copy operation and unlocks connection discarding any exchanged data.
*
* @param op the copy operation presumably currently holding lock on this connection
* @throws SQLException on any additional failure
*/
public void cancelCopy(CopyOperationImpl op) throws SQLException {
if (!hasLock(op)) {
throw new PSQLException(GT.tr("Tried to cancel an inactive copy operation"),
PSQLState.OBJECT_NOT_IN_STATE);
}
SQLException error = null;
int errors = 0;
try {
if (op instanceof CopyIn) {
synchronized (this) {
LOGGER.log(Level.FINEST, "FE => CopyFail");
final byte[] msg = Utils.encodeUTF8("Copy cancel requested");
pgStream.sendChar('f'); // CopyFail
pgStream.sendInteger4(5 + msg.length);
pgStream.send(msg);
pgStream.sendChar(0);
pgStream.flush();
do {
try {
processCopyResults(op, true); // discard rest of input
} catch (SQLException se) { // expected error response to failing copy
errors++;
if (error != null) {
SQLException e = se;
SQLException next;
while ((next = e.getNextException()) != null) {
e = next;
}
e.setNextException(error);
}
error = se;
}
} while (hasLock(op));
}
} else if (op instanceof CopyOut) {
sendQueryCancel();
}
} catch (IOException ioe) {
throw new PSQLException(GT.tr("Database connection failed when canceling copy operation"),
PSQLState.CONNECTION_FAILURE, ioe);
} finally {
// Need to ensure the lock isn't held anymore, or else
// future operations, rather than failing due to the
// broken connection, will simply hang waiting for this
// lock.
synchronized (this) {
if (hasLock(op)) {
unlock(op);
}
}
}
if (op instanceof CopyIn) {
if (errors < 1) {
throw new PSQLException(GT.tr("Missing expected error response to copy cancel request"),
PSQLState.COMMUNICATION_ERROR);
} else if (errors > 1) {
throw new PSQLException(
GT.tr("Got {0} error responses to single copy cancel request", String.valueOf(errors)),
PSQLState.COMMUNICATION_ERROR, error);
}
}
}
/**
* Finishes writing to copy and unlocks connection.
*
* @param op the copy operation presumably currently holding lock on this connection
* @return number of rows updated for server versions 8.2 or newer
* @throws SQLException on failure
*/
public synchronized long endCopy(CopyOperationImpl op) throws SQLException {
if (!hasLock(op)) {
throw new PSQLException(GT.tr("Tried to end inactive copy"), PSQLState.OBJECT_NOT_IN_STATE);
}
try {
LOGGER.log(Level.FINEST, " FE=> CopyDone");
pgStream.sendChar('c'); // CopyDone
pgStream.sendInteger4(4);
pgStream.flush();
do {
processCopyResults(op, true);
} while (hasLock(op));
return op.getHandledRowCount();
} catch (IOException ioe) {
throw new PSQLException(GT.tr("Database connection failed when ending copy"),
PSQLState.CONNECTION_FAILURE, ioe);
}
}
/**
* Sends data during a live COPY IN operation. Only unlocks the connection if server suddenly
* returns CommandComplete, which should not happen
*
* @param op the CopyIn operation presumably currently holding lock on this connection
* @param data bytes to send
* @param off index of first byte to send (usually 0)
* @param siz number of bytes to send (usually data.length)
* @throws SQLException on failure
*/
public synchronized void writeToCopy(CopyOperationImpl op, byte[] data, int off, int siz)
throws SQLException {
if (!hasLock(op)) {
throw new PSQLException(GT.tr("Tried to write to an inactive copy operation"),
PSQLState.OBJECT_NOT_IN_STATE);
}
LOGGER.log(Level.FINEST, " FE=> CopyData({0})", siz);
try {
pgStream.sendChar('d');
pgStream.sendInteger4(siz + 4);
pgStream.send(data, off, siz);
processCopyResults(op, false); // collect any pending notifications without blocking
} catch (IOException ioe) {
throw new PSQLException(GT.tr("Database connection failed when writing to copy"),