-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfunction.c
More file actions
1230 lines (1074 loc) · 27.6 KB
/
function.c
File metadata and controls
1230 lines (1074 loc) · 27.6 KB
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
/*
* Postgres functions
*/
#include <setjmp.h>
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <compile.h>
#include <structmember.h>
#include "postgres.h"
#include "fmgr.h"
#include "funcapi.h"
#include "access/heapam.h"
#include "access/tupdesc.h"
#include "access/transam.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_type.h"
#include "executor/spi.h"
#include "mb/pg_wchar.h"
#include "nodes/params.h"
#include "parser/parse_func.h"
#include "tcop/dest.h"
#include "tcop/tcopprot.h"
#include "utils/memutils.h"
#include "utils/array.h"
#include "utils/datum.h"
#include "utils/elog.h"
#include "utils/palloc.h"
#include "utils/builtins.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
#include "utils/tuplestore.h"
#include "pypg/python.h"
#include "pypg/postgres.h"
#include "pypg/pl.h"
#include "pypg/extension.h"
#include "pypg/error.h"
#include "pypg/type/type.h"
#include "pypg/type/object.h"
#include "pypg/type/system.h"
#include "pypg/type/record.h"
#include "pypg/tupledesc.h"
#include "pypg/function.h"
PyObj Py_builtins_module = NULL;
PyObj Py_compile_ob = NULL;
PyObj PYSTR(exec) = NULL;
PyObj Py_linecache_updatecache_ob = NULL;
/*
* PyPgFunction_get_source - get the function's prosrc
*/
PyObj
PyPgFunction_get_source(PyObj func)
{
PyObj src = NULL;
Assert(func != NULL);
Assert(PyPgFunction_Check(func));
src = PyPgFunction_GetSource(func);
Assert(src != NULL);
Py_INCREF(src);
return(src);
}
/*
* PyPgFunction_get_code - compile the code from the source
*/
PyObj
PyPgFunction_get_code(PyObj func)
{
PyObj prosrc, cargs, rob;
Assert(func != NULL);
Assert(PyPgFunction_Check(func));
Assert(PyPgFunction_GetFilename(func) != NULL);
prosrc = PyPgFunction_get_source(func);
if (prosrc == NULL)
return(NULL);
if (prosrc == Py_None)
{
PyErr_SetString(PyExc_TypeError, "function has no source to compile");
Py_DECREF(prosrc);
return(NULL);
}
cargs = PyTuple_New(3);
if (cargs == NULL)
return(NULL);
PyTuple_SET_ITEM(cargs, 0, prosrc);
PyTuple_SET_ITEM(cargs, 1, PyPgFunction_GetFilename(func));
PyTuple_SET_ITEM(cargs, 2, PYSTR(exec));
Py_INCREF(PyPgFunction_GetFilename(func));
Py_INCREF(PYSTR(exec));
rob = PyObject_CallObject(Py_compile_ob, cargs);
Py_DECREF(cargs);
return(rob);
}
/*
* PyPgFunction_load_module - create and load the module
*
* This execute the module body in a new module object iff the module does not
* already exist in sys.modules.
*
* The PL protocol checks are not done here because this could be called from
* the code of another function. It's the caller's responsibility to ensure that
* the appropriate checks are being made at the appropriate time.
*/
PyObj
PyPgFunction_load_module(PyObj func)
{
PyObj modules, module, modname, d, code, evalr;
int rv;
Assert(func != NULL);
Assert(PyPgFunction_Check(func));
modules = PyImport_GetModuleDict();
/*
* Module already loaded? Return it.
*/
rv = PySequence_Contains(modules, PyPgFunction_GetPyUnicodeOid(func));
if (rv == -1)
return(NULL);
else if (rv == 1)
{
/*
* If this returns NULL, it's probably some weird race condition...
* The check above said it exists, so let's trust it...
*/
return(PyObject_GetItem(modules, PyPgFunction_GetPyUnicodeOid(func)));
}
modname = PyPgFunction_GetPyUnicodeOid(func);
Py_INCREF(modname);
PyObject_StrBytes(&modname);
if (modname == NULL)
return(NULL);
/*
* No module present, initialize a new one.
*/
module = PyModule_New(PyBytes_AS_STRING(modname));
Py_DECREF(modname);
if (module == NULL)
return(NULL);
/* Use the */
d = PyModule_GetDict(module);
if (d == NULL)
{
elog(WARNING, "could not get Python module dictionary");
Py_DECREF(module);
return(NULL);
}
/*
* __loader__ PEP302 support.
* This is what linecache uses to access the function's source
*/
if (PyDict_SetItemString(d, "__loader__", func) != 0)
{
/*
* linecache can't do anything if there's no loader.
*/
Py_DECREF(module);
return(NULL);
}
if (PyDict_SetItemString(d, "__file__", PyPgFunction_GetFilename(func)) != 0)
goto fail;
if (PyDict_SetItemString(d, "__builtins__", Py_builtins_module) != 0)
goto fail;
if (PyDict_SetItemString(d, "__func__", func) != 0)
goto fail;
/*
* Module has to exist in sys.modules before code is loaded.
*/
if (PyObject_SetItem(modules, PyPgFunction_GetPyUnicodeOid(func), module) != 0)
goto fail;
/*
* Hasn't been loaded into sys.modules yet.
*/
code = PyPgFunction_get_code(func);
if (code == NULL)
goto fail;
/*
* Module context, therefore locals and globals are the same object.
*/
evalr = PyEval_EvalCode(code, d, d);
if (evalr == NULL)
{
/*
* Code evaluation failed.
* Remove the junk module from sys.modules *after* updating linecache.
*/
PyObject_DelItem(modules, PyPgFunction_GetPyUnicodeOid(func));
goto fail;
}
Py_DECREF(evalr);
Py_DECREF(code);
return(module);
fail:
/*
* Something went wrong.
* Update the linecache so that the source is accessible.
*/
Assert(d != NULL);
/*
* Ignore any errors here; should cause a context chain.
*/
{
PyObj exc, val, tb;
PyErr_Fetch(&exc, &val, &tb);
PyObject_CallFunction(Py_linecache_updatecache_ob, "OO",
PyPgFunction_GetFilename(func), d);
PyErr_Restore(exc,val,tb);
Py_XDECREF(code);
Py_XDECREF(module);
return(NULL);
}
}
/*
* Create a TupleDesc from a given pg_proc tuple's proarginfo column
*/
TupleDesc
TupleDesc_From_pg_proc_arginfo(HeapTuple ht)
{
int16 pronargs;
Datum proargtypes_datum, proargnames_datum;
bool isnull;
Oid *types;
char **names = NULL;
int nnames;
TupleDesc td;
pronargs = DatumGetInt16(SysCacheGetAttr(PROCOID, ht,
Anum_pg_proc_pronargs, &isnull)
);
if (isnull)
elog(ERROR, "pronargs is NULL");
proargtypes_datum = SysCacheGetAttr(PROCOID, ht,
Anum_pg_proc_proargtypes, &isnull);
if (isnull)
elog(ERROR, "proargtypes is NULL");
types = (Oid *) ARR_DATA_PTR(DatumGetArrayTypeP(proargtypes_datum));
proargnames_datum = SysCacheGetAttr(PROCOID, ht,
Anum_pg_proc_proargnames, &isnull);
if (isnull == false)
{
ArrayType *name_array = NULL;
Datum *name_datums;
bool *name_nulls;
/* INOUT Parameters may adjust the location of the argument name */
bool modes_isnull;
Datum proargmodes_datum;
name_array = DatumGetArrayTypeP(proargnames_datum);
deconstruct_array(
name_array, ARR_ELEMTYPE(name_array),
-1, false, 'i', &name_datums,
&name_nulls, &nnames
);
if (nnames < pronargs)
elog(ERROR, "too few names in proargnames");
if (nnames > 0)
{
names = palloc0(sizeof(char *) * pronargs);
proargmodes_datum = SysCacheGetAttr(PROCOID, ht,
Anum_pg_proc_proargmodes, &modes_isnull);
if (modes_isnull == false)
{
char *modes;
int i, k;
modes = (char *) ARR_DATA_PTR(DatumGetArrayTypeP(proargmodes_datum));
for (i = 0, k = 0; i < nnames; ++i)
{
switch (modes[i])
{
case 'b':
case 'i':
{
Datum name_d;
name_d = name_datums[i];
names[k] = (char *) DirectFunctionCall1(textout, name_d);
++k;
}
break;
case 'o':
break;
default:
{
elog(ERROR, "unknown mode \"%c\" for argument %d",
modes[i], i);
}
break;
}
}
}
else /* Don't process proargnames down here if modes is valid */
{
int i;
for (i = 0; i < nnames; ++i)
{
Datum name_d;
name_d = name_datums[i];
names[i] = (char *) DirectFunctionCall1(textout, name_d);
}
}
}
}
td = TupleDesc_FromNamesAndOids(pronargs, (const char **) names, types);
if (names != NULL)
{
int i;
if (nnames > 0)
for (i = 0; i < pronargs; ++i)
pfree(names[i]);
pfree(names);
}
return(td);
}
/*
* invalid_fullname - Used by the PEP302 interfaces
*
* This will determine whether or not the given "fullname" argument
* corresponds to an identifier of the function.
*
* While normally used only in conjunction with a reference to "__name__",
* other forms of the identifier are allowed for mere convenience.
*/
static bool
invalid_fullname(PyObj self, PyObj args, PyObj kw)
{
char *words[] = {"fullname", NULL};
PyObj fullname = NULL;
Oid fn_oid;
if (!PyPgFunction_CheckExact(self))
{
PyErr_SetString(PyExc_TypeError,
"loader method requires Postgres.Function type");
return(true);
}
if (!PyArg_ParseTupleAndKeywords(args, kw, "|O", words, &fullname))
return(true);
if (fullname == NULL
|| fullname == PyPgFunction_GetPyUnicodeOid(self)
|| fullname == PyPgFunction_GetPyLongOid(self))
return(false);
/*
* fullname is given and it's not an exact Oid object,
* so convert it to a real Oid and compare.
*/
if (Oid_FromPyObject(fullname, &fn_oid))
return(true);
if (PyPgFunction_GetOid(self) == fn_oid)
return(false);
PyErr_Format(PyExc_ImportError,
"loader cannot import module named '%lu'", fn_oid);
return(true);
}
/*
* Postgres FUNCTIONs are not packages. [PEP302]
*/
static PyObj
is_package(PyObj self, PyObj args, PyObj kw)
{
if (invalid_fullname(self, args, kw))
return(NULL);
Py_INCREF(Py_False);
return(Py_False);
}
/*
* Get the function source code. [PEP302]
*/
static PyObj
get_source(PyObj self, PyObj args, PyObj kw)
{
if (invalid_fullname(self, args, kw))
return(NULL);
return(PyPgFunction_get_source(self));
}
/*
* Get the function's compiled code object. [PEP302]
*/
static PyObj
get_code(PyObj self, PyObj args, PyObj kw)
{
if (invalid_fullname(self, args, kw))
return(NULL);
return(PyPgFunction_get_code(self));
}
/*
* def load_module(fullname) -> types.ModuleType
*
* Evaluate the function's code in a new module
* or if the fullname exists in sys.modules, return
* the existing module. [PEP302]
*
* This code must go through pl_handler in order to properly load the
* module. The execution context can dictate much about what happens during
* load time.
*
* i.e., tricky shit happens here. It may be preferrable to make the execution
* context rigging more accessible, but for now, it's the handler's job.
*/
static PyObj
load_module(PyObj self, PyObj args, PyObj kw)
{
MemoryContext former = CurrentMemoryContext;
volatile PyObj rob = NULL;
FmgrInfo flinfo;
FunctionCallInfoData fcinfo;
if (invalid_fullname(self, args, kw))
return(NULL);
/*
* Disallow execution of "anonymous" functions.
*/
flinfo.fn_addr = PyPgFunction_GetPGFunction(self);
flinfo.fn_oid = PyPgFunction_GetOid(self);
flinfo.fn_retset = false;
if (flinfo.fn_addr == NULL || flinfo.fn_oid == InvalidOid)
{
PyErr_SetString(PyExc_TypeError, "internal functions cannot be preloaded");
return(NULL);
}
flinfo.fn_nargs = -1;
flinfo.fn_extra = NULL;
flinfo.fn_mcxt = CurrentMemoryContext;
flinfo.fn_expr = NULL;
fcinfo.nargs = -1;
fcinfo.flinfo = &flinfo;
fcinfo.context = NULL;
fcinfo.resultinfo = NULL;
/*
* Better be true afterwards.
*/
fcinfo.isnull = false;
SPI_push();
PG_TRY();
{
rob = (PyObj) DatumGetPointer(FunctionCallInvoke(&fcinfo));
}
PG_CATCH();
{
rob = NULL;
PyErr_SetPgError(false);
}
PG_END_TRY();
SPI_pop();
MemoryContextSwitchTo(former);
if (fcinfo.isnull == false)
{
PyErr_SetString(PyExc_RuntimeError,
"function module load protocol did not set isnull");
rob = NULL;
}
Py_XINCREF(rob);
return(rob);
}
/*
* Create a PyPgFunction from an Oid object
*/
static PyObj
find_module(PyObj typ, PyObj args, PyObj kw)
{
char *words[] = {"fullname", "path", NULL};
PyObj fullname, path;
Oid fn_oid;
if (typ != (PyObj) &PyPgFunction_Type)
{
PyErr_SetString(PyExc_TypeError,
"find_module expects Postgres.Function as its first argument");
return(NULL);
}
if (!PyArg_ParseTupleAndKeywords(args, kw, "O|O", words, &fullname, &path))
return(NULL);
if (path != NULL && path != Py_None)
{
PyErr_SetString(PyExc_ImportError, "Postgres functions are top-level modules");
return(NULL);
}
if (Oid_FromPyObject(fullname, &fn_oid))
return(NULL);
return(PyPgFunction_FromOid(fn_oid));
}
static PyMethodDef PyPgFunction_Methods[] = {
/*
* PEP 302 Interfaces
*
* These interfaces should only be used on Python functions
*/
{"is_package", (PyCFunction) is_package, METH_VARARGS|METH_KEYWORDS,
PyDoc_STR("Always returns false. [PEP302 interface]")},
{"get_source", (PyCFunction) get_source, METH_VARARGS|METH_KEYWORDS,
PyDoc_STR("Get the function's procedure source [PEP302 interface]")},
{"get_code", (PyCFunction) get_code, METH_VARARGS|METH_KEYWORDS,
PyDoc_STR("Return the code of the source. [PEP302 interface]")},
{"load_module", (PyCFunction) load_module, METH_VARARGS|METH_KEYWORDS,
PyDoc_STR("Return a module based on the source. [PEP302 interface]")},
{"find_module", (PyCFunction) find_module, METH_VARARGS|METH_KEYWORDS|METH_CLASS,
PyDoc_STR("Get a Postgres.Function--loader--object based on the given fullname. [PEP302 interface]")},
{NULL}
};
static PyObj
func_get_pronamespace(PyObj self, void *closure)
{
PyObj rob;
rob = PyLong_FromUnsignedLong(PyPgFunction_GetNamespace(self));
return(rob);
}
static PyObj
func_get_prolang(PyObj self, void *closure)
{
PyObj rob;
rob = PyLong_FromUnsignedLong(PyPgFunction_GetLanguage(self));
return(rob);
}
static PyGetSetDef PyPgFunction_GetSet[] = {
{"namespace", func_get_pronamespace, NULL, PyDoc_STR("get the namespace oid")},
{"language", func_get_prolang, NULL, PyDoc_STR("get the language oid")},
{NULL,}
};
static PyMemberDef PyPgFunction_Members[] = {
{"oid", T_OBJECT, offsetof(struct PyPgFunction, fn_oid_int), READONLY,
PyDoc_STR("pg_proc entry's Oid")},
{"oidstr", T_OBJECT, offsetof(struct PyPgFunction, fn_oid_str), READONLY,
PyDoc_STR("pg_proc entry's Oid as a str object")},
{"nspname", T_OBJECT, offsetof(struct PyPgFunction, fn_nspname_str), READONLY,
PyDoc_STR("namespace name when the function was loaded")},
{"filename", T_OBJECT, offsetof(struct PyPgFunction, fn_filename_str), READONLY,
PyDoc_STR("regprocedure-like representation of the procedure's identifier")},
{"input", T_OBJECT, offsetof(struct PyPgFunction, fn_input), READONLY,
PyDoc_STR("the function's parameter descriptor")},
{"output", T_OBJECT, offsetof(struct PyPgFunction, fn_output), READONLY,
PyDoc_STR("the function's results")},
{"stateful", T_BOOL, offsetof(struct PyPgFunction, fn_stateful), 0,
PyDoc_STR("the function returns a send'able iterator(generator)")},
{NULL,}
};
static void
func_dealloc(PyObj self)
{
PyObj ob;
ob = PyPgFunction_GetOutput(self);
if (ob != NULL)
{
PyPgFunction_SetOutput(self, NULL);
Py_DECREF(ob);
}
ob = PyPgFunction_GetInput(self);
if (ob != NULL)
{
PyPgFunction_SetInput(self, NULL);
Py_DECREF(ob);
}
ob = PyPgFunction_GetPyUnicodeOid(self);
if (ob != NULL)
{
PyPgFunction_SetPyUnicodeOid(self, NULL);
Py_DECREF(ob);
}
ob = PyPgFunction_GetPyLongOid(self);
if (ob != NULL)
{
PyPgFunction_SetPyLongOid(self, NULL);
Py_DECREF(ob);
}
ob = PyPgFunction_GetNamespaceName(self);
if (ob != NULL)
{
PyPgFunction_SetNamespaceName(self, NULL);
Py_DECREF(ob);
}
ob = PyPgFunction_GetFilename(self);
if (ob != NULL)
{
PyPgFunction_SetFilename(self, NULL);
Py_DECREF(ob);
}
ob = PyPgFunction_GetSource(self);
if (ob != NULL)
{
PyPgFunction_SetSource(self, NULL);
Py_DECREF(ob);
}
self->ob_type->tp_free(self);
}
static PyObj
func_call(PyObj self, PyObj args, PyObj kw)
{
MemoryContext former = CurrentMemoryContext;
PyObj fn_input, fn_output, input, rob = NULL;
TupleDesc td;
FmgrInfo flinfo;
FunctionCallInfoData fcinfo;
volatile Datum datum = 0;
/*
* Disallow execution of "anonymous" functions.
*/
flinfo.fn_addr = PyPgFunction_GetPGFunction(self);
flinfo.fn_oid = PyPgFunction_GetOid(self);
flinfo.fn_retset = PyPgFunction_GetReturnsSet(self);
if (flinfo.fn_addr == NULL || flinfo.fn_oid == InvalidOid)
{
PyErr_SetString(PyExc_TypeError, "internal functions are not directly callable");
return(NULL);
}
if (flinfo.fn_retset)
{
PyErr_SetString(PyExc_NotImplementedError,
"cannot directly execute set returning functions");
return(NULL);
}
fn_input = PyPgFunction_GetInput(self);
fn_output = PyPgFunction_GetOutput(self);
if (PyPgTupleDesc_IsPolymorphic(fn_input) ||
PyPgType_IsPolymorphic(fn_output))
{
PyErr_SetString(PyExc_NotImplementedError,
"cannot directly execute polymorphic functions");
return(NULL);
}
if (PyPgType_GetOid(fn_output) == TRIGGEROID)
{
PyErr_SetString(PyExc_NotImplementedError,
"cannot directly execute TRIGGER returning functions");
return(NULL);
}
/* No access if failed transaction */
if (DB_IS_NOT_READY())
return(NULL);
td = PyPgTupleDesc_GetTupleDesc(fn_input);
/*
* Normalize the parameters.
*/
input = PyTuple_FromTupleDescAndParameters(td, args, kw);
if (input == NULL)
return(NULL);
flinfo.fn_nargs = td->natts;
flinfo.fn_extra = NULL;
flinfo.fn_mcxt = CurrentMemoryContext;
flinfo.fn_expr = NULL;
fcinfo.flinfo = &flinfo;
fcinfo.context = NULL;
fcinfo.resultinfo = NULL;
fcinfo.isnull = false;
/*
* Custom built descriptor; no dropped attributes.
*/
fcinfo.nargs = td->natts;
SPI_push();
PG_TRY();
{
Py_BuildDatumsAndNulls(td,
PyPgTupleDesc_GetTypesTuple(fn_input),
input, fcinfo.arg, fcinfo.argnull);
datum = FunctionCallInvoke(&fcinfo);
/*
* Special casing void to avoid the singleton.
*/
if (fcinfo.isnull ||
PyPgType_GetOid(fn_output) == VOIDOID)
{
rob = Py_None;
Py_INCREF(rob);
}
else
{
/*
* Some functions will return a parameter that its given.
* This is problematic if we are going to free the output
* after re-allocating as a Postgres.Object.
*/
if (PyPgType_ShouldFree(fn_output))
{
int i;
/*
* Scan for !typbyval parameters.
* When one is found, compare the datum to the result datum.
*/
for (i = 0; i < PyTuple_GET_SIZE(input); ++i)
{
PyObj param = PyTuple_GET_ITEM(input, i);
/*
* It's tempting to check the types first, but in situations
* of functions doing binary compatible coercion, it would be a
* mistake.
*/
if (PyPgType_ShouldFree(Py_TYPE(param)))
{
if (PyPgObject_GetDatum(param) == datum)
{
/*
* It's the same Datum of an argument,
* inc the ref and return the param.
*/
if (fn_output == (PyObj) Py_TYPE(param))
{
rob = param;
Py_INCREF(rob);
}
else
{
/*
* It's the same Datum, but a different type.
* Make a Copy.
*/
rob = PyPgObject_New(fn_output, datum);
}
break;
}
}
}
/*
* It's a newly allocated result? (not an argument)
*/
if (rob == NULL)
{
/*
* New result, Datum is copied into the PythonMemoryContext
*/
rob = PyPgObject_New(fn_output, datum);
/*
* Cleanup.
*/
pfree(DatumGetPointer(datum));
}
}
else
{
/* Not pfree'ing typbyval, so no need to check parameters. */
rob = PyPgObject_New(fn_output, datum);
}
}
}
PG_CATCH();
{
Py_XDECREF(rob);
rob = NULL;
PyErr_SetPgError(false);
}
PG_END_TRY();
SPI_pop();
Py_DECREF(input);
MemoryContextSwitchTo(former);
return(rob);
}
static PyObj
func_new_from_oid(PyTypeObject *subtype, Oid fn_oid, PyObj fn_oid_int, PyObj fn_oid_str)
{
volatile HeapTuple ht = NULL;
volatile PyObj rob = NULL;
Assert(OidIsValid(fn_oid));
Assert(fn_oid_int != NULL);
Assert(fn_oid_str != NULL);
rob = subtype->tp_alloc(subtype, 0);
if (rob == NULL)
return(NULL);
PyPgFunction_SetOid(rob, fn_oid);
PyPgFunction_SetStateful(rob, false);
Py_INCREF(fn_oid_int);
Py_INCREF(fn_oid_str);
PyPgFunction_SetPyLongOid(rob, fn_oid_int);
PyPgFunction_SetPyUnicodeOid(rob, fn_oid_str);
/*
* Collect the Function information from the system cache
*/
PG_TRY();
{
Form_pg_proc ps;
Form_pg_namespace ns;
FmgrInfo flinfo;
text *prosrc;
Datum prosrc_datum;
bool isnull = true;
const char *filename = NULL, *nspname, *q_nspname;
TupleDesc argdesc = NULL, result_desc = NULL;
Oid prorettype = InvalidOid;
PyObj id_str_ob = NULL, nspname_str_ob = NULL;
PyObj filename_str_ob = NULL, q_nspname_str_ob = NULL;
PyObj output = NULL, src = NULL;
PyObj input;
ht = SearchSysCache(PROCOID, fn_oid, 0, 0, 0);
if (!HeapTupleIsValid(ht))
{
ereport(ERROR,(
errcode(ERRCODE_UNDEFINED_FUNCTION),
errmsg("failed to find function at oid %d", fn_oid)
));
}
PyPgFunction_SetXMin(rob, HeapTupleHeaderGetXmin(ht->t_data));
PyPgFunction_SetItemPointer(rob, &(ht->t_self));
ps = (Form_pg_proc) GETSTRUCT(ht);
PyPgFunction_SetNamespace(rob, ps->pronamespace);
PyPgFunction_SetLanguage(rob, ps->prolang);
PyPgFunction_SetReturnsSet(rob, ps->proretset);
PyPgFunction_SetVolatile(rob, ps->provolatile);
prorettype = ps->prorettype;
prosrc_datum = SysCacheGetAttr(
PROCOID, ht, Anum_pg_proc_prosrc, &isnull);
if (!isnull)
{
prosrc = DatumGetTextPCopy(prosrc_datum);
src = PyUnicode_FromTEXT(prosrc);
PyPgFunction_SetSource(rob, src);
pfree(prosrc);
prosrc = NULL;
}
else
{
src = Py_None;
Py_INCREF(src);
PyPgFunction_SetSource(rob, src);
}
if (src == NULL)
PyErr_RelayException();
/*
* Get the function's address.
*/
fmgr_info(fn_oid, &flinfo);
PyPgFunction_SetPGFunction(rob, flinfo.fn_addr);
/*
* Build function parameters TupleDesc
*/
if (ps->pronargs > 0)
{
argdesc = TupleDesc_From_pg_proc_arginfo(ht);
input = PyPgTupleDesc_FromCopy(argdesc);
if (input == NULL)
PyErr_RelayException();
PyPgFunction_SetInput(rob, input);
FreeTupleDesc(argdesc);
}
else
{
Py_INCREF(EmptyPyPgTupleDesc);
PyPgFunction_SetInput(rob, EmptyPyPgTupleDesc);
}
/*
* If it's a registered composite,
* PyPgType_FromOid will resolve that below.
*/
if (prorettype == RECORDOID)
{
/*
* Otherwise, build out a function result tupdesc.
*/
result_desc = build_function_result_tupdesc_t(ht);
if (result_desc != NULL)
{
/*
* Anonymous composite returned by function.
*/
output = PyPgType_FromTupleDesc(result_desc);
PyPgFunction_SetOutput(rob, output);
FreeTupleDesc(result_desc);
/*
* We will certainly be using it, so bless it right now iff
* it's *not* polymorphic.
*/
if (output && !PyPgType_IsPolymorphic(output))
BlessTupleDesc(PyPgType_GetTupleDesc(output));
}
else
{
/*
* ew..
*/
goto lookup_output_type;
}
}
else
{
lookup_output_type:
output = PyPgType_FromOid(prorettype);
if (output == NULL)
PyErr_RelayException();
PyPgFunction_SetOutput(rob, output);
}
RELEASESYSCACHE(&ht);
/*
* Don't worry *too* much about leaking memory.
*/
filename = format_procedure(fn_oid);
Assert(filename != NULL);
ht = SearchSysCache(NAMESPACEOID,
PyPgFunction_GetNamespace(rob), 0, 0, 0);
if (!HeapTupleIsValid(ht))
{
pfree((char *) filename);
elog(ERROR, "function %u namespace %u does not exist",
fn_oid, PyPgFunction_GetNamespace(rob));
}