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
  
2787
  
2788
  
2789
  
2790
  
2791
  
2792
  
2793
  
2794
  
2795
  
2796
  
2797
  
2798
  
2799
  
2800
  
2801
  
2802
  
2803
  
2804
  
2805
  
2806
  
2807
  
2808
  
2809
  
2810
  
2811
  
2812
  
2813
  
2814
  
2815
  
2816
  
2817
  
2818
  
2819
  
2820
  
2821
  
2822
  
2823
  
2824
  
2825
  
2826
  
2827
  
2828
  
2829
  
2830
  
2831
  
2832
  
2833
  
2834
  
2835
  
2836
  
2837
  
2838
  
2839
  
2840
  
2841
  
2842
  
2843
  
2844
  
2845
  
2846
  
2847
  
2848
  
2849
  
2850
  
2851
  
2852
  
2853
  
2854
  
2855
  
2856
  
2857
  
2858
  
2859
  
2860
  
2861
  
2862
  
2863
  
2864
  
2865
  
2866
  
2867
  
2868
  
2869
  
2870
  
2871
  
2872
  
2873
  
2874
  
2875
  
2876
  
2877
  
2878
  
2879
  
2880
  
2881
  
2882
  
2883
  
2884
  
2885
  
2886
  
2887
  
2888
  
2889
  
2890
  
2891
  
2892
  
2893
  
2894
  
2895
  
2896
  
2897
  
2898
  
2899
  
2900
  
2901
  
2902
  
2903
  
2904
  
2905
  
2906
  
2907
  
2908
  
2909
  
2910
  
2911
  
2912
  
2913
  
2914
  
2915
  
2916
  
2917
  
2918
  
2919
  
2920
  
2921
  
2922
  
2923
  
/* 
 * Some pgsql utility functions. 
 * They are kept here to avoid circular references. 
 */ 
 
//! The pgsql backend, shared between all connection instances. 
//! It runs even in non-callback mode in a separate thread and makes sure 
//! that communication with the database is real-time and event driven 
//! at all times. 
//! 
//! @note 
//! Callbacks running from this backend directly determine the latency 
//! in reacting to communication with the database server; so it 
//! would be prudent not to block in these callbacks. 
 
#pike __REAL_VERSION__ 
#pragma dynamic_dot 
#require constant(Thread.Thread) 
 
#include "pgsql.h" 
 
#define PORTALINIT            0       // Portal states 
#define PARSING                     1 
#define BOUND                       2 
#define COMMITTED           3 
#define COPYINPROGRESS              4 
#define CLOSING                     5 
#define CLOSED                      6 
#define PURGED                      7 
 
#define NOERROR                       0       // Error states networkparser 
#define PROTOCOLERROR               1 
#define PROTOCOLUNSUPPORTED 2 
 
#define LOSTERROR     "Database connection lost" 
 
#if PG_DEADLOCK_SENTINEL 
private multiset mutexes = set_weak_flag((<>), Pike.WEAK); 
private int deadlockseq; 
 
private class MUTEX { 
  inherit Thread.Mutex; 
 
  private Thread.Thread sentinelthread; 
 
  private void dump_lockgraph(Thread.Thread curthread) { 
    sleep(PG_DEADLOCK_SENTINEL); 
    String.Buffer buf = String.Buffer(); 
    buf.add("\n{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{\n"); 
    buf.sprintf("Deadlock detected at\n%s\n", 
     describe_backtrace(curthread.backtrace(), -1)); 
    foreach(mutexes; this_program mu; ) 
      if (mu) { 
        Thread.Thread ct; 
        if (ct = mu.current_locking_thread()) 
        buf.sprintf("====================================== Mutex: %O\n%s\n", 
         mu, describe_backtrace(ct.backtrace(), -1)); 
      } 
    buf.add("}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}"); 
    werror(replace(buf.get(), "\n", sprintf("\n%d> ", deadlockseq++)) + "\n"); 
  } 
 
  Thread.MutexKey lock(void|int type) { 
    Thread.MutexKey key; 
    if (!(key = trylock(type))) { 
      sentinelthread = Thread.Thread(dump_lockgraph, this_thread()); 
      key = ::lock(type); 
      sentinelthread->kill(); 
    } 
    return key; 
  } 
 
  protected void create() { 
    //::create(); 
    mutexes[this] = 1; 
  } 
}; 
#else 
#define MUTEX                       Thread.Mutex 
#endif 
 
//! The instance of the pgsql dedicated backend. 
final Pike.Backend local_backend; 
 
private Pike.Backend cb_backend; 
private Result qalreadyprinted; 
private Thread.Mutex backendmux = Thread.Mutex(); 
final multiset(proxy) clients = set_weak_flag((<>), Pike.WEAK); 
 
mapping describenodata 
 = (["datarowdesc":({}), "datarowtypes":({}), "datatypeoid":({})]); 
private multiset censoroptions = (<"use_ssl", "force_ssl", 
 "cache_autoprepared_statements", "reconnect", "text_query", "is_superuser", 
 "server_encoding", "server_version", "integer_datetimes", 
 "session_authorization">); 
 
 /* Statements matching createprefix cause the prepared statement cache 
  * to be flushed to prevent stale references to (temporary) tables 
  */ 
final Regexp createprefix = iregexp("^\a*(CREATE|DROP)\a"); 
 
 /* Statements matching dontcacheprefix never enter the cache 
  */ 
private Regexp dontcacheprefix = iregexp("^\a*(FETCH|COPY)\a"); 
 
 /* Statements not matching paralleliseprefix will cause the driver 
  * to stall submission until all previously started statements have 
  * run to completion 
  */ 
private Regexp paralleliseprefix 
 = iregexp("^\a*((SELEC|INSER)T|(UPDA|DELE)TE|(FETC|WIT)H)\a"); 
 
 /* Statements matching transbeginprefix will cause the driver to 
  * insert a sync after the statement. 
  * Failure to do so, will result in portal synchronisation errors 
  * in the event of an ErrorResponse. 
  */ 
final Regexp transbeginprefix 
 = iregexp("^\a*(BEGIN|START)([; \t\f\r\n]|$)"); 
 
 /* Statements matching transendprefix will cause the driver to 
  * insert a sync after the statement. 
  * Failure to do so, will result in portal synchronisation errors 
  * in the event of an ErrorResponse. 
  */ 
final Regexp transendprefix 
 = iregexp("^\a*(COMMIT|ROLLBACK|END)([; \t\f\r\n]|$)"); 
 
 /* Statements matching nodataresprefix will cause the driver 
  * to skip asking for a query description and query results, since there 
  * are no arguments or results to begin with. 
  */ 
final Regexp nodataresprefix 
 = iregexp("^\a*(RESET|CLOSE|DISCARD)\a"); 
 
 /* For statements matching execfetchlimit the resultrows will not be 
  * fetched in pieces.  This heuristic will be sub-optimal whenever 
  * either an UPDATE/DELETE/INSERT statement is prefixed by WITH, or 
  * if there is a RETURNING with a *lot* of results.  In those cases 
  * the portal will be busy until all results have been fetched, and will 
  * not be able to deliver results belonging to other parallel queries 
  * running on the same filedescriptor. 
  * 
  * However, considering that the current heuristic increases query-speed 
  * in the majority of the real-world cases, it would be considered a good 
  * tradeoff. 
  */ 
private Regexp execfetchlimit 
 = iregexp("^\a*((UPDA|DELE)TE|INSERT|CREATE|DROP" 
           "|RESET|CLOSE|DISCARD)\a|\aLIMIT\a+[1-9][; \t\f\r\n]*$"); 
 
private void default_backend_runs() {               // Runs as soon as the 
  cb_backend = Pike.DefaultBackend;             // DefaultBackend has started 
} 
 
protected void create() { 
  atexit(_destruct); 
  // Run callbacks from our local_backend until DefaultBackend has started 
  cb_backend = local_backend = Pike.SmallBackend(); 
  call_out(default_backend_runs, 0); 
} 
 
protected void _destruct() { 
  foreach (clients; proxy client; ) 
    destruct(client); 
} 
 
private Regexp iregexp(string expr) { 
  Stdio.Buffer ret = Stdio.Buffer(); 
  foreach (expr; ; int c) 
    if (c >= 'A' && c <= 'Z') 
      ret->add('[', c, c + 'a' - 'A', ']'); 
    else if (c == '\a')                 // Replace with generic whitespace 
      ret->add("[ \t\f\r\n]"); 
    else 
      ret->add_int8(c); 
  return Regexp(ret->read()); 
} 
 
final void closestatement(bufcon|conxsess plugbuffer, string oldprep) { 
  if (oldprep) { 
    PD("Close statement %s\n", oldprep); 
    CHAIN(plugbuffer)->add_int8('C')->add_hstring(({'S', oldprep, 0}), 4, 4); 
  } 
} 
 
private void run_local_backend() { 
  Thread.MutexKey lock; 
  int looponce; 
  do { 
    looponce = 0; 
    if (lock = backendmux->trylock()) { 
      PD("Starting local backend\n"); 
      while (sizeof(clients)                    // Autoterminate when not needed 
       || sizeof(local_backend->call_out_info())) { 
        mixed err; 
        if (err = catch(local_backend(4096.0))) 
          master()->handle_error(err); 
      } 
      PD("Terminating local backend\n"); 
      lock = 0; 
      looponce = sizeof(clients); 
    } 
  } while (looponce); 
} 
 
//! Registers yourself as a user of this backend.  If the backend 
//! has not been started yet, it will be spawned automatically. 
final void register_backend(proxy client) { 
  int startbackend = !sizeof(clients); 
  clients[client] = 1; 
  if (startbackend) 
    Thread.Thread(run_local_backend); 
} 
 
final void throwdelayederror(Result|proxy parent) { 
  if (mixed err = parent->delayederror) { 
    if (!objectp(parent->pgsqlsess)) 
      parent->untolderror = 0; 
    else if (parent->pgsqlsess) 
      parent->pgsqlsess->untolderror = parent->pgsqlsess->delayederror = 0; 
    parent->delayederror = 0; 
    if (stringp(err)) 
      err = ({err, backtrace()[..<2]}); 
    throw(err); 
  } 
} 
 
private int readoidformat(int oid) { 
  switch (oid) { 
    case BOOLOID: 
    case BYTEAOID: 
    case CHAROID: 
    case INT8OID: 
    case INT2OID: 
    case INT4OID: 
    case FLOAT4OID: 
#if !constant(__builtin.__SINGLE_PRECISION_FLOAT__) 
    case FLOAT8OID: 
#endif 
    case NUMERICOID: 
    case TEXTOID: 
    case OIDOID: 
    case XMLOID: 
    case DATEOID: 
    case TIMEOID: 
    case TIMETZOID: 
    case TIMESTAMPOID: 
    case TIMESTAMPTZOID: 
    case INTERVALOID: 
    case INT4RANGEOID: 
    case INT8RANGEOID: 
    case DATERANGEOID: 
    case TSRANGEOID: 
    case TSTZRANGEOID: 
    case MACADDROID: 
    case BPCHAROID: 
    case VARCHAROID: 
    case CIDROID: 
    case INETOID: 
    case CTIDOID: 
    case UUIDOID: 
      return 1; //binary 
  } 
  return 0; // text 
} 
 
private int writeoidformat(int oid, array(string|int) paramValues, 
 array(int) ai) { 
  mixed value = paramValues[ai[0]++]; 
  switch (oid) { 
    case BOOLOID: 
    case BYTEAOID: 
    case CHAROID: 
    case INT8OID: 
    case INT2OID: 
    case INT4OID: 
    case TEXTOID: 
    case OIDOID: 
    case XMLOID: 
    case MACADDROID: 
    case BPCHAROID: 
    case VARCHAROID: 
    case CTIDOID: 
    case UUIDOID: 
      return 1; //binary 
    case NUMERICOID: 
    case CIDROID: 
    case INETOID: 
    case DATEOID: 
    case TIMEOID: 
    case TIMETZOID: 
    case TIMESTAMPOID: 
    case TIMESTAMPTZOID: 
    case INTERVALOID: 
    case INT4RANGEOID: 
    case INT8RANGEOID: 
    case DATERANGEOID: 
    case TSRANGEOID: 
    case TSTZRANGEOID: 
    case FLOAT4OID: 
#if !constant(__builtin.__SINGLE_PRECISION_FLOAT__) 
    case FLOAT8OID: 
#endif 
      if (!stringp(value)) 
        return 1; 
  } 
  return 0; // text 
} 
 
#define DAYSEPOCHTO2000               10957           // 2000/01/01 00:00:00 UTC 
#define USEPOCHTO2000               (DAYSEPOCHTO2000*24*3600*1000000) 
 
