aboutsummaryrefslogtreecommitdiff
path: root/src/pl/plpython/plpython.c
blob: 3483d21ae3349eb834d7579b71827b79e0542040 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
/**********************************************************************
 * plpython.c - python as a procedural language for PostgreSQL
 *
 * This software is copyright by Andrew Bosma
 * but is really shameless cribbed from pltcl.c by Jan Weick, and
 * plperl.c by Mark Hollomon.
 *
 * The author hereby grants permission to use, copy, modify,
 * distribute, and license this software and its documentation for any
 * purpose, provided that existing copyright notices are retained in
 * all copies and that this notice is included verbatim in any
 * distributions. No written agreement, license, or royalty fee is
 * required for any of the authorized uses.  Modifications to this
 * software may be copyrighted by their author and need not follow the
 * licensing terms described here, provided that the new terms are
 * clearly indicated on the first page of each file where they apply.
 *
 * IN NO EVENT SHALL THE AUTHOR OR DISTRIBUTORS BE LIABLE TO ANY PARTY
 * FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
 * ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
 * DERIVATIVES THEREOF, EVEN IF THE AUTHOR HAVE BEEN ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * THE AUTHOR AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND
 * NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS,
 * AND THE AUTHOR AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
 * MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
 *
 * IDENTIFICATION
 *	$Header: /cvsroot/pgsql/src/pl/plpython/plpython.c,v 1.10 2001/10/25 05:50:20 momjian Exp $
 *
 *********************************************************************
 */

#include "postgres.h"

/* system stuff
 */
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <setjmp.h>

/* postgreSQL stuff
 */
#include "executor/spi.h"
#include "commands/trigger.h"
#include "utils/elog.h"
#include "fmgr.h"
#include "access/heapam.h"

#include "tcop/tcopprot.h"
#include "utils/syscache.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"

#include <Python.h>
#include "plpython.h"

/* convert Postgresql Datum or tuple into a PyObject.
 * input to Python.  Tuples are converted to dictionary
 * objects.
 */

typedef PyObject *(*PLyDatumToObFunc) (const char *);

typedef struct PLyDatumToOb
{
	PLyDatumToObFunc func;
	FmgrInfo	typfunc;
	Oid			typelem;
	bool		typbyval;
}			PLyDatumToOb;

typedef struct PLyTupleToOb
{
	PLyDatumToOb *atts;
	int			natts;
}			PLyTupleToOb;

typedef union PLyTypeInput
{
	PLyDatumToOb d;
	PLyTupleToOb r;
}			PLyTypeInput;

/* convert PyObject to a Postgresql Datum or tuple.
 * output from Python
 */
typedef struct PLyObToDatum
{
	FmgrInfo	typfunc;
	Oid			typelem;
	bool		typbyval;
}			PLyObToDatum;

typedef struct PLyObToTuple
{
	PLyObToDatum *atts;
	int			natts;
}			PLyObToTuple;

typedef union PLyTypeOutput
{
	PLyObToDatum d;
	PLyObToTuple r;
}			PLyTypeOutput;

/* all we need to move Postgresql data to Python objects,
 * and vis versa
 */
typedef struct PLyTypeInfo
{
	PLyTypeInput in;
	PLyTypeOutput out;
	int			is_rel;
}			PLyTypeInfo;


/* cached procedure data
 */
typedef struct PLyProcedure
{
	char	   *proname;
	TransactionId fn_xmin;
	CommandId	fn_cmin;
	PLyTypeInfo result;			/* also used to store info for trigger
								 * tuple type */
	PLyTypeInfo args[FUNC_MAX_ARGS];
	int			nargs;
	PyObject   *interp;			/* restricted interpreter instance */
	PyObject   *reval;			/* interpreter return */
	PyObject   *code;			/* compiled procedure code */
	PyObject   *statics;		/* data saved across calls, local scope */
	PyObject   *globals;		/* data saved across calls, global score */
	PyObject   *me;				/* PyCObject containing pointer to this
								 * PLyProcedure */
}			PLyProcedure;


/* Python objects.
 */
typedef struct PLyPlanObject
{
	PyObject_HEAD;
	void	   *plan;			/* return of an SPI_saveplan */
	int			nargs;
	Oid		   *types;
	Datum	   *values;
	PLyTypeInfo *args;
}			PLyPlanObject;

typedef struct PLyResultObject
{
	PyObject_HEAD;
	/* HeapTuple *tuples; */
	PyObject   *nrows;			/* number of rows returned by query */
	PyObject   *rows;			/* data rows, or None if no data returned */
	PyObject   *status;			/* query status, SPI_OK_*, or SPI_ERR_* */
}			PLyResultObject;


/* function declarations
 */

/* the only exported function, with the magic telling Postgresql
 * what function call interface it implements.
 */
Datum		plpython_call_handler(PG_FUNCTION_ARGS);

PG_FUNCTION_INFO_V1(plpython_call_handler);

/* most of the remaining of the declarations, all static
 */

/* these should only be called once at the first call
 * of plpython_call_handler.  initialize the python interpreter
 * and global data.
 */
static void PLy_init_all(void);
static void PLy_init_interp(void);
static void PLy_init_safe_interp(void);
static void PLy_init_plpy(void);

/* error handler.  collects the current Python exception, if any,
 * and appends it to the error and sends it to elog
 */
static void PLy_elog(int, const char *,...);

/* call PyErr_SetString with a vprint interface
 */
static void
PLy_exception_set(PyObject *, const char *,...)
__attribute__((format(printf, 2, 3)));

/* some utility functions
 */
static void *PLy_malloc(size_t);
static void *PLy_realloc(void *, size_t);
static void PLy_free(void *);

/* sub handlers for functions and triggers
 */
static Datum PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure *);
static HeapTuple PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure *);

static PyObject *PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *);
static PyObject *PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *,
					   HeapTuple *);
static HeapTuple PLy_modify_tuple(PLyProcedure *, PyObject *,
				 TriggerData *, HeapTuple);

static PyObject *PLy_procedure_call(PLyProcedure *, char *, PyObject *);

/* returns a cached PLyProcedure, or creates, stores and returns
 * a new PLyProcedure.
 */
static PLyProcedure *PLy_procedure_get(FunctionCallInfo fcinfo, bool);

static PLyProcedure *PLy_procedure_create(FunctionCallInfo fcinfo,
					 bool is_trigger,
					 HeapTuple procTup, char *key);

static void PLy_procedure_compile(PLyProcedure *, const char *);
static char *PLy_procedure_munge_source(const char *, const char *);
static void PLy_procedure_delete(PLyProcedure *);

static void PLy_typeinfo_init(PLyTypeInfo *);
static void PLy_typeinfo_dealloc(PLyTypeInfo *);
static void PLy_output_datum_func(PLyTypeInfo *, Form_pg_type);
static void PLy_output_datum_func2(PLyObToDatum *, Form_pg_type);
static void PLy_input_datum_func(PLyTypeInfo *, Form_pg_type);
static void PLy_input_datum_func2(PLyDatumToOb *, Form_pg_type);
static void PLy_output_tuple_funcs(PLyTypeInfo *, TupleDesc);
static void PLy_input_tuple_funcs(PLyTypeInfo *, TupleDesc);

/* conversion functions
 */
static PyObject *PLyDict_FromTuple(PLyTypeInfo *, HeapTuple, TupleDesc);
static PyObject *PLyBool_FromString(const char *);
static PyObject *PLyFloat_FromString(const char *);
static PyObject *PLyInt_FromString(const char *);
static PyObject *PLyLong_FromString(const char *);
static PyObject *PLyString_FromString(const char *);


/* global data
 */
static int	PLy_first_call = 1;
static volatile int PLy_call_level = 0;

/* this gets modified in plpython_call_handler and PLy_elog.
 * test it any old where, but do NOT modify it anywhere except
 * those two functions
 */
static volatile int PLy_restart_in_progress = 0;

static PyObject *PLy_interp_globals = NULL;
static PyObject *PLy_interp_safe = NULL;
static PyObject *PLy_interp_safe_globals = NULL;
static PyObject *PLy_importable_modules = NULL;
static PyObject *PLy_procedure_cache = NULL;

char	   *PLy_importable_modules_list[] = {
	"array",
	"bisect",
	"calendar",
	"cmath",
	"errno",
	"marshal",
	"math",
	"md5",
	"mpz",
	"operator",
	"pickle",
	"random",
	"re",
	"sha",
	"string",
	"StringIO",
	"time",
	"whrandom",
	"zlib"
};

/* Python exceptions
 */
PyObject   *PLy_exc_error = NULL;
PyObject   *PLy_exc_fatal = NULL;
PyObject   *PLy_exc_spi_error = NULL;

/* some globals for the python module
 */
static char PLy_plan_doc[] = {
	"Store a PostgreSQL plan"
};

static char PLy_result_doc[] = {
	"Results of a PostgreSQL query"
};


#if DEBUG_EXC
volatile int exc_save_calls = 0;
volatile int exc_restore_calls = 0;
volatile int func_enter_calls = 0;
volatile int func_leave_calls = 0;
#endif

/*
 * the function definitions
 */

/*
 * This routine is a crock, and so is everyplace that calls it.  The problem
 * is that the cached form of plpython functions/queries is allocated permanently
 * (mostly via malloc()) and never released until backend exit.  Subsidiary
 * data structures such as fmgr info records therefore must live forever
 * as well.  A better implementation would store all this stuff in a per-
 * function memory context that could be reclaimed at need.  In the meantime,
 * fmgr_info_cxt must be called specifying TopMemoryContext so that whatever
 * it might allocate, and whatever the eventual function might allocate using
 * fn_mcxt, will live forever too.
 */
