File: adodb-db2.inc.php

package info (click to toggle)
libphp-adodb 5.21.4-1%2Bdeb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 2,276 kB
  • sloc: php: 35,839; xml: 52; sql: 32; makefile: 5
file content (2009 lines) | stat: -rw-r--r-- 45,484 bytes parent folder | download | duplicates (2)
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
<?php
/**
 * IBM DB2 Native Client driver.
 *
 * Originally DB2 drivers were dependent on an ODBC driver, and some installations
 * may still use that. To use an ODBC driver connection, use the odbc_db2
 * ADOdb driver. For Linux, you need the 'ibm_db2' PECL extension for PHP,
 * For Windows, you need to locate an appropriate version of the php_ibm_db2.dll,
 * as well as the IBM data server client software.
 * This is basically a full rewrite of the original driver, for information
 * about all the changes, see the update information on the ADOdb website
 * for version 5.21.0.
 *
 * @link http://pecl.php.net/package/ibm_db2 PECL Extension For DB2
 *
 * This file is part of ADOdb, a Database Abstraction Layer library for PHP.
 *
 * @package ADOdb
 * @link https://adodb.org Project's web site and documentation
 * @link https://github.com/ADOdb/ADOdb Source code and issue tracker
 *
 * The ADOdb Library is dual-licensed, released under both the BSD 3-Clause
 * and the GNU Lesser General Public Licence (LGPL) v2.1 or, at your option,
 * any later version. This means you can use it in proprietary products.
 * See the LICENSE.md file distributed with this source code for details.
 * @license BSD-3-Clause
 * @license LGPL-2.1-or-later
 *
 * @copyright 2000-2013 John Lim
 * @copyright 2014 Damien Regad, Mark Newnham and the ADOdb community
 * @author Mark Newnham
 */

// security - hide paths
if (!defined('ADODB_DIR')) die();

define("_ADODB_DB2_LAYER", 2 );


class ADODB_db2 extends ADOConnection {
	var $databaseType = "db2";
	var $fmtDate = "'Y-m-d'";
	var $concat_operator = '||';

	var $sysTime = 'CURRENT TIME';
	var $sysDate = 'CURRENT DATE';
	var $sysTimeStamp = 'CURRENT TIMESTAMP';

	var $fmtTimeStamp = "'Y-m-d H:i:s'";
	var $replaceQuote = "''"; // string to use to replace quotes
	var $dataProvider = "db2";
	var $hasAffectedRows = true;

	var $binmode = DB2_BINARY;

	/*
	* setting this to true will make array elements in FETCH_ASSOC
	* mode case-sensitive breaking backward-compat
	*/
	var $useFetchArray = false;
	var $_bindInputArray = true;
	var $_genIDSQL = "VALUES NEXTVAL FOR %s";
	var $_genSeqSQL = "
	CREATE SEQUENCE %s START WITH %s
	NO MAXVALUE NO CYCLE INCREMENT BY 1 NO CACHE
	";
	var $_dropSeqSQL = "DROP SEQUENCE %s";
	var $_autocommit = true;
	var $_lastAffectedRows = 0;
	var $hasInsertID = true;
	var $hasGenID    = true;

	/*
	 * Character used to wrap column and table names for escaping special
	 * characters in column and table names as well as forcing upper and
	 * lower case
	 */
	public $nameQuote = '"';

	/*
	 * Executed after successful connection
	 */
	public $connectStmt = '';

	/*
	 * Holds the current database name
	 */
	private $databaseName = '';

	/*
	 * Holds information about the stored procedure request
	 * currently being built
	 */
	private $storedProcedureParameters = false;


	function __construct() {}

	protected function _insertID($table = '', $column = '')
	{
		return ADOConnection::GetOne('VALUES IDENTITY_VAL_LOCAL()');
	}

	public function _connect($argDSN, $argUsername, $argPassword, $argDatabasename)
	{
		return $this->doDB2Connect($argDSN, $argUsername, $argPassword, $argDatabasename);
	}

