]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB/adodb/drivers/adodb-mysql.inc.php
trailing_spaces
[SourceForge/phpwiki.git] / lib / WikiDB / adodb / drivers / adodb-mysql.inc.php
1 <?php
2 /*
3 V4.22 15 Apr 2004  (c) 2000-2004 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.
8
9   MySQL code that does not support transactions. Use mysqlt if you need transactions.
10   Requires mysql client. Works on Windows and Unix.
11
12  28 Feb 2001: MetaColumns bug fix - suggested by  Freek Dijkstra (phpeverywhere@macfreek.com)
13 */
14
15 if (! defined("_ADODB_MYSQL_LAYER")) {
16  define("_ADODB_MYSQL_LAYER", 1 );
17
18 class ADODB_mysql extends ADOConnection {
19         var $databaseType = 'mysql';
20         var $dataProvider = 'mysql';
21         var $hasInsertID = true;
22         var $hasAffectedRows = true;
23         var $metaTablesSQL = "SHOW TABLES";
24         var $metaColumnsSQL = "SHOW COLUMNS FROM %s";
25         var $fmtTimeStamp = "'Y-m-d H:i:s'";
26         var $hasLimit = true;
27         var $hasMoveFirst = true;
28         var $hasGenID = true;
29         var $upperCase = 'upper';
30         var $isoDates = true; // accepts dates in ISO format
31         var $sysDate = 'CURDATE()';
32         var $sysTimeStamp = 'NOW()';
33         var $hasTransactions = false;
34         var $forceNewConnect = false;
35         var $poorAffectedRows = true;
36         var $clientFlags = 0;
37         var $substr = "substring";
38         var $nameQuote = '`';           /// string to use to quote identifiers and names
39
40         function ADODB_mysql()
41         {
42         }
43
44         function ServerInfo()
45         {
46                 $arr['description'] = ADOConnection::GetOne("select version()");
47                 $arr['version'] = ADOConnection::_findvers($arr['description']);
48                 return $arr;
49         }
50
51         function IfNull( $field, $ifNull )
52         {
53                 return " IFNULL($field, $ifNull) "; // if MySQL
54         }
55
56         function &MetaTables($ttype=false,$showSchema=false,$mask=false)
57         {
58                 if ($mask) {
59                         $save = $this->metaTablesSQL;
60                         $mask = $this->qstr($mask);
61                         $this->metaTablesSQL .= " like $mask";
62                 }
63                 $ret =& ADOConnection::MetaTables($ttype,$showSchema);
64
65                 if ($mask) {
66                         $this->metaTablesSQL = $save;
67                 }
68                 return $ret;
69         }
70
71
72         function &MetaIndexes ($table, $primary = FALSE, $owner=false)
73         {
74         // save old fetch mode
75         global $ADODB_FETCH_MODE;
76
77         $save = $ADODB_FETCH_MODE;
78         $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
79         if ($this->fetchMode !== FALSE) {
80                $savem = $this->SetFetchMode(FALSE);
81         }
82
83         // get index details
84         $rs = $this->Execute(sprintf('SHOW INDEX FROM %s',$table));
85
86         // restore fetchmode
87         if (isset($savem)) {
88                 $this->SetFetchMode($savem);
89         }
90         $ADODB_FETCH_MODE = $save;
91
92         if (!is_object($rs)) {
93                 return FALSE;
94         }
95
96         $indexes = array ();
97
98         // parse index data into array
99         while ($row = $rs->FetchRow()) {
100                 if ($primary == FALSE AND $row[2] == 'PRIMARY') {
101                         continue;
102                 }
103
104                 if (!isset($indexes[$row[2]])) {
105                         $indexes[$row[2]] = array(
106                                 'unique' => ($row[1] == 0),
107                                 'columns' => array()
108                         );
109                 }
110
111                 $indexes[$row[2]]['columns'][$row[3] - 1] = $row[4];
112         }
113
114         // sort columns by order in the index
115         foreach ( array_keys ($indexes) as $index )
116         {
117                 ksort ($indexes[$index]['columns']);
118         }
119
120         return $indexes;
121         }
122
123
124         // if magic quotes disabled, use mysql_real_escape_string()
125         function qstr($s,$magic_quotes=false)
126         {
127                 if (!$magic_quotes) {
128
129                         if (ADODB_PHPVER >= 0x4300) {
130                                 if (is_resource($this->_connectionID))
131                                         return "'".mysql_real_escape_string($s,$this->_connectionID)."'";
132                         }
133                         if ($this->replaceQuote[0] == '\\'){
134                                 $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
135                         }
136                         return  "'".str_replace("'",$this->replaceQuote,$s)."'";
137                 }
138
139                 // undo magic quotes for "
140                 $s = str_replace('\\"','"',$s);
141                 return "'$s'";
142         }
143
144         function _insertid()
145         {
146                 return mysql_insert_id($this->_connectionID);
147         }
148
149         function GetOne($sql,$inputarr=false)
150         {
151                 $rs =& $this->SelectLimit($sql,1,-1,$inputarr);
152                 if ($rs) {
153                         $rs->Close();
154                         if ($rs->EOF) return false;
155                         return reset($rs->fields);
156                 }
157
158                 return false;
159         }
160
161         function _affectedrows()
162         {
163             return mysql_affected_rows($this->_connectionID);
164         }
165
166         // See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html
167         // Reference on Last_Insert_ID on the recommended way to simulate sequences
168         var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);";
169         var $_genSeqSQL = "create table %s (id int not null)";
170         var $_genSeq2SQL = "insert into %s values (%s)";
171         var $_dropSeqSQL = "drop table %s";
172
173         function CreateSequence($seqname='adodbseq',$startID=1)
174         {
175                 if (empty($this->_genSeqSQL)) return false;
176                 $u = strtoupper($seqname);
177
178                 $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));
179                 if (!$ok) return false;
180                 return $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
181         }
182
183
184         function GenID($seqname='adodbseq',$startID=1)
185         {
186                 // post-nuke sets hasGenID to false
187                 if (!$this->hasGenID) return false;
188
189                 $savelog = $this->_logsql;
190                 $this->_logsql = false;
191                 $getnext = sprintf($this->_genIDSQL,$seqname);
192                 $holdtransOK = $this->_transOK; // save the current status
193                 $rs = @$this->Execute($getnext);
194                 if (!$rs) {
195                         if ($holdtransOK) $this->_transOK = true; //if the status was ok before reset
196                         $u = strtoupper($seqname);
197                         $this->Execute(sprintf($this->_genSeqSQL,$seqname));
198                         $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
199                         $rs = $this->Execute($getnext);
200                 }
201                 $this->genID = mysql_insert_id($this->_connectionID);
202
203                 if ($rs) $rs->Close();
204
205                 $this->_logsql = $savelog;
206                 return $this->genID;
207         }
208
209         function &MetaDatabases()
210         {
211                 $qid = mysql_list_dbs($this->_connectionID);
212                 $arr = array();
213                 $i = 0;
214                 $max = mysql_num_rows($qid);
215                 while ($i < $max) {
216                         $db = mysql_tablename($qid,$i);
217                         if ($db != 'mysql') $arr[] = $db;
218                         $i += 1;
219                 }
220                 return $arr;
221         }
222
223
224         // Format date column in sql string given an input format that understands Y M D
225         function SQLDate($fmt, $col=false)
226         {
227                 if (!$col) $col = $this->sysTimeStamp;
228                 $s = 'DATE_FORMAT('.$col.",'";
229                 $concat = false;
230                 $len = strlen($fmt);
231                 for ($i=0; $i < $len; $i++) {
232                         $ch = $fmt[$i];
233                         switch($ch) {
234                         case 'Y':
235                         case 'y':
236                                 $s .= '%Y';
237                                 break;
238                         case 'Q':
239                         case 'q':
240                                 $s .= "'),Quarter($col)";
241
242                                 if ($len > $i+1) $s .= ",DATE_FORMAT($col,'";
243                                 else $s .= ",('";
244                                 $concat = true;
245                                 break;
246                         case 'M':
247                                 $s .= '%b';
248                                 break;
249
250                         case 'm':
251                                 $s .= '%m';
252                                 break;
253                         case 'D':
254                         case 'd':
255                                 $s .= '%d';
256                                 break;
257
258                         case 'H':
259                                 $s .= '%H';
260                                 break;
261
262                         case 'h':
263                                 $s .= '%I';
264                                 break;
265
266                         case 'i':
267                                 $s .= '%i';
268                                 break;
269
270                         case 's':
271                                 $s .= '%s';
272                                 break;
273
274                         case 'a':
275                         case 'A':
276                                 $s .= '%p';
277                                 break;
278
279                         default:
280
281                                 if ($ch == '\\') {
282                                         $i++;
283                                         $ch = substr($fmt,$i,1);
284                                 }
285                                 $s .= $ch;
286                                 break;
287                         }
288                 }
289                 $s.="')";
290                 if ($concat) $s = "CONCAT($s)";
291                 return $s;
292         }
293
294
295         // returns concatenated string
296         // much easier to run "mysqld --ansi" or "mysqld --sql-mode=PIPES_AS_CONCAT" and use || operator
297         function Concat()
298         {
299                 $s = "";
300                 $arr = func_get_args();
301
302                 // suggestion by andrew005@mnogo.ru
303                 $s = implode(',',$arr);
304                 if (strlen($s) > 0) return "CONCAT($s)";
305                 else return '';
306         }
307
308         function OffsetDate($dayFraction,$date=false)
309         {
310                 if (!$date) $date = $this->sysDate;
311                 return "from_unixtime(unix_timestamp($date)+($dayFraction)*24*3600)";
312         }
313
314         // returns true or false
315         function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
316         {
317                 if (ADODB_PHPVER >= 0x4300)
318                         $this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword,
319                                                                                                 $this->forceNewConnect,$this->clientFlags);
320                 else if (ADODB_PHPVER >= 0x4200)
321                         $this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword,
322                                                                                                 $this->forceNewConnect);
323                 else
324                         $this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword);
325
326                 if ($this->_connectionID === false) return false;
327                 if ($argDatabasename) return $this->SelectDB($argDatabasename);
328                 return true;
329         }
330
331         // returns true or false
332         function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
333         {
334                 if (ADODB_PHPVER >= 0x4300)
335                         $this->_connectionID = mysql_pconnect($argHostname,$argUsername,$argPassword,$this->clientFlags);
336                 else
337                         $this->_connectionID = mysql_pconnect($argHostname,$argUsername,$argPassword);
338                 if ($this->_connectionID === false) return false;
339                 if ($this->autoRollback) $this->RollbackTrans();
340                 if ($argDatabasename) return $this->SelectDB($argDatabasename);
341                 return true;
342         }
343
344         function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
345         {
346                 $this->forceNewConnect = true;
347                 return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename);
348         }
349
350         function &MetaColumns($table)
351         {
352
353                 if ($this->metaColumnsSQL) {
354                 global $ADODB_FETCH_MODE;
355
356                         $save = $ADODB_FETCH_MODE;
357                         $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
358                         if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
359
360                         $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));
361
362                         if (isset($savem)) $this->SetFetchMode($savem);
363                         $ADODB_FETCH_MODE = $save;
364
365                         if ($rs === false) return false;
366
367                         $retarr = array();
368                         while (!$rs->EOF){
369                                 $fld = new ADOFieldObject();
370                                 $fld->name = $rs->fields[0];
371                                 $type = $rs->fields[1];
372
373
374                                 // split type into type(length):
375                                 $fld->scale = null;
376                                 if (strpos($type,',') && preg_match("/^(.+)\((\d+),(\d+)/", $type, $query_array)) {
377                                         $fld->type = $query_array[1];
378                                         $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
379                                         $fld->scale = is_numeric($query_array[3]) ? $query_array[3] : -1;
380                                 } elseif (preg_match("/^(.+)\((\d+)/", $type, $query_array)) {
381                                         $fld->type = $query_array[1];
382                                         $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
383                                 } else {
384                                         $fld->max_length = -1;
385                                         $fld->type = $type;
386                                 }
387                                 /*
388                                 // split type into type(length):
389                                 if (preg_match("/^(.+)\((\d+)/", $type, $query_array)) {
390                                         $fld->type = $query_array[1];
391                                         $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
392                                 } else {
393                                         $fld->max_length = -1;
394                                         $fld->type = $type;
395                                 }*/
396                                 $fld->not_null = ($rs->fields[2] != 'YES');
397                                 $fld->primary_key = ($rs->fields[3] == 'PRI');
398                                 $fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);
399                                 $fld->binary = (strpos($fld->type,'blob') !== false);
400
401                                 if (!$fld->binary) {
402                                         $d = $rs->fields[4];
403                                         if ($d != "" && $d != "NULL") {
404                                                 $fld->has_default = true;
405                                                 $fld->default_value = $d;
406                                         } else {
407                                                 $fld->has_default = false;
408                                         }
409                                 }
410                                 if ($save == ADODB_FETCH_NUM) $retarr[] = $fld;
411                                 else $retarr[strtoupper($fld->name)] = $fld;
412                                 $rs->MoveNext();
413                         }
414                         $rs->Close();
415                         return $retarr;
416                 }
417                 return false;
418         }
419
420         // returns true or false
421         function SelectDB($dbName)
422         {
423                 $this->databaseName = $dbName;
424                 if ($this->_connectionID) {
425                         return @mysql_select_db($dbName,$this->_connectionID);
426                 }
427                 else return false;
428         }
429
430         // parameters use PostgreSQL convention, not MySQL
431         function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs=0)
432         {
433                 $offsetStr =($offset>=0) ? "$offset," : '';
434
435                 if ($secs)
436                         $rs =& $this->CacheExecute($secs,$sql." LIMIT $offsetStr$nrows",$inputarr);
437                 else
438                         $rs =& $this->Execute($sql." LIMIT $offsetStr$nrows",$inputarr);
439                 return $rs;
440         }
441
442
443         // returns queryID or false
444         function _query($sql,$inputarr)
445         {
446         //global $ADODB_COUNTRECS;
447                 //if($ADODB_COUNTRECS)
448                 return mysql_query($sql,$this->_connectionID);
449                 //else return @mysql_unbuffered_query($sql,$this->_connectionID); // requires PHP >= 4.0.6
450         }
451
452         /*      Returns: the last error message from previous database operation        */
453         function ErrorMsg()
454         {
455
456                 if ($this->_logsql) return $this->_errorMsg;
457                 if (empty($this->_connectionID)) $this->_errorMsg = @mysql_error();
458                 else $this->_errorMsg = @mysql_error($this->_connectionID);
459                 return $this->_errorMsg;
460         }
461
462         /*      Returns: the last error number from previous database operation */
463         function ErrorNo()
464         {
465                 if ($this->_logsql) return $this->_errorCode;
466                 if (empty($this->_connectionID))  return @mysql_errno();
467                 else return @mysql_errno($this->_connectionID);
468         }
469
470
471
472         // returns true or false
473         function _close()
474         {
475                 @mysql_close($this->_connectionID);
476                 $this->_connectionID = false;
477         }
478
479
480         /*
481         * Maximum size of C field
482         */
483         function CharMax()
484         {
485                 return 255;
486         }
487
488         /*
489         * Maximum size of X field
490         */
491         function TextMax()
492         {
493                 return 4294967295;
494         }
495
496 }
497
498 /*--------------------------------------------------------------------------------------
499          Class Name: Recordset
500 --------------------------------------------------------------------------------------*/
501
502 class ADORecordSet_mysql extends ADORecordSet{
503
504         var $databaseType = "mysql";
505         var $canSeek = true;
506
507         function ADORecordSet_mysql($queryID,$mode=false)
508         {
509                 if ($mode === false) {
510                         global $ADODB_FETCH_MODE;
511                         $mode = $ADODB_FETCH_MODE;
512                 }
513                 switch ($mode)
514                 {
515                 case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break;
516                 case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break;
517                 default:
518                 case ADODB_FETCH_DEFAULT:
519                 case ADODB_FETCH_BOTH:$this->fetchMode = MYSQL_BOTH; break;
520                 }
521
522                 $this->ADORecordSet($queryID);
523         }
524
525         function _initrs()
526         {
527         //GLOBAL $ADODB_COUNTRECS;
528         //      $this->_numOfRows = ($ADODB_COUNTRECS) ? @mysql_num_rows($this->_queryID):-1;
529                 $this->_numOfRows = @mysql_num_rows($this->_queryID);
530                 $this->_numOfFields = @mysql_num_fields($this->_queryID);
531         }
532
533         function &FetchField($fieldOffset = -1)
534         {
535
536                 if ($fieldOffset != -1) {
537                         $o = @mysql_fetch_field($this->_queryID, $fieldOffset);
538                         $f = @mysql_field_flags($this->_queryID,$fieldOffset);
539                         $o->max_length = @mysql_field_len($this->_queryID,$fieldOffset); // suggested by: Jim Nicholson (jnich@att.com)
540                         //$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable
541                         $o->binary = (strpos($f,'binary')!== false);
542                 }
543                 else if ($fieldOffset == -1) {  /*      The $fieldOffset argument is not provided thus its -1   */
544                         $o = @mysql_fetch_field($this->_queryID);
545                         $o->max_length = @mysql_field_len($this->_queryID); // suggested by: Jim Nicholson (jnich@att.com)
546                         //$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable
547                 }
548
549                 return $o;
550         }
551
552         function &GetRowAssoc($upper=true)
553         {
554                 if ($this->fetchMode == MYSQL_ASSOC && !$upper) return $this->fields;
555                 $row =& ADORecordSet::GetRowAssoc($upper);
556                 return $row;
557         }
558
559         /* Use associative array to get fields array */
560         function Fields($colname)
561         {
562                 // added @ by "Michael William Miller" <mille562@pilot.msu.edu>
563                 if ($this->fetchMode != MYSQL_NUM) return @$this->fields[$colname];
564
565                 if (!$this->bind) {
566                         $this->bind = array();
567                         for ($i=0; $i < $this->_numOfFields; $i++) {
568                                 $o = $this->FetchField($i);
569                                 $this->bind[strtoupper($o->name)] = $i;
570                         }
571                 }
572                  return $this->fields[$this->bind[strtoupper($colname)]];
573         }
574
575         function _seek($row)
576         {
577                 if ($this->_numOfRows == 0) return false;
578                 return @mysql_data_seek($this->_queryID,$row);
579         }
580
581
582         // 10% speedup to move MoveNext to child class
583         function MoveNext()
584         {
585         //global $ADODB_EXTENSION;if ($ADODB_EXTENSION) return adodb_movenext($this);
586
587                 if ($this->EOF) return false;
588
589                 $this->_currentRow++;
590                 $this->fields = @mysql_fetch_array($this->_queryID,$this->fetchMode);
591                 if (is_array($this->fields)) return true;
592
593                 $this->EOF = true;
594
595                 /* -- tested raising an error -- appears pointless
596                 $conn = $this->connection;
597                 if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) {
598                         $fn = $conn->raiseErrorFn;
599                         $fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database);
600                 }
601                 */
602                 return false;
603         }
604
605         function _fetch()
606         {
607                 $this->fields =  @mysql_fetch_array($this->_queryID,$this->fetchMode);
608                 return is_array($this->fields);
609         }
610
611         function _close() {
612                 @mysql_free_result($this->_queryID);
613                 $this->_queryID = false;
614         }
615
616         function MetaType($t,$len=-1,$fieldobj=false)
617         {
618                 if (is_object($t)) {
619                         $fieldobj = $t;
620                         $t = $fieldobj->type;
621                         $len = $fieldobj->max_length;
622                 }
623
624                 $len = -1; // mysql max_length is not accurate
625                 switch (strtoupper($t)) {
626                 case 'STRING':
627                 case 'CHAR':
628                 case 'VARCHAR':
629                 case 'TINYBLOB':
630                 case 'TINYTEXT':
631                 case 'ENUM':
632                 case 'SET':
633                         if ($len <= $this->blobSize) return 'C';
634
635                 case 'TEXT':
636                 case 'LONGTEXT':
637                 case 'MEDIUMTEXT':
638                         return 'X';
639
640                 // php_mysql extension always returns 'blob' even if 'text'
641                 // so we have to check whether binary...
642                 case 'IMAGE':
643                 case 'LONGBLOB':
644                 case 'BLOB':
645                 case 'MEDIUMBLOB':
646                         return !empty($fieldobj->binary) ? 'B' : 'X';
647
648                 case 'YEAR':
649                 case 'DATE': return 'D';
650
651                 case 'TIME':
652                 case 'DATETIME':
653                 case 'TIMESTAMP': return 'T';
654
655                 case 'INT':
656                 case 'INTEGER':
657                 case 'BIGINT':
658                 case 'TINYINT':
659                 case 'MEDIUMINT':
660                 case 'SMALLINT':
661
662                         if (!empty($fieldobj->primary_key)) return 'R';
663                         else return 'I';
664
665                 default: return 'N';
666                 }
667         }
668
669 }
670 }
671
672 // Local Variables:
673 // mode: php
674 // tab-width: 8
675 // c-basic-offset: 4
676 // c-hanging-comment-ender-p: nil
677 // indent-tabs-mode: nil
678 // End:
679 ?>