static void
perm_fmgr_info(Oid functionId, FmgrInfo *finfo)
{
	fmgr_info_cxt(functionId, finfo, TopMemoryContext);
}


Datum
plpython_call_handler(PG_FUNCTION_ARGS)
{
	DECLARE_EXC();
	Datum		retval;
	bool		is_trigger;
	PLyProcedure *volatile proc = NULL;

	enter();

	if (PLy_first_call)
		PLy_init_all();

	if (SPI_connect() != SPI_OK_CONNECT)
		elog(ERROR, "plpython: Unable to connect to SPI manager");

	CALL_LEVEL_INC();
	is_trigger = CALLED_AS_TRIGGER(fcinfo);

	SAVE_EXC();
	if (TRAP_EXC())
	{
		RESTORE_EXC();
		CALL_LEVEL_DEC();
		if (PLy_call_level == 0)
		{
			PLy_restart_in_progress = 0;
			PyErr_Clear();
		}
		else
			PLy_restart_in_progress += 1;
		if (proc)
			Py_DECREF(proc->me);
		RERAISE_EXC();
	}

	/*
	 * elog(NOTICE, "PLy_restart_in_progress is %d",
	 * PLy_restart_in_progress);
	 */

	proc = PLy_procedure_get(fcinfo, is_trigger);

	if (is_trigger)
	{
		HeapTuple	trv = PLy_trigger_handler(fcinfo, proc);

		retval = PointerGetDatum(trv);
	}
	else
		retval = PLy_function_handler(fcinfo, proc);

	CALL_LEVEL_DEC();
	RESTORE_EXC();

	Py_DECREF(proc->me);
	refc(proc->me);

	return retval;
}

/* trigger and function sub handlers
 *
 * the python function is expected to return Py_None if the tuple is
 * acceptable and unmodified.  Otherwise it should return a PyString
 * object who's value is SKIP, or MODIFY.  SKIP means don't perform
 * this action.  MODIFY means the tuple has been modified, so update
 * tuple and perform action.  SKIP and MODIFY assume the trigger fires
 * BEFORE the event and is ROW level.  postgres expects the function
 * to take no arguments and return an argument of type opaque.
 */
HeapTuple
PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
{
	DECLARE_EXC();
	HeapTuple	rv = NULL;
	PyObject   *volatile plargs = NULL;
	PyObject   *volatile plrv = NULL;

	enter();

	SAVE_EXC();
	if (TRAP_EXC())
	{
		RESTORE_EXC();

		Py_XDECREF(plargs);
		Py_XDECREF(plrv);

		RERAISE_EXC();
	}

	plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
	plrv = PLy_procedure_call(proc, "TD", plargs);

	/*
	 * Disconnect from SPI manager
	 */
	if (SPI_finish() != SPI_OK_FINISH)
		elog(ERROR, "plpython: SPI_finish failed");

	if (plrv == NULL)
		elog(FATAL, "Aiieee, PLy_procedure_call returned NULL");

	if (PLy_restart_in_progress)
		elog(FATAL, "Aiieee, restart in progress not expected");

	/*
	 * return of None means we're happy with the tuple
	 */
	if (plrv != Py_None)
	{
		char	   *srv;

		if (!PyString_Check(plrv))
			elog(ERROR, "plpython: Expected trigger to return None or a String");

		srv = PyString_AsString(plrv);
		if (strcasecmp(srv, "SKIP") == 0)
			rv = NULL;
		else if (strcasecmp(srv, "MODIFY") == 0)
		{
			TriggerData *tdata = (TriggerData *) fcinfo->context;

			if ((TRIGGER_FIRED_BY_INSERT(tdata->tg_event)) ||
				(TRIGGER_FIRED_BY_UPDATE(tdata->tg_event)))
				rv = PLy_modify_tuple(proc, plargs, tdata, rv);
			else
				elog(NOTICE, "plpython: Ignoring modified tuple in DELETE trigger");
		}
		else if (strcasecmp(srv, "OK"))
		{
			/*
			 * hmmm, perhaps they only read the pltcl page, not a
			 * surprising thing since i've written no documentation, so
			 * accept a belated OK
			 */
			elog(ERROR, "plpython: Expected return to be 'SKIP' or 'MODIFY'");
		}
	}

	Py_DECREF(plargs);
	Py_DECREF(plrv);

	RESTORE_EXC();

	return rv;
}

HeapTuple
PLy_modify_tuple(PLyProcedure * proc, PyObject * pltd, TriggerData *tdata,
				 HeapTuple otup)
{
	DECLARE_EXC();
	PyObject   *volatile plntup;
	PyObject   *volatile plkeys;
	PyObject   *volatile platt;
	PyObject   *volatile plval;
	PyObject   *volatile plstr;
	HeapTuple	rtup;
	int			natts,
				i,
				j,
				attn,
				atti;
	int		   *volatile modattrs;
	Datum	   *volatile modvalues;
	char	   *volatile modnulls;
	TupleDesc	tupdesc;

	plntup = plkeys = platt = plval = plstr = NULL;
	modattrs = NULL;
	modvalues = NULL;
	modnulls = NULL;

	enter();

	SAVE_EXC();
	if (TRAP_EXC())
	{
		RESTORE_EXC();

		Py_XDECREF(plntup);
		Py_XDECREF(plkeys);
		Py_XDECREF(platt);
		Py_XDECREF(plval);
		Py_XDECREF(plstr);

		if (modnulls)
			pfree(modnulls);
		if (modvalues)
			pfree(modvalues);
		if (modattrs)
			pfree(modattrs);

		RERAISE_EXC();
	}

	if ((plntup = PyDict_GetItemString(pltd, "new")) == NULL)
		elog(ERROR, "plpython: TD[\"new\"] deleted, unable to modify tuple");
	if (!PyDict_Check(plntup))
		elog(ERROR, "plpython: TD[\"new\"] is not a dictionary object");
	Py_INCREF(plntup);

	plkeys = PyDict_Keys(plntup);
	natts = PyList_Size(plkeys);

	if (natts != proc->result.out.r.natts)
		elog(ERROR, "plpython: TD[\"new\"] has an incorrect number of keys.");

	modattrs = palloc(natts * sizeof(int));
	modvalues = palloc(natts * sizeof(Datum));
	for (i = 0; i < natts; i++)
	{
		modattrs[i] = i + 1;
		modvalues[i] = (Datum) NULL;
	}
	modnulls = palloc(natts + 1);
	memset(modnulls, 'n', natts);
	modnulls[natts] = '\0';

	tupdesc = tdata->tg_relation->rd_att;

	for (j = 0; j < natts; j++)
	{
		char	   *src;

		platt = PyList_GetItem(plkeys, j);
		if (!PyString_Check(platt))
			elog(ERROR, "plpython: attribute is not a string");
		attn = modattrs[j] = SPI_fnumber(tupdesc, PyString_AsString(platt));

		if (attn == SPI_ERROR_NOATTRIBUTE)
			elog(ERROR, "plpython: invalid attribute `%s' in tuple.",
				 PyString_AsString(platt));
		atti = attn - 1;

		plval = PyDict_GetItem(plntup, platt);
		if (plval == NULL)
			elog(FATAL, "plpython: interpreter is probably corrupted");

		Py_INCREF(plval);

		if (plval != Py_None)
		{
			plstr = PyObject_Str(plval);
			src = PyString_AsString(plstr);

			modvalues[j] = FunctionCall3(&proc->result.out.r.atts[atti].typfunc,
										 CStringGetDatum(src),
				 ObjectIdGetDatum(proc->result.out.r.atts[atti].typelem),
							Int32GetDatum(tupdesc->attrs[j]->atttypmod));
			modnulls[j] = ' ';

			Py_DECREF(plstr);
			plstr = NULL;
		}
		Py_DECREF(plval);
		plval = NULL;

	}
	rtup = SPI_modifytuple(tdata->tg_relation, otup, natts, modattrs,
						   modvalues, modnulls);

	/*
	 * FIXME -- these leak if not explicity pfree'd by other elog calls,
	 * no?
	 */
	pfree(modattrs);
	pfree(modvalues);
	pfree(modnulls);

	if (rtup == NULL)
		elog(ERROR, "plpython: SPI_modifytuple failed -- error %d", SPI_result);

	Py_DECREF(plntup);
	Py_DECREF(plkeys);

	RESTORE_EXC();

	return rtup;
}