	public function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)
	{
		return $this->doDB2Connect($argDSN, $argUsername, $argPassword, $argDatabasename,true);
	}

	private function doDB2Connect($argDSN, $argUsername, $argPassword, $argDatabasename, $persistent=false)
	{
		global $php_errormsg;

		if (!function_exists('db2_connect')) {
			ADOConnection::outp("DB2 extension not installed.");
			return null;
		}

		$connectionParameters = $this->unpackParameters($argDSN,
														$argUsername,
														$argPassword,
														$argDatabasename);

		if ($connectionParameters == null)
		{
			/*
			 * Error thrown
			 */
			return null;
		}

		$argDSN 		         = $connectionParameters['dsn'];
		$argUsername 	         = $connectionParameters['uid'];
		$argPassword 	         = $connectionParameters['pwd'];
		$argDatabasename         = $connectionParameters['database'];
		$useCataloguedConnection = $connectionParameters['catalogue'];

		if ($this->debug){
			if ($useCataloguedConnection){
				$connectMessage = "Catalogued connection using parameters: ";
				$connectMessage .= "DB=$argDatabasename / ";
				$connectMessage .= "UID=$argUsername / ";
				$connectMessage .= "PWD=$argPassword";
			}
			else
			{
				$connectMessage = "Uncatalogued connection using DSN: $argDSN";
			}
			ADOConnection::outp($connectMessage);
		}
		/*
		 * This needs to be set before the connect().
		 */
		ini_set('ibm_db2.binmode', $this->binmode);

		if ($persistent)
			$db2Function = 'db2_pconnect';
		else
			$db2Function = 'db2_connect';

		/*
		* We need to flatten out the connectionParameters
		*/

		$db2Options = array();
		if ($this->connectionParameters)
		{
			foreach($this->connectionParameters as $p)
				foreach($p as $k=>$v)
					$db2Options[$k] = $v;
		}

		if ($useCataloguedConnection)
			$this->_connectionID = $db2Function($argDatabasename,
												$argUsername,
												$argPassword,
												$db2Options);
		else
			$this->_connectionID = $db2Function($argDSN,
												null,
												null,
												$db2Options);

		$php_errormsg = '';

		$this->_errorMsg = @db2_conn_errormsg();

		if ($this->_connectionID && $this->connectStmt)
			$this->execute($this->connectStmt);

		return $this->_connectionID != false;

	}

	/**
	 * Validates and preprocesses the passed parameters for consistency
	 *
	 * @param	string	$argDSN				Either DSN or database
	 * @param	string	$argUsername		User name or null
	 * @param	string	$argPassword		Password or null
	 * @param	string	$argDatabasename	Either DSN or database
	 *
	 * @return mixed  array if correct, null if not
	 */
	private function unpackParameters($argDSN, $argUsername, $argPassword, $argDatabasename)
	{

		global $php_errormsg;

		$connectionParameters = array('dsn'=>'',
									  'uid'=>'',
									  'pwd'=>'',
									  'database'=>'',
									  'catalogue'=>true
									  );

		/*
		 * Uou can either connect to a catalogued connection
		 * with a database name e.g. 'SAMPLE'
		 * or an uncatalogued connection with a DSN like connection
		 * DATABASE=database;HOSTNAME=hostname;PORT=port;PROTOCOL=TCPIP;UID=username;PWD=password;
		 */

		if (!$argDSN && !$argDatabasename)
		{
			$errorMessage = 'Supply either catalogued or uncatalogued connection parameters';
			$this->_errorMsg = $errorMessage;
			if ($this->debug)
				ADOConnection::outp($errorMessage);
			return null;
		}

		$useCataloguedConnection = true;
		$schemaName 			 = '';

		if ($argDSN && $argDatabasename)
		{
			/*
			 * If a catalogued connection if provided,
			 * as well as user and password
			 * that will take priority
			 */
			if ($argUsername && $argPassword && !$this->isDsn($argDatabasename))
			{
				if ($this->debug){
					$errorMessage = 'Warning: Because you provided user,';
					$errorMessage.= 'password and database, DSN connection ';
					$errorMessage.= 'parameters were discarded';
					ADOConnection::outp($errorMessage);

				}
				$argDSN = '';
			}
			else if ($this->isDsn($argDSN) && $this->isDsn($argDatabasename))
			{
				$errorMessage = 'Supply uncatalogued connection parameters ';
				$errorMessage.= 'in either the database or DSN arguments, ';
				$errorMessage.= 'but not both';
				$php_errormsg = $errorMessage;
				if ($this->debug)
					ADOConnection::outp($errorMessage);
				return null;
			}
		}

		if (!$this->isDsn($argDSN) && $this->isDsn($argDatabasename))
		{
			/*
			 * Switch them around for next test
			 */
			$temp           = $argDSN;
			$argDsn         = $argDatabasename;
			$argDatabasenME = $temp;
		}

		if ($this->isDsn($argDSN))
		{

			if (!preg_match('/uid=/i',$argDSN)
			||  !preg_match('/pwd=/i',$argDSN))
			{
				$errorMessage = 'For uncatalogued connections, provide ';
				$errorMessage.= 'both UID and PWD in the connection string';
				$php_errormsg = $errorMessage;
				if ($this->debug)
					ADOConnection::outp($errorMessage);
				return null;
			}

			if (preg_match('/database=/i',$argDSN))
			{
				if ($argDatabasename)
				{
					$argDatabasename = '';
					if ($this->debug)
					{
						$errorMessage = 'Warning: Because you provided ';
						$errorMessage.= 'database information in the DSN ';
						$errorMessage.= 'parameters, the supplied database ';
						$errorMessage.= 'name was discarded';
						ADOConnection::outp($errorMessage);
					}
				}
				$useCataloguedConnection = false;

			}
			elseif ($argDatabasename)
			{
				$this->databaseName = $argDatabasename;
				$argDSN .= ';database=' . $argDatabasename;
				$argDatabasename = '';
				$useCataloguedConnection = false;

			}
			else
			{
				$errorMessage = 'Uncatalogued connection parameters ';
				$errorMessage.= 'must contain a database= argument';
				$php_errormsg = $errorMessage;
				if ($this->debug)
					ADOConnection::outp($errorMessage);
				return null;
			}
		}

		if ($argDSN && !$argDatabasename && $useCataloguedConnection)
		{
			$argDatabasename = $argDSN;
			$argDSN          = '';
		}


		if ($useCataloguedConnection
		&& (!$argDatabasename
		|| !$argUsername
		|| !$argPassword))
		{

			$errorMessage = 'For catalogued connections, provide ';
			$errorMessage.= 'database, username and password';
			$this->_errorMsg = $errorMessage;
			if ($this->debug)
				ADOConnection::outp($errorMessage);
			return null;

		}

		if ($argDatabasename)
			$this->databaseName = $argDatabasename;
		elseif (!$this->databaseName)
			$this->databaseName = $this->getDatabasenameFromDsn($argDSN);


		$connectionParameters = array('dsn'=>$argDSN,
									  'uid'=>$argUsername,
									  'pwd'=>$argPassword,
									  'database'=>$argDatabasename,
									  'catalogue'=>$useCataloguedConnection
									  );

		return $connectionParameters;

	}

	/**
	  * Does the provided string look like a DSN
	  *
	  * @param	string	$dsnString
	  *
	  * @return bool
	  */
	private function isDsn($dsnString){
		$dsnArray = preg_split('/[;=]+/',$dsnString);
		if (count($dsnArray) > 2)
			return true;
		return false;
	}


	/**
	  * Gets the database name from the DSN
	  *
	  * @param	string	$dsnString
	  *
	  * @return string
	  */
	private function getDatabasenameFromDsn($dsnString){

		$dsnArray = preg_split('/[;=]+/',$dsnString);
		$dbIndex  = array_search('database',$dsnArray);

		return $dsnArray[$dbIndex + 1];
	}


	/**
	* format and return date string in database timestamp format
	*
	* @param	mixed	$ts		either a string or a unixtime
	* @param	bool	$isField	discarded
	*
	* @return string
	*/
	function dbTimeStamp($ts,$isField=false)
	{
		if (empty($ts) && $ts !== 0) return 'null';
		if (is_string($ts)) $ts = ADORecordSet::unixTimeStamp($ts);
		return 'TO_DATE('.adodb_date($this->fmtTimeStamp,$ts).",'YYYY-MM-DD HH24:MI:SS')";
	}

	/**
	* Format date column in sql string given an input format that understands Y M D
	*
	* @param	string	$fmt
	* @param	bool	$col
	*
	* @return string
	*/
	function sqlDate($fmt, $col=false)
	{
		if (!$col) $col = $this->sysDate;

		/* use TO_CHAR() if $fmt is TO_CHAR() allowed fmt */
		if ($fmt== 'Y-m-d H:i:s')
			return 'TO_CHAR('.$col.", 'YYYY-MM-DD HH24:MI:SS')";

		$s = '';

		$len = strlen($fmt);
		for ($i=0; $i < $len; $i++) {
			if ($s) $s .= $this->concat_operator;
			$ch = $fmt[$i];
			switch($ch) {
			case 'Y':
			case 'y':
				if ($len==1) return "year($col)";
				$s .= "char(year($col))";
				break;
			case 'M':
				if ($len==1) return "monthname($col)";
				$s .= "substr(monthname($col),1,3)";
				break;
			case 'm':
				if ($len==1) return "month($col)";
				$s .= "right(digits(month($col)),2)";
				break;
			case 'D':
			case 'd':
				if ($len==1) return "day($col)";
				$s .= "right(digits(day($col)),2)";
				break;
			case 'H':
			case 'h':
				if ($len==1) return "hour($col)";
				if ($col != $this->sysDate) $s .= "right(digits(hour($col)),2)";
				else $s .= "''";
				break;
			case 'i':
			case 'I':
				if ($len==1) return "minute($col)";
				if ($col != $this->sysDate)
					$s .= "right(digits(minute($col)),2)";
					else $s .= "''";
				break;
			case 'S':
			case 's':
				if ($len==1) return "second($col)";
				if ($col != $this->sysDate)
					$s .= "right(digits(second($col)),2)";
				else $s .= "''";
				break;
			default:
				if ($ch == '\\') {
					$i++;
					$ch = substr($fmt,$i,1);
				}
				$s .= $this->qstr($ch);
			}
		}
		return $s;
	}


	function serverInfo()
	{
		$sql = "SELECT service_level, fixpack_num
				  FROM TABLE(sysproc.env_get_inst_info())
					AS INSTANCEINFO";
		$row = $this->GetRow($sql);


		if ($row) {
			$info['version'] = $row[0].':'.$row[1];
			$info['fixpack'] = $row[1];
			$info['description'] = '';
		} else {
			return ADOConnection::serverInfo();
		}

		return $info;
	}

	function createSequence($seqname='adodbseq',$start=1)
	{
		if (empty($this->_genSeqSQL))
			return false;

		$ok = $this->execute(sprintf($this->_genSeqSQL,$seqname,$start));
		if (!$ok)
			return false;
		return true;
	}

	function dropSequence($seqname='adodbseq')
	{
		if (empty($this->_dropSeqSQL)) return false;
		return $this->execute(sprintf($this->_dropSeqSQL,$seqname));
	}

	function selectLimit($sql,$nrows=-1,$offset=-1,$inputArr=false,$secs2cache=0)
	{
		$nrows = (integer) $nrows;

		if ($offset <= 0)
		{
			if ($nrows >= 0)
				$sql .=  " FETCH FIRST $nrows ROWS ONLY ";

			$rs = $this->execute($sql,$inputArr);

		}
		else
		{
			if ($offset > 0 && $nrows < 0);

			else
			{
				$nrows += $offset;
				$sql .=  " FETCH FIRST $nrows ROWS ONLY ";
			}

			/*
			 * DB2 has no native support for mid table offset
			 */
			$rs = ADOConnection::selectLimit($sql,$nrows,$offset,$inputArr);

		}

		return $rs;
	}


	function errorMsg()
	{
		if ($this->_errorMsg !== false)
			return $this->_errorMsg;

		if (empty($this->_connectionID))
			return @db2_conn_errormsg();

		return @db2_conn_errormsg($this->_connectionID);
	}

	function errorNo()
	{

		if ($this->_errorCode !== false)
			return $this->_errorCode;


		if (empty($this->_connectionID))
			$e = @db2_conn_error();

		else
			$e = @db2_conn_error($this->_connectionID);

		return $e;
	}



	function beginTrans()
	{
		if (!$this->hasTransactions)
			return false;
		if ($this->transOff)
			return true;

		$this->transCnt += 1;

		$this->_autocommit = false;

		return db2_autocommit($this->_connectionID,false);
	}

	function CommitTrans($ok=true)
	{
		if ($this->transOff)
			return true;

		if (!$ok)
			return $this->RollbackTrans();

		if ($this->transCnt)
			$this->transCnt -= 1;

		$this->_autocommit = true;
		$ret = @db2_commit($this->_connectionID);
		@db2_autocommit($this->_connectionID,true);
		return $ret;
	}

	function RollbackTrans()
	{
		if ($this->transOff) return true;
		if ($this->transCnt) $this->transCnt -= 1;
		$this->_autocommit = true;
		$ret = @db2_rollback($this->_connectionID);
		@db2_autocommit($this->_connectionID,true);
		return $ret;
	}

	/**
	 * Return a list of Primary Keys for a specified table
	 *
	 * We don't use db2_statistics as the function does not seem to play
	 * well with mixed case table names
	 *
	 * @param string   $table
	 * @param bool     $primary    (optional) only return primary keys
	 * @param bool     $owner      (optional) not used in this driver
	 *
	 * @return string[]    Array of indexes
	 */
	public function metaPrimaryKeys($table,$owner=false)
	{

		$primaryKeys = array();

		global $ADODB_FETCH_MODE;

		$schema = '';
		$this->_findschema($table,$schema);

		$table = $this->getTableCasedValue($table);

		$savem 			  = $ADODB_FETCH_MODE;
		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
		$this->setFetchMode(ADODB_FETCH_NUM);


		$sql = "SELECT *
				  FROM syscat.indexes
				 WHERE tabname='$table'";

		$rows = $this->getAll($sql);

		$this->setFetchMode($savem);
		$ADODB_FETCH_MODE = $savem;

		if (empty($rows))
			return false;

		foreach ($rows as $r)
		{
			if ($r[7] != 'P')
				continue;

			$cols = explode('+',$r[6]);
			foreach ($cols as $colIndex=>$col)
			{
				if ($colIndex == 0)
					continue;
				$columnName = $this->getMetaCasedValue($col);
				$primaryKeys[] = $columnName;
			}
			break;
		}
		return $primaryKeys;
	}

	/**
	 * returns assoc array where keys are tables, and values are foreign keys
	 *
	 * @param	string	$table
	 * @param	string	$owner		[optional][discarded]
	 * @param	bool	$upper		[optional][discarded]
	 * @param	bool	$associative[optional][discarded]
	 *
	 * @return	mixed[]			Array of foreign key information
	 */
	public function metaForeignKeys($table, $owner = FALSE, $upper = FALSE, $asociative = FALSE )
	{

		global $ADODB_FETCH_MODE;

		$schema = '';
		$this->_findschema($table,$schema);

		$savem = $ADODB_FETCH_MODE;
		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;

		$this->setFetchMode(ADODB_FETCH_NUM);

		$sql = "SELECT SUBSTR(tabname,1,20) table_name,
					   SUBSTR(constname,1,20) fk_name,
					   SUBSTR(REFTABNAME,1,12) parent_table,
					   SUBSTR(refkeyname,1,20) pk_orig_table,
					   fk_colnames
				 FROM syscat.references
				WHERE tabname = '$table'";

		$results = $this->getAll($sql);

		$ADODB_FETCH_MODE = $savem;
		$this->setFetchMode($savem);

		if (empty($results))
			return false;

		$foreignKeys = array();

		foreach ($results as $r)
		{
			$parentTable = trim($this->getMetaCasedValue($r[2]));
			$keyName     = trim($this->getMetaCasedValue($r[1]));
			$foreignKeys[$parentTable] = $keyName;
		}

		return $foreignKeys;
	}

	/**
	 * Returns a list of tables
	 *
	 * @param string	$ttype (optional)
	 * @param	string	$schema	(optional)
	 * @param	string	$mask	(optional)
	 *
	 * @return array
	 */
	public function metaTables($ttype=false,$schema=false,$mask=false)
	{

		global $ADODB_FETCH_MODE;

		$savem 			  = $ADODB_FETCH_MODE;
		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;

		/*
		* Values for TABLE_TYPE
		* ---------------------------
		* ALIAS, HIERARCHY TABLE, INOPERATIVE VIEW, NICKNAME,
		* MATERIALIZED QUERY TABLE, SYSTEM TABLE, TABLE,
		* TYPED TABLE, TYPED VIEW, and VIEW
		*
		* If $ttype passed as '', match 'TABLE' and 'VIEW'
		* If $ttype passed as 'T' it is assumed to be 'TABLE'
		* if $ttype passed as 'V' it is assumed to be 'VIEW'
		*/
		$ttype = strtoupper($ttype);
		if ($ttype) {
			/*
			 * @todo We could do valid type checking or array type
			 */
			 if ($ttype == 'V')
				$ttype = 'VIEW';
			if ($ttype == 'T')
				$ttype = 'TABLE';
		}

		if (!$schema)
			$schema = '%';

		if (!$mask)
			$mask = '%';

		$qid = @db2_tables($this->_connectionID,NULL,$schema,$mask,$ttype);

		$rs = new ADORecordSet_db2($qid);

		$ADODB_FETCH_MODE = $savem;

		if (!$rs)
			return false;

		$arr = $rs->getArray();

		$rs->Close();

		$tableList = array();

		/*
		* Array items
		* ---------------------------------
		* 0 TABLE_CAT	The catalog that contains the table.
		*				The value is NULL if this table does not have catalogs.
		* 1 TABLE_SCHEM	Name of the schema that contains the table.
		* 2 TABLE_NAME	Name of the table.
		* 3 TABLE_TYPE	Table type identifier for the table.
		* 4 REMARKS		Description of the table.
		*/

		for ($i=0; $i < sizeof($arr); $i++)
		{

			$tableRow = $arr[$i];
			$tableName = $tableRow[2];
			$tableType = $tableRow[3];

			if (!$tableName)
				continue;

			if ($ttype == '' && (strcmp($tableType,'TABLE') <> 0 && strcmp($tableType,'VIEW') <> 0))
				continue;

			/*
			 * Set metacasing if required
			 */
			$tableName = $this->getMetaCasedValue($tableName);

			/*
			 * If we requested a schema, we prepend the schema
			   name to the table name
			 */
			if (strcmp($schema,'%') <> 0)
				$tableName = $schema . '.' . $tableName;

			$tableList[] = $tableName;

		}
		return $tableList;
	}

	/**
	  * Return a list of indexes for a specified table
	  *
	  * We don't use db2_statistics as the function does not seem to play
	  * well with mixed case table names
	  *
	  * @param string   $table
	  * @param bool     $primary    (optional) only return primary keys
	  * @param bool     $owner      (optional) not used in this driver
	  *
	  * @return string[]    Array of indexes
	  */
	public function metaIndexes($table, $primary = false, $owner = false) {

		global $ADODB_FETCH_MODE;

		 /* Array(
		 *   [name_of_index] => Array(
		 *     [unique] => true or false
		 *     [columns] => Array(
		 *       [0] => firstcol
		 *       [1] => nextcol
		 *       [2] => etc........
		 *     )
		 *   )
		 * )
		 */
		$indices 		= array();
		$primaryKeyName = '';

		$table = $this->getTableCasedValue($table);


		$savem 			  = $ADODB_FETCH_MODE;
		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
		$this->setFetchMode(ADODB_FETCH_NUM);

		$sql = "SELECT *
				  FROM syscat.indexes
				 WHERE tabname='$table'";

		$rows = $this->getAll($sql);

		$this->setFetchMode($savem);
		$ADODB_FETCH_MODE = $savem;

		if (empty($rows))
			return false;

		foreach ($rows as $r)
		{

			$primaryIndex = $r[7] == 'P'?1:0;
			if (!$primary)
				/*
				 * Primary key not requested, ignore that one
				 */
				if ($r[7] == 'P')
					continue;

			$indexName = $this->getMetaCasedValue($r[1]);
			if (!isset($indices[$indexName]))
			{
				$unique = ($r[7] == 'U')?1:0;
				$indices[$indexName] = array('unique'=>$unique,
											 'primary'=>$primaryIndex,
											 'columns'=>array()
										);
			}
			$cols = explode('+',$r[6]);
			foreach ($cols as $colIndex=>$col)
			{
				if ($colIndex == 0)
					continue;
				$columnName = $this->getMetaCasedValue($col);
				$indices[$indexName]['columns'][] = $columnName;
			}

		}

		return $indices;

	}

	/**
	 * List procedures or functions in an array.
	 *
	 * We interrogate syscat.routines instead of calling the PHP
	 * function procedures because ADOdb requires the type of procedure
	 * this is not available in the php function
	 *
	 * @param	string $procedureNamePattern (optional)
	 * @param	string $catalog				 (optional)
	 * @param	string $schemaPattern		 (optional)

	 * @return array of procedures on current database.
	 *
	 */
	public function metaProcedures($procedureNamePattern = null, $catalog  = null, $schemaPattern  = null) {


		global $ADODB_FETCH_MODE;

		$metaProcedures = array();
		$procedureSQL   = '';
		$catalogSQL     = '';
		$schemaSQL      = '';

		$savem 			  = $ADODB_FETCH_MODE;
		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;

		if ($procedureNamePattern)
			$procedureSQL = "AND ROUTINENAME LIKE " . strtoupper($this->qstr($procedureNamePattern));

		if ($catalog)
			$catalogSQL = "AND OWNER=" . strtoupper($this->qstr($catalog));

		if ($schemaPattern)
			$schemaSQL = "AND ROUTINESCHEMA LIKE {$this->qstr($schemaPattern)}";


		$fields = "
		ROUTINENAME,
		CASE ROUTINETYPE
			 WHEN 'P' THEN 'PROCEDURE'
			 WHEN 'F' THEN 'FUNCTION'
			 ELSE 'METHOD'
			 END AS ROUTINETYPE_NAME,
		ROUTINESCHEMA,
		REMARKS";

		$SQL = "SELECT $fields
				  FROM syscat.routines
				 WHERE OWNER IS NOT NULL
				  $procedureSQL
				  $catalogSQL
				  $schemaSQL
				ORDER BY ROUTINENAME
				";

		$result = $this->execute($SQL);

		$ADODB_FETCH_MODE = $savem;

		if (!$result)
			return false;

		while ($r = $result->fetchRow()){
			$procedureName = $this->getMetaCasedValue($r[0]);
			$schemaName    = $this->getMetaCasedValue($r[2]);
			$metaProcedures[$procedureName] = array('type'=> $r[1],
												   'catalog' => '',
												   'schema'  => $schemaName,
												   'remarks' => $r[3]
													);
		}

		return $metaProcedures;

	}

	/**
	  * Lists databases. Because instances are independent, we only know about
	  * the current database name
	  *
	  * @return string[]
	  */
	public function metaDatabases(){

		$dbName = $this->getMetaCasedValue($this->databaseName);

		return (array)$dbName;

	}




