mysql.php 32 KB

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