PyObject *
PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc, HeapTuple *rv)
{
	DECLARE_EXC();
	TriggerData *tdata;
	PyObject   *pltname,
			   *pltevent,
			   *pltwhen,
			   *pltlevel,
			   *pltrelid;
	PyObject   *pltargs,
			   *pytnew,
			   *pytold;
	PyObject   *volatile pltdata = NULL;
	char	   *stroid;

	enter();

	SAVE_EXC();
	if (TRAP_EXC())
	{
		RESTORE_EXC();

		Py_XDECREF(pltdata);

		RERAISE_EXC();
	}

	tdata = (TriggerData *) fcinfo->context;

	pltdata = PyDict_New();
	if (!pltdata)
		PLy_elog(ERROR, "Unable to build arguments for trigger procedure");

	pltname = PyString_FromString(tdata->tg_trigger->tgname);
	PyDict_SetItemString(pltdata, "name", pltname);
	Py_DECREF(pltname);

	stroid = DatumGetCString(DirectFunctionCall1(oidout,
						   ObjectIdGetDatum(tdata->tg_relation->rd_id)));
	pltrelid = PyString_FromString(stroid);
	PyDict_SetItemString(pltdata, "relid", pltrelid);
	Py_DECREF(pltrelid);
	pfree(stroid);



	if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
		pltwhen = PyString_FromString("BEFORE");
	else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
		pltwhen = PyString_FromString("AFTER");
	else
		pltwhen = PyString_FromString("UNKNOWN");
	PyDict_SetItemString(pltdata, "when", pltwhen);
	Py_DECREF(pltwhen);

	if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
		pltlevel = PyString_FromString("ROW");
	else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
		pltlevel = PyString_FromString("STATEMENT");
	else
		pltlevel = PyString_FromString("UNKNOWN");
	PyDict_SetItemString(pltdata, "level", pltlevel);
	Py_DECREF(pltlevel);

	if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
	{
		pltevent = PyString_FromString("INSERT");
		PyDict_SetItemString(pltdata, "old", Py_None);
		pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
								   tdata->tg_relation->rd_att);
		PyDict_SetItemString(pltdata, "new", pytnew);
		Py_DECREF(pytnew);
		*rv = tdata->tg_trigtuple;
	}
	else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
	{
		pltevent = PyString_FromString("DELETE");
		PyDict_SetItemString(pltdata, "new", Py_None);
		pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
								   tdata->tg_relation->rd_att);
		PyDict_SetItemString(pltdata, "old", pytold);
		Py_DECREF(pytold);
		*rv = tdata->tg_trigtuple;
	}
	else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
	{
		pltevent = PyString_FromString("UPDATE");
		pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_newtuple,
								   tdata->tg_relation->rd_att);
		PyDict_SetItemString(pltdata, "new", pytnew);
		Py_DECREF(pytnew);
		pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
								   tdata->tg_relation->rd_att);
		PyDict_SetItemString(pltdata, "old", pytold);
		Py_DECREF(pytold);
		*rv = tdata->tg_newtuple;
	}
	else
	{
		pltevent = PyString_FromString("UNKNOWN");
		PyDict_SetItemString(pltdata, "old", Py_None);
		PyDict_SetItemString(pltdata, "new", Py_None);
		*rv = tdata->tg_trigtuple;
	}
	PyDict_SetItemString(pltdata, "event", pltevent);
	Py_DECREF(pltevent);

	if (tdata->tg_trigger->tgnargs)
	{
		/*
		 * all strings...
		 */
		int			i;
		PyObject   *pltarg;

		pltargs = PyList_New(tdata->tg_trigger->tgnargs);
		for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
		{
			pltarg = PyString_FromString(tdata->tg_trigger->tgargs[i]);

			/*
			 * stolen, don't Py_DECREF
			 */
			PyList_SetItem(pltargs, i, pltarg);
		}
	}
	else
	{
		Py_INCREF(Py_None);
		pltargs = Py_None;
	}
	PyDict_SetItemString(pltdata, "args", pltargs);
	Py_DECREF(pltargs);

	RESTORE_EXC();

	return pltdata;
}



/* function handler and friends
 */
Datum
PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
{
	DECLARE_EXC();
	Datum		rv;
	PyObject   *volatile plargs = NULL;
	PyObject   *volatile plrv = NULL;
	PyObject   *volatile plrv_so = NULL;
	char	   *plrv_sc;

	enter();

	/*
	 * setup to catch elog in while building function arguments, and
	 * DECREF the plargs if the function call fails
	 */
	SAVE_EXC();
	if (TRAP_EXC())
	{
		RESTORE_EXC();

		Py_XDECREF(plargs);
		Py_XDECREF(plrv);
		Py_XDECREF(plrv_so);

		RERAISE_EXC();
	}

	plargs = PLy_function_build_args(fcinfo, proc);
	plrv = PLy_procedure_call(proc, "args", plargs);

	/*
	 * Disconnect from SPI manager and then create the return values datum
	 * (if the input function does a palloc for it this must not be
	 * allocated in the SPI memory context because SPI_finish would free
	 * it).
	 */
	if (SPI_finish() != SPI_OK_FINISH)
		elog(ERROR, "plpython: SPI_finish failed");

	if (plrv == NULL)
	{
		elog(FATAL, "Aiieee, PLy_procedure_call returned NULL");
#if 0
		if (!PLy_restart_in_progress)
			PLy_elog(ERROR, "plpython: Function \"%s\" failed.", proc->proname);

		/*
		 * FIXME is this dead code?  i'm pretty sure it is for unnested
		 * calls, but not for nested calls
		 */
		RAISE_EXC(1);
#endif
	}

	/*
	 * convert the python PyObject to a postgresql Datum FIXME returning a
	 * NULL, ie PG_RETURN_NULL() blows the backend to small messy bits...
	 * it this a bug or expected?  so just call with the string value of
	 * None for now
	 */

	if (plrv == Py_None)
	{
		fcinfo->isnull = true;
		rv = (Datum) NULL;
	}
	else
	{
		fcinfo->isnull = false;
		plrv_so = PyObject_Str(plrv);
		plrv_sc = PyString_AsString(plrv_so);
		rv = FunctionCall3(&proc->result.out.d.typfunc,
						   PointerGetDatum(plrv_sc),
						   ObjectIdGetDatum(proc->result.out.d.typelem),
						   Int32GetDatum(-1));
	}

	RESTORE_EXC();

	Py_XDECREF(plargs);
	Py_DECREF(plrv);
	Py_XDECREF(plrv_so);

	return rv;
}

PyObject *
PLy_procedure_call(PLyProcedure * proc, char *kargs, PyObject * vargs)
{
	PyObject   *rv;

	enter();

	PyDict_SetItemString(proc->globals, kargs, vargs);
	rv = PyObject_CallFunction(proc->reval, "O", proc->code);

	if ((rv == NULL) || (PyErr_Occurred()))
	{
		Py_XDECREF(rv);
		if (!PLy_restart_in_progress)
			PLy_elog(ERROR, "Call of function `%s' failed.", proc->proname);
		RAISE_EXC(1);
	}

	return rv;
}

PyObject *
PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc)
{
	DECLARE_EXC();
	PyObject   *volatile arg = NULL;
	PyObject   *volatile args = NULL;
	int			i;

	enter();

	/*
	 * FIXME -- if the setjmp setup is expensive, add the arg and args
	 * field to the procedure struct and cleanup at the start of the next
	 * call
	 */
	SAVE_EXC();
	if (TRAP_EXC())
	{
		RESTORE_EXC();
		Py_XDECREF(arg);
		Py_XDECREF(args);

		RERAISE_EXC();
	}

	args = PyList_New(proc->nargs);
	for (i = 0; i < proc->nargs; i++)
	{
		if (proc->args[i].is_rel == 1)
		{
			TupleTableSlot *slot = (TupleTableSlot *) fcinfo->arg[i];

			arg = PLyDict_FromTuple(&(proc->args[i]), slot->val,
									slot->ttc_tupleDescriptor);
		}
		else
		{
			if (!fcinfo->argnull[i])
			{
				char	   *ct;
				Datum		dt;

				dt = FunctionCall3(&(proc->args[i].in.d.typfunc),
								   fcinfo->arg[i],
							ObjectIdGetDatum(proc->args[i].in.d.typelem),
								   Int32GetDatum(-1));
				ct = DatumGetCString(dt);
				arg = (proc->args[i].in.d.func) (ct);
				pfree(ct);
			}
			else
				arg = NULL;
		}

		if (arg == NULL)
		{
			Py_INCREF(Py_None);
			arg = Py_None;
		}

		/*
		 * FIXME -- error check this
		 */
		PyList_SetItem(args, i, arg);
	}

	RESTORE_EXC();

	return args;
}


/* PLyProcedure functions
 */
static PLyProcedure *
PLy_procedure_get(FunctionCallInfo fcinfo, bool is_trigger)
{
	Oid			fn_oid;
	HeapTuple	procTup;
	char		key[128];
	PyObject   *plproc;
	PLyProcedure *proc = NULL;
	int			rv;

	enter();

	fn_oid = fcinfo->flinfo->fn_oid;
	procTup = SearchSysCache(PROCOID,
							 ObjectIdGetDatum(fn_oid),
							 0, 0, 0);
	if (!HeapTupleIsValid(procTup))
		elog(ERROR, "plpython: cache lookup for procedure %u failed", fn_oid);

	rv = snprintf(key, sizeof(key), "%u%s",
				  fn_oid,
				  is_trigger ? "_trigger" : "");
	if ((rv >= sizeof(key)) || (rv < 0))
		elog(FATAL, "plpython: Buffer overrun in %s:%d", __FILE__, __LINE__);

	plproc = PyDict_GetItemString(PLy_procedure_cache, key);

	if (plproc != NULL)
	{
		Py_INCREF(plproc);
		if (!PyCObject_Check(plproc))
			elog(FATAL, "plpython: Expected a PyCObject, didn't get one");

		mark();

		proc = PyCObject_AsVoidPtr(plproc);
		if (proc->me != plproc)
			elog(FATAL, "plpython: Aiieee, proc->me != plproc");
		/* did we find an up-to-date cache entry? */
		if (proc->fn_xmin != procTup->t_data->t_xmin ||
			proc->fn_cmin != procTup->t_data->t_cmin)
		{
			Py_DECREF(plproc);
			proc = NULL;
		}
	}

	if (proc == NULL)
		proc = PLy_procedure_create(fcinfo, is_trigger, procTup, key);

	ReleaseSysCache(procTup);

	return proc;
}

