PHP /ext/interbase/ibase_query.c

Language C Lines 2108
MD5 Hash 9d08e89be8e8e666f12a31bddea3dcb0 Estimated Cost $44,808 (why?)
Repository git://github.com/infusion/PHP.git View Raw File View Project SPDX
   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
/*
   +----------------------------------------------------------------------+
   | PHP Version 5                                                        |
   +----------------------------------------------------------------------+
   | Copyright (c) 1997-2011 The PHP Group                                |
   +----------------------------------------------------------------------+
   | This source file is subject to version 3.01 of the PHP license,      |
   | that is bundled with this package in the file LICENSE, and is        |
   | available through the world-wide-web at the following url:           |
   | http://www.php.net/license/3_01.txt                                  |
   | If you did not receive a copy of the PHP license and are unable to   |
   | obtain it through the world-wide-web, please send a note to          |
   | license@php.net so we can mail you a copy immediately.               |
   +----------------------------------------------------------------------+
   | Authors: Ard Biesheuvel <a.k.biesheuvel@its.tudelft.nl>              |
   +----------------------------------------------------------------------+
 */

/* $Id: ibase_query.c 306939 2011-01-01 02:19:59Z felipe $ */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "php.h"
#include "php_ini.h"

#if HAVE_IBASE

#include "ext/standard/php_standard.h"
#include "php_interbase.h"
#include "php_ibase_includes.h"

#define ISC_LONG_MIN 	INT_MIN
#define ISC_LONG_MAX 	INT_MAX

#define QUERY_RESULT	1
#define EXECUTE_RESULT	2

#define FETCH_ROW		1
#define FETCH_ARRAY		2

typedef struct {
	ISC_ARRAY_DESC ar_desc;
	ISC_LONG ar_size; /* size of entire array in bytes */
	unsigned short el_type, el_size;
} ibase_array;

typedef struct {
	ibase_db_link *link;
	ibase_trans *trans;
	struct _ib_query *query;
	isc_stmt_handle stmt;
	unsigned short type;
	unsigned char has_more_rows, statement_type;
	XSQLDA *out_sqlda;
	ibase_array out_array[1]; /* last member */
} ibase_result;

typedef struct _ib_query {
	ibase_db_link *link;
	ibase_trans *trans;
	ibase_result *result;
	int result_res_id;
	isc_stmt_handle stmt;
	XSQLDA *in_sqlda, *out_sqlda;
	ibase_array *in_array, *out_array;
	unsigned short in_array_cnt, out_array_cnt;
	unsigned short dialect;
	char statement_type;
	char *query;
	long trans_res_id;
} ibase_query;

typedef struct {
	unsigned short vary_length;
	char vary_string[1];
} IBVARY;

/* sql variables union 
 * used for convert and binding input variables
 */
typedef struct {
	union {
		short sval;
		float fval;
		ISC_LONG lval;
		ISC_QUAD qval;
		ISC_TIMESTAMP tsval;
		ISC_DATE dtval;
		ISC_TIME tmval;
	} val;
	short sqlind;
} BIND_BUF;

static int le_result, le_query;

#define LE_RESULT "Firebird/InterBase result"
#define LE_QUERY "Firebird/InterBase query"

static void _php_ibase_free_xsqlda(XSQLDA *sqlda) /* {{{ */
{
	int i;
	XSQLVAR *var;

	IBDEBUG("Free XSQLDA?");
	if (sqlda) {
		IBDEBUG("Freeing XSQLDA...");
		var = sqlda->sqlvar;
		for (i = 0; i < sqlda->sqld; i++, var++) {
			efree(var->sqldata);
			if (var->sqlind) {
				efree(var->sqlind);
			}
		}
		efree(sqlda);
	}
}
/* }}} */

static void _php_ibase_free_stmt_handle(ibase_db_link *link, isc_stmt_handle stmt TSRMLS_DC) /* {{{ */
{
	static char info[] = { isc_info_base_level, isc_info_end };

	if (stmt) {
		char res_buf[8];
		IBDEBUG("Dropping statement handle (free_stmt_handle)...");
		/* Only free statement if db-connection is still open */
		if (SUCCESS == isc_database_info(IB_STATUS, &link->handle, 
							sizeof(info), info, sizeof(res_buf), res_buf)) {
			if (isc_dsql_free_statement(IB_STATUS, &stmt, DSQL_drop)) {
				_php_ibase_error(TSRMLS_C);
			}
		}
	}
}
/* }}} */

static void _php_ibase_free_result(zend_rsrc_list_entry *rsrc TSRMLS_DC) /* {{{ */
{
	ibase_result *ib_result = (ibase_result *) rsrc->ptr;

	IBDEBUG("Freeing result by dtor...");
	if (ib_result) {
		_php_ibase_free_xsqlda(ib_result->out_sqlda);
		if (ib_result->query != NULL) {
			IBDEBUG("query still valid; don't drop statement handle");
			ib_result->query->result = NULL;	/* Indicate to query, that result is released */
		} else {
			_php_ibase_free_stmt_handle(ib_result->link, ib_result->stmt TSRMLS_CC);
		}
		efree(ib_result);
	}
}
/* }}} */

static void _php_ibase_free_query(ibase_query *ib_query TSRMLS_DC) /* {{{ */
{
	IBDEBUG("Freeing query...");

	if (ib_query->in_sqlda) {
		efree(ib_query->in_sqlda);
	}
	if (ib_query->out_sqlda) {
		efree(ib_query->out_sqlda);
	}
	if (ib_query->result != NULL) {
		IBDEBUG("result still valid; don't drop statement handle");
		ib_query->result->query = NULL;	/* Indicate to result, that query is released */
	} else {
		_php_ibase_free_stmt_handle(ib_query->link, ib_query->stmt TSRMLS_CC);
	}
	if (ib_query->in_array) {
		efree(ib_query->in_array);
	}
	if (ib_query->out_array) {
		efree(ib_query->out_array);
	}
	if (ib_query->query) {
		efree(ib_query->query);
	}
}
/* }}} */

static void php_ibase_free_query_rsrc(zend_rsrc_list_entry *rsrc TSRMLS_DC) /* {{{ */
{
	ibase_query *ib_query = (ibase_query *)rsrc->ptr;

	if (ib_query != NULL) {
		IBDEBUG("Preparing to free query by dtor...");
		_php_ibase_free_query(ib_query TSRMLS_CC);
		efree(ib_query);
	}
}
/* }}} */

void php_ibase_query_minit(INIT_FUNC_ARGS) /* {{{ */
{
	le_result = zend_register_list_destructors_ex(_php_ibase_free_result, NULL, 
	    "interbase result", module_number);
	le_query = zend_register_list_destructors_ex(php_ibase_free_query_rsrc, NULL, 
	    "interbase query", module_number);
}
/* }}} */

static int _php_ibase_alloc_array(ibase_array **ib_arrayp, XSQLDA *sqlda, /* {{{ */
	isc_db_handle link, isc_tr_handle trans, unsigned short *array_cnt TSRMLS_DC)
{
	unsigned short i, n;
	ibase_array *ar;

	/* first check if we have any arrays at all */
	for (i = *array_cnt = 0; i < sqlda->sqld; ++i) {
		if ((sqlda->sqlvar[i].sqltype & ~1) == SQL_ARRAY) {
			++*array_cnt;
		}
	}
	if (! *array_cnt) return SUCCESS;

	ar = safe_emalloc(sizeof(ibase_array), *array_cnt, 0);

	for (i = n = 0; i < sqlda->sqld; ++i) {
		unsigned short dim;
		unsigned long ar_size = 1;
		XSQLVAR *var = &sqlda->sqlvar[i];

		if ((var->sqltype & ~1) == SQL_ARRAY) {
			ibase_array *a = &ar[n++];
			ISC_ARRAY_DESC *ar_desc = &a->ar_desc;

			if (isc_array_lookup_bounds(IB_STATUS, &link, &trans, var->relname,
					var->sqlname, ar_desc)) {
				_php_ibase_error(TSRMLS_C);
				efree(ar);
				return FAILURE;
			}

			switch (ar_desc->array_desc_dtype) {
				case blr_text:
				case blr_text2:
					a->el_type = SQL_TEXT;
					a->el_size = ar_desc->array_desc_length;
					break;
				case blr_short:
					a->el_type = SQL_SHORT;
					a->el_size = sizeof(short);
					break;
				case blr_long:
					a->el_type = SQL_LONG;
					a->el_size = sizeof(ISC_LONG);
					break;
				case blr_float:
					a->el_type = SQL_FLOAT;
					a->el_size = sizeof(float);
					break;
				case blr_double:
					a->el_type = SQL_DOUBLE;
					a->el_size = sizeof(double);
					break;
				case blr_int64:
					a->el_type = SQL_INT64;
					a->el_size = sizeof(ISC_INT64);
					break;
				case blr_timestamp:
					a->el_type = SQL_TIMESTAMP;
					a->el_size = sizeof(ISC_TIMESTAMP);
					break;
				case blr_sql_date:
					a->el_type = SQL_TYPE_DATE;
					a->el_size = sizeof(ISC_DATE);
					break;
				case blr_sql_time:
					a->el_type = SQL_TYPE_TIME;
					a->el_size = sizeof(ISC_TIME);
					break;
				case blr_varying:
				case blr_varying2:
					/**
					 * IB has a strange way of handling VARCHAR arrays. It doesn't store
					 * the length in the first short, as with VARCHAR fields. It does, 
					 * however, expect the extra short to be allocated for each element.
					 */
					a->el_type = SQL_TEXT;
					a->el_size = ar_desc->array_desc_length + sizeof(short);
					break;
				case blr_quad:
				case blr_blob_id:
				case blr_cstring:
				case blr_cstring2:
					/**
					 * These types are mentioned as array types in the manual, but I 
					 * wouldn't know how to create an array field with any of these
					 * types. I assume these types are not applicable to arrays, and
					 * were mentioned erroneously.
					 */
				default:
					_php_ibase_module_error("Unsupported array type %d in relation '%s' column '%s'"
						TSRMLS_CC, ar_desc->array_desc_dtype, var->relname, var->sqlname);
					efree(ar);
					return FAILURE;
			} /* switch array_desc_type */

			/* calculate elements count */
			for (dim = 0; dim < ar_desc->array_desc_dimensions; dim++) {
				ar_size *= 1 + ar_desc->array_desc_bounds[dim].array_bound_upper
					-ar_desc->array_desc_bounds[dim].array_bound_lower;
			}
			a->ar_size = a->el_size * ar_size;
		} /* if SQL_ARRAY */
	} /* for column */
	*ib_arrayp = ar;
	return SUCCESS;
}
/* }}} */

