fix Row size too large error, change varchar(255) to TEXT
[openemr.git] / gacl / adodb / drivers / adodb-mysql.inc.php
blob7a7f3416eccc8abe5050c0dafc6bd8cd619317b9
1 <?php
2 /*
3 V4.92a 29 Aug 2006 (c) 2000-2006 John Lim (jlim#natsoft.com.my). 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 8.
9 MySQL code that does not support transactions. Use mysqlt if you need transactions.
10 Requires mysql client. Works on Windows and Unix.
12 28 Feb 2001: MetaColumns bug fix - suggested by Freek Dijkstra (phpeverywhere@macfreek.com)
13 */
15 // security - hide paths
16 if (!defined('ADODB_DIR')) die();
18 if (! defined("_ADODB_MYSQL_LAYER")) {
19 define("_ADODB_MYSQL_LAYER", 1 );
21 class ADODB_mysql extends ADOConnection {
22 var $databaseType = 'mysql';
23 var $dataProvider = 'mysql';
24 var $hasInsertID = true;
25 var $hasAffectedRows = true;
26 var $metaTablesSQL = "SHOW TABLES";
27 var $metaColumnsSQL = "SHOW COLUMNS FROM `%s`";
28 var $fmtTimeStamp = "'Y-m-d H:i:s'";
29 var $hasLimit = true;
30 var $hasMoveFirst = true;
31 var $hasGenID = true;
32 var $isoDates = true; // accepts dates in ISO format
33 var $sysDate = 'CURDATE()';
34 var $sysTimeStamp = 'NOW()';
35 var $hasTransactions = false;
36 var $forceNewConnect = false;
37 var $poorAffectedRows = true;
38 var $clientFlags = 0;
39 var $substr = "substring";
40 var $nameQuote = '`'; /// string to use to quote identifiers and names
41 var $compat323 = false; // true if compat with mysql 3.23
43 function ADODB_mysql()
45 if (defined('ADODB_EXTENSION')) $this->rsPrefix .= 'ext_';
48 function ServerInfo()
50 $arr['description'] = ADOConnection::GetOne("select version()");
51 $arr['version'] = ADOConnection::_findvers($arr['description']);
52 return $arr;
55 function IfNull( $field, $ifNull )
57 return " IFNULL($field, $ifNull) "; // if MySQL
61 function &MetaTables($ttype=false,$showSchema=false,$mask=false)
63 $save = $this->metaTablesSQL;
64 if ($showSchema && is_string($showSchema)) {
65 $this->metaTablesSQL .= " from $showSchema";
68 if ($mask) {
69 $mask = $this->qstr($mask);
70 $this->metaTablesSQL .= " like $mask";
72 $ret =& ADOConnection::MetaTables($ttype,$showSchema);
74 $this->metaTablesSQL = $save;
75 return $ret;
79 function &MetaIndexes ($table, $primary = FALSE, $owner=false)
81 // save old fetch mode
82 global $ADODB_FETCH_MODE;
84 $false = false;
85 $save = $ADODB_FETCH_MODE;
86 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
87 if ($this->fetchMode !== FALSE) {
88 $savem = $this->SetFetchMode(FALSE);
91 // get index details
92 $rs = $this->Execute(sprintf('SHOW INDEX FROM %s',$table));
94 // restore fetchmode
95 if (isset($savem)) {
96 $this->SetFetchMode($savem);
98 $ADODB_FETCH_MODE = $save;
100 if (!is_object($rs)) {
101 return $false;
104 $indexes = array ();
106 // parse index data into array
107 while ($row = $rs->FetchRow()) {
108 if ($primary == FALSE AND $row[2] == 'PRIMARY') {
109 continue;
112 if (!isset($indexes[$row[2]])) {
113 $indexes[$row[2]] = array(
114 'unique' => ($row[1] == 0),
115 'columns' => array()
119 $indexes[$row[2]]['columns'][$row[3] - 1] = $row[4];
122 // sort columns by order in the index
123 foreach ( array_keys ($indexes) as $index )
125 ksort ($indexes[$index]['columns']);
128 return $indexes;
132 // if magic quotes disabled, use mysql_real_escape_string()
133 function qstr($s,$magic_quotes=false)
135 if (!$magic_quotes) {
137 if (ADODB_PHPVER >= 0x4300) {
138 if (is_resource($this->_connectionID))
139 return "'".mysql_real_escape_string($s,$this->_connectionID)."'";
141 if ($this->replaceQuote[0] == '\\'){
142 $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
144 return "'".str_replace("'",$this->replaceQuote,$s)."'";
147 // undo magic quotes for "
148 $s = str_replace('\\"','"',$s);
149 return "'$s'";
152 function _insertid()
154 return ADOConnection::GetOne('SELECT LAST_INSERT_ID()');
155 //return mysql_insert_id($this->_connectionID);
158 function GetOne($sql,$inputarr=false)
160 if ($this->compat323 == false && strncasecmp($sql,'sele',4) == 0) {
161 $rs =& $this->SelectLimit($sql,1,-1,$inputarr);
162 if ($rs) {
163 $rs->Close();
164 if ($rs->EOF) return false;
165 return reset($rs->fields);
167 } else {
168 return ADOConnection::GetOne($sql,$inputarr);
170 return false;
173 function BeginTrans()
175 if ($this->debug) ADOConnection::outp("Transactions not supported in 'mysql' driver. Use 'mysqlt' or 'mysqli' driver");
178 function _affectedrows()
180 return mysql_affected_rows($this->_connectionID);
183 // See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html
184 // Reference on Last_Insert_ID on the recommended way to simulate sequences
185 var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);";
186 var $_genSeqSQL = "create table %s (id int not null)";
187 var $_genSeq2SQL = "insert into %s values (%s)";
188 var $_dropSeqSQL = "drop table %s";
190 function CreateSequence($seqname='adodbseq',$startID=1)
192 if (empty($this->_genSeqSQL)) return false;
193 $u = strtoupper($seqname);
195 $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));
196 if (!$ok) return false;
197 return $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
201 function GenID($seqname='adodbseq',$startID=1)
203 // post-nuke sets hasGenID to false
204 if (!$this->hasGenID) return false;
206 $savelog = $this->_logsql;
207 $this->_logsql = false;
208 $getnext = sprintf($this->_genIDSQL,$seqname);
209 $holdtransOK = $this->_transOK; // save the current status
210 $rs = @$this->Execute($getnext);
211 if (!$rs) {
212 if ($holdtransOK) $this->_transOK = true; //if the status was ok before reset
213 $u = strtoupper($seqname);
214 $this->Execute(sprintf($this->_genSeqSQL,$seqname));
215 $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
216 $rs = $this->Execute($getnext);
218 $this->genID = mysql_insert_id($this->_connectionID);
220 if ($rs) $rs->Close();
222 $this->_logsql = $savelog;
223 return $this->genID;
226 function &MetaDatabases()
228 $qid = mysql_list_dbs($this->_connectionID);
229 $arr = array();
230 $i = 0;
231 $max = mysql_num_rows($qid);
232 while ($i < $max) {
233 $db = mysql_tablename($qid,$i);
234 if ($db != 'mysql') $arr[] = $db;
235 $i += 1;
237 return $arr;
241 // Format date column in sql string given an input format that understands Y M D
242 function SQLDate($fmt, $col=false)
244 if (!$col) $col = $this->sysTimeStamp;
245 $s = 'DATE_FORMAT('.$col.",'";
246 $concat = false;
247 $len = strlen($fmt);
248 for ($i=0; $i < $len; $i++) {
249 $ch = $fmt[$i];
250 switch($ch) {
252 default:
253 if ($ch == '\\') {
254 $i++;
255 $ch = substr($fmt,$i,1);
257 /** FALL THROUGH */
258 case '-':
259 case '/':
260 $s .= $ch;
261 break;
263 case 'Y':
264 case 'y':
265 $s .= '%Y';
266 break;
267 case 'M':
268 $s .= '%b';
269 break;
271 case 'm':
272 $s .= '%m';
273 break;
274 case 'D':
275 case 'd':
276 $s .= '%d';
277 break;
279 case 'Q':
280 case 'q':
281 $s .= "'),Quarter($col)";
283 if ($len > $i+1) $s .= ",DATE_FORMAT($col,'";
284 else $s .= ",('";
285 $concat = true;
286 break;
288 case 'H':
289 $s .= '%H';
290 break;
292 case 'h':
293 $s .= '%I';
294 break;
296 case 'i':
297 $s .= '%i';
298 break;
300 case 's':
301 $s .= '%s';
302 break;
304 case 'a':
305 case 'A':
306 $s .= '%p';
307 break;
309 case 'w':
310 $s .= '%w';
311 break;
313 case 'W':
314 $s .= '%U';
315 break;
317 case 'l':
318 $s .= '%W';
319 break;
322 $s.="')";
323 if ($concat) $s = "CONCAT($s)";
324 return $s;
328 // returns concatenated string
329 // much easier to run "mysqld --ansi" or "mysqld --sql-mode=PIPES_AS_CONCAT" and use || operator
330 function Concat()
332 $s = "";
333 $arr = func_get_args();
335 // suggestion by andrew005@mnogo.ru
336 $s = implode(',',$arr);
337 if (strlen($s) > 0) return "CONCAT($s)";
338 else return '';
341 function OffsetDate($dayFraction,$date=false)
343 if (!$date) $date = $this->sysDate;
345 $fraction = $dayFraction * 24 * 3600;
346 return $date . ' + INTERVAL ' . $fraction.' SECOND';
348 // return "from_unixtime(unix_timestamp($date)+$fraction)";
351 // returns true or false
352 function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
354 if (!empty($this->port)) $argHostname .= ":".$this->port;
356 if (ADODB_PHPVER >= 0x4300)
357 $this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword,
358 $this->forceNewConnect,$this->clientFlags);
359 else if (ADODB_PHPVER >= 0x4200)
360 $this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword,
361 $this->forceNewConnect);
362 else
363 $this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword);
365 if ($this->_connectionID === false) return false;
366 if ($argDatabasename) return $this->SelectDB($argDatabasename);
367 return true;
370 // returns true or false
371 function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
373 if (!empty($this->port)) $argHostname .= ":".$this->port;
375 if (ADODB_PHPVER >= 0x4300)
376 $this->_connectionID = mysql_pconnect($argHostname,$argUsername,$argPassword,$this->clientFlags);
377 else
378 $this->_connectionID = mysql_pconnect($argHostname,$argUsername,$argPassword);
379 if ($this->_connectionID === false) return false;
380 if ($this->autoRollback) $this->RollbackTrans();
381 if ($argDatabasename) return $this->SelectDB($argDatabasename);
382 return true;
385 function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
387 $this->forceNewConnect = true;
388 return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename);
391 function &MetaColumns($table)
393 $this->_findschema($table,$schema);
394 if ($schema) {
395 $dbName = $this->database;
396 $this->SelectDB($schema);
398 global $ADODB_FETCH_MODE;
399 $save = $ADODB_FETCH_MODE;
400 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
402 if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
403 $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));
405 if ($schema) {
406 $this->SelectDB($dbName);
409 if (isset($savem)) $this->SetFetchMode($savem);
410 $ADODB_FETCH_MODE = $save;
411 if (!is_object($rs)) {
412 $false = false;
413 return $false;
416 $retarr = array();
417 while (!$rs->EOF){
418 $fld = new ADOFieldObject();
419 $fld->name = $rs->fields[0];
420 $type = $rs->fields[1];
422 // split type into type(length):
423 $fld->scale = null;
424 if (preg_match("/^(.+)\((\d+),(\d+)/", $type, $query_array)) {
425 $fld->type = $query_array[1];
426 $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
427 $fld->scale = is_numeric($query_array[3]) ? $query_array[3] : -1;
428 } elseif (preg_match("/^(.+)\((\d+)/", $type, $query_array)) {
429 $fld->type = $query_array[1];
430 $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
431 } elseif (preg_match("/^(enum)\((.*)\)$/i", $type, $query_array)) {
432 $fld->type = $query_array[1];
433 $arr = explode(",",$query_array[2]);
434 $fld->enums = $arr;
435 $zlen = max(array_map("strlen",$arr)) - 2; // PHP >= 4.0.6
436 $fld->max_length = ($zlen > 0) ? $zlen : 1;
437 } else {
438 $fld->type = $type;
439 $fld->max_length = -1;
441 $fld->not_null = ($rs->fields[2] != 'YES');
442 $fld->primary_key = ($rs->fields[3] == 'PRI');
443 $fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);
444 $fld->binary = (strpos($type,'blob') !== false);
445 $fld->unsigned = (strpos($type,'unsigned') !== false);
447 if (!$fld->binary) {
448 $d = $rs->fields[4];
449 if ($d != '' && $d != 'NULL') {
450 $fld->has_default = true;
451 $fld->default_value = $d;
452 } else {
453 $fld->has_default = false;
457 if ($save == ADODB_FETCH_NUM) {
458 $retarr[] = $fld;
459 } else {
460 $retarr[strtoupper($fld->name)] = $fld;
462 $rs->MoveNext();
465 $rs->Close();
466 return $retarr;
469 // returns true or false
470 function SelectDB($dbName)
472 $this->database = $dbName;
473 $this->databaseName = $dbName; # obsolete, retained for compat with older adodb versions
474 if ($this->_connectionID) {
475 return @mysql_select_db($dbName,$this->_connectionID);
477 else return false;
480 // parameters use PostgreSQL convention, not MySQL
481 function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs=0)
483 $offsetStr =($offset>=0) ? ((integer)$offset)."," : '';
484 // jason judge, see http://phplens.com/lens/lensforum/msgs.php?id=9220
485 if ($nrows < 0) $nrows = '18446744073709551615';
487 if ($secs)
488 $rs =& $this->CacheExecute($secs,$sql." LIMIT $offsetStr".((integer)$nrows),$inputarr);
489 else
490 $rs =& $this->Execute($sql." LIMIT $offsetStr".((integer)$nrows),$inputarr);
491 return $rs;
494 // returns queryID or false
495 function _query($sql,$inputarr)
497 //global $ADODB_COUNTRECS;
498 //if($ADODB_COUNTRECS)
499 return mysql_query($sql,$this->_connectionID);
500 //else return @mysql_unbuffered_query($sql,$this->_connectionID); // requires PHP >= 4.0.6
503 /* Returns: the last error message from previous database operation */
504 function ErrorMsg()
507 if ($this->_logsql) return $this->_errorMsg;
508 if (empty($this->_connectionID)) $this->_errorMsg = @mysql_error();
509 else $this->_errorMsg = @mysql_error($this->_connectionID);
510 return $this->_errorMsg;
513 /* Returns: the last error number from previous database operation */
514 function ErrorNo()
516 if ($this->_logsql) return $this->_errorCode;
517 if (empty($this->_connectionID)) return @mysql_errno();
518 else return @mysql_errno($this->_connectionID);
521 // returns true or false
522 function _close()
524 @mysql_close($this->_connectionID);
525 $this->_connectionID = false;
530 * Maximum size of C field
532 function CharMax()
534 return 255;
538 * Maximum size of X field
540 function TextMax()
542 return 4294967295;
545 // "Innox - Juan Carlos Gonzalez" <jgonzalez#innox.com.mx>
546 function MetaForeignKeys( $table, $owner = FALSE, $upper = FALSE, $associative = FALSE )
548 global $ADODB_FETCH_MODE;
549 if ($ADODB_FETCH_MODE == ADODB_FETCH_ASSOC || $this->fetchMode == ADODB_FETCH_ASSOC) $associative = true;
551 if ( !empty($owner) ) {
552 $table = "$owner.$table";
554 $a_create_table = $this->getRow(sprintf('SHOW CREATE TABLE %s', $table));
555 if ($associative) $create_sql = $a_create_table["Create Table"];
556 else $create_sql = $a_create_table[1];
558 $matches = array();
560 if (!preg_match_all("/FOREIGN KEY \(`(.*?)`\) REFERENCES `(.*?)` \(`(.*?)`\)/", $create_sql, $matches)) return false;
561 $foreign_keys = array();
562 $num_keys = count($matches[0]);
563 for ( $i = 0; $i < $num_keys; $i ++ ) {
564 $my_field = explode('`, `', $matches[1][$i]);
565 $ref_table = $matches[2][$i];
566 $ref_field = explode('`, `', $matches[3][$i]);
568 if ( $upper ) {
569 $ref_table = strtoupper($ref_table);
572 $foreign_keys[$ref_table] = array();
573 $num_fields = count($my_field);
574 for ( $j = 0; $j < $num_fields; $j ++ ) {
575 if ( $associative ) {
576 $foreign_keys[$ref_table][$ref_field[$j]] = $my_field[$j];
577 } else {
578 $foreign_keys[$ref_table][] = "{$my_field[$j]}={$ref_field[$j]}";
583 return $foreign_keys;
589 /*--------------------------------------------------------------------------------------
590 Class Name: Recordset
591 --------------------------------------------------------------------------------------*/
594 class ADORecordSet_mysql extends ADORecordSet{
596 var $databaseType = "mysql";
597 var $canSeek = true;
599 function ADORecordSet_mysql($queryID,$mode=false)
601 if ($mode === false) {
602 global $ADODB_FETCH_MODE;
603 $mode = $ADODB_FETCH_MODE;
605 switch ($mode)
607 case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break;
608 case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break;
609 case ADODB_FETCH_DEFAULT:
610 case ADODB_FETCH_BOTH:
611 default:
612 $this->fetchMode = MYSQL_BOTH; break;
614 $this->adodbFetchMode = $mode;
615 $this->ADORecordSet($queryID);
618 function _initrs()
620 //GLOBAL $ADODB_COUNTRECS;
621 // $this->_numOfRows = ($ADODB_COUNTRECS) ? @mysql_num_rows($this->_queryID):-1;
622 $this->_numOfRows = @mysql_num_rows($this->_queryID);
623 $this->_numOfFields = @mysql_num_fields($this->_queryID);
626 function &FetchField($fieldOffset = -1)
628 if ($fieldOffset != -1) {
629 $o = @mysql_fetch_field($this->_queryID, $fieldOffset);
630 $f = @mysql_field_flags($this->_queryID,$fieldOffset);
631 $o->max_length = @mysql_field_len($this->_queryID,$fieldOffset); // suggested by: Jim Nicholson (jnich@att.com)
632 //$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable
633 $o->binary = (strpos($f,'binary')!== false);
635 else if ($fieldOffset == -1) { /* The $fieldOffset argument is not provided thus its -1 */
636 $o = @mysql_fetch_field($this->_queryID);
637 $o->max_length = @mysql_field_len($this->_queryID); // suggested by: Jim Nicholson (jnich@att.com)
638 //$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable
641 return $o;
644 function &GetRowAssoc($upper=true)
646 if ($this->fetchMode == MYSQL_ASSOC && !$upper) $row = $this->fields;
647 else $row =& ADORecordSet::GetRowAssoc($upper);
648 return $row;
651 /* Use associative array to get fields array */
652 function Fields($colname)
654 // added @ by "Michael William Miller" <mille562@pilot.msu.edu>
655 if ($this->fetchMode != MYSQL_NUM) return @$this->fields[$colname];
657 if (!$this->bind) {
658 $this->bind = array();
659 for ($i=0; $i < $this->_numOfFields; $i++) {
660 $o = $this->FetchField($i);
661 $this->bind[strtoupper($o->name)] = $i;
664 return $this->fields[$this->bind[strtoupper($colname)]];
667 function _seek($row)
669 if ($this->_numOfRows == 0) return false;
670 return @mysql_data_seek($this->_queryID,$row);
673 function MoveNext()
675 //return adodb_movenext($this);
676 //if (defined('ADODB_EXTENSION')) return adodb_movenext($this);
677 if (@$this->fields = mysql_fetch_array($this->_queryID,$this->fetchMode)) {
678 $this->_currentRow += 1;
679 return true;
681 if (!$this->EOF) {
682 $this->_currentRow += 1;
683 $this->EOF = true;
685 return false;
688 function _fetch()
690 $this->fields = @mysql_fetch_array($this->_queryID,$this->fetchMode);
691 return is_array($this->fields);
694 function _close() {
695 @mysql_free_result($this->_queryID);
696 $this->_queryID = false;
699 function MetaType($t,$len=-1,$fieldobj=false)
701 if (is_object($t)) {
702 $fieldobj = $t;
703 $t = $fieldobj->type;
704 $len = $fieldobj->max_length;
707 $len = -1; // mysql max_length is not accurate
708 switch (strtoupper($t)) {
709 case 'STRING':
710 case 'CHAR':
711 case 'VARCHAR':
712 case 'TINYBLOB':
713 case 'TINYTEXT':
714 case 'ENUM':
715 case 'SET':
716 if ($len <= $this->blobSize) return 'C';
718 case 'TEXT':
719 case 'LONGTEXT':
720 case 'MEDIUMTEXT':
721 return 'X';
723 // php_mysql extension always returns 'blob' even if 'text'
724 // so we have to check whether binary...
725 case 'IMAGE':
726 case 'LONGBLOB':
727 case 'BLOB':
728 case 'MEDIUMBLOB':
729 return !empty($fieldobj->binary) ? 'B' : 'X';
731 case 'YEAR':
732 case 'DATE': return 'D';
734 case 'TIME':
735 case 'DATETIME':
736 case 'TIMESTAMP': return 'T';
738 case 'INT':
739 case 'INTEGER':
740 case 'BIGINT':
741 case 'TINYINT':
742 case 'MEDIUMINT':
743 case 'SMALLINT':
745 if (!empty($fieldobj->primary_key)) return 'R';
746 else return 'I';
748 default: return 'N';
754 class ADORecordSet_ext_mysql extends ADORecordSet_mysql {
755 function ADORecordSet_ext_mysql($queryID,$mode=false)
757 if ($mode === false) {
758 global $ADODB_FETCH_MODE;
759 $mode = $ADODB_FETCH_MODE;
761 switch ($mode)
763 case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break;
764 case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break;
765 case ADODB_FETCH_DEFAULT:
766 case ADODB_FETCH_BOTH:
767 default:
768 $this->fetchMode = MYSQL_BOTH; break;
770 $this->adodbFetchMode = $mode;
771 $this->ADORecordSet($queryID);
774 function MoveNext()
776 return @adodb_movenext($this);