private array timestamptotype 
                    = ({Val.Timestamp, 8, USEPOCHTO2000,  "usecs", 8}); 
private array datetotype = ({Val.Date, 4, DAYSEPOCHTO2000, "days", 4}); 
 
private mapping(int:array) oidtotype = ([ 
   DATEOID:        datetotype, 
   TIMEOID:        ({Val.Time,    8, 0, "usecs", 8}), 
   TIMETZOID:      ({Val.TimeTZ, 12, 0, "usecs", 8, "timezone", 4}), 
   INTERVALOID:    ({Val.Interval, 16, 0, "usecs", 8, "days", 4, "months",4}), 
   TIMESTAMPOID:   timestamptotype, 
   TIMESTAMPTZOID: timestamptotype, 
   INT4RANGEOID:   ({0, 4}), 
   INT8RANGEOID:   ({0, 8}), 
   DATERANGEOID:   datetotype, 
   TSRANGEOID:     timestamptotype, 
   TSTZRANGEOID:   timestamptotype, 
 ]); 
 
private inline mixed callout(function(mixed ...:void) f, 
 float|int delay, mixed ... args) { 
  return cb_backend->call_out(f, delay, @args); 
} 
 
// Some pgsql utility functions 
 
class bufcon { 
  inherit Stdio.Buffer; 
  private Thread.ResourceCountKey dirty; 
 
#ifdef PG_DEBUGRACE 
  final bufcon `chain() { 
    return this; 
  } 
#endif 
 
  private conxion realbuffer; 
 
  protected void create(conxion _realbuffer) { 
    realbuffer = _realbuffer; 
  } 
 
  final Thread.ResourceCount `stashcount() { 
    return realbuffer->stashcount; 
  } 
 
