mysql.php 32 KB

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