ruby-pg / ext / pg_connection.c

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
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
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
/*
 * pg_connection.c - PG::Connection class extension
 * $Id$
 *
 */

#include "pg.h"


VALUE rb_cPGconn;

static PQnoticeReceiver default_notice_receiver = NULL;
static PQnoticeProcessor default_notice_processor = NULL;

static PGconn *pgconn_check( VALUE );
static VALUE pgconn_finish( VALUE );
#ifdef M17N_SUPPORTED
static VALUE pgconn_set_default_encoding( VALUE self );
#endif

#ifndef HAVE_RB_THREAD_FD_SELECT
#define rb_fdset_t fd_set
#define rb_fd_init(f)
#define rb_fd_zero(f)  FD_ZERO(f)
#define rb_fd_set(n, f)  FD_SET(n, f)
#define rb_fd_term(f)
#define rb_thread_fd_select rb_thread_select
#endif

/*
 * Global functions
 */

/*
 * Fetch the data pointer and check it for sanity.
 */
PGconn *
pg_get_pgconn( VALUE self )
{
	PGconn *conn = pgconn_check( self );

	if ( !conn )
		rb_raise( rb_eConnectionBad, "connection is closed" );

	return conn;
}


/*
 * Close the associated socket IO object if there is one.
 */
void
pgconn_close_socket_io( VALUE self )
{
	VALUE socket_io = rb_iv_get( self, "@socket_io" );

	if ( RTEST(socket_io) ) {
#if defined(_WIN32) && defined(HAVE_RB_W32_WRAP_IO_HANDLE)
		int ruby_sd = NUM2INT(rb_funcall( socket_io, rb_intern("fileno"), 0 ));
		if( rb_w32_unwrap_io_handle(ruby_sd) ){
			rb_raise(rb_eConnectionBad, "Could not unwrap win32 socket handle");
		}
#endif
		rb_funcall( socket_io, rb_intern("close"), 0 );
	}

	rb_iv_set( self, "@socket_io", Qnil );
}


/*
 * Allocation/
 */

/*
 * Object validity checker. Returns the data pointer.
 */
static PGconn *
pgconn_check( VALUE self ) {

	Check_Type( self, T_DATA );

    if ( !rb_obj_is_kind_of(self, rb_cPGconn) ) {
		rb_raise( rb_eTypeError, "wrong argument type %s (expected PG::Connection)",
				  rb_obj_classname( self ) );
    }

	return DATA_PTR( self );
}


/*
 * GC Free function
 */
static void
pgconn_gc_free( PGconn *conn )
{
	if (conn != NULL)
		PQfinish( conn );
}


/**************************************************************************
 * Class Methods
 **************************************************************************/

/*
 * Document-method: allocate
 *
 * call-seq:
 *   PG::Connection.allocate -> conn
 */
static VALUE
pgconn_s_allocate( VALUE klass )
{
	VALUE self = Data_Wrap_Struct( klass, NULL, pgconn_gc_free, NULL );
	rb_iv_set( self, "@socket_io", Qnil );
	rb_iv_set( self, "@notice_receiver", Qnil);
	rb_iv_set( self, "@notice_processor", Qnil);
	return self;
}


/*
 * Document-method: new
 *
 * call-seq:
 *    PG::Connection.new -> conn
 *    PG::Connection.new(connection_hash) -> conn
 *    PG::Connection.new(connection_string) -> conn
 *    PG::Connection.new(host, port, options, tty, dbname, user, password) ->  conn
 *
 * Create a connection to the specified server.
 *
 * [+host+]
 *   server hostname
 * [+hostaddr+]
 *   server address (avoids hostname lookup, overrides +host+)
 * [+port+]
 *   server port number
 * [+dbname+]
 *   connecting database name
 * [+user+]
 *   login user name
 * [+password+]
 *   login password
 * [+connect_timeout+]
 *   maximum time to wait for connection to succeed
 * [+options+]
 *   backend options
 * [+tty+]
 *   (ignored in newer versions of PostgreSQL)
 * [+sslmode+]
 *   (disable|allow|prefer|require)
 * [+krbsrvname+]
 *   kerberos service name
 * [+gsslib+]
 *   GSS library to use for GSSAPI authentication
 * [+service+]
 *   service name to use for additional parameters
 *
 * Examples:
 *
 *   # Connect using all defaults
 *   PG::Connection.new
 *
 *   # As a Hash
 *   PG::Connection.new( :dbname => 'test', :port => 5432 )
 *
 *   # As a String
 *   PG::Connection.new( "dbname=test port=5432" )
 *
 *   # As an Array
 *   PG::Connection.new( nil, 5432, nil, nil, 'test', nil, nil )
 *
 * If the Ruby default internal encoding is set (i.e., Encoding.default_internal != nil), the
 * connection will have its +client_encoding+ set accordingly.
 *
 * Raises a PG::Error if the connection fails.
 */
static VALUE
pgconn_init(int argc, VALUE *argv, VALUE self)
{
	PGconn *conn = NULL;
	VALUE conninfo;
	VALUE error;

	conninfo = rb_funcall2( rb_cPGconn, rb_intern("parse_connect_args"), argc, argv );
	conn = gvl_PQconnectdb(StringValuePtr(conninfo));

	if(conn == NULL)
		rb_raise(rb_ePGerror, "PQconnectdb() unable to allocate structure");

	Check_Type(self, T_DATA);
	DATA_PTR(self) = conn;

	if (PQstatus(conn) == CONNECTION_BAD) {
		error = rb_exc_new2(rb_eConnectionBad, PQerrorMessage(conn));
		rb_iv_set(error, "@connection", self);
		rb_exc_raise(error);
	}

#ifdef M17N_SUPPORTED
	pgconn_set_default_encoding( self );
#endif

	if (rb_block_given_p()) {
		return rb_ensure(rb_yield, self, pgconn_finish, self);
	}
	return self;
}

/*
 * call-seq:
 *    PG::Connection.connect_start(connection_hash)       -> conn
 *    PG::Connection.connect_start(connection_string)     -> conn
 *    PG::Connection.connect_start(host, port, options, tty, dbname, login, password) ->  conn
 *
 * This is an asynchronous version of PG::Connection.connect().
 *
 * Use #connect_poll to poll the status of the connection.
 *
 * NOTE: this does *not* set the connection's +client_encoding+ for you if
 * Encoding.default_internal is set. To set it after the connection is established,
 * call #internal_encoding=. You can also set it automatically by setting
 * ENV['PGCLIENTENCODING'], or include the 'options' connection parameter.
 *
 */
static VALUE
pgconn_s_connect_start( int argc, VALUE *argv, VALUE klass )
{
	PGconn *conn = NULL;
	VALUE rb_conn;
	VALUE conninfo;
	VALUE error;

	/*
	 * PG::Connection.connect_start must act as both alloc() and initialize()
	 * because it is not invoked by calling new().
	 */
	rb_conn  = pgconn_s_allocate( klass );
	conninfo = rb_funcall2( klass, rb_intern("parse_connect_args"), argc, argv );
	conn     = gvl_PQconnectStart( StringValuePtr(conninfo) );

	if( conn == NULL )
		rb_raise(rb_ePGerror, "PQconnectStart() unable to allocate structure");

	Check_Type(rb_conn, T_DATA);
	DATA_PTR(rb_conn) = conn;

	if ( PQstatus(conn) == CONNECTION_BAD ) {
		error = rb_exc_new2(rb_eConnectionBad, PQerrorMessage(conn));
		rb_iv_set(error, "@connection", rb_conn);
		rb_exc_raise(error);
	}

	if ( rb_block_given_p() ) {
		return rb_ensure( rb_yield, rb_conn, pgconn_finish, rb_conn );
	}
	return rb_conn;
}

#ifdef HAVE_PQPING
/*
 * call-seq:
 *    PG::Connection.ping(connection_hash)       -> Fixnum
 *    PG::Connection.ping(connection_string)     -> Fixnum
 *    PG::Connection.ping(host, port, options, tty, dbname, login, password) ->  Fixnum
 *
 * Check server status.
 *
 * Returns one of:
 * [+PQPING_OK+]
 *   server is accepting connections
 * [+PQPING_REJECT+]
 *   server is alive but rejecting connections
 * [+PQPING_NO_RESPONSE+]
 *   could not establish connection
 * [+PQPING_NO_ATTEMPT+]
 *   connection not attempted (bad params)
 */
static VALUE
pgconn_s_ping( int argc, VALUE *argv, VALUE klass )
{
	PGPing ping;
	VALUE conninfo;

	conninfo = rb_funcall2( klass, rb_intern("parse_connect_args"), argc, argv );
	ping     = PQping( StringValuePtr(conninfo) );

	return INT2FIX((int)ping);
}
#endif

/*
 * call-seq:
 *    PG::Connection.conndefaults() -> Array
 *
 * Returns an array of hashes. Each hash has the keys:
 * [+:keyword+]
 *   the name of the option
 * [+:envvar+]
 *   the environment variable to fall back to
 * [+:compiled+]
 *   the compiled in option as a secondary fallback
 * [+:val+]
 *   the option's current value, or +nil+ if not known
 * [+:label+]
 *   the label for the field
 * [+:dispchar+]
 *   "" for normal, "D" for debug, and "*" for password
 * [+:dispsize+]
 *   field size
 */
static VALUE
pgconn_s_conndefaults(VALUE self)
{
	PQconninfoOption *options = PQconndefaults();
	VALUE ary = rb_ary_new();
	VALUE hash;
	int i = 0;

	UNUSED( self );

	for(i = 0; options[i].keyword != NULL; i++) {
		hash = rb_hash_new();
		if(options[i].keyword)
			rb_hash_aset(hash, ID2SYM(rb_intern("keyword")), rb_str_new2(options[i].keyword));
		if(options[i].envvar)
			rb_hash_aset(hash, ID2SYM(rb_intern("envvar")), rb_str_new2(options[i].envvar));
		if(options[i].compiled)
			rb_hash_aset(hash, ID2SYM(rb_intern("compiled")), rb_str_new2(options[i].compiled));
		if(options[i].val)
			rb_hash_aset(hash, ID2SYM(rb_intern("val")), rb_str_new2(options[i].val));
		if(options[i].label)
			rb_hash_aset(hash, ID2SYM(rb_intern("label")), rb_str_new2(options[i].label));
		if(options[i].dispchar)
			rb_hash_aset(hash, ID2SYM(rb_intern("dispchar")), rb_str_new2(options[i].dispchar));
		rb_hash_aset(hash, ID2SYM(rb_intern("dispsize")), INT2NUM(options[i].dispsize));
		rb_ary_push(ary, hash);
	}
	PQconninfoFree(options);
	return ary;
}


/*
 * call-seq:
 *    PG::Connection.encrypt_password( password, username ) -> String
 *
 * This function is intended to be used by client applications that
 * send commands like: +ALTER USER joe PASSWORD 'pwd'+.
 * The arguments are the cleartext password, and the SQL name
 * of the user it is for.
 *
 * Return value is the encrypted password.
 */
static VALUE
pgconn_s_encrypt_password(VALUE self, VALUE password, VALUE username)
{
	char *encrypted = NULL;
	VALUE rval = Qnil;

	UNUSED( self );

	Check_Type(password, T_STRING);
	Check_Type(username, T_STRING);

	encrypted = PQencryptPassword(StringValuePtr(password), StringValuePtr(username));
	rval = rb_str_new2( encrypted );
	PQfreemem( encrypted );

	OBJ_INFECT( rval, password );
	OBJ_INFECT( rval, username );

	return rval;
}


/**************************************************************************
 * PG::Connection INSTANCE METHODS
 **************************************************************************/

/*
 * call-seq:
 *    conn.connect_poll() -> Fixnum
 *
 * Returns one of:
 * [+PGRES_POLLING_READING+]
 *   wait until the socket is ready to read
 * [+PGRES_POLLING_WRITING+]
 *   wait until the socket is ready to write
 * [+PGRES_POLLING_FAILED+]
 *   the asynchronous connection has failed
 * [+PGRES_POLLING_OK+]
 *   the asynchronous connection is ready
 *
 * Example:
 *   conn = PG::Connection.connect_start("dbname=mydatabase")
 *   socket = conn.socket_io
 *   status = conn.connect_poll
 *   while(status != PG::PGRES_POLLING_OK) do
 *     # do some work while waiting for the connection to complete
 *     if(status == PG::PGRES_POLLING_READING)
 *       if(not select([socket], [], [], 10.0))
 *         raise "Asynchronous connection timed out!"
 *       end
 *     elsif(status == PG::PGRES_POLLING_WRITING)
 *       if(not select([], [socket], [], 10.0))
 *         raise "Asynchronous connection timed out!"
 *       end
 *     end
 *     status = conn.connect_poll
 *   end
 *   # now conn.status == CONNECTION_OK, and connection
 *   # is ready.
 */
static VALUE
pgconn_connect_poll(VALUE self)
{
	PostgresPollingStatusType status;
	status = gvl_PQconnectPoll(pg_get_pgconn(self));
	return INT2FIX((int)status);
}

/*
 * call-seq:
 *    conn.finish
 *
 * Closes the backend connection.
 */
static VALUE
pgconn_finish( VALUE self )
{
	pgconn_close_socket_io( self );
	PQfinish( pg_get_pgconn(self) );
	DATA_PTR( self ) = NULL;
	return Qnil;
}


/*
 * call-seq:
 *    conn.finished?      -> boolean
 *
 * Returns +true+ if the backend connection has been closed.
 */
static VALUE
pgconn_finished_p( VALUE self )
{
	if ( DATA_PTR(self) ) return Qfalse;
	return Qtrue;
}


/*
 * call-seq:
 *    conn.reset()
 *
 * Resets the backend connection. This method closes the
 * backend connection and tries to re-connect.
 */
static VALUE
pgconn_reset( VALUE self )
{
	pgconn_close_socket_io( self );
	gvl_PQreset( pg_get_pgconn(self) );
	return self;
}

/*
 * call-seq:
 *    conn.reset_start() -> nil
 *
 * Initiate a connection reset in a nonblocking manner.
 * This will close the current connection and attempt to
 * reconnect using the same connection parameters.
 * Use #reset_poll to check the status of the
 * connection reset.
 */
static VALUE
pgconn_reset_start(VALUE self)
{
	pgconn_close_socket_io( self );
	if(gvl_PQresetStart(pg_get_pgconn(self)) == 0)
		rb_raise(rb_eUnableToSend, "reset has failed");
	return Qnil;
}

/*
 * call-seq:
 *    conn.reset_poll -> Fixnum
 *
 * Checks the status of a connection reset operation.
 * See #connect_start and #connect_poll for
 * usage information and return values.
 */
static VALUE
pgconn_reset_poll(VALUE self)
{
	PostgresPollingStatusType status;
	status = gvl_PQresetPoll(pg_get_pgconn(self));
	return INT2FIX((int)status);
}

/*
 * call-seq:
 *    conn.db()
 *
 * Returns the connected database name.
 */
static VALUE
pgconn_db(VALUE self)
{
	char *db = PQdb(pg_get_pgconn(self));
	if (!db) return Qnil;
	return rb_tainted_str_new2(db);
}