/* allocate and prepare query */
static int _php_ibase_alloc_query(ibase_query *ib_query, ibase_db_link *link, /* {{{ */
	ibase_trans *trans, char *query, unsigned short dialect, int trans_res_id TSRMLS_DC)
{
	static char info_type[] = {isc_info_sql_stmt_type};
	char result[8];

	/* Return FAILURE, if querystring is empty */
	if (*query == '\0') {
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Querystring empty.");
		return FAILURE;
	}

	ib_query->link = link;
	ib_query->trans = trans;
	ib_query->result_res_id = 0;
	ib_query->result = NULL;
	ib_query->stmt = NULL;
	ib_query->in_array = NULL;
	ib_query->out_array = NULL;
	ib_query->dialect = dialect;
	ib_query->query = estrdup(query);
	ib_query->trans_res_id = trans_res_id;
	ib_query->out_sqlda = NULL;
	ib_query->in_sqlda = NULL;

	if (isc_dsql_allocate_statement(IB_STATUS, &link->handle, &ib_query->stmt)) {
		_php_ibase_error(TSRMLS_C);
		goto _php_ibase_alloc_query_error;
	}

	ib_query->out_sqlda = (XSQLDA *) emalloc(XSQLDA_LENGTH(1));
	ib_query->out_sqlda->sqln = 1;
	ib_query->out_sqlda->version = SQLDA_CURRENT_VERSION;

	if (isc_dsql_prepare(IB_STATUS, &ib_query->trans->handle, &ib_query->stmt,
			0, query, dialect, ib_query->out_sqlda)) {
		_php_ibase_error(TSRMLS_C);
		goto _php_ibase_alloc_query_error;
	}

	/* find out what kind of statement was prepared */
	if (isc_dsql_sql_info(IB_STATUS, &ib_query->stmt, sizeof(info_type), 
			info_type, sizeof(result), result)) {
		_php_ibase_error(TSRMLS_C);
		goto _php_ibase_alloc_query_error;
	}
	ib_query->statement_type = result[3];	

	/* not enough output variables ? */
	if (ib_query->out_sqlda->sqld > ib_query->out_sqlda->sqln) {
		ib_query->out_sqlda = erealloc(ib_query->out_sqlda, XSQLDA_LENGTH(ib_query->out_sqlda->sqld));
		ib_query->out_sqlda->sqln = ib_query->out_sqlda->sqld;
		ib_query->out_sqlda->version = SQLDA_CURRENT_VERSION;
		if (isc_dsql_describe(IB_STATUS, &ib_query->stmt, SQLDA_CURRENT_VERSION, ib_query->out_sqlda)) {
			_php_ibase_error(TSRMLS_C);
			goto _php_ibase_alloc_query_error;
		}
	}

	/* maybe have input placeholders? */
	ib_query->in_sqlda = emalloc(XSQLDA_LENGTH(1));
	ib_query->in_sqlda->sqln = 1;
	ib_query->in_sqlda->version = SQLDA_CURRENT_VERSION;
	if (isc_dsql_describe_bind(IB_STATUS, &ib_query->stmt, SQLDA_CURRENT_VERSION, ib_query->in_sqlda)) {
		_php_ibase_error(TSRMLS_C);
		goto _php_ibase_alloc_query_error;
	}

	/* not enough input variables ? */
	if (ib_query->in_sqlda->sqln < ib_query->in_sqlda->sqld) {
		ib_query->in_sqlda = erealloc(ib_query->in_sqlda, XSQLDA_LENGTH(ib_query->in_sqlda->sqld));
		ib_query->in_sqlda->sqln = ib_query->in_sqlda->sqld;
		ib_query->in_sqlda->version = SQLDA_CURRENT_VERSION;

		if (isc_dsql_describe_bind(IB_STATUS, &ib_query->stmt,
				SQLDA_CURRENT_VERSION, ib_query->in_sqlda)) {
			_php_ibase_error(TSRMLS_C);
			goto _php_ibase_alloc_query_error;
		}
	}

	/* no, haven't placeholders at all */
	if (ib_query->in_sqlda->sqld == 0) {
		efree(ib_query->in_sqlda);
		ib_query->in_sqlda = NULL;
	} else if (FAILURE == _php_ibase_alloc_array(&ib_query->in_array, ib_query->in_sqlda,
			link->handle, trans->handle, &ib_query->in_array_cnt TSRMLS_CC)) {
		goto _php_ibase_alloc_query_error;
	}

	if (ib_query->out_sqlda->sqld == 0) {
		efree(ib_query->out_sqlda);
		ib_query->out_sqlda = NULL;
	} else 	if (FAILURE == _php_ibase_alloc_array(&ib_query->out_array, ib_query->out_sqlda,
			link->handle, trans->handle, &ib_query->out_array_cnt TSRMLS_CC)) {
		goto _php_ibase_alloc_query_error;
	}

	return SUCCESS;

_php_ibase_alloc_query_error:

	if (ib_query->out_sqlda) {
		efree(ib_query->out_sqlda);
	}
	if (ib_query->in_sqlda) {
		efree(ib_query->in_sqlda);
	}
	if (ib_query->out_array) {
		efree(ib_query->out_array);
	}
	if (ib_query->query) {
		efree(ib_query->query);
	}
	return FAILURE;
}
/* }}} */

