forked from psycopg/psycopg2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpqpath.c
1834 lines (1516 loc) · 52.3 KB
/
pqpath.c
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
/* pqpath.c - single path into libpq
*
* Copyright (C) 2003-2019 Federico Di Gregorio <fog@debian.org>
* Copyright (C) 2020-2021 The Psycopg Team
*
* This file is part of psycopg.
*
* psycopg2 is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* In addition, as a special exception, the copyright holders give
* permission to link this program with the OpenSSL library (or with
* modified versions of OpenSSL that use the same license as OpenSSL),
* and distribute linked combinations including the two.
*
* You must obey the GNU Lesser General Public License in all respects for
* all of the code used other than OpenSSL.
*
* psycopg2 is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*/
/* IMPORTANT NOTE: no function in this file do its own connection locking
except for pg_execute and pq_fetch (that are somehow high-level). This means
that all the other functions should be called while holding a lock to the
connection.
*/
#define PSYCOPG_MODULE
#include "psycopg/psycopg.h"
#include "psycopg/pqpath.h"
#include "psycopg/connection.h"
#include "psycopg/cursor.h"
#include "psycopg/replication_cursor.h"
#include "psycopg/replication_message.h"
#include "psycopg/green.h"
#include "psycopg/typecast.h"
#include "psycopg/pgtypes.h"
#include "psycopg/error.h"
#include "psycopg/column.h"
#include "psycopg/libpq_support.h"
#include "libpq-fe.h"
#ifdef _WIN32
/* select() */
#include <winsock2.h>
/* gettimeofday() */
#include "win32_support.h"
#elif defined(__sun) && defined(__SVR4)
#include "solaris_support.h"
#elif defined(_AIX)
#include "aix_support.h"
#else
#include <sys/time.h>
#endif
extern HIDDEN PyObject *psyco_DescriptionType;
extern HIDDEN const char *srv_isolevels[];
extern HIDDEN const char *srv_readonly[];
extern HIDDEN const char *srv_deferrable[];
/* Strip off the severity from a Postgres error message. */
static const char *
strip_severity(const char *msg)
{
if (!msg)
return NULL;
if (strlen(msg) > 8 && (!strncmp(msg, "ERROR: ", 8) ||
!strncmp(msg, "FATAL: ", 8) ||
!strncmp(msg, "PANIC: ", 8)))
return &msg[8];
else
return msg;
}
/* pq_raise - raise a python exception of the right kind
This function should be called while holding the GIL.
The function passes the ownership of the pgres to the returned exception,
where the pgres was the explicit argument or taken from the cursor.
So, after calling it curs->pgres will be set to null */
RAISES static void
pq_raise(connectionObject *conn, cursorObject *curs, PGresult **pgres)
{
PyObject *exc = NULL;
const char *err = NULL;
const char *err2 = NULL;
const char *code = NULL;
PyObject *pyerr = NULL;
PyObject *pgerror = NULL, *pgcode = NULL;
if (conn == NULL) {
PyErr_SetString(DatabaseError,
"psycopg went psychotic and raised a null error");
return;
}
/* if the connection has somehow been broken, we mark the connection
object as closed but requiring cleanup */
if (conn->pgconn != NULL && PQstatus(conn->pgconn) == CONNECTION_BAD) {
conn->closed = 2;
exc = OperationalError;
}
if (pgres == NULL && curs != NULL)
pgres = &curs->pgres;
if (pgres && *pgres) {
err = PQresultErrorMessage(*pgres);
if (err != NULL) {
Dprintf("pq_raise: PQresultErrorMessage: err=%s", err);
code = PQresultErrorField(*pgres, PG_DIAG_SQLSTATE);
}
}
if (err == NULL) {
err = PQerrorMessage(conn->pgconn);
Dprintf("pq_raise: PQerrorMessage: err=%s", err);
}
/* if the is no error message we probably called pq_raise without reason:
we need to set an exception anyway because the caller will probably
raise and a meaningful message is better than an empty one.
Note: it can happen without it being our error: see ticket #82 */
if (err == NULL || err[0] == '\0') {
PyErr_Format(DatabaseError,
"error with status %s and no message from the libpq",
PQresStatus(pgres == NULL ?
PQstatus(conn->pgconn) : PQresultStatus(*pgres)));
return;
}
/* Analyze the message and try to deduce the right exception kind
(only if we got the SQLSTATE from the pgres, obviously) */
if (code != NULL) {
exc = exception_from_sqlstate(code);
}
else if (exc == NULL) {
/* Fallback if there is no exception code (unless we already
determined that the connection was closed). */
exc = DatabaseError;
}
/* try to remove the initial "ERROR: " part from the postgresql error */
err2 = strip_severity(err);
Dprintf("pq_raise: err2=%s", err2);
/* decode now the details of the error, because after psyco_set_error
* decoding will fail.
*/
if (!(pgerror = conn_text_from_chars(conn, err))) {
/* we can't really handle an exception while handling this error
* so just print it. */
PyErr_Print();
PyErr_Clear();
}
if (!(pgcode = conn_text_from_chars(conn, code))) {
PyErr_Print();
PyErr_Clear();
}
pyerr = psyco_set_error(exc, curs, err2);
if (pyerr && PyObject_TypeCheck(pyerr, &errorType)) {
errorObject *perr = (errorObject *)pyerr;
Py_CLEAR(perr->pydecoder);
Py_XINCREF(conn->pydecoder);
perr->pydecoder = conn->pydecoder;
Py_CLEAR(perr->pgerror);
perr->pgerror = pgerror;
pgerror = NULL;
Py_CLEAR(perr->pgcode);
perr->pgcode = pgcode;
pgcode = NULL;
CLEARPGRES(perr->pgres);
if (pgres && *pgres) {
perr->pgres = *pgres;
*pgres = NULL;
}
}
Py_XDECREF(pgerror);
Py_XDECREF(pgcode);
}
/* pq_clear_async - clear the effects of a previous async query
note that this function does block because it needs to wait for the full
result sets of the previous query to clear them.
this function does not call any Py_*_ALLOW_THREADS macros */
void
pq_clear_async(connectionObject *conn)
{
PGresult *pgres;
/* this will get all pending results (if the submitted query consisted of
many parts, i.e. "select 1; select 2", there will be many) and also
finalize asynchronous processing so the connection will be ready to
accept another query */
while ((pgres = PQgetResult(conn->pgconn))) {
Dprintf("pq_clear_async: clearing PGresult at %p", pgres);
PQclear(pgres);
}
Py_CLEAR(conn->async_cursor);
}
/* pq_set_non_blocking - set the nonblocking status on a connection.
Accepted arg values are 1 (nonblocking) and 0 (blocking).
Return 0 if everything ok, else < 0 and set an exception.
*/
RAISES_NEG int
pq_set_non_blocking(connectionObject *conn, int arg)
{
int ret = PQsetnonblocking(conn->pgconn, arg);
if (0 != ret) {
Dprintf("PQsetnonblocking(%d) FAILED", arg);
PyErr_SetString(OperationalError, "PQsetnonblocking() failed");
ret = -1;
}
return ret;
}
/* pg_execute_command_locked - execute a no-result query on a locked connection.
This function should only be called on a locked connection without
holding the global interpreter lock.
On error, -1 is returned, and the conn->pgres will hold the
relevant result structure.
The tstate parameter should be the pointer of the _save variable created by
Py_BEGIN_ALLOW_THREADS: this enables the function to acquire and release
again the GIL if needed, i.e. if a Python wait callback must be invoked.
*/
int
pq_execute_command_locked(
connectionObject *conn, const char *query, PyThreadState **tstate)
{
int pgstatus, retvalue = -1;
Dprintf("pq_execute_command_locked: pgconn = %p, query = %s",
conn->pgconn, query);
if (!psyco_green()) {
conn_set_result(conn, PQexec(conn->pgconn, query));
} else {
PyEval_RestoreThread(*tstate);
conn_set_result(conn, psyco_exec_green(conn, query));
*tstate = PyEval_SaveThread();
}
if (conn->pgres == NULL) {
Dprintf("pq_execute_command_locked: PQexec returned NULL");
PyEval_RestoreThread(*tstate);
if (!PyErr_Occurred()) {
conn_set_error(conn, PQerrorMessage(conn->pgconn));
}
*tstate = PyEval_SaveThread();
goto cleanup;
}
pgstatus = PQresultStatus(conn->pgres);
if (pgstatus != PGRES_COMMAND_OK ) {
Dprintf("pq_execute_command_locked: result was not COMMAND_OK (%d)",
pgstatus);
goto cleanup;
}
retvalue = 0;
CLEARPGRES(conn->pgres);
cleanup:
return retvalue;
}
/* pq_complete_error: handle an error from pq_execute_command_locked()
If pq_execute_command_locked() returns -1, this function should be
called to convert the result to a Python exception.
This function should be called while holding the global interpreter
lock.
*/
RAISES void
pq_complete_error(connectionObject *conn)
{
Dprintf("pq_complete_error: pgconn = %p, error = %s",
conn->pgconn, conn->error);
if (conn->pgres) {
pq_raise(conn, NULL, &conn->pgres);
/* now conn->pgres is null */
}
else {
if (conn->error) {
PyErr_SetString(OperationalError, conn->error);
} else if (PyErr_Occurred()) {
/* There was a Python error (e.g. in the callback). Don't clobber
* it with an unknown exception. (see #410) */
Dprintf("pq_complete_error: forwarding Python exception");
} else {
PyErr_SetString(OperationalError, "unknown error");
}
/* Trivia: with a broken socket connection PQexec returns NULL, so we
* end up here. With a TCP connection we get a pgres with an error
* instead, and the connection gets closed in the pq_raise call above
* (see ticket #196)
*/
if (CONNECTION_BAD == PQstatus(conn->pgconn)) {
conn->closed = 2;
}
}
conn_set_error(conn, NULL);
}
/* pq_begin_locked - begin a transaction, if necessary
This function should only be called on a locked connection without
holding the global interpreter lock.
On error, -1 is returned, and the conn->pgres argument will hold the
relevant result structure.
*/
int
pq_begin_locked(connectionObject *conn, PyThreadState **tstate)
{
const size_t bufsize = 256;
char buf[256]; /* buf size must be same as bufsize */
int result;
Dprintf("pq_begin_locked: pgconn = %p, %d, status = %d",
conn->pgconn, conn->autocommit, conn->status);
if (conn->status != CONN_STATUS_READY) {
Dprintf("pq_begin_locked: transaction in progress");
return 0;
}
if (conn->autocommit && !conn->entered) {
Dprintf("pq_begin_locked: autocommit and no with block");
return 0;
}
if (conn->isolevel == ISOLATION_LEVEL_DEFAULT
&& conn->readonly == STATE_DEFAULT
&& conn->deferrable == STATE_DEFAULT) {
strcpy(buf, "BEGIN");
}
else {
snprintf(buf, bufsize,
conn->server_version >= 80000 ?
"BEGIN%s%s%s%s" : "BEGIN;SET TRANSACTION%s%s%s%s",
(conn->isolevel >= 1 && conn->isolevel <= 4)
? " ISOLATION LEVEL " : "",
(conn->isolevel >= 1 && conn->isolevel <= 4)
? srv_isolevels[conn->isolevel] : "",
srv_readonly[conn->readonly],
srv_deferrable[conn->deferrable]);
}
result = pq_execute_command_locked(conn, buf, tstate);
if (result == 0)
conn->status = CONN_STATUS_BEGIN;
return result;
}
/* pq_commit - send an END, if necessary
This function should be called while holding the global interpreter
lock.
*/
int
pq_commit(connectionObject *conn)
{
int retvalue = -1;
Py_BEGIN_ALLOW_THREADS;
pthread_mutex_lock(&conn->lock);
Dprintf("pq_commit: pgconn = %p, status = %d",
conn->pgconn, conn->status);
if (conn->status != CONN_STATUS_BEGIN) {
Dprintf("pq_commit: no transaction to commit");
retvalue = 0;
}
else {
conn->mark += 1;
retvalue = pq_execute_command_locked(conn, "COMMIT", &_save);
}
Py_BLOCK_THREADS;
conn_notice_process(conn);
Py_UNBLOCK_THREADS;
/* Even if an error occurred, the connection will be rolled back,
so we unconditionally set the connection status here. */
conn->status = CONN_STATUS_READY;
pthread_mutex_unlock(&conn->lock);
Py_END_ALLOW_THREADS;
if (retvalue < 0)
pq_complete_error(conn);
return retvalue;
}
RAISES_NEG int
pq_abort_locked(connectionObject *conn, PyThreadState **tstate)
{
int retvalue = -1;
Dprintf("pq_abort_locked: pgconn = %p, status = %d",
conn->pgconn, conn->status);
if (conn->status != CONN_STATUS_BEGIN) {
Dprintf("pq_abort_locked: no transaction to abort");
return 0;
}
conn->mark += 1;
retvalue = pq_execute_command_locked(conn, "ROLLBACK", tstate);
if (retvalue == 0)
conn->status = CONN_STATUS_READY;
return retvalue;
}
/* pq_abort - send an ABORT, if necessary
This function should be called while holding the global interpreter
lock. */
RAISES_NEG int
pq_abort(connectionObject *conn)
{
int retvalue = -1;
Dprintf("pq_abort: pgconn = %p, autocommit = %d, status = %d",
conn->pgconn, conn->autocommit, conn->status);
Py_BEGIN_ALLOW_THREADS;
pthread_mutex_lock(&conn->lock);
retvalue = pq_abort_locked(conn, &_save);
Py_BLOCK_THREADS;
conn_notice_process(conn);
Py_UNBLOCK_THREADS;
pthread_mutex_unlock(&conn->lock);
Py_END_ALLOW_THREADS;
if (retvalue < 0)
pq_complete_error(conn);
return retvalue;
}
/* pq_reset - reset the connection
This function should be called while holding the global interpreter
lock.
The _locked version of this function should be called on a locked
connection without holding the global interpreter lock.
*/
RAISES_NEG int
pq_reset_locked(connectionObject *conn, PyThreadState **tstate)
{
int retvalue = -1;
Dprintf("pq_reset_locked: pgconn = %p, status = %d",
conn->pgconn, conn->status);
conn->mark += 1;
if (conn->status == CONN_STATUS_BEGIN) {
retvalue = pq_execute_command_locked(conn, "ABORT", tstate);
if (retvalue != 0) return retvalue;
}
if (conn->server_version >= 80300) {
retvalue = pq_execute_command_locked(conn, "DISCARD ALL", tstate);
if (retvalue != 0) return retvalue;
}
else {
retvalue = pq_execute_command_locked(conn, "RESET ALL", tstate);
if (retvalue != 0) return retvalue;
retvalue = pq_execute_command_locked(conn,
"SET SESSION AUTHORIZATION DEFAULT", tstate);
if (retvalue != 0) return retvalue;
}
/* should set the tpc xid to null: postponed until we get the GIL again */
conn->status = CONN_STATUS_READY;
return retvalue;
}
int
pq_reset(connectionObject *conn)
{
int retvalue = -1;
Dprintf("pq_reset: pgconn = %p, autocommit = %d, status = %d",
conn->pgconn, conn->autocommit, conn->status);
Py_BEGIN_ALLOW_THREADS;
pthread_mutex_lock(&conn->lock);
retvalue = pq_reset_locked(conn, &_save);
Py_BLOCK_THREADS;
conn_notice_process(conn);
Py_UNBLOCK_THREADS;
pthread_mutex_unlock(&conn->lock);
Py_END_ALLOW_THREADS;
if (retvalue < 0) {
pq_complete_error(conn);
}
else {
Py_CLEAR(conn->tpc_xid);
}
return retvalue;
}
/* Get a session parameter.
*
* The function should be called on a locked connection without
* holding the GIL.
*
* The result is a new string allocated with malloc.
*/
char *
pq_get_guc_locked(connectionObject *conn, const char *param, PyThreadState **tstate)
{
char query[256];
int size;
char *rv = NULL;
Dprintf("pq_get_guc_locked: reading %s", param);
size = PyOS_snprintf(query, sizeof(query), "SHOW %s", param);
if (size < 0 || (size_t)size >= sizeof(query)) {
conn_set_error(conn, "SHOW: query too large");
goto cleanup;
}
Dprintf("pq_get_guc_locked: pgconn = %p, query = %s", conn->pgconn, query);
if (!psyco_green()) {
conn_set_result(conn, PQexec(conn->pgconn, query));
} else {
PyEval_RestoreThread(*tstate);
conn_set_result(conn, psyco_exec_green(conn, query));
*tstate = PyEval_SaveThread();
}
if (!conn->pgres) {
Dprintf("pq_get_guc_locked: PQexec returned NULL");
PyEval_RestoreThread(*tstate);
if (!PyErr_Occurred()) {
conn_set_error(conn, PQerrorMessage(conn->pgconn));
}
*tstate = PyEval_SaveThread();
goto cleanup;
}
if (PQresultStatus(conn->pgres) != PGRES_TUPLES_OK) {
Dprintf("pq_get_guc_locked: result was not TUPLES_OK (%s)",
PQresStatus(PQresultStatus(conn->pgres)));
goto cleanup;
}
rv = strdup(PQgetvalue(conn->pgres, 0, 0));
CLEARPGRES(conn->pgres);
cleanup:
return rv;
}
/* Set a session parameter.
*
* The function should be called on a locked connection without
* holding the GIL
*/
int
pq_set_guc_locked(
connectionObject *conn, const char *param, const char *value,
PyThreadState **tstate)
{
char query[256];
int size;
int rv = -1;
Dprintf("pq_set_guc_locked: setting %s to %s", param, value);
if (0 == strcmp(value, "default")) {
size = PyOS_snprintf(query, sizeof(query),
"SET %s TO DEFAULT", param);
}
else {
size = PyOS_snprintf(query, sizeof(query),
"SET %s TO '%s'", param, value);
}
if (size < 0 || (size_t)size >= sizeof(query)) {
conn_set_error(conn, "SET: query too large");
goto exit;
}
rv = pq_execute_command_locked(conn, query, tstate);
exit:
return rv;
}
/* Call one of the PostgreSQL tpc-related commands.
*
* This function should only be called on a locked connection without
* holding the global interpreter lock. */
int
pq_tpc_command_locked(
connectionObject *conn, const char *cmd, const char *tid,
PyThreadState **tstate)
{
int rv = -1;
char *etid = NULL, *buf = NULL;
Py_ssize_t buflen;
Dprintf("_pq_tpc_command: pgconn = %p, command = %s",
conn->pgconn, cmd);
conn->mark += 1;
PyEval_RestoreThread(*tstate);
/* convert the xid into the postgres transaction_id and quote it. */
if (!(etid = psyco_escape_string(conn, tid, -1, NULL, NULL)))
{ goto exit; }
/* prepare the command to the server */
buflen = 2 + strlen(cmd) + strlen(etid); /* add space, zero */
if (!(buf = PyMem_Malloc(buflen))) {
PyErr_NoMemory();
goto exit;
}
if (0 > PyOS_snprintf(buf, buflen, "%s %s", cmd, etid)) { goto exit; }
/* run the command and let it handle the error cases */
*tstate = PyEval_SaveThread();
rv = pq_execute_command_locked(conn, buf, tstate);
PyEval_RestoreThread(*tstate);
exit:
PyMem_Free(buf);
PyMem_Free(etid);
*tstate = PyEval_SaveThread();
return rv;
}
/* pq_get_result_async - read an available result without blocking.
*
* Return 0 if the result is ready, 1 if it will block, -1 on error.
* The last result will be returned in conn->pgres.
*
* The function should be called with the lock and holding the GIL.
*/
RAISES_NEG int
pq_get_result_async(connectionObject *conn)
{
int rv = -1;
Dprintf("pq_get_result_async: calling PQconsumeInput()");
if (PQconsumeInput(conn->pgconn) == 0) {
Dprintf("pq_get_result_async: PQconsumeInput() failed");
/* if the libpq says pgconn is lost, close the py conn */
if (CONNECTION_BAD == PQstatus(conn->pgconn)) {
conn->closed = 2;
}
PyErr_SetString(OperationalError, PQerrorMessage(conn->pgconn));
goto exit;
}
conn_notifies_process(conn);
conn_notice_process(conn);
for (;;) {
int busy;
PGresult *res;
ExecStatusType status;
Dprintf("pq_get_result_async: calling PQisBusy()");
busy = PQisBusy(conn->pgconn);
if (busy) {
/* try later */
Dprintf("pq_get_result_async: PQisBusy() = 1");
rv = 1;
goto exit;
}
if (!(res = PQgetResult(conn->pgconn))) {
Dprintf("pq_get_result_async: got no result");
/* the result is ready: it was the previously read one */
rv = 0;
goto exit;
}
status = PQresultStatus(res);
Dprintf("pq_get_result_async: got result %s", PQresStatus(status));
/* Store the result outside because we want to return the last non-null
* one and we may have to do it across poll calls. However if there is
* an error in the stream of results we want to handle the *first*
* error. So don't clobber it with the following ones. */
if (conn->pgres && PQresultStatus(conn->pgres) == PGRES_FATAL_ERROR) {
Dprintf("previous pgres is error: discarding");
PQclear(res);
}
else {
conn_set_result(conn, res);
}
switch (status) {
case PGRES_COPY_OUT:
case PGRES_COPY_IN:
case PGRES_COPY_BOTH:
/* After entering copy mode, libpq will make a phony
* PGresult for us every time we query for it, so we need to
* break out of this endless loop. */
rv = 0;
goto exit;
default:
/* keep on reading to check if there are other results or
* we have finished. */
continue;
}
}
exit:
return rv;
}
/* pq_flush - flush output and return connection status
a status of 1 means that a some data is still pending to be flushed, while a
status of 0 means that there is no data waiting to be sent. -1 means an
error and an exception will be set accordingly.
this function locks the connection object
this function call Py_*_ALLOW_THREADS macros */
int
pq_flush(connectionObject *conn)
{
int res;
Dprintf("pq_flush: flushing output");
Py_BEGIN_ALLOW_THREADS;
pthread_mutex_lock(&(conn->lock));
res = PQflush(conn->pgconn);
pthread_mutex_unlock(&(conn->lock));
Py_END_ALLOW_THREADS;
return res;
}
/* pq_execute - execute a query, possibly asynchronously
*
* With no_result an eventual query result is discarded.
* Currently only used to implement cursor.executemany().
*
* This function locks the connection object
* This function call Py_*_ALLOW_THREADS macros
*/
RAISES_NEG int
_pq_execute_sync(cursorObject *curs, const char *query, int no_result, int no_begin)
{
connectionObject *conn = curs->conn;
CLEARPGRES(curs->pgres);
Py_BEGIN_ALLOW_THREADS;
pthread_mutex_lock(&(conn->lock));
if (!no_begin && pq_begin_locked(conn, &_save) < 0) {
pthread_mutex_unlock(&(conn->lock));
Py_BLOCK_THREADS;
pq_complete_error(conn);
return -1;
}
Dprintf("pq_execute: executing SYNC query: pgconn = %p", conn->pgconn);
Dprintf(" %-.200s", query);
if (!psyco_green()) {
conn_set_result(conn, PQexec(conn->pgconn, query));
}
else {
Py_BLOCK_THREADS;
conn_set_result(conn, psyco_exec_green(conn, query));
Py_UNBLOCK_THREADS;
}
/* don't let pgres = NULL go to pq_fetch() */
if (!conn->pgres) {
if (CONNECTION_BAD == PQstatus(conn->pgconn)) {
conn->closed = 2;
}
pthread_mutex_unlock(&(conn->lock));
Py_BLOCK_THREADS;
if (!PyErr_Occurred()) {
PyErr_SetString(OperationalError,
PQerrorMessage(conn->pgconn));
}
return -1;
}
Py_BLOCK_THREADS;
/* assign the result back to the cursor now that we have the GIL */
curs_set_result(curs, conn->pgres);
conn->pgres = NULL;
/* Process notifies here instead of when fetching the tuple as we are
* into the same critical section that received the data. Without this
* care, reading notifies may disrupt other thread communications.
* (as in ticket #55). */
conn_notifies_process(conn);
conn_notice_process(conn);
Py_UNBLOCK_THREADS;
pthread_mutex_unlock(&(conn->lock));
Py_END_ALLOW_THREADS;
/* if the execute was sync, we call pq_fetch() immediately,
to respect the old DBAPI-2.0 compatible behaviour */
Dprintf("pq_execute: entering synchronous DBAPI compatibility mode");
if (pq_fetch(curs, no_result) < 0) return -1;
return 1;
}
RAISES_NEG int
_pq_execute_async(cursorObject *curs, const char *query, int no_result)
{
int async_status = ASYNC_WRITE;
connectionObject *conn = curs->conn;
int ret;
CLEARPGRES(curs->pgres);
Py_BEGIN_ALLOW_THREADS;
pthread_mutex_lock(&(conn->lock));
Dprintf("pq_execute: executing ASYNC query: pgconn = %p", conn->pgconn);
Dprintf(" %-.200s", query);
if (PQsendQuery(conn->pgconn, query) == 0) {
if (CONNECTION_BAD == PQstatus(conn->pgconn)) {
conn->closed = 2;
}
pthread_mutex_unlock(&(conn->lock));
Py_BLOCK_THREADS;
PyErr_SetString(OperationalError,
PQerrorMessage(conn->pgconn));
return -1;
}
Dprintf("pq_execute: async query sent to backend");
ret = PQflush(conn->pgconn);
if (ret == 0) {
/* the query got fully sent to the server */
Dprintf("pq_execute: query got flushed immediately");
/* the async status will be ASYNC_READ */
async_status = ASYNC_READ;
}
else if (ret == 1) {
/* not all of the query got sent to the server */
async_status = ASYNC_WRITE;
}
else {
/* there was an error */
pthread_mutex_unlock(&(conn->lock));
Py_BLOCK_THREADS;
PyErr_SetString(OperationalError,
PQerrorMessage(conn->pgconn));
return -1;
}
pthread_mutex_unlock(&(conn->lock));
Py_END_ALLOW_THREADS;
conn->async_status = async_status;
if (!(conn->async_cursor
= PyWeakref_NewRef((PyObject *)curs, NULL))) {
return -1;
}
return 0;
}
RAISES_NEG int
pq_execute(cursorObject *curs, const char *query, int async, int no_result, int no_begin)
{
/* check status of connection, raise error if not OK */
if (PQstatus(curs->conn->pgconn) != CONNECTION_OK) {
Dprintf("pq_execute: connection NOT OK");
PyErr_SetString(OperationalError, PQerrorMessage(curs->conn->pgconn));
return -1;
}
Dprintf("pq_execute: pg connection at %p OK", curs->conn->pgconn);
if (!async) {
return _pq_execute_sync(curs, query, no_result, no_begin);
} else {
return _pq_execute_async(curs, query, no_result);
}
}
/* send an async query to the backend.
*
* Return 1 if command succeeded, else 0.
*
* The function should be called helding the connection lock and the GIL.
*/
int
pq_send_query(connectionObject *conn, const char *query)
{
int rv;
Dprintf("pq_send_query: sending ASYNC query:");
Dprintf(" %-.200s", query);
CLEARPGRES(conn->pgres);
if (0 == (rv = PQsendQuery(conn->pgconn, query))) {
Dprintf("pq_send_query: error: %s", PQerrorMessage(conn->pgconn));
}
return rv;
}
/* pq_fetch - fetch data after a query
this function locks the connection object
this function call Py_*_ALLOW_THREADS macros
return value:
-1 - some error occurred while calling libpq
0 - no result from the backend but no libpq errors
1 - result from backend (possibly data is ready)
*/
static PyObject *
_get_cast(cursorObject *curs, PGresult *pgres, int i)
{
/* fill the right cast function by accessing three different dictionaries:
- the per-cursor dictionary, if available (can be NULL or None)
- the per-connection dictionary (always exists but can be null)
- the global dictionary (at module level)
if we get no defined cast use the default one */