/*
 * call-seq:
 *    conn.user()
 *
 * Returns the authenticated user name.
 */
static VALUE
pgconn_user(VALUE self)
{
	char *user = PQuser(pg_get_pgconn(self));
	if (!user) return Qnil;
	return rb_tainted_str_new2(user);
}

/*
 * call-seq:
 *    conn.pass()
 *
 * Returns the authenticated user name.
 */
static VALUE
pgconn_pass(VALUE self)
{
	char *user = PQpass(pg_get_pgconn(self));
	if (!user) return Qnil;
	return rb_tainted_str_new2(user);
}

/*
 * call-seq:
 *    conn.host()
 *
 * Returns the connected server name.
 */
static VALUE
pgconn_host(VALUE self)
{
	char *host = PQhost(pg_get_pgconn(self));
	if (!host) return Qnil;
	return rb_tainted_str_new2(host);
}

/*
 * call-seq:
 *    conn.port()
 *
 * Returns the connected server port number.
 */
static VALUE
pgconn_port(VALUE self)
{
	char* port = PQport(pg_get_pgconn(self));
	return INT2NUM(atol(port));
}

/*
 * call-seq:
 *    conn.tty()
 *
 * Returns the connected pgtty. (Obsolete)
 */
static VALUE
pgconn_tty(VALUE self)
{
	char *tty = PQtty(pg_get_pgconn(self));
	if (!tty) return Qnil;
	return rb_tainted_str_new2(tty);
}

/*
 * call-seq:
 *    conn.options()
 *
 * Returns backend option string.
 */
static VALUE
pgconn_options(VALUE self)
{
	char *options = PQoptions(pg_get_pgconn(self));
	if (!options) return Qnil;
	return rb_tainted_str_new2(options);
}

/*
 * call-seq:
 *    conn.status()
 *
 * Returns status of connection : CONNECTION_OK or CONNECTION_BAD
 */
static VALUE
pgconn_status(VALUE self)
{
	return INT2NUM(PQstatus(pg_get_pgconn(self)));
}

/*
 * call-seq:
 *    conn.transaction_status()
 *
 * returns one of the following statuses:
 *   PQTRANS_IDLE    = 0 (connection idle)
 *   PQTRANS_ACTIVE  = 1 (command in progress)
 *   PQTRANS_INTRANS = 2 (idle, within transaction block)
 *   PQTRANS_INERROR = 3 (idle, within failed transaction)
 *   PQTRANS_UNKNOWN = 4 (cannot determine status)
 */
static VALUE
pgconn_transaction_status(VALUE self)
{
	return INT2NUM(PQtransactionStatus(pg_get_pgconn(self)));
}

/*
 * call-seq:
 *    conn.parameter_status( param_name ) -> String
 *
 * Returns the setting of parameter _param_name_, where
 * _param_name_ is one of
 * * +server_version+
 * * +server_encoding+
 * * +client_encoding+
 * * +is_superuser+
 * * +session_authorization+
 * * +DateStyle+
 * * +TimeZone+
 * * +integer_datetimes+
 * * +standard_conforming_strings+
 *
 * Returns nil if the value of the parameter is not known.
 */
static VALUE
pgconn_parameter_status(VALUE self, VALUE param_name)
{
	const char *ret = PQparameterStatus(pg_get_pgconn(self), StringValuePtr(param_name));
	if(ret == NULL)
		return Qnil;
	else
		return rb_tainted_str_new2(ret);
}

/*
 * call-seq:
 *   conn.protocol_version -> Integer
 *
 * The 3.0 protocol will normally be used when communicating with PostgreSQL 7.4
 * or later servers; pre-7.4 servers support only protocol 2.0. (Protocol 1.0 is
 * obsolete and not supported by libpq.)
 */
static VALUE
pgconn_protocol_version(VALUE self)
{
	return INT2NUM(PQprotocolVersion(pg_get_pgconn(self)));
}

/*
 * call-seq:
 *   conn.server_version -> Integer
 *
 * The number is formed by converting the major, minor, and revision
 * numbers into two-decimal-digit numbers and appending them together.
 * For example, version 7.4.2 will be returned as 70402, and version
 * 8.1 will be returned as 80100 (leading zeroes are not shown). Zero
 * is returned if the connection is bad.
 *
 */
static VALUE
pgconn_server_version(VALUE self)
{
	return INT2NUM(PQserverVersion(pg_get_pgconn(self)));
}

/*
 * call-seq:
 *    conn.error_message -> String
 *
 * Returns the error message about connection.
 */
static VALUE
pgconn_error_message(VALUE self)
{
	char *error = PQerrorMessage(pg_get_pgconn(self));
	if (!error) return Qnil;
	return rb_tainted_str_new2(error);
}

/*
 * call-seq:
 *    conn.socket() -> Fixnum
 *
 * Returns the socket's file descriptor for this connection.
 * <tt>IO.for_fd()</tt> can be used to build a proper IO object to the socket.
 * If you do so, you will likely also want to set <tt>autoclose=false</tt>
 * on it to prevent Ruby from closing the socket to PostgreSQL if it
 * goes out of scope. Alternatively, you can use #socket_io, which
 * creates an IO that's associated with the connection object itself,
 * and so won't go out of scope until the connection does.
 *
 * *Note:* On Windows the file descriptor is not really usable,
 * since it can not be used to build a Ruby IO object.
 */
static VALUE
pgconn_socket(VALUE self)
{
	int sd;
	if( (sd = PQsocket(pg_get_pgconn(self))) < 0)
		rb_raise(rb_eConnectionBad, "PQsocket() can't get socket descriptor");
	return INT2NUM(sd);
}


#if !defined(_WIN32) || defined(HAVE_RB_W32_WRAP_IO_HANDLE)

/*
 * call-seq:
 *    conn.socket_io() -> IO
 *
 * Fetch a memoized IO object created from the Connection's underlying socket.
 * This object can be used for IO.select to wait for events while running
 * asynchronous API calls.
 *
 * Using this instead of #socket avoids the problem of the underlying connection
 * being closed by Ruby when an IO created using <tt>IO.for_fd(conn.socket)</tt>
 * goes out of scope.
 *
 * This method can also be used on Windows but requires Ruby-2.0+.
 */
static VALUE
pgconn_socket_io(VALUE self)
{
	int sd;
	int ruby_sd;
	ID id_autoclose = rb_intern("autoclose=");
	VALUE socket_io = rb_iv_get( self, "@socket_io" );

	if ( !RTEST(socket_io) ) {
		if( (sd = PQsocket(pg_get_pgconn(self))) < 0)
			rb_raise(rb_eConnectionBad, "PQsocket() can't get socket descriptor");

		#ifdef _WIN32
			ruby_sd = rb_w32_wrap_io_handle((HANDLE)(intptr_t)sd, O_RDWR|O_BINARY|O_NOINHERIT);
		#else
			ruby_sd = sd;
		#endif

		socket_io = rb_funcall( rb_cIO, rb_intern("for_fd"), 1, INT2NUM(ruby_sd) );

		/* Disable autoclose feature, when supported */
		if( rb_respond_to(socket_io, id_autoclose) ){
			rb_funcall( socket_io, id_autoclose, 1, Qfalse );
		}

		rb_iv_set( self, "@socket_io", socket_io );
	}

	return socket_io;
}

#endif

/*
 * call-seq:
 *    conn.backend_pid() -> Fixnum
 *
 * Returns the process ID of the backend server
 * process for this connection.
 * Note that this is a PID on database server host.
 */
static VALUE
pgconn_backend_pid(VALUE self)
{
	return INT2NUM(PQbackendPID(pg_get_pgconn(self)));
}

/*
 * call-seq:
 *    conn.connection_needs_password() -> Boolean
 *
 * Returns +true+ if the authentication method required a
 * password, but none was available. +false+ otherwise.
 */
static VALUE
pgconn_connection_needs_password(VALUE self)
{
	return PQconnectionNeedsPassword(pg_get_pgconn(self)) ? Qtrue : Qfalse;
}

/*
 * call-seq:
 *    conn.connection_used_password() -> Boolean
 *
 * Returns +true+ if the authentication method used
 * a caller-supplied password, +false+ otherwise.
 */
static VALUE
pgconn_connection_used_password(VALUE self)
{
	return PQconnectionUsedPassword(pg_get_pgconn(self)) ? Qtrue : Qfalse;
}


/* :TODO: get_ssl */


static VALUE pgconn_exec_params( int, VALUE *, VALUE );

/*
 * call-seq:
 *    conn.exec(sql) -> PG::Result
 *    conn.exec(sql) {|pg_result| block }
 *
 * Sends SQL query request specified by _sql_ to PostgreSQL.
 * Returns a PG::Result instance on success.
 * On failure, it raises a PG::Error.
 *
 * For backward compatibility, if you pass more than one parameter to this method,
 * it will call #exec_params for you. New code should explicitly use #exec_params if
 * argument placeholders are used.
 *
 * If the optional code block is given, it will be passed <i>result</i> as an argument,
 * and the PG::Result object will  automatically be cleared when the block terminates.
 * In this instance, <code>conn.exec</code> returns the value of the block.
 */
static VALUE
pgconn_exec(int argc, VALUE *argv, VALUE self)
{
	PGconn *conn = pg_get_pgconn(self);
	PGresult *result = NULL;
	VALUE rb_pgresult;

	/* If called with no parameters, use PQexec */
	if ( argc == 1 ) {
		Check_Type(argv[0], T_STRING);

		result = gvl_PQexec(conn, StringValuePtr(argv[0]));
		rb_pgresult = pg_new_result(result, self);
		pg_result_check(rb_pgresult);
		if (rb_block_given_p()) {
			return rb_ensure(rb_yield, rb_pgresult, pg_result_clear, rb_pgresult);
		}
		return rb_pgresult;
	}

	/* Otherwise, just call #exec_params instead for backward-compatibility */
	else {
		return pgconn_exec_params( argc, argv, self );
	}

}


/*
 * call-seq:
 *    conn.exec_params(sql, params[, result_format ] ) -> PG::Result
 *    conn.exec_params(sql, params[, result_format ] ) {|pg_result| block }
 *
 * Sends SQL query request specified by +sql+ to PostgreSQL using placeholders
 * for parameters.
 *
 * Returns a PG::Result instance on success. On failure, it raises a PG::Error.
 *
 * +params+ is an array of the bind parameters for the SQL query.
 * Each element of the +params+ array may be either:
 *   a hash of the form:
 *     {:value  => String (value of bind parameter)
 *      :type   => Fixnum (oid of type of bind parameter)
 *      :format => Fixnum (0 for text, 1 for binary)
 *     }
 *   or, it may be a String. If it is a string, that is equivalent to the hash:
 *     { :value => <string value>, :type => 0, :format => 0 }
 *
 * PostgreSQL bind parameters are represented as $1, $1, $2, etc.,
 * inside the SQL query. The 0th element of the +params+ array is bound
 * to $1, the 1st element is bound to $2, etc. +nil+ is treated as +NULL+.
 *
 * If the types are not specified, they will be inferred by PostgreSQL.
 * Instead of specifying type oids, it's recommended to simply add
 * explicit casts in the query to ensure that the right type is used.
 *
 * For example: "SELECT $1::int"
 *
 * The optional +result_format+ should be 0 for text results, 1
 * for binary.
 *
 * If the optional code block is given, it will be passed <i>result</i> as an argument,
 * and the PG::Result object will  automatically be cleared when the block terminates.
 * In this instance, <code>conn.exec</code> returns the value of the block.
 */
static VALUE
pgconn_exec_params( int argc, VALUE *argv, VALUE self )
{
	PGconn *conn = pg_get_pgconn(self);
	PGresult *result = NULL;
	VALUE rb_pgresult;
	VALUE command, params, in_res_fmt;
	VALUE param, param_type, param_value, param_format;
	VALUE param_value_tmp;
	VALUE sym_type, sym_value, sym_format;
	VALUE gc_array;
	int i=0;
	int nParams;
	Oid *paramTypes;
	char ** paramValues;
	int *paramLengths;
	int *paramFormats;
	int resultFormat;

	rb_scan_args(argc, argv, "12", &command, &params, &in_res_fmt);

	/*
	 * Handle the edge-case where the caller is coming from #exec, but passed an explict +nil+
	 * for the second parameter.
	 */
	if ( NIL_P(params) ) {
		return pgconn_exec( 1, argv, self );
		}

	Check_Type(params, T_ARRAY);

	if ( NIL_P(in_res_fmt) ) {
		resultFormat = 0;
	}
	else {
		resultFormat = NUM2INT(in_res_fmt);
	}

	gc_array = rb_ary_new();
	rb_gc_register_address(&gc_array);

	sym_type = ID2SYM(rb_intern("type"));
	sym_value = ID2SYM(rb_intern("value"));
	sym_format = ID2SYM(rb_intern("format"));
	nParams = (int)RARRAY_LEN(params);
	paramTypes = ALLOC_N(Oid, nParams);
	paramValues = ALLOC_N(char *, nParams);
	paramLengths = ALLOC_N(int, nParams);
	paramFormats = ALLOC_N(int, nParams);

	for ( i = 0; i < nParams; i++ ) {
		param = rb_ary_entry(params, i);
		if (TYPE(param) == T_HASH) {
			param_type = rb_hash_aref(param, sym_type);
			param_value_tmp = rb_hash_aref(param, sym_value);
			if(param_value_tmp == Qnil)
				param_value = param_value_tmp;
			else
				param_value = rb_obj_as_string(param_value_tmp);
			param_format = rb_hash_aref(param, sym_format);
		}
		else {
			param_type = Qnil;
			if(param == Qnil)
				param_value = param;
			else
				param_value = rb_obj_as_string(param);
			param_format = Qnil;
		}

		if(param_type == Qnil)
			paramTypes[i] = 0;
		else
			paramTypes[i] = NUM2INT(param_type);

		if(param_value == Qnil) {
			paramValues[i] = NULL;
			paramLengths[i] = 0;
		}
		else {
			Check_Type(param_value, T_STRING);
			/* make sure param_value doesn't get freed by the GC */
			rb_ary_push(gc_array, param_value);
			paramValues[i] = StringValuePtr(param_value);
			paramLengths[i] = (int)RSTRING_LEN(param_value);
		}

		if(param_format == Qnil)
			paramFormats[i] = 0;
		else
			paramFormats[i] = NUM2INT(param_format);
	}

	result = gvl_PQexecParams(conn, StringValuePtr(command), nParams, paramTypes,
		(const char * const *)paramValues, paramLengths, paramFormats, resultFormat);

	rb_gc_unregister_address(&gc_array);

	xfree(paramTypes);
	xfree(paramValues);
	xfree(paramLengths);
	xfree(paramFormats);

	rb_pgresult = pg_new_result(result, self);
	pg_result_check(rb_pgresult);

	if (rb_block_given_p()) {
		return rb_ensure(rb_yield, rb_pgresult, pg_result_clear, rb_pgresult);
	}

	return rb_pgresult;
}

