PageRenderTime 33ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/includes/external/MDB2/Driver/mysqli.php

https://bitbucket.org/djl/flyspray-mirror
PHP | 1841 lines | 1172 code | 144 blank | 525 comment | 248 complexity | 227f2137194d4e2e79a032e53d7dc075 MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0, BSD-3-Clause, MPL-2.0-no-copyleft-exception
  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: mysqli.php,v 1.188 2008/03/13 03:31:55 afz Exp $
  47. //
  48. /**
  49. * MDB2 MySQLi driver
  50. *
  51. * @package MDB2
  52. * @category Database
  53. * @author Lukas Smith <smith@pooteeweet.org>
  54. */
  55. class MDB2_Driver_mysqli 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 $server_capabilities_checked = false;
  66. var $start_transaction = false;
  67. var $varchar_max_length = 255;
  68. // }}}
  69. // {{{ constructor
  70. /**
  71. * Constructor
  72. */
  73. function __construct()
  74. {
  75. parent::__construct();
  76. $this->phptype = 'mysqli';
  77. $this->dbsyntax = 'mysql';
  78. $this->supported['sequences'] = 'emulated';
  79. $this->supported['indexes'] = true;
  80. $this->supported['affected_rows'] = true;
  81. $this->supported['transactions'] = false;
  82. $this->supported['savepoints'] = false;
  83. $this->supported['summary_functions'] = true;
  84. $this->supported['order_by_text'] = true;
  85. $this->supported['current_id'] = 'emulated';
  86. $this->supported['limit_queries'] = true;
  87. $this->supported['LOBs'] = true;
  88. $this->supported['replace'] = true;
  89. $this->supported['sub_selects'] = 'emulated';
  90. $this->supported['triggers'] = false;
  91. $this->supported['auto_increment'] = true;
  92. $this->supported['primary_key'] = true;
  93. $this->supported['result_introspection'] = true;
  94. $this->supported['prepared_statements'] = 'emulated';
  95. $this->supported['identifier_quoting'] = true;
  96. $this->supported['pattern_escaping'] = true;
  97. $this->supported['new_link'] = true;
  98. $this->options['DBA_username'] = false;
  99. $this->options['DBA_password'] = false;
  100. $this->options['default_table_type'] = '';
  101. $this->options['multi_query'] = false;
  102. $this->options['max_identifiers_length'] = 64;
  103. $this->_reCheckSupportedOptions();
  104. }
  105. // }}}
  106. // {{{ _reCheckSupportedOptions()
  107. /**
  108. * If the user changes certain options, other capabilities may depend
  109. * on the new settings, so we need to check them (again).
  110. *
  111. * @access private
  112. */
  113. function _reCheckSupportedOptions()
  114. {
  115. $this->supported['transactions'] = $this->options['use_transactions'];
  116. $this->supported['savepoints'] = $this->options['use_transactions'];
  117. if ($this->options['default_table_type']) {
  118. switch (strtoupper($this->options['default_table_type'])) {
  119. case 'BLACKHOLE':
  120. case 'MEMORY':
  121. case 'ARCHIVE':
  122. case 'CSV':
  123. case 'HEAP':
  124. case 'ISAM':
  125. case 'MERGE':
  126. case 'MRG_ISAM':
  127. case 'ISAM':
  128. case 'MRG_MYISAM':
  129. case 'MYISAM':
  130. $this->supported['savepoints'] = false;
  131. $this->supported['transactions'] = false;
  132. $this->warnings[] = $this->options['default_table_type'] .
  133. ' is not a supported default table type';
  134. break;
  135. }
  136. }
  137. }
  138. // }}}
  139. // {{{ function setOption($option, $value)
  140. /**
  141. * set the option for the db class
  142. *
  143. * @param string option name
  144. * @param mixed value for the option
  145. *
  146. * @return mixed MDB2_OK or MDB2 Error Object
  147. *
  148. * @access public
  149. */
  150. function setOption($option, $value)
  151. {
  152. $res = parent::setOption($option, $value);
  153. $this->_reCheckSupportedOptions();
  154. }
  155. // }}}
  156. // {{{ errorInfo()
  157. /**
  158. * This method is used to collect information about an error
  159. *
  160. * @param integer $error
  161. * @return array
  162. * @access public
  163. */
  164. function errorInfo($error = null)
  165. {
  166. if ($this->connection) {
  167. $native_code = @mysqli_errno($this->connection);
  168. $native_msg = @mysqli_error($this->connection);
  169. } else {
  170. $native_code = @mysqli_connect_errno();
  171. $native_msg = @mysqli_connect_error();
  172. }
  173. if (is_null($error)) {
  174. static $ecode_map;
  175. if (empty($ecode_map)) {
  176. $ecode_map = array(
  177. 1000 => MDB2_ERROR_INVALID, //hashchk
  178. 1001 => MDB2_ERROR_INVALID, //isamchk
  179. 1004 => MDB2_ERROR_CANNOT_CREATE,
  180. 1005 => MDB2_ERROR_CANNOT_CREATE,
  181. 1006 => MDB2_ERROR_CANNOT_CREATE,
  182. 1007 => MDB2_ERROR_ALREADY_EXISTS,
  183. 1008 => MDB2_ERROR_CANNOT_DROP,
  184. 1009 => MDB2_ERROR_CANNOT_DROP,
  185. 1010 => MDB2_ERROR_CANNOT_DROP,
  186. 1011 => MDB2_ERROR_CANNOT_DELETE,
  187. 1022 => MDB2_ERROR_ALREADY_EXISTS,
  188. 1029 => MDB2_ERROR_NOT_FOUND,
  189. 1032 => MDB2_ERROR_NOT_FOUND,
  190. 1044 => MDB2_ERROR_ACCESS_VIOLATION,
  191. 1045 => MDB2_ERROR_ACCESS_VIOLATION,
  192. 1046 => MDB2_ERROR_NODBSELECTED,
  193. 1048 => MDB2_ERROR_CONSTRAINT,
  194. 1049 => MDB2_ERROR_NOSUCHDB,
  195. 1050 => MDB2_ERROR_ALREADY_EXISTS,
  196. 1051 => MDB2_ERROR_NOSUCHTABLE,
  197. 1054 => MDB2_ERROR_NOSUCHFIELD,
  198. 1060 => MDB2_ERROR_ALREADY_EXISTS,
  199. 1061 => MDB2_ERROR_ALREADY_EXISTS,
  200. 1062 => MDB2_ERROR_ALREADY_EXISTS,
  201. 1064 => MDB2_ERROR_SYNTAX,
  202. 1067 => MDB2_ERROR_INVALID,
  203. 1072 => MDB2_ERROR_NOT_FOUND,
  204. 1086 => MDB2_ERROR_ALREADY_EXISTS,
  205. 1091 => MDB2_ERROR_NOT_FOUND,
  206. 1100 => MDB2_ERROR_NOT_LOCKED,
  207. 1109 => MDB2_ERROR_NOT_FOUND,
  208. 1125 => MDB2_ERROR_ALREADY_EXISTS,
  209. 1136 => MDB2_ERROR_VALUE_COUNT_ON_ROW,
  210. 1138 => MDB2_ERROR_INVALID,
  211. 1142 => MDB2_ERROR_ACCESS_VIOLATION,
  212. 1143 => MDB2_ERROR_ACCESS_VIOLATION,
  213. 1146 => MDB2_ERROR_NOSUCHTABLE,
  214. 1149 => MDB2_ERROR_SYNTAX,
  215. 1169 => MDB2_ERROR_CONSTRAINT,
  216. 1176 => MDB2_ERROR_NOT_FOUND,
  217. 1177 => MDB2_ERROR_NOSUCHTABLE,
  218. 1213 => MDB2_ERROR_DEADLOCK,
  219. 1216 => MDB2_ERROR_CONSTRAINT,
  220. 1217 => MDB2_ERROR_CONSTRAINT,
  221. 1227 => MDB2_ERROR_ACCESS_VIOLATION,
  222. 1235 => MDB2_ERROR_CANNOT_CREATE,
  223. 1299 => MDB2_ERROR_INVALID_DATE,
  224. 1300 => MDB2_ERROR_INVALID,
  225. 1304 => MDB2_ERROR_ALREADY_EXISTS,
  226. 1305 => MDB2_ERROR_NOT_FOUND,
  227. 1306 => MDB2_ERROR_CANNOT_DROP,
  228. 1307 => MDB2_ERROR_CANNOT_CREATE,
  229. 1334 => MDB2_ERROR_CANNOT_ALTER,
  230. 1339 => MDB2_ERROR_NOT_FOUND,
  231. 1356 => MDB2_ERROR_INVALID,
  232. 1359 => MDB2_ERROR_ALREADY_EXISTS,
  233. 1360 => MDB2_ERROR_NOT_FOUND,
  234. 1363 => MDB2_ERROR_NOT_FOUND,
  235. 1365 => MDB2_ERROR_DIVZERO,
  236. 1451 => MDB2_ERROR_CONSTRAINT,
  237. 1452 => MDB2_ERROR_CONSTRAINT,
  238. 1542 => MDB2_ERROR_CANNOT_DROP,
  239. 1546 => MDB2_ERROR_CONSTRAINT,
  240. 1582 => MDB2_ERROR_CONSTRAINT,
  241. 2003 => MDB2_ERROR_CONNECT_FAILED,
  242. 2019 => MDB2_ERROR_INVALID,
  243. );
  244. }
  245. if ($this->options['portability'] & MDB2_PORTABILITY_ERRORS) {
  246. $ecode_map[1022] = MDB2_ERROR_CONSTRAINT;
  247. $ecode_map[1048] = MDB2_ERROR_CONSTRAINT_NOT_NULL;
  248. $ecode_map[1062] = MDB2_ERROR_CONSTRAINT;
  249. } else {
  250. // Doing this in case mode changes during runtime.
  251. $ecode_map[1022] = MDB2_ERROR_ALREADY_EXISTS;
  252. $ecode_map[1048] = MDB2_ERROR_CONSTRAINT;
  253. $ecode_map[1062] = MDB2_ERROR_ALREADY_EXISTS;
  254. }
  255. if (isset($ecode_map[$native_code])) {
  256. $error = $ecode_map[$native_code];
  257. }
  258. }
  259. return array($error, $native_code, $native_msg);
  260. }
  261. // }}}
  262. // {{{ escape()
  263. /**
  264. * Quotes a string so it can be safely used in a query. It will quote
  265. * the text so it can safely be used within a query.
  266. *
  267. * @param string the input string to quote
  268. * @param bool escape wildcards
  269. *
  270. * @return string quoted string
  271. *
  272. * @access public
  273. */
  274. function escape($text, $escape_wildcards = false)
  275. {
  276. if ($escape_wildcards) {
  277. $text = $this->escapePattern($text);
  278. }
  279. $connection = $this->getConnection();
  280. if (PEAR::isError($connection)) {
  281. return $connection;
  282. }
  283. $text = @mysqli_real_escape_string($connection, $text);
  284. return $text;
  285. }
  286. // }}}
  287. // {{{ beginTransaction()
  288. /**
  289. * Start a transaction or set a savepoint.
  290. *
  291. * @param string name of a savepoint to set
  292. * @return mixed MDB2_OK on success, a MDB2 error on failure
  293. *
  294. * @access public
  295. */
  296. function beginTransaction($savepoint = null)
  297. {
  298. $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  299. $this->_getServerCapabilities();
  300. if (!is_null($savepoint)) {
  301. if (!$this->supports('savepoints')) {
  302. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  303. 'savepoints are not supported', __FUNCTION__);
  304. }
  305. if (!$this->in_transaction) {
  306. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  307. 'savepoint cannot be released when changes are auto committed', __FUNCTION__);
  308. }
  309. $query = 'SAVEPOINT '.$savepoint;
  310. return $this->_doQuery($query, true);
  311. } elseif ($this->in_transaction) {
  312. return MDB2_OK; //nothing to do
  313. }
  314. $query = $this->start_transaction ? 'START TRANSACTION' : 'SET AUTOCOMMIT = 1';
  315. $result =& $this->_doQuery($query, true);
  316. if (PEAR::isError($result)) {
  317. return $result;
  318. }
  319. $this->in_transaction = true;
  320. return MDB2_OK;
  321. }
  322. // }}}
  323. // {{{ commit()
  324. /**
  325. * Commit the database changes done during a transaction that is in
  326. * progress or release a savepoint. This function may only be called when
  327. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  328. * transaction is implicitly started after committing the pending changes.
  329. *
  330. * @param string name of a savepoint to release
  331. * @return mixed MDB2_OK on success, a MDB2 error on failure
  332. *
  333. * @access public
  334. */
  335. function commit($savepoint = null)
  336. {
  337. $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  338. if (!$this->in_transaction) {
  339. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  340. 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
  341. }
  342. if (!is_null($savepoint)) {
  343. if (!$this->supports('savepoints')) {
  344. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  345. 'savepoints are not supported', __FUNCTION__);
  346. }
  347. $server_info = $this->getServerVersion();
  348. if (version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '5.0.3', '<')) {
  349. return MDB2_OK;
  350. }
  351. $query = 'RELEASE SAVEPOINT '.$savepoint;
  352. return $this->_doQuery($query, true);
  353. }
  354. if (!$this->supports('transactions')) {
  355. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  356. 'transactions are not supported', __FUNCTION__);
  357. }
  358. $result =& $this->_doQuery('COMMIT', true);
  359. if (PEAR::isError($result)) {
  360. return $result;
  361. }
  362. if (!$this->start_transaction) {
  363. $query = 'SET AUTOCOMMIT = 0';
  364. $result =& $this->_doQuery($query, true);
  365. if (PEAR::isError($result)) {
  366. return $result;
  367. }
  368. }
  369. $this->in_transaction = false;
  370. return MDB2_OK;
  371. }
  372. // }}}
  373. // {{{ rollback()
  374. /**
  375. * Cancel any database changes done during a transaction or since a specific
  376. * savepoint that is in progress. This function may only be called when
  377. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  378. * transaction is implicitly started after canceling the pending changes.
  379. *
  380. * @param string name of a savepoint to rollback to
  381. * @return mixed MDB2_OK on success, a MDB2 error on failure
  382. *
  383. * @access public
  384. */
  385. function rollback($savepoint = null)
  386. {
  387. $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  388. if (!$this->in_transaction) {
  389. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  390. 'rollback cannot be done changes are auto committed', __FUNCTION__);
  391. }
  392. if (!is_null($savepoint)) {
  393. if (!$this->supports('savepoints')) {
  394. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  395. 'savepoints are not supported', __FUNCTION__);
  396. }
  397. $query = 'ROLLBACK TO SAVEPOINT '.$savepoint;
  398. return $this->_doQuery($query, true);
  399. }
  400. $query = 'ROLLBACK';
  401. $result =& $this->_doQuery($query, true);
  402. if (PEAR::isError($result)) {
  403. return $result;
  404. }
  405. if (!$this->start_transaction) {
  406. $query = 'SET AUTOCOMMIT = 0';
  407. $result =& $this->_doQuery($query, true);
  408. if (PEAR::isError($result)) {
  409. return $result;
  410. }
  411. }
  412. $this->in_transaction = false;
  413. return MDB2_OK;
  414. }
  415. // }}}
  416. // {{{ function setTransactionIsolation()
  417. /**
  418. * Set the transacton isolation level.
  419. *
  420. * @param string standard isolation level
  421. * READ UNCOMMITTED (allows dirty reads)
  422. * READ COMMITTED (prevents dirty reads)
  423. * REPEATABLE READ (prevents nonrepeatable reads)
  424. * SERIALIZABLE (prevents phantom reads)
  425. * @return mixed MDB2_OK on success, a MDB2 error on failure
  426. *
  427. * @access public
  428. * @since 2.1.1
  429. */
  430. function setTransactionIsolation($isolation)
  431. {
  432. $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
  433. if (!$this->supports('transactions')) {
  434. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  435. 'transactions are not supported', __FUNCTION__);
  436. }
  437. switch ($isolation) {
  438. case 'READ UNCOMMITTED':
  439. case 'READ COMMITTED':
  440. case 'REPEATABLE READ':
  441. case 'SERIALIZABLE':
  442. break;
  443. default:
  444. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  445. 'isolation level is not supported: '.$isolation, __FUNCTION__);
  446. }
  447. $query = "SET SESSION TRANSACTION ISOLATION LEVEL $isolation";
  448. return $this->_doQuery($query, true);
  449. }
  450. // }}}
  451. // {{{ _doConnect()
  452. /**
  453. * do the grunt work of the connect
  454. *
  455. * @return connection on success or MDB2 Error Object on failure
  456. * @access protected
  457. */
  458. function _doConnect($username, $password, $persistent = false)
  459. {
  460. if (!PEAR::loadExtension($this->phptype)) {
  461. return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  462. 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
  463. }
  464. $connection = @mysqli_init();
  465. if (!empty($this->dsn['charset']) && defined('MYSQLI_SET_CHARSET_NAME')) {
  466. @mysqli_options($connection, MYSQLI_SET_CHARSET_NAME, $this->dsn['charset']);
  467. }
  468. if ($this->options['ssl']) {
  469. @mysqli_ssl_set(
  470. $connection,
  471. empty($this->dsn['key']) ? null : $this->dsn['key'],
  472. empty($this->dsn['cert']) ? null : $this->dsn['cert'],
  473. empty($this->dsn['ca']) ? null : $this->dsn['ca'],
  474. empty($this->dsn['capath']) ? null : $this->dsn['capath'],
  475. empty($this->dsn['cipher']) ? null : $this->dsn['cipher']
  476. );
  477. }
  478. if (!@mysqli_real_connect(
  479. $connection,
  480. $this->dsn['hostspec'],
  481. $username,
  482. $password,
  483. $this->database_name,
  484. $this->dsn['port'],
  485. $this->dsn['socket']
  486. )) {
  487. if (($err = @mysqli_connect_error()) != '') {
  488. return $this->raiseError(null,
  489. null, null, $err, __FUNCTION__);
  490. } else {
  491. return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
  492. 'unable to establish a connection', __FUNCTION__);
  493. }
  494. }
  495. if (!empty($this->dsn['charset']) && !defined('MYSQLI_SET_CHARSET_NAME')) {
  496. $result = $this->setCharset($this->dsn['charset'], $connection);
  497. if (PEAR::isError($result)) {
  498. return $result;
  499. }
  500. }
  501. return $connection;
  502. }
  503. // }}}
  504. // {{{ connect()
  505. /**
  506. * Connect to the database
  507. *
  508. * @return true on success, MDB2 Error Object on failure
  509. */
  510. function connect()
  511. {
  512. if (is_object($this->connection)) {
  513. //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0) {
  514. if (MDB2::areEquals($this->connected_dsn, $this->dsn)) {
  515. return MDB2_OK;
  516. }
  517. $this->connection = 0;
  518. }
  519. $connection = $this->_doConnect(
  520. $this->dsn['username'],
  521. $this->dsn['password']
  522. );
  523. if (PEAR::isError($connection)) {
  524. return $connection;
  525. }
  526. $this->connection = $connection;
  527. $this->connected_dsn = $this->dsn;
  528. $this->connected_database_name = $this->database_name;
  529. $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
  530. $this->_getServerCapabilities();
  531. return MDB2_OK;
  532. }
  533. // }}}
  534. // {{{ setCharset()
  535. /**
  536. * Set the charset on the current connection
  537. *
  538. * @param string charset (or array(charset, collation))
  539. * @param resource connection handle
  540. *
  541. * @return true on success, MDB2 Error Object on failure
  542. */
  543. function setCharset($charset, $connection = null)
  544. {
  545. if (is_null($connection)) {
  546. $connection = $this->getConnection();
  547. if (PEAR::isError($connection)) {
  548. return $connection;
  549. }
  550. }
  551. $collation = null;
  552. if (is_array($charset) && 2 == count($charset)) {
  553. $collation = array_pop($charset);
  554. $charset = array_pop($charset);
  555. }
  556. $client_info = mysqli_get_client_version();
  557. if (OS_WINDOWS && ((40111 > $client_info) ||
  558. ((50000 <= $client_info) && (50006 > $client_info)))
  559. ) {
  560. $query = "SET NAMES '".mysqli_real_escape_string($connection, $charset)."'";
  561. if (!is_null($collation)) {
  562. $query .= " COLLATE '".mysqli_real_escape_string($connection, $collation)."'";
  563. }
  564. return $this->_doQuery($query, true, $connection);
  565. }
  566. if (!$result = mysqli_set_charset($connection, $charset)) {
  567. $err =& $this->raiseError(null, null, null,
  568. 'Could not set client character set', __FUNCTION__);
  569. return $err;
  570. }
  571. return $result;
  572. }
  573. // }}}
  574. // {{{ databaseExists()
  575. /**
  576. * check if given database name is exists?
  577. *
  578. * @param string $name name of the database that should be checked
  579. *
  580. * @return mixed true/false on success, a MDB2 error on failure
  581. * @access public
  582. */
  583. function databaseExists($name)
  584. {
  585. $connection = $this->_doConnect($this->dsn['username'],
  586. $this->dsn['password']);
  587. if (PEAR::isError($connection)) {
  588. return $connection;
  589. }
  590. $result = @mysqli_select_db($connection, $name);
  591. @mysqli_close($connection);
  592. return $result;
  593. }
  594. // }}}
  595. // {{{ disconnect()
  596. /**
  597. * Log out and disconnect from the database.
  598. *
  599. * @param boolean $force if the disconnect should be forced even if the
  600. * connection is opened persistently
  601. * @return mixed true on success, false if not connected and error
  602. * object on error
  603. * @access public
  604. */
  605. function disconnect($force = true)
  606. {
  607. if (is_object($this->connection)) {
  608. if ($this->in_transaction) {
  609. $dsn = $this->dsn;
  610. $database_name = $this->database_name;
  611. $persistent = $this->options['persistent'];
  612. $this->dsn = $this->connected_dsn;
  613. $this->database_name = $this->connected_database_name;
  614. $this->options['persistent'] = $this->opened_persistent;
  615. $this->rollback();
  616. $this->dsn = $dsn;
  617. $this->database_name = $database_name;
  618. $this->options['persistent'] = $persistent;
  619. }
  620. if ($force) {
  621. @mysqli_close($this->connection);
  622. }
  623. }
  624. return parent::disconnect($force);
  625. }
  626. // }}}
  627. // {{{ standaloneQuery()
  628. /**
  629. * execute a query as DBA
  630. *
  631. * @param string $query the SQL query
  632. * @param mixed $types array that contains the types of the columns in
  633. * the result set
  634. * @param boolean $is_manip if the query is a manipulation query
  635. * @return mixed MDB2_OK on success, a MDB2 error on failure
  636. * @access public
  637. */
  638. function &standaloneQuery($query, $types = null, $is_manip = false)
  639. {
  640. $user = $this->options['DBA_username']? $this->options['DBA_username'] : $this->dsn['username'];
  641. $pass = $this->options['DBA_password']? $this->options['DBA_password'] : $this->dsn['password'];
  642. $connection = $this->_doConnect($user, $pass);
  643. if (PEAR::isError($connection)) {
  644. return $connection;
  645. }
  646. $offset = $this->offset;
  647. $limit = $this->limit;
  648. $this->offset = $this->limit = 0;
  649. $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
  650. $result =& $this->_doQuery($query, $is_manip, $connection, $this->database_name);
  651. if (!PEAR::isError($result)) {
  652. $result = $this->_affectedRows($connection, $result);
  653. }
  654. @mysqli_close($connection);
  655. return $result;
  656. }
  657. // }}}
  658. // {{{ _doQuery()
  659. /**
  660. * Execute a query
  661. * @param string $query query
  662. * @param boolean $is_manip if the query is a manipulation query
  663. * @param resource $connection
  664. * @param string $database_name
  665. * @return result or error object
  666. * @access protected
  667. */
  668. function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
  669. {
  670. $this->last_query = $query;
  671. $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
  672. if ($result) {
  673. if (PEAR::isError($result)) {
  674. return $result;
  675. }
  676. $query = $result;
  677. }
  678. if ($this->options['disable_query']) {
  679. $result = $is_manip ? 0 : null;
  680. return $result;
  681. }
  682. if (is_null($connection)) {
  683. $connection = $this->getConnection();
  684. if (PEAR::isError($connection)) {
  685. return $connection;
  686. }
  687. }
  688. if (is_null($database_name)) {
  689. $database_name = $this->database_name;
  690. }
  691. if ($database_name) {
  692. if ($database_name != $this->connected_database_name) {
  693. if (!@mysqli_select_db($connection, $database_name)) {
  694. $err = $this->raiseError(null, null, null,
  695. 'Could not select the database: '.$database_name, __FUNCTION__);
  696. return $err;
  697. }
  698. $this->connected_database_name = $database_name;
  699. }
  700. }
  701. if ($this->options['multi_query']) {
  702. $result = mysqli_multi_query($connection, $query);
  703. } else {
  704. $resultmode = $this->options['result_buffering'] ? MYSQLI_USE_RESULT : MYSQLI_USE_RESULT;
  705. $result = mysqli_query($connection, $query);
  706. }
  707. if (!$result) {
  708. $err =& $this->raiseError(null, null, null,
  709. 'Could not execute statement', __FUNCTION__);
  710. return $err;
  711. }
  712. if ($this->options['multi_query']) {
  713. if ($this->options['result_buffering']) {
  714. if (!($result = @mysqli_store_result($connection))) {
  715. $err =& $this->raiseError(null, null, null,
  716. 'Could not get the first result from a multi query', __FUNCTION__);
  717. return $err;
  718. }
  719. } elseif (!($result = @mysqli_use_result($connection))) {
  720. $err =& $this->raiseError(null, null, null,
  721. 'Could not get the first result from a multi query', __FUNCTION__);
  722. return $err;
  723. }
  724. }
  725. $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
  726. return $result;
  727. }
  728. // }}}
  729. // {{{ _affectedRows()
  730. /**
  731. * Returns the number of rows affected
  732. *
  733. * @param resource $result
  734. * @param resource $connection
  735. * @return mixed MDB2 Error Object or the number of rows affected
  736. * @access private
  737. */
  738. function _affectedRows($connection, $result = null)
  739. {
  740. if (is_null($connection)) {
  741. $connection = $this->getConnection();
  742. if (PEAR::isError($connection)) {
  743. return $connection;
  744. }
  745. }
  746. return @mysqli_affected_rows($connection);
  747. }
  748. // }}}
  749. // {{{ _modifyQuery()
  750. /**
  751. * Changes a query string for various DBMS specific reasons
  752. *
  753. * @param string $query query to modify
  754. * @param boolean $is_manip if it is a DML query
  755. * @param integer $limit limit the number of rows
  756. * @param integer $offset start reading from given offset
  757. * @return string modified query
  758. * @access protected
  759. */
  760. function _modifyQuery($query, $is_manip, $limit, $offset)
  761. {
  762. if ($this->options['portability'] & MDB2_PORTABILITY_DELETE_COUNT) {
  763. // "DELETE FROM table" gives 0 affected rows in MySQL.
  764. // This little hack lets you know how many rows were deleted.
  765. if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
  766. $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
  767. 'DELETE FROM \1 WHERE 1=1', $query);
  768. }
  769. }
  770. if ($limit > 0
  771. && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)
  772. ) {
  773. $query = rtrim($query);
  774. if (substr($query, -1) == ';') {
  775. $query = substr($query, 0, -1);
  776. }
  777. // LIMIT doesn't always come last in the query
  778. // @see http://dev.mysql.com/doc/refman/5.0/en/select.html
  779. $after = '';
  780. if (preg_match('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims', $query, $matches)) {
  781. $after = $matches[0];
  782. $query = preg_replace('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims', '', $query);
  783. } elseif (preg_match('/(\s+FOR\s+UPDATE\s*)$/i', $query, $matches)) {
  784. $after = $matches[0];
  785. $query = preg_replace('/(\s+FOR\s+UPDATE\s*)$/im', '', $query);
  786. } elseif (preg_match('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im', $query, $matches)) {
  787. $after = $matches[0];
  788. $query = preg_replace('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im', '', $query);
  789. }
  790. if ($is_manip) {
  791. return $query . " LIMIT $limit" . $after;
  792. } else {
  793. return $query . " LIMIT $offset, $limit" . $after;
  794. }
  795. }
  796. return $query;
  797. }
  798. // }}}
  799. // {{{ getServerVersion()
  800. /**
  801. * return version information about the server
  802. *
  803. * @param bool $native determines if the raw version string should be returned
  804. * @return mixed array/string with version information or MDB2 error object
  805. * @access public
  806. */
  807. function getServerVersion($native = false)
  808. {
  809. $connection = $this->getConnection();
  810. if (PEAR::isError($connection)) {
  811. return $connection;
  812. }
  813. if ($this->connected_server_info) {
  814. $server_info = $this->connected_server_info;
  815. } else {
  816. $server_info = @mysqli_get_server_info($connection);
  817. }
  818. if (!$server_info) {
  819. return $this->raiseError(null, null, null,
  820. 'Could not get server information', __FUNCTION__);
  821. }
  822. // cache server_info
  823. $this->connected_server_info = $server_info;
  824. if (!$native) {
  825. $tmp = explode('.', $server_info, 3);
  826. if (isset($tmp[2]) && strpos($tmp[2], '-')) {
  827. $tmp2 = explode('-', @$tmp[2], 2);
  828. } else {
  829. $tmp2[0] = isset($tmp[2]) ? $tmp[2] : null;
  830. $tmp2[1] = null;
  831. }
  832. $server_info = array(
  833. 'major' => isset($tmp[0]) ? $tmp[0] : null,
  834. 'minor' => isset($tmp[1]) ? $tmp[1] : null,
  835. 'patch' => $tmp2[0],
  836. 'extra' => $tmp2[1],
  837. 'native' => $server_info,
  838. );
  839. }
  840. return $server_info;
  841. }
  842. // }}}
  843. // {{{ _getServerCapabilities()
  844. /**
  845. * Fetch some information about the server capabilities
  846. * (transactions, subselects, prepared statements, etc).
  847. *
  848. * @access private
  849. */
  850. function _getServerCapabilities()
  851. {
  852. if (!$this->server_capabilities_checked) {
  853. $this->server_capabilities_checked = true;
  854. //set defaults
  855. $this->supported['sub_selects'] = 'emulated';
  856. $this->supported['prepared_statements'] = 'emulated';
  857. $this->supported['triggers'] = false;
  858. $this->start_transaction = false;
  859. $this->varchar_max_length = 255;
  860. $server_info = $this->getServerVersion();
  861. if (is_array($server_info)) {
  862. $server_version = $server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'];
  863. if (!version_compare($server_version, '4.1.0', '<')) {
  864. $this->supported['sub_selects'] = true;
  865. $this->supported['prepared_statements'] = true;
  866. }
  867. // SAVEPOINTS were introduced in MySQL 4.0.14 and 4.1.1 (InnoDB)
  868. if (version_compare($server_version, '4.1.0', '>=')) {
  869. if (version_compare($server_version, '4.1.1', '<')) {
  870. $this->supported['savepoints'] = false;
  871. }
  872. } elseif (version_compare($server_version, '4.0.14', '<')) {
  873. $this->supported['savepoints'] = false;
  874. }
  875. if (!version_compare($server_version, '4.0.11', '<')) {
  876. $this->start_transaction = true;
  877. }
  878. if (!version_compare($server_version, '5.0.3', '<')) {
  879. $this->varchar_max_length = 65532;
  880. }
  881. if (!version_compare($server_version, '5.0.2', '<')) {
  882. $this->supported['triggers'] = true;
  883. }
  884. }
  885. }
  886. }
  887. // }}}
  888. // {{{ function _skipUserDefinedVariable($query, $position)
  889. /**
  890. * Utility method, used by prepare() to avoid misinterpreting MySQL user
  891. * defined variables (SELECT @x:=5) for placeholders.
  892. * Check if the placeholder is a false positive, i.e. if it is an user defined
  893. * variable instead. If so, skip it and advance the position, otherwise
  894. * return the current position, which is valid
  895. *
  896. * @param string $query
  897. * @param integer $position current string cursor position
  898. * @return integer $new_position
  899. * @access protected
  900. */
  901. function _skipUserDefinedVariable($query, $position)
  902. {
  903. $found = strpos(strrev(substr($query, 0, $position)), '@');
  904. if ($found === false) {
  905. return $position;
  906. }
  907. $pos = strlen($query) - strlen(substr($query, $position)) - $found - 1;
  908. $substring = substr($query, $pos, $position - $pos + 2);
  909. if (preg_match('/^@\w+\s*:=$/', $substring)) {
  910. return $position + 1; //found an user defined variable: skip it
  911. }
  912. return $position;
  913. }
  914. // }}}
  915. // {{{ prepare()
  916. /**
  917. * Prepares a query for multiple execution with execute().
  918. * With some database backends, this is emulated.
  919. * prepare() requires a generic query as string like
  920. * 'INSERT INTO numbers VALUES(?,?)' or
  921. * 'INSERT INTO numbers VALUES(:foo,:bar)'.
  922. * The ? and :name and are placeholders which can be set using
  923. * bindParam() and the query can be sent off using the execute() method.
  924. * The allowed format for :name can be set with the 'bindname_format' option.
  925. *
  926. * @param string $query the query to prepare
  927. * @param mixed $types array that contains the types of the placeholders
  928. * @param mixed $result_types array that contains the types of the columns in
  929. * the result set or MDB2_PREPARE_RESULT, if set to
  930. * MDB2_PREPARE_MANIP the query is handled as a manipulation query
  931. * @param mixed $lobs key (field) value (parameter) pair for all lob placeholders
  932. * @return mixed resource handle for the prepared query on success, a MDB2
  933. * error on failure
  934. * @access public
  935. * @see bindParam, execute
  936. */
  937. function &prepare($query, $types = null, $result_types = null, $lobs = array())
  938. {
  939. if ($this->options['emulate_prepared']
  940. || $this->supported['prepared_statements'] !== true
  941. ) {
  942. $obj =& parent::prepare($query, $types, $result_types, $lobs);
  943. return $obj;
  944. }
  945. $is_manip = ($result_types === MDB2_PREPARE_MANIP);
  946. $offset = $this->offset;
  947. $limit = $this->limit;
  948. $this->offset = $this->limit = 0;
  949. $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
  950. $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
  951. if ($result) {
  952. if (PEAR::isError($result)) {
  953. return $result;
  954. }
  955. $query = $result;
  956. }
  957. $placeholder_type_guess = $placeholder_type = null;
  958. $question = '?';
  959. $colon = ':';
  960. $positions = array();
  961. $position = 0;
  962. while ($position < strlen($query)) {
  963. $q_position = strpos($query, $question, $position);
  964. $c_position = strpos($query, $colon, $position);
  965. if ($q_position && $c_position) {
  966. $p_position = min($q_position, $c_position);
  967. } elseif ($q_position) {
  968. $p_position = $q_position;
  969. } elseif ($c_position) {
  970. $p_position = $c_position;
  971. } else {
  972. break;
  973. }
  974. if (is_null($placeholder_type)) {
  975. $placeholder_type_guess = $query[$p_position];
  976. }
  977. $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
  978. if (PEAR::isError($new_pos)) {
  979. return $new_pos;
  980. }
  981. if ($new_pos != $position) {
  982. $position = $new_pos;
  983. continue; //evaluate again starting from the new position
  984. }
  985. //make sure this is not part of an user defined variable
  986. $new_pos = $this->_skipUserDefinedVariable($query, $position);
  987. if ($new_pos != $position) {
  988. $position = $new_pos;
  989. continue; //evaluate again starting from the new position
  990. }
  991. if ($query[$position] == $placeholder_type_guess) {
  992. if (is_null($placeholder_type)) {
  993. $placeholder_type = $query[$p_position];
  994. $question = $colon = $placeholder_type;
  995. }
  996. if ($placeholder_type == ':') {
  997. $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
  998. $parameter = preg_replace($regexp, '\\1', $query);
  999. if ($parameter === '') {
  1000. $err =& $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
  1001. 'named parameter name must match "bindname_format" option', __FUNCTION__);
  1002. return $err;
  1003. }
  1004. $positions[$p_position] = $parameter;
  1005. $query = substr_replace($query, '?', $position, strlen($parameter)+1);
  1006. } else {
  1007. $positions[$p_position] = count($positions);
  1008. }
  1009. $position = $p_position + 1;
  1010. } else {
  1011. $position = $p_position;
  1012. }
  1013. }
  1014. $connection = $this->getConnection();
  1015. if (PEAR::isError($connection)) {
  1016. return $connection;
  1017. }
  1018. if (!$is_manip) {
  1019. static $prep_statement_counter = 1;
  1020. $statement_name = sprintf($this->options['statement_format'], $this->phptype, $prep_statement_counter++ . sha1(microtime() + mt_rand()));
  1021. $statement_name = substr(strtolower($statement_name), 0, $this->options['max_identifiers_length']);
  1022. $query = "PREPARE $statement_name FROM ".$this->quote($query, 'text');
  1023. $statement =& $this->_doQuery($query, true, $connection);
  1024. if (PEAR::isError($statement)) {
  1025. return $statement;
  1026. }
  1027. $statement = $statement_name;
  1028. } else {
  1029. $statement = @mysqli_prepare($connection, $query);
  1030. if (!$statement) {
  1031. $err =& $this->raiseError(null, null, null,
  1032. 'Unable to create prepared statement handle', __FUNCTION__);
  1033. return $err;
  1034. }
  1035. }
  1036. $class_name = 'MDB2_Statement_'.$this->phptype;
  1037. $obj = new $class_name($this, $statement, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
  1038. $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
  1039. return $obj;
  1040. }
  1041. // }}}
  1042. // {{{ replace()
  1043. /**
  1044. * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
  1045. * query, except that if there is already a row in the table with the same
  1046. * key field values, the REPLACE query just updates its values instead of
  1047. * inserting a new row.
  1048. *
  1049. * The REPLACE type of query does not make part of the SQL standards. Since
  1050. * practically only MySQL implements it natively, this type of query is
  1051. * emulated through this method for other DBMS using standard types of
  1052. * queries inside a transaction to assure the atomicity of the operation.
  1053. *
  1054. * @access public
  1055. *
  1056. * @param string $table name of the table on which the REPLACE query will
  1057. * be executed.
  1058. * @param array $fields associative array that describes the fields and the
  1059. * values that will be inserted or updated in the specified table. The
  1060. * indexes of the array are the names of all the fields of the table. The
  1061. * values of the array are also associative arrays that describe the
  1062. * values and other properties of the table fields.
  1063. *
  1064. * Here follows a list of field properties that need to be specified:
  1065. *
  1066. * value:
  1067. * Value to be assigned to the specified field. This value may be
  1068. * of specified in database independent type format as this
  1069. * function can perform the necessary datatype conversions.
  1070. *
  1071. * Default:
  1072. * this property is required unless the Null property
  1073. * is set to 1.
  1074. *
  1075. * type
  1076. * Name of the type of the field. Currently, all types Metabase
  1077. * are supported except for clob and blob.
  1078. *
  1079. * Default: no type conversion
  1080. *
  1081. * null
  1082. * Boolean property that indicates that the value for this field
  1083. * should be set to null.
  1084. *
  1085. * The default value for fields missing in INSERT queries may be
  1086. * specified the definition of a table. Often, the default value
  1087. * is already null, but since the REPLACE may be emulated using
  1088. * an UPDATE query, make sure that all fields of the table are
  1089. * listed in this function argument array.
  1090. *
  1091. * Default: 0
  1092. *
  1093. * key
  1094. * Boolean property that indicates that this field should be
  1095. * handled as a primary key or at least as part of the compound
  1096. * unique index of the table that will determine the row that will
  1097. * updated if it exists or inserted a new row otherwise.
  1098. *
  1099. * This function will fail if no key field is specified or if the
  1100. * value of a key field is set to null because fields that are
  1101. * part of unique index they may not be null.
  1102. *
  1103. * Default: 0
  1104. *
  1105. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1106. */
  1107. function replace($table, $fields)
  1108. {
  1109. $count = count($fields);
  1110. $query = $values = '';
  1111. $keys = $colnum = 0;
  1112. for (reset($fields); $colnum < $count; next($fields), $colnum++) {
  1113. $name = key($fields);
  1114. if ($colnum > 0) {
  1115. $query .= ',';
  1116. $values.= ',';
  1117. }
  1118. $query.= $this->quoteIdentifier($name, true);
  1119. if (isset($fields[$name]['null']) && $fields[$name]['null']) {
  1120. $value = 'NULL';
  1121. } else {
  1122. $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
  1123. $value = $this->quote($fields[$name]['value'], $type);
  1124. if (PEAR::isError($value)) {
  1125. return $value;
  1126. }
  1127. }
  1128. $values.= $value;
  1129. if (isset($fields[$name]['key']) && $fields[$name]['key']) {
  1130. if ($value === 'NULL') {
  1131. return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
  1132. 'key value '.$name.' may not be NULL', __FUNCTION__);
  1133. }
  1134. $keys++;
  1135. }
  1136. }
  1137. if ($keys == 0) {
  1138. return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
  1139. 'not specified which fields are keys', __FUNCTION__);
  1140. }
  1141. $connection = $this->getConnection();
  1142. if (PEAR::isError($connection)) {
  1143. return $connection;
  1144. }
  1145. $table = $this->quoteIdentifier($table, true);
  1146. $query = "REPLACE INTO $table ($query) VALUES ($values)";
  1147. $result =& $this->_doQuery($query, true, $connection);
  1148. if (PEAR::isError($result)) {
  1149. return $result;
  1150. }
  1151. return $this->_affectedRows($connection, $result);
  1152. }
  1153. // }}}
  1154. // {{{ nextID()
  1155. /**
  1156. * Returns the next free id of a sequence
  1157. *
  1158. * @param string $seq_name name of the sequence
  1159. * @param boolean $ondemand when true the sequence is
  1160. * automatic created, if it
  1161. * not exists
  1162. *
  1163. * @return mixed MDB2 Error Object or id
  1164. * @access public
  1165. */
  1166. function nextID($seq_name, $ondemand = true)
  1167. {
  1168. $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
  1169. $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
  1170. $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
  1171. $this->pushErrorHandling(PEAR_ERROR_RETURN);
  1172. $this->expectError(MDB2_ERROR_NOSUCHTABLE);
  1173. $result =& $this->_doQuery($query, true);
  1174. $this->popExpect();
  1175. $this->popErrorHandling();
  1176. if (PEAR::isError($result)) {
  1177. if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
  1178. $this->loadModule('Manager', null, true);
  1179. $result = $this->manager->createSequence($seq_name);
  1180. if (PEAR::isError($result)) {
  1181. return $this->raiseError($result, null, null,
  1182. 'on demand sequence '.$seq_name.' could not be created', __FUNCTION__);
  1183. } else {
  1184. return $this->nextID($seq_name, false);
  1185. }
  1186. }
  1187. return $result;
  1188. }
  1189. $value = $this->lastInsertID();
  1190. if (is_numeric($value)) {
  1191. $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
  1192. $result =& $this->_doQuery($query, true);
  1193. if (PEAR::isError($result)) {
  1194. $this->warnings[] = 'nextID: could not delete previous sequence table values from '.$seq_name;
  1195. }
  1196. }
  1197. return $value;
  1198. }
  1199. // }}}
  1200. // {{{ lastInsertID()
  1201. /**
  1202. * Returns the autoincrement ID if supported or $id or fetches the current
  1203. * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
  1204. *
  1205. * @param string $table name of the table into which a new row was inserted
  1206. * @param string $field name of the field into which a new row was inserted
  1207. * @return mixed MDB2 Error Object or id
  1208. * @access public
  1209. */
  1210. function lastInsertID($table = null, $field = null)
  1211. {
  1212. // not using mysql_insert_id() due to http://pear.php.net/bugs/bug.php?id=8051
  1213. return $this->queryOne('SELECT LAST_INSERT_ID()', 'integer');
  1214. }
  1215. // }}}
  1216. // {{{ currID()
  1217. /**
  1218. * Returns the current id of a sequence
  1219. *
  1220. * @param string $seq_name name of the sequence
  1221. * @return mixed MDB2 Error Object or id
  1222. * @access public
  1223. */
  1224. function currID($seq_name)
  1225. {
  1226. $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
  1227. $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
  1228. $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
  1229. return $this->queryOne($query, 'integer');
  1230. }
  1231. }
  1232. /**
  1233. * MDB2 MySQLi result driver
  1234. *
  1235. * @package MDB2
  1236. * @category Database
  1237. * @author Lukas Smith <smith@pooteeweet.org>
  1238. */
  1239. class MDB2_Result_mysqli extends MDB2_Result_Common
  1240. {
  1241. // }}}
  1242. // {{{ fetchRow()
  1243. /**
  1244. * Fetch a row and insert the data into an existing array.
  1245. *
  1246. * @param int $fetchmode how the array data should be indexed
  1247. * @param int $rownum number of the row where the data can be found
  1248. * @return int data array on success, a MDB2 error on failure
  1249. * @access public
  1250. */
  1251. function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
  1252. {
  1253. if (!is_null($rownum)) {
  1254. $seek = $this->seek($rownum);
  1255. if (PEAR::isError($seek)) {
  1256. return $seek;
  1257. }
  1258. }
  1259. if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
  1260. $fetchmode = $this->db->fetchmode;
  1261. }
  1262. if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
  1263. $row = @mysqli_fetch_assoc($this->result);
  1264. if (is_array($row)
  1265. && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
  1266. ) {
  1267. $row = array_change_key_case($row, $this->db->options['field_case']);
  1268. }
  1269. } else {
  1270. $row = @mysqli_fetch_row($this->result);
  1271. }
  1272. if (!$row) {
  1273. if ($this->result === false) {
  1274. $err =& $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1275. 'resultset has already been freed', __FUNCTION__);
  1276. return $err;
  1277. }
  1278. $null = null;
  1279. return $null;
  1280. }
  1281. $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
  1282. $rtrim = false;
  1283. if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
  1284. if (empty($this->types)) {
  1285. $mode += MDB2_PORTABILITY_RTRIM;
  1286. } else {
  1287. $rtrim = true;
  1288. }
  1289. }
  1290. if ($mode) {
  1291. $this->db->_fixResultArrayValues($row, $mode);
  1292. }
  1293. if (!empty($this->types)) {
  1294. $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
  1295. }
  1296. if (!empty($this->values)) {
  1297. $this->_assignBindColumns($row);
  1298. }
  1299. if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
  1300. $object_class = $this->db->options['fetch_class'];
  1301. if ($object_class == 'stdClass') {
  1302. $row = (object) $row;
  1303. } else {
  1304. $row = &new $object_class($row);
  1305. }
  1306. }
  1307. ++$this->rownum;
  1308. return $row;
  1309. }
  1310. // }}}
  1311. // {{{ _getColumnNames()
  1312. /**
  1313. * Retrieve the names of columns returned by the DBMS in a query result.
  1314. *
  1315. * @return mixed Array variable that holds the names of columns as keys
  1316. * or an MDB2 error on failure.
  1317. * Some DBMS may not return any columns when the result set
  1318. * does not contain any rows.
  1319. * @access private
  1320. */
  1321. function _getColumnNames()
  1322. {
  1323. $columns = array();
  1324. $numcols = $this->numCols();
  1325. if (PEAR::isError($numcols)) {
  1326. return $numcols;
  1327. }
  1328. for ($column = 0; $column < $numcols; $column++) {
  1329. $column_info = @mysqli_fetch_field_direct($this->result, $column);
  1330. $columns[$column_info->name] = $column;
  1331. }
  1332. if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  1333. $columns = array_change_key_case($columns, $this->db->options['field_case']);
  1334. }
  1335. return $columns;
  1336. }
  1337. // }}}
  1338. // {{{ numCols()
  1339. /**
  1340. * Count the number of columns returned by the DBMS in a query result.
  1341. *
  1342. * @return mixed integer value with the number of columns, a MDB2 error
  1343. * on failure
  1344. * @access public
  1345. */
  1346. function numCols()
  1347. {
  1348. $cols = @mysqli_num_fields($this->result);
  1349. if (is_null($cols)) {
  1350. if ($this->result === false) {
  1351. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1352. 'resultset has already been freed', __FUNCTION__);
  1353. } elseif (is_null($this->result)) {
  1354. return count($this->types);
  1355. }
  1356. return $this->db->raiseError(null, null, null,
  1357. 'Could not get column count', __FUNCTION__);
  1358. }
  1359. return $cols;
  1360. }
  1361. // }}}
  1362. // {{{ nextResult()
  1363. /**
  1364. * Move the internal result pointer to the next available result
  1365. *
  1366. * @return true on success, false if there is no more result set or an error object on failure
  1367. * @access public
  1368. */
  1369. function nextResult()
  1370. {
  1371. $connection = $this->db->getConnection();
  1372. if (PEAR::isError($connection)) {
  1373. return $connection;
  1374. }
  1375. if (!@mysqli_more_results($connection)) {
  1376. return false;
  1377. }
  1378. if (!@mysqli_next_result($connection)) {
  1379. return false;
  1380. }
  1381. if (!($this->result = @mysqli_use_result($connection))) {
  1382. return false;
  1383. }
  1384. return MDB2_OK;
  1385. }
  1386. // }}}
  1387. // {{{ free()
  1388. /**
  1389. * Free the internal resources associated with result.
  1390. *
  1391. * @return boolean true on success, false if result is invalid
  1392. * @access public
  1393. */
  1394. function free()
  1395. {
  1396. if (is_object($this->result) && $this->db->connection) {
  1397. $free = @mysqli_free_result($this->result);
  1398. if ($free === false) {
  1399. return $this->db->raiseError(null, null, null,
  1400. 'Could not free result', __FUNCTION__);
  1401. }
  1402. }
  1403. $this->result = false;
  1404. return MDB2_OK;
  1405. }
  1406. }
  1407. /**
  1408. * MDB2 MySQLi buffered result driver
  1409. *
  1410. * @package MDB2
  1411. * @category Database
  1412. * @author Lukas Smith <smith@pooteeweet.org>
  1413. */
  1414. class MDB2_BufferedResult_mysqli extends MDB2_Result_mysqli
  1415. {
  1416. // }}}
  1417. // {{{ seek()
  1418. /**
  1419. * Seek to a specific row in a result set
  1420. *
  1421. * @param int $rownum number of the row where the data can be found
  1422. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1423. * @access public
  1424. */
  1425. function seek($rownum = 0)
  1426. {
  1427. if ($this->rownum != ($rownum - 1) && !@mysqli_data_seek($this->result, $rownum)) {
  1428. if ($this->result === false) {
  1429. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1430. 'resultset has already been freed', __FUNCTION__);
  1431. } elseif (is_null($this->result)) {
  1432. return MDB2_OK;
  1433. }
  1434. return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
  1435. 'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
  1436. }
  1437. $this->rownum = $rownum - 1;
  1438. return MDB2_OK;
  1439. }
  1440. // }}}
  1441. // {{{ valid()
  1442. /**
  1443. * Check if the end of the result set has been reached
  1444. *
  1445. * @return mixed true or false on sucess, a MDB2 error on failure
  1446. * @access public
  1447. */
  1448. function valid()
  1449. {
  1450. $numrows = $this->numRows();
  1451. if (PEAR::isError($numrows)) {
  1452. return $numrows;
  1453. }
  1454. return $this->rownum < ($numrows - 1);
  1455. }
  1456. // }}}
  1457. // {{{ numRows()
  1458. /**
  1459. * Returns the number of rows in a result object
  1460. *
  1461. * @return mixed MDB2 Error Object or the number of rows
  1462. * @access public
  1463. */
  1464. function numRows()
  1465. {
  1466. $rows = @mysqli_num_rows($this->result);
  1467. if (is_null($rows)) {
  1468. if ($this->result === false) {
  1469. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1470. 'resultset has already been freed', __FUNCTION__);
  1471. } elseif (is_null($this->result)) {
  1472. return 0;
  1473. }
  1474. return $this->db->raiseError(null, null, null,
  1475. 'Could not get row count', __FUNCTION__);
  1476. }
  1477. return $rows;
  1478. }
  1479. // }}}
  1480. // {{{ nextResult()
  1481. /**
  1482. * Move the internal result pointer to the next available result
  1483. *
  1484. * @param a valid result resource
  1485. * @return true on success, false if there is no more result set or an error object on failure
  1486. * @access public
  1487. */
  1488. function nextResult()
  1489. {
  1490. $connection = $this->db->getConnection();
  1491. if (PEAR::isError($connection)) {
  1492. return $connection;
  1493. }
  1494. if (!@mysqli_more_results($connection)) {
  1495. return false;
  1496. }
  1497. if (!@mysqli_next_result($connection)) {
  1498. return false;
  1499. }
  1500. if (!($this->result = @mysqli_store_result($connection))) {
  1501. return false;
  1502. }
  1503. return MDB2_OK;
  1504. }
  1505. }
  1506. /**
  1507. * MDB2 MySQLi statement driver
  1508. *
  1509. * @package MDB2
  1510. * @category Database
  1511. * @author Lukas Smith <smith@pooteeweet.org>
  1512. */
  1513. class MDB2_Statement_mysqli extends MDB2_Statement_Common
  1514. {
  1515. // {{{ _execute()
  1516. /**
  1517. * Execute a prepared query statement helper method.
  1518. *
  1519. * @param mixed $result_class string which specifies which result class to use
  1520. * @param mixed $result_wrap_class string which specifies which class to wrap results in
  1521. * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
  1522. * @access private
  1523. */
  1524. function &_execute($result_class = true, $result_wrap_class = false)
  1525. {
  1526. if (is_null($this->statement)) {
  1527. $result =& parent::_execute($result_class, $result_wrap_class);
  1528. return $result;
  1529. }
  1530. $this->db->last_query = $this->query;
  1531. $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values));
  1532. if ($this->db->getOption('disable_query')) {
  1533. $result = $this->is_manip ? 0 : null;
  1534. return $result;
  1535. }
  1536. $connection = $this->db->getConnection();
  1537. if (PEAR::isError($connection)) {
  1538. return $connection;
  1539. }
  1540. if (!is_object($this->statement)) {
  1541. $query = 'EXECUTE '.$this->statement;
  1542. }
  1543. if (!empty($this->positions)) {
  1544. $parameters = array(0 => $this->statement, 1 => '');
  1545. $lobs = array();
  1546. $i = 0;
  1547. foreach ($this->positions as $parameter) {
  1548. if (!array_key_exists($parameter, $this->values)) {
  1549. return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  1550. 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
  1551. }
  1552. $value = $this->values[$parameter];
  1553. $type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null;
  1554. if (!is_object($this->statement)) {
  1555. if (is_resource($value) || $type == 'clob' || $type == 'blob' && $this->db->options['lob_allow_url_include']) {
  1556. if (!is_resource($value) && preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {
  1557. if ($match[1] == 'file://') {
  1558. $value = $match[2];
  1559. }
  1560. $value = @fopen($value, 'r');
  1561. $close = true;
  1562. }
  1563. if (is_resource($value)) {
  1564. $data = '';
  1565. while (!@feof($value)) {
  1566. $data.= @fread($value, $this->db->options['lob_buffer_length']);
  1567. }
  1568. if ($close) {
  1569. @fclose($value);
  1570. }
  1571. $value = $data;
  1572. }
  1573. }
  1574. $quoted = $this->db->quote($value, $type);
  1575. if (PEAR::isError($quoted)) {
  1576. return $quoted;
  1577. }
  1578. $param_query = 'SET @'.$parameter.' = '.$quoted;
  1579. $result = $this->db->_doQuery($param_query, true, $connection);
  1580. if (PEAR::isError($result)) {
  1581. return $result;
  1582. }
  1583. } else {
  1584. if (is_resource($value) || $type == 'clob' || $type == 'blob') {
  1585. $parameters[] = null;
  1586. $parameters[1].= 'b';
  1587. $lobs[$i] = $parameter;
  1588. } else {
  1589. $quoted = $this->db->quote($value, $type, false);
  1590. if (PEAR::isError($quoted)) {
  1591. return $quoted;
  1592. }
  1593. $parameters[] = $quoted;
  1594. $parameters[1].= $this->db->datatype->mapPrepareDatatype($type);
  1595. }
  1596. ++$i;
  1597. }
  1598. }
  1599. if (!is_object($this->statement)) {
  1600. $query.= ' USING @'.implode(', @', array_values($this->positions));
  1601. } else {
  1602. $result = @call_user_func_array('mysqli_stmt_bind_param', $parameters);
  1603. if ($result === false) {
  1604. $err =& $this->db->raiseError(null, null, null,
  1605. 'Unable to bind parameters', __FUNCTION__);
  1606. return $err;
  1607. }
  1608. foreach ($lobs as $i => $parameter) {
  1609. $value = $this->values[$parameter];
  1610. $close = false;
  1611. if (!is_resource($value)) {
  1612. $close = true;
  1613. if (preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {
  1614. if ($match[1] == 'file://') {
  1615. $value = $match[2];
  1616. }
  1617. $value = @fopen($value, 'r');
  1618. } else {
  1619. $fp = @tmpfile();
  1620. @fwrite($fp, $value);
  1621. @rewind($fp);
  1622. $value = $fp;
  1623. }
  1624. }
  1625. while (!@feof($value)) {
  1626. $data = @fread($value, $this->db->options['lob_buffer_length']);
  1627. @mysqli_stmt_send_long_data($this->statement, $i, $data);
  1628. }
  1629. if ($close) {
  1630. @fclose($value);
  1631. }
  1632. }
  1633. }
  1634. }
  1635. if (!is_object($this->statement)) {
  1636. $result = $this->db->_doQuery($query, $this->is_manip, $connection);
  1637. if (PEAR::isError($result)) {
  1638. return $result;
  1639. }
  1640. if ($this->is_manip) {
  1641. $affected_rows = $this->db->_affectedRows($connection, $result);
  1642. return $affected_rows;
  1643. }
  1644. $result =& $this->db->_wrapResult($result, $this->result_types,
  1645. $result_class, $result_wrap_class, $this->limit, $this->offset);
  1646. } else {
  1647. if (!@mysqli_stmt_execute($this->statement)) {
  1648. $err =& $this->db->raiseError(null, null, null,
  1649. 'Unable to execute statement', __FUNCTION__);
  1650. return $err;
  1651. }
  1652. if ($this->is_manip) {
  1653. $affected_rows = @mysqli_stmt_affected_rows($this->statement);
  1654. return $affected_rows;
  1655. }
  1656. if ($this->db->options['result_buffering']) {
  1657. @mysqli_stmt_store_result($this->statement);
  1658. }
  1659. $result =& $this->db->_wrapResult($this->statement, $this->result_types,
  1660. $result_class, $result_wrap_class, $this->limit, $this->offset);
  1661. }
  1662. $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result));
  1663. return $result;
  1664. }
  1665. // }}}
  1666. // {{{ free()
  1667. /**
  1668. * Release resources allocated for the specified prepared query.
  1669. *
  1670. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1671. * @access public
  1672. */
  1673. function free()
  1674. {
  1675. if (is_null($this->positions)) {
  1676. return $this->db->raiseError(MDB2_ERROR, null, null,
  1677. 'Prepared statement has already been freed', __FUNCTION__);
  1678. }
  1679. $result = MDB2_OK;
  1680. if (is_object($this->statement)) {
  1681. if (!@mysqli_stmt_close($this->statement)) {
  1682. $result = $this->db->raiseError(null, null, null,
  1683. 'Could not free statement', __FUNCTION__);
  1684. }
  1685. } elseif (!is_null($this->statement)) {
  1686. $connection = $this->db->getConnection();
  1687. if (PEAR::isError($connection)) {
  1688. return $connection;
  1689. }
  1690. $query = 'DEALLOCATE PREPARE '.$this->statement;
  1691. $result = $this->db->_doQuery($query, true, $connection);
  1692. }
  1693. parent::free();
  1694. return $result;
  1695. }
  1696. }
  1697. ?>