static PLyProcedure *
PLy_procedure_create(FunctionCallInfo fcinfo, bool is_trigger,
					 HeapTuple procTup, char *key)
{
	char		procName[256];

	DECLARE_EXC();
	Form_pg_proc procStruct;
	PLyProcedure *volatile proc;
	char	   *volatile procSource = NULL;
	Datum		procDatum;
	int			i,
				rv;

	enter();

	procStruct = (Form_pg_proc) GETSTRUCT(procTup);

	rv = snprintf(procName, sizeof(procName),
				  "__plpython_procedure_%s_%u%s",
				  NameStr(procStruct->proname),
				  fcinfo->flinfo->fn_oid,
				  is_trigger ? "_trigger" : "");
	if ((rv >= sizeof(procName)) || (rv < 0))
		elog(FATAL, "plpython: Procedure name would overrun buffer");

	proc = PLy_malloc(sizeof(PLyProcedure));
	proc->proname = PLy_malloc(strlen(procName) + 1);
	strcpy(proc->proname, procName);
	proc->fn_xmin = procTup->t_data->t_xmin;
	proc->fn_cmin = procTup->t_data->t_cmin;
	PLy_typeinfo_init(&proc->result);
	for (i = 0; i < FUNC_MAX_ARGS; i++)
		PLy_typeinfo_init(&proc->args[i]);
	proc->nargs = 0;
	proc->code = proc->interp = proc->reval = proc->statics = NULL;
	proc->globals = proc->me = NULL;

	SAVE_EXC();
	if (TRAP_EXC())
	{
		RESTORE_EXC();
		PLy_procedure_delete(proc);
		if (procSource)
			pfree(procSource);
		RERAISE_EXC();
	}

	/*
	 * get information required for output conversion of the return value,
	 * but only if this isn't a trigger.
	 */
	if (!is_trigger)
	{
		HeapTuple	rvTypeTup;
		Form_pg_type rvTypeStruct;
		Datum		rvDatum;

		rvDatum = ObjectIdGetDatum(procStruct->prorettype);
		rvTypeTup = SearchSysCache(TYPEOID, rvDatum, 0, 0, 0);
		if (!HeapTupleIsValid(rvTypeTup))
			elog(ERROR, "plpython: cache lookup for type \"%u\" failed",
				 procStruct->prorettype);

		rvTypeStruct = (Form_pg_type) GETSTRUCT(rvTypeTup);
		if (rvTypeStruct->typrelid == InvalidOid)
			PLy_output_datum_func(&proc->result, rvTypeStruct);
		else
			elog(ERROR, "plpython: tuple return types not supported, yet");

		ReleaseSysCache(rvTypeTup);
	}
	else
	{
		/*
		 * input/output conversion for trigger tuples.	use the result
		 * TypeInfo variable to store the tuple conversion info.
		 */
		TriggerData *tdata = (TriggerData *) fcinfo->context;

		PLy_input_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
		PLy_output_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
	}

	/*
	 * now get information required for input conversion of the procedures
	 * arguments.
	 */
	proc->nargs = fcinfo->nargs;
	for (i = 0; i < fcinfo->nargs; i++)
	{
		HeapTuple	argTypeTup;
		Form_pg_type argTypeStruct;
		Datum		argDatum;

		argDatum = ObjectIdGetDatum(procStruct->proargtypes[i]);
		argTypeTup = SearchSysCache(TYPEOID, argDatum, 0, 0, 0);
		if (!HeapTupleIsValid(argTypeTup))
			elog(ERROR, "plpython: cache lookup for type \"%u\" failed",
				 procStruct->proargtypes[i]);
		argTypeStruct = (Form_pg_type) GETSTRUCT(argTypeTup);

		if (argTypeStruct->typrelid == InvalidOid)
			PLy_input_datum_func(&(proc->args[i]), argTypeStruct);
		else
		{
			TupleTableSlot *slot = (TupleTableSlot *) fcinfo->arg[i];

			PLy_input_tuple_funcs(&(proc->args[i]),
								  slot->ttc_tupleDescriptor);
		}

		ReleaseSysCache(argTypeTup);
	}


	/*
	 * get the text of the function.
	 */
	procDatum = DirectFunctionCall1(textout,
									PointerGetDatum(&procStruct->prosrc));
	procSource = DatumGetCString(procDatum);

	PLy_procedure_compile(proc, procSource);

	pfree(procSource);

	proc->me = PyCObject_FromVoidPtr(proc, NULL);
	PyDict_SetItemString(PLy_procedure_cache, key, proc->me);

	RESTORE_EXC();

	return proc;
}

void
PLy_procedure_compile(PLyProcedure * proc, const char *src)
{
	PyObject   *module,
			   *crv = NULL;
	char	   *msrc;

	enter();

	/*
	 * get an instance of rexec.RExec for the function
	 */
	proc->interp = PyObject_CallMethod(PLy_interp_safe, "RExec", NULL);
	if ((proc->interp == NULL) || (PyErr_Occurred()))
		PLy_elog(ERROR, "Unable to create rexec.RExec instance");

	/*
	 * tweak the list of permitted modules
	 */
	PyObject_SetAttrString(proc->interp, "ok_builtin_modules",
						   PLy_importable_modules);

	proc->reval = PyObject_GetAttrString(proc->interp, "r_eval");
	if ((proc->reval == NULL) || (PyErr_Occurred()))
		PLy_elog(ERROR, "Unable to get method `r_eval' from rexec.RExec");

	/*
	 * add a __main__ module to the function's interpreter
	 */
	module = PyObject_CallMethod(proc->interp, "add_module", "s", "__main__");
	if ((module == NULL) || (PyErr_Occurred()))
		PLy_elog(ERROR, "Unable to get module `__main__' from rexec.RExec");

	/*
	 * add plpy module to the interpreters main dictionary
	 */
	proc->globals = PyModule_GetDict(module);
	if ((proc->globals == NULL) || (PyErr_Occurred()))
		PLy_elog(ERROR, "Unable to get `__main__.__dict__' from rexec.RExec");

	/*
	 * why the hell won't r_import or r_exec('import plpy') work?
	 */
	module = PyDict_GetItemString(PLy_interp_globals, "plpy");
	if ((module == NULL) || (PyErr_Occurred()))
		PLy_elog(ERROR, "Unable to get `plpy'");
	Py_INCREF(module);
	PyDict_SetItemString(proc->globals, "plpy", module);

	/*
	 * SD is private preserved data between calls GD is global data shared
	 * by all functions
	 */
	proc->statics = PyDict_New();
	PyDict_SetItemString(proc->globals, "SD", proc->statics);
	PyDict_SetItemString(proc->globals, "GD", PLy_interp_safe_globals);

	/*
	 * insert the function code into the interpreter
	 */
	msrc = PLy_procedure_munge_source(proc->proname, src);
	crv = PyObject_CallMethod(proc->interp, "r_exec", "s", msrc);
	free(msrc);

	if ((crv != NULL) && (!PyErr_Occurred()))
	{
		int			clen;
		char		call[256];

		Py_DECREF(crv);

		/*
		 * compile a call to the function
		 */
		clen = snprintf(call, sizeof(call), "%s()", proc->proname);
		if ((clen < 0) || (clen >= sizeof(call)))
			elog(ERROR, "plpython: string would overflow buffer.");
		proc->code = Py_CompileString(call, "<string>", Py_eval_input);
		if ((proc->code != NULL) && (!PyErr_Occurred()))
			return;
	}
	else
		Py_XDECREF(crv);

	PLy_elog(ERROR, "Unable to compile function %s", proc->proname);
}

char *
PLy_procedure_munge_source(const char *name, const char *src)
{
	char	   *mrc,
			   *mp;
	const char *sp;
	size_t		mlen,
				plen;

	enter();

	/*
	 * room for function source and the def statement
	 */
	mlen = (strlen(src) * 2) + strlen(name) + 16;

	mrc = PLy_malloc(mlen);
	plen = snprintf(mrc, mlen, "def %s():\n\t", name);
	if ((plen < 0) || (plen >= mlen))
		elog(FATAL, "Aiieee, impossible buffer overrun (or snprintf failure)");

	sp = src;
	mp = mrc + plen;

	while (*sp != '\0')
	{
		if (*sp == '\n')
		{
			*mp++ = *sp++;
			*mp++ = '\t';
		}
		else
			*mp++ = *sp++;
	}
	*mp++ = '\n';
	*mp++ = '\n';
	*mp = '\0';

	if (mp > (mrc + mlen))
		elog(FATAL, "plpython: Buffer overrun in PLy_munge_source");

	return mrc;
}

void
PLy_procedure_delete(PLyProcedure * proc)
{
	int			i;

	enter();

	Py_XDECREF(proc->code);
	Py_XDECREF(proc->interp);
	Py_XDECREF(proc->reval);
	Py_XDECREF(proc->statics);
	Py_XDECREF(proc->globals);
	Py_XDECREF(proc->me);
	if (proc->proname)
		PLy_free(proc->proname);
	for (i = 0; i < proc->nargs; i++)
		if (proc->args[i].is_rel == 1)
		{
			if (proc->args[i].in.r.atts)
				PLy_free(proc->args[i].in.r.atts);
			if (proc->args[i].out.r.atts)
				PLy_free(proc->args[i].out.r.atts);
		}

	leave();
}

/* conversion functions.  remember output from python is
 * input to postgresql, and vis versa.
 */
void
PLy_input_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
{
	int			i;
	Datum		datum;

	enter();

	if (arg->is_rel == 0)
		elog(FATAL, "plpython: PLyTypeInfo struct is initialized for a Datum");

	arg->is_rel = 1;
	arg->in.r.natts = desc->natts;
	arg->in.r.atts = malloc(desc->natts * sizeof(PLyDatumToOb));

	for (i = 0; i < desc->natts; i++)
	{
		HeapTuple	typeTup;
		Form_pg_type typeStruct;

		datum = ObjectIdGetDatum(desc->attrs[i]->atttypid);
		typeTup = SearchSysCache(TYPEOID, datum, 0, 0, 0);
		if (!HeapTupleIsValid(typeTup))
		{
			char	   *attname = NameStr(desc->attrs[i]->attname);

			elog(ERROR, "plpython: Cache lookup for attribute `%s' type `%u' failed",
				 attname, desc->attrs[i]->atttypid);
		}

		typeStruct = (Form_pg_type) GETSTRUCT(typeTup);

		PLy_input_datum_func2(&(arg->in.r.atts[i]), typeStruct);

		ReleaseSysCache(typeTup);
	}
}