static int _php_ibase_bind_array(zval *val, char *buf, unsigned long buf_size, /* {{{ */
	ibase_array *array, int dim TSRMLS_DC)
{
	zval null_val, *pnull_val = &null_val;
	int u_bound = array->ar_desc.array_desc_bounds[dim].array_bound_upper,
		l_bound = array->ar_desc.array_desc_bounds[dim].array_bound_lower,
		dim_len = 1 + u_bound - l_bound;

	ZVAL_NULL(pnull_val);

	if (dim < array->ar_desc.array_desc_dimensions) {
		unsigned long slice_size = buf_size / dim_len;
		unsigned short i;
		zval **subval = &val;

		if (Z_TYPE_P(val) == IS_ARRAY) {
			zend_hash_internal_pointer_reset(Z_ARRVAL_P(val));
		}

		for (i = 0; i < dim_len; ++i) { 

			if (Z_TYPE_P(val) == IS_ARRAY &&
				zend_hash_get_current_data(Z_ARRVAL_P(val), (void *) &subval) == FAILURE)
			{
				subval = &pnull_val;
			}

			if (_php_ibase_bind_array(*subval, buf, slice_size, array, dim+1 TSRMLS_CC) == FAILURE)
			{
				return FAILURE;
			}
			buf += slice_size;

			if (Z_TYPE_P(val) == IS_ARRAY) {
				zend_hash_move_forward(Z_ARRVAL_P(val));
			}
		}

		if (Z_TYPE_P(val) == IS_ARRAY) {
			zend_hash_internal_pointer_reset(Z_ARRVAL_P(val));
		}

	} else {
		/* expect a single value */
		if (Z_TYPE_P(val) == IS_NULL) {
			memset(buf, 0, buf_size);
		} else if (array->ar_desc.array_desc_scale < 0) {

			/* no coercion for array types */
			double l;

			convert_to_double(val);

			if (Z_DVAL_P(val) > 0) {
				l = Z_DVAL_P(val) * pow(10, -array->ar_desc.array_desc_scale) + .5;
			} else {
				l = Z_DVAL_P(val) * pow(10, -array->ar_desc.array_desc_scale) - .5;
			}

			switch (array->el_type) {
				case SQL_SHORT:
					if (l > SHRT_MAX || l < SHRT_MIN) {
						_php_ibase_module_error("Array parameter exceeds field width" TSRMLS_CC);
						return FAILURE;
					}
					*(short*) buf = (short) l;
					break;
				case SQL_LONG:
					if (l > ISC_LONG_MAX || l < ISC_LONG_MIN) {
						_php_ibase_module_error("Array parameter exceeds field width" TSRMLS_CC);
						return FAILURE;
					}
					*(ISC_LONG*) buf = (ISC_LONG) l;
					break;
				case SQL_INT64:
					{
						long double l;

						convert_to_string(val);

						if (!sscanf(Z_STRVAL_P(val), "%Lf", &l)) {
							_php_ibase_module_error("Cannot convert '%s' to long double"
								TSRMLS_CC, Z_STRVAL_P(val));
							return FAILURE;
						}

						if (l > 0) {
							*(ISC_INT64 *) buf = (ISC_INT64) (l * pow(10, 
								-array->ar_desc.array_desc_scale) + .5);
						} else {
							*(ISC_INT64 *) buf = (ISC_INT64) (l * pow(10, 
								-array->ar_desc.array_desc_scale) - .5);
						}
					}
					break;
			}			
		} else {
			struct tm t = { 0, 0, 0, 0, 0, 0 };

			switch (array->el_type) {
				unsigned short n;
				ISC_INT64 l;

				case SQL_SHORT:
					convert_to_long(val);
					if (Z_LVAL_P(val) > SHRT_MAX || Z_LVAL_P(val) < SHRT_MIN) {
						_php_ibase_module_error("Array parameter exceeds field width" TSRMLS_CC);
						return FAILURE;
					}
					*(short *) buf = (short) Z_LVAL_P(val);
					break;
				case SQL_LONG:
					convert_to_long(val);
#if (SIZEOF_LONG > 4)
					if (Z_LVAL_P(val) > ISC_LONG_MAX || Z_LVAL_P(val) < ISC_LONG_MIN) {
						_php_ibase_module_error("Array parameter exceeds field width" TSRMLS_CC);
						return FAILURE;
					}
#endif
					*(ISC_LONG *) buf = (ISC_LONG) Z_LVAL_P(val);
					break;
				case SQL_INT64:
#if (SIZEOF_LONG >= 8)
					convert_to_long(val);
					*(long *) buf = Z_LVAL_P(val);
#else
					convert_to_string(val);
					if (!sscanf(Z_STRVAL_P(val), "%" LL_MASK "d", &l)) {
						_php_ibase_module_error("Cannot convert '%s' to long integer"
							TSRMLS_CC, Z_STRVAL_P(val));
						return FAILURE;
					} else {
						*(ISC_INT64 *) buf = l;
					}
#endif
					break;
				case SQL_FLOAT:
					convert_to_double(val);
					*(float*) buf = (float) Z_DVAL_P(val);
					break;
				case SQL_DOUBLE:
					convert_to_double(val);
					*(double*) buf = Z_DVAL_P(val);
					break;
				case SQL_TIMESTAMP:
					convert_to_string(val);
#ifdef HAVE_STRPTIME
					strptime(Z_STRVAL_P(val), INI_STR("ibase.timestampformat"), &t);
#else
					n = sscanf(Z_STRVAL_P(val), "%d%*[/]%d%*[/]%d %d%*[:]%d%*[:]%d", 
						&t.tm_mon, &t.tm_mday, &t.tm_year, &t.tm_hour, &t.tm_min, &t.tm_sec);

					if (n != 3 && n != 6) {
						_php_ibase_module_error("Invalid date/time format (expected 3 or 6 fields, got %d."
							" Use format 'm/d/Y H:i:s'. You gave '%s')" TSRMLS_CC, n, Z_STRVAL_P(val));
						return FAILURE;
					}
					t.tm_year -= 1900;
					t.tm_mon--;
#endif
					isc_encode_timestamp(&t, (ISC_TIMESTAMP * ) buf);
					break;
				case SQL_TYPE_DATE:
					convert_to_string(val);
#ifdef HAVE_STRPTIME
					strptime(Z_STRVAL_P(val), INI_STR("ibase.dateformat"), &t);
#else
					n = sscanf(Z_STRVAL_P(val), "%d%*[/]%d%*[/]%d", &t.tm_mon, &t.tm_mday, &t.tm_year);

					if (n != 3) {
						_php_ibase_module_error("Invalid date format (expected 3 fields, got %d. "
							"Use format 'm/d/Y' You gave '%s')" TSRMLS_CC, n, Z_STRVAL_P(val));
						return FAILURE;
					}
					t.tm_year -= 1900;
					t.tm_mon--;
#endif
					isc_encode_sql_date(&t, (ISC_DATE *) buf);
					break;
				case SQL_TYPE_TIME:
					convert_to_string(val);
#ifdef HAVE_STRPTIME
					strptime(Z_STRVAL_P(val), INI_STR("ibase.timeformat"), &t);
#else
					n = sscanf(Z_STRVAL_P(val), "%d%*[:]%d%*[:]%d", &t.tm_hour, &t.tm_min, &t.tm_sec);

					if (n != 3) {
						_php_ibase_module_error("Invalid time format (expected 3 fields, got %d. "
							"Use format 'H:i:s'. You gave '%s')" TSRMLS_CC, n, Z_STRVAL_P(val));
						return FAILURE;
					}
#endif
					isc_encode_sql_time(&t, (ISC_TIME *) buf);
					break;
				default:
					convert_to_string(val);
					strlcpy(buf, Z_STRVAL_P(val), buf_size);
			}
		}
	}
	return SUCCESS;
}		
/* }}} */

static int _php_ibase_bind(XSQLDA *sqlda, zval ***b_vars, BIND_BUF *buf, /* {{{ */
	ibase_query *ib_query TSRMLS_DC)
{
	int i, array_cnt = 0, rv = SUCCESS;

	for (i = 0; i < sqlda->sqld; ++i) { /* bound vars */

		zval *b_var = *b_vars[i];
		XSQLVAR *var = &sqlda->sqlvar[i];

		var->sqlind = &buf[i].sqlind;

		/* check if a NULL should be inserted */
		switch (Z_TYPE_P(b_var)) {
			int force_null;

			case IS_STRING:

				force_null = 0;

				/* for these types, an empty string can be handled like a NULL value */
				switch (var->sqltype & ~1) {
					case SQL_SHORT:
					case SQL_LONG:
					case SQL_INT64:
					case SQL_FLOAT:
					case SQL_DOUBLE:
					case SQL_TIMESTAMP:
					case SQL_TYPE_DATE:
					case SQL_TYPE_TIME:
						force_null = (Z_STRLEN_P(b_var) == 0);
				}

				if (! force_null) break;

			case IS_NULL:

				/* complain if this field doesn't allow NULL values */
				if (! (var->sqltype & 1)) {
					_php_ibase_module_error("Parameter %d: non-empty value required" TSRMLS_CC, i+1);
					rv = FAILURE;
				} else {
					buf[i].sqlind = -1;
				}

				if (var->sqltype & SQL_ARRAY) ++array_cnt;

				continue;
		}

		/* if we make it to this point, we must provide a value for the parameter */

		buf[i].sqlind = 0;

		var->sqldata = (void*)&buf[i].val;

		switch (var->sqltype & ~1) {
			struct tm t;

			case SQL_TIMESTAMP:
			case SQL_TYPE_DATE:
			case SQL_TYPE_TIME:
				if (Z_TYPE_P(b_var) == IS_LONG) {
					struct tm *res;
					res = php_gmtime_r(&Z_LVAL_P(b_var), &t);
					if (!res) {
						return FAILURE;
					}
				} else {
#ifdef HAVE_STRPTIME
					char *format = INI_STR("ibase.timestampformat");

					convert_to_string(b_var);

					switch (var->sqltype & ~1) {
						case SQL_TYPE_DATE:
							format = INI_STR("ibase.dateformat");
							break;
						case SQL_TYPE_TIME:
							format = INI_STR("ibase.timeformat");
					}
					if (!strptime(Z_STRVAL_P(b_var), format, &t)) {
						/* strptime() cannot handle it, so let IB have a try */
						break;
					}
#else /* ifndef HAVE_STRPTIME */
					break; /* let IB parse it as a string */
#endif
				}

				switch (var->sqltype & ~1) {
					default: /* == case SQL_TIMESTAMP */
						isc_encode_timestamp(&t, &buf[i].val.tsval);
						break;
					case SQL_TYPE_DATE:
						isc_encode_sql_date(&t, &buf[i].val.dtval);
						break;
					case SQL_TYPE_TIME:
						isc_encode_sql_time(&t, &buf[i].val.tmval);
						break;
				}
				continue;

			case SQL_BLOB:

				convert_to_string(b_var);

				if (Z_STRLEN_P(b_var) != BLOB_ID_LEN ||
					!_php_ibase_string_to_quad(Z_STRVAL_P(b_var), &buf[i].val.qval)) {

					ibase_blob ib_blob = { NULL, BLOB_INPUT };

					if (isc_create_blob(IB_STATUS, &ib_query->link->handle,
							&ib_query->trans->handle, &ib_blob.bl_handle, &ib_blob.bl_qd)) {
						_php_ibase_error(TSRMLS_C);
						return FAILURE;
					}

					if (_php_ibase_blob_add(&b_var, &ib_blob TSRMLS_CC) != SUCCESS) {
						return FAILURE;
					}

					if (isc_close_blob(IB_STATUS, &ib_blob.bl_handle)) {
						_php_ibase_error(TSRMLS_C);
						return FAILURE;
					}
					buf[i].val.qval = ib_blob.bl_qd;
				}
				continue;

			case SQL_ARRAY:

				if (Z_TYPE_P(b_var) != IS_ARRAY) {
					convert_to_string(b_var);

					if (Z_STRLEN_P(b_var) != BLOB_ID_LEN ||
						!_php_ibase_string_to_quad(Z_STRVAL_P(b_var), &buf[i].val.qval)) {

						_php_ibase_module_error("Parameter %d: invalid array ID" TSRMLS_CC,i+1);
						rv = FAILURE;
					}
				} else {
					/* convert the array data into something IB can understand */
					ibase_array *ar = &ib_query->in_array[array_cnt];
					void *array_data = emalloc(ar->ar_size);
					ISC_QUAD array_id = { 0, 0 };

					if (FAILURE == _php_ibase_bind_array(b_var, array_data, ar->ar_size, 
							ar, 0 TSRMLS_CC)) {
						_php_ibase_module_error("Parameter %d: failed to bind array argument"
							TSRMLS_CC,i+1);
						efree(array_data);
						rv = FAILURE;
						continue;
					}

					if (isc_array_put_slice(IB_STATUS, &ib_query->link->handle, &ib_query->trans->handle, 
							&array_id, &ar->ar_desc, array_data, &ar->ar_size)) {
						_php_ibase_error(TSRMLS_C);
						efree(array_data);
						return FAILURE;
					}
					buf[i].val.qval = array_id;
					efree(array_data);
				}				
				++array_cnt;
				continue;
			} /* switch */

			/* we end up here if none of the switch cases handled the field */
			convert_to_string(b_var);
			var->sqldata = Z_STRVAL_P(b_var);
			var->sqllen	 = Z_STRLEN_P(b_var);
			var->sqltype = SQL_TEXT;
	} /* for */
	return rv;
}
/* }}} */