/*
 * call-seq:
 *    conn.prepare(stmt_name, sql [, param_types ] ) -> PG::Result
 *
 * Prepares statement _sql_ with name _name_ to be executed later.
 * Returns a PG::Result instance on success.
 * On failure, it raises a PG::Error.
 *
 * +param_types+ is an optional parameter to specify the Oids of the
 * types of the parameters.
 *
 * If the types are not specified, they will be inferred by PostgreSQL.
 * Instead of specifying type oids, it's recommended to simply add
 * explicit casts in the query to ensure that the right type is used.
 *
 * For example: "SELECT $1::int"
 *
 * PostgreSQL bind parameters are represented as $1, $1, $2, etc.,
 * inside the SQL query.
 */
static VALUE
pgconn_prepare(int argc, VALUE *argv, VALUE self)
{
	PGconn *conn = pg_get_pgconn(self);
	PGresult *result = NULL;
	VALUE rb_pgresult;
	VALUE name, command, in_paramtypes;
	VALUE param;
	int i = 0;
	int nParams = 0;
	Oid *paramTypes = NULL;

	rb_scan_args(argc, argv, "21", &name, &command, &in_paramtypes);
	Check_Type(name, T_STRING);
	Check_Type(command, T_STRING);

	if(! NIL_P(in_paramtypes)) {
		Check_Type(in_paramtypes, T_ARRAY);
		nParams = (int)RARRAY_LEN(in_paramtypes);
		paramTypes = ALLOC_N(Oid, nParams);
		for(i = 0; i < nParams; i++) {
			param = rb_ary_entry(in_paramtypes, i);
			Check_Type(param, T_FIXNUM);
			if(param == Qnil)
				paramTypes[i] = 0;
			else
				paramTypes[i] = NUM2INT(param);
		}
	}
	result = gvl_PQprepare(conn, StringValuePtr(name), StringValuePtr(command),
			nParams, paramTypes);

	xfree(paramTypes);

	rb_pgresult = pg_new_result(result, self);
	pg_result_check(rb_pgresult);
	return rb_pgresult;
}

/*
 * call-seq:
 *    conn.exec_prepared(statement_name [, params, result_format ] ) -> PG::Result
 *    conn.exec_prepared(statement_name [, params, result_format ] ) {|pg_result| block }
 *
 * Execute prepared named statement specified by _statement_name_.
 * Returns a PG::Result instance on success.
 * On failure, it raises a PG::Error.
 *
 * +params+ is an array of the optional bind parameters for the
 * SQL query. Each element of the +params+ array may be either:
 *   a hash of the form:
 *     {:value  => String (value of bind parameter)
 *      :format => Fixnum (0 for text, 1 for binary)
 *     }
 *   or, it may be a String. If it is a string, that is equivalent to the hash:
 *     { :value => <string value>, :format => 0 }
 *
 * PostgreSQL bind parameters are represented as $1, $1, $2, etc.,
 * inside the SQL query. The 0th element of the +params+ array is bound
 * to $1, the 1st element is bound to $2, etc. +nil+ is treated as +NULL+.
 *
 * The optional +result_format+ should be 0 for text results, 1
 * for binary.
 *
 * If the optional code block is given, it will be passed <i>result</i> as an argument,
 * and the PG::Result object will  automatically be cleared when the block terminates.
 * In this instance, <code>conn.exec_prepared</code> returns the value of the block.
 */
static VALUE
pgconn_exec_prepared(int argc, VALUE *argv, VALUE self)
{
	PGconn *conn = pg_get_pgconn(self);
	PGresult *result = NULL;
	VALUE rb_pgresult;
	VALUE name, params, in_res_fmt;
	VALUE param, param_value, param_format;
	VALUE param_value_tmp;
	VALUE sym_value, sym_format;
	VALUE gc_array;
	int i = 0;
	int nParams;
	char ** paramValues;
	int *paramLengths;
	int *paramFormats;
	int resultFormat;


	rb_scan_args(argc, argv, "12", &name, &params, &in_res_fmt);
	Check_Type(name, T_STRING);

	if(NIL_P(params)) {
		params = rb_ary_new2(0);
		resultFormat = 0;
	}
	else {
		Check_Type(params, T_ARRAY);
	}

	if(NIL_P(in_res_fmt)) {
		resultFormat = 0;
	}
	else {
		resultFormat = NUM2INT(in_res_fmt);
	}

	gc_array = rb_ary_new();
	rb_gc_register_address(&gc_array);
	sym_value = ID2SYM(rb_intern("value"));
	sym_format = ID2SYM(rb_intern("format"));
	nParams = (int)RARRAY_LEN(params);
	paramValues = ALLOC_N(char *, nParams);
	paramLengths = ALLOC_N(int, nParams);
	paramFormats = ALLOC_N(int, nParams);
	for(i = 0; i < nParams; i++) {
		param = rb_ary_entry(params, i);
		if (TYPE(param) == T_HASH) {
			param_value_tmp = rb_hash_aref(param, sym_value);
			if(param_value_tmp == Qnil)
				param_value = param_value_tmp;
			else
				param_value = rb_obj_as_string(param_value_tmp);
			param_format = rb_hash_aref(param, sym_format);
		}
		else {
			if(param == Qnil)
				param_value = param;
			else
				param_value = rb_obj_as_string(param);
			param_format = INT2NUM(0);
		}
		if(param_value == Qnil) {
			paramValues[i] = NULL;
			paramLengths[i] = 0;
		}
		else {
			Check_Type(param_value, T_STRING);
			/* make sure param_value doesn't get freed by the GC */
			rb_ary_push(gc_array, param_value);
			paramValues[i] = StringValuePtr(param_value);
			paramLengths[i] = (int)RSTRING_LEN(param_value);
		}

		if(param_format == Qnil)
			paramFormats[i] = 0;
		else
			paramFormats[i] = NUM2INT(param_format);
	}

	result = gvl_PQexecPrepared(conn, StringValuePtr(name), nParams,
		(const char * const *)paramValues, paramLengths, paramFormats,
		resultFormat);

	rb_gc_unregister_address(&gc_array);

	xfree(paramValues);
	xfree(paramLengths);
	xfree(paramFormats);

	rb_pgresult = pg_new_result(result, self);
	pg_result_check(rb_pgresult);
	if (rb_block_given_p()) {
		return rb_ensure(rb_yield, rb_pgresult,
			pg_result_clear, rb_pgresult);
	}
	return rb_pgresult;
}

/*
 * call-seq:
 *    conn.describe_prepared( statement_name ) -> PG::Result
 *
 * Retrieve information about the prepared statement
 * _statement_name_.
 */
static VALUE
pgconn_describe_prepared(VALUE self, VALUE stmt_name)
{
	PGresult *result;
	VALUE rb_pgresult;
	PGconn *conn = pg_get_pgconn(self);
	char *stmt;
	if(stmt_name == Qnil) {
		stmt = NULL;
	}
	else {
		Check_Type(stmt_name, T_STRING);
		stmt = StringValuePtr(stmt_name);
	}
	result = gvl_PQdescribePrepared(conn, stmt);
	rb_pgresult = pg_new_result(result, self);
	pg_result_check(rb_pgresult);
	return rb_pgresult;
}


/*
 * call-seq:
 *    conn.describe_portal( portal_name ) -> PG::Result
 *
 * Retrieve information about the portal _portal_name_.
 */
static VALUE
pgconn_describe_portal(self, stmt_name)
	VALUE self, stmt_name;
{
	PGresult *result;
	VALUE rb_pgresult;
	PGconn *conn = pg_get_pgconn(self);
	char *stmt;
	if(stmt_name == Qnil) {
		stmt = NULL;
	}
	else {
		Check_Type(stmt_name, T_STRING);
		stmt = StringValuePtr(stmt_name);
	}
	result = gvl_PQdescribePortal(conn, stmt);
	rb_pgresult = pg_new_result(result, self);
	pg_result_check(rb_pgresult);
	return rb_pgresult;
}


/*
 * call-seq:
 *    conn.make_empty_pgresult( status ) -> PG::Result
 *
 * Constructs and empty PG::Result with status _status_.
 * _status_ may be one of:
 * * +PGRES_EMPTY_QUERY+
 * * +PGRES_COMMAND_OK+
 * * +PGRES_TUPLES_OK+
 * * +PGRES_COPY_OUT+
 * * +PGRES_COPY_IN+
 * * +PGRES_BAD_RESPONSE+
 * * +PGRES_NONFATAL_ERROR+
 * * +PGRES_FATAL_ERROR+
 * * +PGRES_COPY_BOTH+
 */
static VALUE
pgconn_make_empty_pgresult(VALUE self, VALUE status)
{
	PGresult *result;
	VALUE rb_pgresult;
	PGconn *conn = pg_get_pgconn(self);
	result = PQmakeEmptyPGresult(conn, NUM2INT(status));
	rb_pgresult = pg_new_result(result, self);
	pg_result_check(rb_pgresult);
	return rb_pgresult;
}


/*
 * call-seq:
 *    conn.escape_string( str ) -> String
 *
 * Connection instance method for versions of 8.1 and higher of libpq
 * uses PQescapeStringConn, which is safer. Avoid calling as a class method,
 * the class method uses the deprecated PQescapeString() API function.
 *
 * Returns a SQL-safe version of the String _str_.
 * This is the preferred way to make strings safe for inclusion in
 * SQL queries.
 *
 * Consider using exec_params, which avoids the need for passing values
 * inside of SQL commands.
 *
 * Encoding of escaped string will be equal to client encoding of connection.
 */
static VALUE
pgconn_s_escape(VALUE self, VALUE string)
{
	char *escaped;
	size_t size;
	int error;
	VALUE result;
#ifdef M17N_SUPPORTED
	rb_encoding* enc;
#endif

	Check_Type(string, T_STRING);

	escaped = ALLOC_N(char, RSTRING_LEN(string) * 2 + 1);
	if(rb_obj_class(self) == rb_cPGconn) {
		size = PQescapeStringConn(pg_get_pgconn(self), escaped,
			RSTRING_PTR(string), RSTRING_LEN(string), &error);
		if(error) {
			xfree(escaped);
			rb_raise(rb_ePGerror, "%s", PQerrorMessage(pg_get_pgconn(self)));
		}
	} else {
		size = PQescapeString(escaped, RSTRING_PTR(string), (int)RSTRING_LEN(string));
	}
	result = rb_str_new(escaped, size);
	xfree(escaped);
	OBJ_INFECT(result, string);

#ifdef M17N_SUPPORTED
	if ( rb_obj_class(self) == rb_cPGconn ) {
		enc = pg_conn_enc_get( pg_get_pgconn(self) );
	} else {
		enc = rb_enc_get(string);
	}
	rb_enc_associate(result, enc);
#endif

	return result;
}

/*
 * call-seq:
 *   conn.escape_bytea( string ) -> String
 *
 * Connection instance method for versions of 8.1 and higher of libpq
 * uses PQescapeByteaConn, which is safer. Avoid calling as a class method,
 * the class method uses the deprecated PQescapeBytea() API function.
 *
 * Use the instance method version of this function, it is safer than the
 * class method.
 *
 * Escapes binary data for use within an SQL command with the type +bytea+.
 *
 * Certain byte values must be escaped (but all byte values may be escaped)
 * when used as part of a +bytea+ literal in an SQL statement. In general, to
 * escape a byte, it is converted into the three digit octal number equal to
 * the octet value, and preceded by two backslashes. The single quote (') and
 * backslash (\) characters have special alternative escape sequences.
 * #escape_bytea performs this operation, escaping only the minimally required
 * bytes.
 *
 * Consider using exec_params, which avoids the need for passing values inside of
 * SQL commands.
 */
static VALUE
pgconn_s_escape_bytea(VALUE self, VALUE str)
{
	unsigned char *from, *to;
	size_t from_len, to_len;
	VALUE ret;

	Check_Type(str, T_STRING);
	from      = (unsigned char*)RSTRING_PTR(str);
	from_len  = RSTRING_LEN(str);

	if(rb_obj_class(self) == rb_cPGconn) {
		to = PQescapeByteaConn(pg_get_pgconn(self), from, from_len, &to_len);
	} else {
		to = PQescapeBytea( from, from_len, &to_len);
	}

	ret = rb_str_new((char*)to, to_len - 1);
	OBJ_INFECT(ret, str);
	PQfreemem(to);
	return ret;
}


/*
 * call-seq:
 *   PG::Connection.unescape_bytea( string )
 *
 * Converts an escaped string representation of binary data into binary data --- the
 * reverse of #escape_bytea. This is needed when retrieving +bytea+ data in text format,
 * but not when retrieving it in binary format.
 *
 */
static VALUE
pgconn_s_unescape_bytea(VALUE self, VALUE str)
{
	unsigned char *from, *to;
	size_t to_len;
	VALUE ret;

	UNUSED( self );

	Check_Type(str, T_STRING);
	from = (unsigned char*)StringValuePtr(str);

	to = PQunescapeBytea(from, &to_len);

	ret = rb_str_new((char*)to, to_len);
	OBJ_INFECT(ret, str);
	PQfreemem(to);
	return ret;
}

#ifdef HAVE_PQESCAPELITERAL
/*
 * call-seq:
 *    conn.escape_literal( str ) -> String
 *
 * Escape an arbitrary String +str+ as a literal.
 */
static VALUE
pgconn_escape_literal(VALUE self, VALUE string)
{
	PGconn *conn = pg_get_pgconn(self);
	char *escaped = NULL;
	VALUE error;
	VALUE result = Qnil;

	Check_Type(string, T_STRING);

	escaped = PQescapeLiteral(conn, RSTRING_PTR(string), RSTRING_LEN(string));
	if (escaped == NULL)
	{
		error = rb_exc_new2(rb_ePGerror, PQerrorMessage(conn));
		rb_iv_set(error, "@connection", self);
		rb_exc_raise(error);
		return Qnil;
	}
	result = rb_str_new2(escaped);
	PQfreemem(escaped);
	OBJ_INFECT(result, string);

#ifdef M17N_SUPPORTED
	rb_enc_associate(result, pg_conn_enc_get( pg_get_pgconn(self) ));
#endif

	return result;
}
#endif

#ifdef HAVE_PQESCAPEIDENTIFIER
/*
 * call-seq:
 *    conn.escape_identifier( str ) -> String
 *
 * Escape an arbitrary String +str+ as an identifier.
 *
 * This method does the same as #quote_ident, but uses libpq to
 * process the string.
 */
static VALUE
pgconn_escape_identifier(VALUE self, VALUE string)
{
	PGconn *conn = pg_get_pgconn(self);
	char *escaped = NULL;
	VALUE error;
	VALUE result = Qnil;

	Check_Type(string, T_STRING);

	escaped = PQescapeIdentifier(conn, RSTRING_PTR(string), RSTRING_LEN(string));
	if (escaped == NULL)
	{
		error = rb_exc_new2(rb_ePGerror, PQerrorMessage(conn));
		rb_iv_set(error, "@connection", self);
		rb_exc_raise(error);
		return Qnil;
	}
	result = rb_str_new2(escaped);
	PQfreemem(escaped);
	OBJ_INFECT(result, string);

#ifdef M17N_SUPPORTED
	rb_enc_associate(result, pg_conn_enc_get( pg_get_pgconn(self) ));
#endif

	return result;
}
#endif