void
PLy_output_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
{
	int			i;
	Datum		datum;

	enter();

	if (arg->is_rel == 0)
		elog(FATAL, "plpython: PLyTypeInfo struct is initialized for a Datum");

	arg->is_rel = 1;
	arg->out.r.natts = desc->natts;
	arg->out.r.atts = malloc(desc->natts * sizeof(PLyDatumToOb));

	for (i = 0; i < desc->natts; i++)
	{
		HeapTuple	typeTup;
		Form_pg_type typeStruct;

		datum = ObjectIdGetDatum(desc->attrs[i]->atttypid);
		typeTup = SearchSysCache(TYPEOID, datum, 0, 0, 0);
		if (!HeapTupleIsValid(typeTup))
		{
			char	   *attname = NameStr(desc->attrs[i]->attname);

			elog(ERROR, "plpython: Cache lookup for attribute `%s' type `%u' failed",
				 attname, desc->attrs[i]->atttypid);
		}

		typeStruct = (Form_pg_type) GETSTRUCT(typeTup);

		PLy_output_datum_func2(&(arg->out.r.atts[i]), typeStruct);

		ReleaseSysCache(typeTup);
	}
}

void
PLy_output_datum_func(PLyTypeInfo * arg, Form_pg_type typeStruct)
{
	enter();

	if (arg->is_rel == 1)
		elog(FATAL, "plpython: PLyTypeInfo struct is initialized for a Tuple");
	arg->is_rel = 0;
	PLy_output_datum_func2(&(arg->out.d), typeStruct);
}

void
PLy_output_datum_func2(PLyObToDatum * arg, Form_pg_type typeStruct)
{
	enter();

	perm_fmgr_info(typeStruct->typinput, &arg->typfunc);
	arg->typelem = typeStruct->typelem;
	arg->typbyval = typeStruct->typbyval;
}

void
PLy_input_datum_func(PLyTypeInfo * arg, Form_pg_type typeStruct)
{
	enter();

	if (arg->is_rel == 1)
		elog(FATAL, "plpython: PLyTypeInfo struct is initialized for Tuple");
	arg->is_rel = 0;
	PLy_input_datum_func2(&(arg->in.d), typeStruct);
}

void
PLy_input_datum_func2(PLyDatumToOb * arg, Form_pg_type typeStruct)
{
	char	   *type;

	perm_fmgr_info(typeStruct->typoutput, &arg->typfunc);
	arg->typelem = typeStruct->typelem;
	arg->typbyval = typeStruct->typbyval;

	/*
	 * hmmm, wierd.  means this arg will always be converted to a python
	 * None
	 */
	if (!OidIsValid(typeStruct->typoutput))
	{
		elog(ERROR, "plpython: (FIXME) typeStruct->typoutput is invalid");

		arg->func = NULL;
		return;
	}

	type = NameStr(typeStruct->typname);
	switch (type[0])
	{
		case 'b':
			{
				if (strcasecmp("bool", type))
				{
					arg->func = PLyBool_FromString;
					return;
				}
				break;
			}
		case 'f':
			{
				if ((strncasecmp("float", type, 5) == 0) &&
					((type[5] == '8') || (type[5] == '4')))
				{
					arg->func = PLyFloat_FromString;
					return;
				}
				break;
			}
		case 'i':
			{
				if ((strncasecmp("int", type, 3) == 0) &&
					((type[3] == '4') || (type[3] == '2')) &&
					(type[4] == '\0'))
				{
					arg->func = PLyInt_FromString;
					return;
				}
				else if (strcasecmp("int8", type) == 0)
					arg->func = PLyLong_FromString;
				break;
			}
		case 'n':
			{
				if (strcasecmp("numeric", type) == 0)
				{
					arg->func = PLyFloat_FromString;
					return;
				}
				break;
			}
		default:
			break;
	}
	arg->func = PLyString_FromString;
}

void
PLy_typeinfo_init(PLyTypeInfo * arg)
{
	arg->is_rel = -1;
	arg->in.r.natts = arg->out.r.natts = 0;
	arg->in.r.atts = NULL;
	arg->out.r.atts = NULL;
}

void
PLy_typeinfo_dealloc(PLyTypeInfo * arg)
{
	if (arg->is_rel == 1)
	{
		if (arg->in.r.atts)
			PLy_free(arg->in.r.atts);
		if (arg->out.r.atts)
			PLy_free(arg->out.r.atts);
	}
}

/* assumes that a bool is always returned as a 't' or 'f'
 */
PyObject *
PLyBool_FromString(const char *src)
{
	enter();

	if (src[0] == 't')
		return PyInt_FromLong(1);
	return PyInt_FromLong(0);
}

PyObject *
PLyFloat_FromString(const char *src)
{
	double		v;
	char	   *eptr;

	enter();

	errno = 0;
	v = strtod(src, &eptr);
	if ((*eptr != '\0') || (errno))
		return NULL;
	return PyFloat_FromDouble(v);
}

PyObject *
PLyInt_FromString(const char *src)
{
	long		v;
	char	   *eptr;

	enter();

	errno = 0;
	v = strtol(src, &eptr, 0);
	if ((*eptr != '\0') || (errno))
		return NULL;
	return PyInt_FromLong(v);
}

PyObject *
PLyLong_FromString(const char *src)
{
	return PyLong_FromString((char *) src, NULL, 0);
}

PyObject *
PLyString_FromString(const char *src)
{
	return PyString_FromString(src);
}

PyObject *
PLyDict_FromTuple(PLyTypeInfo * info, HeapTuple tuple, TupleDesc desc)
{
	DECLARE_EXC();
	PyObject   *volatile dict;
	int			i;

	enter();

	if (info->is_rel != 1)
		elog(FATAL, "plpython: PLyTypeInfo structure describes a datum.");

	dict = PyDict_New();
	if (dict == NULL)
		PLy_elog(ERROR, "Unable to create tuple dictionary.");

	SAVE_EXC();
	if (TRAP_EXC())
	{
		RESTORE_EXC();
		Py_DECREF(dict);

		RERAISE_EXC();
	}

	for (i = 0; i < info->in.r.natts; i++)
	{
		char	   *key,
				   *vsrc;
		Datum		vattr,
					vdat;
		bool		is_null;
		PyObject   *value;

		key = NameStr(desc->attrs[i]->attname);
		vattr = heap_getattr(tuple, (i + 1), desc, &is_null);

		if ((is_null) || (info->in.r.atts[i].func == NULL))
			PyDict_SetItemString(dict, key, Py_None);
		else
		{
			vdat = FunctionCall3(&info->in.r.atts[i].typfunc,
								 vattr,
							ObjectIdGetDatum(info->in.r.atts[i].typelem),
							   Int32GetDatum(desc->attrs[i]->atttypmod));
			vsrc = DatumGetCString(vdat);

			/*
			 * no exceptions allowed
			 */
			value = info->in.r.atts[i].func(vsrc);
			pfree(vsrc);
			PyDict_SetItemString(dict, key, value);
			Py_DECREF(value);
		}
	}

	RESTORE_EXC();

	return dict;
}

/* initialization, some python variables function declared here
 */

/* interface to postgresql elog
 */
static PyObject *PLy_debug(PyObject *, PyObject *);
static PyObject *PLy_error(PyObject *, PyObject *);
static PyObject *PLy_fatal(PyObject *, PyObject *);
static PyObject *PLy_notice(PyObject *, PyObject *);

/* PLyPlanObject, PLyResultObject and SPI interface
 */
#define is_PLyPlanObject(x) ((x)->ob_type == &PLy_PlanType)
static PyObject *PLy_plan_new(void);
static void PLy_plan_dealloc(PyObject *);
static PyObject *PLy_plan_getattr(PyObject *, char *);
static PyObject *PLy_plan_status(PyObject *, PyObject *);

static PyObject *PLy_result_new(void);
static void PLy_result_dealloc(PyObject *);
static PyObject *PLy_result_getattr(PyObject *, char *);
static PyObject *PLy_result_fetch(PyObject *, PyObject *);
static PyObject *PLy_result_nrows(PyObject *, PyObject *);
static PyObject *PLy_result_status(PyObject *, PyObject *);
static int	PLy_result_length(PyObject *);
static PyObject *PLy_result_item(PyObject *, int);
static PyObject *PLy_result_slice(PyObject *, int, int);
static int	PLy_result_ass_item(PyObject *, int, PyObject *);
static int	PLy_result_ass_slice(PyObject *, int, int, PyObject *);


static PyObject *PLy_spi_prepare(PyObject *, PyObject *);
static PyObject *PLy_spi_execute(PyObject *, PyObject *);
static const char *PLy_spi_error_string(int);
static PyObject *PLy_spi_execute_query(char *query, int limit);
static PyObject *PLy_spi_execute_plan(PyObject *, PyObject *, int);
static PyObject *PLy_spi_execute_fetch_result(SPITupleTable *, int, int);


PyTypeObject PLy_PlanType = {
	PyObject_HEAD_INIT(NULL)
	0,							/* ob_size */
	"PLyPlan",					/* tp_name */
	sizeof(PLyPlanObject),		/* tp_size */
	0,							/* tp_itemsize */

	/*
	 * methods
	 */
	(destructor) PLy_plan_dealloc,		/* tp_dealloc */
	0,							/* tp_print */
	(getattrfunc) PLy_plan_getattr,		/* tp_getattr */
	0,							/* tp_setattr */
	0,							/* tp_compare */
	0,							/* tp_repr */
	0,							/* tp_as_number */
	0,							/* tp_as_sequence */
	0,							/* tp_as_mapping */
	0,							/* tp_hash */
	0,							/* tp_call */
	0,							/* tp_str */
	0,							/* tp_getattro */
	0,							/* tp_setattro */
	0,							/* tp_as_buffer */
	0,							/* tp_xxx4 */
	PLy_plan_doc,				/* tp_doc */
};

