Automatically exported from code.google.com/p/planningalerts
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

1035 lignes
32 KiB

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