/*
See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/db2/htm/db2datetime_data_type_changes.asp
/ SQL data type codes /
#define	SQL_UNKNOWN_TYPE	0
#define SQL_CHAR			1
#define SQL_NUMERIC		 2
#define SQL_DECIMAL		 3
#define SQL_INTEGER		 4
#define SQL_SMALLINT		5
#define SQL_FLOAT		   6
#define SQL_REAL			7
#define SQL_DOUBLE		  8
#if (DB2VER >= 0x0300)
#define SQL_DATETIME		9
#endif
#define SQL_VARCHAR		12


/ One-parameter shortcuts for date/time data types /
#if (DB2VER >= 0x0300)
#define SQL_TYPE_DATE	  91
#define SQL_TYPE_TIME	  92
#define SQL_TYPE_TIMESTAMP 93

#define SQL_UNICODE                             (-95)
#define SQL_UNICODE_VARCHAR                     (-96)
#define SQL_UNICODE_LONGVARCHAR                 (-97)
*/
	function DB2Types($t)
	{
		switch ((integer)$t) {
		case 1:
		case 12:
		case 0:
		case -95:
		case -96:
			return 'C';
		case -97:
		case -1: //text
			return 'X';
		case -4: //image
			return 'B';

		case 9:
		case 91:
			return 'D';

		case 10:
		case 11:
		case 92:
		case 93:
			return 'T';

		case 4:
		case 5:
		case -6:
			return 'I';

		case -11: // uniqidentifier
			return 'R';
		case -7: //bit
			return 'L';

		default:
			return 'N';
		}
	}

	public function metaColumns($table, $normalize=true)
	{
		global $ADODB_FETCH_MODE;

		$savem = $ADODB_FETCH_MODE;

		$schema = '%';
		$this->_findschema($table,$schema);
		$table = $this->getTableCasedValue($table);
		$colname = "%";
		$qid = db2_columns($this->_connectionID, null, $schema, $table, $colname);
		if (empty($qid))
		{
			if ($this->debug)
			{
				$errorMessage = @db2_conn_errormsg($this->_connectionID);
				ADOConnection::outp($errorMessage);
			}
			return false;
		}

		$rs = new ADORecordSet_db2($qid);

		if (!$rs)
			return false;

		$rs->_fetch();

		$retarr = array();

		/*
		$rs->fields indices
		0 TABLE_QUALIFIER
		1 TABLE_SCHEM
		2 TABLE_NAME
		3 COLUMN_NAME
		4 DATA_TYPE
		5 TYPE_NAME
		6 PRECISION
		7 LENGTH
		8 SCALE
		9 RADIX
		10 NULLABLE
		11 REMARKS
		12 Column Default
		13 SQL Data Type
		14 SQL DateTime SubType
		15 Max length in Octets
		16 Ordinal Position
		17 Is NULLABLE
		*/
		while (!$rs->EOF)
		{
			if ($rs->fields[2] == $table)
			{

				$fld       = new ADOFieldObject();
				$fld->name = $rs->fields[3];
				$fld->type = $this->DB2Types($rs->fields[4]);

				// ref: http://msdn.microsoft.com/library/default.asp?url=/archive/en-us/dnaraccgen/html/msdn_odk.asp
				// access uses precision to store length for char/varchar

				if ($fld->type == 'C' or $fld->type == 'X') {
					if ($rs->fields[4] <= -95) // UNICODE
						$fld->max_length = $rs->fields[7]/2;
					else
						$fld->max_length = $rs->fields[7];
				} else
					$fld->max_length = $rs->fields[7];

				$fld->not_null         = !empty($rs->fields[10]);
				$fld->scale            = $rs->fields[8];
				$fld->primary_key      = false;

				//$columnName = $this->getMetaCasedValue($fld->name);
				$columnName = strtoupper($fld->name);
				$retarr[$columnName] = $fld;

			}
			else if (sizeof($retarr)>0)
				break;

			$rs->MoveNext();

		}

		$rs->Close();
		if (empty($retarr))
			$retarr = false;

		/*
		 * Now we find out if the column is part of a primary key
		 */

		$qid = @db2_primary_keys($this->_connectionID, "", $schema, $table);
		if (empty($qid))
			return false;

		$rs = new ADORecordSet_db2($qid);

		if (!$rs)
		{
			$ADODB_FETCH_MODE = $savem;
			return $retarr;
		}
		$rs->_fetch();

		/*
		$rs->fields indices
		0 TABLE_CAT
		1 TABLE_SCHEM
		2 TABLE_NAME
		3 COLUMN_NAME
		4 KEY_SEQ
		5 PK_NAME
		*/
		while (!$rs->EOF) {
			if (strtoupper(trim($rs->fields[2])) == $table
			&& (!$schema || strtoupper($rs->fields[1]) == $schema))
			{
				$retarr[strtoupper($rs->fields[3])]->primary_key = true;
			}
			else if (sizeof($retarr)>0)
				break;

			$rs->MoveNext();
		}
		$rs->Close();

		$ADODB_FETCH_MODE = $savem;

		if (empty($retarr))
			return false;

		/*
		* If the fetch mode is numeric, return as numeric array
		*/
		if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM)
			$retarr = array_values($retarr);

		return $retarr;
	}

	/**
	  * In this version if prepareSp, we just check to make sure
	  * that the name of the stored procedure is correct
	  * If true, we returns an array
	  * else false
	  *
	  * @param	string	$procedureName
	  * @param	mixed   $parameters (not used in db2 connections)
	  * @return mixed[]
	  */
	function prepareSp($procedureName,$parameters=false) {

		global $ADODB_FETCH_MODE;

		$this->storedProcedureParameters = array('name'=>'',
												 'resource'=>false,
												 'in'=>array(),
												 'out'=>array(),
												 'index'=>array(),
												 'parameters'=>array(),
												 'keyvalue' => array());

		//$procedureName = strtoupper($procedureName);
		//$procedureName = $this->getTableCasedValue($procedureName);

		$savem = $ADODB_FETCH_MODE;
		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;

		$qid = db2_procedures($this->_connectionID, NULL , '%' , $procedureName );

		$ADODB_FETCH_MODE = $savem;

		if (!$qid)
		{
			if ($this->debug)
				ADOConnection::outp(sprintf('No Procedure of name %s available',$procedureName));
			return false;
		}



		$this->storedProcedureParameters['name'] = $procedureName;
		/*
		 * Now we know we have a valid procedure name, lets see if it requires
		 * parameters
		 */
		$savem = $ADODB_FETCH_MODE;
		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;

		$qid = db2_procedure_columns($this->_connectionID, NULL , '%' , $procedureName , NULL );

		$ADODB_FETCH_MODE = $savem;

		if (!$qid)
		{
			if ($this->debug)
				ADOConnection::outp(sprintf('No columns of name %s available',$procedureName));
			return false;
		}
		$rs = new ADORecordSet_db2($qid);
		if (!$rs)
			return false;

		$preparedStatement = 'CALL %s(%s)';
		$parameterMarkers = array();
		while (!$rs->EOF)
		{
			$parameterName = $rs->fields[3];
			if ($parameterName == '')
			{
				$rs->moveNext();
				continue;
			}
			$parameterType = $rs->fields[4];
			$ordinalPosition = $rs->fields[17];
			switch($parameterType)
			{
			case DB2_PARAM_IN:
			case DB2_PARAM_INOUT:
				$this->storedProcedureParameters['in'][$parameterName] = '';
				break;
			case DB2_PARAM_INOUT:
			case DB2_PARAM_OUT:
				$this->storedProcedureParameters['out'][$parameterName] = '';
				break;
			}
			$this->storedProcedureParameters['index'][$parameterName] = $ordinalPosition;
			$this->storedProcedureParameters['parameters'][$ordinalPosition] = $rs->fields;
			$rs->moveNext();

		}
		$parameterCount = count($this->storedProcedureParameters['index']);
		$parameterMarkers = array_fill(0,$parameterCount,'?');

		/*
		 * We now know how many parameters to bind to the stored procedure
		 */
		$parameterList = implode(',',$parameterMarkers);

		$sql = sprintf($preparedStatement,$procedureName,$parameterList);

		$spResource = @db2_prepare($this->_connectionID,$sql);

		if (!$spResource)
		{
			$errorMessage = @db2_conn_errormsg($this->_connectionID);
			$this->_errorMsg = $errorMessage;

			if ($this->debug)
				ADOConnection::outp($errorMessage);

			return false;
		}

		$this->storedProcedureParameters['resource'] = $spResource;

		if ($this->debug)
		{

			ADOConnection::outp('The following parameters will be used in the SP call');
			ADOConnection::outp(print_r($this->storedProcedureParameters));
		}
		/*
		 * We now have a stored parameter resource
		 * to bind to. The spResource and sql that is returned are
		 * not usable, its for dummy compatibility. Everything
		 * will be handled by the storedProcedureParameters
		 * array
		 */
		return array($sql,$spResource);

	}

	private function storedProcedureParameter(&$stmt,
											  &$var,
											  $name,
											  $isOutput=false,
											  $maxLen=4000,
											  $type=false)
	{


		$name = strtoupper($name);

		/*
		 * Must exist in the list of parameter names for the type
		 */
		if ($isOutput
		&& !isset( $this->storedProcedureParameters['out'][$name]))
		{
			$errorMessage = sprintf('%s is not a valid OUT parameter name',$name);

			$this->_errorMsg = $errorMessage;
			if ($this->debug)
				ADOConnection::outp($errorMessage);
			return false;
		}

		if (!$isOutput
		&& !isset( $this->storedProcedureParameters['in'][$name]))
		{
			$errorMessage = sprintf('%s is not a valid IN parameter name',$name);

			$this->_errorMsg = $errorMessage;
			if ($this->debug)
				ADOConnection::outp($errorMessage);
			return false;
		}

		/*
		 * We will use these values to bind to when we execute
		 * the query
		 */
		$this->storedProcedureParameters['keyvalue'][$name] = &$var;

		return true;

	}

	/**
	* Executes a prepared stored procedure.
	*
	* The function uses the previously accumulated information and
	* resources in the $storedProcedureParameters array
	*
	* @return mixed	The statement id if successful, or false
	*/
	private function executeStoredProcedure()
	{

		/*
		 * Get the previously built resource
		 */
		$stmtid = $this->storedProcedureParameters['resource'];

		/*
		 * Bind our variables to the DB2 procedure
		 */
		foreach ($this->storedProcedureParameters['keyvalue'] as $spName=>$spValue){

			/*
			 * Get the ordinal position, required for binding
			 */
			$ordinalPosition = $this->storedProcedureParameters['index'][$spName];

			/*
			 * Get the db2 column dictionary for the parameter
			 */
			$columnDictionary = $this->storedProcedureParameters['parameters'][$ordinalPosition];
			$parameterType    = $columnDictionary[4];
			$dataType         = $columnDictionary[5];
			$precision        = $columnDictionary[10];
			$scale        	  = $columnDictionary[9];

			$ok = @db2_bind_param ($this->storedProcedureParameters['resource'],
								  $ordinalPosition ,
								  $spName,
								  $parameterType,
								  $dataType,
								  $precision,
								  $scale
								  );

			if (!$ok)
			{
				$this->_errorMsg  = @db2_stmt_errormsg();
				$this->_errorCode = @db2_stmt_error();

				if ($this->debug)
					ADOConnection::outp($this->_errorMsg);
				return false;
			}

			if ($this->debug)
				ADOConnection::outp("Correctly Bound parameter $spName to procedure");

			/*
			 * Build a variable in the current environment that matches
			 * the parameter name
			 */
			${$spName} = $spValue;

		}

		/*
		 * All bound, execute
		 */

		if (!@db2_execute($stmtid))
		{
			$this->_errorMsg = @db2_stmt_errormsg();
			$this->_errorCode = @db2_stmt_error();

			if ($this->debug)
				ADOConnection::outp($this->_errorMsg);
			return false;
		}

		/*
		 * We now take the changed parameters back into the
		 * stored procedures array where we can query them later
		 * Remember that $spValue was passed in by reference, so we
		 * can access the value in the variable that was originally
		 * passed to inParameter or outParameter
		 */
		foreach ($this->storedProcedureParameters['keyvalue'] as $spName=>$spValue)
		{
			/*
			 * We make it available to the environment
			 */
			$spValue = ${$spName};
			$this->storedProcedureParameters['keyvalue'][$spName] = $spValue;
		}

		return $stmtid;
	}

	/**
	 *
	 * Accepts an input or output parameter to bind to either a stored
	 * or prepared statements. For DB2, this should not be called as an
	 * API. always wrap with inParameter and outParameter
	 *
	 * @param mixed[] $stmt 		Statement returned by Prepare() or PrepareSP().
	 * @param mixed   $var 		PHP variable to bind to. Can set to null (for isNull support).
	 * @param string  $name 		Name of stored procedure variable name to bind to.
	 * @param int	 $isOutput 	optional) Indicates direction of parameter
	 * 							0/false=IN  1=OUT  2= IN/OUT
	 *							This is ignored for Stored Procedures
	 * @param int	$maxLen		(optional)Holds an maximum length of the variable.
	 *							This is ignored for Stored Procedures
	 * @param int	$type 		(optional) The data type of $var.
	 *							This is ignored for Stored Procedures
	 *
	 * @return bool				Success of the operation
	 */
	public function parameter(&$stmt, &$var, $name, $isOutput=false, $maxLen=4000, $type=false)
	{

		/*
		 * If the $stmt is the name of a stored procedure we are
		 * setting up, we will process it one way, otherwise
		 * we assume we are setting up a prepared statement
		*/
		if (is_array($stmt))
		{
			if ($this->debug)
				ADOConnection::outp("Adding parameter to stored procedure");
			if ($stmt[1] == $this->storedProcedureParameters['resource'])
				return $this->storedProcedureParameter($stmt[1],
														$var,
														$name,
														$isOutput,
														$maxLen,
														$type);

		}

		/*
		 * We are going to add a parameter to a prepared statement
		 */
		if ($this->debug)
			ADOConnection::outp("Adding parameter to prepared statement");
	}


	/**
	 * Prepares a prepared SQL statement, not used for stored procedures
	 *
	 * @param string	$sql
	 *
	 * @return mixed
	 */
	function prepare($sql)
	{

		if (! $this->_bindInputArray) return $sql; // no binding

		$stmt = @db2_prepare($this->_connectionID,$sql);
		if (!$stmt) {
			// we don't know whether db2 driver is parsing prepared stmts, so just return sql
			return $sql;
		}
		return array($sql,$stmt,false);
	}

	/**
	 * Executes a query
	 *
	 * @param	mixed $sql
	 * @param	mixed $inputarr	An optional array of parameters
	 *
	 * @return mixed				either the queryID or false
	 */
	function _query(&$sql,$inputarr=false)
	{

		GLOBAL $php_errormsg;

		if (isset($php_errormsg))
			$php_errormsg = '';
		$this->_error = '';

		$db2Options = array();
		/*
		 * Use DB2 Internal case handling for best speed
		 */
		switch(ADODB_ASSOC_CASE)
		{
		case ADODB_ASSOC_CASE_UPPER:
			$db2Options = array('db2_attr_case'=>DB2_CASE_UPPER);
			$setOption = @db2_set_option($this->_connectionID,$db2Options,1);
			break;

		 case ADODB_ASSOC_CASE_LOWER:
			$db2Options = array('db2_attr_case'=>DB2_CASE_LOWER);
			$setOption = @db2_set_option($this->_connectionID,$db2Options,1);
			break;

		default:
			$db2Options = array('db2_attr_case'=>DB2_CASE_NATURAL);
			$setOption = @db2_set_option($this->_connectionID,$db2Options,1);
		}

		if ($inputarr)
		{
			if (is_array($sql))
			{
				$stmtid = $sql[1];
			}
			else
			{
				$stmtid = @db2_prepare($this->_connectionID,$sql);

				if ($stmtid == false)
				{
					$this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
					return false;
				}
			}

			if (! @db2_execute($stmtid,$inputarr))
			{
				$this->_errorMsg = @db2_stmt_errormsg();
				$this->_errorCode = @db2_stmt_error();
				if ($this->debug)
					ADOConnection::outp($this->_errorMsg);
				return false;
			}

		}
		else if (is_array($sql))
		{

			/*
			 * Either a prepared statement or a stored procedure
			 */

			if (is_array($this->storedProcedureParameters)
				&& is_resource($this->storedProcedureParameters['resource']
			))
				/*
				 * This is all handled in the separate method for
				 * readability
				 */
				return $this->executeStoredProcedure();

			/*
			 * First, we prepare the statement
			 */
			$stmtid = @db2_prepare($this->_connectionID,$sql[0]);
			if (!$stmtid){
				$this->_errorMsg = @db2_stmt_errormsg();
				$this->_errorCode = @db2_stmt_error();
				if ($this->debug)
					ADOConnection::outp("Prepare failed: " . $this->_errorMsg);

				return false;
			}
			/*
			 * We next bind some input parameters
			 */
			$ordinal = 1;
			foreach ($sql[1] as $psVar=>$psVal){
				${$psVar} = $psVal;
				$ok = @db2_bind_param($stmtid, $ordinal, $psVar, DB2_PARAM_IN);
				if (!$ok)
				{
					$this->_errorMsg = @db2_stmt_errormsg();
					$this->_errorCode = @db2_stmt_error();
					if ($this->debug)
						ADOConnection::outp("Bind failed: " . $this->_errorMsg);
					return false;
				}
			}

			if (!@db2_execute($stmtid))
			{
				$this->_errorMsg = @db2_stmt_errormsg();
				$this->_errorCode = @db2_stmt_error();
				if ($this->debug)
					ADOConnection::outp($this->_errorMsg);
				return false;
			}

			return $stmtid;
		}
		else
		{

			$stmtid = @db2_exec($this->_connectionID,$sql);
		}
		$this->_lastAffectedRows = 0;
		if ($stmtid)
		{
			if (@db2_num_fields($stmtid) == 0)
			{
				$this->_lastAffectedRows = db2_num_rows($stmtid);
				$stmtid = true;
			}
			else
			{
				$this->_lastAffectedRows = 0;
			}

			$this->_errorMsg = '';
			$this->_errorCode = 0;

		}
		else
		{

			$this->_errorMsg = @db2_stmt_errormsg();
			$this->_errorCode = @db2_stmt_error();

		}
		return $stmtid;
	}

	/*
		Insert a null into the blob field of the table first.
		Then use UpdateBlob to store the blob.

		Usage:

		$conn->execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
		$conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
	*/
	function updateBlob($table,$column,$val,$where,$blobtype='BLOB')
	{
		return $this->execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;
	}

	// returns true or false
	function _close()
	{
		$ret = @db2_close($this->_connectionID);
		$this->_connectionID = false;
		return $ret;
	}

	function _affectedrows()
	{
		return $this->_lastAffectedRows;
	}

	/**
	 * Gets a meta cased parameter
	 *
	 * Receives an input variable to be processed per the metaCasing
	 * rule, and returns the same value, processed
	 *
	 * @param string $value
	 *
	 * @return string
	 */
	final public function getMetaCasedValue($value)
	{
		global $ADODB_ASSOC_CASE;

		switch($ADODB_ASSOC_CASE)
		{
		case ADODB_ASSOC_CASE_LOWER:
			$value = strtolower($value);
			break;
		case ADODB_ASSOC_CASE_UPPER:
			$value = strtoupper($value);
			break;
		}
		return $value;
	}


	const TABLECASE_LOWER    =  0;
	const TABLECASE_UPPER    =  1;
	const TABLECASE_DEFAULT  =  2;

	/**
	 * Controls the casing of the table provided to the meta functions
	 */
	private $tableCase = 2;

	/**
	 * Sets the table case parameter
	 *
	 * @param int $caseOption
	 * @return null
	 */
	final public function setTableCasing($caseOption)
	{
		$this->tableCase = $caseOption;
	}

	/**
	 * Gets the table casing parameter
	 *
	 * @return int $caseOption
	 */
	final public function getTableCasing()
	{
		return $this->tableCase;
	}

	/**
	 * Gets a table cased parameter
	 *
	 * Receives an input variable to be processed per the tableCasing
	 * rule, and returns the same value, processed
	 *
	 * @param string $value
	 *
	 * @return string
	 */
	final public function getTableCasedValue($value)
	{
		switch($this->tableCase)
		{
		case self::TABLECASE_LOWER:
			$value = strtolower($value);
			break;
		case self::TABLECASE_UPPER:
			$value = strtoupper($value);
			break;
		}
		return $value;
	}

}