#ifdef HAVE_PQSETSINGLEROWMODE
/*
 * call-seq:
 *    conn.set_single_row_mode -> self
 *
 * To enter single-row mode, call this method immediately after a successful
 * call of send_query (or a sibling function). This mode selection is effective
 * only for the currently executing query.
 * Then call Connection#get_result repeatedly, until it returns nil.
 *
 * Each (but the last) received Result has exactly one row and a
 * Result#result_status of PGRES_SINGLE_TUPLE. The last row has
 * zero rows and is used to indicate a successful execution of the query.
 * All of these Result objects will contain the same row description data
 * (column names, types, etc) that an ordinary Result object for the query
 * would have.
 *
 * *Caution:* While processing a query, the server may return some rows and
 * then encounter an error, causing the query to be aborted. Ordinarily, pg
 * discards any such rows and reports only the error. But in single-row mode,
 * those rows will have already been returned to the application. Hence, the
 * application will see some Result objects followed by an Error raised in get_result.
 * For proper transactional behavior, the application must be designed to discard
 * or undo whatever has been done with the previously-processed rows, if the query
 * ultimately fails.
 *
 * Example:
 *   conn.send_query( "your SQL command" )
 *   conn.set_single_row_mode
 *   loop do
 *     res = conn.get_result or break
 *     res.check
 *     res.each do |row|
 *       # do something with the received row
 *     end
 *   end
 *
 */
static VALUE
pgconn_set_single_row_mode(VALUE self)
{
	PGconn *conn = pg_get_pgconn(self);
	VALUE error;

	if( PQsetSingleRowMode(conn) == 0 )
	{
		error = rb_exc_new2(rb_ePGerror, PQerrorMessage(conn));
		rb_iv_set(error, "@connection", self);
		rb_exc_raise(error);
	}

	return self;
}
#endif

/*
 * call-seq:
 *    conn.send_query(sql [, params, result_format ] ) -> nil
 *
 * Sends SQL query request specified by _sql_ to PostgreSQL for
 * asynchronous processing, and immediately returns.
 * On failure, it raises a PG::Error.
 *
 * +params+ is an optional array of the bind parameters for the SQL query.
 * Each element of the +params+ array may be either:
 *   a hash of the form:
 *     {:value  => String (value of bind parameter)
 *      :type   => Fixnum (oid of type of bind parameter)
 *      :format => Fixnum (0 for text, 1 for binary)
 *     }
 *   or, it may be a String. If it is a string, that is equivalent to the hash:
 *     { :value => <string value>, :type => 0, :format => 0 }
 *
 * PostgreSQL bind parameters are represented as $1, $1, $2, etc.,
 * inside the SQL query. The 0th element of the +params+ array is bound
 * to $1, the 1st element is bound to $2, etc. +nil+ is treated as +NULL+.
 *
 * If the types are not specified, they will be inferred by PostgreSQL.
 * Instead of specifying type oids, it's recommended to simply add
 * explicit casts in the query to ensure that the right type is used.
 *
 * For example: "SELECT $1::int"
 *
 * The optional +result_format+ should be 0 for text results, 1
 * for binary.
 */
static VALUE
pgconn_send_query(int argc, VALUE *argv, VALUE self)
{
	PGconn *conn = pg_get_pgconn(self);
	int result;
	VALUE command, params, in_res_fmt;
	VALUE param, param_type, param_value, param_format;
	VALUE param_value_tmp;
	VALUE sym_type, sym_value, sym_format;
	VALUE gc_array;
	VALUE error;
	int i=0;
	int nParams;
	Oid *paramTypes;
	char ** paramValues;
	int *paramLengths;
	int *paramFormats;
	int resultFormat;

	rb_scan_args(argc, argv, "12", &command, &params, &in_res_fmt);
	Check_Type(command, T_STRING);

	/* If called with no parameters, use PQsendQuery */
	if(NIL_P(params)) {
		if(PQsendQuery(conn,StringValuePtr(command)) == 0) {
			error = rb_exc_new2(rb_eUnableToSend, PQerrorMessage(conn));
			rb_iv_set(error, "@connection", self);
			rb_exc_raise(error);
		}
		return Qnil;
	}

	/* If called with parameters, and optionally result_format,
	 * use PQsendQueryParams
	 */
	Check_Type(params, T_ARRAY);

	if(NIL_P(in_res_fmt)) {
		resultFormat = 0;
	}
	else {
		resultFormat = NUM2INT(in_res_fmt);
	}

	gc_array = rb_ary_new();
	rb_gc_register_address(&gc_array);
	sym_type = ID2SYM(rb_intern("type"));
	sym_value = ID2SYM(rb_intern("value"));
	sym_format = ID2SYM(rb_intern("format"));
	nParams = (int)RARRAY_LEN(params);
	paramTypes = ALLOC_N(Oid, nParams);
	paramValues = ALLOC_N(char *, nParams);
	paramLengths = ALLOC_N(int, nParams);
	paramFormats = ALLOC_N(int, nParams);
	for(i = 0; i < nParams; i++) {
		param = rb_ary_entry(params, i);
		if (TYPE(param) == T_HASH) {
			param_type = rb_hash_aref(param, sym_type);
			param_value_tmp = rb_hash_aref(param, sym_value);
			if(param_value_tmp == Qnil)
				param_value = param_value_tmp;
			else
				param_value = rb_obj_as_string(param_value_tmp);
			param_format = rb_hash_aref(param, sym_format);
		}
		else {
			param_type = INT2NUM(0);
			if(param == Qnil)
				param_value = param;
			else
				param_value = rb_obj_as_string(param);
			param_format = INT2NUM(0);
		}

		if(param_type == Qnil)
			paramTypes[i] = 0;
		else
			paramTypes[i] = NUM2INT(param_type);

		if(param_value == Qnil) {
			paramValues[i] = NULL;
			paramLengths[i] = 0;
		}
		else {
			Check_Type(param_value, T_STRING);
			/* make sure param_value doesn't get freed by the GC */
			rb_ary_push(gc_array, param_value);
			paramValues[i] = StringValuePtr(param_value);
			paramLengths[i] = (int)RSTRING_LEN(param_value);
		}

		if(param_format == Qnil)
			paramFormats[i] = 0;
		else
			paramFormats[i] = NUM2INT(param_format);
	}

	result = PQsendQueryParams(conn, StringValuePtr(command), nParams, paramTypes,
		(const char * const *)paramValues, paramLengths, paramFormats, resultFormat);

	rb_gc_unregister_address(&gc_array);

	xfree(paramTypes);
	xfree(paramValues);
	xfree(paramLengths);
	xfree(paramFormats);

	if(result == 0) {
		error = rb_exc_new2(rb_eUnableToSend, PQerrorMessage(conn));
		rb_iv_set(error, "@connection", self);
		rb_exc_raise(error);
	}
	return Qnil;
}

/*
 * call-seq:
 *    conn.send_prepare( stmt_name, sql [, param_types ] ) -> nil
 *
 * Prepares statement _sql_ with name _name_ to be executed later.
 * Sends prepare command asynchronously, and returns immediately.
 * On failure, it raises a PG::Error.
 *
 * +param_types+ is an optional parameter to specify the Oids of the
 * types of the parameters.
 *
 * If the types are not specified, they will be inferred by PostgreSQL.
 * Instead of specifying type oids, it's recommended to simply add
 * explicit casts in the query to ensure that the right type is used.
 *
 * For example: "SELECT $1::int"
 *
 * PostgreSQL bind parameters are represented as $1, $1, $2, etc.,
 * inside the SQL query.
 */
static VALUE
pgconn_send_prepare(int argc, VALUE *argv, VALUE self)
{
	PGconn *conn = pg_get_pgconn(self);
	int result;
	VALUE name, command, in_paramtypes;
	VALUE param;
	VALUE error;
	int i = 0;
	int nParams = 0;
	Oid *paramTypes = NULL;

	rb_scan_args(argc, argv, "21", &name, &command, &in_paramtypes);
	Check_Type(name, T_STRING);
	Check_Type(command, T_STRING);

	if(! NIL_P(in_paramtypes)) {
		Check_Type(in_paramtypes, T_ARRAY);
		nParams = (int)RARRAY_LEN(in_paramtypes);
		paramTypes = ALLOC_N(Oid, nParams);
		for(i = 0; i < nParams; i++) {
			param = rb_ary_entry(in_paramtypes, i);
			Check_Type(param, T_FIXNUM);
			if(param == Qnil)
				paramTypes[i] = 0;
			else
				paramTypes[i] = NUM2INT(param);
		}
	}
	result = PQsendPrepare(conn, StringValuePtr(name), StringValuePtr(command),
			nParams, paramTypes);

	xfree(paramTypes);

	if(result == 0) {
		error = rb_exc_new2(rb_eUnableToSend, PQerrorMessage(conn));
		rb_iv_set(error, "@connection", self);
		rb_exc_raise(error);
	}
	return Qnil;
}

/*
 * call-seq:
 *    conn.send_query_prepared( statement_name [, params, result_format ] )
 *      -> nil
 *
 * Execute prepared named statement specified by _statement_name_
 * asynchronously, and returns immediately.
 * On failure, it raises a PG::Error.
 *
 * +params+ is an array of the optional bind parameters for the
 * SQL query. Each element of the +params+ array may be either:
 *   a hash of the form:
 *     {:value  => String (value of bind parameter)
 *      :format => Fixnum (0 for text, 1 for binary)
 *     }
 *   or, it may be a String. If it is a string, that is equivalent to the hash:
 *     { :value => <string value>, :format => 0 }
 *
 * PostgreSQL bind parameters are represented as $1, $1, $2, etc.,
 * inside the SQL query. The 0th element of the +params+ array is bound
 * to $1, the 1st element is bound to $2, etc. +nil+ is treated as +NULL+.
 *
 * The optional +result_format+ should be 0 for text results, 1
 * for binary.
 */
static VALUE
pgconn_send_query_prepared(int argc, VALUE *argv, VALUE self)
{
	PGconn *conn = pg_get_pgconn(self);
	int result;
	VALUE name, params, in_res_fmt;
	VALUE param, param_value, param_format;
	VALUE param_value_tmp;
	VALUE sym_value, sym_format;
	VALUE gc_array;
	VALUE error;
	int i = 0;
	int nParams;
	char ** paramValues;
	int *paramLengths;
	int *paramFormats;
	int resultFormat;

	rb_scan_args(argc, argv, "12", &name, &params, &in_res_fmt);
	Check_Type(name, T_STRING);

	if(NIL_P(params)) {
		params = rb_ary_new2(0);
		resultFormat = 0;
	}
	else {
		Check_Type(params, T_ARRAY);
	}

	if(NIL_P(in_res_fmt)) {
		resultFormat = 0;
	}
	else {
		resultFormat = NUM2INT(in_res_fmt);
	}

	gc_array = rb_ary_new();
	rb_gc_register_address(&gc_array);
	sym_value = ID2SYM(rb_intern("value"));
	sym_format = ID2SYM(rb_intern("format"));
	nParams = (int)RARRAY_LEN(params);
	paramValues = ALLOC_N(char *, nParams);
	paramLengths = ALLOC_N(int, nParams);
	paramFormats = ALLOC_N(int, nParams);
	for(i = 0; i < nParams; i++) {
		param = rb_ary_entry(params, i);
		if (TYPE(param) == T_HASH) {
			param_value_tmp = rb_hash_aref(param, sym_value);
			if(param_value_tmp == Qnil)
				param_value = param_value_tmp;
			else
				param_value = rb_obj_as_string(param_value_tmp);
			param_format = rb_hash_aref(param, sym_format);
		}
		else {
			if(param == Qnil)
				param_value = param;
			else
				param_value = rb_obj_as_string(param);
			param_format = INT2NUM(0);
		}

		if(param_value == Qnil) {
			paramValues[i] = NULL;
			paramLengths[i] = 0;
		}
		else {
			Check_Type(param_value, T_STRING);
			/* make sure param_value doesn't get freed by the GC */
			rb_ary_push(gc_array, param_value);
			paramValues[i] = StringValuePtr(param_value);
			paramLengths[i] = (int)RSTRING_LEN(param_value);
		}

		if(param_format == Qnil)
			paramFormats[i] = 0;
		else
			paramFormats[i] = NUM2INT(param_format);
	}

	result = PQsendQueryPrepared(conn, StringValuePtr(name), nParams,
		(const char * const *)paramValues, paramLengths, paramFormats,
		resultFormat);

	rb_gc_unregister_address(&gc_array);

	xfree(paramValues);
	xfree(paramLengths);
	xfree(paramFormats);

	if(result == 0) {
		error = rb_exc_new2(rb_eUnableToSend, PQerrorMessage(conn));
		rb_iv_set(error, "@connection", self);
		rb_exc_raise(error);
	}
	return Qnil;
}

/*
 * call-seq:
 *    conn.send_describe_prepared( statement_name ) -> nil
 *
 * Asynchronously send _command_ to the server. Does not block.
 * Use in combination with +conn.get_result+.
 */
static VALUE
pgconn_send_describe_prepared(VALUE self, VALUE stmt_name)
{
	VALUE error;
	PGconn *conn = pg_get_pgconn(self);
	/* returns 0 on failure */
	if(PQsendDescribePrepared(conn,StringValuePtr(stmt_name)) == 0) {
		error = rb_exc_new2(rb_eUnableToSend, PQerrorMessage(conn));
		rb_iv_set(error, "@connection", self);
		rb_exc_raise(error);
	}
	return Qnil;
}


/*
 * call-seq:
 *    conn.send_describe_portal( portal_name ) -> nil
 *
 * Asynchronously send _command_ to the server. Does not block.
 * Use in combination with +conn.get_result+.
 */
static VALUE
pgconn_send_describe_portal(VALUE self, VALUE portal)
{
	VALUE error;
	PGconn *conn = pg_get_pgconn(self);
	/* returns 0 on failure */
	if(PQsendDescribePortal(conn,StringValuePtr(portal)) == 0) {
		error = rb_exc_new2(rb_eUnableToSend, PQerrorMessage(conn));
		rb_iv_set(error, "@connection", self);
		rb_exc_raise(error);
	}
	return Qnil;
}


/*
 * call-seq:
 *    conn.get_result() -> PG::Result
 *    conn.get_result() {|pg_result| block }
 *
 * Blocks waiting for the next result from a call to
 * #send_query (or another asynchronous command), and returns
 * it. Returns +nil+ if no more results are available.
 *
 * Note: call this function repeatedly until it returns +nil+, or else
 * you will not be able to issue further commands.
 *
 * If the optional code block is given, it will be passed <i>result</i> as an argument,
 * and the PG::Result object will  automatically be cleared when the block terminates.
 * In this instance, <code>conn.exec</code> returns the value of the block.
 */
static VALUE
pgconn_get_result(VALUE self)
{
	PGconn *conn = pg_get_pgconn(self);
	PGresult *result;
	VALUE rb_pgresult;

	result = gvl_PQgetResult(conn);
	if(result == NULL)
		return Qnil;
	rb_pgresult = pg_new_result(result, self);
	if (rb_block_given_p()) {
		return rb_ensure(rb_yield, rb_pgresult,
			pg_result_clear, rb_pgresult);
	}
	return rb_pgresult;
}