static void _php_ibase_alloc_xsqlda(XSQLDA *sqlda) /* {{{ */
{
	int i;

	for (i = 0; i < sqlda->sqld; i++) {
		XSQLVAR *var = &sqlda->sqlvar[i];

		switch (var->sqltype & ~1) {
			case SQL_TEXT:
				var->sqldata = safe_emalloc(sizeof(char), var->sqllen, 0);
				break;
			case SQL_VARYING:
				var->sqldata = safe_emalloc(sizeof(char), var->sqllen + sizeof(short), 0);
				break;
			case SQL_SHORT:
				var->sqldata = emalloc(sizeof(short));
				break;
			case SQL_LONG:
				var->sqldata = emalloc(sizeof(ISC_LONG));
				break;
			case SQL_FLOAT:
				var->sqldata = emalloc(sizeof(float));
					break;
			case SQL_DOUBLE:
				var->sqldata = emalloc(sizeof(double));
				break;
			case SQL_INT64:
				var->sqldata = emalloc(sizeof(ISC_INT64));
				break;
			case SQL_TIMESTAMP:
				var->sqldata = emalloc(sizeof(ISC_TIMESTAMP));
				break;
			case SQL_TYPE_DATE:
				var->sqldata = emalloc(sizeof(ISC_DATE));
				break;
			case SQL_TYPE_TIME:
				var->sqldata = emalloc(sizeof(ISC_TIME));
				break;
			case SQL_BLOB:
			case SQL_ARRAY:
				var->sqldata = emalloc(sizeof(ISC_QUAD));
				break;
		} /* switch */

		if (var->sqltype & 1) { /* sql NULL flag */
			var->sqlind = emalloc(sizeof(short));
		} else {
			var->sqlind = NULL;
		}
	} /* for */
}
/* }}} */

static int _php_ibase_exec(INTERNAL_FUNCTION_PARAMETERS, ibase_result **ib_resultp, /* {{{ */
	ibase_query *ib_query, zval ***args)
{
	XSQLDA *in_sqlda = NULL, *out_sqlda = NULL;
	BIND_BUF *bind_buf = NULL;
	int i, rv = FAILURE;
	static char info_count[] = { isc_info_sql_records };
	char result[64];
	ISC_STATUS isc_result;
	int argc = ib_query->in_sqlda ? ib_query->in_sqlda->sqld : 0;
	
	RESET_ERRMSG;

	for (i = 0; i < argc; ++i) {
		SEPARATE_ZVAL(args[i]);
	}

	switch (ib_query->statement_type) {
		isc_tr_handle tr;
		ibase_tr_list **l;
		ibase_trans *trans;

		case isc_info_sql_stmt_start_trans:

			/* a SET TRANSACTION statement should be executed with a NULL trans handle */
			tr = NULL;

			if (isc_dsql_execute_immediate(IB_STATUS, &ib_query->link->handle, &tr, 0, 
					ib_query->query, ib_query->dialect, NULL)) {
				_php_ibase_error(TSRMLS_C);
				goto _php_ibase_exec_error;
			}

			trans = (ibase_trans *) emalloc(sizeof(ibase_trans));
			trans->handle = tr;
			trans->link_cnt = 1;
			trans->affected_rows = 0;
			trans->db_link[0] = ib_query->link;

			if (ib_query->link->tr_list == NULL) {
				ib_query->link->tr_list = (ibase_tr_list *) emalloc(sizeof(ibase_tr_list));
				ib_query->link->tr_list->trans = NULL;
				ib_query->link->tr_list->next = NULL;
			}

			/* link the transaction into the connection-transaction list */
			for (l = &ib_query->link->tr_list; *l != NULL; l = &(*l)->next);
			*l = (ibase_tr_list *) emalloc(sizeof(ibase_tr_list));
			(*l)->trans = trans;
			(*l)->next = NULL;

			ZEND_REGISTER_RESOURCE(return_value, trans, le_trans);

			return SUCCESS;

		case isc_info_sql_stmt_commit:
		case isc_info_sql_stmt_rollback:

			if (isc_dsql_execute_immediate(IB_STATUS, &ib_query->link->handle, 
					&ib_query->trans->handle, 0, ib_query->query, ib_query->dialect, NULL)) {
				_php_ibase_error(TSRMLS_C);
				goto _php_ibase_exec_error;
			}

			if (ib_query->trans->handle == NULL && ib_query->trans_res_id != 0) {
				/* transaction was released by the query and was a registered resource, 
				   so we have to release it */
				zend_list_delete(ib_query->trans_res_id);
			}

			RETVAL_TRUE;

			return SUCCESS;

		default:
			RETVAL_FALSE;
	}

	/* allocate sqlda and output buffers */
	if (ib_query->out_sqlda) { /* output variables in select, select for update */
		ibase_result *res;

		IBDEBUG("Query wants XSQLDA for output");
		res = emalloc(sizeof(ibase_result)+sizeof(ibase_array)*max(0,ib_query->out_array_cnt-1));
		res->link = ib_query->link;
		res->trans = ib_query->trans;
		res->stmt = ib_query->stmt;
		/* ib_result and ib_query point at each other to handle release of statement handle properly */
		res->query = ib_query;
		ib_query->result = res;
		res->statement_type = ib_query->statement_type;
		res->has_more_rows = 1;

		out_sqlda = res->out_sqlda = emalloc(XSQLDA_LENGTH(ib_query->out_sqlda->sqld));
		memcpy(out_sqlda, ib_query->out_sqlda, XSQLDA_LENGTH(ib_query->out_sqlda->sqld));
		_php_ibase_alloc_xsqlda(out_sqlda);

		if (ib_query->out_array) {
			memcpy(&res->out_array, ib_query->out_array, sizeof(ibase_array)*ib_query->out_array_cnt);
		}
		*ib_resultp = res;
	}

	if (ib_query->in_sqlda) { /* has placeholders */
		IBDEBUG("Query wants XSQLDA for input");
		in_sqlda = emalloc(XSQLDA_LENGTH(ib_query->in_sqlda->sqld));
		memcpy(in_sqlda, ib_query->in_sqlda, XSQLDA_LENGTH(ib_query->in_sqlda->sqld));
		bind_buf = safe_emalloc(sizeof(BIND_BUF), ib_query->in_sqlda->sqld, 0);
		if (_php_ibase_bind(in_sqlda, args, bind_buf, ib_query TSRMLS_CC) == FAILURE) {
			IBDEBUG("Could not bind input XSQLDA");
			goto _php_ibase_exec_error;
		}
	}

	if (ib_query->statement_type == isc_info_sql_stmt_exec_procedure) {
		isc_result = isc_dsql_execute2(IB_STATUS, &ib_query->trans->handle,
			&ib_query->stmt, SQLDA_CURRENT_VERSION, in_sqlda, out_sqlda);
	} else {
		isc_result = isc_dsql_execute(IB_STATUS, &ib_query->trans->handle,
			&ib_query->stmt, SQLDA_CURRENT_VERSION, in_sqlda);
	}
	if (isc_result) {
		IBDEBUG("Could not execute query");
		_php_ibase_error(TSRMLS_C);
		goto _php_ibase_exec_error;
	}
	ib_query->trans->affected_rows = 0;

	switch (ib_query->statement_type) {

		unsigned long affected_rows;

		case isc_info_sql_stmt_insert:
		case isc_info_sql_stmt_update:
		case isc_info_sql_stmt_delete:
		case isc_info_sql_stmt_exec_procedure:

			if (isc_dsql_sql_info(IB_STATUS, &ib_query->stmt, sizeof(info_count),
					info_count, sizeof(result), result)) {
				_php_ibase_error(TSRMLS_C);
				goto _php_ibase_exec_error;
			}

			affected_rows = 0;

			if (result[0] == isc_info_sql_records) {
				unsigned i = 3, result_size = isc_vax_integer(&result[1],2);

				while (result[i] != isc_info_end && i < result_size) {
					short len = (short)isc_vax_integer(&result[i+1],2);
					if (result[i] != isc_info_req_select_count) {
						affected_rows += isc_vax_integer(&result[i+3],len);
					}
					i += len+3;
				}
			}

			ib_query->trans->affected_rows = affected_rows;

			if (!ib_query->out_sqlda) { /* no result set is being returned */
				if (affected_rows) {
					RETVAL_LONG(affected_rows);
				} else {
					RETVAL_TRUE;
				}
				break;
			}
		default:
			RETVAL_TRUE;
	}

	rv = SUCCESS;

_php_ibase_exec_error:

	if (in_sqlda) {
		efree(in_sqlda);
	}
	if (bind_buf)
		efree(bind_buf);

	if (rv == FAILURE) {
		if (*ib_resultp) {
			efree(*ib_resultp);
			*ib_resultp = NULL;
		}
		if (out_sqlda) {
			_php_ibase_free_xsqlda(out_sqlda);
		}
	}

	return rv;
}
/* }}} */