/*--------------------------------------------------------------------------------------
	 Class Name: Recordset
--------------------------------------------------------------------------------------*/

class ADORecordSet_db2 extends ADORecordSet {

	var $bind = false;
	var $databaseType = "db2";
	var $dataProvider = "db2";
	var $useFetchArray;

	function __construct($id,$mode=false)
	{
		if ($mode === false) {
			global $ADODB_FETCH_MODE;
			$mode = $ADODB_FETCH_MODE;
		}
		$this->fetchMode = $mode;

		$this->_queryID = $id;
	}


	// returns the field object
	function fetchField($offset = 0)
	{
		$o			   = new ADOFieldObject();
		$o->name 	   = @db2_field_name($this->_queryID,$offset);
		$o->type 	   = @db2_field_type($this->_queryID,$offset);
		$o->max_length = @db2_field_width($this->_queryID,$offset);

		/*
		if (ADODB_ASSOC_CASE == 0)
			$o->name = strtolower($o->name);
		else if (ADODB_ASSOC_CASE == 1)
			$o->name = strtoupper($o->name);
		*/
		return $o;
	}

	/* Use associative array to get fields array */
	function fields($colname)
	{

		if ($this->fetchMode & ADODB_FETCH_ASSOC) {
			return $this->fields[$colname];
		}

		if (!$this->bind) {
			$this->bind = array();
			for ($i=0; $i < $this->_numOfFields; $i++) {
				$o = $this->FetchField($i);
				$this->bind[strtoupper($o->name)] = $i;
			}
		}

		 return $this->fields[$this->bind[strtoupper($colname)]];
	}