PyMethodDef PLy_plan_methods[] = {
	{"status", (PyCFunction) PLy_plan_status, METH_VARARGS, NULL},
	{NULL, NULL, 0, NULL}
};


PySequenceMethods PLy_result_as_sequence = {
	(inquiry) PLy_result_length,/* sq_length */
	(binaryfunc) 0,				/* sq_concat */
	(intargfunc) 0,				/* sq_repeat */
	(intargfunc) PLy_result_item,		/* sq_item */
	(intintargfunc) PLy_result_slice,	/* sq_slice */
	(intobjargproc) PLy_result_ass_item,		/* sq_ass_item */
	(intintobjargproc) PLy_result_ass_slice,	/* sq_ass_slice */
};

PyTypeObject PLy_ResultType = {
	PyObject_HEAD_INIT(NULL)
	0,							/* ob_size */
	"PLyResult",				/* tp_name */
	sizeof(PLyResultObject),	/* tp_size */
	0,							/* tp_itemsize */

	/*
	 * methods
	 */
	(destructor) PLy_result_dealloc,	/* tp_dealloc */
	0,							/* tp_print */
	(getattrfunc) PLy_result_getattr,	/* tp_getattr */
	0,							/* tp_setattr */
	0,							/* tp_compare */
	0,							/* tp_repr */
	0,							/* tp_as_number */
	&PLy_result_as_sequence,	/* tp_as_sequence */
	0,							/* tp_as_mapping */
	0,							/* tp_hash */
	0,							/* tp_call */
	0,							/* tp_str */
	0,							/* tp_getattro */
	0,							/* tp_setattro */
	0,							/* tp_as_buffer */
	0,							/* tp_xxx4 */
	PLy_result_doc,				/* tp_doc */
};

PyMethodDef PLy_result_methods[] = {
	{"fetch", (PyCFunction) PLy_result_fetch, METH_VARARGS, NULL,},
	{"nrows", (PyCFunction) PLy_result_nrows, METH_VARARGS, NULL},
	{"status", (PyCFunction) PLy_result_status, METH_VARARGS, NULL},
	{NULL, NULL, 0, NULL}
};


static PyMethodDef PLy_methods[] = {
	/*
	 * logging methods
	 */
	{"debug", PLy_debug, METH_VARARGS, NULL},
	{"error", PLy_error, METH_VARARGS, NULL},
	{"fatal", PLy_fatal, METH_VARARGS, NULL},
	{"notice", PLy_notice, METH_VARARGS, NULL},

	/*
	 * create a stored plan
	 */
	{"prepare", PLy_spi_prepare, METH_VARARGS, NULL},

	/*
	 * execute a plan or query
	 */
	{"execute", PLy_spi_execute, METH_VARARGS, NULL},

	{NULL, NULL, 0, NULL}
};


/* plan object methods
 */
PyObject *
PLy_plan_new(void)
{
	PLyPlanObject *ob;

	enter();

	if ((ob = PyObject_NEW(PLyPlanObject, &PLy_PlanType)) == NULL)
		return NULL;

	ob->plan = NULL;
	ob->nargs = 0;
	ob->types = NULL;
	ob->args = NULL;

	return (PyObject *) ob;
}


void
PLy_plan_dealloc(PyObject * arg)
{
	PLyPlanObject *ob = (PLyPlanObject *) arg;

	enter();

	if (ob->plan)
	{
		/*
		 * free the plan... pfree(ob->plan);
		 *
		 * FIXME -- leaks saved plan on object destruction.  can this be
		 * avoided?
		 */
	}
	if (ob->types)
		PLy_free(ob->types);
	if (ob->args)
	{
		int			i;

		for (i = 0; i < ob->nargs; i++)
			PLy_typeinfo_dealloc(&ob->args[i]);
		PLy_free(ob->args);
	}

	PyMem_DEL(arg);

	leave();
}


PyObject *
PLy_plan_getattr(PyObject * self, char *name)
{
	return Py_FindMethod(PLy_plan_methods, self, name);
}

PyObject *
PLy_plan_status(PyObject * self, PyObject * args)
{
	if (PyArg_ParseTuple(args, ""))
	{
		Py_INCREF(Py_True);
		return Py_True;
		/* return PyInt_FromLong(self->status); */
	}
	PyErr_SetString(PLy_exc_error, "plan.status() takes no arguments");
	return NULL;
}



/* result object methods
 */

static PyObject *
PLy_result_new(void)
{
	PLyResultObject *ob;

	enter();

	if ((ob = PyObject_NEW(PLyResultObject, &PLy_ResultType)) == NULL)
		return NULL;

	/* ob->tuples = NULL; */

	Py_INCREF(Py_None);
	ob->status = Py_None;
	ob->nrows = PyInt_FromLong(-1);
	ob->rows = PyList_New(0);

	return (PyObject *) ob;
}

static void
PLy_result_dealloc(PyObject * arg)
{
	PLyResultObject *ob = (PLyResultObject *) arg;

	enter();

	Py_XDECREF(ob->nrows);
	Py_XDECREF(ob->rows);
	Py_XDECREF(ob->status);

	PyMem_DEL(ob);
}

static PyObject *
PLy_result_getattr(PyObject * self, char *attr)
{
	return NULL;
}

static PyObject *
PLy_result_fetch(PyObject * self, PyObject * args)
{
	return NULL;
}

static PyObject *
PLy_result_nrows(PyObject * self, PyObject * args)
{
	PLyResultObject *ob = (PLyResultObject *) self;

	Py_INCREF(ob->nrows);
	return ob->nrows;
}

static PyObject *
PLy_result_status(PyObject * self, PyObject * args)
{
	PLyResultObject *ob = (PLyResultObject *) self;

	Py_INCREF(ob->status);
	return ob->status;
}

int
PLy_result_length(PyObject * arg)
{
	PLyResultObject *ob = (PLyResultObject *) arg;

	return PyList_Size(ob->rows);
}

PyObject *
PLy_result_item(PyObject * arg, int idx)
{
	PyObject   *rv;
	PLyResultObject *ob = (PLyResultObject *) arg;

	rv = PyList_GetItem(ob->rows, idx);
	if (rv != NULL)
		Py_INCREF(rv);
	return rv;
}

int
PLy_result_ass_item(PyObject * arg, int idx, PyObject * item)
{
	int			rv;
	PLyResultObject *ob = (PLyResultObject *) arg;

	Py_INCREF(item);
	rv = PyList_SetItem(ob->rows, idx, item);
	return rv;
}

PyObject *
PLy_result_slice(PyObject * arg, int lidx, int hidx)
{
	PyObject   *rv;
	PLyResultObject *ob = (PLyResultObject *) arg;

	rv = PyList_GetSlice(ob->rows, lidx, hidx);
	if (rv == NULL)
		return NULL;
	Py_INCREF(rv);
	return rv;
}

int
PLy_result_ass_slice(PyObject * arg, int lidx, int hidx, PyObject * slice)
{
	int			rv;
	PLyResultObject *ob = (PLyResultObject *) arg;

	rv = PyList_SetSlice(ob->rows, lidx, hidx, slice);
	return rv;
}

/* SPI interface
 */
PyObject *
PLy_spi_prepare(PyObject * self, PyObject * args)
{
	DECLARE_EXC();
	PLyPlanObject *plan;
	PyObject   *list = NULL;
	PyObject   *volatile optr = NULL;
	char	   *query;

	enter();

	if (!PyArg_ParseTuple(args, "s|O", &query, &list))
	{
		PyErr_SetString(PLy_exc_spi_error,
						"Invalid arguments for plpy.prepare()");
		return NULL;
	}

	if ((list) && (!PySequence_Check(list)))
	{
		PyErr_SetString(PLy_exc_spi_error,
				 "Second argument in plpy.prepare() must be a sequence");
		return NULL;
	}


	if ((plan = (PLyPlanObject *) PLy_plan_new()) == NULL)
		return NULL;

	SAVE_EXC();
	if (TRAP_EXC())
	{
		RESTORE_EXC();
		Py_DECREF(plan);
		Py_XDECREF(optr);
		if (!PyErr_Occurred())
			PyErr_SetString(PLy_exc_spi_error,
							"Unknown error in PLy_spi_prepare.");
		return NULL;
	}

	if (list != NULL)
	{
		int			nargs,
					i;


		nargs = PySequence_Length(list);
		if (nargs > 0)
		{
			plan->nargs = nargs;
			plan->types = PLy_malloc(sizeof(Oid) * nargs);
			plan->values = PLy_malloc(sizeof(Datum) * nargs);
			plan->args = PLy_malloc(sizeof(PLyTypeInfo) * nargs);

			/*
			 * the other loop might throw an exception, if PLyTypeInfo
			 * member isn't properly initialized the Py_DECREF(plan) will
			 * go boom
			 */
			for (i = 0; i < nargs; i++)
			{
				PLy_typeinfo_init(&plan->args[i]);
				plan->values[i] = (Datum) NULL;
			}

			for (i = 0; i < nargs; i++)
			{
				char	   *sptr;
				HeapTuple	typeTup;
				Form_pg_type typeStruct;

				optr = PySequence_GetItem(list, i);
				if (!PyString_Check(optr))
				{
					PyErr_SetString(PLy_exc_spi_error,
									"Type names must be strings.");
					RAISE_EXC(1);
				}
				sptr = PyString_AsString(optr);
				typeTup = SearchSysCache(TYPENAME, PointerGetDatum(sptr),
										 0, 0, 0);
				if (!HeapTupleIsValid(typeTup))
				{
					PLy_exception_set(PLy_exc_spi_error,
									"Cache lookup for type `%s' failed.",
									  sptr);
					RAISE_EXC(1);
				}

				Py_DECREF(optr);
				optr = NULL;	/* this is important */

				plan->types[i] = typeTup->t_data->t_oid;
				typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
				if (typeStruct->typrelid == InvalidOid)
					PLy_output_datum_func(&plan->args[i], typeStruct);
				else
				{
					PyErr_SetString(PLy_exc_spi_error,
							 "tuples not handled in plpy.prepare, yet.");
					RAISE_EXC(1);
				}
				ReleaseSysCache(typeTup);
			}
		}
	}

	plan->plan = SPI_prepare(query, plan->nargs, plan->types);
	if (plan->plan == NULL)
	{
		PLy_exception_set(PLy_exc_spi_error,
					 "Unable to prepare plan. SPI_prepare failed -- %s.",
						  PLy_spi_error_string(SPI_result));
		RAISE_EXC(1);
	}

	plan->plan = SPI_saveplan(plan->plan);
	if (plan->plan == NULL)
	{
		PLy_exception_set(PLy_exc_spi_error,
					   "Unable to save plan. SPI_saveplan failed -- %s.",
						  PLy_spi_error_string(SPI_result));
		RAISE_EXC(1);
	}

	RESTORE_EXC();

	return (PyObject *) plan;
}