/* {{{ proto mixed ibase_query([resource link_identifier, [ resource link_identifier, ]] string query [, mixed bind_arg [, mixed bind_arg [, ...]]])
   Execute a query */
PHP_FUNCTION(ibase_query)
{
	zval *zlink, *ztrans, ***bind_args = NULL;
	char *query;
	int bind_i, query_len, bind_num;
	long trans_res_id = 0;
	ibase_db_link *ib_link = NULL;
	ibase_trans *trans = NULL;
	ibase_query ib_query = { NULL, NULL, 0, 0 };
	ibase_result *result = NULL;

	RESET_ERRMSG;
	
	RETVAL_FALSE;

	switch (ZEND_NUM_ARGS()) {
		long l;

		default:
		    if (SUCCESS == zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, 3 TSRMLS_CC, "rrs",
					&zlink, &ztrans, &query, &query_len)) {

				ZEND_FETCH_RESOURCE2(ib_link, ibase_db_link*, &zlink, -1, LE_LINK, le_link, le_plink);
				ZEND_FETCH_RESOURCE(trans, ibase_trans*, &ztrans, -1, LE_TRANS,	le_trans);
				
				trans_res_id = Z_LVAL_P(ztrans);
				bind_i = 3;
				break;
		    }
		case 2:
			if (SUCCESS == zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, 2 TSRMLS_CC, "rs",
					&zlink, &query, &query_len)) {
				_php_ibase_get_link_trans(INTERNAL_FUNCTION_PARAM_PASSTHRU, &zlink, &ib_link, &trans);
	
				if (trans != NULL) {
					trans_res_id = Z_LVAL_P(zlink);
				}
				bind_i = 2;
				break;
			}

			/* the statement is 'CREATE DATABASE ...' if the link argument is IBASE_CREATE */
			if (SUCCESS == zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS()
					TSRMLS_CC, "ls", &l, &query, &query_len) && l == PHP_IBASE_CREATE) {
				isc_db_handle db = NULL;
				isc_tr_handle trans = NULL;

				if (((l = INI_INT("ibase.max_links")) != -1) && (IBG(num_links) >= l)) {
					_php_ibase_module_error("CREATE DATABASE is not allowed: maximum link count "
						"(%ld) reached" TSRMLS_CC, l);

				} else if (isc_dsql_execute_immediate(IB_STATUS, &db, &trans, (short)query_len, 
						query, SQL_DIALECT_CURRENT, NULL)) {
					_php_ibase_error(TSRMLS_C);

				} else if (!db) {
					_php_ibase_module_error("Connection to created database could not be "
						"established" TSRMLS_CC);

				} else {

					/* register the link as a resource; unfortunately, we cannot register 
					   it in the hash table, because we don't know the connection params */
					ib_link = (ibase_db_link *) emalloc(sizeof(ibase_db_link));
					ib_link->handle = db;
					ib_link->dialect = SQL_DIALECT_CURRENT;
					ib_link->tr_list = NULL;
					ib_link->event_head = NULL;

					ZEND_REGISTER_RESOURCE(return_value, ib_link, le_link);
					zend_list_addref(Z_LVAL_P(return_value));
					IBG(default_link) = Z_LVAL_P(return_value);
					++IBG(num_links);
				}
				return;
			}					
		case 1:
		case 0:
			if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() ? 1 : 0 TSRMLS_CC, "s", &query, 
					&query_len)) {
				ZEND_FETCH_RESOURCE2(ib_link, ibase_db_link *, NULL, IBG(default_link), LE_LINK,
			    	le_link, le_plink);

				bind_i = 1;
				break;
			}
			return;
	}

	/* open default transaction */
	if (ib_link == NULL || FAILURE == _php_ibase_def_trans(ib_link, &trans TSRMLS_CC) 
			|| FAILURE == _php_ibase_alloc_query(&ib_query, ib_link, trans, query, ib_link->dialect,
				trans_res_id TSRMLS_CC)) {
		return;
	}

	do {
		int bind_n = ZEND_NUM_ARGS() - bind_i,
		    expected_n = ib_query.in_sqlda ? ib_query.in_sqlda->sqld : 0;
		
		if (bind_n != expected_n) {
			php_error_docref(NULL TSRMLS_CC, (bind_n < expected_n) ? E_WARNING : E_NOTICE,
				"Statement expects %d arguments, %d given", expected_n, bind_n);
			if (bind_n < expected_n) {
				break;
			}
		} else if (bind_n > 0) {		
			if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &bind_args, &bind_num) == FAILURE) {
				return;
			}
		}
	
		if (FAILURE == _php_ibase_exec(INTERNAL_FUNCTION_PARAM_PASSTHRU, &result, &ib_query, 
				&bind_args[bind_i])) {
			break;
		}

		if (result != NULL) { /* statement returns a result */
			result->type = QUERY_RESULT;	

			/* EXECUTE PROCEDURE returns only one row => statement can be released immediately */
			if (ib_query.statement_type != isc_info_sql_stmt_exec_procedure) {
				ib_query.stmt = NULL; /* keep stmt when free query */
			}
			ZEND_REGISTER_RESOURCE(return_value, result, le_result);
		}
	} while (0);

	_php_ibase_free_query(&ib_query TSRMLS_CC);

	if (bind_args) {
		efree(bind_args);
	}
}
/* }}} */

/* {{{ proto int ibase_affected_rows( [ resource link_identifier ] )
   Returns the number of rows affected by the previous INSERT, UPDATE or DELETE statement */
PHP_FUNCTION(ibase_affected_rows)
{
	ibase_trans *trans = NULL;
	ibase_db_link *ib_link;
	zval *arg = NULL;
		
	RESET_ERRMSG;
	
	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|r", &arg) == FAILURE) {
		return;
	}

	if (!arg) {
		ZEND_FETCH_RESOURCE2(ib_link, ibase_db_link *, NULL, IBG(default_link), LE_LINK, le_link, le_plink);
		if (ib_link->tr_list == NULL || ib_link->tr_list->trans == NULL) {
			RETURN_FALSE;
		}
		trans = ib_link->tr_list->trans;
	} else {
		/* one id was passed, could be db or trans id */
		_php_ibase_get_link_trans(INTERNAL_FUNCTION_PARAM_PASSTHRU, &arg, &ib_link, &trans);
		if (trans == NULL) {
			ZEND_FETCH_RESOURCE2(ib_link, ibase_db_link *, &arg, -1, LE_LINK, le_link, le_plink);

			if (ib_link->tr_list == NULL || ib_link->tr_list->trans == NULL) {
				RETURN_FALSE;
			}
			trans = ib_link->tr_list->trans;
		}
	}
	RETURN_LONG(trans->affected_rows);
}
/* }}} */

/* {{{ proto int ibase_num_rows( resource result_identifier ) 
   Return the number of rows that are available in a result */
#if abies_0
PHP_FUNCTION(ibase_num_rows) 
{
	/**
	 * As this function relies on the InterBase API function isc_dsql_sql_info()
	 * which has a couple of limitations (which I hope will be fixed in future 
	 * releases of Firebird), this function is fairly useless. I'm leaving it
	 * in place for people who can live with the limitations, which I only 
	 * found out about after I had implemented it anyway.
	 *
	 * Currently, there's no way to determine how many rows can be fetched from
	 * a cursor. The only number that _can_ be determined is the number of rows
	 * that have already been pre-fetched by the client library. 
	 * This implies the following:
	 * - num_rows() always returns zero before the first fetch;
	 * - num_rows() for SELECT ... FOR UPDATE is broken -> never returns a
	 *   higher number than the number of records fetched so far (no pre-fetch);
	 * - the result of num_rows() for other statements is merely a lower bound 
	 *   on the number of records => calling ibase_num_rows() again after a couple
	 *   of fetches will most likely return a new (higher) figure for large result 
	 *   sets.
	 */

	zval *result_arg;
	ibase_result *ib_result;
	static char info_count[] = {isc_info_sql_records};
	char result[64];

	RESET_ERRMSG;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &result_arg) == FAILURE) {
		return;
	}

	ZEND_FETCH_RESOURCE(ib_result, ibase_result *, &result_arg, -1, LE_RESULT, le_result);

	if (isc_dsql_sql_info(IB_STATUS, &ib_result->stmt, sizeof(info_count), info_count, sizeof(result), result)) {
		_php_ibase_error(TSRMLS_C);
		RETURN_FALSE;
	}

	if (result[0] == isc_info_sql_records) {
		unsigned i = 3, result_size = isc_vax_integer(&result[1],2);

		while (result[i] != isc_info_end && i < result_size) {
			short len = (short)isc_vax_integer(&result[i+1],2);
			if (result[i] == isc_info_req_select_count) {
				RETURN_LONG(isc_vax_integer(&result[i+3],len));
			}
			i += len+3;
		}
	}					
}
#endif
/* }}} */