	function _initrs()
	{
		global $ADODB_COUNTRECS;
		$this->_numOfRows = ($ADODB_COUNTRECS) ? @db2_num_rows($this->_queryID) : -1;

		$this->_numOfFields = @db2_num_fields($this->_queryID);

		// some silly drivers such as db2 as/400 and intersystems cache return _numOfRows = 0

		if ($this->_numOfRows == 0)
			$this->_numOfRows = -1;
	}

	function _seek($row)
	{
		return false;
	}

	function getArrayLimit($nrows,$offset=0)
	{
		if ($offset <= 0) {
			$rs = $this->GetArray($nrows);
			return $rs;
		}

		$this->Move($offset);


		$results = array();
		$cnt = 0;
		while (!$this->EOF && $nrows != $cnt) {
			$results[$cnt++] = $this->fields;
			$this->MoveNext();
		}

		return $results;
	}

	function moveNext()
	{
		if ($this->EOF || $this->_numOfRows == 0)
			return false;

		$this->_currentRow++;

		$this->processCoreFetch();
		return $this->processMoveRecord();

	}

	private function processCoreFetch()
	{
		switch ($this->fetchMode){
		case ADODB_FETCH_ASSOC:

			/*
			 * Associative array
			 */
			$this->fields = @db2_fetch_assoc($this->_queryID);
			break;

		case ADODB_FETCH_BOTH:
			/*
			 * Fetch both numeric and Associative array
			 */
			$this->fields = @db2_fetch_both($this->_queryID);
			break;
		default:
			/*
			 * Numeric array
			 */
			$this->fields = @db2_fetch_array($this->_queryID);
			break;
		}
	}

	private function processMoveRecord()
	{
		if (!$this->fields){
			$this->EOF = true;
			return false;
		}

		return true;
	}

	function _fetch()
	{
		$this->processCoreFetch();
		if ($this->fields)
			return true;

		$this->fields = false;
		return false;
	}

	function _close()
	{
		$ok = @db2_free_result($this->_queryID);
		if (!$ok)
		{
			$this->_errorMsg  = @db2_stmt_errormsg($this->_queryId);
			$this->_errorCode = @db2_stmt_error();

			if ($this->debug)
				ADOConnection::outp($this->_errorMsg);
			return false;
		}

	}

}