/* execute(query="select * from foo", limit=5)
 * execute(plan=plan, values=(foo, bar), limit=5)
 */
PyObject *
PLy_spi_execute(PyObject * self, PyObject * args)
{
	char	   *query;
	PyObject   *plan;
	PyObject   *list = NULL;
	int			limit = 0;

	enter();

#if 0

	/*
	 * there should - hahaha - be an python exception set so just return
	 * NULL.  FIXME -- is this needed?
	 */
	if (PLy_restart_in_progress)
		return NULL;
#endif

	if (PyArg_ParseTuple(args, "s|i", &query, &limit))
		return PLy_spi_execute_query(query, limit);

	PyErr_Clear();

	if ((PyArg_ParseTuple(args, "O|Oi", &plan, &list, &limit)) &&
		(is_PLyPlanObject(plan)))
	{
		PyObject   *rv = PLy_spi_execute_plan(plan, list, limit);

		return rv;
	}

	PyErr_SetString(PLy_exc_error, "Expected a query or plan.");
	return NULL;
}

PyObject *
PLy_spi_execute_plan(PyObject * ob, PyObject * list, int limit)
{
	DECLARE_EXC();
	volatile int nargs;
	int			i,
				rv;
	PLyPlanObject *plan;

	enter();

	if (list != NULL)
	{
		if ((!PySequence_Check(list)) || (PyString_Check(list)))
		{
			char	   *msg = "plpy.execute() takes a sequence as its second argument";

			PyErr_SetString(PLy_exc_spi_error, msg);
			return NULL;
		}
		nargs = PySequence_Length(list);
	}
	else
		nargs = 0;

	plan = (PLyPlanObject *) ob;

	if (nargs != plan->nargs)
	{
		char	   *sv;

		PyObject   *so = PyObject_Str(list);

		sv = PyString_AsString(so);
		PLy_exception_set(PLy_exc_spi_error,
						  "Expected sequence of %d arguments, got %d. %s",
						  plan->nargs, nargs, sv);
		Py_DECREF(so);

		return NULL;
	}

	SAVE_EXC();
	if (TRAP_EXC())
	{
		RESTORE_EXC();

		/*
		 * cleanup plan->values array
		 */
		for (i = 0; i < nargs; i++)
		{
			if (!plan->args[i].out.d.typbyval &&
				(plan->values[i] != (Datum) NULL))
			{
				pfree(DatumGetPointer(plan->values[i]));
				plan->values[i] = (Datum) NULL;
			}
		}

		if (!PyErr_Occurred())
			PyErr_SetString(PLy_exc_error,
							"Unknown error in PLy_spi_execute_plan");
		return NULL;
	}

	if (nargs)
	{
		for (i = 0; i < nargs; i++)
		{
			PyObject   *elem,
					   *so;
			char	   *sv;

			elem = PySequence_GetItem(list, i);
			so = PyObject_Str(elem);
			sv = PyString_AsString(so);

			/*
			 * FIXME -- if this can elog, we have leak
			 */
			plan->values[i] = FunctionCall3(&(plan->args[i].out.d.typfunc),
											CStringGetDatum(sv),
						   ObjectIdGetDatum(plan->args[i].out.d.typelem),
											Int32GetDatum(-1));

			Py_DECREF(so);
			Py_DECREF(elem);
		}
	}

	rv = SPI_execp(plan->plan, plan->values, NULL, limit);
	RESTORE_EXC();

	for (i = 0; i < nargs; i++)
	{
		if (!plan->args[i].out.d.typbyval &&
			(plan->values[i] != (Datum) NULL))
		{
			pfree(DatumGetPointer(plan->values[i]));
			plan->values[i] = (Datum) NULL;
		}
	}

	if (rv < 0)
	{
		PLy_exception_set(PLy_exc_spi_error,
					   "Unable to execute plan.  SPI_execp failed -- %s",
						  PLy_spi_error_string(rv));
		return NULL;
	}

	return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
}

PyObject *
PLy_spi_execute_query(char *query, int limit)
{
	DECLARE_EXC();
	int			rv;

	SAVE_EXC();
	if (TRAP_EXC())
	{
		RESTORE_EXC();

		if ((!PLy_restart_in_progress) && (!PyErr_Occurred()))
			PyErr_SetString(PLy_exc_spi_error,
							"Unknown error in PLy_spi_execute_query.");
		return NULL;
	}

	rv = SPI_exec(query, limit);
	RESTORE_EXC();

	if (rv < 0)
	{
		PLy_exception_set(PLy_exc_spi_error,
					   "Unable to execute query.  SPI_exec failed -- %s",
						  PLy_spi_error_string(rv));
		return NULL;
	}

	return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
}

PyObject *
PLy_spi_execute_fetch_result(SPITupleTable *tuptable, int rows, int status)
{
	PLyResultObject *result;

	enter();

	result = (PLyResultObject *) PLy_result_new();
	Py_DECREF(result->status);
	result->status = PyInt_FromLong(status);

	if (status == SPI_OK_UTILITY)
	{
		Py_DECREF(result->nrows);
		result->nrows = PyInt_FromLong(0);
	}
	else if (status != SPI_OK_SELECT)
	{
		Py_DECREF(result->nrows);
		result->nrows = PyInt_FromLong(rows);
	}
	else
	{
		DECLARE_EXC();
		PLyTypeInfo args;
		int			i;

		PLy_typeinfo_init(&args);
		Py_DECREF(result->nrows);
		result->nrows = PyInt_FromLong(rows);

		SAVE_EXC();
		if (TRAP_EXC())
		{
			RESTORE_EXC();

			if (!PyErr_Occurred())
				PyErr_SetString(PLy_exc_error,
						"Unknown error in PLy_spi_execute_fetch_result");
			Py_DECREF(result);
			PLy_typeinfo_dealloc(&args);
			return NULL;
		}

		if (rows)
		{
			Py_DECREF(result->rows);
			result->rows = PyList_New(rows);

			PLy_input_tuple_funcs(&args, tuptable->tupdesc);
			for (i = 0; i < rows; i++)
			{
				PyObject   *row = PLyDict_FromTuple(&args, tuptable->vals[i],
													tuptable->tupdesc);

				PyList_SetItem(result->rows, i, row);
			}
			PLy_typeinfo_dealloc(&args);
		}
		RESTORE_EXC();
	}

	return (PyObject *) result;
}

const char *
PLy_spi_error_string(int code)
{
	switch (code)
	{
		case SPI_ERROR_TYPUNKNOWN:
			return "SPI_ERROR_TYPUNKNOWN";
		case SPI_ERROR_NOOUTFUNC:
			return "SPI_ERROR_NOOUTFUNC";
		case SPI_ERROR_NOATTRIBUTE:
			return "SPI_ERROR_NOATTRIBUTE";
		case SPI_ERROR_TRANSACTION:
			return "SPI_ERROR_TRANSACTION";
		case SPI_ERROR_PARAM:
			return "SPI_ERROR_PARAM";
		case SPI_ERROR_ARGUMENT:
			return "SPI_ERROR_ARGUMENT";
		case SPI_ERROR_CURSOR:
			return "SPI_ERROR_CURSOR";
		case SPI_ERROR_UNCONNECTED:
			return "SPI_ERROR_UNCONNECTED";
		case SPI_ERROR_OPUNKNOWN:
			return "SPI_ERROR_OPUNKNOWN";
		case SPI_ERROR_COPY:
			return "SPI_ERROR_COPY";
		case SPI_ERROR_CONNECT:
			return "SPI_ERROR_CONNECT";
	}
	return "Unknown or Invalid code";
}

/* language handler and interpreter initialization
 */

void
PLy_init_all(void)
{
	static volatile int init_active = 0;

	enter();

	if (init_active)
		elog(FATAL, "plpython: Initialization of language module failed.");
	init_active = 1;

	Py_Initialize();
	PLy_init_interp();
	PLy_init_plpy();
	PLy_init_safe_interp();
	if (PyErr_Occurred())
		PLy_elog(FATAL, "Untrapped error in initialization.");
	PLy_procedure_cache = PyDict_New();
	if (PLy_procedure_cache == NULL)
		PLy_elog(ERROR, "Unable to create procedure cache.");

	PLy_first_call = 0;

	leave();
}

