Merge branch 'master' into wip_leon_T8050_add_shenzen_SZ_to_ISIN
[pear] / DB / mysql.php
1 <?php
2
3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
4
5 /**
6  * The PEAR DB driver for PHP's mysql extension
7  * for interacting with MySQL databases
8  *
9  * PHP versions 4 and 5
10  *
11  * LICENSE: This source file is subject to version 3.0 of the PHP license
12  * that is available through the world-wide-web at the following URI:
13  * http://www.php.net/license/3_0.txt.  If you did not receive a copy of
14  * the PHP License and are unable to obtain it through the web, please
15  * send a note to license@php.net so we can mail you a copy immediately.
16  *
17  * @category   Database
18  * @package    DB
19  * @author     Stig Bakken <ssb@php.net>
20  * @author     Daniel Convissor <danielc@php.net>
21  * @copyright  1997-2007 The PHP Group
22  * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
23  * @version    CVS: $Id: mysql.php 242769 2007-09-21 13:32:52Z aharvey $
24  * @link       http://pear.php.net/package/DB
25  */
26
27 /**
28  * Obtain the DB_common class so it can be extended from
29  */
30 require_once 'DB/common.php';
31
32 /**
33  * The methods PEAR DB uses to interact with PHP's mysql extension
34  * for interacting with MySQL databases
35  *
36  * These methods overload the ones declared in DB_common.
37  *
38  * @category   Database
39  * @package    DB
40  * @author     Stig Bakken <ssb@php.net>
41  * @author     Daniel Convissor <danielc@php.net>
42  * @copyright  1997-2007 The PHP Group
43  * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
44  * @version    Release: 1.7.14
45  * @link       http://pear.php.net/package/DB
46  */
47 class DB_mysql extends DB_common
48 {
49     // {{{ properties
50
51     /**
52      * The DB driver type (mysql, oci8, odbc, etc.)
53      * @var string
54      */
55     var $phptype = 'mysql';
56
57     /**
58      * The database syntax variant to be used (db2, access, etc.), if any
59      * @var string
60      */
61     var $dbsyntax = 'mysql';
62
63     /**
64      * The capabilities of this DB implementation
65      *
66      * The 'new_link' element contains the PHP version that first provided
67      * new_link support for this DBMS.  Contains false if it's unsupported.
68      *
69      * Meaning of the 'limit' element:
70      *   + 'emulate' = emulate with fetch row by number
71      *   + 'alter'   = alter the query
72      *   + false     = skip rows
73      *
74      * @var array
75      */
76     var $features = array(
77         'limit'         => 'alter',
78         'new_link'      => '4.2.0',
79         'numrows'       => true,
80         'pconnect'      => true,
81         'prepare'       => false,
82         'ssl'           => false,
83         'transactions'  => true,
84     );
85
86     /**
87      * A mapping of native error codes to DB error codes
88      * @var array
89      */
90     var $errorcode_map = array(
91         1004 => DB_ERROR_CANNOT_CREATE,
92         1005 => DB_ERROR_CANNOT_CREATE,
93         1006 => DB_ERROR_CANNOT_CREATE,
94         1007 => DB_ERROR_ALREADY_EXISTS,
95         1008 => DB_ERROR_CANNOT_DROP,
96         1022 => DB_ERROR_ALREADY_EXISTS,
97         1044 => DB_ERROR_ACCESS_VIOLATION,
98         1046 => DB_ERROR_NODBSELECTED,
99         1048 => DB_ERROR_CONSTRAINT,
100         1049 => DB_ERROR_NOSUCHDB,
101         1050 => DB_ERROR_ALREADY_EXISTS,
102         1051 => DB_ERROR_NOSUCHTABLE,
103         1054 => DB_ERROR_NOSUCHFIELD,
104         1061 => DB_ERROR_ALREADY_EXISTS,
105         1062 => DB_ERROR_ALREADY_EXISTS,
106         1064 => DB_ERROR_SYNTAX,
107         1091 => DB_ERROR_NOT_FOUND,
108         1100 => DB_ERROR_NOT_LOCKED,
109         1136 => DB_ERROR_VALUE_COUNT_ON_ROW,
110         1142 => DB_ERROR_ACCESS_VIOLATION,
111         1146 => DB_ERROR_NOSUCHTABLE,
112         1216 => DB_ERROR_CONSTRAINT,
113         1217 => DB_ERROR_CONSTRAINT,
114         1356 => DB_ERROR_DIVZERO,
115         1451 => DB_ERROR_CONSTRAINT,
116         1452 => DB_ERROR_CONSTRAINT,
117     );
118
119     /**
120      * The raw database connection created by PHP
121      * @var resource
122      */
123     var $connection;
124
125     /**
126      * The DSN information for connecting to a database
127      * @var array
128      */
129     var $dsn = array();
130
131
132     /**
133      * Should data manipulation queries be committed automatically?
134      * @var bool
135      * @access private
136      */
137     var $autocommit = true;
138
139     /**
140      * The quantity of transactions begun
141      *
142      * {@internal  While this is private, it can't actually be designated
143      * private in PHP 5 because it is directly accessed in the test suite.}}
144      *
145      * @var integer
146      * @access private
147      */
148     var $transaction_opcount = 0;
149
150     /**
151      * The database specified in the DSN
152      *
153      * It's a fix to allow calls to different databases in the same script.
154      *
155      * @var string
156      * @access private
157      */
158     var $_db = '';
159
160
161     // }}}
162     // {{{ constructor
163
164     /**
165      * This constructor calls <kbd>$this->DB_common()</kbd>
166      *
167      * @return void
168      */
169     function DB_mysql()
170     {
171         parent::__construct(); 
172     }
173
174     // }}}
175     // {{{ connect()
176
177     /**
178      * Connect to the database server, log in and open the database
179      *
180      * Don't call this method directly.  Use DB::connect() instead.
181      *
182      * PEAR DB's mysql driver supports the following extra DSN options:
183      *   + new_link      If set to true, causes subsequent calls to connect()
184      *                    to return a new connection link instead of the
185      *                    existing one.  WARNING: this is not portable to
186      *                    other DBMS's. Available since PEAR DB 1.7.0.
187      *   + client_flags  Any combination of MYSQL_CLIENT_* constants.
188      *                    Only used if PHP is at version 4.3.0 or greater.
189      *                    Available since PEAR DB 1.7.0.
190      *
191      * @param array $dsn         the data source name
192      * @param bool  $persistent  should the connection be persistent?
193      *
194      * @return int  DB_OK on success. A DB_Error object on failure.
195      */
196     function connect($dsn, $persistent = false)
197     {
198         if (!PEAR::loadExtension('mysql')) {
199             return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
200         }
201
202         $this->dsn = $dsn;
203         if ($dsn['dbsyntax']) {
204             $this->dbsyntax = $dsn['dbsyntax'];
205         }
206
207         $params = array();
208         if ($dsn['protocol'] && $dsn['protocol'] == 'unix') {
209             $params[0] = ':' . $dsn['socket'];
210         } else {
211             $params[0] = $dsn['hostspec'] ? $dsn['hostspec']
212                          : 'localhost';
213             if ($dsn['port']) {
214                 $params[0] .= ':' . $dsn['port'];
215             }
216         }
217         $params[] = $dsn['username'] ? $dsn['username'] : null;
218         $params[] = $dsn['password'] ? $dsn['password'] : null;
219
220         if (!$persistent) {
221             if (isset($dsn['new_link'])
222                 && ($dsn['new_link'] == 'true' || $dsn['new_link'] === true))
223             {
224                 $params[] = true;
225             } else {
226                 $params[] = false;
227             }
228         }
229         if (version_compare(phpversion(), '4.3.0', '>=')) {
230             $params[] = isset($dsn['client_flags'])
231                         ? $dsn['client_flags'] : null;
232         }
233
234         $connect_function = $persistent ? 'mysql_pconnect' : 'mysql_connect';
235
236         $ini = ini_get('track_errors');
237         $php_errormsg = '';
238         if ($ini) {
239             $this->connection = @call_user_func_array($connect_function,
240                                                       $params);
241         } else {
242             @ini_set('track_errors', 1);
243             $this->connection = @call_user_func_array($connect_function,
244                                                       $params);
245             @ini_set('track_errors', $ini);
246         }
247
248         if (!$this->connection) {
249             if (($err = @mysql_error()) != '') {
250                 return $this->raiseError(DB_ERROR_CONNECT_FAILED,
251                                          null, null, null, 
252                                          $err);
253             } else {
254                 return $this->raiseError(DB_ERROR_CONNECT_FAILED,
255                                          null, null, null,
256                                          $php_errormsg);
257             }
258         }
259         
260         //mysql_set_charset('utf8', $this->connection);
261         
262         if ($dsn['database']) {
263             if (!@mysql_select_db($dsn['database'], $this->connection)) {
264                 return $this->mysqlRaiseError();
265             }
266             $this->_db = $dsn['database'];
267         }
268
269         return DB_OK;
270     }
271
272     // }}}
273     // {{{ disconnect()
274
275     /**
276      * Disconnects from the database server
277      *
278      * @return bool  TRUE on success, FALSE on failure
279      */
280     function disconnect()
281     {
282         $ret = @mysql_close($this->connection);
283         $this->connection = null;
284         return $ret;
285     }
286
287     // }}}
288     // {{{ simpleQuery()
289
290     /**
291      * Sends a query to the database server
292      *
293      * Generally uses mysql_query().  If you want to use
294      * mysql_unbuffered_query() set the "result_buffering" option to 0 using
295      * setOptions().  This option was added in Release 1.7.0.
296      *
297      * @param string  the SQL query string
298      *
299      * @return mixed  + a PHP result resrouce for successful SELECT queries
300      *                + the DB_OK constant for other successful queries
301      *                + a DB_Error object on failure
302      */
303     function simpleQuery($query)
304     {
305         $ismanip = $this->_checkManip($query);
306         $this->last_query = $query;
307         $query = $this->modifyQuery($query);
308         if ($this->_db) {
309             if (!@mysql_select_db($this->_db, $this->connection)) {
310                 return $this->mysqlRaiseError(DB_ERROR_NODBSELECTED);
311             }
312         }
313         if (!$this->autocommit && $ismanip || $query == 'BEGIN') {
314             if ($this->transaction_opcount == 0) {
315                 
316                // echo "SET AUTOCOMMIT=0/nBEGIN\n";
317                 $result = @mysql_query('SET AUTOCOMMIT=0', $this->connection);
318                 $result = @mysql_query('BEGIN', $this->connection);
319                 if (!$result) {
320                     return $this->mysqlRaiseError();
321                 }
322             }
323             $this->transaction_opcount++;
324         }
325         if (!$this->options['result_buffering']) {
326             $result = @mysql_unbuffered_query($query, $this->connection);
327         } else {
328             $result = @mysql_query($query, $this->connection);
329         }
330         if (!$result) {
331             return $this->mysqlRaiseError();
332         }
333         if (is_resource($result)) {
334             return $result;
335         }
336         return DB_OK;
337     }
338
339     // }}}
340     // {{{ nextResult()
341
342     /**
343      * Move the internal mysql result pointer to the next available result
344      *
345      * This method has not been implemented yet.
346      *
347      * @param a valid sql result resource
348      *
349      * @return false
350      */
351     function nextResult($result)
352     {
353         return false;
354     }
355
356     // }}}
357     // {{{ fetchInto()
358
359     /**
360      * Places a row from the result set into the given array
361      *
362      * Formating of the array and the data therein are configurable.
363      * See DB_result::fetchInto() for more information.
364      *
365      * This method is not meant to be called directly.  Use
366      * DB_result::fetchInto() instead.  It can't be declared "protected"
367      * because DB_result is a separate object.
368      *
369      * @param resource $result    the query result resource
370      * @param array    $arr       the referenced array to put the data in
371      * @param int      $fetchmode how the resulting array should be indexed
372      * @param int      $rownum    the row number to fetch (0 = first row)
373      *
374      * @return mixed  DB_OK on success, NULL when the end of a result set is
375      *                 reached or on failure
376      *
377      * @see DB_result::fetchInto()
378      */
379     function fetchInto($result, &$arr, $fetchmode, $rownum = null)
380     {
381         if ($rownum !== null) {
382             if (!@mysql_data_seek($result, $rownum)) {
383                 return null;
384             }
385         }
386         if ($fetchmode & DB_FETCHMODE_ASSOC) {
387             $arr = @mysql_fetch_array($result, MYSQL_ASSOC);
388             if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
389                 $arr = array_change_key_case($arr, CASE_LOWER);
390             }
391         } else {
392             $arr = @mysql_fetch_row($result);
393         }
394         if (!$arr) {
395             return null;
396         }
397         if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
398             /*
399              * Even though this DBMS already trims output, we do this because
400              * a field might have intentional whitespace at the end that
401              * gets removed by DB_PORTABILITY_RTRIM under another driver.
402              */
403             $this->_rtrimArrayValues($arr);
404         }
405         if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
406             $this->_convertNullArrayValuesToEmpty($arr);
407         }
408         return DB_OK;
409     }
410
411     // }}}
412     // {{{ freeResult()
413
414     /**
415      * Deletes the result set and frees the memory occupied by the result set
416      *
417      * This method is not meant to be called directly.  Use
418      * DB_result::free() instead.  It can't be declared "protected"
419      * because DB_result is a separate object.
420      *
421      * @param resource $result  PHP's query result resource
422      *
423      * @return bool  TRUE on success, FALSE if $result is invalid
424      *
425      * @see DB_result::free()
426      */
427     function freeResult($result)
428     {
429         return is_resource($result) ? mysql_free_result($result) : false;
430     }
431
432     // }}}
433     // {{{ numCols()
434
435     /**
436      * Gets the number of columns in a result set
437      *
438      * This method is not meant to be called directly.  Use
439      * DB_result::numCols() instead.  It can't be declared "protected"
440      * because DB_result is a separate object.
441      *
442      * @param resource $result  PHP's query result resource
443      *
444      * @return int  the number of columns.  A DB_Error object on failure.
445      *
446      * @see DB_result::numCols()
447      */
448     function numCols($result)
449     {
450         $cols = @mysql_num_fields($result);
451         if (!$cols) {
452             return $this->mysqlRaiseError();
453         }
454         return $cols;
455     }
456
457     // }}}
458     // {{{ numRows()
459
460     /**
461      * Gets the number of rows in a result set
462      *
463      * This method is not meant to be called directly.  Use
464      * DB_result::numRows() instead.  It can't be declared "protected"
465      * because DB_result is a separate object.
466      *
467      * @param resource $result  PHP's query result resource
468      *
469      * @return int  the number of rows.  A DB_Error object on failure.
470      *
471      * @see DB_result::numRows()
472      */
473     function numRows($result)
474     {
475         $rows = @mysql_num_rows($result);
476         if ($rows === null) {
477             return $this->mysqlRaiseError();
478         }
479         return $rows;
480     }
481
482     // }}}
483     // {{{ autoCommit()
484
485     /**
486      * Enables or disables automatic commits
487      *
488      * @param bool $onoff  true turns it on, false turns it off
489      *
490      * @return int  DB_OK on success.  A DB_Error object if the driver
491      *               doesn't support auto-committing transactions.
492      */
493     function autoCommit($onoff = false)
494     {
495         // XXX if $this->transaction_opcount > 0, we should probably
496         // issue a warning here.
497         $this->autocommit = $onoff ? true : false;
498         return DB_OK;
499     }
500
501     // }}}
502     // {{{ commit()
503
504     /**
505      * Commits the current transaction
506      *
507      * @return int  DB_OK on success.  A DB_Error object on failure.
508      */
509     function commit()
510     {
511         if ($this->transaction_opcount > 0) {
512             if ($this->_db) {
513                 if (!@mysql_select_db($this->_db, $this->connection)) {
514                     return $this->mysqlRaiseError(DB_ERROR_NODBSELECTED);
515                 }
516             }
517             //echo "COMMIT / SET AUTOCOMMIT=1\n";
518             $result = @mysql_query('COMMIT', $this->connection);
519             $result = @mysql_query('SET AUTOCOMMIT=1', $this->connection);
520             $this->transaction_opcount = 0;
521             if (!$result) {
522                 return $this->mysqlRaiseError();
523             }
524         }
525         return DB_OK;
526     }
527
528     // }}}
529     // {{{ rollback()
530
531     /**
532      * Reverts the current transaction
533      *
534      * @return int  DB_OK on success.  A DB_Error object on failure.
535      */
536     function rollback()
537     {
538         if ($this->transaction_opcount > 0) {
539             if ($this->_db) {
540                 if (!@mysql_select_db($this->_db, $this->connection)) {
541                     return $this->mysqlRaiseError(DB_ERROR_NODBSELECTED);
542                 }
543             }
544             //   echo "ROLLBACK / SET AUTOCOMMIT=1\n";
545             $result = @mysql_query('ROLLBACK', $this->connection);
546             $result = @mysql_query('SET AUTOCOMMIT=1', $this->connection);
547             $this->transaction_opcount = 0;
548             if (!$result) {
549                 return $this->mysqlRaiseError();
550             }
551         }
552         return DB_OK;
553     }
554
555     // }}}
556     // {{{ affectedRows()
557
558     /**
559      * Determines the number of rows affected by a data maniuplation query
560      *
561      * 0 is returned for queries that don't manipulate data.
562      *
563      * @return int  the number of rows.  A DB_Error object on failure.
564      */
565     function affectedRows()
566     {
567         if ($this->_last_query_manip) {
568             return @mysql_affected_rows($this->connection);
569         } else {
570             return 0;
571         }
572      }
573
574     // }}}
575     // {{{ nextId()
576
577     /**
578      * Returns the next free id in a sequence
579      *
580      * @param string  $seq_name  name of the sequence
581      * @param boolean $ondemand  when true, the seqence is automatically
582      *                            created if it does not exist
583      *
584      * @return int  the next id number in the sequence.
585      *               A DB_Error object on failure.
586      *
587      * @see DB_common::nextID(), DB_common::getSequenceName(),
588      *      DB_mysql::createSequence(), DB_mysql::dropSequence()
589      */
590     function nextId($seq_name, $ondemand = true)
591     {
592         $seqname = $this->getSequenceName($seq_name);
593         do {
594             $repeat = 0;
595             $this->pushErrorHandling(PEAR_ERROR_RETURN);
596             $result = $this->query("UPDATE ${seqname} ".
597                                    'SET id=LAST_INSERT_ID(id+1)');
598             $this->popErrorHandling();
599             if ($result === DB_OK) {
600                 // COMMON CASE
601                 $id = @mysql_insert_id($this->connection);
602                 if ($id != 0) {
603                     return $id;
604                 }
605                 // EMPTY SEQ TABLE
606                 // Sequence table must be empty for some reason, so fill
607                 // it and return 1 and obtain a user-level lock
608                 $result = $this->getOne("SELECT GET_LOCK('${seqname}_lock',10)");
609                 if (DB::isError($result)) {
610                     return $this->raiseError($result);
611                 }
612                 if ($result == 0) {
613                     // Failed to get the lock
614                     return $this->mysqlRaiseError(DB_ERROR_NOT_LOCKED);
615                 }
616
617                 // add the default value
618                 $result = $this->query("REPLACE INTO ${seqname} (id) VALUES (0)");
619                 if (DB::isError($result)) {
620                     return $this->raiseError($result);
621                 }
622
623                 // Release the lock
624                 $result = $this->getOne('SELECT RELEASE_LOCK('
625                                         . "'${seqname}_lock')");
626                 if (DB::isError($result)) {
627                     return $this->raiseError($result);
628                 }
629                 // We know what the result will be, so no need to try again
630                 return 1;
631
632             } elseif ($ondemand && DB::isError($result) &&
633                 $result->getCode() == DB_ERROR_NOSUCHTABLE)
634             {
635                 // ONDEMAND TABLE CREATION
636                 $result = $this->createSequence($seq_name);
637                 if (DB::isError($result)) {
638                     return $this->raiseError($result);
639                 } else {
640                     $repeat = 1;
641                 }
642
643             } elseif (DB::isError($result) &&
644                       $result->getCode() == DB_ERROR_ALREADY_EXISTS)
645             {
646                 // BACKWARDS COMPAT
647                 // see _BCsequence() comment
648                 $result = $this->_BCsequence($seqname);
649                 if (DB::isError($result)) {
650                     return $this->raiseError($result);
651                 }
652                 $repeat = 1;
653             }
654         } while ($repeat);
655
656         return $this->raiseError($result);
657     }
658
659     // }}}
660     // {{{ createSequence()
661
662     /**
663      * Creates a new sequence
664      *
665      * @param string $seq_name  name of the new sequence
666      *
667      * @return int  DB_OK on success.  A DB_Error object on failure.
668      *
669      * @see DB_common::createSequence(), DB_common::getSequenceName(),
670      *      DB_mysql::nextID(), DB_mysql::dropSequence()
671      */
672     function createSequence($seq_name)
673     {
674         $seqname = $this->getSequenceName($seq_name);
675         $res = $this->query('CREATE TABLE ' . $seqname
676                             . ' (id INTEGER UNSIGNED AUTO_INCREMENT NOT NULL,'
677                             . ' PRIMARY KEY(id))');
678         if (DB::isError($res)) {
679             return $res;
680         }
681         // insert yields value 1, nextId call will generate ID 2
682         $res = $this->query("INSERT INTO ${seqname} (id) VALUES (0)");
683         if (DB::isError($res)) {
684             return $res;
685         }
686         // so reset to zero
687         return $this->query("UPDATE ${seqname} SET id = 0");
688     }
689
690     // }}}
691     // {{{ dropSequence()
692
693     /**
694      * Deletes a sequence
695      *
696      * @param string $seq_name  name of the sequence to be deleted
697      *
698      * @return int  DB_OK on success.  A DB_Error object on failure.
699      *
700      * @see DB_common::dropSequence(), DB_common::getSequenceName(),
701      *      DB_mysql::nextID(), DB_mysql::createSequence()
702      */
703     function dropSequence($seq_name)
704     {
705         return $this->query('DROP TABLE ' . $this->getSequenceName($seq_name));
706     }
707
708     // }}}
709     // {{{ _BCsequence()
710
711     /**
712      * Backwards compatibility with old sequence emulation implementation
713      * (clean up the dupes)
714      *
715      * @param string $seqname  the sequence name to clean up
716      *
717      * @return bool  true on success.  A DB_Error object on failure.
718      *
719      * @access private
720      */
721     function _BCsequence($seqname)
722     {
723         // Obtain a user-level lock... this will release any previous
724         // application locks, but unlike LOCK TABLES, it does not abort
725         // the current transaction and is much less frequently used.
726         $result = $this->getOne("SELECT GET_LOCK('${seqname}_lock',10)");
727         if (DB::isError($result)) {
728             return $result;
729         }
730         if ($result == 0) {
731             // Failed to get the lock, can't do the conversion, bail
732             // with a DB_ERROR_NOT_LOCKED error
733             return $this->mysqlRaiseError(DB_ERROR_NOT_LOCKED);
734         }
735
736         $highest_id = $this->getOne("SELECT MAX(id) FROM ${seqname}");
737         if (DB::isError($highest_id)) {
738             return $highest_id;
739         }
740         // This should kill all rows except the highest
741         // We should probably do something if $highest_id isn't
742         // numeric, but I'm at a loss as how to handle that...
743         $result = $this->query('DELETE FROM ' . $seqname
744                                . " WHERE id <> $highest_id");
745         if (DB::isError($result)) {
746             return $result;
747         }
748
749         // If another thread has been waiting for this lock,
750         // it will go thru the above procedure, but will have no
751         // real effect
752         $result = $this->getOne("SELECT RELEASE_LOCK('${seqname}_lock')");
753         if (DB::isError($result)) {
754             return $result;
755         }
756         return true;
757     }
758
759     // }}}
760     // {{{ quoteIdentifier()
761
762     /**
763      * Quotes a string so it can be safely used as a table or column name
764      * (WARNING: using names that require this is a REALLY BAD IDEA)
765      *
766      * WARNING:  Older versions of MySQL can't handle the backtick
767      * character (<kbd>`</kbd>) in table or column names.
768      *
769      * @param string $str  identifier name to be quoted
770      *
771      * @return string  quoted identifier string
772      *
773      * @see DB_common::quoteIdentifier()
774      * @since Method available since Release 1.6.0
775      */
776     function quoteIdentifier($str)
777     {
778         return '`' . str_replace('`', '``', $str) . '`';
779     }
780
781     // }}}
782     // {{{ quote()
783
784     /**
785      * @deprecated  Deprecated in release 1.6.0
786      */
787     function quote($str = null)
788     {
789         return $this->quoteSmart($str);
790     }
791
792     // }}}
793     // {{{ escapeSimple()
794
795     /**
796      * Escapes a string according to the current DBMS's standards
797      *
798      * @param string $str  the string to be escaped
799      *
800      * @return string  the escaped string
801      *
802      * @see DB_common::quoteSmart()
803      * @since Method available since Release 1.6.0
804      */
805     function escapeSimple($str)
806     {
807         if (function_exists('mysql_real_escape_string')) {
808             return @mysql_real_escape_string($str, $this->connection);
809         } else {
810             return @mysql_escape_string($str);
811         }
812     }
813
814     // }}}
815     // {{{ modifyQuery()
816
817     /**
818      * Changes a query string for various DBMS specific reasons
819      *
820      * This little hack lets you know how many rows were deleted
821      * when running a "DELETE FROM table" query.  Only implemented
822      * if the DB_PORTABILITY_DELETE_COUNT portability option is on.
823      *
824      * @param string $query  the query string to modify
825      *
826      * @return string  the modified query string
827      *
828      * @access protected
829      * @see DB_common::setOption()
830      */
831     function modifyQuery($query)
832     {
833         if ($this->options['portability'] & DB_PORTABILITY_DELETE_COUNT) {
834             // "DELETE FROM table" gives 0 affected rows in MySQL.
835             // This little hack lets you know how many rows were deleted.
836             if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
837                 $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
838                                       'DELETE FROM \1 WHERE 1=1', $query);
839             }
840         }
841         return $query;
842     }
843
844     // }}}
845     // {{{ modifyLimitQuery()
846
847     /**
848      * Adds LIMIT clauses to a query string according to current DBMS standards
849      *
850      * @param string $query   the query to modify
851      * @param int    $from    the row to start to fetching (0 = the first row)
852      * @param int    $count   the numbers of rows to fetch
853      * @param mixed  $params  array, string or numeric data to be used in
854      *                         execution of the statement.  Quantity of items
855      *                         passed must match quantity of placeholders in
856      *                         query:  meaning 1 placeholder for non-array
857      *                         parameters or 1 placeholder per array element.
858      *
859      * @return string  the query string with LIMIT clauses added
860      *
861      * @access protected
862      */
863     function modifyLimitQuery($query, $from, $count, $params = array())
864     {
865         if (DB::isManip($query) || $this->_next_query_manip) {
866             return $query . " LIMIT $count";
867         } else {
868             return $query . " LIMIT $from, $count";
869         }
870     }
871
872     // }}}
873     // {{{ mysqlRaiseError()
874
875     /**
876      * Produces a DB_Error object regarding the current problem
877      *
878      * @param int $errno  if the error is being manually raised pass a
879      *                     DB_ERROR* constant here.  If this isn't passed
880      *                     the error information gathered from the DBMS.
881      *
882      * @return object  the DB_Error object
883      *
884      * @see DB_common::raiseError(),
885      *      DB_mysql::errorNative(), DB_common::errorCode()
886      */
887     function mysqlRaiseError($errno = null)
888     {
889         if ($errno === null) {
890             if ($this->options['portability'] & DB_PORTABILITY_ERRORS) {
891                 $this->errorcode_map[1022] = DB_ERROR_CONSTRAINT;
892                 $this->errorcode_map[1048] = DB_ERROR_CONSTRAINT_NOT_NULL;
893                 $this->errorcode_map[1062] = DB_ERROR_CONSTRAINT;
894             } else {
895                 // Doing this in case mode changes during runtime.
896                 $this->errorcode_map[1022] = DB_ERROR_ALREADY_EXISTS;
897                 $this->errorcode_map[1048] = DB_ERROR_CONSTRAINT;
898                 $this->errorcode_map[1062] = DB_ERROR_ALREADY_EXISTS;
899             }
900             $errno = $this->errorCode(mysql_errno($this->connection));
901         }
902         return $this->raiseError($errno, null, null, null,
903                                  @mysql_errno($this->connection) . ' ** ' .
904                                  @mysql_error($this->connection));
905     }
906
907     // }}}
908     // {{{ errorNative()
909
910     /**
911      * Gets the DBMS' native error code produced by the last query
912      *
913      * @return int  the DBMS' error code
914      */
915     function errorNative()
916     {
917         return @mysql_errno($this->connection);
918     }
919
920     // }}}
921     // {{{ tableInfo()
922
923     /**
924      * Returns information about a table or a result set
925      *
926      * @param object|string  $result  DB_result object from a query or a
927      *                                 string containing the name of a table.
928      *                                 While this also accepts a query result
929      *                                 resource identifier, this behavior is
930      *                                 deprecated.
931      * @param int            $mode    a valid tableInfo mode
932      *
933      * @return array  an associative array with the information requested.
934      *                 A DB_Error object on failure.
935      *
936      * @see DB_common::tableInfo()
937      */
938     function tableInfo($result, $mode = null)
939     {
940         if (is_string($result)) {
941             // Fix for bug #11580.
942             if ($this->_db) {
943                 if (!@mysql_select_db($this->_db, $this->connection)) {
944                     return $this->mysqlRaiseError(DB_ERROR_NODBSELECTED);
945                 }
946             }
947             
948             /*
949              * Probably received a table name.
950              * Create a result resource identifier.
951              */
952             $id = @mysql_query("SELECT * FROM $result LIMIT 0",
953                                $this->connection);
954             $got_string = true;
955         } elseif (isset($result->result)) {
956             /*
957              * Probably received a result object.
958              * Extract the result resource identifier.
959              */
960             $id = $result->result;
961             $got_string = false;
962         } else {
963             /*
964              * Probably received a result resource identifier.
965              * Copy it.
966              * Deprecated.  Here for compatibility only.
967              */
968             $id = $result;
969             $got_string = false;
970         }
971
972         if (!is_resource($id)) {
973             return $this->mysqlRaiseError(DB_ERROR_NEED_MORE_DATA);
974         }
975
976         if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
977             $case_func = 'strtolower';
978         } else {
979             $case_func = 'strval';
980         }
981
982         $count = @mysql_num_fields($id);
983         $res   = array();
984
985         if ($mode) {
986             $res['num_fields'] = $count;
987         }
988
989         for ($i = 0; $i < $count; $i++) {
990             $res[$i] = array(
991                 'table' => $case_func(@mysql_field_table($id, $i)),
992                 'name'  => $case_func(@mysql_field_name($id, $i)),
993                 'type'  => @mysql_field_type($id, $i),
994                 'len'   => @mysql_field_len($id, $i),
995                 'flags' => @mysql_field_flags($id, $i),
996             );
997             if ($mode & DB_TABLEINFO_ORDER) {
998                 $res['order'][$res[$i]['name']] = $i;
999             }
1000             if ($mode & DB_TABLEINFO_ORDERTABLE) {
1001                 $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
1002             }
1003         }
1004
1005         // free the result only if we were called on a table
1006         if ($got_string) {
1007             @mysql_free_result($id);
1008         }
1009         return $res;
1010     }
1011
1012     // }}}
1013     // {{{ getSpecialQuery()
1014
1015     /**
1016      * Obtains the query string needed for listing a given type of objects
1017      *
1018      * @param string $type  the kind of objects you want to retrieve
1019      *
1020      * @return string  the SQL query string or null if the driver doesn't
1021      *                  support the object type requested
1022      *
1023      * @access protected
1024      * @see DB_common::getListOf()
1025      */
1026     function getSpecialQuery($type)
1027     {
1028         switch ($type) {
1029             case 'tables':
1030                 return 'SHOW TABLES';
1031             case 'users':
1032                 return 'SELECT DISTINCT User FROM mysql.user';
1033             case 'databases':
1034                 return 'SHOW DATABASES';
1035             case 'views':
1036                 return "SELECT
1037                         distinct(TABLE_NAME)
1038                     FROM
1039                         information_schema.TABLES
1040                     WHERE
1041                         table_type = 'VIEW'
1042                         AND
1043                         TABLE_SCHEMA=DATABASE()
1044                     ";
1045             
1046             default:
1047                 return null;
1048         }
1049     }
1050     
1051
1052     // }}}
1053
1054 }
1055
1056 /*
1057  * Local variables:
1058  * tab-width: 4
1059  * c-basic-offset: 4
1060  * End:
1061  */
1062
1063 ?>