-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
plpy_typeio.c
1569 lines (1367 loc) · 40.5 KB
/
plpy_typeio.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
/*
* transforming Datums to Python objects and vice versa
*
* src/pl/plpython/plpy_typeio.c
*/
#include "postgres.h"
#include "access/htup_details.h"
#include "catalog/pg_type.h"
#include "funcapi.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "plpy_elog.h"
#include "plpy_main.h"
#include "plpy_typeio.h"
#include "plpython.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
/* conversion from Datums to Python objects */
static PyObject *PLyBool_FromBool(PLyDatumToOb *arg, Datum d);
static PyObject *PLyFloat_FromFloat4(PLyDatumToOb *arg, Datum d);
static PyObject *PLyFloat_FromFloat8(PLyDatumToOb *arg, Datum d);
static PyObject *PLyDecimal_FromNumeric(PLyDatumToOb *arg, Datum d);
static PyObject *PLyInt_FromInt16(PLyDatumToOb *arg, Datum d);
static PyObject *PLyInt_FromInt32(PLyDatumToOb *arg, Datum d);
static PyObject *PLyLong_FromInt64(PLyDatumToOb *arg, Datum d);
static PyObject *PLyLong_FromOid(PLyDatumToOb *arg, Datum d);
static PyObject *PLyBytes_FromBytea(PLyDatumToOb *arg, Datum d);
static PyObject *PLyString_FromScalar(PLyDatumToOb *arg, Datum d);
static PyObject *PLyObject_FromTransform(PLyDatumToOb *arg, Datum d);
static PyObject *PLyList_FromArray(PLyDatumToOb *arg, Datum d);
static PyObject *PLyList_FromArray_recurse(PLyDatumToOb *elm, int *dims, int ndim, int dim,
char **dataptr_p, bits8 **bitmap_p, int *bitmask_p);
static PyObject *PLyDict_FromComposite(PLyDatumToOb *arg, Datum d);
static PyObject *PLyDict_FromTuple(PLyDatumToOb *arg, HeapTuple tuple, TupleDesc desc, bool include_generated);
/* conversion from Python objects to Datums */
static Datum PLyObject_ToBool(PLyObToDatum *arg, PyObject *plrv,
bool *isnull, bool inarray);
static Datum PLyObject_ToBytea(PLyObToDatum *arg, PyObject *plrv,
bool *isnull, bool inarray);
static Datum PLyObject_ToComposite(PLyObToDatum *arg, PyObject *plrv,
bool *isnull, bool inarray);
static Datum PLyObject_ToScalar(PLyObToDatum *arg, PyObject *plrv,
bool *isnull, bool inarray);
static Datum PLyObject_ToDomain(PLyObToDatum *arg, PyObject *plrv,
bool *isnull, bool inarray);
static Datum PLyObject_ToTransform(PLyObToDatum *arg, PyObject *plrv,
bool *isnull, bool inarray);
static Datum PLySequence_ToArray(PLyObToDatum *arg, PyObject *plrv,
bool *isnull, bool inarray);
static void PLySequence_ToArray_recurse(PLyObToDatum *elm, PyObject *list,
int *dims, int ndim, int dim,
Datum *elems, bool *nulls, int *currelem);
/* conversion from Python objects to composite Datums */
static Datum PLyString_ToComposite(PLyObToDatum *arg, PyObject *string, bool inarray);
static Datum PLyMapping_ToComposite(PLyObToDatum *arg, TupleDesc desc, PyObject *mapping);
static Datum PLySequence_ToComposite(PLyObToDatum *arg, TupleDesc desc, PyObject *sequence);
static Datum PLyGenericObject_ToComposite(PLyObToDatum *arg, TupleDesc desc, PyObject *object, bool inarray);
/*
* Conversion functions. Remember output from Python is input to
* PostgreSQL, and vice versa.
*/
/*
* Perform input conversion, given correctly-set-up state information.
*
* This is the outer-level entry point for any input conversion. Internally,
* the conversion functions recurse directly to each other.
*/
PyObject *
PLy_input_convert(PLyDatumToOb *arg, Datum val)
{
PyObject *result;
PLyExecutionContext *exec_ctx = PLy_current_execution_context();
MemoryContext scratch_context = PLy_get_scratch_context(exec_ctx);
MemoryContext oldcontext;
/*
* Do the work in the scratch context to avoid leaking memory from the
* datatype output function calls. (The individual PLyDatumToObFunc
* functions can't reset the scratch context, because they recurse and an
* inner one might clobber data an outer one still needs. So we do it
* once at the outermost recursion level.)
*
* We reset the scratch context before, not after, each conversion cycle.
* This way we aren't on the hook to release a Python refcount on the
* result object in case MemoryContextReset throws an error.
*/
MemoryContextReset(scratch_context);
oldcontext = MemoryContextSwitchTo(scratch_context);
result = arg->func(arg, val);
MemoryContextSwitchTo(oldcontext);
return result;
}
/*
* Perform output conversion, given correctly-set-up state information.
*
* This is the outer-level entry point for any output conversion. Internally,
* the conversion functions recurse directly to each other.
*
* The result, as well as any cruft generated along the way, are in the
* current memory context. Caller is responsible for cleanup.
*/
Datum
PLy_output_convert(PLyObToDatum *arg, PyObject *val, bool *isnull)
{
/* at outer level, we are not considering an array element */
return arg->func(arg, val, isnull, false);
}
/*
* Transform a tuple into a Python dict object.
*
* Note: the tupdesc must match the one used to set up *arg. We could
* insist that this function lookup the tupdesc from what is in *arg,
* but in practice all callers have the right tupdesc available.
*/
PyObject *
PLy_input_from_tuple(PLyDatumToOb *arg, HeapTuple tuple, TupleDesc desc, bool include_generated)
{
PyObject *dict;
PLyExecutionContext *exec_ctx = PLy_current_execution_context();
MemoryContext scratch_context = PLy_get_scratch_context(exec_ctx);
MemoryContext oldcontext;
/*
* As in PLy_input_convert, do the work in the scratch context.
*/
MemoryContextReset(scratch_context);
oldcontext = MemoryContextSwitchTo(scratch_context);
dict = PLyDict_FromTuple(arg, tuple, desc, include_generated);
MemoryContextSwitchTo(oldcontext);
return dict;
}
/*
* Initialize, or re-initialize, per-column input info for a composite type.
*
* This is separate from PLy_input_setup_func() because in cases involving
* anonymous record types, we need to be passed the tupdesc explicitly.
* It's caller's responsibility that the tupdesc has adequate lifespan
* in such cases. If the tupdesc is for a named composite or registered
* record type, it does not need to be long-lived.
*/
void
PLy_input_setup_tuple(PLyDatumToOb *arg, TupleDesc desc, PLyProcedure *proc)
{
int i;
/* We should be working on a previously-set-up struct */
Assert(arg->func == PLyDict_FromComposite);
/* Save pointer to tupdesc, but only if this is an anonymous record type */
if (arg->typoid == RECORDOID && arg->typmod < 0)
arg->u.tuple.recdesc = desc;
/* (Re)allocate atts array as needed */
if (arg->u.tuple.natts != desc->natts)
{
if (arg->u.tuple.atts)
pfree(arg->u.tuple.atts);
arg->u.tuple.natts = desc->natts;
arg->u.tuple.atts = (PLyDatumToOb *)
MemoryContextAllocZero(arg->mcxt,
desc->natts * sizeof(PLyDatumToOb));
}
/* Fill the atts entries, except for dropped columns */
for (i = 0; i < desc->natts; i++)
{
Form_pg_attribute attr = TupleDescAttr(desc, i);
PLyDatumToOb *att = &arg->u.tuple.atts[i];
if (attr->attisdropped)
continue;
if (att->typoid == attr->atttypid && att->typmod == attr->atttypmod)
continue; /* already set up this entry */
PLy_input_setup_func(att, arg->mcxt,
attr->atttypid, attr->atttypmod,
proc);
}
}
/*
* Initialize, or re-initialize, per-column output info for a composite type.
*
* This is separate from PLy_output_setup_func() because in cases involving
* anonymous record types, we need to be passed the tupdesc explicitly.
* It's caller's responsibility that the tupdesc has adequate lifespan
* in such cases. If the tupdesc is for a named composite or registered
* record type, it does not need to be long-lived.
*/
void
PLy_output_setup_tuple(PLyObToDatum *arg, TupleDesc desc, PLyProcedure *proc)
{
int i;
/* We should be working on a previously-set-up struct */
Assert(arg->func == PLyObject_ToComposite);
/* Save pointer to tupdesc, but only if this is an anonymous record type */
if (arg->typoid == RECORDOID && arg->typmod < 0)
arg->u.tuple.recdesc = desc;
/* (Re)allocate atts array as needed */
if (arg->u.tuple.natts != desc->natts)
{
if (arg->u.tuple.atts)
pfree(arg->u.tuple.atts);
arg->u.tuple.natts = desc->natts;
arg->u.tuple.atts = (PLyObToDatum *)
MemoryContextAllocZero(arg->mcxt,
desc->natts * sizeof(PLyObToDatum));
}
/* Fill the atts entries, except for dropped columns */
for (i = 0; i < desc->natts; i++)
{
Form_pg_attribute attr = TupleDescAttr(desc, i);
PLyObToDatum *att = &arg->u.tuple.atts[i];
if (attr->attisdropped)
continue;
if (att->typoid == attr->atttypid && att->typmod == attr->atttypmod)
continue; /* already set up this entry */
PLy_output_setup_func(att, arg->mcxt,
attr->atttypid, attr->atttypmod,
proc);
}
}
/*
* Set up output info for a PL/Python function returning record.
*
* Note: the given tupdesc is not necessarily long-lived.
*/
void
PLy_output_setup_record(PLyObToDatum *arg, TupleDesc desc, PLyProcedure *proc)
{
/* Makes no sense unless RECORD */
Assert(arg->typoid == RECORDOID);
Assert(desc->tdtypeid == RECORDOID);
/*
* Bless the record type if not already done. We'd have to do this anyway
* to return a tuple, so we might as well force the issue so we can use
* the known-record-type code path.
*/
BlessTupleDesc(desc);
/*
* Update arg->typmod, and clear the recdesc link if it's changed. The
* next call of PLyObject_ToComposite will look up a long-lived tupdesc
* for the record type.
*/
arg->typmod = desc->tdtypmod;
if (arg->u.tuple.recdesc &&
arg->u.tuple.recdesc->tdtypmod != arg->typmod)
arg->u.tuple.recdesc = NULL;
/* Update derived data if necessary */
PLy_output_setup_tuple(arg, desc, proc);
}
/*
* Recursively initialize the PLyObToDatum structure(s) needed to construct
* a SQL value of the specified typeOid/typmod from a Python value.
* (But note that at this point we may have RECORDOID/-1, ie, an indeterminate
* record type.)
* proc is used to look up transform functions.
*/
void
PLy_output_setup_func(PLyObToDatum *arg, MemoryContext arg_mcxt,
Oid typeOid, int32 typmod,
PLyProcedure *proc)
{
TypeCacheEntry *typentry;
char typtype;
Oid trfuncid;
Oid typinput;
/* Since this is recursive, it could theoretically be driven to overflow */
check_stack_depth();
arg->typoid = typeOid;
arg->typmod = typmod;
arg->mcxt = arg_mcxt;
/*
* Fetch typcache entry for the target type, asking for whatever info
* we'll need later. RECORD is a special case: just treat it as composite
* without bothering with the typcache entry.
*/
if (typeOid != RECORDOID)
{
typentry = lookup_type_cache(typeOid, TYPECACHE_DOMAIN_BASE_INFO);
typtype = typentry->typtype;
arg->typbyval = typentry->typbyval;
arg->typlen = typentry->typlen;
arg->typalign = typentry->typalign;
}
else
{
typentry = NULL;
typtype = TYPTYPE_COMPOSITE;
/* hard-wired knowledge about type RECORD: */
arg->typbyval = false;
arg->typlen = -1;
arg->typalign = TYPALIGN_DOUBLE;
}
/*
* Choose conversion method. Note that transform functions are checked
* for composite and scalar types, but not for arrays or domains. This is
* somewhat historical, but we'd have a problem allowing them on domains,
* since we drill down through all levels of a domain nest without looking
* at the intermediate levels at all.
*/
if (typtype == TYPTYPE_DOMAIN)
{
/* Domain */
arg->func = PLyObject_ToDomain;
arg->u.domain.domain_info = NULL;
/* Recursively set up conversion info for the element type */
arg->u.domain.base = (PLyObToDatum *)
MemoryContextAllocZero(arg_mcxt, sizeof(PLyObToDatum));
PLy_output_setup_func(arg->u.domain.base, arg_mcxt,
typentry->domainBaseType,
typentry->domainBaseTypmod,
proc);
}
else if (typentry &&
IsTrueArrayType(typentry))
{
/* Standard array */
arg->func = PLySequence_ToArray;
/* Get base type OID to insert into constructed array */
/* (note this might not be the same as the immediate child type) */
arg->u.array.elmbasetype = getBaseType(typentry->typelem);
/* Recursively set up conversion info for the element type */
arg->u.array.elm = (PLyObToDatum *)
MemoryContextAllocZero(arg_mcxt, sizeof(PLyObToDatum));
PLy_output_setup_func(arg->u.array.elm, arg_mcxt,
typentry->typelem, typmod,
proc);
}
else if ((trfuncid = get_transform_tosql(typeOid,
proc->langid,
proc->trftypes)))
{
arg->func = PLyObject_ToTransform;
fmgr_info_cxt(trfuncid, &arg->u.transform.typtransform, arg_mcxt);
}
else if (typtype == TYPTYPE_COMPOSITE)
{
/* Named composite type, or RECORD */
arg->func = PLyObject_ToComposite;
/* We'll set up the per-field data later */
arg->u.tuple.recdesc = NULL;
arg->u.tuple.typentry = typentry;
arg->u.tuple.tupdescid = INVALID_TUPLEDESC_IDENTIFIER;
arg->u.tuple.atts = NULL;
arg->u.tuple.natts = 0;
/* Mark this invalid till needed, too */
arg->u.tuple.recinfunc.fn_oid = InvalidOid;
}
else
{
/* Scalar type, but we have a couple of special cases */
switch (typeOid)
{
case BOOLOID:
arg->func = PLyObject_ToBool;
break;
case BYTEAOID:
arg->func = PLyObject_ToBytea;
break;
default:
arg->func = PLyObject_ToScalar;
getTypeInputInfo(typeOid, &typinput, &arg->u.scalar.typioparam);
fmgr_info_cxt(typinput, &arg->u.scalar.typfunc, arg_mcxt);
break;
}
}
}
/*
* Recursively initialize the PLyDatumToOb structure(s) needed to construct
* a Python value from a SQL value of the specified typeOid/typmod.
* (But note that at this point we may have RECORDOID/-1, ie, an indeterminate
* record type.)
* proc is used to look up transform functions.
*/
void
PLy_input_setup_func(PLyDatumToOb *arg, MemoryContext arg_mcxt,
Oid typeOid, int32 typmod,
PLyProcedure *proc)
{
TypeCacheEntry *typentry;
char typtype;
Oid trfuncid;
Oid typoutput;
bool typisvarlena;
/* Since this is recursive, it could theoretically be driven to overflow */
check_stack_depth();
arg->typoid = typeOid;
arg->typmod = typmod;
arg->mcxt = arg_mcxt;
/*
* Fetch typcache entry for the target type, asking for whatever info
* we'll need later. RECORD is a special case: just treat it as composite
* without bothering with the typcache entry.
*/
if (typeOid != RECORDOID)
{
typentry = lookup_type_cache(typeOid, TYPECACHE_DOMAIN_BASE_INFO);
typtype = typentry->typtype;
arg->typbyval = typentry->typbyval;
arg->typlen = typentry->typlen;
arg->typalign = typentry->typalign;
}
else
{
typentry = NULL;
typtype = TYPTYPE_COMPOSITE;
/* hard-wired knowledge about type RECORD: */
arg->typbyval = false;
arg->typlen = -1;
arg->typalign = TYPALIGN_DOUBLE;
}
/*
* Choose conversion method. Note that transform functions are checked
* for composite and scalar types, but not for arrays or domains. This is
* somewhat historical, but we'd have a problem allowing them on domains,
* since we drill down through all levels of a domain nest without looking
* at the intermediate levels at all.
*/
if (typtype == TYPTYPE_DOMAIN)
{
/* Domain --- we don't care, just recurse down to the base type */
PLy_input_setup_func(arg, arg_mcxt,
typentry->domainBaseType,
typentry->domainBaseTypmod,
proc);
}
else if (typentry &&
IsTrueArrayType(typentry))
{
/* Standard array */
arg->func = PLyList_FromArray;
/* Recursively set up conversion info for the element type */
arg->u.array.elm = (PLyDatumToOb *)
MemoryContextAllocZero(arg_mcxt, sizeof(PLyDatumToOb));
PLy_input_setup_func(arg->u.array.elm, arg_mcxt,
typentry->typelem, typmod,
proc);
}
else if ((trfuncid = get_transform_fromsql(typeOid,
proc->langid,
proc->trftypes)))
{
arg->func = PLyObject_FromTransform;
fmgr_info_cxt(trfuncid, &arg->u.transform.typtransform, arg_mcxt);
}
else if (typtype == TYPTYPE_COMPOSITE)
{
/* Named composite type, or RECORD */
arg->func = PLyDict_FromComposite;
/* We'll set up the per-field data later */
arg->u.tuple.recdesc = NULL;
arg->u.tuple.typentry = typentry;
arg->u.tuple.tupdescid = INVALID_TUPLEDESC_IDENTIFIER;
arg->u.tuple.atts = NULL;
arg->u.tuple.natts = 0;
}
else
{
/* Scalar type, but we have a couple of special cases */
switch (typeOid)
{
case BOOLOID:
arg->func = PLyBool_FromBool;
break;
case FLOAT4OID:
arg->func = PLyFloat_FromFloat4;
break;
case FLOAT8OID:
arg->func = PLyFloat_FromFloat8;
break;
case NUMERICOID:
arg->func = PLyDecimal_FromNumeric;
break;
case INT2OID:
arg->func = PLyInt_FromInt16;
break;
case INT4OID:
arg->func = PLyInt_FromInt32;
break;
case INT8OID:
arg->func = PLyLong_FromInt64;
break;
case OIDOID:
arg->func = PLyLong_FromOid;
break;
case BYTEAOID:
arg->func = PLyBytes_FromBytea;
break;
default:
arg->func = PLyString_FromScalar;
getTypeOutputInfo(typeOid, &typoutput, &typisvarlena);
fmgr_info_cxt(typoutput, &arg->u.scalar.typfunc, arg_mcxt);
break;
}
}
}
/*
* Special-purpose input converters.
*/
static PyObject *
PLyBool_FromBool(PLyDatumToOb *arg, Datum d)
{
if (DatumGetBool(d))
Py_RETURN_TRUE;
Py_RETURN_FALSE;
}
static PyObject *
PLyFloat_FromFloat4(PLyDatumToOb *arg, Datum d)
{
return PyFloat_FromDouble(DatumGetFloat4(d));
}
static PyObject *
PLyFloat_FromFloat8(PLyDatumToOb *arg, Datum d)
{
return PyFloat_FromDouble(DatumGetFloat8(d));
}
static PyObject *
PLyDecimal_FromNumeric(PLyDatumToOb *arg, Datum d)
{
static PyObject *decimal_constructor;
char *str;
PyObject *pyvalue;
/* Try to import cdecimal. If it doesn't exist, fall back to decimal. */
if (!decimal_constructor)
{
PyObject *decimal_module;
decimal_module = PyImport_ImportModule("cdecimal");
if (!decimal_module)
{
PyErr_Clear();
decimal_module = PyImport_ImportModule("decimal");
}
if (!decimal_module)
PLy_elog(ERROR, "could not import a module for Decimal constructor");
decimal_constructor = PyObject_GetAttrString(decimal_module, "Decimal");
if (!decimal_constructor)
PLy_elog(ERROR, "no Decimal attribute in module");
}
str = DatumGetCString(DirectFunctionCall1(numeric_out, d));
pyvalue = PyObject_CallFunction(decimal_constructor, "s", str);
if (!pyvalue)
PLy_elog(ERROR, "conversion from numeric to Decimal failed");
return pyvalue;
}
static PyObject *
PLyInt_FromInt16(PLyDatumToOb *arg, Datum d)
{
return PyInt_FromLong(DatumGetInt16(d));
}
static PyObject *
PLyInt_FromInt32(PLyDatumToOb *arg, Datum d)
{
return PyInt_FromLong(DatumGetInt32(d));
}
static PyObject *
PLyLong_FromInt64(PLyDatumToOb *arg, Datum d)
{
return PyLong_FromLongLong(DatumGetInt64(d));
}
static PyObject *
PLyLong_FromOid(PLyDatumToOb *arg, Datum d)
{
return PyLong_FromUnsignedLong(DatumGetObjectId(d));
}
static PyObject *
PLyBytes_FromBytea(PLyDatumToOb *arg, Datum d)
{
text *txt = DatumGetByteaPP(d);
char *str = VARDATA_ANY(txt);
size_t size = VARSIZE_ANY_EXHDR(txt);
return PyBytes_FromStringAndSize(str, size);
}
/*
* Generic input conversion using a SQL type's output function.
*/
static PyObject *
PLyString_FromScalar(PLyDatumToOb *arg, Datum d)
{
char *x = OutputFunctionCall(&arg->u.scalar.typfunc, d);
PyObject *r = PyString_FromString(x);
pfree(x);
return r;
}
/*
* Convert using a from-SQL transform function.
*/
static PyObject *
PLyObject_FromTransform(PLyDatumToOb *arg, Datum d)
{
Datum t;
t = FunctionCall1(&arg->u.transform.typtransform, d);
return (PyObject *) DatumGetPointer(t);
}
/*
* Convert a SQL array to a Python list.
*/
static PyObject *
PLyList_FromArray(PLyDatumToOb *arg, Datum d)
{
ArrayType *array = DatumGetArrayTypeP(d);
PLyDatumToOb *elm = arg->u.array.elm;
int ndim;
int *dims;
char *dataptr;
bits8 *bitmap;
int bitmask;
if (ARR_NDIM(array) == 0)
return PyList_New(0);
/* Array dimensions and left bounds */
ndim = ARR_NDIM(array);
dims = ARR_DIMS(array);
Assert(ndim <= MAXDIM);
/*
* We iterate the SQL array in the physical order it's stored in the
* datum. For example, for a 3-dimensional array the order of iteration
* would be the following: [0,0,0] elements through [0,0,k], then [0,1,0]
* through [0,1,k] till [0,m,k], then [1,0,0] through [1,0,k] till
* [1,m,k], and so on.
*
* In Python, there are no multi-dimensional lists as such, but they are
* represented as a list of lists. So a 3-d array of [n,m,k] elements is a
* list of n m-element arrays, each element of which is k-element array.
* PLyList_FromArray_recurse() builds the Python list for a single
* dimension, and recurses for the next inner dimension.
*/
dataptr = ARR_DATA_PTR(array);
bitmap = ARR_NULLBITMAP(array);
bitmask = 1;
return PLyList_FromArray_recurse(elm, dims, ndim, 0,
&dataptr, &bitmap, &bitmask);
}
static PyObject *
PLyList_FromArray_recurse(PLyDatumToOb *elm, int *dims, int ndim, int dim,
char **dataptr_p, bits8 **bitmap_p, int *bitmask_p)
{
int i;
PyObject *list;
list = PyList_New(dims[dim]);
if (!list)
return NULL;
if (dim < ndim - 1)
{
/* Outer dimension. Recurse for each inner slice. */
for (i = 0; i < dims[dim]; i++)
{
PyObject *sublist;
sublist = PLyList_FromArray_recurse(elm, dims, ndim, dim + 1,
dataptr_p, bitmap_p, bitmask_p);
PyList_SET_ITEM(list, i, sublist);
}
}
else
{
/*
* Innermost dimension. Fill the list with the values from the array
* for this slice.
*/
char *dataptr = *dataptr_p;
bits8 *bitmap = *bitmap_p;
int bitmask = *bitmask_p;
for (i = 0; i < dims[dim]; i++)
{
/* checking for NULL */
if (bitmap && (*bitmap & bitmask) == 0)
{
Py_INCREF(Py_None);
PyList_SET_ITEM(list, i, Py_None);
}
else
{
Datum itemvalue;
itemvalue = fetch_att(dataptr, elm->typbyval, elm->typlen);
PyList_SET_ITEM(list, i, elm->func(elm, itemvalue));
dataptr = att_addlength_pointer(dataptr, elm->typlen, dataptr);
dataptr = (char *) att_align_nominal(dataptr, elm->typalign);
}
/* advance bitmap pointer if any */
if (bitmap)
{
bitmask <<= 1;
if (bitmask == 0x100 /* (1<<8) */ )
{
bitmap++;
bitmask = 1;
}
}
}
*dataptr_p = dataptr;
*bitmap_p = bitmap;
*bitmask_p = bitmask;
}
return list;
}
/*
* Convert a composite SQL value to a Python dict.
*/
static PyObject *
PLyDict_FromComposite(PLyDatumToOb *arg, Datum d)
{
PyObject *dict;
HeapTupleHeader td;
Oid tupType;
int32 tupTypmod;
TupleDesc tupdesc;
HeapTupleData tmptup;
td = DatumGetHeapTupleHeader(d);
/* Extract rowtype info and find a tupdesc */
tupType = HeapTupleHeaderGetTypeId(td);
tupTypmod = HeapTupleHeaderGetTypMod(td);
tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
/* Set up I/O funcs if not done yet */
PLy_input_setup_tuple(arg, tupdesc,
PLy_current_execution_context()->curr_proc);
/* Build a temporary HeapTuple control structure */
tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
tmptup.t_data = td;
dict = PLyDict_FromTuple(arg, &tmptup, tupdesc, true);
ReleaseTupleDesc(tupdesc);
return dict;
}
/*
* Transform a tuple into a Python dict object.
*/
static PyObject *
PLyDict_FromTuple(PLyDatumToOb *arg, HeapTuple tuple, TupleDesc desc, bool include_generated)
{
PyObject *volatile dict;
/* Simple sanity check that desc matches */
Assert(desc->natts == arg->u.tuple.natts);
dict = PyDict_New();
if (dict == NULL)
return NULL;
PG_TRY();
{
int i;
for (i = 0; i < arg->u.tuple.natts; i++)
{
PLyDatumToOb *att = &arg->u.tuple.atts[i];
Form_pg_attribute attr = TupleDescAttr(desc, i);
char *key;
Datum vattr;
bool is_null;
PyObject *value;
if (attr->attisdropped)
continue;
if (attr->attgenerated)
{
/* don't include unless requested */
if (!include_generated)
continue;
}
key = NameStr(attr->attname);
vattr = heap_getattr(tuple, (i + 1), desc, &is_null);
if (is_null)
PyDict_SetItemString(dict, key, Py_None);
else
{
value = att->func(att, vattr);
PyDict_SetItemString(dict, key, value);
Py_DECREF(value);
}
}
}
PG_CATCH();
{
Py_DECREF(dict);
PG_RE_THROW();
}
PG_END_TRY();
return dict;
}
/*
* Convert a Python object to a PostgreSQL bool datum. This can't go
* through the generic conversion function, because Python attaches a
* Boolean value to everything, more things than the PostgreSQL bool
* type can parse.
*/
static Datum
PLyObject_ToBool(PLyObToDatum *arg, PyObject *plrv,
bool *isnull, bool inarray)
{
if (plrv == Py_None)
{
*isnull = true;
return (Datum) 0;
}
*isnull = false;
return BoolGetDatum(PyObject_IsTrue(plrv));
}
/*
* Convert a Python object to a PostgreSQL bytea datum. This doesn't
* go through the generic conversion function to circumvent problems
* with embedded nulls. And it's faster this way.
*/
static Datum
PLyObject_ToBytea(PLyObToDatum *arg, PyObject *plrv,
bool *isnull, bool inarray)
{
PyObject *volatile plrv_so = NULL;
Datum rv = (Datum) 0;
if (plrv == Py_None)
{
*isnull = true;
return (Datum) 0;
}
*isnull = false;
plrv_so = PyObject_Bytes(plrv);
if (!plrv_so)
PLy_elog(ERROR, "could not create bytes representation of Python object");
PG_TRY();
{
char *plrv_sc = PyBytes_AsString(plrv_so);
size_t len = PyBytes_Size(plrv_so);
size_t size = len + VARHDRSZ;
bytea *result = palloc(size);
SET_VARSIZE(result, size);
memcpy(VARDATA(result), plrv_sc, len);
rv = PointerGetDatum(result);
}
PG_FINALLY();
{
Py_XDECREF(plrv_so);
}
PG_END_TRY();
return rv;
}
/*
* Convert a Python object to a composite type. First look up the type's
* description, then route the Python object through the conversion function
* for obtaining PostgreSQL tuples.
*/
static Datum
PLyObject_ToComposite(PLyObToDatum *arg, PyObject *plrv,
bool *isnull, bool inarray)
{
Datum rv;
TupleDesc desc;
if (plrv == Py_None)
{
*isnull = true;
return (Datum) 0;
}
*isnull = false;
/*
* The string conversion case doesn't require a tupdesc, nor per-field
* conversion data, so just go for it if that's the case to use.
*/
if (PyString_Check(plrv) || PyUnicode_Check(plrv))
return PLyString_ToComposite(arg, plrv, inarray);
/*
* If we're dealing with a named composite type, we must look up the
* tupdesc every time, to protect against possible changes to the type.
* RECORD types can't change between calls; but we must still be willing
* to set up the info the first time, if nobody did yet.
*/
if (arg->typoid != RECORDOID)
{
desc = lookup_rowtype_tupdesc(arg->typoid, arg->typmod);
/* We should have the descriptor of the type's typcache entry */
Assert(desc == arg->u.tuple.typentry->tupDesc);
/* Detect change of descriptor, update cache if needed */
if (arg->u.tuple.tupdescid != arg->u.tuple.typentry->tupDesc_identifier)
{
PLy_output_setup_tuple(arg, desc,
PLy_current_execution_context()->curr_proc);
arg->u.tuple.tupdescid = arg->u.tuple.typentry->tupDesc_identifier;
}
}
else
{
desc = arg->u.tuple.recdesc;
if (desc == NULL)
{
desc = lookup_rowtype_tupdesc(arg->typoid, arg->typmod);
arg->u.tuple.recdesc = desc;
}
else
{
/* Pin descriptor to match unpin below */
PinTupleDesc(desc);
}
}
/* Simple sanity check on our caching */
Assert(desc->natts == arg->u.tuple.natts);
/*
* Convert, using the appropriate method depending on the type of the
* supplied Python object.
*/