void
PLy_init_interp(void)
{
	PyObject   *mainmod;

	enter();

	mainmod = PyImport_AddModule("__main__");
	if ((mainmod == NULL) || (PyErr_Occurred()))
		PLy_elog(ERROR, "Unable to import '__main__' module.");
	Py_INCREF(mainmod);
	PLy_interp_globals = PyModule_GetDict(mainmod);
	Py_DECREF(mainmod);
	if ((PLy_interp_globals == NULL) || (PyErr_Occurred()))
		PLy_elog(ERROR, "Unable to initialize globals.");
}

void
PLy_init_plpy(void)
{
	PyObject   *main_mod,
			   *main_dict,
			   *plpy_mod;
	PyObject   *plpy,
			   *plpy_dict;

	enter();

	/*
	 * initialize plpy module
	 */
	PLy_PlanType.ob_type = PLy_ResultType.ob_type = &PyType_Type;
	plpy = Py_InitModule("plpy", PLy_methods);
	plpy_dict = PyModule_GetDict(plpy);

	/* PyDict_SetItemString(plpy, "PlanType", (PyObject *) &PLy_PlanType); */

	PLy_exc_error = PyErr_NewException("plpy.Error", NULL, NULL);
	PLy_exc_fatal = PyErr_NewException("plpy.Fatal", NULL, NULL);
	PLy_exc_spi_error = PyErr_NewException("plpy.SPIError", NULL, NULL);
	PyDict_SetItemString(plpy_dict, "Error", PLy_exc_error);
	PyDict_SetItemString(plpy_dict, "Fatal", PLy_exc_fatal);
	PyDict_SetItemString(plpy_dict, "SPIError", PLy_exc_spi_error);

	/*
	 * initialize main module, and add plpy
	 */
	main_mod = PyImport_AddModule("__main__");
	main_dict = PyModule_GetDict(main_mod);
	plpy_mod = PyImport_AddModule("plpy");
	PyDict_SetItemString(main_dict, "plpy", plpy_mod);
	if (PyErr_Occurred())
		elog(ERROR, "Unable to init plpy.");
}

void
PLy_init_safe_interp(void)
{
	PyObject   *rmod;
	char	   *rname = "rexec";
	int			i,
				imax;

	enter();

	rmod = PyImport_ImportModuleEx(rname, PLy_interp_globals,
								   PLy_interp_globals, Py_None);
	if ((rmod == NULL) || (PyErr_Occurred()))
		PLy_elog(ERROR, "Unable to import %s.", rname);
	PyDict_SetItemString(PLy_interp_globals, rname, rmod);
	PLy_interp_safe = rmod;

	imax = sizeof(PLy_importable_modules_list) / sizeof(char *);
	PLy_importable_modules = PyTuple_New(imax);
	for (i = 0; i < imax; i++)
	{
		PyObject   *m = PyString_FromString(PLy_importable_modules_list[i]);

		PyTuple_SetItem(PLy_importable_modules, i, m);
	}

	PLy_interp_safe_globals = PyDict_New();
	if (PLy_interp_safe_globals == NULL)
		PLy_elog(ERROR, "Unable to create shared global dictionary.");

}


/* the python interface to the elog function
 * don't confuse these with PLy_elog
 */
static PyObject *PLy_log(int, PyObject *, PyObject *);

PyObject *
PLy_debug(PyObject * self, PyObject * args)
{
	return PLy_log(DEBUG, self, args);
}

PyObject *
PLy_error(PyObject * self, PyObject * args)
{
	return PLy_log(ERROR, self, args);
}

PyObject *
PLy_fatal(PyObject * self, PyObject * args)
{
	return PLy_log(FATAL, self, args);
}

PyObject *
PLy_notice(PyObject * self, PyObject * args)
{
	return PLy_log(NOTICE, self, args);
}


PyObject *
PLy_log(volatile int level, PyObject * self, PyObject * args)
{
	DECLARE_EXC();
	PyObject   *so;
	char	   *volatile sv;

	enter();

	if (args == NULL)
		elog(NOTICE, "plpython, args is NULL in %s", __FUNCTION__);

	so = PyObject_Str(args);
	if ((so == NULL) || ((sv = PyString_AsString(so)) == NULL))
	{
		level = ERROR;
		sv = "Unable to parse error message in `plpy.elog'";
	}

	/*
	 * returning NULL here causes the python interpreter to bail. when
	 * control passes back into plpython_*_handler, we check for python
	 * exceptions and do the actual elog call.	actually PLy_elog.
	 */
	if (level == ERROR)
	{
		PyErr_SetString(PLy_exc_error, sv);
		return NULL;
	}
	else if (level >= FATAL)
	{
		PyErr_SetString(PLy_exc_fatal, sv);
		return NULL;
	}

	/*
	 * ok, this is a NOTICE, or DEBUG message
	 *
	 * but just in case DON'T long jump out of the interpreter!
	 */
	SAVE_EXC();
	if (TRAP_EXC())
	{
		RESTORE_EXC();

		Py_XDECREF(so);

		/*
		 * the real error message should already be written into the
		 * postgresql log, no?	whatever, this shouldn't happen so die
		 * hideously.
		 */
		elog(FATAL, "plpython: Aiieee, elog threw an unknown exception!");
		return NULL;
	}

	elog(level, sv);

	RESTORE_EXC();

	Py_XDECREF(so);
	Py_INCREF(Py_None);

	/*
	 * return a legal object so the interpreter will continue on its merry
	 * way
	 */
	return Py_None;
}


/* output a python traceback/exception via the postgresql elog
 * function.  not pretty.
 */

static char *PLy_traceback(int *);
static char *PLy_vprintf(const char *fmt, va_list ap);
static char *PLy_printf(const char *fmt,...);

void
PLy_exception_set(PyObject * exc, const char *fmt,...)
{
	char		buf[1024];
	va_list		ap;

	va_start(ap, fmt);
	vsnprintf(buf, sizeof(buf), fmt, ap);
	va_end(ap);

	PyErr_SetString(exc, buf);
}

void
PLy_elog(int elevel, const char *fmt,...)
{
	DECLARE_EXC();
	va_list		ap;
	char	   *xmsg,
			   *emsg;
	int			xlevel;

	enter();

	xmsg = PLy_traceback(&xlevel);

	va_start(ap, fmt);
	emsg = PLy_vprintf(fmt, ap);
	va_end(ap);

	SAVE_EXC();
	if (TRAP_EXC())
	{
		RESTORE_EXC();
		mark();

		/*
		 * elog called siglongjmp. cleanup, restore and reraise
		 */
		PLy_restart_in_progress += 1;
		PLy_free(emsg);
		PLy_free(xmsg);
		RERAISE_EXC();
	}

	if (xmsg)
	{
		elog(elevel, "plpython: %s\n%s", emsg, xmsg);
		PLy_free(xmsg);
	}
	else
		elog(elevel, "plpython: %s", emsg);
	PLy_free(emsg);

	leave();

	RESTORE_EXC();
}

char *
PLy_traceback(int *xlevel)
{
	PyObject   *e,
			   *v,
			   *tb;
	PyObject   *eob,
			   *vob = NULL;
	char	   *vstr,
			   *estr,
			   *xstr = NULL;

	enter();

	/*
	 * get the current exception
	 */
	PyErr_Fetch(&e, &v, &tb);

	/*
	 * oops, no exception, return
	 */
	if (e == NULL)
	{
		*xlevel = NOTICE;
		return NULL;
	}

	PyErr_NormalizeException(&e, &v, &tb);

	eob = PyObject_Str(e);
	if ((v) && ((vob = PyObject_Str(v)) != NULL))
		vstr = PyString_AsString(vob);
	else
		vstr = "Unknown";

	estr = PyString_AsString(eob);
	xstr = PLy_printf("%s: %s", estr, vstr);

	Py_DECREF(eob);
	Py_XDECREF(vob);

	/*
	 * intuit an appropriate error level for based on the exception type
	 */
	if ((PLy_exc_error) && (PyErr_GivenExceptionMatches(e, PLy_exc_error)))
		*xlevel = ERROR;
	else if ((PLy_exc_fatal) && (PyErr_GivenExceptionMatches(e, PLy_exc_fatal)))
		*xlevel = FATAL;
	else
		*xlevel = ERROR;

	leave();

	return xstr;
}

char *
PLy_printf(const char *fmt,...)
{
	va_list		ap;
	char	   *emsg;

	va_start(ap, fmt);
	emsg = PLy_vprintf(fmt, ap);
	va_end(ap);
	return emsg;
}

char *
PLy_vprintf(const char *fmt, va_list ap)
{
	size_t		blen;
	int			bchar,
				tries = 2;
	char	   *buf;

	blen = strlen(fmt) * 2;
	if (blen < 256)
		blen = 256;
	buf = PLy_malloc(blen * sizeof(char));

	while (1)
	{
		bchar = vsnprintf(buf, blen, fmt, ap);
		if ((bchar > 0) && (bchar < blen))
			return buf;
		if (tries-- <= 0)
			break;
		if (blen > 0)
			blen = bchar + 1;
		else
			blen *= 2;
		buf = PLy_realloc(buf, blen);
	}
	PLy_free(buf);
	return NULL;
}

/* python module code
 */


/* some dumb utility functions
 */

void *
PLy_malloc(size_t bytes)
{
	void	   *ptr = malloc(bytes);

	if (ptr == NULL)
		elog(FATAL, "plpython: Memory exhausted.");
	return ptr;
}

void *
PLy_realloc(void *optr, size_t bytes)
{
	void	   *nptr = realloc(optr, bytes);

	if (nptr == NULL)
		elog(FATAL, "plpython: Memory exhausted.");
	return nptr;
}

/* define this away
 */
void
PLy_free(void *ptr)
{
	free(ptr);
}