static int _php_ibase_var_zval(zval *val, void *data, int type, int len, /* {{{ */
	int scale, int flag TSRMLS_DC)
{
	static ISC_INT64 const scales[] = { 1, 10, 100, 1000, 
		10000, 
		100000, 
		1000000, 
		10000000,
		100000000, 
		1000000000, 
		LL_LIT(10000000000), 
		LL_LIT(100000000000),
		LL_LIT(1000000000000), 
		LL_LIT(10000000000000), 
		LL_LIT(100000000000000),
		LL_LIT(1000000000000000),
		LL_LIT(10000000000000000), 
		LL_LIT(100000000000000000), 
		LL_LIT(1000000000000000000)
	};

	switch (type & ~1) {
		unsigned short l;
		long n;
		char string_data[255];
		struct tm t;
		char *format;

		case SQL_VARYING:
			len = ((IBVARY *) data)->vary_length;
			data = ((IBVARY *) data)->vary_string;
			/* no break */
		case SQL_TEXT:
			{
				ZVAL_STRINGL(val,(char *) data,len,1);
			}
			break;
		case SQL_SHORT:
			n = *(short *) data;
			goto _sql_long;
		case SQL_INT64:
#if (SIZEOF_LONG >= 8)
			n = *(long *) data;
			goto _sql_long;
#else
			if (scale == 0) {
				l = slprintf(string_data, sizeof(string_data), "%" LL_MASK "d", *(ISC_INT64 *) data);
				ZVAL_STRINGL(val,string_data,l,1);
			} else {
				ISC_INT64 n = *(ISC_INT64 *) data, f = scales[-scale];

				if (n >= 0) {
					l = slprintf(string_data, sizeof(string_data), "%" LL_MASK "d.%0*" LL_MASK "d", n / f, -scale, n % f);
				} else if (n <= -f) {
					l = slprintf(string_data, sizeof(string_data), "%" LL_MASK "d.%0*" LL_MASK "d", n / f, -scale, -n % f);				
				 } else {
					l = slprintf(string_data, sizeof(string_data), "-0.%0*" LL_MASK "d", -scale, -n % f);
				}
				ZVAL_STRINGL(val,string_data,l,1);
			}
			break;
#endif
		case SQL_LONG:
			n = *(ISC_LONG *) data; 
		_sql_long:
			if (scale == 0) {
				ZVAL_LONG(val,n);
			} else {
				long f = (long) scales[-scale];

				if (n >= 0) {
					l = slprintf(string_data, sizeof(string_data), "%ld.%0*ld", n / f, -scale,  n % f);
				} else if (n <= -f) {
					l = slprintf(string_data, sizeof(string_data), "%ld.%0*ld", n / f, -scale,  -n % f);
				} else {
					l = slprintf(string_data, sizeof(string_data), "-0.%0*ld", -scale, -n % f);
				}
				ZVAL_STRINGL(val,string_data,l,1);
			}
			break;
		case SQL_FLOAT:
			ZVAL_DOUBLE(val, *(float *) data);
			break;
		case SQL_DOUBLE:
			ZVAL_DOUBLE(val, *(double *) data);
			break;
		case SQL_DATE: /* == case SQL_TIMESTAMP: */
			format = INI_STR("ibase.timestampformat");
			isc_decode_timestamp((ISC_TIMESTAMP *) data, &t);
			goto format_date_time;
		case SQL_TYPE_DATE:
			format = INI_STR("ibase.dateformat");
			isc_decode_sql_date((ISC_DATE *) data, &t);
			goto format_date_time;
		case SQL_TYPE_TIME:
			format = INI_STR("ibase.timeformat");
			isc_decode_sql_time((ISC_TIME *) data, &t);

format_date_time:
			/*
			  XXX - Might have to remove this later - seems that isc_decode_date()
			   always sets tm_isdst to 0, sometimes incorrectly (InterBase 6 bug?)
			*/
			t.tm_isdst = -1;
#if HAVE_TM_ZONE
			t.tm_zone = tzname[0];
#endif
			if (flag & PHP_IBASE_UNIXTIME) {
				ZVAL_LONG(val, mktime(&t));
			} else {
#if HAVE_STRFTIME
				l = strftime(string_data, sizeof(string_data), format, &t);
#else
				switch (type & ~1) {
					default:
						l = slprintf(string_data, sizeof(string_data), "%02d/%02d/%4d %02d:%02d:%02d", t.tm_mon+1, t.tm_mday, 
							t.tm_year + 1900, t.tm_hour, t.tm_min, t.tm_sec);
						break;
					case SQL_TYPE_DATE:
						l = slprintf(string_data, sizeof(string_data), "%02d/%02d/%4d", t.tm_mon + 1, t.tm_mday, t.tm_year+1900);
						break;
					case SQL_TYPE_TIME:
						l = slprintf(string_data, sizeof(string_data), "%02d:%02d:%02d", t.tm_hour, t.tm_min, t.tm_sec);
						break;
				}
#endif
				ZVAL_STRINGL(val,string_data,l,1);
				break;
			}
	} /* switch (type) */
	return SUCCESS;
}
/* }}}	*/

static int _php_ibase_arr_zval(zval *ar_zval, char *data, unsigned long data_size, /* {{{ */
	ibase_array *ib_array, int dim, int flag TSRMLS_DC)
{
	/**
	 * Create multidimension array - recursion function
	 */
	int 
		u_bound = ib_array->ar_desc.array_desc_bounds[dim].array_bound_upper,
		l_bound = ib_array->ar_desc.array_desc_bounds[dim].array_bound_lower,
		dim_len = 1 + u_bound - l_bound;
	unsigned short i;

	if (dim < ib_array->ar_desc.array_desc_dimensions) { /* array again */
		unsigned long slice_size = data_size / dim_len;

		array_init(ar_zval);

		for (i = 0; i < dim_len; ++i) {
			zval *slice_zval;
			ALLOC_INIT_ZVAL(slice_zval);

			/* recursion here */
			if (FAILURE == _php_ibase_arr_zval(slice_zval, data, slice_size, ib_array, dim + 1,
					flag TSRMLS_CC)) {
				return FAILURE;
			}
			data += slice_size;

			add_index_zval(ar_zval,l_bound+i,slice_zval);
		}
	} else { /* data at last */

		if (FAILURE == _php_ibase_var_zval(ar_zval, data, ib_array->el_type,
				ib_array->ar_desc.array_desc_length, ib_array->ar_desc.array_desc_scale, flag TSRMLS_CC)) {
			return FAILURE;
		}

		/* fix for peculiar handling of VARCHAR arrays;
		   truncate the field to the cstring length */
		if (ib_array->ar_desc.array_desc_dtype == blr_varying ||
			ib_array->ar_desc.array_desc_dtype == blr_varying2) {

			Z_STRLEN_P(ar_zval) = strlen(Z_STRVAL_P(ar_zval));
		}
	}
	return SUCCESS;
}
/* }}} */