/*
 * call-seq:
 *    conn.consume_input()
 *
 * If input is available from the server, consume it.
 * After calling +consume_input+, you can check +is_busy+
 * or *notifies* to see if the state has changed.
 */
static VALUE
pgconn_consume_input(self)
	VALUE self;
{
	VALUE error;
	PGconn *conn = pg_get_pgconn(self);
	/* returns 0 on error */
	if(PQconsumeInput(conn) == 0) {
		error = rb_exc_new2(rb_eConnectionBad, PQerrorMessage(conn));
		rb_iv_set(error, "@connection", self);
		rb_exc_raise(error);
	}
	return Qnil;
}

/*
 * call-seq:
 *    conn.is_busy() -> Boolean
 *
 * Returns +true+ if a command is busy, that is, if
 * PQgetResult would block. Otherwise returns +false+.
 */
static VALUE
pgconn_is_busy(self)
	VALUE self;
{
	return PQisBusy(pg_get_pgconn(self)) ? Qtrue : Qfalse;
}

/*
 * call-seq:
 *    conn.setnonblocking(Boolean) -> nil
 *
 * Sets the nonblocking status of the connection.
 * In the blocking state, calls to #send_query
 * will block until the message is sent to the server,
 * but will not wait for the query results.
 * In the nonblocking state, calls to #send_query
 * will return an error if the socket is not ready for
 * writing.
 * Note: This function does not affect #exec, because
 * that function doesn't return until the server has
 * processed the query and returned the results.
 * Returns +nil+.
 */
static VALUE
pgconn_setnonblocking(self, state)
	VALUE self, state;
{
	int arg;
	VALUE error;
	PGconn *conn = pg_get_pgconn(self);
	if(state == Qtrue)
		arg = 1;
	else if (state == Qfalse)
		arg = 0;
	else
		rb_raise(rb_eArgError, "Boolean value expected");

	if(PQsetnonblocking(conn, arg) == -1) {
		error = rb_exc_new2(rb_ePGerror, PQerrorMessage(conn));
		rb_iv_set(error, "@connection", self);
		rb_exc_raise(error);
	}
	return Qnil;
}


/*
 * call-seq:
 *    conn.isnonblocking() -> Boolean
 *
 * Returns +true+ if a command is busy, that is, if
 * PQgetResult would block. Otherwise returns +false+.
 */
static VALUE
pgconn_isnonblocking(self)
	VALUE self;
{
	return PQisnonblocking(pg_get_pgconn(self)) ? Qtrue : Qfalse;
}

/*
 * call-seq:
 *    conn.flush() -> Boolean
 *
 * Attempts to flush any queued output data to the server.
 * Returns +true+ if data is successfully flushed, +false+
 * if not (can only return +false+ if connection is
 * nonblocking.
 * Raises PG::Error if some other failure occurred.
 */
static VALUE
pgconn_flush(self)
	VALUE self;
{
	PGconn *conn = pg_get_pgconn(self);
	int ret;
	VALUE error;
	ret = PQflush(conn);
	if(ret == -1) {
		error = rb_exc_new2(rb_ePGerror, PQerrorMessage(conn));
		rb_iv_set(error, "@connection", self);
		rb_exc_raise(error);
	}
	return (ret) ? Qfalse : Qtrue;
}

/*
 * call-seq:
 *    conn.cancel() -> String
 *
 * Requests cancellation of the command currently being
 * processed. (Only implemented in PostgreSQL >= 8.0)
 *
 * Returns +nil+ on success, or a string containing the
 * error message if a failure occurs.
 */
static VALUE
pgconn_cancel(VALUE self)
{
#ifdef HAVE_PQGETCANCEL
	char errbuf[256];
	PGcancel *cancel;
	VALUE retval;
	int ret;

	cancel = PQgetCancel(pg_get_pgconn(self));
	if(cancel == NULL)
		rb_raise(rb_ePGerror,"Invalid connection!");

	ret = PQcancel(cancel, errbuf, 256);
	if(ret == 1)
		retval = Qnil;
	else
		retval = rb_str_new2(errbuf);

	PQfreeCancel(cancel);
	return retval;
#else
	rb_notimplement();
#endif
}


/*
 * call-seq:
 *    conn.notifies()
 *
 * Returns a hash of the unprocessed notifications.
 * If there is no unprocessed notifier, it returns +nil+.
 */
static VALUE
pgconn_notifies(VALUE self)
{
	PGconn* conn = pg_get_pgconn(self);
	PGnotify *notification;
	VALUE hash;
	VALUE sym_relname, sym_be_pid, sym_extra;
	VALUE relname, be_pid, extra;

	sym_relname = ID2SYM(rb_intern("relname"));
	sym_be_pid = ID2SYM(rb_intern("be_pid"));
	sym_extra = ID2SYM(rb_intern("extra"));

	notification = gvl_PQnotifies(conn);
	if (notification == NULL) {
		return Qnil;
	}

	hash = rb_hash_new();
	relname = rb_tainted_str_new2(notification->relname);
	be_pid = INT2NUM(notification->be_pid);
	extra = rb_tainted_str_new2(notification->extra);
#ifdef M17N_SUPPORTED
	ENCODING_SET( relname, rb_enc_to_index(pg_conn_enc_get( conn )) );
	ENCODING_SET( extra, rb_enc_to_index(pg_conn_enc_get( conn )) );
#endif

	rb_hash_aset(hash, sym_relname, relname);
	rb_hash_aset(hash, sym_be_pid, be_pid);
	rb_hash_aset(hash, sym_extra, extra);

	PQfreemem(notification);
	return hash;
}

/* Win32 + Ruby 1.8 */
#if !defined( HAVE_RUBY_VM_H ) && defined( _WIN32 )

/*
 * Duplicate the sockets from libpq and create temporary CRT FDs
 */
void create_crt_fd(fd_set *os_set, fd_set *crt_set)
{
	int i;
	crt_set->fd_count = os_set->fd_count;
	for (i = 0; i < os_set->fd_count; i++) {
		WSAPROTOCOL_INFO wsa_pi;
		/* dupicate the SOCKET */
		int r = WSADuplicateSocket(os_set->fd_array[i], GetCurrentProcessId(), &wsa_pi);
		SOCKET s = WSASocket(wsa_pi.iAddressFamily, wsa_pi.iSocketType, wsa_pi.iProtocol, &wsa_pi, 0, 0);
		/* create the CRT fd so ruby can get back to the SOCKET */
		int fd = _open_osfhandle(s, O_RDWR|O_BINARY);
		os_set->fd_array[i] = s;
		crt_set->fd_array[i] = fd;
	}
}

/*
 * Clean up the CRT FDs from create_crt_fd()
 */
void cleanup_crt_fd(fd_set *os_set, fd_set *crt_set)
{
	int i;
	for (i = 0; i < os_set->fd_count; i++) {
		/* cleanup the CRT fd */
		_close(crt_set->fd_array[i]);
		/* cleanup the duplicated SOCKET */
		closesocket(os_set->fd_array[i]);
	}
}
#endif

/* Win32 + Ruby 1.9+ */
#if defined( HAVE_RUBY_VM_H ) && defined( _WIN32 )
/*
 * On Windows, use platform-specific strategies to wait for the socket
 * instead of rb_thread_select().
 */

int rb_w32_wait_events( HANDLE *events, int num, DWORD timeout );

/* If WIN32 and Ruby 1.9 do not use rb_thread_select() which sometimes hangs
 * and does not wait (nor sleep) any time even if timeout is given.
 * Instead use the Winsock events and rb_w32_wait_events(). */

static void *
wait_socket_readable( PGconn *conn, struct timeval *ptimeout, void *(*is_readable)(PGconn *) )
{
	int sd = PQsocket( conn );
	void *retval;
	struct timeval aborttime={0,0}, currtime, waittime;
	DWORD timeout_milisec = INFINITE;
	DWORD wait_ret;
	WSAEVENT hEvent;

	if ( sd < 0 )
		rb_raise(rb_eConnectionBad, "PQsocket() can't get socket descriptor");

	hEvent = WSACreateEvent();

	/* Check for connection errors (PQisBusy is true on connection errors) */
	if( PQconsumeInput(conn) == 0 ) {
		WSACloseEvent( hEvent );
		rb_raise( rb_eConnectionBad, "PQconsumeInput() %s", PQerrorMessage(conn) );
	}

	if ( ptimeout ) {
		gettimeofday(&currtime, NULL);
		timeradd(&currtime, ptimeout, &aborttime);
	}

	while ( !(retval=is_readable(conn)) ) {
		if ( WSAEventSelect(sd, hEvent, FD_READ|FD_CLOSE) == SOCKET_ERROR ) {
			WSACloseEvent( hEvent );
			rb_raise( rb_eConnectionBad, "WSAEventSelect socket error: %d", WSAGetLastError() );
		}

		if ( ptimeout ) {
			gettimeofday(&currtime, NULL);
			timersub(&aborttime, &currtime, &waittime);
			timeout_milisec = (DWORD)( waittime.tv_sec * 1e3 + waittime.tv_usec / 1e3 );
		}

		/* Is the given timeout valid? */
		if( !ptimeout || (waittime.tv_sec >= 0 && waittime.tv_usec >= 0) ){
			/* Wait for the socket to become readable before checking again */
			wait_ret = rb_w32_wait_events( &hEvent, 1, timeout_milisec );
		} else {
			wait_ret = WAIT_TIMEOUT;
		}

		if ( wait_ret == WAIT_TIMEOUT ) {
			WSACloseEvent( hEvent );
			return NULL;
		} else if ( wait_ret == WAIT_OBJECT_0 ) {
			/* The event we were waiting for. */
		} else if ( wait_ret == WAIT_OBJECT_0 + 1) {
			/* This indicates interruption from timer thread, GC, exception
			 * from other threads etc... */
			rb_thread_check_ints();
		} else if ( wait_ret == WAIT_FAILED ) {
			WSACloseEvent( hEvent );
			rb_raise( rb_eConnectionBad, "Wait on socket error (WaitForMultipleObjects): %lu", GetLastError() );
		} else {
			WSACloseEvent( hEvent );
			rb_raise( rb_eConnectionBad, "Wait on socket abandoned (WaitForMultipleObjects)" );
		}

		/* Check for connection errors (PQisBusy is true on connection errors) */
		if ( PQconsumeInput(conn) == 0 ) {
			WSACloseEvent( hEvent );
			rb_raise( rb_eConnectionBad, "PQconsumeInput() %s", PQerrorMessage(conn) );
		}
	}

	WSACloseEvent( hEvent );
	return retval;
}

#else

/* non Win32 or Win32+Ruby-1.8 */

static void *
wait_socket_readable( PGconn *conn, struct timeval *ptimeout, void *(*is_readable)(PGconn *))
{
	int sd = PQsocket( conn );
	int ret;
	void *retval;
	rb_fdset_t sd_rset;
	struct timeval aborttime={0,0}, currtime, waittime;
#ifdef _WIN32
	rb_fdset_t crt_sd_rset;
#endif

	if ( sd < 0 )
		rb_raise(rb_eConnectionBad, "PQsocket() can't get socket descriptor");

	/* Check for connection errors (PQisBusy is true on connection errors) */
	if ( PQconsumeInput(conn) == 0 )
		rb_raise( rb_eConnectionBad, "PQconsumeInput() %s", PQerrorMessage(conn) );

	rb_fd_init( &sd_rset );

	if ( ptimeout ) {
		gettimeofday(&currtime, NULL);
		timeradd(&currtime, ptimeout, &aborttime);
	}

	while ( !(retval=is_readable(conn)) ) {
		rb_fd_zero( &sd_rset );
		rb_fd_set( sd, &sd_rset );

#ifdef _WIN32
		/* Ruby's FD_SET is modified on win32 to convert a file descriptor
		 * to osfhandle, but we already get a osfhandle from PQsocket().
		 * Therefore it's overwritten here. */
		sd_rset.fd_array[0] = sd;
		create_crt_fd(&sd_rset, &crt_sd_rset);
#endif

		if ( ptimeout ) {
			gettimeofday(&currtime, NULL);
			timersub(&aborttime, &currtime, &waittime);
		}

		/* Is the given timeout valid? */
		if( !ptimeout || (waittime.tv_sec >= 0 && waittime.tv_usec >= 0) ){
			/* Wait for the socket to become readable before checking again */
			ret = rb_thread_fd_select( sd+1, &sd_rset, NULL, NULL, ptimeout ? &waittime : NULL );
		} else {
			ret = 0;
		}


#ifdef _WIN32
		cleanup_crt_fd(&sd_rset, &crt_sd_rset);
#endif

		if ( ret < 0 ){
			rb_fd_term( &sd_rset );
			rb_sys_fail( "rb_thread_select()" );
		}

		/* Return false if the select() timed out */
		if ( ret == 0 ){
			rb_fd_term( &sd_rset );
			return NULL;
		}

		/* Check for connection errors (PQisBusy is true on connection errors) */
		if ( PQconsumeInput(conn) == 0 ){
			rb_fd_term( &sd_rset );
			rb_raise( rb_eConnectionBad, "PQconsumeInput() %s", PQerrorMessage(conn) );
		}
	}

	rb_fd_term( &sd_rset );
	return retval;
}


#endif

static void *
notify_readable(PGconn *conn)
{
	return (void*)gvl_PQnotifies(conn);
}

/*
 * call-seq:
 *    conn.wait_for_notify( [ timeout ] ) -> String
 *    conn.wait_for_notify( [ timeout ] ) { |event, pid| block }
 *    conn.wait_for_notify( [ timeout ] ) { |event, pid, payload| block } # PostgreSQL 9.0
 *
 * Blocks while waiting for notification(s), or until the optional
 * _timeout_ is reached, whichever comes first.  _timeout_ is
 * measured in seconds and can be fractional.
 *
 * Returns +nil+ if _timeout_ is reached, the name of the NOTIFY
 * event otherwise.  If used in block form, passes the name of the
 * NOTIFY +event+ and the generating +pid+ into the block.
 *
 * Under PostgreSQL 9.0 and later, if the notification is sent with
 * the optional +payload+ string, it will be given to the block as the
 * third argument.
 *
 */
