fix for escaping in the code search popup
[openemr.git] / library / adodb / drivers / adodb-odbc.inc.php
blob9089616cbb7de08ff9f4dea2ef2852686929e794
1 <?php
2 /*
3 V5.14 8 Sept 2011 (c) 2000-2011 John Lim (jlim#natsoft.com). All rights reserved.
4 Released under both BSD license and Lesser GPL library license.
5 Whenever there is any discrepancy between the two licenses,
6 the BSD license will take precedence.
7 Set tabs to 4 for best viewing.
9 Latest version is available at http://adodb.sourceforge.net
11 Requires ODBC. Works on Windows and Unix.
13 // security - hide paths
14 if (!defined('ADODB_DIR')) die();
16 define("_ADODB_ODBC_LAYER", 2 );
18 /*--------------------------------------------------------------------------------------
19 --------------------------------------------------------------------------------------*/
22 class ADODB_odbc extends ADOConnection {
23 var $databaseType = "odbc";
24 var $fmtDate = "'Y-m-d'";
25 var $fmtTimeStamp = "'Y-m-d, h:i:sA'";
26 var $replaceQuote = "''"; // string to use to replace quotes
27 var $dataProvider = "odbc";
28 var $hasAffectedRows = true;
29 var $binmode = ODBC_BINMODE_RETURN;
30 var $useFetchArray = false; // setting this to true will make array elements in FETCH_ASSOC mode case-sensitive
31 // breaking backward-compat
32 //var $longreadlen = 8000; // default number of chars to return for a Blob/Long field
33 var $_bindInputArray = false;
34 var $curmode = SQL_CUR_USE_DRIVER; // See sqlext.h, SQL_CUR_DEFAULT == SQL_CUR_USE_DRIVER == 2L
35 var $_genSeqSQL = "create table %s (id integer)";
36 var $_autocommit = true;
37 var $_haserrorfunctions = true;
38 var $_has_stupid_odbc_fetch_api_change = true;
39 var $_lastAffectedRows = 0;
40 var $uCaseTables = true; // for meta* functions, uppercase table names
42 function ADODB_odbc()
44 $this->_haserrorfunctions = ADODB_PHPVER >= 0x4050;
45 $this->_has_stupid_odbc_fetch_api_change = ADODB_PHPVER >= 0x4200;
48 // returns true or false
49 function _connect($argDSN, $argUsername, $argPassword, $argDatabasename)
51 global $php_errormsg;
53 if (!function_exists('odbc_connect')) return null;
55 if ($this->debug && $argDatabasename && $this->databaseType != 'vfp') {
56 ADOConnection::outp("For odbc Connect(), $argDatabasename is not used. Place dsn in 1st parameter.");
58 if (isset($php_errormsg)) $php_errormsg = '';
59 if ($this->curmode === false) $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword);
60 else $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword,$this->curmode);
61 $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
62 if (isset($this->connectStmt)) $this->Execute($this->connectStmt);
64 return $this->_connectionID != false;
67 // returns true or false
68 function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)
70 global $php_errormsg;
72 if (!function_exists('odbc_connect')) return null;
74 if (isset($php_errormsg)) $php_errormsg = '';
75 $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
76 if ($this->debug && $argDatabasename) {
77 ADOConnection::outp("For odbc PConnect(), $argDatabasename is not used. Place dsn in 1st parameter.");
79 // print "dsn=$argDSN u=$argUsername p=$argPassword<br>"; flush();
80 if ($this->curmode === false) $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword);
81 else $this->_connectionID = odbc_pconnect($argDSN,$argUsername,$argPassword,$this->curmode);
83 $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
84 if ($this->_connectionID && $this->autoRollback) @odbc_rollback($this->_connectionID);
85 if (isset($this->connectStmt)) $this->Execute($this->connectStmt);
87 return $this->_connectionID != false;
91 function ServerInfo()
94 if (!empty($this->host) && ADODB_PHPVER >= 0x4300) {
95 $dsn = strtoupper($this->host);
96 $first = true;
97 $found = false;
99 if (!function_exists('odbc_data_source')) return false;
101 while(true) {
103 $rez = @odbc_data_source($this->_connectionID,
104 $first ? SQL_FETCH_FIRST : SQL_FETCH_NEXT);
105 $first = false;
106 if (!is_array($rez)) break;
107 if (strtoupper($rez['server']) == $dsn) {
108 $found = true;
109 break;
112 if (!$found) return ADOConnection::ServerInfo();
113 if (!isset($rez['version'])) $rez['version'] = '';
114 return $rez;
115 } else {
116 return ADOConnection::ServerInfo();
121 function CreateSequence($seqname='adodbseq',$start=1)
123 if (empty($this->_genSeqSQL)) return false;
124 $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));
125 if (!$ok) return false;
126 $start -= 1;
127 return $this->Execute("insert into $seqname values($start)");
130 var $_dropSeqSQL = 'drop table %s';
131 function DropSequence($seqname)
133 if (empty($this->_dropSeqSQL)) return false;
134 return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
138 This algorithm is not very efficient, but works even if table locking
139 is not available.
141 Will return false if unable to generate an ID after $MAXLOOPS attempts.
143 function GenID($seq='adodbseq',$start=1)
145 // if you have to modify the parameter below, your database is overloaded,
146 // or you need to implement generation of id's yourself!
147 $MAXLOOPS = 100;
148 //$this->debug=1;
149 while (--$MAXLOOPS>=0) {
150 $num = $this->GetOne("select id from $seq");
151 if ($num === false) {
152 $this->Execute(sprintf($this->_genSeqSQL ,$seq));
153 $start -= 1;
154 $num = '0';
155 $ok = $this->Execute("insert into $seq values($start)");
156 if (!$ok) return false;
158 $this->Execute("update $seq set id=id+1 where id=$num");
160 if ($this->affected_rows() > 0) {
161 $num += 1;
162 $this->genID = $num;
163 return $num;
164 } elseif ($this->affected_rows() == 0) {
165 // some drivers do not return a valid value => try with another method
166 $value = $this->GetOne("select id from $seq");
167 if ($value == $num + 1) {
168 return $value;
172 if ($fn = $this->raiseErrorFn) {
173 $fn($this->databaseType,'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts",$seq,$num);
175 return false;
179 function ErrorMsg()
181 if ($this->_haserrorfunctions) {
182 if ($this->_errorMsg !== false) return $this->_errorMsg;
183 if (empty($this->_connectionID)) return @odbc_errormsg();
184 return @odbc_errormsg($this->_connectionID);
185 } else return ADOConnection::ErrorMsg();
188 function ErrorNo()
191 if ($this->_haserrorfunctions) {
192 if ($this->_errorCode !== false) {
193 // bug in 4.0.6, error number can be corrupted string (should be 6 digits)
194 return (strlen($this->_errorCode)<=2) ? 0 : $this->_errorCode;
197 if (empty($this->_connectionID)) $e = @odbc_error();
198 else $e = @odbc_error($this->_connectionID);
200 // bug in 4.0.6, error number can be corrupted string (should be 6 digits)
201 // so we check and patch
202 if (strlen($e)<=2) return 0;
203 return $e;
204 } else return ADOConnection::ErrorNo();
209 function BeginTrans()
211 if (!$this->hasTransactions) return false;
212 if ($this->transOff) return true;
213 $this->transCnt += 1;
214 $this->_autocommit = false;
215 return odbc_autocommit($this->_connectionID,false);
218 function CommitTrans($ok=true)
220 if ($this->transOff) return true;
221 if (!$ok) return $this->RollbackTrans();
222 if ($this->transCnt) $this->transCnt -= 1;
223 $this->_autocommit = true;
224 $ret = odbc_commit($this->_connectionID);
225 odbc_autocommit($this->_connectionID,true);
226 return $ret;
229 function RollbackTrans()
231 if ($this->transOff) return true;
232 if ($this->transCnt) $this->transCnt -= 1;
233 $this->_autocommit = true;
234 $ret = odbc_rollback($this->_connectionID);
235 odbc_autocommit($this->_connectionID,true);
236 return $ret;
239 function MetaPrimaryKeys($table)
241 global $ADODB_FETCH_MODE;
243 if ($this->uCaseTables) $table = strtoupper($table);
244 $schema = '';
245 $this->_findschema($table,$schema);
247 $savem = $ADODB_FETCH_MODE;
248 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
249 $qid = @odbc_primarykeys($this->_connectionID,'',$schema,$table);
251 if (!$qid) {
252 $ADODB_FETCH_MODE = $savem;
253 return false;
255 $rs = new ADORecordSet_odbc($qid);
256 $ADODB_FETCH_MODE = $savem;
258 if (!$rs) return false;
259 $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
261 $arr = $rs->GetArray();
262 $rs->Close();
263 //print_r($arr);
264 $arr2 = array();
265 for ($i=0; $i < sizeof($arr); $i++) {
266 if ($arr[$i][3]) $arr2[] = $arr[$i][3];
268 return $arr2;
273 function MetaTables($ttype=false)
275 global $ADODB_FETCH_MODE;
277 $savem = $ADODB_FETCH_MODE;
278 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
279 $qid = odbc_tables($this->_connectionID);
281 $rs = new ADORecordSet_odbc($qid);
283 $ADODB_FETCH_MODE = $savem;
284 if (!$rs) {
285 $false = false;
286 return $false;
288 $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
290 $arr = $rs->GetArray();
291 //print_r($arr);
293 $rs->Close();
294 $arr2 = array();
296 if ($ttype) {
297 $isview = strncmp($ttype,'V',1) === 0;
299 for ($i=0; $i < sizeof($arr); $i++) {
300 if (!$arr[$i][2]) continue;
301 $type = $arr[$i][3];
302 if ($ttype) {
303 if ($isview) {
304 if (strncmp($type,'V',1) === 0) $arr2[] = $arr[$i][2];
305 } else if (strncmp($type,'SYS',3) !== 0) $arr2[] = $arr[$i][2];
306 } else if (strncmp($type,'SYS',3) !== 0) $arr2[] = $arr[$i][2];
308 return $arr2;
312 See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odbc/htm/odbcdatetime_data_type_changes.asp
313 / SQL data type codes /
314 #define SQL_UNKNOWN_TYPE 0
315 #define SQL_CHAR 1
316 #define SQL_NUMERIC 2
317 #define SQL_DECIMAL 3
318 #define SQL_INTEGER 4
319 #define SQL_SMALLINT 5
320 #define SQL_FLOAT 6
321 #define SQL_REAL 7
322 #define SQL_DOUBLE 8
323 #if (ODBCVER >= 0x0300)
324 #define SQL_DATETIME 9
325 #endif
326 #define SQL_VARCHAR 12
329 / One-parameter shortcuts for date/time data types /
330 #if (ODBCVER >= 0x0300)
331 #define SQL_TYPE_DATE 91
332 #define SQL_TYPE_TIME 92
333 #define SQL_TYPE_TIMESTAMP 93
335 #define SQL_UNICODE (-95)
336 #define SQL_UNICODE_VARCHAR (-96)
337 #define SQL_UNICODE_LONGVARCHAR (-97)
339 function ODBCTypes($t)
341 switch ((integer)$t) {
342 case 1:
343 case 12:
344 case 0:
345 case -95:
346 case -96:
347 return 'C';
348 case -97:
349 case -1: //text
350 return 'X';
351 case -4: //image
352 return 'B';
354 case 9:
355 case 91:
356 return 'D';
358 case 10:
359 case 11:
360 case 92:
361 case 93:
362 return 'T';
364 case 4:
365 case 5:
366 case -6:
367 return 'I';
369 case -11: // uniqidentifier
370 return 'R';
371 case -7: //bit
372 return 'L';
374 default:
375 return 'N';
379 function MetaColumns($table, $normalize=true)
381 global $ADODB_FETCH_MODE;
383 $false = false;
384 if ($this->uCaseTables) $table = strtoupper($table);
385 $schema = '';
386 $this->_findschema($table,$schema);
388 $savem = $ADODB_FETCH_MODE;
389 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
391 /*if (false) { // after testing, confirmed that the following does not work becoz of a bug
392 $qid2 = odbc_tables($this->_connectionID);
393 $rs = new ADORecordSet_odbc($qid2);
394 $ADODB_FETCH_MODE = $savem;
395 if (!$rs) return false;
396 $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
397 $rs->_fetch();
399 while (!$rs->EOF) {
400 if ($table == strtoupper($rs->fields[2])) {
401 $q = $rs->fields[0];
402 $o = $rs->fields[1];
403 break;
405 $rs->MoveNext();
407 $rs->Close();
409 $qid = odbc_columns($this->_connectionID,$q,$o,strtoupper($table),'%');
410 } */
412 switch ($this->databaseType) {
413 case 'access':
414 case 'vfp':
415 $qid = odbc_columns($this->_connectionID);#,'%','',strtoupper($table),'%');
416 break;
419 case 'db2':
420 $colname = "%";
421 $qid = odbc_columns($this->_connectionID, "", $schema, $table, $colname);
422 break;
424 default:
425 $qid = @odbc_columns($this->_connectionID,'%','%',strtoupper($table),'%');
426 if (empty($qid)) $qid = odbc_columns($this->_connectionID);
427 break;
429 if (empty($qid)) return $false;
431 $rs = new ADORecordSet_odbc($qid);
432 $ADODB_FETCH_MODE = $savem;
434 if (!$rs) return $false;
435 $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
436 $rs->_fetch();
438 $retarr = array();
441 $rs->fields indices
442 0 TABLE_QUALIFIER
443 1 TABLE_SCHEM
444 2 TABLE_NAME
445 3 COLUMN_NAME
446 4 DATA_TYPE
447 5 TYPE_NAME
448 6 PRECISION
449 7 LENGTH
450 8 SCALE
451 9 RADIX
452 10 NULLABLE
453 11 REMARKS
455 while (!$rs->EOF) {
456 // adodb_pr($rs->fields);
457 if (strtoupper(trim($rs->fields[2])) == $table && (!$schema || strtoupper($rs->fields[1]) == $schema)) {
458 $fld = new ADOFieldObject();
459 $fld->name = $rs->fields[3];
460 $fld->type = $this->ODBCTypes($rs->fields[4]);
462 // ref: http://msdn.microsoft.com/library/default.asp?url=/archive/en-us/dnaraccgen/html/msdn_odk.asp
463 // access uses precision to store length for char/varchar
464 if ($fld->type == 'C' or $fld->type == 'X') {
465 if ($this->databaseType == 'access')
466 $fld->max_length = $rs->fields[6];
467 else if ($rs->fields[4] <= -95) // UNICODE
468 $fld->max_length = $rs->fields[7]/2;
469 else
470 $fld->max_length = $rs->fields[7];
471 } else
472 $fld->max_length = $rs->fields[7];
473 $fld->not_null = !empty($rs->fields[10]);
474 $fld->scale = $rs->fields[8];
475 $retarr[strtoupper($fld->name)] = $fld;
476 } else if (sizeof($retarr)>0)
477 break;
478 $rs->MoveNext();
480 $rs->Close(); //-- crashes 4.03pl1 -- why?
482 if (empty($retarr)) $retarr = false;
483 return $retarr;
486 function Prepare($sql)
488 if (! $this->_bindInputArray) return $sql; // no binding
489 $stmt = odbc_prepare($this->_connectionID,$sql);
490 if (!$stmt) {
491 // we don't know whether odbc driver is parsing prepared stmts, so just return sql
492 return $sql;
494 return array($sql,$stmt,false);
497 /* returns queryID or false */
498 function _query($sql,$inputarr=false)
500 GLOBAL $php_errormsg;
501 if (isset($php_errormsg)) $php_errormsg = '';
502 $this->_error = '';
504 if ($inputarr) {
505 if (is_array($sql)) {
506 $stmtid = $sql[1];
507 } else {
508 $stmtid = odbc_prepare($this->_connectionID,$sql);
510 if ($stmtid == false) {
511 $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
512 return false;
516 if (! odbc_execute($stmtid,$inputarr)) {
517 //@odbc_free_result($stmtid);
518 if ($this->_haserrorfunctions) {
519 $this->_errorMsg = odbc_errormsg();
520 $this->_errorCode = odbc_error();
522 return false;
525 } else if (is_array($sql)) {
526 $stmtid = $sql[1];
527 if (!odbc_execute($stmtid)) {
528 //@odbc_free_result($stmtid);
529 if ($this->_haserrorfunctions) {
530 $this->_errorMsg = odbc_errormsg();
531 $this->_errorCode = odbc_error();
533 return false;
535 } else
536 $stmtid = odbc_exec($this->_connectionID,$sql);
538 $this->_lastAffectedRows = 0;
539 if ($stmtid) {
540 if (@odbc_num_fields($stmtid) == 0) {
541 $this->_lastAffectedRows = odbc_num_rows($stmtid);
542 $stmtid = true;
543 } else {
544 $this->_lastAffectedRows = 0;
545 odbc_binmode($stmtid,$this->binmode);
546 odbc_longreadlen($stmtid,$this->maxblobsize);
549 if ($this->_haserrorfunctions) {
550 $this->_errorMsg = '';
551 $this->_errorCode = 0;
552 } else
553 $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
554 } else {
555 if ($this->_haserrorfunctions) {
556 $this->_errorMsg = odbc_errormsg();
557 $this->_errorCode = odbc_error();
558 } else
559 $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
561 return $stmtid;
565 Insert a null into the blob field of the table first.
566 Then use UpdateBlob to store the blob.
568 Usage:
570 $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
571 $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
573 function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
575 return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;
578 // returns true or false
579 function _close()
581 $ret = @odbc_close($this->_connectionID);
582 $this->_connectionID = false;
583 return $ret;
586 function _affectedrows()
588 return $this->_lastAffectedRows;
593 /*--------------------------------------------------------------------------------------
594 Class Name: Recordset
595 --------------------------------------------------------------------------------------*/
597 class ADORecordSet_odbc extends ADORecordSet {
599 var $bind = false;
600 var $databaseType = "odbc";
601 var $dataProvider = "odbc";
602 var $useFetchArray;
603 var $_has_stupid_odbc_fetch_api_change;
605 function ADORecordSet_odbc($id,$mode=false)
607 if ($mode === false) {
608 global $ADODB_FETCH_MODE;
609 $mode = $ADODB_FETCH_MODE;
611 $this->fetchMode = $mode;
613 $this->_queryID = $id;
615 // the following is required for mysql odbc driver in 4.3.1 -- why?
616 $this->EOF = false;
617 $this->_currentRow = -1;
618 //$this->ADORecordSet($id);
622 // returns the field object
623 function FetchField($fieldOffset = -1)
626 $off=$fieldOffset+1; // offsets begin at 1
628 $o= new ADOFieldObject();
629 $o->name = @odbc_field_name($this->_queryID,$off);
630 $o->type = @odbc_field_type($this->_queryID,$off);
631 $o->max_length = @odbc_field_len($this->_queryID,$off);
632 if (ADODB_ASSOC_CASE == 0) $o->name = strtolower($o->name);
633 else if (ADODB_ASSOC_CASE == 1) $o->name = strtoupper($o->name);
634 return $o;
637 /* Use associative array to get fields array */
638 function Fields($colname)
640 if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];
641 if (!$this->bind) {
642 $this->bind = array();
643 for ($i=0; $i < $this->_numOfFields; $i++) {
644 $o = $this->FetchField($i);
645 $this->bind[strtoupper($o->name)] = $i;
649 return $this->fields[$this->bind[strtoupper($colname)]];
653 function _initrs()
655 global $ADODB_COUNTRECS;
656 $this->_numOfRows = ($ADODB_COUNTRECS) ? @odbc_num_rows($this->_queryID) : -1;
657 $this->_numOfFields = @odbc_num_fields($this->_queryID);
658 // some silly drivers such as db2 as/400 and intersystems cache return _numOfRows = 0
659 if ($this->_numOfRows == 0) $this->_numOfRows = -1;
660 //$this->useFetchArray = $this->connection->useFetchArray;
661 $this->_has_stupid_odbc_fetch_api_change = ADODB_PHPVER >= 0x4200;
664 function _seek($row)
666 return false;
669 // speed up SelectLimit() by switching to ADODB_FETCH_NUM as ADODB_FETCH_ASSOC is emulated
670 function GetArrayLimit($nrows,$offset=-1)
672 if ($offset <= 0) {
673 $rs = $this->GetArray($nrows);
674 return $rs;
676 $savem = $this->fetchMode;
677 $this->fetchMode = ADODB_FETCH_NUM;
678 $this->Move($offset);
679 $this->fetchMode = $savem;
681 if ($this->fetchMode & ADODB_FETCH_ASSOC) {
682 $this->fields = $this->GetRowAssoc(ADODB_ASSOC_CASE);
685 $results = array();
686 $cnt = 0;
687 while (!$this->EOF && $nrows != $cnt) {
688 $results[$cnt++] = $this->fields;
689 $this->MoveNext();
692 return $results;
696 function MoveNext()
698 if ($this->_numOfRows != 0 && !$this->EOF) {
699 $this->_currentRow++;
701 if ($this->_has_stupid_odbc_fetch_api_change)
702 $rez = @odbc_fetch_into($this->_queryID,$this->fields);
703 else {
704 $row = 0;
705 $rez = @odbc_fetch_into($this->_queryID,$row,$this->fields);
707 if ($rez) {
708 if ($this->fetchMode & ADODB_FETCH_ASSOC) {
709 $this->fields = $this->GetRowAssoc(ADODB_ASSOC_CASE);
711 return true;
714 $this->fields = false;
715 $this->EOF = true;
716 return false;
719 function _fetch()
722 if ($this->_has_stupid_odbc_fetch_api_change)
723 $rez = @odbc_fetch_into($this->_queryID,$this->fields);
724 else {
725 $row = 0;
726 $rez = @odbc_fetch_into($this->_queryID,$row,$this->fields);
728 if ($rez) {
729 if ($this->fetchMode & ADODB_FETCH_ASSOC) {
730 $this->fields = $this->GetRowAssoc(ADODB_ASSOC_CASE);
732 return true;
734 $this->fields = false;
735 return false;
738 function _close()
740 return @odbc_free_result($this->_queryID);