static void _php_ibase_fetch_hash(INTERNAL_FUNCTION_PARAMETERS, int fetch_type) /* {{{ */
{
	zval *result_arg;
	long i, array_cnt = 0, flag = 0;
	ibase_result *ib_result;

	RESET_ERRMSG;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|l", &result_arg, &flag)) {
		return;
	}

	ZEND_FETCH_RESOURCE(ib_result, ibase_result *, &result_arg, -1, LE_RESULT, le_result);

	if (ib_result->out_sqlda == NULL || !ib_result->has_more_rows) {
		RETURN_FALSE;
	}

	if (ib_result->statement_type != isc_info_sql_stmt_exec_procedure) {
		if (isc_dsql_fetch(IB_STATUS, &ib_result->stmt, 1, ib_result->out_sqlda)) {
			ib_result->has_more_rows = 0;
			if (IB_STATUS[0] && IB_STATUS[1]) { /* error in fetch */
				_php_ibase_error(TSRMLS_C);
			}
			RETURN_FALSE;
		}
	} else {
		ib_result->has_more_rows = 0;
	}	

	array_init(return_value);

	for (i = 0; i < ib_result->out_sqlda->sqld; ++i) {
		XSQLVAR *var = &ib_result->out_sqlda->sqlvar[i];
		char buf[METADATALENGTH+4], *alias = var->aliasname;
		
		if (! (fetch_type & FETCH_ROW)) {
			int i = 0;
			char const *base = "FIELD"; /* use 'FIELD' if name is empty */
			
			/**
			* Ensure no two columns have identical names: 
			* keep generating new names until we find one that is unique.
			*/
			switch (*alias) {
				void *p;
				
				default:
					i = 1;
					base = alias;
					
					while (SUCCESS == zend_symtable_find(
							Z_ARRVAL_P(return_value),alias,strlen(alias)+1,&p)) {
				
				case '\0':
						snprintf(alias = buf, sizeof(buf), "%s_%02d", base, i++);
					}
			}
		}

		if (((var->sqltype & 1) == 0) || *var->sqlind != -1) {
			zval *result;
			ALLOC_INIT_ZVAL(result);

			switch (var->sqltype & ~1) {

				default:
					_php_ibase_var_zval(result, var->sqldata, var->sqltype, var->sqllen,
						var->sqlscale, flag TSRMLS_CC);
					break;
				case SQL_BLOB:
					if (flag & PHP_IBASE_FETCH_BLOBS) { /* fetch blob contents into hash */

						ibase_blob blob_handle;
						unsigned long max_len = 0;
						static char bl_items[] = {isc_info_blob_total_length};
						char bl_info[20];
						unsigned short i;

						blob_handle.bl_handle = NULL;
						blob_handle.bl_qd = *(ISC_QUAD *) var->sqldata;

						if (isc_open_blob(IB_STATUS, &ib_result->link->handle, &ib_result->trans->handle,
								&blob_handle.bl_handle, &blob_handle.bl_qd)) {
							_php_ibase_error(TSRMLS_C);
							goto _php_ibase_fetch_error;
						}

						if (isc_blob_info(IB_STATUS, &blob_handle.bl_handle, sizeof(bl_items),
								bl_items, sizeof(bl_info), bl_info)) {
							_php_ibase_error(TSRMLS_C);
							goto _php_ibase_fetch_error;
						}

						/* find total length of blob's data */
						for (i = 0; i < sizeof(bl_info); ) {
							unsigned short item_len;
							char item = bl_info[i++];

							if (item == isc_info_end || item == isc_info_truncated || 
								item == isc_info_error || i >= sizeof(bl_info)) {

								_php_ibase_module_error("Could not determine BLOB size (internal error)"
									TSRMLS_CC);
								goto _php_ibase_fetch_error;
							}								

							item_len = (unsigned short) isc_vax_integer(&bl_info[i], 2);

							if (item == isc_info_blob_total_length) {
								max_len = isc_vax_integer(&bl_info[i+2], item_len);
								break;
							}
							i += item_len+2;
						}

						if (max_len == 0) {
							ZVAL_STRING(result, "", 1);
						} else if (SUCCESS != _php_ibase_blob_get(result, &blob_handle, 
								max_len TSRMLS_CC)) {
							goto _php_ibase_fetch_error;
						}

						if (isc_close_blob(IB_STATUS, &blob_handle.bl_handle)) {
							_php_ibase_error(TSRMLS_C);
							goto _php_ibase_fetch_error;
						}

					} else { /* blob id only */
						ISC_QUAD bl_qd = *(ISC_QUAD *) var->sqldata;
						ZVAL_STRINGL(result,_php_ibase_quad_to_string(bl_qd), BLOB_ID_LEN, 0);
					}
					break;
				case SQL_ARRAY:
					if (flag & PHP_IBASE_FETCH_ARRAYS) { /* array can be *huge* so only fetch if asked */
						ISC_QUAD ar_qd = *(ISC_QUAD *) var->sqldata;
						ibase_array *ib_array = &ib_result->out_array[array_cnt++];
						void *ar_data = emalloc(ib_array->ar_size);

						if (isc_array_get_slice(IB_STATUS, &ib_result->link->handle, 
								&ib_result->trans->handle, &ar_qd, &ib_array->ar_desc,
								ar_data, &ib_array->ar_size)) {
							_php_ibase_error(TSRMLS_C);
							efree(ar_data);
							goto _php_ibase_fetch_error;
						}

						if (FAILURE == _php_ibase_arr_zval(result, ar_data, ib_array->ar_size, ib_array,
								0, flag TSRMLS_CC)) {
							efree(ar_data);
							goto _php_ibase_fetch_error;
						}
						efree(ar_data);

					} else { /* blob id only */
						ISC_QUAD ar_qd = *(ISC_QUAD *) var->sqldata;
						ZVAL_STRINGL(result,_php_ibase_quad_to_string(ar_qd), BLOB_ID_LEN, 0);
					}
					break;
				_php_ibase_fetch_error:
					zval_dtor(result);
					FREE_ZVAL(result);
					RETURN_FALSE;
			} /* switch */

			if (fetch_type & FETCH_ROW) {
				add_index_zval(return_value, i, result);
			} else {
				add_assoc_zval(return_value, alias, result);
			}
		} else {
			if (fetch_type & FETCH_ROW) {
				add_index_null(return_value, i);
			} else {
				add_assoc_null(return_value, alias);
			}
		}
	} /* for field */
}
/* }}} */

/* {{{ proto array ibase_fetch_row(resource result [, int fetch_flags])
   Fetch a row  from the results of a query */
PHP_FUNCTION(ibase_fetch_row)
{
	_php_ibase_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, FETCH_ROW);
}
/* }}} */

/* {{{ proto array ibase_fetch_assoc(resource result [, int fetch_flags])
   Fetch a row  from the results of a query */
PHP_FUNCTION(ibase_fetch_assoc)
{
	_php_ibase_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, FETCH_ARRAY);
}
/* }}} */

/* {{{ proto object ibase_fetch_object(resource result [, int fetch_flags])
   Fetch a object from the results of a query */
PHP_FUNCTION(ibase_fetch_object)
{
	_php_ibase_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, FETCH_ARRAY);

	if (Z_TYPE_P(return_value) == IS_ARRAY) {
		object_and_properties_init(return_value, ZEND_STANDARD_CLASS_DEF_PTR, Z_ARRVAL_P(return_value));
	}
}
/* }}} */


/* {{{ proto bool ibase_name_result(resource result, string name)
   Assign a name to a result for use with ... WHERE CURRENT OF <name> statements */
PHP_FUNCTION(ibase_name_result)
{
	zval *result_arg;
	char *name_arg;
	int name_arg_len;
	ibase_result *ib_result;

	RESET_ERRMSG;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &result_arg, &name_arg, &name_arg_len) == FAILURE) {
		return;
	}

	ZEND_FETCH_RESOURCE(ib_result, ibase_result *, &result_arg, -1, LE_RESULT, le_result);

	if (isc_dsql_set_cursor_name(IB_STATUS, &ib_result->stmt, name_arg, 0)) {
		_php_ibase_error(TSRMLS_C);
		RETURN_FALSE;
	}
	RETURN_TRUE;
}
/* }}} */


/* {{{ proto bool ibase_free_result(resource result)
   Free the memory used by a result */
PHP_FUNCTION(ibase_free_result)
{
	zval *result_arg;
	ibase_result *ib_result;

	RESET_ERRMSG;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &result_arg) == FAILURE) {
		return;
	}

	ZEND_FETCH_RESOURCE(ib_result, ibase_result *, &result_arg, -1, LE_RESULT, le_result);
	zend_list_delete(Z_RESVAL_P(result_arg));
	RETURN_TRUE;
}
/* }}} */

/* {{{ proto resource ibase_prepare(resource link_identifier[, string query [, resource trans_identifier ]])
   Prepare a query for later execution */
PHP_FUNCTION(ibase_prepare)
{
	zval *link_arg, *trans_arg;
	ibase_db_link *ib_link;
	ibase_trans *trans = NULL;
	int query_len, trans_res_id = 0;
	ibase_query *ib_query;
	char *query;

	RESET_ERRMSG;
	
	if (ZEND_NUM_ARGS() == 1) {
		if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &query, &query_len) == FAILURE) {
			return;
		}
		ZEND_FETCH_RESOURCE2(ib_link, ibase_db_link *, NULL, IBG(default_link), LE_LINK, le_link, le_plink);
	} else if (ZEND_NUM_ARGS() == 2) {
		if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &link_arg, &query, &query_len) == FAILURE) {
			return;
		}
		_php_ibase_get_link_trans(INTERNAL_FUNCTION_PARAM_PASSTHRU, &link_arg, &ib_link, &trans);

		if (trans != NULL) {
			trans_res_id = Z_RESVAL_P(link_arg);
		}
	} else {
		if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrs", &link_arg, &trans_arg, &query, &query_len) == FAILURE) {
			return;
		}
		ZEND_FETCH_RESOURCE2(ib_link, ibase_db_link *, &link_arg, -1, LE_LINK, le_link, le_plink);
		ZEND_FETCH_RESOURCE(trans, ibase_trans *, &trans_arg, -1, LE_TRANS, le_trans);
		trans_res_id = Z_RESVAL_P(trans_arg);
	}

	if (FAILURE == _php_ibase_def_trans(ib_link, &trans TSRMLS_CC)) {
		RETURN_FALSE;
	}

	ib_query = (ibase_query *) emalloc(sizeof(ibase_query));

	if (FAILURE == _php_ibase_alloc_query(ib_query, ib_link, trans, query, ib_link->dialect, trans_res_id TSRMLS_CC)) {
		efree(ib_query);
		RETURN_FALSE;
	}
	ZEND_REGISTER_RESOURCE(return_value, ib_query, le_query);
}
/* }}} */

/* {{{ proto mixed ibase_execute(resource query [, mixed bind_arg [, mixed bind_arg [, ...]]])
   Execute a previously prepared query */