static VALUE
pgconn_wait_for_notify(int argc, VALUE *argv, VALUE self)
{
	PGconn *conn = pg_get_pgconn( self );
	PGnotify *pnotification;
	struct timeval timeout;
	struct timeval *ptimeout = NULL;
	VALUE timeout_in = Qnil, relname = Qnil, be_pid = Qnil, extra = Qnil;
	double timeout_sec;

	rb_scan_args( argc, argv, "01", &timeout_in );

	if ( RTEST(timeout_in) ) {
		timeout_sec = NUM2DBL( timeout_in );
		timeout.tv_sec = (time_t)timeout_sec;
		timeout.tv_usec = (suseconds_t)( (timeout_sec - (long)timeout_sec) * 1e6 );
		ptimeout = &timeout;
	}

	pnotification = (PGnotify*) wait_socket_readable( conn, ptimeout, notify_readable);

	/* Return nil if the select timed out */
	if ( !pnotification ) return Qnil;

	relname = rb_tainted_str_new2( pnotification->relname );
#ifdef M17N_SUPPORTED
	ENCODING_SET( relname, rb_enc_to_index(pg_conn_enc_get( conn )) );
#endif
	be_pid = INT2NUM( pnotification->be_pid );
#ifdef HAVE_ST_NOTIFY_EXTRA
	if ( *pnotification->extra ) {
		extra = rb_tainted_str_new2( pnotification->extra );
#ifdef M17N_SUPPORTED
		ENCODING_SET( extra, rb_enc_to_index(pg_conn_enc_get( conn )) );
#endif
	}
#endif
	PQfreemem( pnotification );

	if ( rb_block_given_p() )
		rb_yield_values( 3, relname, be_pid, extra );

	return relname;
}


/*
 * call-seq:
 *    conn.put_copy_data( buffer ) -> Boolean
 *
 * Transmits _buffer_ as copy data to the server.
 * Returns true if the data was sent, false if it was
 * not sent (false is only possible if the connection
 * is in nonblocking mode, and this command would block).
 *
 * Raises an exception if an error occurs.
 *
 * See also #copy_data.
 *
 */
static VALUE
pgconn_put_copy_data(self, buffer)
	VALUE self, buffer;
{
	int ret;
	VALUE error;
	PGconn *conn = pg_get_pgconn(self);
	Check_Type(buffer, T_STRING);

	ret = gvl_PQputCopyData(conn, RSTRING_PTR(buffer), (int)RSTRING_LEN(buffer));
	if(ret == -1) {
		error = rb_exc_new2(rb_ePGerror, PQerrorMessage(conn));
		rb_iv_set(error, "@connection", self);
		rb_exc_raise(error);
	}
	return (ret) ? Qtrue : Qfalse;
}

/*
 * call-seq:
 *    conn.put_copy_end( [ error_message ] ) -> Boolean
 *
 * Sends end-of-data indication to the server.
 *
 * _error_message_ is an optional parameter, and if set,
 * forces the COPY command to fail with the string
 * _error_message_.
 *
 * Returns true if the end-of-data was sent, false if it was
 * not sent (false is only possible if the connection
 * is in nonblocking mode, and this command would block).
 */
static VALUE
pgconn_put_copy_end(int argc, VALUE *argv, VALUE self)
{
	VALUE str;
	VALUE error;
	int ret;
	char *error_message = NULL;
	PGconn *conn = pg_get_pgconn(self);

	if (rb_scan_args(argc, argv, "01", &str) == 0)
		error_message = NULL;
	else
		error_message = StringValuePtr(str);

	ret = gvl_PQputCopyEnd(conn, error_message);
	if(ret == -1) {
		error = rb_exc_new2(rb_ePGerror, PQerrorMessage(conn));
		rb_iv_set(error, "@connection", self);
		rb_exc_raise(error);
	}
	return (ret) ? Qtrue : Qfalse;
}

/*
 * call-seq:
 *    conn.get_copy_data( [ async = false ] ) -> String
 *
 * Return a string containing one row of data, +nil+
 * if the copy is done, or +false+ if the call would
 * block (only possible if _async_ is true).
 *
 * See also #copy_data.
 *
 */
static VALUE
pgconn_get_copy_data(int argc, VALUE *argv, VALUE self )
{
	VALUE async_in;
	VALUE error;
	VALUE result_str;
	int ret;
	int async;
	char *buffer;
	PGconn *conn = pg_get_pgconn(self);

	if (rb_scan_args(argc, argv, "01", &async_in) == 0)
		async = 0;
	else
		async = (async_in == Qfalse || async_in == Qnil) ? 0 : 1;

	ret = gvl_PQgetCopyData(conn, &buffer, async);
	if(ret == -2) { /* error */
		error = rb_exc_new2(rb_ePGerror, PQerrorMessage(conn));
		rb_iv_set(error, "@connection", self);
		rb_exc_raise(error);
	}
	if(ret == -1) { /* No data left */
		return Qnil;
	}
	if(ret == 0) { /* would block */
		return Qfalse;
	}
	result_str = rb_tainted_str_new(buffer, ret);
	PQfreemem(buffer);
	return result_str;
}

/*
 * call-seq:
 *    conn.set_error_verbosity( verbosity ) -> Fixnum
 *
 * Sets connection's verbosity to _verbosity_ and returns
 * the previous setting. Available settings are:
 * * PQERRORS_TERSE
 * * PQERRORS_DEFAULT
 * * PQERRORS_VERBOSE
 */
static VALUE
pgconn_set_error_verbosity(VALUE self, VALUE in_verbosity)
{
	PGconn *conn = pg_get_pgconn(self);
	PGVerbosity verbosity = NUM2INT(in_verbosity);
	return INT2FIX(PQsetErrorVerbosity(conn, verbosity));
}

/*
 * call-seq:
 *    conn.trace( stream ) -> nil
 *
 * Enables tracing message passing between backend. The
 * trace message will be written to the stream _stream_,
 * which must implement a method +fileno+ that returns
 * a writable file descriptor.
 */
static VALUE
pgconn_trace(VALUE self, VALUE stream)
{
	VALUE fileno;
	FILE *new_fp;
	int old_fd, new_fd;
	VALUE new_file;

	if(rb_respond_to(stream,rb_intern("fileno")) == Qfalse)
		rb_raise(rb_eArgError, "stream does not respond to method: fileno");

	fileno = rb_funcall(stream, rb_intern("fileno"), 0);
	if(fileno == Qnil)
		rb_raise(rb_eArgError, "can't get file descriptor from stream");

	/* Duplicate the file descriptor and re-open
	 * it. Then, make it into a ruby File object
	 * and assign it to an instance variable.
	 * This prevents a problem when the File
	 * object passed to this function is closed
	 * before the connection object is. */
	old_fd = NUM2INT(fileno);
	new_fd = dup(old_fd);
	new_fp = fdopen(new_fd, "w");

	if(new_fp == NULL)
		rb_raise(rb_eArgError, "stream is not writable");

	new_file = rb_funcall(rb_cIO, rb_intern("new"), 1, INT2NUM(new_fd));
	rb_iv_set(self, "@trace_stream", new_file);

	PQtrace(pg_get_pgconn(self), new_fp);
	return Qnil;
}

/*
 * call-seq:
 *    conn.untrace() -> nil
 *
 * Disables the message tracing.
 */
static VALUE
pgconn_untrace(VALUE self)
{
	VALUE trace_stream;
	PQuntrace(pg_get_pgconn(self));
	trace_stream = rb_iv_get(self, "@trace_stream");
	rb_funcall(trace_stream, rb_intern("close"), 0);
	rb_iv_set(self, "@trace_stream", Qnil);
	return Qnil;
}


/*
 * Notice callback proxy function -- delegate the callback to the
 * currently-registered Ruby notice_receiver object.
 */
void
notice_receiver_proxy(void *arg, const PGresult *result)
{
	VALUE proc;
	VALUE self = (VALUE)arg;

	if ((proc = rb_iv_get(self, "@notice_receiver")) != Qnil) {
		VALUE val = Data_Wrap_Struct(rb_cPGresult, NULL, NULL, (PGresult*)result);
#ifdef M17N_SUPPORTED
		PGconn *conn = pg_get_pgconn( self );
		rb_encoding *enc = pg_conn_enc_get( conn );
		ENCODING_SET( val, rb_enc_to_index(enc) );
#endif
		rb_funcall(proc, rb_intern("call"), 1, val);
	}
	return;
}

/*
 * call-seq:
 *   conn.set_notice_receiver {|result| ... } -> Proc
 *
 * Notice and warning messages generated by the server are not returned
 * by the query execution functions, since they do not imply failure of
 * the query. Instead they are passed to a notice handling function, and
 * execution continues normally after the handler returns. The default
 * notice handling function prints the message on <tt>stderr</tt>, but the
 * application can override this behavior by supplying its own handling
 * function.
 *
 * For historical reasons, there are two levels of notice handling, called the
 * notice receiver and notice processor. The default behavior is for the notice
 * receiver to format the notice and pass a string to the notice processor for
 * printing. However, an application that chooses to provide its own notice
 * receiver will typically ignore the notice processor layer and just do all
 * the work in the notice receiver.
 *
 * This function takes a new block to act as the handler, which should
 * accept a single parameter that will be a PG::Result object, and returns
 * the Proc object previously set, or +nil+ if it was previously the default.
 *
 * If you pass no arguments, it will reset the handler to the default.
 *
 * *Note:* The +result+ passed to the block should not be used outside
 * of the block, since the corresponding C object could be freed after the
 * block finishes.
 */
static VALUE
pgconn_set_notice_receiver(VALUE self)
{
	VALUE proc, old_proc;
	PGconn *conn = pg_get_pgconn(self);

	/* If default_notice_receiver is unset, assume that the current
	 * notice receiver is the default, and save it to a global variable.
	 * This should not be a problem because the default receiver is
	 * always the same, so won't vary among connections.
	 */
	if(default_notice_receiver == NULL)
		default_notice_receiver = PQsetNoticeReceiver(conn, NULL, NULL);

	old_proc = rb_iv_get(self, "@notice_receiver");
	if( rb_block_given_p() ) {
		proc = rb_block_proc();
		PQsetNoticeReceiver(conn, gvl_notice_receiver_proxy, (void *)self);
	} else {
		/* if no block is given, set back to default */
		proc = Qnil;
		PQsetNoticeReceiver(conn, default_notice_receiver, NULL);
	}

	rb_iv_set(self, "@notice_receiver", proc);
	return old_proc;
}


/*
 * Notice callback proxy function -- delegate the callback to the
 * currently-registered Ruby notice_processor object.
 */
void
notice_processor_proxy(void *arg, const char *message)
{
	VALUE proc;
	VALUE self = (VALUE)arg;

	if ((proc = rb_iv_get(self, "@notice_processor")) != Qnil) {
		VALUE message_str = rb_tainted_str_new2(message);
#ifdef M17N_SUPPORTED
		PGconn *conn = pg_get_pgconn( self );
		rb_encoding *enc = pg_conn_enc_get( conn );
		ENCODING_SET( message_str, rb_enc_to_index(enc) );
#endif
		rb_funcall(proc, rb_intern("call"), 1, message_str);
	}
	return;
}

/*
 * call-seq:
 *   conn.set_notice_processor {|message| ... } -> Proc
 *
 * See #set_notice_receiver for the desription of what this and the
 * notice_processor methods do.
 *
 * This function takes a new block to act as the notice processor and returns
 * the Proc object previously set, or +nil+ if it was previously the default.
 * The block should accept a single String object.
 *
 * If you pass no arguments, it will reset the handler to the default.
 */
static VALUE
pgconn_set_notice_processor(VALUE self)
{
	VALUE proc, old_proc;
	PGconn *conn = pg_get_pgconn(self);

	/* If default_notice_processor is unset, assume that the current
	 * notice processor is the default, and save it to a global variable.
	 * This should not be a problem because the default processor is
	 * always the same, so won't vary among connections.
	 */
	if(default_notice_processor == NULL)
		default_notice_processor = PQsetNoticeProcessor(conn, NULL, NULL);

	old_proc = rb_iv_get(self, "@notice_processor");
	if( rb_block_given_p() ) {
		proc = rb_block_proc();
		PQsetNoticeProcessor(conn, gvl_notice_processor_proxy, (void *)self);
	} else {
		/* if no block is given, set back to default */
		proc = Qnil;
		PQsetNoticeProcessor(conn, default_notice_processor, NULL);
	}

	rb_iv_set(self, "@notice_processor", proc);
	return old_proc;
}


/*
 * call-seq:
 *    conn.get_client_encoding() -> String
 *
 * Returns the client encoding as a String.
 */
static VALUE
pgconn_get_client_encoding(VALUE self)
{
	char *encoding = (char *)pg_encoding_to_char(PQclientEncoding(pg_get_pgconn(self)));
	return rb_tainted_str_new2(encoding);
}


/*
 * call-seq:
 *    conn.set_client_encoding( encoding )
 *
 * Sets the client encoding to the _encoding_ String.
 */
static VALUE
pgconn_set_client_encoding(VALUE self, VALUE str)
{
	PGconn *conn = pg_get_pgconn( self );

	Check_Type(str, T_STRING);

	if ( (PQsetClientEncoding(conn, StringValuePtr(str))) == -1 ) {
		rb_raise(rb_ePGerror, "invalid encoding name: %s",StringValuePtr(str));
	}

	return Qnil;
}

/*
 * call-seq:
 *    conn.transaction { |conn| ... } -> result of the block
 *
 * Executes a +BEGIN+ at the start of the block,
 * and a +COMMIT+ at the end of the block, or
 * +ROLLBACK+ if any exception occurs.
 */
static VALUE
pgconn_transaction(VALUE self)
{
	PGconn *conn = pg_get_pgconn(self);
	PGresult *result;
	VALUE rb_pgresult;
	VALUE block_result = Qnil;
	int status;

	if (rb_block_given_p()) {
		result = gvl_PQexec(conn, "BEGIN");
		rb_pgresult = pg_new_result(result, self);
		pg_result_check(rb_pgresult);
		block_result = rb_protect(rb_yield, self, &status);
		if(status == 0) {
			result = gvl_PQexec(conn, "COMMIT");
			rb_pgresult = pg_new_result(result, self);
			pg_result_check(rb_pgresult);
		}
		else {
			/* exception occurred, ROLLBACK and re-raise */
			result = gvl_PQexec(conn, "ROLLBACK");
			rb_pgresult = pg_new_result(result, self);
			pg_result_check(rb_pgresult);
			rb_jump_tag(status);
		}

	}
	else {
		/* no block supplied? */
		rb_raise(rb_eArgError, "Must supply block for PG::Connection#transaction");
	}
	return block_result;
}


/*
 * call-seq:
 *    PG::Connection.quote_ident( str ) -> String
 *    conn.quote_ident( str ) -> String
 *
 * Returns a string that is safe for inclusion in a SQL query as an
 * identifier. Note: this is not a quote function for values, but for
 * identifiers.
 *
 * For example, in a typical SQL query: <tt>SELECT FOO FROM MYTABLE</tt>
 * The identifier <tt>FOO</tt> is folded to lower case, so it actually
 * means <tt>foo</tt>. If you really want to access the case-sensitive
 * field name <tt>FOO</tt>, use this function like
 * <tt>PG::Connection.quote_ident('FOO')</tt>, which will return <tt>"FOO"</tt>
 * (with double-quotes). PostgreSQL will see the double-quotes, and
 * it will not fold to lower case.
 *
 * Similarly, this function also protects against special characters,
 * and other things that might allow SQL injection if the identifier
 * comes from an untrusted source.
 */
