-
Notifications
You must be signed in to change notification settings - Fork 36
/
dbdimp.c
5783 lines (4829 loc) · 199 KB
/
dbdimp.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
/*
Copyright (c) 2002-2024 Greg Sabino Mullane and others: see the Changes file
Portions Copyright (c) 2002 Jeffrey W. Baker
Portions Copyright (c) 1997-2000 Edmund Mergl
Portions Copyright (c) 1994-1997 Tim Bunce
You may distribute under the terms of either the GNU General Public
License or the Artistic License, as specified in the Perl README file.
*/
#include "Pg.h"
#if defined (_WIN32) && !defined (atoll)
#define atoll(X) _atoi64(X)
#endif
#define DEBUG_LAST_RESULT 0
#if PGLIBVERSION < 80300
Oid lo_truncate (PGconn *conn, int fd, size_t len);
Oid lo_truncate (PGconn *conn, int fd, size_t len) {
croak ("Cannot use lo_truncate unless compiled against Postgres 8.3 or later");
}
#endif
#if PGLIBVERSION < 80400
Oid lo_import_with_oid (PGconn *conn, char *filename, unsigned int lobjId);
Oid lo_import_with_oid (PGconn *conn, char *filename, unsigned int lobjId) {
croak ("Cannot use lo_import_with_oid unless compiled against Postgres 8.4 or later");
}
#endif
#ifndef PG_DIAG_SCHEMA_NAME
#define PG_DIAG_SCHEMA_NAME 's'
#define PG_DIAG_TABLE_NAME 't'
#define PG_DIAG_COLUMN_NAME 'c'
#define PG_DIAG_DATATYPE_NAME 'd'
#define PG_DIAG_CONSTRAINT_NAME 'n'
#endif
#ifndef PG_DIAG_SEVERITY_NONLOCALIZED
#define PG_DIAG_SEVERITY_NONLOCALIZED 'V'
#endif
#ifndef PGErrorVerbosity
typedef enum
{
PGERROR_TERSE, /* single-line error messages */
PGERROR_DEFAULT, /* recommended style */
PGERROR_VERBOSE /* all the facts, ma'am */
} PGErrorVerbosity;
#endif
typedef enum
{
PQTYPE_UNKNOWN,
PQTYPE_EXEC,
PQTYPE_PARAMS,
PQTYPE_PREPARED,
} PQExecType;
#define IS_DBI_HANDLE(h) \
(SvROK(h) && SvTYPE(SvRV(h)) == SVt_PVHV && \
SvRMAGICAL(SvRV(h)) && (SvMAGIC(SvRV(h)))->mg_type == 'P')
static void pg_error(pTHX_ SV *h, int error_num, const char *error_msg);
static void pg_warn (void * arg, const char * message);
static ExecStatusType _result(pTHX_ imp_dbh_t *imp_dbh, const char *sql);
static void _fatal_sqlstate(pTHX_ imp_dbh_t *imp_dbh);
static ExecStatusType _sqlstate(pTHX_ imp_dbh_t *imp_dbh, PGresult *result);
static int pg_db_rollback_commit (pTHX_ SV *dbh, imp_dbh_t *imp_dbh, int action);
static SV *pg_st_placeholder_key (imp_sth_t *imp_sth, ph_t *currph, int i);
static void pg_st_split_statement (pTHX_ imp_sth_t *imp_sth, char *statement);
static int pg_st_prepare_statement (pTHX_ SV *sth, imp_sth_t *imp_sth);
static int pg_st_deallocate_statement(pTHX_ SV *sth, imp_sth_t *imp_sth);
static PGTransactionStatusType pg_db_txn_status (pTHX_ imp_dbh_t *imp_dbh);
static int pg_db_start_txn (pTHX_ SV *dbh, imp_dbh_t *imp_dbh);
static int handle_old_async(pTHX_ SV * handle, imp_dbh_t * imp_dbh, const int asyncflag);
static void pg_db_detect_client_encoding_utf8(pTHX_ imp_dbh_t *imp_dbh);
/* ================================================================== */
void dbd_init (dbistate_t *dbistate)
{
dTHX;
DBISTATE_INIT;
}
/* ================================================================== */
int dbd_db_login6 (SV * dbh, imp_dbh_t * imp_dbh, char * dbname, char * uid, char * pwd, SV *attr)
{
dTHR;
dTHX;
char * conn_str;
char * dest;
bool inquote = DBDPG_FALSE;
STRLEN connect_string_size;
ConnStatusType connstatus;
if (TSTART_slow) TRC(DBILOGFP, "%sBegin dbd_db_login\n", THEADER_slow);
/* DBD::Pg syntax: 'dbname=dbname;host=host;port=port', 'User', 'Pass' */
/* libpq syntax: 'dbname=dbname host=host port=port user=uid password=pwd' */
/* Figure out how large our connection string is going to be */
connect_string_size = strlen(dbname);
if (*uid)
connect_string_size += strlen("user='' ") + 2*strlen(uid);
if (*pwd)
connect_string_size += strlen("password='' ") + 2*strlen(pwd);
New(0, conn_str, connect_string_size+1, char); /* freed below */
/* Change all semi-colons in dbname to a space, unless single-quoted */
dest = conn_str;
while (*dbname != '\0') {
if (';' == *dbname && !inquote)
*dest++ = ' ';
else {
if ('\\' == *dbname && *(dbname+1) != '\0')
*dest++ = *dbname++;
else if ('\'' == *dbname)
inquote = !inquote;
*dest++ = *dbname;
}
dbname++;
}
*dest = '\0';
/* Add in the user and/or password if they exist, escaping single quotes and backslashes */
if (*uid) {
strcat(conn_str, " user='");
dest = conn_str;
while(*dest != '\0')
dest++;
while(*uid != '\0') {
if ('\''==*uid || '\\'==*uid)
*(dest++)='\\';
*(dest++)=*(uid++);
}
*dest = '\0';
strcat(conn_str, "'");
}
if (*pwd) {
strcat(conn_str, " password='");
dest = conn_str;
while(*dest != '\0')
dest++;
while(*pwd != '\0') {
if ('\''==*pwd || '\\'==*pwd)
*(dest++)='\\';
*(dest++)=*(pwd++);
}
*dest = '\0';
strcat(conn_str, "'");
}
/* Remove any stored savepoint information */
if (imp_dbh->savepoints) {
av_undef(imp_dbh->savepoints);
sv_free((SV *)imp_dbh->savepoints);
}
imp_dbh->savepoints = newAV(); /* freed in dbd_db_destroy */
/* Close any old connection and free memory, just in case */
if (imp_dbh->conn) {
TRACE_PQFINISH;
PQfinish(imp_dbh->conn);
}
/* Attempt the connection to the database */
if (TLOGIN_slow) TRC(DBILOGFP, "%sLogin connection string: (%s)\n", THEADER_slow, conn_str);
TRACE_PQCONNECTDB;
imp_dbh->conn = PQconnectdb(conn_str);
if (TLOGIN_slow) TRC(DBILOGFP, "%sConnection complete\n", THEADER_slow);
Safefree(conn_str);
/* Set the initial sqlstate */
Renew(imp_dbh->sqlstate, 6, char); /* freed in dbd_db_destroy */
strncpy(imp_dbh->sqlstate, "25P01", 6); /* "NO ACTIVE SQL TRANSACTION" */
/* Check to see that the backend connection was successfully made */
TRACE_PQSTATUS;
connstatus = PQstatus(imp_dbh->conn);
if (CONNECTION_OK != connstatus) {
TRACE_PQERRORMESSAGE;
strncpy(imp_dbh->sqlstate, "08006", 6); /* "CONNECTION FAILURE" */
pg_error(aTHX_ dbh, connstatus, PQerrorMessage(imp_dbh->conn));
TRACE_PQFINISH;
PQfinish(imp_dbh->conn);
sv_free((SV *)imp_dbh->savepoints);
if (TEND_slow) TRC(DBILOGFP, "%sEnd dbd_db_login (error)\n", THEADER_slow);
return 0;
}
/* Call the pg_warn function anytime this connection raises a notice */
TRACE_PQSETNOTICEPROCESSOR;
(void)PQsetNoticeProcessor(imp_dbh->conn, pg_warn, (void *)SvRV(dbh));
/* Figure out what protocol this server is using (most likely 3) */
TRACE_PQPROTOCOLVERSION;
imp_dbh->pg_protocol = PQprotocolVersion(imp_dbh->conn);
/* Figure out this particular backend's version */
TRACE_PQSERVERVERSION;
imp_dbh->pg_server_version = PQserverVersion(imp_dbh->conn);
if (imp_dbh->pg_server_version < 80000) {
/*
Special workaround for PgBouncer, which has the unfortunate habit of modifying 'server_version',
something it should never do. If we think this is the case for the version failure, we
simply allow things to continue with a faked version. See github issue #47
*/
if (NULL != strstr(PQparameterStatus(imp_dbh->conn, "server_version"), "bouncer")) {
imp_dbh->pg_server_version = 90600;
}
else {
TRACE_PQERRORMESSAGE;
strncpy(imp_dbh->sqlstate, "08001", 6); /* sqlclient_unable_to_establish_sqlconnection */
pg_error(aTHX_ dbh, CONNECTION_BAD, "Server version 8.0 required");
TRACE_PQFINISH;
PQfinish(imp_dbh->conn);
sv_free((SV *)imp_dbh->savepoints);
if (TEND_slow) TRC(DBILOGFP, "%sEnd dbd_db_login (error)\n", THEADER_slow);
return 0;
}
}
pg_db_detect_client_encoding_utf8(aTHX_ imp_dbh);
/* If the client_encoding is UTF8, flip the utf8 flag until convinced otherwise */
imp_dbh->pg_utf8_flag = imp_dbh->client_encoding_utf8;
imp_dbh->pg_enable_utf8 = -1;
imp_dbh->prepare_now = DBDPG_FALSE;
imp_dbh->done_begin = DBDPG_FALSE;
imp_dbh->dollaronly = DBDPG_FALSE;
imp_dbh->nocolons = DBDPG_FALSE;
imp_dbh->ph_escaped = DBDPG_TRUE;
imp_dbh->expand_array = DBDPG_TRUE;
imp_dbh->txn_read_only = DBDPG_FALSE;
imp_dbh->pid_number = getpid();
imp_dbh->server_prepare = DBDPG_TRUE;
imp_dbh->prepare_number = 1;
imp_dbh->switch_prepared = 2;
imp_dbh->copystate = 0;
imp_dbh->copybinary = DBDPG_FALSE;
imp_dbh->pg_errorlevel = 1; /* Default */
imp_dbh->async_status = 0;
imp_dbh->async_sth = NULL;
imp_dbh->last_result = NULL; /* NULL or the last PGresult returned by a database or statement handle */
imp_dbh->result_clearable = DBDPG_TRUE;
imp_dbh->pg_int8_as_string = DBDPG_FALSE;
imp_dbh->skip_deallocate = DBDPG_FALSE;
/* Tell DBI that we should call destroy when the handle dies */
DBIc_IMPSET_on(imp_dbh);
/* Tell DBI that we should call disconnect when the handle dies */
DBIc_ACTIVE_on(imp_dbh);
if (TEND_slow) TRC(DBILOGFP, "%sEnd dbd_db_login\n", THEADER_slow);
return 1;
} /* end of dbd_db_login */
/* ================================================================== */
/*
Database specific error handling.
*/
static void pg_error (pTHX_ SV * h, int error_num, const char * error_msg)
{
D_imp_xxh(h);
size_t error_len;
imp_dbh_t * imp_dbh = (imp_dbh_t *)(DBIc_TYPE(imp_xxh) == DBIt_ST ? DBIc_PARENT_COM(imp_xxh) : imp_xxh);
if (TSTART_slow) TRC(DBILOGFP, "%sBegin pg_error (message: %s number: %d)\n",
THEADER_slow, error_msg, error_num);
error_len = strlen(error_msg);
/* Strip final newline so line number appears for warn/die */
if (error_len > 0 && error_msg[error_len-1] == 10)
error_len--;
sv_setiv(DBIc_ERR(imp_xxh), (IV)error_num);
sv_setpv(DBIc_STATE(imp_xxh), (char*)imp_dbh->sqlstate);
/*
We need a special exception for cases in which libpq doesn't know what the error was,
and Postgres returns nothing. Probably client_min_messages is boosted too high.
See CPAN ticket #109591
*/
if (7 == error_num && 0 == error_len) {
sv_setpvn(DBIc_ERRSTR(imp_xxh), "No error returned from Postgres. Perhaps client_min_messages is set too high?", 77);
}
else {
sv_setpvn(DBIc_ERRSTR(imp_xxh), error_msg, error_len);
}
/* Set as utf-8 */
if (imp_dbh->pg_utf8_flag)
SvUTF8_on(DBIc_ERRSTR(imp_xxh));
if (TEND_slow) TRC(DBILOGFP, "%sEnd pg_error\n", THEADER_slow);
} /* end of pg_error */
/* ================================================================== */
/*
Turn database notices into perl warnings for proper handling.
*/
static void pg_warn (void * arg, const char * message)
{
dTHX;
SV *tmp;
tmp = sv_2mortal(newRV_inc((SV *)arg));
/* This fun little bit is to prevent a core dump when the following occurs:
client_min_messages is set to DEBUG3 or greater, and we exit without a disconnect.
DBI issues a 'rollback' in this case, which causes some debugging messages
to be emitted from the server (such as "StartTransactionCommand"). However, we can't do
the D_imp_dbh call anymore, because the underlying dbh has lost some of its magic.
Unfortunately, DBI then coredumps in dbh_getcom2. Hence, we make sure that the
object passed in is still 'valid', in that a certain level has a ROK flag.
If it's not, we just return without issuing any warning, as we can't check things
like DBIc_WARN. There may be a better way of handling all this, and we may want to
default to always warn() - input welcome.
*/
if (!SvROK(SvMAGIC(SvRV(tmp))->mg_obj)) {
return;
}
else {
D_imp_dbh(tmp);
if (TSTART_slow) TRC(DBILOGFP, "%sBegin pg_warn (message: %s DBIc_WARN: %d PrintWarn: %d)\n",
THEADER_slow,
message, DBIc_WARN(imp_dbh) ? 1 : 0,
DBIc_is(imp_dbh, DBIcf_PrintWarn) ? 1 : 0);
if (DBIc_WARN(imp_dbh) && DBIc_is(imp_dbh, DBIcf_PrintWarn))
warn("%s", message);
if (TEND_slow) TRC(DBILOGFP, "%sEnd pg_warn\n", THEADER_slow);
}
} /* end of pg_warn */
/* ================================================================== */
/*
Quick command executor used throughout this file
*/
static ExecStatusType _result(pTHX_ imp_dbh_t * imp_dbh, const char * sql)
{
ExecStatusType status;
if (TSTART_slow) TRC(DBILOGFP, "%sBegin _result (sql: %s)\n", THEADER_slow, sql);
if (TSQL) TRC(DBILOGFP, "%s;\n\n", sql);
/* Free the last_result as needed, as we are about to replace it */
if (imp_dbh->last_result && imp_dbh->result_clearable) {
TRACE_PQCLEAR;
#if DEBUG_LAST_RESULT
fprintf(stderr, "CLEAR last_result of %ld at line %d of %s\n", (long int)imp_dbh->last_result,__LINE__,__func__);
#endif
PQclear(imp_dbh->last_result);
imp_dbh->last_result = NULL;
}
TRACE_PQEXEC;
imp_dbh->last_result = PQexec(imp_dbh->conn, sql);
imp_dbh->result_clearable = DBDPG_TRUE;
status = _sqlstate(aTHX_ imp_dbh, imp_dbh->last_result);
if (TEND_slow) TRC(DBILOGFP, "%sEnd _result\n", THEADER_slow);
return status;
} /* end of _result */
/* ================================================================== */
/* Set the SQLSTATE for a 'fatal' error */
static void _fatal_sqlstate(pTHX_ imp_dbh_t * imp_dbh)
{
char *sqlstate;
sqlstate = PQstatus(imp_dbh->conn) == CONNECTION_BAD ?
"08000" : /* CONNECTION EXCEPTION */
"22000"; /* DATA EXCEPTION */
strncpy(imp_dbh->sqlstate, sqlstate, 6);
}
/* ================================================================== */
/*
Set the SQLSTATE based on a result, returns the status
*/
static ExecStatusType _sqlstate(pTHX_ imp_dbh_t * imp_dbh, PGresult * result)
{
char *sqlstate;
ExecStatusType status = PGRES_FATAL_ERROR; /* until proven otherwise */
if (TSTART_slow) TRC(DBILOGFP, "%sBegin _sqlstate\n", THEADER_slow);
if (result) {
TRACE_PQRESULTSTATUS;
status = PQresultStatus(result);
}
sqlstate = NULL;
/*
Because PQresultErrorField may not work completely when an error occurs, and
we are connecting over TCP/IP, only set it here if non-null, and fall through
to a better default value below.
*/
if (result) {
TRACE_PQRESULTERRORFIELD;
sqlstate = PQresultErrorField(result, PG_DIAG_SQLSTATE);
}
if (!sqlstate) {
/* Do our best to map the status result to a sqlstate code */
switch ((int)status) {
case PGRES_EMPTY_QUERY:
case PGRES_COMMAND_OK:
case PGRES_TUPLES_OK:
case PGRES_COPY_OUT:
case PGRES_COPY_IN:
case PGRES_COPY_BOTH:
sqlstate = "00000"; /* SUCCESSFUL COMPLETION */
break;
case PGRES_BAD_RESPONSE:
case PGRES_NONFATAL_ERROR:
sqlstate = "01000"; /* WARNING */
break;
case PGRES_FATAL_ERROR:
/* libpq returns NULL result in case of connection failures */
if (!result || PQstatus(imp_dbh->conn) == CONNECTION_BAD) {
sqlstate = "08000"; /* CONNECTION EXCEPTION */
break;
}
/*@fallthrough@*/
default:
sqlstate = "22000"; /* DATA EXCEPTION */
break;
}
}
strncpy(imp_dbh->sqlstate, sqlstate, 5);
imp_dbh->sqlstate[5] = 0;
if (TEND_slow) TRC(DBILOGFP, "%sEnd _sqlstate (imp_dbh->sqlstate: %s)\n",
THEADER_slow, imp_dbh->sqlstate);
if (TRACE7_slow) TRC(DBILOGFP, "%s_sqlstate txn_status is %d\n",
THEADER_slow, pg_db_txn_status(aTHX_ imp_dbh));
if (TEND_slow) TRC(DBILOGFP, "%sEnd _sqlstate (status: %d)\n", THEADER_slow, status);
return status;
} /* end of _sqlstate */
/* ================================================================== */
int dbd_db_ping (SV * dbh)
{
dTHX;
D_imp_dbh(dbh);
PGTransactionStatusType tstatus;
ExecStatusType status;
PGresult * result;
if (TSTART_slow) TRC(DBILOGFP, "%sBegin dbd_db_ping\n", THEADER_slow);
if (NULL == imp_dbh->conn) {
if (TEND_slow) TRC(DBILOGFP, "%sEnd dbd_db_ping (error: no connection)\n", THEADER_slow);
return -1;
}
tstatus = pg_db_txn_status(aTHX_ imp_dbh);
if (TRACE5_slow) TRC(DBILOGFP, "%sdbd_db_ping txn_status is %d\n", THEADER_slow, tstatus);
if (tstatus >= PQTRANS_UNKNOWN) { /* Unknown, so we err on the side of "bad" */
if (TEND_slow) TRC(DBILOGFP, "%sEnd dbd_pg_ping (result: -2 unknown/bad)\n", THEADER_slow);
return -2;
}
/* No matter what state we are in, send an empty query to the backend */
result = PQexec(imp_dbh->conn, "/* DBD::Pg ping test v3.18.0 */");
status = PQresultStatus(result);
PQclear(result);
if (PGRES_FATAL_ERROR == status) {
/* Something very bad, usually indicating the backend is gone */
return -3;
}
/* We expect to see an empty query most times */
if (PGRES_EMPTY_QUERY == status) {
if (TEND_slow) TRC(DBILOGFP, "%sEnd dbd_pg_ping (PGRES_EMPTY_QUERY)\n", THEADER_slow);
return 1+tstatus;
/* 0=idle 1=active 2=intrans 3=inerror 4=unknown */
}
/* As a safety measure, check PQstatus as well */
if (CONNECTION_BAD == PQstatus(imp_dbh->conn)) {
if (TEND_slow) TRC(DBILOGFP, "%sEnd dbd_pg_ping (PQstatus returned CONNECTION_BAD)\n", THEADER_slow);
return -4;
}
if (TEND_slow) TRC(DBILOGFP, "%sEnd dbd_pg_ping\n", THEADER_slow);
return 1+tstatus;
} /* end of dbd_db_ping */
/* ================================================================== */
static PGTransactionStatusType pg_db_txn_status (pTHX_ imp_dbh_t * imp_dbh)
{
if (TSTART_slow) TRC(DBILOGFP, "%sBegin PGTransactionStatusType\n", THEADER_slow);
TRACE_PQTRANSACTIONSTATUS;
return PQtransactionStatus(imp_dbh->conn);
} /* end of pg_db_txn_status */
/* rollback and commit share so much code they get one function: */
/* ================================================================== */
static int pg_db_rollback_commit (pTHX_ SV * dbh, imp_dbh_t * imp_dbh, int action)
{
PGTransactionStatusType tstatus;
ExecStatusType status;
if (TSTART_slow) TRC(DBILOGFP, "%sBegin pg_db_rollback_commit (action: %s AutoCommit: %d BegunWork: %d)\n",
THEADER_slow,
action ? "commit" : "rollback",
DBIc_is(imp_dbh, DBIcf_AutoCommit) ? 1 : 0,
DBIc_is(imp_dbh, DBIcf_BegunWork) ? 1 : 0);
/* No action if AutoCommit = on or the connection is invalid */
if ((NULL == imp_dbh->conn) || (DBIc_has(imp_dbh, DBIcf_AutoCommit))) {
if (TEND_slow) TRC(DBILOGFP, "%sEnd pg_db_rollback_commit (result: 0)\n", THEADER_slow);
return 0;
}
/* We only perform these actions if we need to. For newer servers, we
ask it for the status directly and double-check things */
tstatus = pg_db_txn_status(aTHX_ imp_dbh);
if (TRACE4_slow) TRC(DBILOGFP, "%sdbd_db_%s txn_status is %d\n", THEADER_slow, action ? "commit" : "rollback", tstatus);
if (PQTRANS_IDLE == tstatus) { /* Not in a transaction */
if (imp_dbh->done_begin) {
/* We think we ARE in a transaction but we really are not */
if (TRACEWARN_slow)
TRC(DBILOGFP, "%sWarning: invalid done_begin turned off\n", THEADER_slow);
imp_dbh->done_begin = DBDPG_FALSE;
}
}
else if (PQTRANS_ACTIVE == tstatus) { /* Still active - probably in a COPY */
if (TRACEWARN_slow)
TRC(DBILOGFP,"%sCommand in progress, so no done_begin checking!\n", THEADER_slow);
}
else if (PQTRANS_INTRANS == tstatus || PQTRANS_INERROR == tstatus) { /* In a (possibly failed) transaction */
if (!imp_dbh->done_begin) {
/* We think we are NOT in a transaction but we really are */
if (TRACEWARN_slow)
TRC(DBILOGFP, "%sWarning: invalid done_begin turned on\n", THEADER_slow);
imp_dbh->done_begin = DBDPG_TRUE;
}
}
else { /* Something is wrong: transaction status unknown */
if (TRACEWARN_slow)
TRC(DBILOGFP, "%sWarning: cannot determine transaction status\n", THEADER_slow);
}
if (!imp_dbh->done_begin) { /* for example, inside a COPY */
if (TEND_slow) TRC(DBILOGFP, "%sEnd pg_db_rollback_commit (result: 1)\n", THEADER_slow);
return 1;
}
status = _result(aTHX_ imp_dbh, action ? "commit" : "rollback");
/* Set this early, for scripts that continue despite the error below */
imp_dbh->done_begin = DBDPG_FALSE;
if (PGRES_COMMAND_OK != status) {
TRACE_PQERRORMESSAGE;
pg_error(aTHX_ dbh, status, PQerrorMessage(imp_dbh->conn));
if (TEND_slow) TRC(DBILOGFP, "%sEnd pg_db_rollback_commit (error: status not OK)\n", THEADER_slow);
return 0;
}
/* If begin_work has been called, turn AutoCommit back on and BegunWork off */
if (DBIc_has(imp_dbh, DBIcf_BegunWork)!=0) {
DBIc_set(imp_dbh, DBIcf_AutoCommit, 1);
DBIc_set(imp_dbh, DBIcf_BegunWork, 0);
}
/* We just did a rollback or a commit, so savepoints are not relevant, and we cannot be in a PGRES_COPY state */
av_undef(imp_dbh->savepoints);
imp_dbh->copystate=0;
if (TEND_slow) TRC(DBILOGFP, "%sEnd pg_db_rollback_commit (result: 1)\n", THEADER_slow);
return 1;
} /* end of pg_db_rollback_commit */
/* ================================================================== */
int dbd_db_commit (SV * dbh, imp_dbh_t * imp_dbh)
{
dTHX;
if (TSTART_slow) TRC(DBILOGFP, "%sBegin dbd_db_commit\n", THEADER_slow);
return pg_db_rollback_commit(aTHX_ dbh, imp_dbh, 1);
}
/* ================================================================== */
int dbd_db_rollback (SV * dbh, imp_dbh_t * imp_dbh)
{
dTHX;
if (TSTART_slow) TRC(DBILOGFP, "%sBegin dbd_db_rollback\n", THEADER_slow);
return pg_db_rollback_commit(aTHX_ dbh, imp_dbh, 0);
}
/* ================================================================== */
int dbd_db_disconnect (SV * dbh, imp_dbh_t * imp_dbh)
{
dTHX;
if (TSTART_slow) TRC(DBILOGFP, "%sBegin dbd_db_disconnect\n", THEADER_slow);
/* We assume that disconnect will always work
since most errors imply already disconnected. */
DBIc_ACTIVE_off(imp_dbh);
if (NULL != imp_dbh->conn) {
/* Attempt a rollback */
if (0 != dbd_db_rollback(dbh, imp_dbh) && TRACE5_slow)
TRC(DBILOGFP, "%sdbd_db_disconnect: AutoCommit=off -> rollback\n", THEADER_slow);
TRACE_PQFINISH;
PQfinish(imp_dbh->conn);
imp_dbh->conn = NULL;
}
/* We don't free imp_dbh since a reference still exists */
/* The DESTROY method is the only one to 'free' memory. */
/* Note that statement objects may still exists for this dbh! */
if (TLOGIN_slow) TRC(DBILOGFP, "%sDisconnection complete\n", THEADER_slow);
if (TEND_slow) TRC(DBILOGFP, "%sEnd dbd_db_disconnect\n", THEADER_slow);
return 1;
} /* end of dbd_db_disconnect */
/* ================================================================== */
void dbd_db_destroy (SV * dbh, imp_dbh_t * imp_dbh)
{
dTHX;
if (TSTART_slow) TRC(DBILOGFP, "%sBegin dbd_db_destroy\n", THEADER_slow);
imp_dbh->do_tmp_sth = NULL;
if (DBIc_ACTIVE(imp_dbh))
(void)dbd_db_disconnect(dbh, imp_dbh);
if (NULL != imp_dbh->async_sth) { /* Just in case */
if (imp_dbh->async_sth->result) {
TRACE_PQCLEAR;
PQclear(imp_dbh->async_sth->result);
imp_dbh->async_sth->result = NULL;
}
imp_dbh->async_sth = NULL;
}
/* Free the last_result as needed */
if (imp_dbh->last_result && imp_dbh->result_clearable) {
TRACE_PQCLEAR;
#if DEBUG_LAST_RESULT
fprintf(stderr, "CLEAR last_result of %ld at line %d of %s\n", (long int)imp_dbh->last_result,__LINE__,__func__);
#endif
PQclear(imp_dbh->last_result);
imp_dbh->last_result = NULL;
}
av_undef(imp_dbh->savepoints);
sv_free((SV *)imp_dbh->savepoints);
Safefree(imp_dbh->sqlstate);
DBIc_IMPSET_off(imp_dbh);
if (TEND_slow) TRC(DBILOGFP, "%sEnd dbd_db_destroy\n", THEADER_slow);
} /* end of dbd_db_destroy */
/* ================================================================== */
SV * dbd_db_FETCH_attrib (SV * dbh, imp_dbh_t * imp_dbh, SV * keysv)
{
dTHX;
STRLEN kl;
char * key = SvPV(keysv,kl);
SV * retsv = Nullsv;
if (TSTART_slow) TRC(DBILOGFP, "%sBegin dbd_db_FETCH (key: %s)\n", THEADER_slow, dbh ? key : key);
switch (kl) {
case 5: /* pg_db */
if (strEQ("pg_db", key)) {
TRACE_PQDB;
retsv = newSVpv(PQdb(imp_dbh->conn),0);
}
break;
case 6: /* pg_pid */
if (strEQ("pg_pid", key)) {
TRACE_PQBACKENDPID;
retsv = newSViv((IV)PQbackendPID(imp_dbh->conn));
}
break;
case 7: /* pg_user pg_pass pg_port pg_host */
if (strEQ("pg_user", key)) {
TRACE_PQUSER;
retsv = newSVpv(PQuser(imp_dbh->conn),0);
}
else if (strEQ("pg_pass", key)) {
TRACE_PQPASS;
retsv = newSVpv(PQpass(imp_dbh->conn),0);
}
else if (strEQ("pg_port", key)) {
TRACE_PQPORT;
retsv = newSVpv(PQport(imp_dbh->conn),0);
}
else if (strEQ("pg_host", key)) {
TRACE_PQHOST;
retsv = PQhost(imp_dbh->conn) ? newSVpv(PQhost(imp_dbh->conn),0) : Nullsv;
}
break;
case 9: /* pg_socket */
if (strEQ("pg_socket", key)) {
TRACE_PQSOCKET;
retsv = newSViv((IV)PQsocket(imp_dbh->conn));
}
break;
case 10: /* AutoCommit pg_bool_tf pg_options */
if (strEQ("AutoCommit", key))
retsv = boolSV(DBIc_has(imp_dbh, DBIcf_AutoCommit));
else if (strEQ("pg_bool_tf", key))
retsv = newSViv((IV)imp_dbh->pg_bool_tf);
else if (strEQ("pg_options", key)) {
TRACE_PQOPTIONS;
retsv = newSVpv(PQoptions(imp_dbh->conn),0);
}
break;
case 11: /* pg_INV_READ pg_protocol ParamValues */
if (strEQ("pg_INV_READ", key))
retsv = newSViv((IV)INV_READ);
else if (strEQ("pg_protocol", key))
retsv = newSViv((IV)imp_dbh->pg_protocol);
else if (strEQ("ParamValues", key) && imp_dbh->do_tmp_sth != NULL)
return dbd_st_FETCH_attrib (dbh, imp_dbh->do_tmp_sth, keysv);
break;
case 12: /* pg_INV_WRITE pg_utf8_flag */
if (strEQ("pg_INV_WRITE", key))
retsv = newSViv((IV) INV_WRITE );
else if (strEQ("pg_utf8_flag", key))
retsv = newSViv((IV)imp_dbh->pg_utf8_flag);
break;
case 13: /* pg_errorlevel */
if (strEQ("pg_errorlevel", key))
retsv = newSViv((IV)imp_dbh->pg_errorlevel);
break;
case 14: /* pg_lib_version pg_prepare_now pg_enable_utf8 */
if (strEQ("pg_lib_version", key))
retsv = newSViv((IV) PGLIBVERSION );
else if (strEQ("pg_prepare_now", key))
retsv = newSViv((IV)imp_dbh->prepare_now);
else if (strEQ("pg_enable_utf8", key))
retsv = newSViv((IV)imp_dbh->pg_enable_utf8);
break;
case 15: /* pg_default_port pg_async_status pg_expand_array */
if (strEQ("pg_default_port", key))
retsv = newSViv((IV) PGDEFPORT );
else if (strEQ("pg_async_status", key))
retsv = newSViv((IV)imp_dbh->async_status);
else if (strEQ("pg_expand_array", key))
retsv = newSViv((IV)imp_dbh->expand_array);
break;
case 17: /* pg_server_prepare pg_server_version pg_int8_as_string */
if (strEQ("pg_server_prepare", key))
retsv = newSViv((IV)imp_dbh->server_prepare);
else if (strEQ("pg_server_version", key))
retsv = newSViv((IV)imp_dbh->pg_server_version);
else if (strEQ("pg_int8_as_string", key)) {
retsv = newSViv((IV)imp_dbh->pg_int8_as_string);
}
break;
case 18: /* pg_switch_prepared pg_skip_deallocate */
if (strEQ("pg_switch_prepared", key))
retsv = newSViv((IV)imp_dbh->switch_prepared);
else if (strEQ("pg_skip_deallocate", key))
retsv = newSViv((IV)imp_dbh->skip_deallocate);
break;
case 23: /* pg_placeholder_nocolons */
if (strEQ("pg_placeholder_nocolons", key))
retsv = newSViv((IV)imp_dbh->nocolons);
break;
case 25: /* pg_placeholder_dollaronly */
if (strEQ("pg_placeholder_dollaronly", key))
retsv = newSViv((IV)imp_dbh->dollaronly);
break;
case 30: /* pg_standard_conforming_strings */
if (strEQ("pg_standard_conforming_strings", key)) {
if (NULL != PQparameterStatus(imp_dbh->conn, "standard_conforming_strings")) {
retsv = newSVpv(PQparameterStatus(imp_dbh->conn,"standard_conforming_strings"),0);
}
}
break;
default: /* Do nothing, unknown name */
break;
}
if (TEND_slow) TRC(DBILOGFP, "%sEnd dbd_db_FETCH_attrib\n", THEADER_slow);
if (!retsv)
return Nullsv;
if (retsv == &PL_sv_yes || retsv == &PL_sv_no) {
return retsv; /* no need to mortalize yes or no */
}
return sv_2mortal(retsv);
} /* end of dbd_db_FETCH_attrib */
/* ================================================================== */
int dbd_db_STORE_attrib (SV * dbh, imp_dbh_t * imp_dbh, SV * keysv, SV * valuesv)
{
dTHX;
STRLEN kl;
char * key = SvPV(keysv,kl);
unsigned int newval = SvTRUE(valuesv);
int retval = 0;
if (TSTART_slow) TRC(DBILOGFP, "%sBegin dbd_db_STORE (key: %s newval: %d kl:%d)\n", THEADER_slow, key, newval, (int)kl);
switch (kl) {
case 8: /* ReadOnly */
if (strEQ("ReadOnly", key)) {
if (DBIc_has(imp_dbh, DBIcf_AutoCommit)) {
warn("Setting ReadOnly in AutoCommit mode has no effect");
}
imp_dbh->txn_read_only = newval ? DBDPG_TRUE : DBDPG_FALSE;
retval = 1;
}
break;
case 10: /* AutoCommit pg_bool_tf */
if (strEQ("AutoCommit", key)) {
if (newval != DBIc_has(imp_dbh, DBIcf_AutoCommit)) {
if (newval!=0) { /* It was off but is now on, so do a final commit */
if (0!=dbd_db_commit(dbh, imp_dbh) && TRACE4_slow)
TRC(DBILOGFP, "%sSetting AutoCommit to 'on' forced a commit\n", THEADER_slow);
}
DBIc_set(imp_dbh, DBIcf_AutoCommit, newval);
}
retval = 1;
}
else if (strEQ("pg_bool_tf", key)) {
imp_dbh->pg_bool_tf = newval!=0 ? DBDPG_TRUE : DBDPG_FALSE;
retval = 1;
}
break;
case 13: /* pg_errorlevel */
if (strEQ("pg_errorlevel", key)) {
if (SvOK(valuesv)) {
newval = (unsigned)SvIV(valuesv);
}
/* Default to "1" if an invalid value is passed in */
imp_dbh->pg_errorlevel = 0==newval ? 0 : 2==newval ? 2 : 1;
TRACE_PQSETERRORVERBOSITY;
(void)PQsetErrorVerbosity(imp_dbh->conn, (PGVerbosity)imp_dbh->pg_errorlevel);
if (TRACE5_slow)
TRC(DBILOGFP, "%sReset error verbosity to %d\n", THEADER_slow, imp_dbh->pg_errorlevel);
retval = 1;
}
break;
case 14: /* pg_prepare_now pg_enable_utf8 */
if (strEQ("pg_prepare_now", key)) {
imp_dbh->prepare_now = newval ? DBDPG_TRUE : DBDPG_FALSE;
retval = 1;
}
/*
We don't want to check the client_encoding every single time we talk to the database,
so we only do it here, which allows people to signal DBD::Pg that something
may have changed, so could you please rescan client_encoding?
*/
else if (strEQ("pg_enable_utf8", key)) {
/* Technically, we only allow -1, 0, and 1 */
if (SvOK(valuesv)) {
newval = (unsigned)SvIV(valuesv);
}
imp_dbh->pg_enable_utf8 = newval;
/* Never use the utf8 flag, no matter what */
if (0 == imp_dbh->pg_enable_utf8) {
imp_dbh->pg_utf8_flag = DBDPG_FALSE;
}
/* Always use the flag, no matter what */
else if (1 == imp_dbh->pg_enable_utf8) {
imp_dbh->pg_utf8_flag = DBDPG_TRUE;
}
/* Do The Right Thing */
else if (-1 == imp_dbh->pg_enable_utf8) {
pg_db_detect_client_encoding_utf8(aTHX_ imp_dbh);
imp_dbh->pg_enable_utf8 = -1;
imp_dbh->pg_utf8_flag = imp_dbh->client_encoding_utf8;
}
else {
warn("The pg_enable_utf8 setting can only be set to 0, 1, or -1");
}
retval = 1;
}
break;
case 15: /* pg_expand_array */
if (strEQ("pg_expand_array", key)) {
imp_dbh->expand_array = newval ? DBDPG_TRUE : DBDPG_FALSE;
retval = 1;
}
break;
case 17: /* pg_server_prepare pg_int8_as_string */
if (strEQ("pg_server_prepare", key)) {
imp_dbh->server_prepare = newval ? DBDPG_TRUE : DBDPG_FALSE;
retval = 1;
}
else if (strEQ("pg_int8_as_string", key)) {