-
Notifications
You must be signed in to change notification settings - Fork 57
/
DBI.xs
5701 lines (5104 loc) · 201 KB
/
DBI.xs
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
/* vim: ts=8:sw=4:expandtab
*
* $Id$
*
* Copyright (c) 1994-2024 Tim Bunce Ireland.
*
* See COPYRIGHT section in DBI.pm for usage and distribution rights.
*/
#define IN_DBI_XS 1 /* see DBIXS.h */
#define PERL_NO_GET_CONTEXT
#include "DBIXS.h" /* DBI public interface for DBD's written in C */
# if (defined(_WIN32) && (! defined(HAS_GETTIMEOFDAY)))
#include <sys/timeb.h>
# endif
/* The XS dispatcher code can optimize calls to XS driver methods,
* bypassing the usual call_sv() and argument handling overheads.
* Just-in-case it causes problems there's an (undocumented) way
* to disable it by setting an env var.
*/
static int use_xsbypass = 1; /* set in dbi_bootinit() */
#ifndef CvISXSUB
#define CvISXSUB(sv) CvXSUB(sv)
#endif
#define DBI_MAGIC '~'
/* HvMROMETA introduced in 5.9.5, but mro_meta_init not exported in 5.10.0 */
#if (PERL_REVISION == 5)
# if (PERL_VERSION < 10)
# define MY_cache_gen(stash) 0
# else
# if ((PERL_VERSION == 10) && (PERL_SUBVERSION == 0))
# define MY_cache_gen(stash) \
(HvAUX(stash)->xhv_mro_meta \
? HvAUX(stash)->xhv_mro_meta->cache_gen \
: 0)
# else
# define MY_cache_gen(stash) HvMROMETA(stash)->cache_gen
# endif
# endif
#endif
/* If the tests fail with errors about 'setlinebuf' then try */
/* deleting the lines in the block below except the setvbuf one */
#ifndef PerlIO_setlinebuf
# ifdef HAS_SETLINEBUF
# define PerlIO_setlinebuf(f) setlinebuf(f)
# else
# ifndef USE_PERLIO
# define PerlIO_setlinebuf(f) setvbuf(f, Nullch, _IOLBF, 0)
# endif
# endif
#endif
#if (PERL_REVISION == 5)
# if (PERL_VERSION < 8) || ((PERL_VERSION == 8) && (PERL_SUBVERSION == 0))
# define DBI_save_hv_fetch_ent
# endif
/* prior to 5.8.9: when a CV is duped, the mg dup method is called,
* then *afterwards*, any_ptr is copied from the old CV to the new CV.
* This wipes out anything which the dup method did to any_ptr.
* This needs working around */
# if defined(USE_ITHREADS) && (PERL_VERSION == 8) && (PERL_SUBVERSION < 9)
# define BROKEN_DUP_ANY_PTR
# endif
#endif
/* types of method name */
typedef enum {
methtype_ordinary, /* nothing special about this method name */
methtype_DESTROY,
methtype_FETCH,
methtype_can,
methtype_fetch_star, /* fetch*, i.e. fetch() or fetch_...() */
methtype_set_err
} meth_types;
static imp_xxh_t *dbih_getcom _((SV *h));
static imp_xxh_t *dbih_getcom2 _((pTHX_ SV *h, MAGIC **mgp));
static void dbih_clearcom _((imp_xxh_t *imp_xxh));
static int dbih_logmsg _((imp_xxh_t *imp_xxh, const char *fmt, ...));
static SV *dbih_make_com _((SV *parent_h, imp_xxh_t *p_imp_xxh, const char *imp_class, STRLEN imp_size, STRLEN extra, SV *copy));
static SV *dbih_make_fdsv _((SV *sth, const char *imp_class, STRLEN imp_size, const char *col_name));
static AV *dbih_get_fbav _((imp_sth_t *imp_sth));
static SV *dbih_event _((SV *h, const char *name, SV*, SV*));
static int dbih_set_attr_k _((SV *h, SV *keysv, int dbikey, SV *valuesv));
static SV *dbih_get_attr_k _((SV *h, SV *keysv, int dbikey));
static int dbih_sth_bind_col _((SV *sth, SV *col, SV *ref, SV *attribs));
static int set_err_char _((SV *h, imp_xxh_t *imp_xxh, const char *err_c, IV err_i, const char *errstr, const char *state, const char *method));
static int set_err_sv _((SV *h, imp_xxh_t *imp_xxh, SV *err, SV *errstr, SV *state, SV *method));
static int quote_type _((int sql_type, int p, int s, int *base_type, void *v));
static int sql_type_cast_svpv _((pTHX_ SV *sv, int sql_type, U32 flags, void *v));
static I32 dbi_hash _((const char *string, long i));
static void dbih_dumphandle _((pTHX_ SV *h, const char *msg, int level));
static int dbih_dumpcom _((pTHX_ imp_xxh_t *imp_xxh, const char *msg, int level));
static int dbi_ima_free(pTHX_ SV* sv, MAGIC* mg);
#if defined(USE_ITHREADS) && !defined(BROKEN_DUP_ANY_PTR)
static int dbi_ima_dup(pTHX_ MAGIC* mg, CLONE_PARAMS *param);
#endif
char *neatsvpv _((SV *sv, STRLEN maxlen));
SV * preparse(SV *dbh, const char *statement, IV ps_return, IV ps_accept, void *foo);
static meth_types get_meth_type(const char * const name);
struct imp_drh_st { dbih_drc_t com; };
struct imp_dbh_st { dbih_dbc_t com; };
struct imp_sth_st { dbih_stc_t com; };
struct imp_fdh_st { dbih_fdc_t com; };
/* identify the type of a method name for dispatch behaviour */
/* (should probably be folded into the IMA flags mechanism) */
static meth_types
get_meth_type(const char * const name)
{
switch (name[0]) {
case 'D':
if strEQ(name,"DESTROY")
return methtype_DESTROY;
break;
case 'F':
if strEQ(name,"FETCH")
return methtype_FETCH;
break;
case 'c':
if strEQ(name,"can")
return methtype_can;
break;
case 'f':
if strnEQ(name,"fetch", 5) /* fetch* */
return methtype_fetch_star;
break;
case 's':
if strEQ(name,"set_err")
return methtype_set_err;
break;
}
return methtype_ordinary;
}
/* Internal Method Attributes (attached to dispatch methods when installed) */
/* NOTE: when adding SVs to dbi_ima_t, update dbi_ima_dup() dbi_ima_free()
* to ensure that they are duped and correctly ref-counted */
typedef struct dbi_ima_st {
U8 minargs;
U8 maxargs;
IV hidearg;
/* method_trace controls tracing of method calls in the dispatcher:
- if the current trace flags include a trace flag in method_trace
then set trace_level to min(2,trace_level) for duration of the call.
- else, if trace_level < (method_trace & DBIc_TRACE_LEVEL_MASK)
then don't trace the call
*/
U32 method_trace;
const char *usage_msg;
U32 flags;
meth_types meth_type;
/* cached outer to inner method mapping */
HV *stash; /* the stash we found the GV in */
GV *gv; /* the GV containing the inner sub */
U32 generation; /* cache invalidation */
#ifdef BROKEN_DUP_ANY_PTR
PerlInterpreter *my_perl; /* who owns this struct */
#endif
} dbi_ima_t;
/* These values are embedded in the data passed to install_method */
#define IMA_HAS_USAGE 0x00000001 /* check parameter usage */
#define IMA_FUNC_REDIRECT 0x00000002 /* is $h->func(..., "method") */
#define IMA_KEEP_ERR 0x00000004 /* don't reset err & errstr */
#define IMA_KEEP_ERR_SUB 0x00000008 /* '' if in a nested call */
#define IMA_NO_TAINT_IN 0x00000010 /* don't check for PL_tainted args */
#define IMA_NO_TAINT_OUT 0x00000020 /* don't taint results */
#define IMA_COPY_UP_STMT 0x00000040 /* copy sth Statement to dbh */
#define IMA_END_WORK 0x00000080 /* method is commit or rollback */
#define IMA_STUB 0x00000100 /* donothing eg $dbh->connected */
#define IMA_CLEAR_STMT 0x00000200 /* clear Statement before call */
#define IMA_UNRELATED_TO_STMT 0x00000400 /* profile as empty Statement */
#define IMA_NOT_FOUND_OKAY 0x00000800 /* no error if not found */
#define IMA_EXECUTE 0x00001000 /* do/execute: DBIcf_Executed */
#define IMA_SHOW_ERR_STMT 0x00002000 /* dbh meth relates to Statement*/
#define IMA_HIDE_ERR_PARAMVALUES 0x00004000 /* ParamValues are not relevant */
#define IMA_IS_FACTORY 0x00008000 /* new h ie connect and prepare */
#define IMA_CLEAR_CACHED_KIDS 0x00010000 /* clear CachedKids before call */
#define DBIc_STATE_adjust(imp_xxh, state) \
(SvOK(state) /* SQLSTATE is implemented by driver */ \
? (strEQ(SvPV_nolen(state),"00000") ? &PL_sv_no : sv_mortalcopy(state))\
: (SvTRUE(DBIc_ERR(imp_xxh)) \
? sv_2mortal(newSVpv("S1000",5)) /* General error */ \
: &PL_sv_no) /* Success ("00000") */ \
)
#define DBI_LAST_HANDLE g_dbi_last_h /* special fake inner handle */
#define DBI_IS_LAST_HANDLE(h) ((DBI_LAST_HANDLE) == SvRV(h))
#define DBI_SET_LAST_HANDLE(h) ((DBI_LAST_HANDLE) = SvRV(h))
#define DBI_UNSET_LAST_HANDLE ((DBI_LAST_HANDLE) = &PL_sv_undef)
#define DBI_LAST_HANDLE_OK ((DBI_LAST_HANDLE) != &PL_sv_undef)
#define DBIS_TRACE_LEVEL (DBIS->debug & DBIc_TRACE_LEVEL_MASK)
#define DBIS_TRACE_FLAGS (DBIS->debug) /* includes level */
#ifdef PERL_LONG_MAX
#define MAX_LongReadLen PERL_LONG_MAX
#else
#define MAX_LongReadLen 2147483647L
#endif
#ifdef DBI_USE_THREADS
static char *dbi_build_opt = "-ithread";
#else
static char *dbi_build_opt = "-nothread";
#endif
/* 32 bit magic FNV-0 and FNV-1 prime */
#define FNV_32_PRIME ((UV)0x01000193)
/* perl doesn't know anything about the dbi_ima_t struct attached to the
* CvXSUBANY(cv).any_ptr slot, so add some magic to the CV to handle
* duping and freeing.
*/
static MGVTBL dbi_ima_vtbl = { 0, 0, 0, 0, dbi_ima_free,
0,
#if defined(USE_ITHREADS) && !defined(BROKEN_DUP_ANY_PTR)
dbi_ima_dup
#else
0
#endif
#if (PERL_REVISION == 5)
# if (PERL_VERSION > 8) || ((PERL_VERSION == 8) && (PERL_SUBVERSION >= 9))
, 0
# endif
#endif
};
static int dbi_ima_free(pTHX_ SV* sv, PERL_UNUSED_DECL MAGIC* mg)
{
dbi_ima_t *ima = (dbi_ima_t *)(CvXSUBANY((CV*)sv).any_ptr);
#ifdef BROKEN_DUP_ANY_PTR
if (ima->my_perl != my_perl)
return 0;
#endif
SvREFCNT_dec(ima->stash);
SvREFCNT_dec(ima->gv);
Safefree(ima);
return 0;
}
#if defined(USE_ITHREADS) && !defined(BROKEN_DUP_ANY_PTR)
static int dbi_ima_dup(pTHX_ MAGIC* mg, CLONE_PARAMS *param)
{
dbi_ima_t *ima, *nima;
CV *cv = (CV*) mg->mg_ptr;
CV *ncv = (CV*)ptr_table_fetch(PL_ptr_table, (cv));
PERL_UNUSED_VAR(param);
mg->mg_ptr = (char *)ncv;
ima = (dbi_ima_t*) CvXSUBANY(cv).any_ptr;
Newx(nima, 1, dbi_ima_t);
*nima = *ima; /* structure copy */
CvXSUBANY(ncv).any_ptr = nima;
nima->stash = NULL;
nima->gv = NULL;
return 0;
}
#endif
/* --- make DBI safe for multiple perl interpreters --- */
/* Originally contributed by Murray Nesbitt of ActiveState, */
/* but later updated to use MY_CTX */
#define MY_CXT_KEY "DBI::_guts" XS_VERSION
typedef struct {
SV *dbi_last_h; /* maybe better moved into dbistate_t? */
dbistate_t* dbi_state;
} my_cxt_t;
START_MY_CXT
#undef DBIS
#define DBIS (MY_CXT.dbi_state)
#define g_dbi_last_h (MY_CXT.dbi_last_h)
/* allow the 'static' dbi_state struct to be accessed from other files */
dbistate_t**
_dbi_state_lval(pTHX)
{
dMY_CXT;
return &(MY_CXT.dbi_state);
}
/* --- */
static void *
malloc_using_sv(STRLEN len)
{
dTHX;
SV *sv = newSV(len ? len : 1);
void *p = SvPVX(sv);
memzero(p, len);
return p;
}
static char *
savepv_using_sv(char *str)
{
char *buf = malloc_using_sv(strlen(str));
strcpy(buf, str);
return buf;
}
/* --- support functions for concat_hash_sorted --- */
typedef struct str_uv_sort_pair_st {
char *key;
UV numeric;
} str_uv_sort_pair_t;
static int
_cmp_number(const void *val1, const void *val2)
{
UV first = ((str_uv_sort_pair_t *)val1)->numeric;
UV second = ((str_uv_sort_pair_t *)val2)->numeric;
if (first > second)
return 1;
if (first < second)
return -1;
/* only likely to reach here if numeric sort forced for non-numeric keys */
/* fallback to comparing the key strings */
return strcmp(
((str_uv_sort_pair_t *)val1)->key,
((str_uv_sort_pair_t *)val2)->key
);
}
static int
_cmp_str (const void *val1, const void *val2)
{
return strcmp( *(char **)val1, *(char **)val2);
}
static char **
_sort_hash_keys (HV *hash, int num_sort, STRLEN *total_length)
{
dTHX;
I32 hv_len, key_len;
HE *entry;
char **keys;
unsigned int idx = 0;
STRLEN tot_len = 0;
bool has_non_numerics = 0;
str_uv_sort_pair_t *numbers;
hv_len = hv_iterinit(hash);
if (!hv_len)
return 0;
Newz(0, keys, hv_len, char *);
Newz(0, numbers, hv_len, str_uv_sort_pair_t);
while ((entry = hv_iternext(hash))) {
*(keys+idx) = hv_iterkey(entry, &key_len);
tot_len += key_len;
if (grok_number(*(keys+idx), key_len, &(numbers+idx)->numeric) != IS_NUMBER_IN_UV) {
has_non_numerics = 1;
(numbers+idx)->numeric = 0;
}
(numbers+idx)->key = *(keys+idx);
++idx;
}
if (total_length)
*total_length = tot_len;
if (num_sort < 0)
num_sort = (has_non_numerics) ? 0 : 1;
if (!num_sort) {
qsort(keys, hv_len, sizeof(char*), _cmp_str);
}
else {
qsort(numbers, hv_len, sizeof(str_uv_sort_pair_t), _cmp_number);
for (idx = 0; idx < hv_len; ++idx)
*(keys+idx) = (numbers+idx)->key;
}
Safefree(numbers);
return keys;
}
static SV *
_join_hash_sorted(HV *hash, char *kv_sep, STRLEN kv_sep_len, char *pair_sep, STRLEN pair_sep_len, int use_neat, int num_sort)
{
dTHX;
I32 hv_len;
STRLEN total_len = 0;
char **keys;
unsigned int i = 0;
SV *return_sv;
keys = _sort_hash_keys(hash, num_sort, &total_len);
if (!keys)
return newSVpv("", 0);
if (!kv_sep_len)
kv_sep_len = strlen(kv_sep);
if (!pair_sep_len)
pair_sep_len = strlen(pair_sep);
hv_len = hv_iterinit(hash);
/* total_len += Separators + quotes + term null */
total_len += kv_sep_len*hv_len + pair_sep_len*hv_len+2*hv_len+1;
return_sv = newSV(total_len);
sv_setpv(return_sv, ""); /* quell undef warnings */
for (i=0; i<hv_len; ++i) {
SV **hash_svp = hv_fetch(hash, keys[i], strlen(keys[i]), 0);
sv_catpv(return_sv, keys[i]); /* XXX keys can't contain nul chars */
sv_catpvn(return_sv, kv_sep, kv_sep_len);
if (!hash_svp) { /* should never happen */
warn("No hash entry with key '%s'", keys[i]);
sv_catpvn(return_sv, "???", 3);
continue;
}
if (use_neat) {
sv_catpv(return_sv, neatsvpv(*hash_svp,0));
}
else {
if (SvOK(*hash_svp)) {
STRLEN hv_val_len;
char *hv_val = SvPV(*hash_svp, hv_val_len);
sv_catpvn(return_sv, "'", 1);
sv_catpvn(return_sv, hv_val, hv_val_len);
sv_catpvn(return_sv, "'", 1);
}
else sv_catpvn(return_sv, "undef", 5);
}
if (i < hv_len-1)
sv_catpvn(return_sv, pair_sep, pair_sep_len);
}
Safefree(keys);
return return_sv;
}
/* handy for embedding into condition expression for debugging */
/*
static int warn1(char *s) { warn("%s", s); return 1; }
static int dump1(SV *sv) { dTHX; sv_dump(sv); return 1; }
*/
/* --- */
static void
check_version(const char *name, int dbis_cv, int dbis_cs, int need_dbixs_cv, int drc_s,
int dbc_s, int stc_s, int fdc_s)
{
dTHX;
dMY_CXT;
static const char msg[] = "you probably need to rebuild the DBD driver (or possibly the DBI)";
(void)need_dbixs_cv;
if (dbis_cv != DBISTATE_VERSION || dbis_cs != sizeof(*DBIS))
croak("DBI/DBD internal version mismatch (DBI is v%d/s%lu, DBD %s expected v%d/s%d) %s.\n",
DBISTATE_VERSION, (long unsigned int)sizeof(*DBIS), name, dbis_cv, dbis_cs, msg);
/* Catch structure size changes - We should probably force a recompile if the DBI */
/* runtime version is different from the build time. That would be harsh but safe. */
if (drc_s != sizeof(dbih_drc_t) || dbc_s != sizeof(dbih_dbc_t) ||
stc_s != sizeof(dbih_stc_t) || fdc_s != sizeof(dbih_fdc_t) )
croak("%s (dr:%d/%ld, db:%d/%ld, st:%d/%ld, fd:%d/%ld), %s.\n",
"DBI/DBD internal structure mismatch",
drc_s, (long)sizeof(dbih_drc_t), dbc_s, (long)sizeof(dbih_dbc_t),
stc_s, (long)sizeof(dbih_stc_t), fdc_s, (long)sizeof(dbih_fdc_t), msg);
}
static void
dbi_bootinit(dbistate_t * parent_dbis)
{
dTHX;
dMY_CXT;
dbistate_t* DBISx;
DBISx = (struct dbistate_st*)malloc_using_sv(sizeof(struct dbistate_st));
DBIS = DBISx;
/* make DBIS available to DBD modules the "old" (<= 1.618) way,
* so that unrecompiled DBD's will still work against a newer DBI */
sv_setiv(get_sv("DBI::_dbistate", GV_ADDMULTI),
PTR2IV(MY_CXT.dbi_state));
/* store version and size so we can spot DBI/DBD version mismatch */
DBIS->check_version = check_version;
DBIS->version = DBISTATE_VERSION;
DBIS->size = sizeof(*DBIS);
DBIS->xs_version = DBIXS_VERSION;
DBIS->logmsg = dbih_logmsg;
DBIS->logfp = PerlIO_stderr();
DBIS->debug = (parent_dbis) ? parent_dbis->debug
: SvIV(get_sv("DBI::dbi_debug",0x5));
DBIS->neatsvpvlen = (parent_dbis) ? parent_dbis->neatsvpvlen
: get_sv("DBI::neat_maxlen", GV_ADDMULTI);
#ifdef DBI_USE_THREADS
DBIS->thr_owner = PERL_GET_THX;
#endif
/* store some function pointers so DBD's can call our functions */
DBIS->getcom = dbih_getcom;
DBIS->clearcom = dbih_clearcom;
DBIS->event = dbih_event;
DBIS->set_attr_k = dbih_set_attr_k;
DBIS->get_attr_k = dbih_get_attr_k;
DBIS->get_fbav = dbih_get_fbav;
DBIS->make_fdsv = dbih_make_fdsv;
DBIS->neat_svpv = neatsvpv;
DBIS->bind_as_num = quote_type; /* XXX deprecated */
DBIS->hash = dbi_hash;
DBIS->set_err_sv = set_err_sv;
DBIS->set_err_char= set_err_char;
DBIS->bind_col = dbih_sth_bind_col;
DBIS->sql_type_cast_svpv = sql_type_cast_svpv;
/* Remember the last handle used. BEWARE! Sneaky stuff here! */
/* We want a handle reference but we don't want to increment */
/* the handle's reference count and we don't want perl to try */
/* to destroy it during global destruction. Take care! */
DBI_UNSET_LAST_HANDLE; /* ensure setup the correct way */
/* trick to avoid 'possible typo' warnings */
gv_fetchpv("DBI::state", GV_ADDMULTI, SVt_PV);
gv_fetchpv("DBI::err", GV_ADDMULTI, SVt_PV);
gv_fetchpv("DBI::errstr", GV_ADDMULTI, SVt_PV);
gv_fetchpv("DBI::lasth", GV_ADDMULTI, SVt_PV);
gv_fetchpv("DBI::rows", GV_ADDMULTI, SVt_PV);
/* we only need to check the env var on the initial boot
* which is handy because it can core dump during CLONE on windows
*/
if (!parent_dbis && getenv("PERL_DBI_XSBYPASS"))
use_xsbypass = atoi(getenv("PERL_DBI_XSBYPASS"));
}
/* ----------------------------------------------------------------- */
/* Utility functions */
static char *
dbih_htype_name(int htype)
{
switch(htype) {
case DBIt_DR: return "dr";
case DBIt_DB: return "db";
case DBIt_ST: return "st";
case DBIt_FD: return "fd";
default: return "??";
}
}
char *
neatsvpv(SV *sv, STRLEN maxlen) /* return a tidy ascii value, for debugging only */
{
dTHX;
dMY_CXT;
STRLEN len;
SV *nsv = Nullsv;
SV *infosv = Nullsv;
char *v, *quote;
/* We take care not to alter the supplied sv in any way at all. */
/* (but if it is SvGMAGICAL we have to call mg_get and that can */
/* have side effects, especially as it may be called twice overall.) */
if (!sv)
return "Null!"; /* should never happen */
/* try to do the right thing with magical values */
if (SvMAGICAL(sv)) {
if (DBIS_TRACE_LEVEL >= 5) { /* add magic details to help debugging */
MAGIC* mg;
infosv = sv_2mortal(newSVpv(" (magic-",0));
if (SvSMAGICAL(sv)) sv_catpvn(infosv,"s",1);
if (SvGMAGICAL(sv)) sv_catpvn(infosv,"g",1);
if (SvRMAGICAL(sv)) sv_catpvn(infosv,"r",1);
sv_catpvn(infosv,":",1);
for (mg = SvMAGIC(sv); mg; mg = mg->mg_moremagic)
sv_catpvn(infosv, &mg->mg_type, 1);
sv_catpvn(infosv, ")", 1);
}
if (SvGMAGICAL(sv) && !PL_dirty)
mg_get(sv); /* trigger magic to FETCH the value */
}
if (!SvOK(sv)) {
if (SvTYPE(sv) >= SVt_PVAV)
return (char *)sv_reftype(sv,0); /* raw AV/HV etc, not via a ref */
if (!infosv)
return "undef";
sv_insert(infosv, 0,0, "undef",5);
return SvPVX(infosv);
}
if (SvNIOK(sv)) { /* is a numeric value - so no surrounding quotes */
if (SvPOK(sv)) { /* already has string version of the value, so use it */
v = SvPV(sv,len);
if (len == 0) { v="''"; len=2; } /* catch &sv_no style special case */
if (!infosv)
return v;
sv_insert(infosv, 0,0, v, len);
return SvPVX(infosv);
}
/* we don't use SvPV here since we don't want to alter sv in _any_ way */
if (SvUOK(sv))
nsv = newSVpvf("%"UVuf, SvUVX(sv));
else if (SvIOK(sv))
nsv = newSVpvf("%"IVdf, SvIVX(sv));
else nsv = newSVpvf("%"NVgf, SvNVX(sv));
if (infosv)
sv_catsv(nsv, infosv);
return SvPVX(sv_2mortal(nsv));
}
nsv = sv_newmortal();
sv_upgrade(nsv, SVt_PV);
if (SvROK(sv)) {
if (!SvAMAGIC(sv)) /* (un-amagic'd) refs get no special treatment */
v = SvPV(sv,len);
else {
/* handle Overload magic refs */
(void)SvAMAGIC_off(sv); /* should really be done via local scoping */
v = SvPV(sv,len); /* XXX how does this relate to SvGMAGIC? */
SvAMAGIC_on(sv);
}
sv_setpvn(nsv, v, len);
if (infosv)
sv_catsv(nsv, infosv);
return SvPV(nsv, len);
}
if (SvPOK(sv)) /* usual simple string case */
v = SvPV(sv,len);
else /* handles all else via sv_2pv() */
v = SvPV(sv,len); /* XXX how does this relate to SvGMAGIC? */
/* for strings we limit the length and translate codes */
if (maxlen == 0)
maxlen = SvIV(DBIS->neatsvpvlen);
if (maxlen < 6) /* handle daft values */
maxlen = 6;
maxlen -= 2; /* account for quotes */
quote = (SvUTF8(sv)) ? "\"" : "'";
if (len > maxlen) {
SvGROW(nsv, (1+maxlen+1+1));
sv_setpvn(nsv, quote, 1);
sv_catpvn(nsv, v, maxlen-3); /* account for three dots */
sv_catpvn(nsv, "...", 3);
} else {
SvGROW(nsv, (1+len+1+1));
sv_setpvn(nsv, quote, 1);
sv_catpvn(nsv, v, len);
}
sv_catpvn(nsv, quote, 1);
if (infosv)
sv_catsv(nsv, infosv);
v = SvPV(nsv, len);
if (!SvUTF8(sv)) {
while(len-- > 0) { /* cleanup string (map control chars to ascii etc) */
const char c = v[len] & 0x7F; /* ignore top bit for multinational chars */
if (!isPRINT(c) && !isSPACE(c))
v[len] = '.';
}
}
return v;
}
static void
copy_statement_to_parent(pTHX_ SV *h, imp_xxh_t *imp_xxh)
{
SV *parent;
if (PL_dirty)
return;
parent = DBIc_PARENT_H(imp_xxh);
if (parent && SvROK(parent)) {
SV *tmp_sv = *hv_fetch((HV*)SvRV(h), "Statement", 9, 1);
if (SvOK(tmp_sv))
(void)hv_store((HV*)SvRV(parent), "Statement", 9, SvREFCNT_inc(tmp_sv), 0);
}
}
static int
set_err_char(SV *h, imp_xxh_t *imp_xxh, const char *err_c, IV err_i, const char *errstr, const char *state, const char *method)
{
dTHX;
char err_buf[28];
SV *err_sv, *errstr_sv, *state_sv, *method_sv;
if (!err_c) {
sprintf(err_buf, "%ld", (long)err_i);
err_c = &err_buf[0];
}
err_sv = (strEQ(err_c,"1")) ? &PL_sv_yes : sv_2mortal(newSVpvn(err_c, strlen(err_c)));
errstr_sv = sv_2mortal(newSVpvn(errstr, strlen(errstr)));
state_sv = (state && *state) ? sv_2mortal(newSVpvn(state, strlen(state))) : &PL_sv_undef;
method_sv = (method && *method) ? sv_2mortal(newSVpvn(method, strlen(method))) : &PL_sv_undef;
return set_err_sv(h, imp_xxh, err_sv, errstr_sv, state_sv, method_sv);
}
static int
set_err_sv(SV *h, imp_xxh_t *imp_xxh, SV *err, SV *errstr, SV *state, SV *method)
{
dTHX;
SV *h_err;
SV *h_errstr;
SV *h_state;
SV **hook_svp;
int err_changed = 0;
if ( DBIc_has(imp_xxh, DBIcf_HandleSetErr)
&& (hook_svp = hv_fetch((HV*)SvRV(h),"HandleSetErr",12,0))
&& hook_svp
&& ((void)(SvGMAGICAL(*hook_svp) && mg_get(*hook_svp)), SvOK(*hook_svp))
) {
dSP;
IV items;
SV *response_sv;
if (SvREADONLY(err)) err = sv_mortalcopy(err);
if (SvREADONLY(errstr)) errstr = sv_mortalcopy(errstr);
if (SvREADONLY(state)) state = sv_mortalcopy(state);
if (SvREADONLY(method)) method = sv_mortalcopy(method);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh)," -> HandleSetErr(%s, err=%s, errstr=%s, state=%s, %s)\n",
neatsvpv(h,0), neatsvpv(err,0), neatsvpv(errstr,0), neatsvpv(state,0),
neatsvpv(method,0)
);
PUSHMARK(SP);
XPUSHs(sv_2mortal(newRV_inc((SV*)DBIc_MY_H(imp_xxh))));
XPUSHs(err);
XPUSHs(errstr);
XPUSHs(state);
XPUSHs(method);
PUTBACK;
items = call_sv(*hook_svp, G_SCALAR);
SPAGAIN;
response_sv = (items) ? POPs : &PL_sv_undef;
PUTBACK;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 1)
PerlIO_printf(DBIc_LOGPIO(imp_xxh)," <- HandleSetErr= %s (err=%s, errstr=%s, state=%s, %s)\n",
neatsvpv(response_sv,0), neatsvpv(err,0), neatsvpv(errstr,0), neatsvpv(state,0),
neatsvpv(method,0)
);
if (SvTRUE(response_sv)) /* handler says it has handled it, so... */
return 0;
}
else {
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh)," -- HandleSetErr err=%s, errstr=%s, state=%s, %s\n",
neatsvpv(err,0), neatsvpv(errstr,0), neatsvpv(state,0), neatsvpv(method,0)
);
}
if (!SvOK(err)) { /* clear err / errstr / state */
DBIh_CLEAR_ERROR(imp_xxh);
return 1;
}
/* fetch these after calling HandleSetErr */
h_err = DBIc_ERR(imp_xxh);
h_errstr = DBIc_ERRSTR(imp_xxh);
h_state = DBIc_STATE(imp_xxh);
if (SvTRUE(h_errstr)) {
/* append current err, if any, to errstr if it's going to change */
if (SvTRUE(h_err) && SvTRUE(err) && strNE(SvPV_nolen(h_err), SvPV_nolen(err)))
sv_catpvf(h_errstr, " [err was %s now %s]", SvPV_nolen(h_err), SvPV_nolen(err));
if (SvTRUE(h_state) && SvTRUE(state) && strNE(SvPV_nolen(h_state), SvPV_nolen(state)))
sv_catpvf(h_errstr, " [state was %s now %s]", SvPV_nolen(h_state), SvPV_nolen(state));
if (strNE(SvPV_nolen(h_errstr), SvPV_nolen(errstr))) {
sv_catpvn(h_errstr, "\n", 1);
sv_catsv(h_errstr, errstr);
}
}
else
sv_setsv(h_errstr, errstr);
/* SvTRUE(err) > "0" > "" > undef */
if (SvTRUE(err) /* new error: so assign */
|| !SvOK(h_err) /* no existing warn/info: so assign */
/* new warn ("0" len 1) > info ("" len 0): so assign */
|| (SvOK(err) && strlen(SvPV_nolen(err)) > strlen(SvPV_nolen(h_err)))
) {
sv_setsv(h_err, err);
err_changed = 1;
if (SvTRUE(h_err)) /* new error */
++DBIc_ErrCount(imp_xxh);
}
if (err_changed) {
if (SvTRUE(state)) {
if (strlen(SvPV_nolen(state)) != 5) {
warn("set_err: state (%s) is not a 5 character string, using 'S1000' instead", neatsvpv(state,0));
sv_setpv(h_state, "S1000");
}
else
sv_setsv(h_state, state);
}
else
(void)SvOK_off(h_state); /* see DBIc_STATE_adjust */
/* ensure that the parent's Statement attribute reflects the latest error */
/* so that ShowErrorStatement is reliable */
copy_statement_to_parent(aTHX_ h, imp_xxh);
}
return 1;
}
/* err_hash returns a U32 'hash' value representing the current err 'level'
* (err/warn/info) and errstr. It's used by the dispatcher as a way to detect
* a new or changed warning during a 'keep err' method like STORE. Always returns >0.
* The value is 1 for no err/warn/info and guarantees that err > warn > info.
* (It's a bit of a hack but the original approach in 70fe6bd76 using a new
* ErrChangeCount attribute would break binary compatibility with drivers.)
* The chance that two realistic errstr values would hash the same, even with
* only 30 bits, is deemed to small to even bother documenting.
*/
static U32
err_hash(pTHX_ imp_xxh_t *imp_xxh)
{
SV *err_sv = DBIc_ERR(imp_xxh);
SV *errstr_sv;
I32 hash = 1;
if (SvOK(err_sv)) {
errstr_sv = DBIc_ERRSTR(imp_xxh);
if (SvOK(errstr_sv))
hash = -dbi_hash(SvPV_nolen(errstr_sv), 0); /* make positive */
else hash = 0;
hash >>= 1; /* free up extra bit (top bit is already free) */
hash |= (SvTRUE(err_sv)) ? 0x80000000 /* err */
: (SvPOK(err_sv) && !SvCUR(err_sv)) ? 0x20000000 /* '' = info */
: 0x40000000;/* 0 or '0' = warn */
}
return hash;
}
static char *
mkvname(pTHX_ HV *stash, const char *item, int uplevel) /* construct a variable name */
{
SV *sv = sv_newmortal();
sv_setpv(sv, HvNAME(stash));
if(uplevel) {
while(SvCUR(sv) && *SvEND(sv)!=':')
--SvCUR(sv);
if (SvCUR(sv))
--SvCUR(sv);
}
sv_catpv(sv, "::");
sv_catpv(sv, item);
return SvPV_nolen(sv);
}
/* 32 bit magic FNV-0 and FNV-1 prime */
#define FNV_32_PRIME ((UV)0x01000193)
static I32
dbi_hash(const char *key, long type)
{
if (type == 0) {
STRLEN klen = strlen(key);
U32 hash = 0;
while (klen--)
hash = hash * 33 + *key++;
hash &= 0x7FFFFFFF; /* limit to 31 bits */
hash |= 0x40000000; /* set bit 31 */
return -(I32)hash; /* return negative int */
}
else if (type == 1) { /* Fowler/Noll/Vo hash */
/* see http://www.isthe.com/chongo/tech/comp/fnv/ */
U32 hash = 0x811c9dc5;
const unsigned char *s = (unsigned char *)key; /* unsigned string */
while (*s) {
/* multiply by the 32 bit FNV magic prime mod 2^32 */
hash *= FNV_32_PRIME;
/* xor the bottom with the current octet */
hash ^= (U32)*s++;
}
return hash;
}
croak("DBI::hash(%ld): invalid type", type);
return 0; /* NOT REACHED */
}
static int
dbih_logmsg(imp_xxh_t *imp_xxh, const char *fmt, ...)
{
dTHX;
va_list args;
#ifdef I_STDARG
va_start(args, fmt);
#else
va_start(args);
#endif
(void) PerlIO_vprintf(DBIc_DBISTATE(imp_xxh)->logfp, fmt, args);
va_end(args);
(void)imp_xxh;
return 1;
}
static void
close_trace_file(pTHX)
{
dMY_CXT;
if (DBILOGFP == PerlIO_stderr() || DBILOGFP == PerlIO_stdout())
return;
if (DBIS->logfp_ref == NULL)
PerlIO_close(DBILOGFP);
else {
/* DAA dec refcount and discard */
SvREFCNT_dec(DBIS->logfp_ref);
DBIS->logfp_ref = NULL;
}
}
static int
set_trace_file(SV *file)
{
dTHX;
dMY_CXT;
const char *filename;
PerlIO *fp = Nullfp;
IO *io;
if (!file) /* no arg == no change */
return 0;
/* DAA check for a filehandle */
if (SvROK(file)) {
io = sv_2io(file);
if (!io || !(fp = IoOFP(io))) {
warn("DBI trace filehandle is not valid");
return 0;
}
close_trace_file(aTHX);
(void)SvREFCNT_inc(io);
DBIS->logfp_ref = io;
}
else if (isGV_with_GP(file)) {
io = GvIO(file);
if (!io || !(fp = IoOFP(io))) {
warn("DBI trace filehandle from GLOB is not valid");
return 0;
}
close_trace_file(aTHX);
(void)SvREFCNT_inc(io);
DBIS->logfp_ref = io;
}
else {
filename = (SvOK(file)) ? SvPV_nolen(file) : Nullch;
/* undef arg == reset back to stderr */
if (!filename || strEQ(filename,"STDERR")