static VALUE
pgconn_s_quote_ident(VALUE self, VALUE in_str)
{
	VALUE ret;
	char *str = StringValuePtr(in_str);
	/* result size at most NAMEDATALEN*2 plus surrounding
	 * double-quotes. */
	char buffer[NAMEDATALEN*2+2];
	unsigned int i=0,j=0;
#ifdef M17N_SUPPORTED
	rb_encoding* enc;
#endif

	UNUSED( self );

	if(strlen(str) >= NAMEDATALEN) {
		rb_raise(rb_eArgError,
			"Input string is longer than NAMEDATALEN-1 (%d)",
			NAMEDATALEN-1);
	}
	buffer[j++] = '"';
	for(i = 0; i < strlen(str) && str[i]; i++) {
		if(str[i] == '"')
			buffer[j++] = '"';
		buffer[j++] = str[i];
	}
	buffer[j++] = '"';
	ret = rb_str_new(buffer,j);
	OBJ_INFECT(ret, in_str);

#ifdef M17N_SUPPORTED
	if ( rb_obj_class(self) == rb_cPGconn ) {
		enc = pg_conn_enc_get( pg_get_pgconn(self) );
	} else {
		enc = rb_enc_get(in_str);
	}
	rb_enc_associate(ret, enc);
#endif

	return ret;
}


static void *
get_result_readable(PGconn *conn)
{
	return PQisBusy(conn) ? NULL : (void*)1;
}


/*
 * call-seq:
 *    conn.block( [ timeout ] ) -> Boolean
 *
 * Blocks until the server is no longer busy, or until the
 * optional _timeout_ is reached, whichever comes first.
 * _timeout_ is measured in seconds and can be fractional.
 *
 * Returns +false+ if _timeout_ is reached, +true+ otherwise.
 *
 * If +true+ is returned, +conn.is_busy+ will return +false+
 * and +conn.get_result+ will not block.
 */
static VALUE
pgconn_block( int argc, VALUE *argv, VALUE self ) {
	PGconn *conn = pg_get_pgconn( self );

	/* If WIN32 and Ruby 1.9 do not use rb_thread_select() which sometimes hangs
	 * and does not wait (nor sleep) any time even if timeout is given.
	 * Instead use the Winsock events and rb_w32_wait_events(). */

	struct timeval timeout;
	struct timeval *ptimeout = NULL;
	VALUE timeout_in;
	double timeout_sec;
	void *ret;

	if ( rb_scan_args(argc, argv, "01", &timeout_in) == 1 ) {
		timeout_sec = NUM2DBL( timeout_in );
		timeout.tv_sec = (time_t)timeout_sec;
		timeout.tv_usec = (suseconds_t)((timeout_sec - (long)timeout_sec) * 1e6);
		ptimeout = &timeout;
	}

	ret = wait_socket_readable( conn, ptimeout, get_result_readable);

	if( !ret )
		return Qfalse;

	return Qtrue;
}


/*
 * call-seq:
 *    conn.get_last_result( ) -> PG::Result
 *
 * This function retrieves all available results
 * on the current connection (from previously issued
 * asynchronous commands like +send_query()+) and
 * returns the last non-NULL result, or +nil+ if no
 * results are available.
 *
 * This function is similar to #get_result
 * except that it is designed to get one and only
 * one result.
 */
static VALUE
pgconn_get_last_result(VALUE self)
{
	PGconn *conn = pg_get_pgconn(self);
	VALUE rb_pgresult = Qnil;
	PGresult *cur, *prev;


	cur = prev = NULL;
	while ((cur = gvl_PQgetResult(conn)) != NULL) {
		int status;

		if (prev) PQclear(prev);
		prev = cur;

		status = PQresultStatus(cur);
		if (status == PGRES_COPY_OUT || status == PGRES_COPY_IN)
			break;
	}

	if (prev) {
		rb_pgresult = pg_new_result( prev, self );
		pg_result_check(rb_pgresult);
	}

	return rb_pgresult;
}

#if !defined(HAVE_RB_THREAD_CALL_WITHOUT_GVL)

/*
 * call-seq:
 *    conn.async_exec(sql [, params, result_format ] ) -> PG::Result
 *    conn.async_exec(sql [, params, result_format ] ) {|pg_result| block }
 *
 * This function has the same behavior as #exec,
 * but ensures that other threads can process while
 * waiting for the server to complete the request.
 *
 * On Ruby platforms with native threads (MRI-1.9+ and all others)
 * this method is an alias to #exec.
 *
 * On MRI-1.8 it's implemented using asynchronous command
 * processing and ruby's +rb_thread_select+ .
 */
static VALUE
pgconn_async_exec(int argc, VALUE *argv, VALUE self)
{
	VALUE rb_pgresult = Qnil;

	/* remove any remaining results from the queue */
	pgconn_block( 0, NULL, self ); /* wait for input (without blocking) before reading the last result */
	pgconn_get_last_result( self );

	pgconn_send_query( argc, argv, self );
	pgconn_block( 0, NULL, self );
	rb_pgresult = pgconn_get_last_result( self );

	if ( rb_block_given_p() ) {
		return rb_ensure( rb_yield, rb_pgresult, pg_result_clear, rb_pgresult );
	}
	return rb_pgresult;
}

#endif

/**************************************************************************
 * LARGE OBJECT SUPPORT
 **************************************************************************/

/*
 * call-seq:
 *    conn.lo_creat( [mode] ) -> Fixnum
 *
 * Creates a large object with mode _mode_. Returns a large object Oid.
 * On failure, it raises PG::Error.
 */
static VALUE
pgconn_locreat(int argc, VALUE *argv, VALUE self)
{
	Oid lo_oid;
	int mode;
	VALUE nmode;
	PGconn *conn = pg_get_pgconn(self);

	if (rb_scan_args(argc, argv, "01", &nmode) == 0)
		mode = INV_READ;
	else
		mode = NUM2INT(nmode);

	lo_oid = lo_creat(conn, mode);
	if (lo_oid == 0)
		rb_raise(rb_ePGerror, "lo_creat failed");

	return INT2FIX(lo_oid);
}

/*
 * call-seq:
 *    conn.lo_create( oid ) -> Fixnum
 *
 * Creates a large object with oid _oid_. Returns the large object Oid.
 * On failure, it raises PG::Error.
 */
static VALUE
pgconn_locreate(VALUE self, VALUE in_lo_oid)
{
	Oid ret, lo_oid;
	PGconn *conn = pg_get_pgconn(self);
	lo_oid = NUM2INT(in_lo_oid);

	ret = lo_create(conn, lo_oid);
	if (ret == InvalidOid)
		rb_raise(rb_ePGerror, "lo_create failed");

	return INT2FIX(ret);
}

/*
 * call-seq:
 *    conn.lo_import(file) -> Fixnum
 *
 * Import a file to a large object. Returns a large object Oid.
 *
 * On failure, it raises a PG::Error.
 */
static VALUE
pgconn_loimport(VALUE self, VALUE filename)
{
	Oid lo_oid;

	PGconn *conn = pg_get_pgconn(self);

	Check_Type(filename, T_STRING);

	lo_oid = lo_import(conn, StringValuePtr(filename));
	if (lo_oid == 0) {
		rb_raise(rb_ePGerror, "%s", PQerrorMessage(conn));
	}
	return INT2FIX(lo_oid);
}

/*
 * call-seq:
 *    conn.lo_export( oid, file ) -> nil
 *
 * Saves a large object of _oid_ to a _file_.
 */
static VALUE
pgconn_loexport(VALUE self, VALUE lo_oid, VALUE filename)
{
	PGconn *conn = pg_get_pgconn(self);
	int oid;
	Check_Type(filename, T_STRING);

	oid = NUM2INT(lo_oid);
	if (oid < 0) {
		rb_raise(rb_ePGerror, "invalid large object oid %d",oid);
	}

	if (lo_export(conn, oid, StringValuePtr(filename)) < 0) {
		rb_raise(rb_ePGerror, "%s", PQerrorMessage(conn));
	}
	return Qnil;
}

/*
 * call-seq:
 *    conn.lo_open( oid, [mode] ) -> Fixnum
 *
 * Open a large object of _oid_. Returns a large object descriptor
 * instance on success. The _mode_ argument specifies the mode for
 * the opened large object,which is either +INV_READ+, or +INV_WRITE+.
 *
 * If _mode_ is omitted, the default is +INV_READ+.
 */
static VALUE
pgconn_loopen(int argc, VALUE *argv, VALUE self)
{
	Oid lo_oid;
	int fd, mode;
	VALUE nmode, selfid;
	PGconn *conn = pg_get_pgconn(self);

	rb_scan_args(argc, argv, "11", &selfid, &nmode);
	lo_oid = NUM2INT(selfid);
	if(NIL_P(nmode))
		mode = INV_READ;
	else
		mode = NUM2INT(nmode);

	if((fd = lo_open(conn, lo_oid, mode)) < 0) {
		rb_raise(rb_ePGerror, "can't open large object: %s", PQerrorMessage(conn));
	}
	return INT2FIX(fd);
}

/*
 * call-seq:
 *    conn.lo_write( lo_desc, buffer ) -> Fixnum
 *
 * Writes the string _buffer_ to the large object _lo_desc_.
 * Returns the number of bytes written.
 */
static VALUE
pgconn_lowrite(VALUE self, VALUE in_lo_desc, VALUE buffer)
{
	int n;
	PGconn *conn = pg_get_pgconn(self);
	int fd = NUM2INT(in_lo_desc);

	Check_Type(buffer, T_STRING);

	if( RSTRING_LEN(buffer) < 0) {
		rb_raise(rb_ePGerror, "write buffer zero string");
	}
	if((n = lo_write(conn, fd, StringValuePtr(buffer),
				RSTRING_LEN(buffer))) < 0) {
		rb_raise(rb_ePGerror, "lo_write failed: %s", PQerrorMessage(conn));
	}

	return INT2FIX(n);
}

/*
 * call-seq:
 *    conn.lo_read( lo_desc, len ) -> String
 *
 * Attempts to read _len_ bytes from large object _lo_desc_,
 * returns resulting data.
 */
static VALUE
pgconn_loread(VALUE self, VALUE in_lo_desc, VALUE in_len)
{
	int ret;
  PGconn *conn = pg_get_pgconn(self);
	int len = NUM2INT(in_len);
	int lo_desc = NUM2INT(in_lo_desc);
	VALUE str;
	char *buffer;

  buffer = ALLOC_N(char, len);
	if(buffer == NULL)
		rb_raise(rb_eNoMemError, "ALLOC failed!");

	if (len < 0){
		rb_raise(rb_ePGerror,"nagative length %d given", len);
	}

	if((ret = lo_read(conn, lo_desc, buffer, len)) < 0)
		rb_raise(rb_ePGerror, "lo_read failed");

	if(ret == 0) {
		xfree(buffer);
		return Qnil;
	}

	str = rb_tainted_str_new(buffer, ret);
	xfree(buffer);

	return str;
}


/*
 * call-seq:
 *    conn.lo_lseek( lo_desc, offset, whence ) -> Fixnum
 *
 * Move the large object pointer _lo_desc_ to offset _offset_.
 * Valid values for _whence_ are +SEEK_SET+, +SEEK_CUR+, and +SEEK_END+.
 * (Or 0, 1, or 2.)
 */
static VALUE
pgconn_lolseek(VALUE self, VALUE in_lo_desc, VALUE offset, VALUE whence)
{
	PGconn *conn = pg_get_pgconn(self);
	int lo_desc = NUM2INT(in_lo_desc);
	int ret;

	if((ret = lo_lseek(conn, lo_desc, NUM2INT(offset), NUM2INT(whence))) < 0) {
		rb_raise(rb_ePGerror, "lo_lseek failed");
	}

	return INT2FIX(ret);
}

/*
 * call-seq:
 *    conn.lo_tell( lo_desc ) -> Fixnum
 *
 * Returns the current position of the large object _lo_desc_.
 */
static VALUE
pgconn_lotell(VALUE self, VALUE in_lo_desc)
{
	int position;
	PGconn *conn = pg_get_pgconn(self);
	int lo_desc = NUM2INT(in_lo_desc);

	if((position = lo_tell(conn, lo_desc)) < 0)
		rb_raise(rb_ePGerror,"lo_tell failed");

	return INT2FIX(position);
}

/*
 * call-seq:
 *    conn.lo_truncate( lo_desc, len ) -> nil
 *
 * Truncates the large object _lo_desc_ to size _len_.
 */
static VALUE
pgconn_lotruncate(VALUE self, VALUE in_lo_desc, VALUE in_len)
{
	PGconn *conn = pg_get_pgconn(self);
	int lo_desc = NUM2INT(in_lo_desc);
	size_t len = NUM2INT(in_len);

	if(lo_truncate(conn,lo_desc,len) < 0)
		rb_raise(rb_ePGerror,"lo_truncate failed");

	return Qnil;
}

/*
 * call-seq:
 *    conn.lo_close( lo_desc ) -> nil
 *
 * Closes the postgres large object of _lo_desc_.
 */
static VALUE
pgconn_loclose(VALUE self, VALUE in_lo_desc)
{
	PGconn *conn = pg_get_pgconn(self);
	int lo_desc = NUM2INT(in_lo_desc);

	if(lo_close(conn,lo_desc) < 0)
		rb_raise(rb_ePGerror,"lo_close failed");

	return Qnil;
}

/*
 * call-seq:
 *    conn.lo_unlink( oid ) -> nil
 *
 * Unlinks (deletes) the postgres large object of _oid_.
 */
static VALUE
pgconn_lounlink(VALUE self, VALUE in_oid)
{
	PGconn *conn = pg_get_pgconn(self);
	int oid = NUM2INT(in_oid);

	if (oid < 0)
		rb_raise(rb_ePGerror, "invalid oid %d",oid);

	if(lo_unlink(conn,oid) < 0)
		rb_raise(rb_ePGerror,"lo_unlink failed");

	return Qnil;
}


#ifdef M17N_SUPPORTED

/*
 * call-seq:
 *   conn.internal_encoding -> Encoding
 *
 * defined in Ruby 1.9 or later.
 *
 * Returns:
 * * an Encoding - client_encoding of the connection as a Ruby Encoding object.
 * * nil - the client_encoding is 'SQL_ASCII'
 */
static VALUE
pgconn_internal_encoding(VALUE self)
{
	PGconn *conn = pg_get_pgconn( self );
	rb_encoding *enc = pg_conn_enc_get( conn );

	if ( enc ) {
		return rb_enc_from_encoding( enc );
	} else {
		return Qnil;
	}
}

static VALUE pgconn_external_encoding(VALUE self);

/*
 * call-seq:
 *   conn.internal_encoding = value
 *
 * A wrapper of #set_client_encoding.
 * defined in Ruby 1.9 or later.
 *
 * +value+ can be one of:
 * * an Encoding
 * * a String - a name of Encoding
 * * +nil+ - sets the client_encoding to SQL_ASCII.
 */
