PageRenderTime 57ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/gespac/config/PEAR/MDB2/Driver/mysql.php

http://gespac.googlecode.com/
PHP | 1479 lines | 919 code | 105 blank | 455 comment | 208 complexity | de036c07e722213b95a793e2d5db683c MD5 | raw file
  1. <?php
  2. // vim: set et ts=4 sw=4 fdm=marker:
  3. // +----------------------------------------------------------------------+
  4. // | PHP versions 4 and 5 |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox, |
  7. // | Stig. S. Bakken, Lukas Smith |
  8. // | All rights reserved. |
  9. // +----------------------------------------------------------------------+
  10. // | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
  11. // | API as well as database abstraction for PHP applications. |
  12. // | This LICENSE is in the BSD license style. |
  13. // | |
  14. // | Redistribution and use in source and binary forms, with or without |
  15. // | modification, are permitted provided that the following conditions |
  16. // | are met: |
  17. // | |
  18. // | Redistributions of source code must retain the above copyright |
  19. // | notice, this list of conditions and the following disclaimer. |
  20. // | |
  21. // | Redistributions in binary form must reproduce the above copyright |
  22. // | notice, this list of conditions and the following disclaimer in the |
  23. // | documentation and/or other materials provided with the distribution. |
  24. // | |
  25. // | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
  26. // | Lukas Smith nor the names of his contributors may be used to endorse |
  27. // | or promote products derived from this software without specific prior|
  28. // | written permission. |
  29. // | |
  30. // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
  31. // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
  32. // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
  33. // | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
  34. // | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
  35. // | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
  36. // | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
  37. // | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
  38. // | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
  39. // | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
  40. // | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
  41. // | POSSIBILITY OF SUCH DAMAGE. |
  42. // +----------------------------------------------------------------------+
  43. // | Author: Lukas Smith <smith@pooteeweet.org> |
  44. // +----------------------------------------------------------------------+
  45. //
  46. // $Id: mysql.php,v 1.182 2007/05/02 22:00:08 quipo Exp $
  47. //
  48. /**
  49. * MDB2 MySQL driver
  50. *
  51. * @package MDB2
  52. * @category Database
  53. * @author Lukas Smith <smith@pooteeweet.org>
  54. */
  55. class MDB2_Driver_mysql extends MDB2_Driver_Common
  56. {
  57. // {{{ properties
  58. var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => '\\', 'escape_pattern' => '\\');
  59. var $identifier_quoting = array('start' => '`', 'end' => '`', 'escape' => '`');
  60. var $sql_comments = array(
  61. array('start' => '-- ', 'end' => "\n", 'escape' => false),
  62. array('start' => '#', 'end' => "\n", 'escape' => false),
  63. array('start' => '/*', 'end' => '*/', 'escape' => false),
  64. );
  65. var $start_transaction = false;
  66. var $varchar_max_length = 255;
  67. // }}}
  68. // {{{ constructor
  69. /**
  70. * Constructor
  71. */
  72. function __construct()
  73. {
  74. parent::__construct();
  75. $this->phptype = 'mysql';
  76. $this->dbsyntax = 'mysql';
  77. $this->supported['sequences'] = 'emulated';
  78. $this->supported['indexes'] = true;
  79. $this->supported['affected_rows'] = true;
  80. $this->supported['transactions'] = false;
  81. $this->supported['savepoints'] = false;
  82. $this->supported['summary_functions'] = true;
  83. $this->supported['order_by_text'] = true;
  84. $this->supported['current_id'] = 'emulated';
  85. $this->supported['limit_queries'] = true;
  86. $this->supported['LOBs'] = true;
  87. $this->supported['replace'] = true;
  88. $this->supported['sub_selects'] = 'emulated';
  89. $this->supported['auto_increment'] = true;
  90. $this->supported['primary_key'] = true;
  91. $this->supported['result_introspection'] = true;
  92. $this->supported['prepared_statements'] = 'emulated';
  93. $this->supported['identifier_quoting'] = true;
  94. $this->supported['pattern_escaping'] = true;
  95. $this->supported['new_link'] = true;
  96. $this->options['default_table_type'] = '';
  97. }
  98. // }}}
  99. // {{{ errorInfo()
  100. /**
  101. * This method is used to collect information about an error
  102. *
  103. * @param integer $error
  104. * @return array
  105. * @access public
  106. */
  107. function errorInfo($error = null)
  108. {
  109. if ($this->connection) {
  110. $native_code = @mysql_errno($this->connection);
  111. $native_msg = @mysql_error($this->connection);
  112. } else {
  113. $native_code = @mysql_errno();
  114. $native_msg = @mysql_error();
  115. }
  116. if (is_null($error)) {
  117. static $ecode_map;
  118. if (empty($ecode_map)) {
  119. $ecode_map = array(
  120. 1004 => MDB2_ERROR_CANNOT_CREATE,
  121. 1005 => MDB2_ERROR_CANNOT_CREATE,
  122. 1006 => MDB2_ERROR_CANNOT_CREATE,
  123. 1007 => MDB2_ERROR_ALREADY_EXISTS,
  124. 1008 => MDB2_ERROR_CANNOT_DROP,
  125. 1022 => MDB2_ERROR_ALREADY_EXISTS,
  126. 1044 => MDB2_ERROR_ACCESS_VIOLATION,
  127. 1046 => MDB2_ERROR_NODBSELECTED,
  128. 1048 => MDB2_ERROR_CONSTRAINT,
  129. 1049 => MDB2_ERROR_NOSUCHDB,
  130. 1050 => MDB2_ERROR_ALREADY_EXISTS,
  131. 1051 => MDB2_ERROR_NOSUCHTABLE,
  132. 1054 => MDB2_ERROR_NOSUCHFIELD,
  133. 1061 => MDB2_ERROR_ALREADY_EXISTS,
  134. 1062 => MDB2_ERROR_ALREADY_EXISTS,
  135. 1064 => MDB2_ERROR_SYNTAX,
  136. 1091 => MDB2_ERROR_NOT_FOUND,
  137. 1100 => MDB2_ERROR_NOT_LOCKED,
  138. 1136 => MDB2_ERROR_VALUE_COUNT_ON_ROW,
  139. 1142 => MDB2_ERROR_ACCESS_VIOLATION,
  140. 1146 => MDB2_ERROR_NOSUCHTABLE,
  141. 1216 => MDB2_ERROR_CONSTRAINT,
  142. 1217 => MDB2_ERROR_CONSTRAINT,
  143. 1356 => MDB2_ERROR_DIVZERO,
  144. 1451 => MDB2_ERROR_CONSTRAINT,
  145. 1452 => MDB2_ERROR_CONSTRAINT,
  146. );
  147. }
  148. if ($this->options['portability'] & MDB2_PORTABILITY_ERRORS) {
  149. $ecode_map[1022] = MDB2_ERROR_CONSTRAINT;
  150. $ecode_map[1048] = MDB2_ERROR_CONSTRAINT_NOT_NULL;
  151. $ecode_map[1062] = MDB2_ERROR_CONSTRAINT;
  152. } else {
  153. // Doing this in case mode changes during runtime.
  154. $ecode_map[1022] = MDB2_ERROR_ALREADY_EXISTS;
  155. $ecode_map[1048] = MDB2_ERROR_CONSTRAINT;
  156. $ecode_map[1062] = MDB2_ERROR_ALREADY_EXISTS;
  157. }
  158. if (isset($ecode_map[$native_code])) {
  159. $error = $ecode_map[$native_code];
  160. }
  161. }
  162. return array($error, $native_code, $native_msg);
  163. }
  164. // }}}
  165. // {{{ escape()
  166. /**
  167. * Quotes a string so it can be safely used in a query. It will quote
  168. * the text so it can safely be used within a query.
  169. *
  170. * @param string the input string to quote
  171. * @param bool escape wildcards
  172. *
  173. * @return string quoted string
  174. *
  175. * @access public
  176. */
  177. function escape($text, $escape_wildcards = false)
  178. {
  179. if ($escape_wildcards) {
  180. $text = $this->escapePattern($text);
  181. }
  182. $connection = $this->getConnection();
  183. if (PEAR::isError($connection)) {
  184. return $connection;
  185. }
  186. $text = @mysql_real_escape_string($text, $connection);
  187. return $text;
  188. }
  189. // }}}
  190. // {{{
  191. /**
  192. * Start a transaction or set a savepoint.
  193. *
  194. * @param string name of a savepoint to set
  195. * @return mixed MDB2_OK on success, a MDB2 error on failure
  196. *
  197. * @access public
  198. */
  199. function beginTransaction($savepoint = null)
  200. {
  201. $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  202. $this->_getServerCapabilities();
  203. if (!is_null($savepoint)) {
  204. if (!$this->supports('savepoints')) {
  205. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  206. 'savepoints are not supported', __FUNCTION__);
  207. }
  208. if (!$this->in_transaction) {
  209. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  210. 'savepoint cannot be released when changes are auto committed', __FUNCTION__);
  211. }
  212. $query = 'SAVEPOINT '.$savepoint;
  213. return $this->_doQuery($query, true);
  214. } elseif ($this->in_transaction) {
  215. return MDB2_OK; //nothing to do
  216. }
  217. if (!$this->destructor_registered && $this->opened_persistent) {
  218. $this->destructor_registered = true;
  219. register_shutdown_function('MDB2_closeOpenTransactions');
  220. }
  221. $query = $this->start_transaction ? 'START TRANSACTION' : 'SET AUTOCOMMIT = 1';
  222. $result =& $this->_doQuery($query, true);
  223. if (PEAR::isError($result)) {
  224. return $result;
  225. }
  226. $this->in_transaction = true;
  227. return MDB2_OK;
  228. }
  229. // }}}
  230. // {{{ commit()
  231. /**
  232. * Commit the database changes done during a transaction that is in
  233. * progress or release a savepoint. This function may only be called when
  234. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  235. * transaction is implicitly started after committing the pending changes.
  236. *
  237. * @param string name of a savepoint to release
  238. * @return mixed MDB2_OK on success, a MDB2 error on failure
  239. *
  240. * @access public
  241. */
  242. function commit($savepoint = null)
  243. {
  244. $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  245. if (!$this->in_transaction) {
  246. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  247. 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
  248. }
  249. if (!is_null($savepoint)) {
  250. if (!$this->supports('savepoints')) {
  251. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  252. 'savepoints are not supported', __FUNCTION__);
  253. }
  254. $server_info = $this->getServerVersion();
  255. if (version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '5.0.3', '<')) {
  256. return MDB2_OK;
  257. }
  258. $query = 'RELEASE SAVEPOINT '.$savepoint;
  259. return $this->_doQuery($query, true);
  260. }
  261. if (!$this->supports('transactions')) {
  262. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  263. 'transactions are not supported', __FUNCTION__);
  264. }
  265. $result =& $this->_doQuery('COMMIT', true);
  266. if (PEAR::isError($result)) {
  267. return $result;
  268. }
  269. if (!$this->start_transaction) {
  270. $query = 'SET AUTOCOMMIT = 0';
  271. $result =& $this->_doQuery($query, true);
  272. if (PEAR::isError($result)) {
  273. return $result;
  274. }
  275. }
  276. $this->in_transaction = false;
  277. return MDB2_OK;
  278. }
  279. // }}}
  280. // {{{ rollback()
  281. /**
  282. * Cancel any database changes done during a transaction or since a specific
  283. * savepoint that is in progress. This function may only be called when
  284. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  285. * transaction is implicitly started after canceling the pending changes.
  286. *
  287. * @param string name of a savepoint to rollback to
  288. * @return mixed MDB2_OK on success, a MDB2 error on failure
  289. *
  290. * @access public
  291. */
  292. function rollback($savepoint = null)
  293. {
  294. $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  295. if (!$this->in_transaction) {
  296. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  297. 'rollback cannot be done changes are auto committed', __FUNCTION__);
  298. }
  299. if (!is_null($savepoint)) {
  300. if (!$this->supports('savepoints')) {
  301. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  302. 'savepoints are not supported', __FUNCTION__);
  303. }
  304. $query = 'ROLLBACK TO SAVEPOINT '.$savepoint;
  305. return $this->_doQuery($query, true);
  306. }
  307. $query = 'ROLLBACK';
  308. $result =& $this->_doQuery($query, true);
  309. if (PEAR::isError($result)) {
  310. return $result;
  311. }
  312. if (!$this->start_transaction) {
  313. $query = 'SET AUTOCOMMIT = 0';
  314. $result =& $this->_doQuery($query, true);
  315. if (PEAR::isError($result)) {
  316. return $result;
  317. }
  318. }
  319. $this->in_transaction = false;
  320. return MDB2_OK;
  321. }
  322. // }}}
  323. // {{{ function setTransactionIsolation()
  324. /**
  325. * Set the transacton isolation level.
  326. *
  327. * @param string standard isolation level
  328. * READ UNCOMMITTED (allows dirty reads)
  329. * READ COMMITTED (prevents dirty reads)
  330. * REPEATABLE READ (prevents nonrepeatable reads)
  331. * SERIALIZABLE (prevents phantom reads)
  332. * @return mixed MDB2_OK on success, a MDB2 error on failure
  333. *
  334. * @access public
  335. * @since 2.1.1
  336. */
  337. function setTransactionIsolation($isolation)
  338. {
  339. $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
  340. if (!$this->supports('transactions')) {
  341. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  342. 'transactions are not supported', __FUNCTION__);
  343. }
  344. switch ($isolation) {
  345. case 'READ UNCOMMITTED':
  346. case 'READ COMMITTED':
  347. case 'REPEATABLE READ':
  348. case 'SERIALIZABLE':
  349. break;
  350. default:
  351. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  352. 'isolation level is not supported: '.$isolation, __FUNCTION__);
  353. }
  354. $query = "SET SESSION TRANSACTION ISOLATION LEVEL $isolation";
  355. return $this->_doQuery($query, true);
  356. }
  357. // }}}
  358. // {{{ connect()
  359. /**
  360. * Connect to the database
  361. *
  362. * @return true on success, MDB2 Error Object on failure
  363. */
  364. function connect()
  365. {
  366. if (is_resource($this->connection)) {
  367. if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
  368. && $this->opened_persistent == $this->options['persistent']
  369. && $this->connected_database_name == $this->database_name
  370. ) {
  371. return MDB2_OK;
  372. }
  373. $this->disconnect(false);
  374. }
  375. if (!PEAR::loadExtension($this->phptype)) {
  376. return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  377. 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
  378. }
  379. $params = array();
  380. if ($this->dsn['protocol'] && $this->dsn['protocol'] == 'unix') {
  381. $params[0] = ':' . $this->dsn['socket'];
  382. } else {
  383. $params[0] = $this->dsn['hostspec'] ? $this->dsn['hostspec']
  384. : 'localhost';
  385. if ($this->dsn['port']) {
  386. $params[0].= ':' . $this->dsn['port'];
  387. }
  388. }
  389. $params[] = $this->dsn['username'] ? $this->dsn['username'] : null;
  390. $params[] = $this->dsn['password'] ? $this->dsn['password'] : null;
  391. if (!$this->options['persistent']) {
  392. if (isset($this->dsn['new_link'])
  393. && ($this->dsn['new_link'] == 'true' || $this->dsn['new_link'] === true)
  394. ) {
  395. $params[] = true;
  396. } else {
  397. $params[] = false;
  398. }
  399. }
  400. if (version_compare(phpversion(), '4.3.0', '>=')) {
  401. $params[] = isset($this->dsn['client_flags'])
  402. ? $this->dsn['client_flags'] : null;
  403. }
  404. $connect_function = $this->options['persistent'] ? 'mysql_pconnect' : 'mysql_connect';
  405. $connection = @call_user_func_array($connect_function, $params);
  406. if (!$connection) {
  407. if (($err = @mysql_error()) != '') {
  408. return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
  409. $err, __FUNCTION__);
  410. } else {
  411. return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
  412. 'unable to establish a connection', __FUNCTION__);
  413. }
  414. }
  415. if (!empty($this->dsn['charset'])) {
  416. $result = $this->setCharset($this->dsn['charset'], $connection);
  417. if (PEAR::isError($result)) {
  418. return $result;
  419. }
  420. }
  421. $this->connection = $connection;
  422. $this->connected_dsn = $this->dsn;
  423. $this->connected_database_name = '';
  424. $this->opened_persistent = $this->options['persistent'];
  425. $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
  426. if ($this->database_name) {
  427. if ($this->database_name != $this->connected_database_name) {
  428. if (!@mysql_select_db($this->database_name, $connection)) {
  429. $err = $this->raiseError(null, null, null,
  430. 'Could not select the database: '.$this->database_name, __FUNCTION__);
  431. return $err;
  432. }
  433. $this->connected_database_name = $this->database_name;
  434. }
  435. }
  436. $this->supported['transactions'] = $this->options['use_transactions'];
  437. if ($this->options['default_table_type']) {
  438. switch (strtoupper($this->options['default_table_type'])) {
  439. case 'BLACKHOLE':
  440. case 'MEMORY':
  441. case 'ARCHIVE':
  442. case 'CSV':
  443. case 'HEAP':
  444. case 'ISAM':
  445. case 'MERGE':
  446. case 'MRG_ISAM':
  447. case 'ISAM':
  448. case 'MRG_MYISAM':
  449. case 'MYISAM':
  450. $this->supported['transactions'] = false;
  451. $this->warnings[] = $this->options['default_table_type'] .
  452. ' is not a supported default table type';
  453. break;
  454. }
  455. }
  456. $this->_getServerCapabilities();
  457. return MDB2_OK;
  458. }
  459. // }}}
  460. // {{{ setCharset()
  461. /**
  462. * Set the charset on the current connection
  463. *
  464. * @param string charset
  465. * @param resource connection handle
  466. *
  467. * @return true on success, MDB2 Error Object on failure
  468. */
  469. function setCharset($charset, $connection = null)
  470. {
  471. if (is_null($connection)) {
  472. $connection = $this->getConnection();
  473. if (PEAR::isError($connection)) {
  474. return $connection;
  475. }
  476. }
  477. $query = "SET NAMES '".mysql_real_escape_string($charset, $connection)."'";
  478. return $this->_doQuery($query, true, $connection);
  479. }
  480. // }}}
  481. // {{{ disconnect()
  482. /**
  483. * Log out and disconnect from the database.
  484. *
  485. * @param boolean $force if the disconnect should be forced even if the
  486. * connection is opened persistently
  487. * @return mixed true on success, false if not connected and error
  488. * object on error
  489. * @access public
  490. */
  491. function disconnect($force = true)
  492. {
  493. if (is_resource($this->connection)) {
  494. if ($this->in_transaction) {
  495. $dsn = $this->dsn;
  496. $database_name = $this->database_name;
  497. $persistent = $this->options['persistent'];
  498. $this->dsn = $this->connected_dsn;
  499. $this->database_name = $this->connected_database_name;
  500. $this->options['persistent'] = $this->opened_persistent;
  501. $this->rollback();
  502. $this->dsn = $dsn;
  503. $this->database_name = $database_name;
  504. $this->options['persistent'] = $persistent;
  505. }
  506. if (!$this->opened_persistent || $force) {
  507. @mysql_close($this->connection);
  508. }
  509. }
  510. return parent::disconnect($force);
  511. }
  512. // }}}
  513. // {{{ _doQuery()
  514. /**
  515. * Execute a query
  516. * @param string $query query
  517. * @param boolean $is_manip if the query is a manipulation query
  518. * @param resource $connection
  519. * @param string $database_name
  520. * @return result or error object
  521. * @access protected
  522. */
  523. function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
  524. {
  525. $this->last_query = $query;
  526. $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
  527. if ($result) {
  528. if (PEAR::isError($result)) {
  529. return $result;
  530. }
  531. $query = $result;
  532. }
  533. if ($this->options['disable_query']) {
  534. $result = $is_manip ? 0 : null;
  535. return $result;
  536. }
  537. if (is_null($connection)) {
  538. $connection = $this->getConnection();
  539. if (PEAR::isError($connection)) {
  540. return $connection;
  541. }
  542. }
  543. if (is_null($database_name)) {
  544. $database_name = $this->database_name;
  545. }
  546. if ($database_name) {
  547. if ($database_name != $this->connected_database_name) {
  548. if (!@mysql_select_db($database_name, $connection)) {
  549. $err = $this->raiseError(null, null, null,
  550. 'Could not select the database: '.$database_name, __FUNCTION__);
  551. return $err;
  552. }
  553. $this->connected_database_name = $database_name;
  554. }
  555. }
  556. $function = $this->options['result_buffering']
  557. ? 'mysql_query' : 'mysql_unbuffered_query';
  558. $result = @$function($query, $connection);
  559. if (!$result) {
  560. $err =& $this->raiseError(null, null, null,
  561. 'Could not execute statement', __FUNCTION__);
  562. return $err;
  563. }
  564. $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
  565. return $result;
  566. }
  567. // }}}
  568. // {{{ _affectedRows()
  569. /**
  570. * Returns the number of rows affected
  571. *
  572. * @param resource $result
  573. * @param resource $connection
  574. * @return mixed MDB2 Error Object or the number of rows affected
  575. * @access private
  576. */
  577. function _affectedRows($connection, $result = null)
  578. {
  579. if (is_null($connection)) {
  580. $connection = $this->getConnection();
  581. if (PEAR::isError($connection)) {
  582. return $connection;
  583. }
  584. }
  585. return @mysql_affected_rows($connection);
  586. }
  587. // }}}
  588. // {{{ _modifyQuery()
  589. /**
  590. * Changes a query string for various DBMS specific reasons
  591. *
  592. * @param string $query query to modify
  593. * @param boolean $is_manip if it is a DML query
  594. * @param integer $limit limit the number of rows
  595. * @param integer $offset start reading from given offset
  596. * @return string modified query
  597. * @access protected
  598. */
  599. function _modifyQuery($query, $is_manip, $limit, $offset)
  600. {
  601. if ($this->options['portability'] & MDB2_PORTABILITY_DELETE_COUNT) {
  602. // "DELETE FROM table" gives 0 affected rows in MySQL.
  603. // This little hack lets you know how many rows were deleted.
  604. if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
  605. $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
  606. 'DELETE FROM \1 WHERE 1=1', $query);
  607. }
  608. }
  609. if ($limit > 0
  610. && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)
  611. ) {
  612. $query = rtrim($query);
  613. if (substr($query, -1) == ';') {
  614. $query = substr($query, 0, -1);
  615. }
  616. // LIMIT doesn't always come last in the query
  617. // @see http://dev.mysql.com/doc/refman/5.0/en/select.html
  618. $after = '';
  619. if (preg_match('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims', $query, $matches)) {
  620. $after = $matches[0];
  621. $query = preg_replace('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims', '', $query);
  622. } elseif (preg_match('/(\s+FOR\s+UPDATE\s*)$/i', $query, $matches)) {
  623. $after = $matches[0];
  624. $query = preg_replace('/(\s+FOR\s+UPDATE\s*)$/im', '', $query);
  625. } elseif (preg_match('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im', $query, $matches)) {
  626. $after = $matches[0];
  627. $query = preg_replace('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im', '', $query);
  628. }
  629. if ($is_manip) {
  630. return $query . " LIMIT $limit" . $after;
  631. } else {
  632. return $query . " LIMIT $offset, $limit" . $after;
  633. }
  634. }
  635. return $query;
  636. }
  637. // }}}
  638. // {{{ getServerVersion()
  639. /**
  640. * return version information about the server
  641. *
  642. * @param bool $native determines if the raw version string should be returned
  643. * @return mixed array/string with version information or MDB2 error object
  644. * @access public
  645. */
  646. function getServerVersion($native = false)
  647. {
  648. $connection = $this->getConnection();
  649. if (PEAR::isError($connection)) {
  650. return $connection;
  651. }
  652. if ($this->connected_server_info) {
  653. $server_info = $this->connected_server_info;
  654. } else {
  655. $server_info = @mysql_get_server_info($connection);
  656. }
  657. if (!$server_info) {
  658. return $this->raiseError(null, null, null,
  659. 'Could not get server information', __FUNCTION__);
  660. }
  661. // cache server_info
  662. $this->connected_server_info = $server_info;
  663. if (!$native) {
  664. $tmp = explode('.', $server_info, 3);
  665. if (isset($tmp[2]) && strpos($tmp[2], '-')) {
  666. $tmp2 = explode('-', @$tmp[2], 2);
  667. } else {
  668. $tmp2[0] = isset($tmp[2]) ? $tmp[2] : null;
  669. $tmp2[1] = null;
  670. }
  671. $server_info = array(
  672. 'major' => isset($tmp[0]) ? $tmp[0] : null,
  673. 'minor' => isset($tmp[1]) ? $tmp[1] : null,
  674. 'patch' => $tmp2[0],
  675. 'extra' => $tmp2[1],
  676. 'native' => $server_info,
  677. );
  678. }
  679. return $server_info;
  680. }
  681. // }}}
  682. // {{{ _getServerCapabilities()
  683. /**
  684. * Fetch some information about the server capabilities
  685. * (transactions, subselects, prepared statements, etc).
  686. *
  687. * @access private
  688. */
  689. function _getServerCapabilities()
  690. {
  691. static $already_checked = false;
  692. if (!$already_checked) {
  693. $already_checked = true;
  694. //set defaults
  695. $this->supported['sub_selects'] = 'emulated';
  696. $this->supported['prepared_statements'] = 'emulated';
  697. $this->start_transaction = false;
  698. $this->varchar_max_length = 255;
  699. $server_info = $this->getServerVersion();
  700. if (is_array($server_info)) {
  701. if (!version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '4.1.0', '<')) {
  702. $this->supported['sub_selects'] = true;
  703. $this->supported['prepared_statements'] = true;
  704. }
  705. if (!version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '4.0.14', '<')
  706. || !version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '4.1.1', '<')
  707. ) {
  708. $this->supported['savepoints'] = true;
  709. }
  710. if (!version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '4.0.11', '<')) {
  711. $this->start_transaction = true;
  712. }
  713. if (!version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '5.0.3', '<')) {
  714. $this->varchar_max_length = 65532;
  715. }
  716. }
  717. }
  718. }
  719. // }}}
  720. // {{{ function _skipUserDefinedVariable($query, $position)
  721. /**
  722. * Utility method, used by prepare() to avoid misinterpreting MySQL user
  723. * defined variables (SELECT @x:=5) for placeholders.
  724. * Check if the placeholder is a false positive, i.e. if it is an user defined
  725. * variable instead. If so, skip it and advance the position, otherwise
  726. * return the current position, which is valid
  727. *
  728. * @param string $query
  729. * @param integer $position current string cursor position
  730. * @return integer $new_position
  731. * @access protected
  732. */
  733. function _skipUserDefinedVariable($query, $position)
  734. {
  735. $found = strpos(strrev(substr($query, 0, $position)), '@');
  736. if ($found === false) {
  737. return $position;
  738. }
  739. $pos = strlen($query) - strlen(substr($query, $position)) - $found - 1;
  740. $substring = substr($query, $pos, $position - $pos + 2);
  741. if (preg_match('/^@\w+:=$/', $substring)) {
  742. return $position + 1; //found an user defined variable: skip it
  743. }
  744. return $position;
  745. }
  746. // }}}
  747. // {{{ prepare()
  748. /**
  749. * Prepares a query for multiple execution with execute().
  750. * With some database backends, this is emulated.
  751. * prepare() requires a generic query as string like
  752. * 'INSERT INTO numbers VALUES(?,?)' or
  753. * 'INSERT INTO numbers VALUES(:foo,:bar)'.
  754. * The ? and :[a-zA-Z] and are placeholders which can be set using
  755. * bindParam() and the query can be send off using the execute() method.
  756. *
  757. * @param string $query the query to prepare
  758. * @param mixed $types array that contains the types of the placeholders
  759. * @param mixed $result_types array that contains the types of the columns in
  760. * the result set or MDB2_PREPARE_RESULT, if set to
  761. * MDB2_PREPARE_MANIP the query is handled as a manipulation query
  762. * @param mixed $lobs key (field) value (parameter) pair for all lob placeholders
  763. * @return mixed resource handle for the prepared query on success, a MDB2
  764. * error on failure
  765. * @access public
  766. * @see bindParam, execute
  767. */
  768. function &prepare($query, $types = null, $result_types = null, $lobs = array())
  769. {
  770. if ($this->options['emulate_prepared']
  771. || $this->supported['prepared_statements'] !== true
  772. ) {
  773. $obj =& parent::prepare($query, $types, $result_types, $lobs);
  774. return $obj;
  775. }
  776. $is_manip = ($result_types === MDB2_PREPARE_MANIP);
  777. $offset = $this->offset;
  778. $limit = $this->limit;
  779. $this->offset = $this->limit = 0;
  780. $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
  781. $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
  782. if ($result) {
  783. if (PEAR::isError($result)) {
  784. return $result;
  785. }
  786. $query = $result;
  787. }
  788. $placeholder_type_guess = $placeholder_type = null;
  789. $question = '?';
  790. $colon = ':';
  791. $positions = array();
  792. $position = 0;
  793. while ($position < strlen($query)) {
  794. $q_position = strpos($query, $question, $position);
  795. $c_position = strpos($query, $colon, $position);
  796. if ($q_position && $c_position) {
  797. $p_position = min($q_position, $c_position);
  798. } elseif ($q_position) {
  799. $p_position = $q_position;
  800. } elseif ($c_position) {
  801. $p_position = $c_position;
  802. } else {
  803. break;
  804. }
  805. if (is_null($placeholder_type)) {
  806. $placeholder_type_guess = $query[$p_position];
  807. }
  808. $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
  809. if (PEAR::isError($new_pos)) {
  810. return $new_pos;
  811. }
  812. if ($new_pos != $position) {
  813. $position = $new_pos;
  814. continue; //evaluate again starting from the new position
  815. }
  816. if ($query[$position] == $placeholder_type_guess) {
  817. if (is_null($placeholder_type)) {
  818. $placeholder_type = $query[$p_position];
  819. $question = $colon = $placeholder_type;
  820. }
  821. if ($placeholder_type == ':') {
  822. //make sure this is not part of an user defined variable
  823. $new_pos = $this->_skipUserDefinedVariable($query, $position);
  824. if ($new_pos != $position) {
  825. $position = $new_pos;
  826. continue; //evaluate again starting from the new position
  827. }
  828. $parameter = preg_replace('/^.{'.($position+1).'}([a-z0-9_]+).*$/si', '\\1', $query);
  829. if ($parameter === '') {
  830. $err =& $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
  831. 'named parameter with an empty name', __FUNCTION__);
  832. return $err;
  833. }
  834. $positions[$p_position] = $parameter;
  835. $query = substr_replace($query, '?', $position, strlen($parameter)+1);
  836. } else {
  837. $positions[$p_position] = count($positions);
  838. }
  839. $position = $p_position + 1;
  840. } else {
  841. $position = $p_position;
  842. }
  843. }
  844. $connection = $this->getConnection();
  845. if (PEAR::isError($connection)) {
  846. return $connection;
  847. }
  848. $statement_name = sprintf($this->options['statement_format'], $this->phptype, md5(time() + rand()));
  849. $query = "PREPARE $statement_name FROM ".$this->quote($query, 'text');
  850. $statement =& $this->_doQuery($query, true, $connection);
  851. if (PEAR::isError($statement)) {
  852. return $statement;
  853. }
  854. $class_name = 'MDB2_Statement_'.$this->phptype;
  855. $obj =& new $class_name($this, $statement_name, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
  856. $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
  857. return $obj;
  858. }
  859. // }}}
  860. // {{{ replace()
  861. /**
  862. * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
  863. * query, except that if there is already a row in the table with the same
  864. * key field values, the REPLACE query just updates its values instead of
  865. * inserting a new row.
  866. *
  867. * The REPLACE type of query does not make part of the SQL standards. Since
  868. * practically only MySQL implements it natively, this type of query is
  869. * emulated through this method for other DBMS using standard types of
  870. * queries inside a transaction to assure the atomicity of the operation.
  871. *
  872. * @access public
  873. *
  874. * @param string $table name of the table on which the REPLACE query will
  875. * be executed.
  876. * @param array $fields associative array that describes the fields and the
  877. * values that will be inserted or updated in the specified table. The
  878. * indexes of the array are the names of all the fields of the table. The
  879. * values of the array are also associative arrays that describe the
  880. * values and other properties of the table fields.
  881. *
  882. * Here follows a list of field properties that need to be specified:
  883. *
  884. * value:
  885. * Value to be assigned to the specified field. This value may be
  886. * of specified in database independent type format as this
  887. * function can perform the necessary datatype conversions.
  888. *
  889. * Default:
  890. * this property is required unless the Null property
  891. * is set to 1.
  892. *
  893. * type
  894. * Name of the type of the field. Currently, all types Metabase
  895. * are supported except for clob and blob.
  896. *
  897. * Default: no type conversion
  898. *
  899. * null
  900. * Boolean property that indicates that the value for this field
  901. * should be set to null.
  902. *
  903. * The default value for fields missing in INSERT queries may be
  904. * specified the definition of a table. Often, the default value
  905. * is already null, but since the REPLACE may be emulated using
  906. * an UPDATE query, make sure that all fields of the table are
  907. * listed in this function argument array.
  908. *
  909. * Default: 0
  910. *
  911. * key
  912. * Boolean property that indicates that this field should be
  913. * handled as a primary key or at least as part of the compound
  914. * unique index of the table that will determine the row that will
  915. * updated if it exists or inserted a new row otherwise.
  916. *
  917. * This function will fail if no key field is specified or if the
  918. * value of a key field is set to null because fields that are
  919. * part of unique index they may not be null.
  920. *
  921. * Default: 0
  922. *
  923. * @return mixed MDB2_OK on success, a MDB2 error on failure
  924. */
  925. function replace($table, $fields)
  926. {
  927. $count = count($fields);
  928. $query = $values = '';
  929. $keys = $colnum = 0;
  930. for (reset($fields); $colnum < $count; next($fields), $colnum++) {
  931. $name = key($fields);
  932. if ($colnum > 0) {
  933. $query .= ',';
  934. $values.= ',';
  935. }
  936. $query.= $name;
  937. if (isset($fields[$name]['null']) && $fields[$name]['null']) {
  938. $value = 'NULL';
  939. } else {
  940. $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
  941. $value = $this->quote($fields[$name]['value'], $type);
  942. }
  943. $values.= $value;
  944. if (isset($fields[$name]['key']) && $fields[$name]['key']) {
  945. if ($value === 'NULL') {
  946. return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
  947. 'key value '.$name.' may not be NULL', __FUNCTION__);
  948. }
  949. $keys++;
  950. }
  951. }
  952. if ($keys == 0) {
  953. return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
  954. 'not specified which fields are keys', __FUNCTION__);
  955. }
  956. $connection = $this->getConnection();
  957. if (PEAR::isError($connection)) {
  958. return $connection;
  959. }
  960. $query = "REPLACE INTO $table ($query) VALUES ($values)";
  961. $result =& $this->_doQuery($query, true, $connection);
  962. if (PEAR::isError($result)) {
  963. return $result;
  964. }
  965. return $this->_affectedRows($connection, $result);
  966. }
  967. // }}}
  968. // {{{ nextID()
  969. /**
  970. * Returns the next free id of a sequence
  971. *
  972. * @param string $seq_name name of the sequence
  973. * @param boolean $ondemand when true the sequence is
  974. * automatic created, if it
  975. * not exists
  976. *
  977. * @return mixed MDB2 Error Object or id
  978. * @access public
  979. */
  980. function nextID($seq_name, $ondemand = true)
  981. {
  982. $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
  983. $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
  984. $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
  985. $this->expectError(MDB2_ERROR_NOSUCHTABLE);
  986. $result =& $this->_doQuery($query, true);
  987. $this->popExpect();
  988. if (PEAR::isError($result)) {
  989. if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
  990. $this->loadModule('Manager', null, true);
  991. $result = $this->manager->createSequence($seq_name);
  992. if (PEAR::isError($result)) {
  993. return $this->raiseError($result, null, null,
  994. 'on demand sequence '.$seq_name.' could not be created', __FUNCTION__);
  995. } else {
  996. return $this->nextID($seq_name, false);
  997. }
  998. }
  999. return $result;
  1000. }
  1001. $value = $this->lastInsertID();
  1002. if (is_numeric($value)) {
  1003. $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
  1004. $result =& $this->_doQuery($query, true);
  1005. if (PEAR::isError($result)) {
  1006. $this->warnings[] = 'nextID: could not delete previous sequence table values from '.$seq_name;
  1007. }
  1008. }
  1009. return $value;
  1010. }
  1011. // }}}
  1012. // {{{ lastInsertID()
  1013. /**
  1014. * Returns the autoincrement ID if supported or $id or fetches the current
  1015. * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
  1016. *
  1017. * @param string $table name of the table into which a new row was inserted
  1018. * @param string $field name of the field into which a new row was inserted
  1019. * @return mixed MDB2 Error Object or id
  1020. * @access public
  1021. */
  1022. function lastInsertID($table = null, $field = null)
  1023. {
  1024. // not using mysql_insert_id() due to http://pear.php.net/bugs/bug.php?id=8051
  1025. return $this->queryOne('SELECT LAST_INSERT_ID()', 'integer');
  1026. }
  1027. // }}}
  1028. // {{{ currID()
  1029. /**
  1030. * Returns the current id of a sequence
  1031. *
  1032. * @param string $seq_name name of the sequence
  1033. * @return mixed MDB2 Error Object or id
  1034. * @access public
  1035. */
  1036. function currID($seq_name)
  1037. {
  1038. $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
  1039. $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
  1040. $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
  1041. return $this->queryOne($query, 'integer');
  1042. }
  1043. }
  1044. /**
  1045. * MDB2 MySQL result driver
  1046. *
  1047. * @package MDB2
  1048. * @category Database
  1049. * @author Lukas Smith <smith@pooteeweet.org>
  1050. */
  1051. class MDB2_Result_mysql extends MDB2_Result_Common
  1052. {
  1053. // }}}
  1054. // {{{ fetchRow()
  1055. /**
  1056. * Fetch a row and insert the data into an existing array.
  1057. *
  1058. * @param int $fetchmode how the array data should be indexed
  1059. * @param int $rownum number of the row where the data can be found
  1060. * @return int data array on success, a MDB2 error on failure
  1061. * @access public
  1062. */
  1063. function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
  1064. {
  1065. if (!is_null($rownum)) {
  1066. $seek = $this->seek($rownum);
  1067. if (PEAR::isError($seek)) {
  1068. return $seek;
  1069. }
  1070. }
  1071. if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
  1072. $fetchmode = $this->db->fetchmode;
  1073. }
  1074. if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
  1075. $row = @mysql_fetch_assoc($this->result);
  1076. if (is_array($row)
  1077. && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
  1078. ) {
  1079. $row = array_change_key_case($row, $this->db->options['field_case']);
  1080. }
  1081. } else {
  1082. $row = @mysql_fetch_row($this->result);
  1083. }
  1084. if (!$row) {
  1085. if ($this->result === false) {
  1086. $err =& $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1087. 'resultset has already been freed', __FUNCTION__);
  1088. return $err;
  1089. }
  1090. $null = null;
  1091. return $null;
  1092. }
  1093. $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
  1094. if ($mode) {
  1095. $this->db->_fixResultArrayValues($row, $mode);
  1096. }
  1097. if (!empty($this->types)) {
  1098. $row = $this->db->datatype->convertResultRow($this->types, $row, false);
  1099. }
  1100. if (!empty($this->values)) {
  1101. $this->_assignBindColumns($row);
  1102. }
  1103. if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
  1104. $object_class = $this->db->options['fetch_class'];
  1105. if ($object_class == 'stdClass') {
  1106. $row = (object) $row;
  1107. } else {
  1108. $row = &new $object_class($row);
  1109. }
  1110. }
  1111. ++$this->rownum;
  1112. return $row;
  1113. }
  1114. // }}}
  1115. // {{{ _getColumnNames()
  1116. /**
  1117. * Retrieve the names of columns returned by the DBMS in a query result.
  1118. *
  1119. * @return mixed Array variable that holds the names of columns as keys
  1120. * or an MDB2 error on failure.
  1121. * Some DBMS may not return any columns when the result set
  1122. * does not contain any rows.
  1123. * @access private
  1124. */
  1125. function _getColumnNames()
  1126. {
  1127. $columns = array();
  1128. $numcols = $this->numCols();
  1129. if (PEAR::isError($numcols)) {
  1130. return $numcols;
  1131. }
  1132. for ($column = 0; $column < $numcols; $column++) {
  1133. $column_name = @mysql_field_name($this->result, $column);
  1134. $columns[$column_name] = $column;
  1135. }
  1136. if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  1137. $columns = array_change_key_case($columns, $this->db->options['field_case']);
  1138. }
  1139. return $columns;
  1140. }
  1141. // }}}
  1142. // {{{ numCols()
  1143. /**
  1144. * Count the number of columns returned by the DBMS in a query result.
  1145. *
  1146. * @return mixed integer value with the number of columns, a MDB2 error
  1147. * on failure
  1148. * @access public
  1149. */
  1150. function numCols()
  1151. {
  1152. $cols = @mysql_num_fields($this->result);
  1153. if (is_null($cols)) {
  1154. if ($this->result === false) {
  1155. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1156. 'resultset has already been freed', __FUNCTION__);
  1157. } elseif (is_null($this->result)) {
  1158. return count($this->types);
  1159. }
  1160. return $this->db->raiseError(null, null, null,
  1161. 'Could not get column count', __FUNCTION__);
  1162. }
  1163. return $cols;
  1164. }
  1165. // }}}
  1166. // {{{ free()
  1167. /**
  1168. * Free the internal resources associated with result.
  1169. *
  1170. * @return boolean true on success, false if result is invalid
  1171. * @access public
  1172. */
  1173. function free()
  1174. {
  1175. if (is_resource($this->result) && $this->db->connection) {
  1176. $free = @mysql_free_result($this->result);
  1177. if ($free === false) {
  1178. return $this->db->raiseError(null, null, null,
  1179. 'Could not free result', __FUNCTION__);
  1180. }
  1181. }
  1182. $this->result = false;
  1183. return MDB2_OK;
  1184. }
  1185. }
  1186. /**
  1187. * MDB2 MySQL buffered result driver
  1188. *
  1189. * @package MDB2
  1190. * @category Database
  1191. * @author Lukas Smith <smith@pooteeweet.org>
  1192. */
  1193. class MDB2_BufferedResult_mysql extends MDB2_Result_mysql
  1194. {
  1195. // }}}
  1196. // {{{ seek()
  1197. /**
  1198. * Seek to a specific row in a result set
  1199. *
  1200. * @param int $rownum number of the row where the data can be found
  1201. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1202. * @access public
  1203. */
  1204. function seek($rownum = 0)
  1205. {
  1206. if ($this->rownum != ($rownum - 1) && !@mysql_data_seek($this->result, $rownum)) {
  1207. if ($this->result === false) {
  1208. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1209. 'resultset has already been freed', __FUNCTION__);
  1210. } elseif (is_null($this->result)) {
  1211. return MDB2_OK;
  1212. }
  1213. return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
  1214. 'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
  1215. }
  1216. $this->rownum = $rownum - 1;
  1217. return MDB2_OK;
  1218. }
  1219. // }}}
  1220. // {{{ valid()
  1221. /**
  1222. * Check if the end of the result set has been reached
  1223. *
  1224. * @return mixed true or false on sucess, a MDB2 error on failure
  1225. * @access public
  1226. */
  1227. function valid()
  1228. {
  1229. $numrows = $this->numRows();
  1230. if (PEAR::isError($numrows)) {
  1231. return $numrows;
  1232. }
  1233. return $this->rownum < ($numrows - 1);
  1234. }
  1235. // }}}
  1236. // {{{ numRows()
  1237. /**
  1238. * Returns the number of rows in a result object
  1239. *
  1240. * @return mixed MDB2 Error Object or the number of rows
  1241. * @access public
  1242. */
  1243. function numRows()
  1244. {
  1245. $rows = @mysql_num_rows($this->result);
  1246. if (is_null($rows)) {
  1247. if ($this->result === false) {
  1248. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1249. 'resultset has already been freed', __FUNCTION__);
  1250. } elseif (is_null($this->result)) {
  1251. return 0;
  1252. }
  1253. return $this->db->raiseError(null, null, null,
  1254. 'Could not get row count', __FUNCTION__);
  1255. }
  1256. return $rows;
  1257. }
  1258. }
  1259. /**
  1260. * MDB2 MySQL statement driver
  1261. *
  1262. * @package MDB2
  1263. * @category Database
  1264. * @author Lukas Smith <smith@pooteeweet.org>
  1265. */
  1266. class MDB2_Statement_mysql extends MDB2_Statement_Common
  1267. {
  1268. // {{{ _execute()
  1269. /**
  1270. * Execute a prepared query statement helper method.
  1271. *
  1272. * @param mixed $result_class string which specifies which result class to use
  1273. * @param mixed $result_wrap_class string which specifies which class to wrap results in
  1274. * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
  1275. * @access private
  1276. */
  1277. function &_execute($result_class = true, $result_wrap_class = false)
  1278. {
  1279. if (is_null($this->statement)) {
  1280. $result =& parent::_execute($result_class, $result_wrap_class);
  1281. return $result;
  1282. }
  1283. $this->db->last_query = $this->query;
  1284. $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values));
  1285. if ($this->db->getOption('disable_query')) {
  1286. $result = $this->is_manip ? 0 : null;
  1287. return $result;
  1288. }
  1289. $connection = $this->db->getConnection();
  1290. if (PEAR::isError($connection)) {
  1291. return $connection;
  1292. }
  1293. $query = 'EXECUTE '.$this->statement;
  1294. if (!empty($this->positions)) {
  1295. $parameters = array();
  1296. foreach ($this->positions as $parameter) {
  1297. if (!array_key_exists($parameter, $this->values)) {
  1298. return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  1299. 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
  1300. }
  1301. $value = $this->values[$parameter];
  1302. $type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null;
  1303. if (is_resource($value) || $type == 'clob' || $type == 'blob') {
  1304. if (!is_resource($value) && preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {
  1305. if ($match[1] == 'file://') {
  1306. $value = $match[2];
  1307. }
  1308. $value = @fopen($value, 'r');
  1309. $close = true;
  1310. }
  1311. if (is_resource($value)) {
  1312. $data = '';
  1313. while (!@feof($value)) {
  1314. $data.= @fread($value, $this->db->options['lob_buffer_length']);
  1315. }
  1316. if ($close) {
  1317. @fclose($value);
  1318. }
  1319. $value = $data;
  1320. }
  1321. }
  1322. $quoted = $this->db->quote($value, $type);
  1323. if (PEAR::isError($quoted)) {
  1324. return $quoted;
  1325. }
  1326. $param_query = 'SET @'.$parameter.' = '.$quoted;
  1327. $result = $this->db->_doQuery($param_query, true, $connection);
  1328. if (PEAR::isError($result)) {
  1329. return $result;
  1330. }
  1331. }
  1332. $query.= ' USING @'.implode(', @', array_values($this->positions));
  1333. }
  1334. $result = $this->db->_doQuery($query, $this->is_manip, $connection);
  1335. if (PEAR::isError($result)) {
  1336. return $result;
  1337. }
  1338. if ($this->is_manip) {
  1339. $affected_rows = $this->db->_affectedRows($connection, $result);
  1340. return $affected_rows;
  1341. }
  1342. $result =& $this->db->_wrapResult($result, $this->result_types,
  1343. $result_class, $result_wrap_class, $this->limit, $this->offset);
  1344. $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result));
  1345. return $result;
  1346. }
  1347. // }}}
  1348. // {{{ free()
  1349. /**
  1350. * Release resources allocated for the specified prepared query.
  1351. *
  1352. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1353. * @access public
  1354. */
  1355. function free()
  1356. {
  1357. if (is_null($this->positions)) {
  1358. return $this->db->raiseError(MDB2_ERROR, null, null,
  1359. 'Prepared statement has already been freed', __FUNCTION__);
  1360. }
  1361. $result = MDB2_OK;
  1362. if (!is_null($this->statement)) {
  1363. $connection = $this->db->getConnection();
  1364. if (PEAR::isError($connection)) {
  1365. return $connection;
  1366. }
  1367. $query = 'DEALLOCATE PREPARE '.$this->statement;
  1368. $result = $this->db->_doQuery($query, true, $connection);
  1369. }
  1370. parent::free();
  1371. return $result;
  1372. }
  1373. }
  1374. ?>