  final MUTEX `shortmux() { 
    return realbuffer->shortmux; 
  } 
 
  final bufcon start(void|int|array(Thread.MutexKey) waitforreal) { 
    dirty = stashcount->acquire(); 
#ifdef PG_DEBUG 
    if (waitforreal) 
      error("pgsql.bufcon not allowed here\n"); 
#endif 
    return this; 
  } 
 
  final void sendcmd(int mode, void|Result portal) { 
    Thread.MutexKey lock = shortmux->lock(); 
    if (portal) 
      realbuffer->stashqueue->write(portal); 
    if (mode == SYNCSEND) { 
      add(PGSYNC); 
      realbuffer->stashqueue->write(1); 
      mode = SENDOUT;       // Demote it to prevent an extra SYNC upon stashflush 
    } 
    realbuffer->stash->add(this); 
    PD("%d>Stashed mode %d > %d\n", 
     realbuffer->socket->query_fd(), mode, realbuffer->stashflushmode); 
    if (mode > realbuffer->stashflushmode) 
      realbuffer->stashflushmode = mode; 
    dirty = 0;              // Countdown before releasing the lock 
    lock = 0; 
    this->clear(); 
    if (lock = realbuffer->nostash->trylock(1)) { 
#ifdef PG_DEBUGRACE 
      conxsess sess = conxsess(realbuffer); 
      realbuffer->started = lock; 
      lock = 0; 
      sess->sendcmd(SENDOUT); 
#else 
      realbuffer->started = lock; 
      lock = 0; 
      realbuffer->sendcmd(SENDOUT); 
#endif 
    } 
  } 
}; 
 
class conxiin { 
  inherit Stdio.Buffer:i; 
 
  final Thread.Condition fillread; 
  final MUTEX fillreadmux; 
  final int procmsg; 
  private int didreadcb; 
 
#if PG_DEBUGHISTORY > 0 
  final array history = ({}); 
 
  final int(-1..) input_from(Stdio.Stream stm, void|int(0..) nbytes) { 
    int oldsize = sizeof(this); 
    int ret = i::input_from(stm, nbytes); 
    if (ret) { 
      Stdio.Buffer tb = Stdio.Buffer(this); 
      tb->consume(oldsize); 
      history += ({"<<"+tb->read(ret)}); 
      history = history[<PG_DEBUGHISTORY - 1 ..]; 
    } 
    return ret; 
  } 
#endif 
 
  protected final bool range_error(int howmuch) { 
#ifdef PG_DEBUG 
    if (howmuch < 0) { 
      int available = unread(0); 
      unread(available); 
      error("Out of range %d %O %O\n", howmuch, 
       ((string)this)[.. available-1], ((string)this)[available ..]); 
    } 
#endif 
    if (fillread) { 
      Thread.MutexKey lock = fillreadmux->lock(); 
      if (!didreadcb) 
        fillread.wait(lock); 
      didreadcb = 0; 
    } else 
      throw(MAGICTERMINATE); 
    return true; 
  } 
 
  final int read_cb(mixed id, mixed b) { 
    PD("Read callback %O\n", b && ((string)b) 
#ifndef PG_DEBUGMORE 
      [..255] 
#endif 
     ); 
    Thread.MutexKey lock = fillreadmux->lock(); 
    if (procmsg && id) 
      procmsg = 0, lock = 0, Thread.Thread(id); 
    else if (fillread) 
      didreadcb = 1, fillread.signal(); 
    return 0; 
  } 
 
  protected void create() { 
    i::create(); 
    fillreadmux = MUTEX(); 
    fillread = Thread.Condition(); 
  } 
}; 
 
class sfile { 
  inherit Stdio.File; 
  final int query_fd() { 
    return is_open() ? ::query_fd() : -1; 
  } 
}; 
 
class conxion { 
  inherit Stdio.Buffer:o; 
  final conxiin i; 
 
  private Thread.Queue qportals; 
  final MUTEX shortmux; 
  private int closenext; 
 
  final sfile 
#if constant(SSL.File) 
             |SSL.File 
#endif 
                       socket; 
  final multiset(Result) runningportals = (<>); 
 
  final MUTEX nostash; 
  final Thread.MutexKey started; 
  final Thread.Queue stashqueue; 
  final Stdio.Buffer stash; 
  //! @ignore 
  final int(KEEP..SYNCSEND) stashflushmode; 
  //! @endignore 
  final Thread.ResourceCount stashcount; 
  final int synctransact; 
#ifdef PG_DEBUGRACE 
  final mixed nostrack; 
#endif 
#ifdef PG_DEBUG 
  final int queueoutidx; 
  final int queueinidx = -1; 
#endif 
 
#if PG_DEBUGHISTORY > 0 
  final int(-1..) output_to(Stdio.Stream stm, void|int(0..) nbytes) { 
    Stdio.Buffer tb = Stdio.Buffer(this); 
    int ret = o::output_to(stm, nbytes); 
    if (ret) { 
      i->history += ({">>" + tb->read(ret)}); 
      i->history = i->history[<PG_DEBUGHISTORY - 1 ..]; 
    } 
    return ret; 
  } 
#endif 
 
  private inline void queueup(Result portal) { 
    qportals->write(portal); portal->_synctransact = synctransact; 
    PD("%d>%O %d %d Queue portal %d bytes\n", socket->query_fd(), 
     portal._portalname, ++queueoutidx, synctransact, sizeof(this)); 
  } 
 
  final bufcon|conxsess start(void|int|array(Thread.MutexKey) waitforreal) { 
    Thread.MutexKey lock; 
#ifdef PG_DEBUGRACE 
    if (nostash->current_locking_thread()) 
      PD("Nostash locked by %s\n", 
       describe_backtrace(nostash->current_locking_thread()->backtrace())); 
#endif 
    while (lock = (intp(waitforreal) && waitforreal > 0 
                   ? nostash->lock : nostash->trylock)(1)) { 
      int mode; 
      if (sizeof(stash) && (mode = getstash(KEEP)) > KEEP) 
        sendcmd(mode);          // Force out stash to the server 
      if (!stashcount->drained()) { 
        lock = 0;                               // Unlock while we wait 
        if (arrayp(waitforreal)) 
          waitforreal[0] = 0; 
        stashcount->wait_till_drained(); 
        if (arrayp(waitforreal)) 
          return 0; 
        continue;                           // Try again 
      } 
#ifdef PG_DEBUGRACE 
      conxsess sess = conxsess(this); 
#endif 
      started = lock;         // sendcmd() clears started, so delay assignment 
#ifdef PG_DEBUGRACE 
      return sess; 
#else 
      return this; 
#endif 
    } 
    if (arrayp(waitforreal)) 
      waitforreal[0] = 0; 
    return !waitforreal && bufcon(this)->start(); 
  } 
 
  private int write_cb() { 
    Thread.MutexKey lock = shortmux->lock(); 
    if (this) {                             // Guard against async destructs 
      output_to(socket); 
      lock = 0; 
      if (!i->fillread && !sizeof(this)) 
        close(); 
    } 
    return 0; 
  } 
 
  private int getstash(int mode) { 
    Thread.MutexKey lock = shortmux->lock(); 
    add(stash); stash->clear(); 
    foreach (stashqueue->try_read_array(); ; int|Result portal) 
      if (intp(portal)) 
        qportals->write(synctransact++); 
      else 
        queueup(portal); 
    PD("%d>Got stash mode %d > %d\n", 
     socket->query_fd(), stashflushmode, mode); 
    if (stashflushmode > mode) 
      mode = stashflushmode; 
    stashflushmode = KEEP; 
    return mode; 
  } 
 
  final void sendcmd(void|int mode, void|Result portal) { 
    if (portal) 
      queueup(portal); 
unfinalised: 
    do { 
      switch (mode) { 
        default: 
          break unfinalised; 
        case SYNCSEND: 
          PD("%d>Sync %d %d Queue\n", 
           socket->query_fd(), synctransact, ++queueoutidx); 
          add(PGSYNC); 
          mode = SENDOUT; 
          break; 
        case FLUSHLOGSEND: 
          PD("%d>%d Queue simplequery %d bytes\n", 
           socket->query_fd(), ++queueoutidx, sizeof(this)); 
          mode = FLUSHSEND; 
      } 
      qportals->write(synctransact++); 
    } while (0); 
    if (sizeof(stash)) 
      mode = getstash(mode); 
#ifdef PG_DEBUG 
    mixed err; 
#endif 
    for(;;) { 
#ifdef PG_DEBUG 
      err = 
#endif 
      catch { 
outer: 
        do { 
          switch (mode) { 
            default: 
              PD("%d>Skip flush %d Queue %O\n", 
               socket->query_fd(), mode, (string)this); 
              break outer; 
            case FLUSHSEND: 
              PD("Flush\n"); 
              add(PGFLUSH); 
            case SENDOUT:; 
          } 
          Thread.MutexKey lock = shortmux->trylock(); 
          if (lock && sizeof(this)) { 
            PD("%d>Sendcmd %O\n", socket->query_fd(), (string)this); 
            output_to(socket); 
          } 
        } while (0); 
        started = 0; 
        if (sizeof(stash) && (started = nostash->trylock(2))) { 
#ifdef PG_DEBUGRACE 
          conxsess sess = conxsess(this); 
          sess->sendcmd(SENDOUT); 
#else 
          mode = getstash(SENDOUT); 
          continue; 
#endif 
        } 
        return; 
      }; 
      break; 
    } 
    started = 0; 
    PD("Sendcmd failed %s\n", describe_backtrace(err)); 
    destruct(this); 
  } 
 
  final int close() { 
    if (!closenext && nostash) { 
      closenext = 1; 
      { 
        Thread.MutexKey lock = i->fillreadmux->lock(); 
        if (i->fillread) {  // Delayed close() after flushing the output buffer 
          i->fillread.signal(); 
          i->fillread = 0; 
        } 
      } 
      PD("%d>Delayed close, flush write\n", socket->query_fd()); 
      i->read_cb(socket->query_id(), 0); 
      return 0; 
    } else 
      return -1; 
  } 
 
  final void purge() { 
    if (stashcount) { 
      stashcount = 0; 
      PD("%d>Purge conxion %d\n", socket ? socket->query_fd() : -1, !!nostash); 
      int|Result portal; 
      if (qportals)                 // CancelRequest does not use qportals 
        while (portal = qportals->try_read()) 
          if (objectp(portal)) 
            portal->_purgeportal(); 
      if (nostash) { 
        while (sizeof(runningportals)) 
          catch { 
            foreach (runningportals; Result result; ) 
              if (!result.datarowtypes) { 
                result.datarowtypes = ({}); 
                if (result._state != PURGED && !result.delayederror) 
                  result.delayederror = LOSTERROR; 
                result._ddescribe->broadcast(); 
                runningportals[result] = 0; 
              } else 
                destruct(result); 
          }; 
        destruct(nostash); 
        if (socket->set_non_blocking) 
          socket->set_non_blocking();                   // Drop all callbacks 
        PD("%d>Close socket\n", socket->query_fd()); 
        socket->close();                // This will be an asynchronous close 
      } 
      destruct(this); 
    } 
  } 
 
  protected void _destruct() { 
    PD("%d>Close conxion %d\n", socket ? socket->query_fd() : -1, !!nostash); 
    catch(purge()); 
  } 
 
  final void connectloop(proxy pgsqlsess, int nossl) { 
#ifdef PG_DEBUG 
    mixed err = 
#endif 
    catch { 
      for (; ; clear()) { 
        socket->connect(pgsqlsess. host, pgsqlsess. port); 
#if constant(SSL.File) 
        if (!nossl && !pgsqlsess->nossl 
         && (pgsqlsess.options.use_ssl || pgsqlsess.options.force_ssl)) { 
          PD("SSLRequest\n"); 
          start()->add_int32(8)->add_int32(PG_PROTOCOL(1234, 5679)) 
           ->sendcmd(SENDOUT); 
          string s = socket.read(1); 
          switch (sizeof(s) && s[0]) { 
            case 'S': 
              SSL.File fcon = SSL.File(socket, SSL.Context()); 
              if (fcon->connect()) { 
                socket->set_backend(local_backend); 
                socket = fcon; 
                break; 
              } 
            default: 
              PD("%d>Close socket short\n", socket->query_fd()); 
              socket->close(); 
              pgsqlsess.nossl = 1; 
              continue; 
            case 'N': 
              if (pgsqlsess.options.force_ssl) 
                error("Encryption not supported on connection to %s:%d\n", 
                      pgsqlsess.host, pgsqlsess.port); 
          } 
        } 
#else 
        if (pgsqlsess.options.force_ssl) 
          error("Encryption library missing," 
                " cannot establish connection to %s:%d\n", 
                pgsqlsess.host, pgsqlsess.port); 
#endif 
        break; 
      } 
      if (!socket->is_open()) 
        error(strerror(socket->errno()) + ".\n"); 
      socket->set_backend(local_backend); 
      socket->set_buffer_mode(i, 0); 
      socket->set_nonblocking(i->read_cb, write_cb, close); 
      if (nossl != 2) 
        Thread.Thread(pgsqlsess->processloop, this); 
      return; 
    }; 
    PD("Connect error %s\n", describe_backtrace(err)); 
    catch(destruct(pgsqlsess->waitforauthready)); 
    destruct(this); 
  } 
 
  protected string _sprintf(int type) { 
    string res; 
    switch (type) { 
      case 'O': 
        int fd = -1; 
        if (socket) 
          catch(fd = socket->query_fd()); 
        res = predef::sprintf("conxion  fd: %d input queue: %d/%d " 
                    "queued portals: %d  output queue: %d/%d\n" 
                    "started: %d\n", 
                    fd, sizeof(i), i->_size_object(), 
                    qportals && qportals->size(), sizeof(this), _size_object(), 
                    !!started); 
        break; 
    } 
    return res; 
  } 
 
  protected void create(proxy pgsqlsess, Thread.Queue _qportals, int nossl) { 
    o::create(); 
    qportals = _qportals; 
    synctransact = 1; 
    socket = sfile(); 
    i = conxiin(); 
    shortmux = MUTEX(); 
    nostash = MUTEX(); 
    closenext = 0; 
    stashqueue = Thread.Queue(); 
    stash = Stdio.Buffer(); 
    stashcount = Thread.ResourceCount(); 
    Thread.Thread(connectloop, pgsqlsess, nossl); 
  } 
}; 
 
#ifdef PG_DEBUGRACE 
class conxsess { 
  final conxion chain; 
 
  protected void create(conxion parent) { 
    if (parent->started) 
      werror("Overwriting conxsess %s %s\n", 
        describe_backtrace(({"new ", backtrace()[..<1]})), 
        describe_backtrace(({"old ", parent->nostrack}))); 
    parent->nostrack = backtrace(); 
    chain = parent; 
  } 
 
  final void sendcmd(int mode, void|Result portal) { 
    chain->sendcmd(mode, portal); 
    chain = 0; 
  } 
 
  protected void _destruct() { 
    if (chain) 
      werror("Untransmitted conxsess %s\n", 
       describe_backtrace(({"", backtrace()[..<1]}))); 
  } 
}; 
#endif 
 
//! The result object returned by @[Sql.pgsql()->big_query()], except for 
//! the noted differences it behaves the same as @[Sql.Result]. 
//! 
//! @seealso 
//!   @[Sql.Result], @[Sql.pgsql], @[Sql.Sql], @[Sql.pgsql()->big_query()] 
class Result { 
 
  inherit __builtin.Sql.Result; 
 
  private proxy pgsqlsess; 
  private int(0..1) eoffound; 
  private conxion c; 
  private conxiin cr; 
  final int(0..1) untolderror; 
  final mixed delayederror; 
  //! @ignore 
  final int(PORTALINIT..PURGED) _state; 
  //! @endignore 
  final int _fetchlimit; 
  private int(0..1) alltext; 
  final int(0..1) _forcetext; 
  private int syncparse; 
  private int transtype; 
 
  final string _portalname; 
 
  private int inflight; 
  int portalbuffersize; 
  private MUTEX closemux; 
  private Thread.Queue datarows; 
  private Thread.ResourceCountKey stmtifkey, portalsifkey; 
  private array(mapping(string:mixed)) datarowdesc; 
  final array(int) datarowtypes;        // types from datarowdesc 
  private string statuscmdcomplete; 
  private int bytesreceived; 
  final int _synctransact; 
  final Thread.Condition _ddescribe; 
  final MUTEX _ddescribemux; 
  final Thread.MutexKey _unnamedportalkey, _unnamedstatementkey; 
  final array _params; 
  final string _query; 
  final string _preparedname; 
  final mapping(string:mixed) _tprepared; 
  private function(:void) gottimeout; 
  private int timeout; 
 
  protected string _sprintf(int type) { 
    string res; 
    switch (type) { 
      case 'O': 
        int fd = -1; 
        if (c && c->socket) 
          catch(fd = c->socket->query_fd()); 
        res = sprintf( 
                      "Result state: %d numrows: %d eof: %d inflight: %d\n" 
                      "fd: %O portalname: %O  coltypes: %d" 
                      "  synctransact: %d laststatus: %s\n" 
                      "stash: %O\n" 
#if PG_DEBUGHISTORY > 0 
                      "history: %O\n" 
#endif 
                      "query: %O\n%s\n", 
                      _state, index, eoffound, inflight, 
                      fd, _portalname, 
                      datarowtypes && sizeof(datarowtypes), _synctransact, 
                      statuscmdcomplete 
                       || (_unnamedstatementkey ? "*parsing*" : ""), 
                      qalreadyprinted == this ? 0 
                                              : c && (string)c->stash, 
#if PG_DEBUGHISTORY > 0 
                      qalreadyprinted == this ? 0 : c && c->i->history, 
#endif 
                      qalreadyprinted == this 
                       ? "..." : replace(_query, "xxxx\n", "\\n"), 
                      qalreadyprinted == this ? "..." : _showbindings()*"\n"); 
        qalreadyprinted = this; 
        break; 
    } 
    return res; 
  } 
 
  protected void create(proxy _pgsqlsess, conxion _c, string query, 
   int _portalbuffersize, int alltyped, array params, int forcetext, 
   int _timeout, int _syncparse, int _transtype) { 
    pgsqlsess = _pgsqlsess; 
    if (c = _c) 
      cr = c->i; 
    else 
      losterror(); 
    _query = query; 
    datarows = Thread.Queue(); 
    _ddescribe = Thread.Condition(); 
    _ddescribemux = MUTEX(); 
    closemux = MUTEX(); 
    portalbuffersize = _portalbuffersize; 
    alltext = !alltyped; 
    _params = params; 
    _forcetext = forcetext; 
    _state = PORTALINIT; 
    timeout = _timeout; 
    syncparse = _syncparse; 
    gottimeout = _pgsqlsess->cancelquery; 
    c->runningportals[this] = 1; 
    transtype = _transtype; 
  } 
 
  final array(string) _showbindings() { 
    array(string) msgs = ({}); 
    if (_params) { 
      array from, to, paramValues; 
      [from, to, paramValues] = _params; 
      if (sizeof(paramValues)) { 
        int i; 
        string val, fmt = sprintf("%%%ds %%3s %%.61s", max(@map(from, sizeof))); 
        foreach (paramValues; i; val) 
          msgs += ({sprintf(fmt, from[i], to[i], sprintf("%O", val))}); 
      } 
    } 
    return msgs; 
  } 
 
  //! Returns the command-complete status for this query. 
  //! 
  //! @seealso 
  //!  @[Sql.Result()->status_command_complete()] 
  /*semi*/final string status_command_complete() { 
    if (!statuscmdcomplete) { 
      if (!datarowtypes) 
        waitfordescribe(); 
      { 
        Thread.MutexKey lock = closemux->lock(); 
        if (_fetchlimit) { 
          array(Thread.MutexKey) reflock = ({ _fetchlimit = 0 }); 
          for (;;) { 
            reflock[0] = lock; 
            lock = 0; 
            if (!_sendexecute(0, reflock)) { 
              PD("Status_command_complete retry closemux %O\n", _portalname); 
              lock = closemux->lock(); 
              continue; 
            } 
          } 
        } 
        lock = 0;                       // Force release before acquiring next 
        lock = _ddescribemux->lock(); 
        if (!statuscmdcomplete) 
          PT(_ddescribe->wait(lock)); 
      } 
      if (this)         // If object already destructed, skip the next call 
        trydelayederror();      // since you cannot call functions anymore 
      else 
        error(LOSTERROR); 
    } 
    return statuscmdcomplete; 
  } 
 
  //! Returns the number of affected rows by this query. 
  //! 
  //! @seealso 
  //!  @[Sql.Result()->affected_rows()] 
  /*semi*/final int affected_rows() { 
    int rows; 
    sscanf(status_command_complete() || "", "%*s %d %d", rows, rows); 
    return rows; 
  } 
 
  final void _storetiming() { 
    if (_tprepared) { 
      _tprepared.trun = gethrtime() - _tprepared.trunstart; 
      m_delete(_tprepared, "trunstart"); 
      _tprepared = 0; 
    } 
  } 
 
  private void waitfordescribe() { 
    { 
      Thread.MutexKey lock = _ddescribemux->lock(); 
      if (!datarowtypes) 
        PT(_ddescribe->wait(lock)); 
    } 
    if (this)           // If object already destructed, skip the next call 
      trydelayederror();        // since you cannot call functions anymore 
    else 
      error(LOSTERROR); 
  } 
 
  //! @seealso 
  //!  @[Sql.Result()->num_fields()] 
  /*semi*/final int num_fields() { 
    if (!datarowtypes) 
      waitfordescribe(); 
    return sizeof(datarowtypes); 
  } 
 
  //! @note 
  //!  This method returns the number of rows already received from 
  //!  the database for the current query.  Note that this number 
  //!  can still increase between subsequent calls if the results from 
  //!  the query are not complete yet.  This function is only guaranteed to 
  //!  return the correct count after EOF has been reached. 
  //! @seealso 
  //!  @[Sql.Result()->num_rows()] 
  /*semi*/final int num_rows() { 
    trydelayederror(); 
    return index; 
  } 
 
  private void losterror() { 
    string err; 
    if (pgsqlsess) 
      err = pgsqlsess->geterror(1); 
    error("%s\n", err || LOSTERROR); 
  } 
 
  private void trydelayederror() { 
    if (delayederror) 
      throwdelayederror(this); 
    else if (_state == PURGED) 
      losterror(); 
  } 
 
  //! @seealso 
  //!  @[Sql.Result()->eof()] 
  /*semi*/final int eof() { 
    trydelayederror(); 
    return eoffound; 
  } 
 
  //! @seealso 
  //!  @[Sql.Result()->fetch_fields()] 
  /*semi*/final array(mapping(string:mixed)) fetch_fields() { 
    if (!datarowtypes) 
      waitfordescribe(); 
    if (!datarowdesc) 
      error(LOSTERROR); 
    return datarowdesc + ({}); 
  } 
 
#ifdef PG_DEBUG 
#define INTVOID int 
#else 
#define INTVOID void 
#endif 
  final INTVOID _decodedata(int msglen, string cenc) { 
    _storetiming(); _releasestatement(); 
    string serror; 
    bytesreceived += msglen; 
    int cols = cr->read_int16(); 
    array a = allocate(cols, !alltext && Val.null); 
#ifdef PG_DEBUG 
    msglen -= 2 + 4 * cols; 
#endif 
    foreach (datarowtypes; int i; int typ) { 
      int collen = cr->read_sint(4); 
      if (collen > 0) { 
#ifdef PG_DEBUG 
        msglen -= collen; 
#endif 
        mixed value; 
        switch (typ) { 
          case FLOAT4OID: 
#if !constant(__builtin.__SINGLE_PRECISION_FLOAT__) 
          case FLOAT8OID: 
#endif 
            if (_forcetext) { 
              if (!alltext) { 
                value = (float)cr->read(collen); 
                break; 
              } 
            } else { 
              [ value ] = cr->sscanf(collen == 4 ? "%4F" : "%8F"); 
              if (alltext) 
                value = sprintf("%.*g", collen == 4 ? 9 : 17, value); 
              break; 
            } 
          default:value = cr->read(collen); 
            break; 
          case CHAROID: 
            value = alltext ? cr->read(1) : cr->read_int8(); 
            break; 
          case BOOLOID:value = cr->read_int8(); 
            switch (value) { 
              case 'f':value = 0; 
                break; 
              case 't':value = 1; 
            } 
            if (alltext) 
              value = value ? "t" : "f"; 
            break; 
          case TEXTOID: 
          case BPCHAROID: 
          case VARCHAROID: 
            value = cr->read(collen); 
            if (cenc == UTF8CHARSET && catch(value = utf8_to_string(value)) 
             && !serror) 
              serror = SERROR("%O contains non-%s characters\n", 
                                                     value, UTF8CHARSET); 
            break; 
          case NUMERICOID: 
            if (_forcetext) { 
              value = cr->read(collen); 
              if (!alltext) { 
                value = value/"."; 
                if (sizeof(value) == 1) 
                  value = (int)value[0]; 
                else { 
                  int i, denom; 
                  for (i = sizeof(value[1]), denom = 1; --i >= 0; denom *= 10); 
                  i = (int)value[0]; 
                  value = (int)value[1]; 
                  value = Gmp.mpq(i * denom + (i >= 0 ? value : -value), 
                   denom); 
                } 
              } 
            } else { 
              int nwords = cr->read_int16(); 
              int magnitude = cr->read_sint(2); 
              int sign = cr->read_int16(); 
              cr->consume(2); 
              if (nwords) { 
                for (value = cr->read_int16(); --nwords; magnitude--) 
                  value = value * NUMERIC_MAGSTEP + cr->read_int16(); 
                if (sign) 
                  value = -value; 
                if (magnitude > 0) 
                  do 
                    value *= NUMERIC_MAGSTEP; 
                  while (--magnitude); 
                else if (magnitude < 0) { 
                  for (sign = NUMERIC_MAGSTEP; 
                       ++magnitude; 
                       sign *= NUMERIC_MAGSTEP); 
                  value = Gmp.mpq(value, sign); 
                } 
              } else 
                value = 0; 
              if (alltext) 
                value = (string)value; 
            } 
            break; 
          case INT4RANGEOID: 
          case INT8RANGEOID: 
          case DATERANGEOID: 
          case TSRANGEOID: 
          case TSTZRANGEOID: 
            if (_forcetext) 
              value = cr->read(collen); 
            else { 
              array totype = oidtotype[typ]; 
              mixed from = -Math.inf, till = Math.inf; 
              switch (cr->read_int8()) { 
                case 1: from = till = 0; 
                  break; 
                case 0x12: from = cr->read_sint(cr->read_int32()); 
                  break; 
                case 2: from = cr->read_sint(cr->read_int32()); 
                case 8: till = cr->read_sint(cr->read_int32()); 
              } 
              if (totype[0]) { 
                if (intp(from)) { 
                  value = totype[0](); 
                  value[totype[3]] = from + totype[2]; 
                  from = value; 
                } 
                if (intp(till)) { 
                  value = totype[0](); 
                  value[totype[3]] = till + totype[2]; 
                  till = value; 
                } 
              } 
              value = Val.Range(from, till); 
              if (alltext) 
                value = value->sql(); 
            } 
            break; 
          case CIDROID: 
          case INETOID: 
            if (_forcetext) 
              value = cr->read(collen); 
            else { 
              value = Val.Inet(); 
              int iptype = cr->read_int8(); // 2 == IPv4, 3 == IPv6 
              value->masklen = cr->read_int8() + (iptype == 2 && 12*8); 
              cr->read_int8();  // 0 == INET, 1 == CIDR 
              value->address = cr->read_hint(1); 
              if (alltext) 
                value = (string)value; 
            } 
            break; 
          case TIMESTAMPOID: 
          case TIMESTAMPTZOID: 
          case INTERVALOID: 
          case TIMETZOID: 
          case TIMEOID: 
          case DATEOID: 
            if (_forcetext) 
              value = cr->read(collen); 
            else { 
              array totype = oidtotype[typ]; 
              value = totype[0](); 
              value[totype[3]] = cr->read_sint(totype[4]) + totype[2]; 
              int i = 5; 
              while (i < sizeof(totype)) { 
                value[totype[i]] = cr->read_sint(totype[i+1]); 
                i += 2; 
              } 
              if (alltext) 
                value = (string)value; 
            } 
            break; 
          case INT8OID:case INT2OID: 
          case OIDOID:case INT4OID: 
            if (_forcetext) { 
              value = cr->read(collen); 
              if (!alltext) 
                value = (int)value; 
            } else { 
              switch (typ) { 
                case INT8OID:value = cr->read_sint(8); 
                  break; 
                case INT2OID:value = cr->read_sint(2); 
                  break; 
                case OIDOID: 
                case INT4OID:value = cr->read_sint(4); 
              } 
              if (alltext) 
                value = (string)value; 
            } 
        } 
        a[i]=value; 
      } else if (!collen) 
        a[i]=""; 
    } 
    _processdataready(a); 
    if (serror) 
      error(serror); 
#ifdef PG_DEBUG 
    return msglen; 
#endif 
  } 
 
  final void _setrowdesc(array(mapping(string:mixed)) drowdesc, 
   array(int) drowtypes) { 
    Thread.MutexKey lock = _ddescribemux->lock(); 
    datarowdesc = drowdesc; 
    datarowtypes = drowtypes; 
    _ddescribe->broadcast(); 
  } 
 
  final void _preparebind(array dtoid) { 
    array(string|int) paramValues = _params ? _params[2] : ({}); 
    if (sizeof(dtoid) != sizeof(paramValues)) 
      SUSERERROR("Invalid number of bindings, expected %d, got %d\n", 
                 sizeof(dtoid), sizeof(paramValues)); 
    PD("PrepareBind\n"); 
    Thread.MutexKey lock = _ddescribemux->lock(); 
    if (!_portalname) { 
      _portalname 
       = (_unnamedportalkey = pgsqlsess.unnamedportalmux->trylock(1)) 
         ? "" : PORTALPREFIX 
#ifdef PG_DEBUG 
          + (string)(c->socket->query_fd()) + "_" 
#endif 
          + String.int2hex(pgsqlsess.pportalcount++); 
      lock = 0; 
#ifdef PG_DEBUGMORE 
      PD("ParamValues to bind: %O\n", paramValues); 
#endif 
      Stdio.Buffer plugbuffer = Stdio.Buffer(); 
      { array dta = ({sizeof(dtoid)}); 
        plugbuffer->add(_portalname, 0, _preparedname, 0) 
         ->add_ints(dta 
           + map(dtoid, writeoidformat, paramValues, ({0})) + dta, 2); 
      } 
      string cenc = pgsqlsess.runtimeparameter[CLIENT_ENCODING]; 
      foreach (paramValues; int i; mixed value) { 
        if (undefinedp(value) || objectp(value) && value->is_val_null) 
          plugbuffer->add_int32(-1);                            // NULL 
        else if (stringp(value) && !sizeof(value)) { 
          int k = 0; 
          switch (dtoid[i]) { 
            default: 
              k = -1;        // cast empty strings to NULL for non-string types 
            case BYTEAOID: 
            case TEXTOID: 
            case XMLOID: 
            case BPCHAROID: 
            case VARCHAROID:; 
          } 
          plugbuffer->add_int32(k); 
        } else 
          switch (dtoid[i]) { 
            case TEXTOID: 
            case BPCHAROID: 
            case VARCHAROID: { 
              if (!value) { 
                plugbuffer->add_int32(-1); 
                break; 
              } 
              value = (string)value; 
              switch (cenc) { 
                case UTF8CHARSET: 
                  if (has_value(value, 0)) 
                    SUSERERROR("NUL characters not allowed in PG-UTF-8: %O\n", 
                     value); 
                  else 
                    value = string_to_utf8(value); 
                  break; 
                default: 
                  if (String.width(value)>8) { 
                    SUSERERROR("Don't know how to convert %O to %s encoding\n", 
                               value, cenc); 
                    value=""; 
                  } 
              } 
              plugbuffer->add_hstring(value, 4); 
              break; 
            } 
            default: { 
              if (!value) { 
                plugbuffer->add_int32(-1); 
                break; 
              } 
              if (!objectp(value) || typeof(value) != typeof(Stdio.Buffer())); 
                /* 
                 *  Like Oracle and SQLite, we accept literal binary values 
                 *  from single-valued multisets. 
                 */ 
                if (multisetp(value) && sizeof(value) == 1) 
                  value = indices(value)[0]; 
                else { 
                  value = (string)value; 
                  if (String.width(value) > 8) 
                    if (dtoid[i] == BYTEAOID) 
                      /* 
                       *  FIXME We should throw an error here, it would 
                       *  have been correct, but for historical reasons and 
                       *  as a DWIM convenience we autoconvert to UTF8 here. 
                       */ 
                      value = string_to_utf8(value); 
                    else { 
                      SUSERERROR( 
                        "Wide string %O not supported for type OID %d\n", 
                        value, dtoid[i]); 
                      value = ""; 
                    } 
                } 
              plugbuffer->add_hstring(value, 4); 
              break; 
            } 
            case BOOLOID: 
              do { 
                int tval; 
                if (stringp(value)) 
                  tval = value[0]; 
                else if (!intp(value)) { 
                  value = !!value;                      // cast to boolean 
                  break; 
                } else 
                  tval = value; 
                switch (tval) { 
                  case 'o':case 'O': 
                    catch { 
                      tval = value[1]; 
                      value = tval == 'n' || tval == 'N'; 
                    }; 
                    break; 
                  default: 
                    value = 1; 
                    break; 
                  case 0:case '0':case 'f':case 'F':case 'n':case 'N': 
                    value = 0; 
                      break; 
                } 
              } while (0); 
              plugbuffer->add("\0\0\0\1", value); 
              break; 
            case CHAROID: 
              if (intp(value)) 
                plugbuffer->add_hstring(value, 4); 
              else { 
                value = (string)value; 
                switch (sizeof(value)) { 
                  default: 
                    SUSERERROR( 
                     "\"char\" types must be 1 byte wide, got %O\n", value); 
                  case 0: 
                    plugbuffer->add_int32(-1);                  // NULL 
                    break; 
                  case 1: 
                    plugbuffer->add_hstring(value[0], 4); 
                } 
              } 
              break; 
            case NUMERICOID: 
              if (stringp(value)) 
                plugbuffer->add_hstring(value, 4); 
              else { 
                int num, den, sign, magnitude = 0; 
                value = Gmp.mpq(value); 
                num = value->num(); 
                den = value->den(); 
                for (value = den; 
                     value > NUMERIC_MAGSTEP; 
                     value /= NUMERIC_MAGSTEP); 
                if (value > 1) { 
                  value = NUMERIC_MAGSTEP / value; 
                  num *= value; 
                  den *= value; 
                } 
                if (num < 0) 
                  sign = 0x4000, num = -num; 
                else 
                  sign = 0; 
                array stor = ({}); 
                if (num) { 
                  while (!(num % NUMERIC_MAGSTEP)) 
                    num /= NUMERIC_MAGSTEP, magnitude++; 
                  do 
                    stor = ({num % NUMERIC_MAGSTEP}) + stor, magnitude++; 
                  while (num /= NUMERIC_MAGSTEP); 
                  num = --magnitude << 2; 
                  while (den > 1) 
                    magnitude--, den /= NUMERIC_MAGSTEP; 
                } 
                plugbuffer->add_int32(4 * 2 + (sizeof(stor) << 1)) 
                 ->add_int16(sizeof(stor))->add_int16(magnitude) 
                 ->add_int16(sign)->add_int16(num)->add_ints(stor, 2); 
              } 
              break; 
            case INT4RANGEOID: 
            case INT8RANGEOID: 
            case DATERANGEOID: 
            case TSRANGEOID: 
            case TSTZRANGEOID: 
              if (stringp(value)) 
                plugbuffer->add_hstring(value, 4); 
              else if (value->from >= value->till) 
                plugbuffer->add("\0\0\0\1\1"); 
              else { 
                array totype = oidtotype[dtoid[i]]; 
                int w = totype[1]; 
                int from, till; 
                if (totype[0]) 
                  from = value->from, till = value->till; 
                else { 
                  from = value->from[totype[3]] - totype[2]; 
                  till = value->till[totype[3]] - totype[2]; 
                } 
                if (value->till == Math.inf) 
                  if (value->from == -Math.inf) 
                    plugbuffer->add("\0\0\0\1\30"); 
                  else 
                    plugbuffer->add("\0\0\0", 1 + 4 + w, "\22\0\0\0", w) 
                     ->add_int(from, w); 
                else { 
                  if (value->from == -Math.inf) 
                    plugbuffer->add("\0\0\0", 1 + 4 + w, 8); 
                  else 
                    plugbuffer->add("\0\0\0", 1 + 4 * 2 + w * 2, "\2\0\0\0", w) 
                     ->add_int(from, w); 
                  plugbuffer->add_int32(w)->add_int(till, w); 
                } 
              } 
              break; 
            case CIDROID: 
            case INETOID: 
              if (stringp(value)) 
                plugbuffer->add_hstring(value, 4); 
              else if (value->address <= 0xffffffff)    // IPv4 
                plugbuffer->add("\0\0\0\10\2", 
                  value->masklen - 12 * 8, dtoid[i] == CIDROID, 4) 
                 ->add_int32(value->address); 
              else                                  // IPv6 
                plugbuffer->add("\0\0\0\24\3", 
                  value->masklen, dtoid[i] == CIDROID, 16) 
                 ->add_int(value->address, 16); 
              break; 
            case DATEOID: 
            case TIMEOID: 
            case TIMETZOID: 
            case INTERVALOID: 
            case TIMESTAMPOID: 
            case TIMESTAMPTZOID: 
              if (stringp(value)) 
                plugbuffer->add_hstring(value, 4); 
              else { 
                array totype = oidtotype[dtoid[i]]; 
                if (!objectp(value)) 
                  value = totype[0](value); 
                plugbuffer->add_int32(totype[1]) 
                 ->add_int(value[totype[3]] - totype[2], totype[4]); 
                int i = 5; 
                while (i < sizeof(totype)) { 
                  plugbuffer->add_int(value[totype[i]], totype[i+1]); 
                  i += 2; 
                } 
              } 
              break; 
            case FLOAT4OID: 
#if !constant(__builtin.__SINGLE_PRECISION_FLOAT__) 
            case FLOAT8OID: 
#endif 
              if (stringp(value)) 
                plugbuffer->add_hstring(value, 4); 
              else { 
                int w = dtoid[i] == FLOAT4OID ? 4 : 8; 
                plugbuffer->add_int32(w) 
                 ->sprintf(w == 4 ? "%4F" : "%8F", (float)value); 
              } 
              break; 
            case INT8OID: 
              plugbuffer->add_int32(8)->add_int((int)value, 8); 
              break; 
            case OIDOID: 
            case INT4OID: 
              plugbuffer->add_int32(4)->add_int32((int)value); 
              break; 
            case INT2OID: 
              plugbuffer->add_int32(2)->add_int16((int)value); 
              break; 
          } 
      } 
      if (!datarowtypes) { 
        if (_tprepared && dontcacheprefix->match(_query)) 
          m_delete(pgsqlsess->prepareds, _query), _tprepared = 0; 
        PD("WaitForDescribe\n"); 
        waitfordescribe(); 
      } 
      PD("About to bind %d\n", _state); 
      if (_state >= CLOSING) 
        lock = _unnamedstatementkey = 0; 
      else { 
        plugbuffer->add_int16(sizeof(datarowtypes)); 
        if (sizeof(datarowtypes)) { 
          plugbuffer->add_ints(map(datarowtypes, readoidformat), 2); 
          lock = 0; 
        } else if (syncparse < 0 && !pgsqlsess->wasparallelisable 
         && !pgsqlsess->statementsinflight->drained(1)) { 
          lock = 0;                             // Unlock while we wait 
          PD("Commit waiting for statements to finish\n"); 
          catch(PT(pgsqlsess->statementsinflight->wait_till_drained(1))); 
        } 
        PD("Bind portal %O statement %O\n", _portalname, _preparedname); 
        _fetchlimit = pgsqlsess->_fetchlimit; 
        _bindportal(); 
        conxsess bindbuffer = c->start(); 
        stmtifkey = 0; 
        CHAIN(bindbuffer)->add_int8('B')->add_hstring(plugbuffer, 4, 4); 
        if (!_tprepared && sizeof(_preparedname)) 
          closestatement(CHAIN(bindbuffer), _preparedname); 
        _sendexecute(_fetchlimit 
                             && !(transtype != NOTRANS 
                                  || sizeof(_query) >= MINPREPARELENGTH && 
                                  execfetchlimit->match(_query)) 
                             && _fetchlimit, bindbuffer); 
        _unnamedstatementkey = 0; 
      } 
    } 
  } 
 
  final void _processrowdesc(array(mapping(string:mixed)) datarowdesc, 
   array(int) datarowtypes) { 
    _setrowdesc(datarowdesc, datarowtypes); 
    if (_tprepared) { 
      _tprepared.datarowdesc = datarowdesc; 
      _tprepared.datarowtypes = datarowtypes; 
    } 
  } 
 
  final void _parseportal() { 
    for (;;) { 
      Thread.MutexKey lock = closemux->lock(); 
      if ((syncparse || syncparse < 0 && pgsqlsess->wasparallelisable) 
         && !pgsqlsess->statementsinflight->drained()) { 
        lock = 0;                               // Unlock while we wait 
        PD("Commit waiting for statements to finish %d\n", 
         pgsqlsess->statementsinflight->_count); 
        catch(PT(pgsqlsess->statementsinflight->wait_till_drained())); 
        PD("Parseportal retry closemux %O\n", _portalname); 
        continue; 
      } 
      _state = PARSING; 
      stmtifkey = pgsqlsess->statementsinflight->acquire(); 
      break; 
    } 
    statuscmdcomplete = 0; 
    pgsqlsess->wasparallelisable = paralleliseprefix->match(_query); 
  } 
 
  final void _releasestatement() { 
    Thread.MutexKey lock = closemux->lock(); 
    if (_state <= BOUND) { 
      stmtifkey = 0; 
      _state = COMMITTED; 
    } 
  } 
 
  final void _bindportal() { 
    Thread.MutexKey lock = closemux->lock(); 
    _state = BOUND; 
    portalsifkey = pgsqlsess->portalsinflight->acquire(); 
  } 
 
  final void _purgeportal() { 
    PD("Purge portal\n"); 
    datarows->write(1);                            // Signal EOF 
    { 
      Thread.MutexKey lock = closemux->lock(); 
      _fetchlimit = 0;                             // disables further Executes 
      stmtifkey = portalsifkey = 0; 
      _state = PURGED; 
    } 
    releaseconditions(); 
  } 
 
  final int _closeportal(conxsess cs, array(Thread.MutexKey) reflock) { 
    void|bufcon|conxsess plugbuffer = CHAIN(cs); 
    int retval = KEEP; 
    PD("%O Try Closeportal %d\n", _portalname, _state); 
    _fetchlimit = 0;                               // disables further Executes 
    stmtifkey = 0; 
    switch (_state) { 
      case PORTALINIT: 
      case PARSING: 
        _unnamedstatementkey = 0; 
        _state = CLOSING; 
        break; 
      case COPYINPROGRESS: 
        PD("CopyDone\n"); 
        plugbuffer->add("c\0\0\0\4"); 
      case COMMITTED: 
      case BOUND: 
        _state = CLOSING; 
        if (reflock) 
          reflock[0] = 0; 
        PD("Close portal %O\n", _portalname); 
        if (_portalname && sizeof(_portalname)) { 
          plugbuffer->add_int8('C') 
           ->add_hstring(({'P', _portalname, 0}), 4, 4); 
          retval = FLUSHSEND; 
        } else 
          _unnamedportalkey = 0; 
        portalsifkey = 0; 
        if (pgsqlsess->portalsinflight->drained()) { 
          if (plugbuffer->stashcount->drained() && transtype != TRANSBEGIN) { 
           /* 
            * stashcount will be non-zero if a parse request has been queued 
            * before the close was initiated. 
            */ 
            Thread.MutexKey lock = plugbuffer->shortmux->lock(); 
            if (plugbuffer->stashcount->drained()) 
              pgsqlsess->readyforquerycount++, retval = SYNCSEND; 
          } 
          pgsqlsess->pportalcount = 0; 
        } 
    } 
    return retval; 
  } 
 
  private void replenishrows() { 
   if (_fetchlimit && datarows->size() <= _fetchlimit >> 1 
    && _state >= COMMITTED) { 
      Thread.MutexKey lock; 
      for (;;) { 
        lock = closemux->lock(); 
        if (_fetchlimit) { 
          _fetchlimit = pgsqlsess._fetchlimit; 
          if (bytesreceived) 
            _fetchlimit = min((portalbuffersize >> 1) 
             * index / bytesreceived || 1, _fetchlimit); 
          if (_fetchlimit) 
            if (inflight <= (_fetchlimit - 1) >> 1) { 
              array(Thread.MutexKey) reflock = ({ lock }); 
              lock = 0; 
              if (!_sendexecute(_fetchlimit, reflock)) { 
                PD("Replenishrows retry closemux %O\n", _portalname); 
                continue; 
              } 
            } else 
              PD("<%O _fetchlimit %d, inflight %d, skip execute\n", 
               _portalname, _fetchlimit, inflight); 
        } 
        break; 
      } 
    } 
  } 
 
  final void _processdataready(array datarow, void|int msglen) { 
    bytesreceived += msglen; 
    inflight--; 
    if (_state < CLOSED) 
      datarows->write(datarow); 
    if (++index == 1) 
      PD("<%O _fetchlimit %d=min(%d||1,%d), inflight %d\n", _portalname, 
       _fetchlimit, (portalbuffersize >> 1) * index / bytesreceived, 
       pgsqlsess._fetchlimit, inflight); 
    replenishrows(); 
  } 
 
  private void releaseconditions(void|int aborted) { 
    _unnamedportalkey = _unnamedstatementkey = 0; 
    if (!datarowtypes) { 
      if (_state != PURGED && !delayederror) 
        delayederror = LOSTERROR; 
      datarowtypes = ({}); 
      _ddescribe->broadcast(); 
    } 
    if (aborted && delayederror && pgsqlsess && !pgsqlsess.delayederror) 
      pgsqlsess.delayederror = delayederror;    // Preserve error upstream 
    pgsqlsess = 0;                              // Sever connection to upstream 
  } 
 
  final void _releasesession(void|string statusccomplete) { 
    int aborted = statusccomplete == "ABORT" ? 2 : 0; 
    c->runningportals[this] = 0; 
    if (statusccomplete && !statuscmdcomplete) { 
      Thread.MutexKey lock = _ddescribemux->lock(); 
      statuscmdcomplete = statusccomplete; 
      _ddescribe->broadcast(); 
    } 
    inflight = 0; 
    conxsess plugbuffer; 
    array(Thread.MutexKey) reflock = ({ 0 }); 
    for (;;) { 
      reflock[0] = closemux->lock(aborted); 
      if (!catch(plugbuffer = c->start(reflock))) 
        if (plugbuffer) 
          plugbuffer->sendcmd(_closeportal(plugbuffer, reflock)); 
        else { 
          PD("Releasesession retry closemux %O\n", _portalname); 
          continue; 
        } 
      break; 
    } 
    reflock[0] = 0; 
    if (_state < CLOSED) { 
      stmtifkey = 0; 
      _state = CLOSED; 
    } 
    datarows->write(1);                         // Signal EOF 
    releaseconditions(aborted); 
  } 
 
  protected void _destruct() { 
    if (_state < CLOSED) 
      catch {                     // inside destructors, exceptions don't work 
        _releasesession("ABORT"); 
      }; 
  } 
 
  final int _sendexecute(int fetchlimit, 
   void|array(Thread.MutexKey)|bufcon|conxsess plugbuffer) { 
    int flushmode; 
    array(Thread.MutexKey) reflock; 
    PD("Execute portal %O fetchlimit %d transtype %d\n", _portalname, 
     fetchlimit, transtype); 
    if (arrayp(plugbuffer)) { 
      reflock = plugbuffer; 
      if (!(plugbuffer = c->start(reflock))) 
        return 0;   // Found potential deadlock, release and try again 
    } 
    CHAIN(plugbuffer)->add_int8('E')->add_hstring(({_portalname, 0}), 4, 8) 
     ->add_int32(fetchlimit); 
    if (!fetchlimit) { 
      if (transtype != NOTRANS) 
        pgsqlsess.intransaction = transtype == TRANSBEGIN; 
      flushmode = _closeportal(plugbuffer, reflock) == SYNCSEND 
       || transtype == TRANSEND ? SYNCSEND : FLUSHSEND; 
    } else 
      inflight += fetchlimit, flushmode = FLUSHSEND; 
    plugbuffer->sendcmd(flushmode, this); 
    if (reflock) 
      reflock[0] = 0; 
    return 1; 
  } 
 
  inline private array setuptimeout() { 
    return local_backend->call_out(gottimeout, timeout); 
  } 
 
  inline private void scuttletimeout(array cid) { 
    if (local_backend) 
      local_backend->remove_call_out(cid); 
  } 
 
  //! @returns 
  //!  One result row at a time. 
  //! 
  //! When using COPY FROM STDOUT, this method returns one row at a time 
  //! as a single string containing the entire row. 
  //! 
  //! @seealso 
  //!  @[eof()], @[send_row()] 
  /*semi*/final array(mixed) fetch_row() { 
    int|array datarow; 
    if (!this)                  // If object already destructed, return fast 
      return 0; 
    replenishrows(); 
    if (arrayp(datarow = datarows->try_read())) 
      return datarow; 
    if (!eoffound) { 
      if (!datarow) { 
        PD("%O Block for datarow\n", _portalname); 
        array cid = setuptimeout(); 
        PT(datarow = datarows->read()); 
        if (!this)              // If object already destructed, return fast 
          return 0; 
        scuttletimeout(cid); 
        if (arrayp(datarow)) 
          return datarow; 
      } 
      eoffound = 1; 
      datarows->write(1);                       // Signal EOF for other threads 
    } 
    trydelayederror(); 
    return 0; 
  } 
 
  //! @returns 
  //!  Multiple result rows at a time (at least one). 
  //! 
  //! When using COPY FROM STDOUT, this method returns one row at a time 
  //! as a single string containing the entire row. 
  //! 
  //! @seealso 
  //!  @[eof()], @[fetch_row()] 
  /*semi*/final array(array(mixed)) fetch_row_array() { 
    if (eoffound) 
      return 0; 
    replenishrows(); 
    array(array|int) datarow = datarows->try_read_array(); 
    if (!sizeof(datarow)) { 
      array cid = setuptimeout(); 
      PT(datarow = datarows->read_array()); 
      if (!this)                // If object already destructed, return fast 
        return 0; 
      scuttletimeout(cid); 
    } 
    replenishrows(); 
    if (arrayp(datarow[-1])) 
      return datarow; 
    do datarow = datarow[..<1];                     // Swallow EOF mark(s) 
    while (sizeof(datarow) && !arrayp(datarow[-1])); 
    trydelayederror(); 
    eoffound = 1; 
    datarows->write(1);                         // Signal EOF for other threads 
    return datarow; 
  } 
 
  //! @param copydata 
  //! When using COPY FROM STDIN, this method accepts a string or an 
  //! array of strings to be processed by the COPY command; when sending 
  //! the amount of data sent per call does not have to hit row or column 
  //! boundaries. 
  //! 
  //! The COPY FROM STDIN sequence needs to be completed by either 
  //! explicitly or implicitly destroying the result object, or by passing no 
  //! argument to this method. 
  //! 
  //! @seealso 
  //!  @[fetch_row()], @[eof()] 
  /*semi*/final void send_row(void|string|array(string) copydata) { 
    trydelayederror(); 
    if (copydata) { 
      PD("CopyData\n"); 
      void|bufcon|conxsess cs = c->start(); 
      CHAIN(cs)->add_int8('d')->add_hstring(copydata, 4, 4); 
      cs->sendcmd(SENDOUT); 
    } else 
      _releasesession(); 
  } 
 
  private void run_result_cb( 
   function(Result, array(mixed), mixed ...:void) callback, 
   array(mixed) args) { 
    int|array datarow; 
    for (;;) { 
      array cid = setuptimeout(); 
      PT(datarow = datarows->read()); 
      if (!this)                // If object already destructed, return fast 
        return 0; 
      scuttletimeout(cid); 
      if (!arrayp(datarow)) 
        break; 
      callout(callback, 0, this, datarow, @args); 
    } 
    eoffound = 1; 
    callout(callback, 0, this, 0, @args); 
  } 
 
  //! Sets up a callback for every row returned from the database. 
  //! First argument passed is the resultobject itself, second argument 
  //! is the result row (zero on EOF). 
  //! 
  //! @seealso 
  //!  @[fetch_row()] 
  /*semi*/final void set_result_callback( 
   function(Result, array(mixed), mixed ...:void) callback, 
   mixed ... args) { 
    if (callback) 
      Thread.Thread(run_result_cb, callback, args); 
  } 
 
  private void run_result_array_cb( 
   function(Result, array(array(mixed)), mixed ...:void) callback, 
   array(mixed) args) { 
    array(array|int) datarow; 
    for (;;) { 
      array cid = setuptimeout(); 
      PT(datarow = datarows->read_array()); 
      if (!this)                // If object already destructed, return fast 
        return 0; 
      scuttletimeout(cid); 
      if (!datarow || !arrayp(datarow[-1])) 
        break; 
      callout(callback, 0, this, datarow, @args); 
    } 
    eoffound = 1; 
    if (sizeof(datarow)>1) 
      callout(callback, 0, this, datarow = datarow[..<1], @args); 
    callout(callback, 0, this, 0, @args); 
  } 
 
  //! Sets up a callback for sets of rows returned from the database. 
  //! First argument passed is the resultobject itself, second argument 
  //! is the array of result rows (zero on EOF). 
  //! 
  //! @seealso 
  //!  @[fetch_row()] 
  /*semi*/final void set_result_array_callback( 
   function(Result, array(array(mixed)), mixed ...:void) callback, 
   mixed ... args) { 
    if (callback) 
      Thread.Thread(run_result_array_cb, callback, args); 
  } 
 
}; 
 
class proxy { 
  final int _fetchlimit = FETCHLIMIT; 
  final MUTEX unnamedportalmux; 
  final MUTEX unnamedstatement; 
  private Thread.MutexKey termlock; 
  final Thread.ResourceCount portalsinflight, statementsinflight; 
  final int(0..1) wasparallelisable; 
  final int(0..1) intransaction; 
 
  final conxion c; 
  private string cancelsecret; 
  private int backendpid; 
  final int(-128..127) backendstatus; 
  final mapping(string:mixed) options; 
  private array(string) lastmessage = ({}); 
  final int(0..1) clearmessage; 
  final int(0..1) untolderror; 
  final mixed delayederror; 
  private mapping(string:array(mixed)) notifylist = ([]); 
  final mapping(string:string) runtimeparameter; 
  final mapping(string:mapping(string:mixed)) prepareds = ([]); 
  final int pportalcount; 
  final int totalhits; 
  final int msgsreceived;   // Number of protocol messages received 
  final int bytesreceived;  // Number of bytes received 
  final int warningsdropcount;      // Number of uncollected warnings 
  private int warningscollected; 
  final int(0..1) invalidatecache; 
  private Thread.Queue qportals; 
  final function (:void) readyforquery_cb; 
 
  final string host; 
  final int(0..65535) port; 
  final string database, user, pass; 
  private Crypto.Hash.SCRAM SASLcontext; 
  final Thread.Condition waitforauthready; 
  final MUTEX shortmux; 
  final int readyforquerycount; 
 
  protected string _sprintf(int type) { 
    string res; 
    switch (type) { 
      case 'O': 
        res = sprintf(DRIVERNAME".proxy(%s@%s:%d/%s,%d,%d)", 
          user, host, port, database, c && c->socket && c->socket->query_fd(), 
          backendpid); 
        break; 
    } 
    return res; 
  } 
 
  protected void create(void|string host, void|string database, 
                        void|string user, void|string pass, 
                        void|mapping(string:mixed) options) { 
    if (this::pass = pass) { 
      String.secure(pass); 
      pass = "CENSORED"; 
    } 
    this::user = user; 
    this::database = database; 
    this::options = options; 
 
    if (!host) host = PGSQL_DEFAULT_HOST; 
    if (has_value(host,":") && sscanf(host,"%s:%d", host, port) != 2) 
      error("Error in parsing the hostname argument\n"); 
    this::host = host; 
 
    if (!port) 
      port = PGSQL_DEFAULT_PORT; 
    register_backend(this); 
    shortmux = MUTEX(); 
    PD("Connect\n"); 
    waitforauthready = Thread.Condition(); 
    qportals = Thread.Queue(); 
    readyforquerycount = 1; 
    qportals->write(1); 
    if (!(c = conxion(this, qportals, 0))) 
      error("Couldn't connect to database on %s:%d\n", host, port); 
    runtimeparameter = ([]); 
    unnamedportalmux = MUTEX(); 
    unnamedstatement = MUTEX(); 
    readyforquery_cb = connect_cb; 
    portalsinflight = Thread.ResourceCount(); 
    statementsinflight = Thread.ResourceCount(); 
    wasparallelisable = 0; 
  } 
 
  final int is_open() { 
    return c && c->socket && c->socket->is_open(); 
  } 
 
  final string geterror(void|int clear) { 
    untolderror = 0; 
    string s = lastmessage * "\n"; 
    if (clear) 
      lastmessage = ({}); 
    warningscollected = 0; 
    return sizeof(s) && s; 
  } 
 
  final string host_info() { 
    return sprintf("fd:%d TCP/IP %s:%d PID %d", 
                   c ? c->socket->query_fd() : -1, host, port, backendpid); 
  } 
 
  final void cancelquery() { 
    if (cancelsecret > "") { 
      PD("CancelRequest\n"); 
      conxion lcon = conxion(this, 0, 2); 
#ifdef PG_DEBUG 
      mixed err = 
#endif 
      catch(lcon->add_int32(16)->add_int32(PG_PROTOCOL(1234, 5678)) 
        ->add_int32(backendpid)->add(cancelsecret)->sendcmd(FLUSHSEND)); 
#ifdef PG_DEBUG 
      if (err) 
        PD("CancelRequest failed to connect %s\n", describe_backtrace(err)); 
#endif 
      destruct(lcon);         // Destruct explicitly to avoid delayed close 
#ifdef PG_DEBUGMORE 
      PD("Closetrace %O\n", backtrace()); 
#endif 
    } else 
      error("Connection not established, cannot cancel any query\n"); 
  } 
 
  private string a2nls(array(string) msg) { 
    return msg * "\n" + "\n"; 
  } 
 
  private string pinpointerror(void|string query, void|string offset) { 
    if (!query) 
      return ""; 
    int k = (int)offset; 
    if (k <= 0) 
      return MARKSTART + query + MARKEND; 
    return MARKSTART + (k > 1 ? query[..k-2] : "") 
         + MARKERROR + query[k - 1..] + MARKEND; 
  } 
 
  private void connect_cb() { 
    PD("%O\n", runtimeparameter); 
  } 
 
  private array(string) showbindings(Result portal) { 
    return portal ? portal._showbindings() : ({}); 
  } 
 
  private void preplastmessage(mapping(string:string) msgresponse) { 
    lastmessage = ({ 
      sprintf("%s %s:%s %s\n (%s:%s:%s)", 
              msgresponse.S, msgresponse.C, msgresponse.P || "", 
              msgresponse.M, msgresponse.F || "", msgresponse.R || "", 
              msgresponse.L||"")}); 
  } 
 
  private int|Result portal;  // state information procmessage 
#ifdef PG_DEBUG 
  private string datarowdebug; 
  private int datarowdebugcount; 
#endif 
 
  final void processloop(conxion ci) { 
    (c = ci)->socket->set_id(procmessage); 
    cancelsecret = 0; 
    portal = 0; 
    { 
      Stdio.Buffer plugbuffer = Stdio.Buffer()->add_int32(PG_PROTOCOL(3, 0)); 
      if (user) 
        plugbuffer->add("user\0", user, 0); 
      if (database) 
        plugbuffer->add("database\0", database, 0); 
      foreach (options - censoroptions; string name; mixed value) 
        plugbuffer->add(name, 0, (string)value, 0); 
      plugbuffer->add_int8(0); 
      PD("%O\n", (string)plugbuffer); 
      void|bufcon|conxsess cs; 
      if (catch(cs = ci->start())) { 
        destruct(waitforauthready); 
        unnamedstatement = 0; 
        termlock = 0; 
        return; 
      } else { 
        CHAIN(cs)->add_hstring(plugbuffer, 4, 4); 
        cs->sendcmd(SENDOUT); 
      } 
    }                     // Do not flush at this point, PostgreSQL 9.4 disapproves 
    procmessage(); 
  } 
 
  private void procmessage() { 
    mixed err; 
    int terminating = 0; 
    err = catch { 
    conxion ci = c;             // cache value 
    conxiin cr = ci->i;         // cache value 
#ifdef PG_DEBUG 
    PD("Processloop\n"); 
 
#ifdef PG_DEBUGMORE 
    void showportalstack(string label) { 
      PD(sprintf(">>>>>>>>>>> Portalstack %s: %O\n", label, portal)); 
      foreach (qportals->peek_array(); ; int|Result qp) 
        PD(" =========== Portal: %O\n", qp); 
      PD("<<<<<<<<<<<<<< Portalstack end\n"); 
    }; 
#endif 
    void showportal(int msgtype) { 
      if (objectp(portal)) 
        PD("%d<%O %d %c switch portal\n", 
         ci->socket->query_fd(), portal._portalname, ++ci->queueinidx, msgtype); 
      else if (portal > 0) 
        PD("%d<Sync %d %d %c portal\n", 
         ci->socket->query_fd(), ++ci->queueinidx, portal, msgtype); 
    }; 
#endif 
    int msgisfatal(mapping(string:string) msgresponse) { 
      int isfatal = (has_prefix(msgresponse.C, "53") 
                  || has_prefix(msgresponse.C, "3D") 
                  || has_prefix(msgresponse.C, "57P")) && MAGICTERMINATE; 
      if (isfatal && !terminating) // Run the callback once per lost connection 
        runcallback(backendpid, "_lost", ""); 
      return isfatal; 
    }; 
    for (;;) { 
      err = catch { 
#ifdef PG_DEBUG 
        if (!portal && datarowdebug) { 
          PD("%s rows %d\n", datarowdebug, datarowdebugcount); 
          datarowdebug = 0; datarowdebugcount = 0; 
        } 
#endif 
#ifdef PG_DEBUGMORE 
        showportalstack("LOOPTOP"); 
#endif 
        if (!sizeof(cr)) {                    // Preliminary check, fast path 
          Thread.MutexKey lock = cr->fillreadmux->lock(); 
          if (!sizeof(cr)) {                    // Check for real 
            if (!cr->fillread) { 
              lock = 0; 
              throw(MAGICTERMINATE);    // Force proper termination 
            } 
            cr->procmsg = 1; 
            return;                 // Terminate thread, wait for callback 
          } 
        } 
        int msgtype = cr->read_int8(); 
        if (!portal) { 
          portal = qportals->try_read(); 
#ifdef PG_DEBUG 
          showportal(msgtype); 
#endif 
        } 
        int msglen = cr->read_int32(); 
        msgsreceived++; 
        bytesreceived += 1 + msglen; 
        int errtype = NOERROR; 
        PD("%d<", ci->socket->query_fd()); 
        switch (msgtype) { 
          array getcols() { 
            int bintext = cr->read_int8(); 
            int cols = cr->read_int16(); 
#ifdef PG_DEBUG 
            array a; 
            msglen -= 4 + 1 + 2 + 2 * cols; 
            foreach (a = allocate(cols, ([])); ; mapping m) 
              m.type = cr->read_int16(); 
#else 
            cr->consume(cols << 1); 
#endif                      // Discard column info, and make it line oriented 
            return ({ ({(["name":"line"])}), ({bintext?BYTEAOID:TEXTOID}) }); 
          }; 
          array(string) reads() { 
#ifdef PG_DEBUG 
            if (msglen < 1) 
              errtype = PROTOCOLERROR; 
#endif 
            array ret = ({}), aw = ({0}); 
            do { 
              string w = cr->read_cstring(); 
              msglen -= sizeof(w) + 1; aw[0] = w; ret += aw; 
            } while (msglen); 
            return ret; 
          }; 
          mapping(string:string) getresponse() { 
            mapping(string:string) msgresponse = ([]); 
            msglen -= 4; 
            foreach (reads(); ; string f) 
              if (sizeof(f)) 
                msgresponse[f[..0]] = f[1..]; 
            PD("%O\n", msgresponse); 
            return msgresponse; 
          }; 
          case 'R': { 
            void authresponse(string|array msg) { 
              void|bufcon|conxsess cs = ci->start(); 
              CHAIN(cs)->add_int8('p')->add_hstring(msg, 4, 4); 
              cs->sendcmd(SENDOUT); // No flushing, PostgreSQL 9.4 disapproves 
            }; 
            PD("Authentication "); 
            msglen -= 4 + 4; 
            int authtype, k; 
            switch (authtype = cr->read_int32()) { 
              case 0: 
                PD("Ok\n"); 
                if (SASLcontext) { 
                  PD("Authentication validation still in progress\n"); 
                  errtype = PROTOCOLUNSUPPORTED; 
                } else 
                  cancelsecret = ""; 
                break; 
              case 2: 
                PD("KerberosV5\n"); 
                errtype = PROTOCOLUNSUPPORTED; 
                break; 
              case 3: 
                PD("ClearTextPassword\n"); 
                authresponse(({pass, 0})); 
                break; 
              case 4: 
                PD("CryptPassword\n"); 
                errtype = PROTOCOLUNSUPPORTED; 
                break; 
              case 5: 
                PD("MD5Password\n"); 
#ifdef PG_DEBUG 
                if (msglen < 4) 
                  errtype = PROTOCOLERROR; 
#endif 
#define md5hex(x) String.string2hex(Crypto.MD5.hash(x)) 
                authresponse(({"md5", 
                 md5hex(md5hex(pass + user) + cr->read(msglen)), 0})); 
#ifdef PG_DEBUG 
                msglen = 0; 
#endif 
                break; 
              case 6: 
                PD("SCMCredential\n"); 
                errtype = PROTOCOLUNSUPPORTED; 
                break; 
              case 7: 
                PD("GSS\n"); 
                errtype = PROTOCOLUNSUPPORTED; 
                break; 
              case 9: 
                PD("SSPI\n"); 
                errtype = PROTOCOLUNSUPPORTED; 
                break; 
              case 8: 
                PD("GSSContinue\n"); 
                errtype = PROTOCOLUNSUPPORTED; 
                cr->read(msglen);                               // SSauthdata 
#ifdef PG_DEBUG 
                if (msglen<1) 
                  errtype = PROTOCOLERROR; 
                msglen = 0; 
#endif 
                break; 
              case 10: { 
                string word; 
                PD("AuthenticationSASL\n"); 
                k = 0; 
                while (sizeof(word = cr->read_cstring())) { 
                  switch (word) { 
                    case "SCRAM-SHA-256": 
                      k = 1; 
                  } 
#ifdef PG_DEBUG 
                  msglen -= sizeof(word) + 1; 
                  if (msglen < 1) 
                    break; 
#endif 
                } 
                if (k) { 
                  SASLcontext = Crypto.SHA256.SCRAM(); 
                  word = SASLcontext.client_1(); 
                  authresponse(({ 
                    "SCRAM-SHA-256", 0, sprintf("%4c", sizeof(word)), word 
                   })); 
                } else 
                  errtype = PROTOCOLUNSUPPORTED; 
#ifdef PG_DEBUG 
                if (msglen != 1) 
                  errtype = PROTOCOLERROR; 
                msglen = 0; 
#endif 
                break; 
              } 
              case 11: { 
                PD("AuthenticationSASLContinue\n"); 
                string response; 
                if (response 
                 = SASLcontext.client_2(cr->read(msglen), pass)) 
                  authresponse(response); 
                else 
                  errtype = PROTOCOLERROR; 
#ifdef PG_DEBUG 
                msglen = 0; 
#endif 
                break; 
              } 
              case 12: 
                PD("AuthenticationSASLFinal\n"); 
                if (SASLcontext.client_3(cr->read(msglen))) 
                  SASLcontext = 0;      // Clears context and approves server 
                else 
                  errtype = PROTOCOLERROR; 
#ifdef PG_DEBUG 
                msglen = 0; 
#endif 
                break; 
              default: 
                PD("Unknown Authentication Method %c\n", authtype); 
                errtype = PROTOCOLUNSUPPORTED; 
                break; 
            } 
            switch (errtype) { 
              default: 
              case PROTOCOLUNSUPPORTED: 
                error("Unsupported authenticationmethod %c\n", authtype); 
              case NOERROR: 
                break; 
            } 
            break; 
          } 
          case 'K': 
            msglen -= 4 + 4; backendpid = cr->read_int32(); 
            cancelsecret = cr->read(msglen); 
#ifdef PG_DEBUG 
            PD("BackendKeyData %O\n", cancelsecret); 
            msglen = 0; 
#endif 
            break; 
          case 'S': { 
            PD("ParameterStatus "); 
            msglen -= 4; 
            array(string) ts = reads(); 
#ifdef PG_DEBUG 
            if (sizeof(ts) == 2) { 
#endif 
              runtimeparameter[ts[0]] = ts[1]; 
#ifdef PG_DEBUG 
              PD("%O=%O\n", ts[0], ts[1]); 
            } else 
              errtype = PROTOCOLERROR; 
#endif 
            break; 
          } 
          case '3': 
#ifdef PG_DEBUG 
            PD("CloseComplete\n"); 
            msglen -= 4; 
#endif 
            break; 
          case 'Z': { 
            backendstatus = cr->read_int8(); 
#ifdef PG_DEBUG 
            msglen -= 4 + 1; 
            PD("ReadyForQuery %c\n", backendstatus); 
#endif 
#ifdef PG_DEBUGMORE 
            showportalstack("READYFORQUERY"); 
#endif 
            int keeplooking; 
            do 
              for (keeplooking = 0; 
                   objectp(portal); 
                   portal = qportals->read()) { 
#ifdef PG_DEBUG 
                showportal(msgtype); 
#endif 
                if (backendstatus == 'I' && intransaction 
                 && portal->transtype != TRANSEND) 
                  keeplooking = 1; 
                portal->_purgeportal(); 
              } 
            while (keeplooking && (portal = qportals->read())); 
            if (backendstatus == 'I') 
              intransaction = 0; 
            foreach (qportals->peek_array(); ; Result qp) { 
              if (objectp(qp) && qp._synctransact 
               && qp._synctransact <= portal) { 
                PD("Checking portal %O %d<=%d\n", 
                 qp._portalname, qp._synctransact, portal); 
                qp->_purgeportal(); 
              } 
            } 
            portal = 0; 
#ifdef PG_DEBUGMORE 
            showportalstack("AFTER READYFORQUERY"); 
#endif 
            readyforquerycount--; 
            function (:void) cb; 
            destruct(waitforauthready); 
            if (cb = readyforquery_cb) 
              readyforquery_cb = 0, cb(); 
            break; 
          } 
          case '1': 
#ifdef PG_DEBUG 
            PD("ParseComplete portal %O\n", portal); 
            msglen -= 4; 
#endif 
            break; 
          case 't': { 
            array a; 
#ifdef PG_DEBUG 
            int cols = cr->read_int16(); 
            PD("%O ParameterDescription %d values\n", portal._query, cols); 
            msglen -= 4 + 2 + 4 * cols; 
            a = cr->read_ints(cols, 4); 
#else 
            a = cr->read_ints(cr->read_int16(), 4); 
#endif 
#ifdef PG_DEBUGMORE 
            PD("%O\n", a); 
#endif 
            if (portal._tprepared) 
              portal._tprepared.datatypeoid = a; 
            Thread.Thread(portal->_preparebind, a); 
            break; 
          } 
          case 'T': { 
            array a, at; 
            int cols = cr->read_int16(); 
#ifdef PG_DEBUG 
            PD("RowDescription %d columns %O\n", cols, portal._query); 
            msglen -= 4 + 2; 
#endif 
            at = allocate(cols); 
            foreach (a = allocate(cols); int i; ) { 
              string s = cr->read_cstring(); 
              mapping(string:mixed) res = (["name":s]); 
#ifdef PG_DEBUG 
              msglen -= sizeof(s) + 1 + 4 + 2 + 4 + 2 + 4 + 2; 
              res.tableoid = cr->read_int32() || UNDEFINED; 
              res.tablecolattr = cr->read_int16() || UNDEFINED; 
#else 
              cr->consume(6); 
#endif 
              at[i] = cr->read_int32(); 
#ifdef PG_DEBUG 
              res.type = at[i]; 
              { 
                int len = cr->read_sint(2); 
                res.length = len >= 0 ? len : "variable"; 
              } 
              res.atttypmod = cr->read_int32(); 
              /* formatcode contains just a zero when Bind has not been issued 
               * yet, but the content is irrelevant because it's determined 
               * at query time 
               */ 
              res.formatcode = cr->read_int16(); 
#else 
              cr->consume(8); 
#endif 
              a[i] = res; 
            } 
#ifdef PG_DEBUGMORE 
            PD("%O\n", a); 
#endif 
            if (portal._forcetext) 
              portal->_setrowdesc(a, at);       // Do not consume queued portal 
            else { 
              portal->_processrowdesc(a, at); 
              portal = 0; 
            } 
            break; 
          } 
          case 'n': { 
#ifdef PG_DEBUG 
            msglen -= 4; 
            PD("NoData %O\n", portal._query); 
#endif 
            if (!portal._forcetext) { 
              portal._fetchlimit = 0;           // disables subsequent Executes 
              portal->_processrowdesc(({}), ({})); 
              portal = 0; 
            } 
            break; 
          } 
          case 'H': 
            portal->_processrowdesc(@getcols()); 
            PD("CopyOutResponse %O\n", portal. _query); 
            break; 
          case '2': { 
            mapping tp; 
#ifdef PG_DEBUG 
            msglen -= 4; 
            PD("%O BindComplete\n", portal._portalname); 
#endif 
            if (tp = portal._tprepared) { 
              int tend = gethrtime(); 
              int tstart = tp.trun; 
              if (tend == tstart) 
                m_delete(prepareds, portal._query); 
              else { 
                tp.hits++; 
                totalhits++; 
                if (!tp.preparedname) { 
                  if (sizeof(portal._preparedname)) { 
                    PD("Finalising stored statement %s\n", 
                     portal._preparedname); 
                    tp.preparedname = portal._preparedname; 
                  } 
                  tstart = tend - tstart; 
                  if (!tp.tparse || tp.tparse>tstart) 
                    tp.tparse = tstart; 
                } 
                tp.trunstart = tend; 
              } 
            } 
            break; 
          } 
          case 'D': 
            msglen -= 4; 
#ifdef PG_DEBUG 
#ifdef PG_DEBUGMORE 
            PD("%O DataRow %d bytes\n", portal._portalname, msglen); 
#endif 
            datarowdebugcount++; 
            if (!datarowdebug) 
              datarowdebug = sprintf( 
               "%O DataRow %d bytes", portal._portalname, msglen); 
#endif 
#ifdef PG_DEBUG 
            msglen= 
#endif 
            portal->_decodedata(msglen, runtimeparameter[CLIENT_ENCODING]); 
            break; 
          case 's': 
#ifdef PG_DEBUG 
            PD("%O PortalSuspended\n", portal._portalname); 
            msglen -= 4; 
#endif 
            portal = 0; 
            break; 
          case 'C': { 
            msglen -= 4; 
#ifdef PG_DEBUG 
            if (msglen < 1) 
              errtype = PROTOCOLERROR; 
#endif 
            string s = cr->read(msglen - 1); 
            PD("%O CommandComplete %O\n", 
             objectp(portal) && portal._portalname, s); 
#ifdef PG_DEBUG 
            if (cr->read_int8()) 
              errtype = PROTOCOLERROR; 
            msglen = 0; 
#else 
            cr->consume(1); 
#endif 
#ifdef PG_DEBUGMORE 
            showportalstack("COMMANDCOMPLETE"); 
#endif 
            if (!portal._forcetext) { 
              portal->_storetiming(); 
              portal->_releasesession(s); 
              portal = 0; 
            } 
            break; 
          } 
          case 'I': 
#ifdef PG_DEBUG 
            PD("EmptyQueryResponse %O\n", portal._portalname); 
            msglen -= 4; 
#endif 
#ifdef PG_DEBUGMORE 
            showportalstack("EMPTYQUERYRESPONSE"); 
#endif 
            if (!portal._forcetext) { 
              portal->_releasesession(); 
              portal = 0; 
            } 
            break; 
          case 'd': 
            PD("%O CopyData\n", portal._portalname); 
            portal->_storetiming(); 
            msglen -= 4; 
#ifdef PG_DEBUG 
            if (msglen < 0) 
              errtype = PROTOCOLERROR; 
#endif 
            portal->_processdataready(({cr->read(msglen)}), msglen); 
#ifdef PG_DEBUG 
            msglen = 0; 
#endif 
            break; 
          case 'G': 
            portal->_releasestatement(); 
            portal->_setrowdesc(@getcols()); 
            PD("%O CopyInResponse\n", portal._portalname); 
            portal._state = COPYINPROGRESS; 
            break; 
          case 'c': 
#ifdef PG_DEBUG 
            PD("%O CopyDone\n", portal._portalname); 
            msglen -= 4; 
#endif 
            if (!portal._forcetext) 
              portal = 0; 
            break; 
          case 'E': { 
#ifdef PG_DEBUGMORE 
            showportalstack("ERRORRESPONSE"); 
#endif 
            if (portalsinflight->drained() && !readyforquerycount) 
              sendsync(); 
            PD("%O ErrorResponse %O\n", 
             objectp(portal) && (portal._portalname || portal._preparedname), 
             objectp(portal) && portal._query); 
            mapping(string:string) msgresponse; 
            msgresponse = getresponse(); 
            warningsdropcount += warningscollected; 
            warningscollected = 0; 
            untolderror = 1; 
            switch (msgresponse.C) { 
              case "P0001": 
                lastmessage 
                 = ({sprintf("%s: %s", msgresponse.S, msgresponse.M)}); 
                USERERROR(a2nls(lastmessage 
                               +({pinpointerror(portal._query, msgresponse.P)}) 
                               +showbindings(portal))); 
              case "53000":case "53100":case "53200":case "53300":case "53400": 
              case "57P01":case "57P02":case "57P03":case "57P04":case "3D000": 
              case "34000":case "08P01": 
                preplastmessage(msgresponse); 
                PD(a2nls(lastmessage)); throw(msgisfatal(msgresponse)); 
              case "42P05": 
                errtype = PROTOCOLERROR; 
              case "XX000":case "42883":case "42P01": 
                invalidatecache = 1; 
              default: 
                preplastmessage(msgresponse); 
                if (msgresponse.D) 
                  lastmessage += ({msgresponse.D}); 
                if (msgresponse.H) 
                  lastmessage += ({msgresponse.H}); 
                lastmessage += ({ 
                  pinpointerror(objectp(portal) && portal._query, msgresponse.P) 
                  + pinpointerror(msgresponse.q, msgresponse.p)}); 
                if (msgresponse.W) 
                  lastmessage += ({msgresponse.W}); 
                if (objectp(portal)) 
                  lastmessage += showbindings(portal); 
                switch (msgresponse.S) { 
                  case "PANIC":werror(a2nls(lastmessage)); 
                } 
              case "25P02":                      // Preserve last error message 
                USERERROR(a2nls(lastmessage));  // Implicitly closed portal 
            } 
            break; 
          } 
          case 'N': { 
            PD("NoticeResponse\n"); 
            mapping(string:string) msgresponse = getresponse(); 
            switch (msgresponse.C) { 
              default: 
                if (clearmessage) { 
                  warningsdropcount += warningscollected; 
                  clearmessage = warningscollected = 0; 
                  lastmessage = ({}); 
                } 
                warningscollected++; 
                lastmessage = ({sprintf("%s %s: %s", 
                                 msgresponse.S, msgresponse.C, msgresponse.M)}); 
                int val; 
                if (val = msgisfatal(msgresponse)) {  // Some warnings are fatal 
                  preplastmessage(msgresponse); 
                  PD(a2nls(lastmessage)); throw(val); 
                } 
              case "25P01":                 // Suppress some warnings 
                break; 
            } 
            break; 
          } 
          case 'A': { 
            PD("NotificationResponse\n"); 
            msglen -= 4 + 4; 
            int pid = cr->read_int32(); 
            string condition, extrainfo; 
            { 
              array(string) ts = reads(); 
              switch (sizeof(ts)) { 
#if PG_DEBUG 
                case 0: 
                  errtype = PROTOCOLERROR; 
                  break; 
                default: 
                  errtype = PROTOCOLERROR; 
#endif 
                case 2: 
                  extrainfo = ts[1]; 
                case 1: 
                  condition = ts[0]; 
              } 
            } 
            PD("%d %s\n%s\n", pid, condition, extrainfo); 
            runcallback(pid, condition, extrainfo); 
            break; 
          } 
          default: 
            if (msgtype != -1) { 
              string s; 
              PD("Unknown message received %c\n", msgtype); 
              s = cr->read(msglen -= 4); PD("%O\n", s); 
#ifdef PG_DEBUG 
              msglen = 0; 
#endif 
              errtype = PROTOCOLUNSUPPORTED; 
            } else { 
              lastmessage += ({ 
               sprintf("Connection lost to database %s@%s:%d/%s %d\n", 
                    user, host, port, database, backendpid)}); 
              runcallback(backendpid, "_lost", ""); 
              if (!waitforauthready) 
                throw(0); 
              USERERROR(a2nls(lastmessage)); 
            } 
            break; 
        } 
#ifdef PG_DEBUG 
        if (msglen) 
          errtype = PROTOCOLERROR; 
#endif 
        { 
          string msg; 
          switch (errtype) { 
            case PROTOCOLUNSUPPORTED: 
              msg 
               = sprintf("Unsupported servermessage received %c\n", msgtype); 
              break; 
            case PROTOCOLERROR: 
              msg = sprintf("Protocol error with database %s", host_info()); 
              break; 
            case NOERROR: 
              continue;                             // Normal production loop 
          } 
          error(a2nls(lastmessage += ({msg}))); 
        } 
      };                    // We only get here if there is an error 
      if (err == MAGICTERMINATE) { // Announce connection termination to server 
        catch { 
          void|bufcon|conxsess cs = ci->start(); 
          CHAIN(cs)->add(PGSYNC)->add("X\0\0\0\4"); 
          cs->sendcmd(SENDOUT); 
        }; 
        terminating = 1; 
        err = 0; 
      } else if (stringp(err)) { 
        Result or; 
        if (!objectp(or = portal)) 
          or = this; 
        if (!or.delayederror) 
          or.delayederror = err; 
#ifdef PG_DEBUGMORE 
        showportalstack("THROWN"); 
#endif 
        if (objectp(portal)) 
          portal->_releasesession("ERROR"); 
        portal = 0; 
        if (!waitforauthready) 
          continue;         // Only continue if authentication did not fail 
      } 
      break; 
    } 
    PD("Closing database processloop %s\n", err ? describe_backtrace(err) : ""); 
    delayederror = err; 
    if (objectp(portal)) { 
#ifdef PG_DEBUG 
      showportal(0); 
#endif 
      portal->_purgeportal(); 
    } 
    destruct(waitforauthready); 
    termlock = 0; 
    if (err && !stringp(err)) 
      throw(err); 
    }; 
    catch { 
     unnamedstatement = 0; 
     termlock = 0; 
      if (err) { 
        PD("Terminating processloop due to %s\n", describe_backtrace(err)); 
        delayederror = err; 
      } 
      destruct(waitforauthready); 
      c->purge(); 
    }; 
  } 
 
  final void close() { 
    throwdelayederror(this); 
    { 
      Thread.MutexKey lock; 
      if (unnamedstatement) 
        termlock = unnamedstatement->lock(1); 
      foreach (c->runningportals; Result result; ) 
        catch(result->status_command_complete()); 
      if (c)                                // Prevent trivial backtraces 
        c->close(); 
      if (unnamedstatement) 
        lock = unnamedstatement->lock(1); 
      if (c) 
        c->purge(); 
    } 
    destruct(waitforauthready); 
  } 
 
  protected void _destruct() { 
    string errstring; 
    mixed err = catch(close()); 
    clients[this] = 0; 
    if (untolderror) { 
      /* 
       * Flush out any asynchronously reported errors to stderr; because we are 
       * inside a destructor, throwing an error will not work anymore. 
       * Warnings will be silently discarded at this point. 
       */ 
      lastmessage = filter(lastmessage, lambda(string val) { 
        return has_prefix(val, "ERROR ") || has_prefix(val, "FATAL "); }); 
      if (err || (err = catch(errstring = geterror(1)))) 
        werror(describe_backtrace(err)); 
      else if (errstring && sizeof(errstring)) 
        werror("%s\n", errstring);  // Add missing terminating newline 
    } 
  } 
 
  final void sendsync() { 
    readyforquerycount++; 
    c->start()->sendcmd(SYNCSEND); 
  } 
 
  private void runcallback(int pid, string condition, string extrainfo) { 
    array cb; 
    if (condition == "_lost") 
      destruct(c); 
    if ((cb = notifylist[condition] || notifylist[""]) 
       && (pid != backendpid || sizeof(cb) > 1 && cb[1])) 
      callout(cb[0], 0, pid, condition, extrainfo, @cb[2..]); 
  } 
 
  private inline void closestatement( 
   bufcon|conxsess plugbuffer, string oldprep) { 
    closestatement(plugbuffer, oldprep); 
  } 
}; 
 
#pragma deprecation_warnings 
 
//! @class sql_result 
//! @deprecated Result 
 
//! @endclass 
 
__deprecated__(program(Result)) sql_result = 
  (__deprecated__(program(Result)))Result;