static VALUE
pgconn_internal_encoding_set(VALUE self, VALUE enc)
{
	if (NIL_P(enc)) {
		pgconn_set_client_encoding( self, rb_usascii_str_new_cstr("SQL_ASCII") );
		return enc;
	}
	else if ( TYPE(enc) == T_STRING && strcasecmp("JOHAB", RSTRING_PTR(enc)) == 0 ) {
		pgconn_set_client_encoding(self, rb_usascii_str_new_cstr("JOHAB"));
		return enc;
	}
	else {
		rb_encoding *rbenc = rb_to_encoding( enc );
		const char *name = pg_get_rb_encoding_as_pg_encoding( rbenc );

		if ( PQsetClientEncoding(pg_get_pgconn( self ), name) == -1 ) {
			VALUE server_encoding = pgconn_external_encoding( self );
			rb_raise( rb_eEncCompatError, "incompatible character encodings: %s and %s",
					  rb_enc_name(rb_to_encoding(server_encoding)), name );
		}
		return enc;
	}

	rb_raise( rb_ePGerror, "unknown encoding: %s", RSTRING_PTR(rb_inspect(enc)) );

	return Qnil;
}



/*
 * call-seq:
 *   conn.external_encoding() -> Encoding
 *
 * Return the +server_encoding+ of the connected database as a Ruby Encoding object.
 * The <tt>SQL_ASCII</tt> encoding is mapped to to <tt>ASCII_8BIT</tt>.
 */
static VALUE
pgconn_external_encoding(VALUE self)
{
	PGconn *conn = pg_get_pgconn( self );
	VALUE encoding = rb_iv_get( self, "@external_encoding" );
	rb_encoding *enc = NULL;
	const char *pg_encname = NULL;

	/* Use cached value if found */
	if ( RTEST(encoding) ) return encoding;

	pg_encname = PQparameterStatus( conn, "server_encoding" );
	enc = pg_get_pg_encname_as_rb_encoding( pg_encname );
	encoding = rb_enc_from_encoding( enc );

	rb_iv_set( self, "@external_encoding", encoding );

	return encoding;
}



/*
 * call-seq:
 *   conn.set_default_encoding() -> Encoding
 *
 * If Ruby has its Encoding.default_internal set, set PostgreSQL's client_encoding
 * to match. Returns the new Encoding, or +nil+ if the default internal encoding
 * wasn't set.
 */
static VALUE
pgconn_set_default_encoding( VALUE self )
{
	PGconn *conn = pg_get_pgconn( self );
	rb_encoding *enc;
	const char *encname;

	if (( enc = rb_default_internal_encoding() )) {
		encname = pg_get_rb_encoding_as_pg_encoding( enc );
		if ( PQsetClientEncoding(conn, encname) != 0 )
			rb_warn( "Failed to set the default_internal encoding to %s: '%s'",
			         encname, PQerrorMessage(conn) );
		return rb_enc_from_encoding( enc );
	} else {
		return Qnil;
	}
}


#endif /* M17N_SUPPORTED */



void
init_pg_connection()
{
	rb_cPGconn = rb_define_class_under( rb_mPG, "Connection", rb_cObject );
	rb_include_module(rb_cPGconn, rb_mPGconstants);

	/******     PG::Connection CLASS METHODS     ******/
	rb_define_alloc_func( rb_cPGconn, pgconn_s_allocate );

	SINGLETON_ALIAS(rb_cPGconn, "connect", "new");
	SINGLETON_ALIAS(rb_cPGconn, "open", "new");
	SINGLETON_ALIAS(rb_cPGconn, "setdb", "new");
	SINGLETON_ALIAS(rb_cPGconn, "setdblogin", "new");
	rb_define_singleton_method(rb_cPGconn, "escape_string", pgconn_s_escape, 1);
	SINGLETON_ALIAS(rb_cPGconn, "escape", "escape_string");
	rb_define_singleton_method(rb_cPGconn, "escape_bytea", pgconn_s_escape_bytea, 1);
	rb_define_singleton_method(rb_cPGconn, "unescape_bytea", pgconn_s_unescape_bytea, 1);
	rb_define_singleton_method(rb_cPGconn, "encrypt_password", pgconn_s_encrypt_password, 2);
	rb_define_singleton_method(rb_cPGconn, "quote_ident", pgconn_s_quote_ident, 1);
	rb_define_singleton_method(rb_cPGconn, "connect_start", pgconn_s_connect_start, -1);
	rb_define_singleton_method(rb_cPGconn, "conndefaults", pgconn_s_conndefaults, 0);
#ifdef HAVE_PQPING
	rb_define_singleton_method(rb_cPGconn, "ping", pgconn_s_ping, -1);
#endif

	/******     PG::Connection INSTANCE METHODS: Connection Control     ******/
	rb_define_method(rb_cPGconn, "initialize", pgconn_init, -1);
	rb_define_method(rb_cPGconn, "connect_poll", pgconn_connect_poll, 0);
	rb_define_method(rb_cPGconn, "finish", pgconn_finish, 0);
	rb_define_method(rb_cPGconn, "finished?", pgconn_finished_p, 0);
	rb_define_method(rb_cPGconn, "reset", pgconn_reset, 0);
	rb_define_method(rb_cPGconn, "reset_start", pgconn_reset_start, 0);
	rb_define_method(rb_cPGconn, "reset_poll", pgconn_reset_poll, 0);
	rb_define_method(rb_cPGconn, "conndefaults", pgconn_s_conndefaults, 0);
	rb_define_alias(rb_cPGconn, "close", "finish");

	/******     PG::Connection INSTANCE METHODS: Connection Status     ******/
	rb_define_method(rb_cPGconn, "db", pgconn_db, 0);
	rb_define_method(rb_cPGconn, "user", pgconn_user, 0);
	rb_define_method(rb_cPGconn, "pass", pgconn_pass, 0);
	rb_define_method(rb_cPGconn, "host", pgconn_host, 0);
	rb_define_method(rb_cPGconn, "port", pgconn_port, 0);
	rb_define_method(rb_cPGconn, "tty", pgconn_tty, 0);
	rb_define_method(rb_cPGconn, "options", pgconn_options, 0);
	rb_define_method(rb_cPGconn, "status", pgconn_status, 0);
	rb_define_method(rb_cPGconn, "transaction_status", pgconn_transaction_status, 0);
	rb_define_method(rb_cPGconn, "parameter_status", pgconn_parameter_status, 1);
	rb_define_method(rb_cPGconn, "protocol_version", pgconn_protocol_version, 0);
	rb_define_method(rb_cPGconn, "server_version", pgconn_server_version, 0);
	rb_define_method(rb_cPGconn, "error_message", pgconn_error_message, 0);
	rb_define_method(rb_cPGconn, "socket", pgconn_socket, 0);
#if !defined(_WIN32) || defined(HAVE_RB_W32_WRAP_IO_HANDLE)
	rb_define_method(rb_cPGconn, "socket_io", pgconn_socket_io, 0);
#endif
	rb_define_method(rb_cPGconn, "backend_pid", pgconn_backend_pid, 0);
	rb_define_method(rb_cPGconn, "connection_needs_password", pgconn_connection_needs_password, 0);
	rb_define_method(rb_cPGconn, "connection_used_password", pgconn_connection_used_password, 0);
	/* rb_define_method(rb_cPGconn, "getssl", pgconn_getssl, 0); */

	/******     PG::Connection INSTANCE METHODS: Command Execution     ******/
	rb_define_method(rb_cPGconn, "exec", pgconn_exec, -1);
	rb_define_alias(rb_cPGconn, "query", "exec");
	rb_define_method(rb_cPGconn, "exec_params", pgconn_exec_params, -1);
	rb_define_method(rb_cPGconn, "prepare", pgconn_prepare, -1);
	rb_define_method(rb_cPGconn, "exec_prepared", pgconn_exec_prepared, -1);
	rb_define_method(rb_cPGconn, "describe_prepared", pgconn_describe_prepared, 1);
	rb_define_method(rb_cPGconn, "describe_portal", pgconn_describe_portal, 1);
	rb_define_method(rb_cPGconn, "make_empty_pgresult", pgconn_make_empty_pgresult, 1);
	rb_define_method(rb_cPGconn, "escape_string", pgconn_s_escape, 1);
	rb_define_alias(rb_cPGconn, "escape", "escape_string");
#ifdef HAVE_PQESCAPELITERAL
	rb_define_method(rb_cPGconn, "escape_literal", pgconn_escape_literal, 1);
#endif
#ifdef HAVE_PQESCAPEIDENTIFIER
	rb_define_method(rb_cPGconn, "escape_identifier", pgconn_escape_identifier, 1);
#endif
	rb_define_method(rb_cPGconn, "escape_bytea", pgconn_s_escape_bytea, 1);
	rb_define_method(rb_cPGconn, "unescape_bytea", pgconn_s_unescape_bytea, 1);
#ifdef HAVE_PQSETSINGLEROWMODE
	rb_define_method(rb_cPGconn, "set_single_row_mode", pgconn_set_single_row_mode, 0);
#endif

	/******     PG::Connection INSTANCE METHODS: Asynchronous Command Processing     ******/
	rb_define_method(rb_cPGconn, "send_query", pgconn_send_query, -1);
	rb_define_method(rb_cPGconn, "send_prepare", pgconn_send_prepare, -1);
	rb_define_method(rb_cPGconn, "send_query_prepared", pgconn_send_query_prepared, -1);
	rb_define_method(rb_cPGconn, "send_describe_prepared", pgconn_send_describe_prepared, 1);
	rb_define_method(rb_cPGconn, "send_describe_portal", pgconn_send_describe_portal, 1);
	rb_define_method(rb_cPGconn, "get_result", pgconn_get_result, 0);
	rb_define_method(rb_cPGconn, "consume_input", pgconn_consume_input, 0);
	rb_define_method(rb_cPGconn, "is_busy", pgconn_is_busy, 0);
	rb_define_method(rb_cPGconn, "setnonblocking", pgconn_setnonblocking, 1);
	rb_define_method(rb_cPGconn, "isnonblocking", pgconn_isnonblocking, 0);
	rb_define_alias(rb_cPGconn, "nonblocking?", "isnonblocking");
	rb_define_method(rb_cPGconn, "flush", pgconn_flush, 0);

	/******     PG::Connection INSTANCE METHODS: Cancelling Queries in Progress     ******/
	rb_define_method(rb_cPGconn, "cancel", pgconn_cancel, 0);

	/******     PG::Connection INSTANCE METHODS: NOTIFY     ******/
	rb_define_method(rb_cPGconn, "notifies", pgconn_notifies, 0);

	/******     PG::Connection INSTANCE METHODS: COPY     ******/
	rb_define_method(rb_cPGconn, "put_copy_data", pgconn_put_copy_data, 1);
	rb_define_method(rb_cPGconn, "put_copy_end", pgconn_put_copy_end, -1);
	rb_define_method(rb_cPGconn, "get_copy_data", pgconn_get_copy_data, -1);

	/******     PG::Connection INSTANCE METHODS: Control Functions     ******/
	rb_define_method(rb_cPGconn, "set_error_verbosity", pgconn_set_error_verbosity, 1);
	rb_define_method(rb_cPGconn, "trace", pgconn_trace, 1);
	rb_define_method(rb_cPGconn, "untrace", pgconn_untrace, 0);

	/******     PG::Connection INSTANCE METHODS: Notice Processing     ******/
	rb_define_method(rb_cPGconn, "set_notice_receiver", pgconn_set_notice_receiver, 0);
	rb_define_method(rb_cPGconn, "set_notice_processor", pgconn_set_notice_processor, 0);

	/******     PG::Connection INSTANCE METHODS: Other    ******/
	rb_define_method(rb_cPGconn, "get_client_encoding", pgconn_get_client_encoding, 0);
	rb_define_method(rb_cPGconn, "set_client_encoding", pgconn_set_client_encoding, 1);
	rb_define_alias(rb_cPGconn, "client_encoding=", "set_client_encoding");
	rb_define_method(rb_cPGconn, "transaction", pgconn_transaction, 0);
	rb_define_method(rb_cPGconn, "block", pgconn_block, -1);
	rb_define_method(rb_cPGconn, "wait_for_notify", pgconn_wait_for_notify, -1);
	rb_define_alias(rb_cPGconn, "notifies_wait", "wait_for_notify");
	rb_define_method(rb_cPGconn, "quote_ident", pgconn_s_quote_ident, 1);
#if defined(HAVE_RB_THREAD_CALL_WITHOUT_GVL)
	rb_define_alias(rb_cPGconn, "async_exec", "exec");
#else
	rb_define_method(rb_cPGconn, "async_exec", pgconn_async_exec, -1);
#endif
	rb_define_alias(rb_cPGconn, "async_query", "async_exec");
	rb_define_method(rb_cPGconn, "get_last_result", pgconn_get_last_result, 0);

	/******     PG::Connection INSTANCE METHODS: Large Object Support     ******/
	rb_define_method(rb_cPGconn, "lo_creat", pgconn_locreat, -1);
	rb_define_alias(rb_cPGconn, "locreat", "lo_creat");
	rb_define_method(rb_cPGconn, "lo_create", pgconn_locreate, 1);
	rb_define_alias(rb_cPGconn, "locreate", "lo_create");
	rb_define_method(rb_cPGconn, "lo_import", pgconn_loimport, 1);
	rb_define_alias(rb_cPGconn, "loimport", "lo_import");
	rb_define_method(rb_cPGconn, "lo_export", pgconn_loexport, 2);
	rb_define_alias(rb_cPGconn, "loexport", "lo_export");
	rb_define_method(rb_cPGconn, "lo_open", pgconn_loopen, -1);
	rb_define_alias(rb_cPGconn, "loopen", "lo_open");
	rb_define_method(rb_cPGconn, "lo_write",pgconn_lowrite, 2);
	rb_define_alias(rb_cPGconn, "lowrite", "lo_write");
	rb_define_method(rb_cPGconn, "lo_read",pgconn_loread, 2);
	rb_define_alias(rb_cPGconn, "loread", "lo_read");
	rb_define_method(rb_cPGconn, "lo_lseek",pgconn_lolseek, 3);
	rb_define_alias(rb_cPGconn, "lolseek", "lo_lseek");
	rb_define_alias(rb_cPGconn, "lo_seek", "lo_lseek");
	rb_define_alias(rb_cPGconn, "loseek", "lo_lseek");
	rb_define_method(rb_cPGconn, "lo_tell",pgconn_lotell, 1);
	rb_define_alias(rb_cPGconn, "lotell", "lo_tell");
	rb_define_method(rb_cPGconn, "lo_truncate", pgconn_lotruncate, 2);
	rb_define_alias(rb_cPGconn, "lotruncate", "lo_truncate");
	rb_define_method(rb_cPGconn, "lo_close",pgconn_loclose, 1);
	rb_define_alias(rb_cPGconn, "loclose", "lo_close");
	rb_define_method(rb_cPGconn, "lo_unlink", pgconn_lounlink, 1);
	rb_define_alias(rb_cPGconn, "lounlink", "lo_unlink");

#ifdef M17N_SUPPORTED
	rb_define_method(rb_cPGconn, "internal_encoding", pgconn_internal_encoding, 0);
	rb_define_method(rb_cPGconn, "internal_encoding=", pgconn_internal_encoding_set, 1);
	rb_define_method(rb_cPGconn, "external_encoding", pgconn_external_encoding, 0);
	rb_define_method(rb_cPGconn, "set_default_encoding", pgconn_set_default_encoding, 0);
#endif /* M17N_SUPPORTED */

}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.