PHP_FUNCTION(ibase_execute)
{
	zval *query, ***args = NULL;
	ibase_query *ib_query;
	ibase_result *result = NULL;
	ALLOCA_FLAG(use_heap)

	RESET_ERRMSG;
	
	RETVAL_FALSE;

	if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() ? 1 : 0 TSRMLS_CC, "r", &query)) {
		return;
	}

	ZEND_FETCH_RESOURCE(ib_query, ibase_query *, &query, -1, LE_QUERY, le_query);

	do {
		int bind_n = ZEND_NUM_ARGS() - 1,
			expected_n = ib_query->in_sqlda ? ib_query->in_sqlda->sqld : 0;

		if (bind_n != expected_n) {
			php_error_docref(NULL TSRMLS_CC, (bind_n < expected_n) ? E_WARNING : E_NOTICE,
				"Statement expects %d arguments, %d given", expected_n, bind_n);

			if (bind_n < expected_n) {
				break;
			}
		}

		/* have variables to bind */
		args = (zval ***) do_alloca((expected_n + 1) * sizeof(zval **), use_heap);
	
		if (FAILURE == zend_get_parameters_array_ex((expected_n + 1), args)) {
			break;
		}

		/* Have we used this cursor before and it's still open (exec proc has no cursor) ? */
		if (ib_query->result_res_id != 0 
				&& ib_query->statement_type != isc_info_sql_stmt_exec_procedure) {
			IBDEBUG("Implicitly closing a cursor");

			if (isc_dsql_free_statement(IB_STATUS, &ib_query->stmt, DSQL_close)) {
				_php_ibase_error(TSRMLS_C);
				break;
			}
			/* invalidate previous results returned by this query (not necessary for exec proc) */
			zend_list_delete(ib_query->result_res_id);	
		}

		if (FAILURE == _php_ibase_exec(INTERNAL_FUNCTION_PARAM_PASSTHRU, &result, ib_query, 
				&args[1])) {
		    break;
		}

		/* free the query if trans handle was released */
		if (ib_query->trans->handle == NULL) {
			zend_list_delete(Z_LVAL_P(query));
		}
	
		if (result != NULL) {
			result->type = EXECUTE_RESULT;
			if (ib_query->statement_type == isc_info_sql_stmt_exec_procedure) {
				result->stmt = NULL;
			}
			ib_query->result_res_id = zend_list_insert(result, le_result);
			RETVAL_RESOURCE(ib_query->result_res_id);
		}
	} while (0);

	if (args) {
		free_alloca(args, use_heap);
	}
}
/* }}} */

/* {{{ proto bool ibase_free_query(resource query)
   Free memory used by a query */
PHP_FUNCTION(ibase_free_query)
{
	zval *query_arg;
	ibase_query *ib_query;

	RESET_ERRMSG;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &query_arg) == FAILURE) {
		return;
	}

	ZEND_FETCH_RESOURCE(ib_query, ibase_query *, &query_arg, -1, LE_QUERY, le_query);
	zend_list_delete(Z_RESVAL_P(query_arg));
	RETURN_TRUE;
}
/* }}} */

/* {{{ proto int ibase_num_fields(resource query_result)
   Get the number of fields in result */
PHP_FUNCTION(ibase_num_fields)
{
	zval *result;
	int type;
	XSQLDA *sqlda;

	RESET_ERRMSG;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &result) == FAILURE) {
		return;
	}

	zend_list_find(Z_RESVAL_P(result), &type);

	if (type == le_query) {
		ibase_query *ib_query;

		ZEND_FETCH_RESOURCE(ib_query, ibase_query *, &result, -1, LE_QUERY, le_query);
		sqlda = ib_query->out_sqlda;
	} else {
		ibase_result *ib_result;

		ZEND_FETCH_RESOURCE(ib_result, ibase_result *, &result, -1, LE_RESULT, le_result);
		sqlda = ib_result->out_sqlda;
	}

	if (sqlda == NULL) {
		RETURN_LONG(0);
	} else {
		RETURN_LONG(sqlda->sqld);
	}
}
/* }}} */

static void _php_ibase_field_info(zval *return_value, XSQLVAR *var) /* {{{ */
{
	unsigned short len;
	char buf[16], *s = buf;

	array_init(return_value);

	add_index_stringl(return_value, 0, var->sqlname, var->sqlname_length, 1);
	add_assoc_stringl(return_value, "name", var->sqlname, var->sqlname_length, 1);

	add_index_stringl(return_value, 1, var->aliasname, var->aliasname_length, 1);
	add_assoc_stringl(return_value, "alias", var->aliasname, var->aliasname_length, 1);

	add_index_stringl(return_value, 2, var->relname, var->relname_length, 1);
	add_assoc_stringl(return_value, "relation", var->relname, var->relname_length, 1);

	len = slprintf(buf, 16, "%d", var->sqllen);
	add_index_stringl(return_value, 3, buf, len, 1);
	add_assoc_stringl(return_value, "length", buf, len, 1);

	if (var->sqlscale < 0) {
		unsigned short precision = 0;

		switch (var->sqltype & ~1) {

			case SQL_SHORT:
				precision = 4;
				break;
			case SQL_LONG:
				precision = 9;
				break;
			case SQL_INT64:
				precision = 18;
				break;
		}
		len = slprintf(buf, 16, "NUMERIC(%d,%d)", precision, -var->sqlscale);
		add_index_stringl(return_value, 4, s, len, 1);
		add_assoc_stringl(return_value, "type", s, len, 1);
	} else {
		switch (var->sqltype & ~1) {
			case SQL_TEXT:
				s = "CHAR"; 
				break;
			case SQL_VARYING:
				s = "VARCHAR"; 
				break;
			case SQL_SHORT:
				s = "SMALLINT"; 
				break;
			case SQL_LONG:
				s = "INTEGER"; 
				break;
			case SQL_FLOAT:
				s = "FLOAT"; break;
			case SQL_DOUBLE:
			case SQL_D_FLOAT:
				s = "DOUBLE PRECISION"; break;
			case SQL_INT64: 
				s = "BIGINT"; 
				break;
			case SQL_TIMESTAMP:	
				s = "TIMESTAMP"; 
				break;
			case SQL_TYPE_DATE:
				s = "DATE";
				break;
			case SQL_TYPE_TIME:
				s = "TIME"; 
				break;
			case SQL_BLOB:
				s = "BLOB"; 
				break;
			case SQL_ARRAY:
				s = "ARRAY";
				break;
				/* FIXME: provide more detailed information about the field type, field size
				 * and array dimensions */
			case SQL_QUAD:
				s = "QUAD";
				break;
		}
		add_index_string(return_value, 4, s, 1);
		add_assoc_string(return_value, "type", s, 1);
	}
}
/* }}} */

/* {{{ proto array ibase_field_info(resource query_result, int field_number)
   Get information about a field */
PHP_FUNCTION(ibase_field_info)
{
	zval *result_arg;
	long field_arg;
	int type;
	XSQLDA *sqlda;

	RESET_ERRMSG;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &result_arg, &field_arg) == FAILURE) {
		return;
	}

	zend_list_find(Z_RESVAL_P(result_arg), &type);

	if (type == le_query) {
		ibase_query *ib_query;

		ZEND_FETCH_RESOURCE(ib_query, ibase_query *, &result_arg, -1, LE_QUERY, le_query);
		sqlda = ib_query->out_sqlda;
	} else {
		ibase_result *ib_result;

		ZEND_FETCH_RESOURCE(ib_result, ibase_result *, &result_arg, -1, LE_RESULT, le_result);
		sqlda = ib_result->out_sqlda;
	}					

	if (sqlda == NULL) {
		_php_ibase_module_error("Trying to get field info from a non-select query" TSRMLS_CC);
		RETURN_FALSE;
	}

	if (field_arg < 0 || field_arg >= sqlda->sqld) {
		RETURN_FALSE;
	}
	_php_ibase_field_info(return_value, sqlda->sqlvar + field_arg);
}
/* }}} */

/* {{{ proto int ibase_num_params(resource query)
   Get the number of params in a prepared query */
PHP_FUNCTION(ibase_num_params)
{
	zval *result;
	ibase_query *ib_query;

	RESET_ERRMSG;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &result) == FAILURE) {
		return;
	}

	ZEND_FETCH_RESOURCE(ib_query, ibase_query *, &result, -1, LE_QUERY, le_query);

	if (ib_query->in_sqlda == NULL) {
		RETURN_LONG(0);
	} else {
		RETURN_LONG(ib_query->in_sqlda->sqld);
	}
}
/* }}} */

/* {{{ proto array ibase_param_info(resource query, int field_number)
   Get information about a parameter */
PHP_FUNCTION(ibase_param_info)
{
	zval *result_arg;
	long field_arg;
	ibase_query *ib_query;

	RESET_ERRMSG;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &result_arg, &field_arg) == FAILURE) {
		return;
	}

	ZEND_FETCH_RESOURCE(ib_query, ibase_query *, &result_arg, -1, LE_QUERY, le_query);

	if (ib_query->in_sqlda == NULL) {
		RETURN_FALSE;
	}

	if (field_arg < 0 || field_arg >= ib_query->in_sqlda->sqld) {
		RETURN_FALSE;
	}

	_php_ibase_field_info(return_value,ib_query->in_sqlda->sqlvar + field_arg);
}
/* }}} */

#endif /* HAVE_IBASE */

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: sw=4 ts=4 fdm=marker
 * vim<600: sw=4 ts=4
 */
Back to Top