PageRenderTime 58ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/includes/pear/MDB2/Driver/mysql.php

https://bitbucket.org/Yason/armory
PHP | 1710 lines | 1062 code | 130 blank | 518 comment | 222 complexity | 7cc50bd9473ba2cba37f68639462f021 MD5 | raw file
Possible License(s): GPL-3.0

Large files files are truncated, but you can click here to view the full 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-2008 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 302867 2010-08-29 11:22:07Z quipo $
  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 $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 = 'mysql';
  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['max_identifiers_length'] = 64;
  102. $this->_reCheckSupportedOptions();
  103. }
  104. // }}}
  105. // {{{ _reCheckSupportedOptions()
  106. /**
  107. * If the user changes certain options, other capabilities may depend
  108. * on the new settings, so we need to check them (again).
  109. *
  110. * @access private
  111. */
  112. function _reCheckSupportedOptions()
  113. {
  114. $this->supported['transactions'] = $this->options['use_transactions'];
  115. $this->supported['savepoints'] = $this->options['use_transactions'];
  116. if ($this->options['default_table_type']) {
  117. switch (strtoupper($this->options['default_table_type'])) {
  118. case 'BLACKHOLE':
  119. case 'MEMORY':
  120. case 'ARCHIVE':
  121. case 'CSV':
  122. case 'HEAP':
  123. case 'ISAM':
  124. case 'MERGE':
  125. case 'MRG_ISAM':
  126. case 'ISAM':
  127. case 'MRG_MYISAM':
  128. case 'MYISAM':
  129. $this->supported['savepoints'] = false;
  130. $this->supported['transactions'] = false;
  131. $this->warnings[] = $this->options['default_table_type'] .
  132. ' is not a supported default table type';
  133. break;
  134. }
  135. }
  136. }
  137. // }}}
  138. // {{{ function setOption($option, $value)
  139. /**
  140. * set the option for the db class
  141. *
  142. * @param string option name
  143. * @param mixed value for the option
  144. *
  145. * @return mixed MDB2_OK or MDB2 Error Object
  146. *
  147. * @access public
  148. */
  149. function setOption($option, $value)
  150. {
  151. $res = parent::setOption($option, $value);
  152. $this->_reCheckSupportedOptions();
  153. }
  154. // }}}
  155. // {{{ errorInfo()
  156. /**
  157. * This method is used to collect information about an error
  158. *
  159. * @param integer $error
  160. * @return array
  161. * @access public
  162. */
  163. function errorInfo($error = null)
  164. {
  165. if ($this->connection) {
  166. $native_code = @mysql_errno($this->connection);
  167. $native_msg = @mysql_error($this->connection);
  168. } else {
  169. $native_code = @mysql_errno();
  170. $native_msg = @mysql_error();
  171. }
  172. if (is_null($error)) {
  173. static $ecode_map;
  174. if (empty($ecode_map)) {
  175. $ecode_map = array(
  176. 1000 => MDB2_ERROR_INVALID, //hashchk
  177. 1001 => MDB2_ERROR_INVALID, //isamchk
  178. 1004 => MDB2_ERROR_CANNOT_CREATE,
  179. 1005 => MDB2_ERROR_CANNOT_CREATE,
  180. 1006 => MDB2_ERROR_CANNOT_CREATE,
  181. 1007 => MDB2_ERROR_ALREADY_EXISTS,
  182. 1008 => MDB2_ERROR_CANNOT_DROP,
  183. 1009 => MDB2_ERROR_CANNOT_DROP,
  184. 1010 => MDB2_ERROR_CANNOT_DROP,
  185. 1011 => MDB2_ERROR_CANNOT_DELETE,
  186. 1022 => MDB2_ERROR_ALREADY_EXISTS,
  187. 1029 => MDB2_ERROR_NOT_FOUND,
  188. 1032 => MDB2_ERROR_NOT_FOUND,
  189. 1044 => MDB2_ERROR_ACCESS_VIOLATION,
  190. 1045 => MDB2_ERROR_ACCESS_VIOLATION,
  191. 1046 => MDB2_ERROR_NODBSELECTED,
  192. 1048 => MDB2_ERROR_CONSTRAINT,
  193. 1049 => MDB2_ERROR_NOSUCHDB,
  194. 1050 => MDB2_ERROR_ALREADY_EXISTS,
  195. 1051 => MDB2_ERROR_NOSUCHTABLE,
  196. 1054 => MDB2_ERROR_NOSUCHFIELD,
  197. 1060 => MDB2_ERROR_ALREADY_EXISTS,
  198. 1061 => MDB2_ERROR_ALREADY_EXISTS,
  199. 1062 => MDB2_ERROR_ALREADY_EXISTS,
  200. 1064 => MDB2_ERROR_SYNTAX,
  201. 1067 => MDB2_ERROR_INVALID,
  202. 1072 => MDB2_ERROR_NOT_FOUND,
  203. 1086 => MDB2_ERROR_ALREADY_EXISTS,
  204. 1091 => MDB2_ERROR_NOT_FOUND,
  205. 1100 => MDB2_ERROR_NOT_LOCKED,
  206. 1109 => MDB2_ERROR_NOT_FOUND,
  207. 1125 => MDB2_ERROR_ALREADY_EXISTS,
  208. 1136 => MDB2_ERROR_VALUE_COUNT_ON_ROW,
  209. 1138 => MDB2_ERROR_INVALID,
  210. 1142 => MDB2_ERROR_ACCESS_VIOLATION,
  211. 1143 => MDB2_ERROR_ACCESS_VIOLATION,
  212. 1146 => MDB2_ERROR_NOSUCHTABLE,
  213. 1149 => MDB2_ERROR_SYNTAX,
  214. 1169 => MDB2_ERROR_CONSTRAINT,
  215. 1176 => MDB2_ERROR_NOT_FOUND,
  216. 1177 => MDB2_ERROR_NOSUCHTABLE,
  217. 1213 => MDB2_ERROR_DEADLOCK,
  218. 1216 => MDB2_ERROR_CONSTRAINT,
  219. 1217 => MDB2_ERROR_CONSTRAINT,
  220. 1227 => MDB2_ERROR_ACCESS_VIOLATION,
  221. 1235 => MDB2_ERROR_CANNOT_CREATE,
  222. 1299 => MDB2_ERROR_INVALID_DATE,
  223. 1300 => MDB2_ERROR_INVALID,
  224. 1304 => MDB2_ERROR_ALREADY_EXISTS,
  225. 1305 => MDB2_ERROR_NOT_FOUND,
  226. 1306 => MDB2_ERROR_CANNOT_DROP,
  227. 1307 => MDB2_ERROR_CANNOT_CREATE,
  228. 1334 => MDB2_ERROR_CANNOT_ALTER,
  229. 1339 => MDB2_ERROR_NOT_FOUND,
  230. 1356 => MDB2_ERROR_INVALID,
  231. 1359 => MDB2_ERROR_ALREADY_EXISTS,
  232. 1360 => MDB2_ERROR_NOT_FOUND,
  233. 1363 => MDB2_ERROR_NOT_FOUND,
  234. 1365 => MDB2_ERROR_DIVZERO,
  235. 1451 => MDB2_ERROR_CONSTRAINT,
  236. 1452 => MDB2_ERROR_CONSTRAINT,
  237. 1542 => MDB2_ERROR_CANNOT_DROP,
  238. 1546 => MDB2_ERROR_CONSTRAINT,
  239. 1582 => MDB2_ERROR_CONSTRAINT,
  240. 2003 => MDB2_ERROR_CONNECT_FAILED,
  241. 2019 => MDB2_ERROR_INVALID,
  242. );
  243. }
  244. if ($this->options['portability'] & MDB2_PORTABILITY_ERRORS) {
  245. $ecode_map[1022] = MDB2_ERROR_CONSTRAINT;
  246. $ecode_map[1048] = MDB2_ERROR_CONSTRAINT_NOT_NULL;
  247. $ecode_map[1062] = MDB2_ERROR_CONSTRAINT;
  248. } else {
  249. // Doing this in case mode changes during runtime.
  250. $ecode_map[1022] = MDB2_ERROR_ALREADY_EXISTS;
  251. $ecode_map[1048] = MDB2_ERROR_CONSTRAINT;
  252. $ecode_map[1062] = MDB2_ERROR_ALREADY_EXISTS;
  253. }
  254. if (isset($ecode_map[$native_code])) {
  255. $error = $ecode_map[$native_code];
  256. }
  257. }
  258. return array($error, $native_code, $native_msg);
  259. }
  260. // }}}
  261. // {{{ escape()
  262. /**
  263. * Quotes a string so it can be safely used in a query. It will quote
  264. * the text so it can safely be used within a query.
  265. *
  266. * @param string the input string to quote
  267. * @param bool escape wildcards
  268. *
  269. * @return string quoted string
  270. *
  271. * @access public
  272. */
  273. function escape($text, $escape_wildcards = false)
  274. {
  275. if ($escape_wildcards) {
  276. $text = $this->escapePattern($text);
  277. }
  278. $connection = $this->getConnection();
  279. if (PEAR::isError($connection)) {
  280. return $connection;
  281. }
  282. $text = @mysql_real_escape_string($text, $connection);
  283. return $text;
  284. }
  285. // }}}
  286. // {{{ beginTransaction()
  287. /**
  288. * Start a transaction or set a savepoint.
  289. *
  290. * @param string name of a savepoint to set
  291. * @return mixed MDB2_OK on success, a MDB2 error on failure
  292. *
  293. * @access public
  294. */
  295. function beginTransaction($savepoint = null)
  296. {
  297. $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  298. $this->_getServerCapabilities();
  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. if (!$this->in_transaction) {
  305. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  306. 'savepoint cannot be released when changes are auto committed', __FUNCTION__);
  307. }
  308. $query = 'SAVEPOINT '.$savepoint;
  309. return $this->_doQuery($query, true);
  310. } elseif ($this->in_transaction) {
  311. return MDB2_OK; //nothing to do
  312. }
  313. if (!$this->destructor_registered && $this->opened_persistent) {
  314. $this->destructor_registered = true;
  315. register_shutdown_function('MDB2_closeOpenTransactions');
  316. }
  317. $query = $this->start_transaction ? 'START TRANSACTION' : 'SET AUTOCOMMIT = 0';
  318. $result = $this->_doQuery($query, true);
  319. if (PEAR::isError($result)) {
  320. return $result;
  321. }
  322. $this->in_transaction = true;
  323. return MDB2_OK;
  324. }
  325. // }}}
  326. // {{{ commit()
  327. /**
  328. * Commit the database changes done during a transaction that is in
  329. * progress or release a savepoint. This function may only be called when
  330. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  331. * transaction is implicitly started after committing the pending changes.
  332. *
  333. * @param string name of a savepoint to release
  334. * @return mixed MDB2_OK on success, a MDB2 error on failure
  335. *
  336. * @access public
  337. */
  338. function commit($savepoint = null)
  339. {
  340. $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  341. if (!$this->in_transaction) {
  342. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  343. 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
  344. }
  345. if (!is_null($savepoint)) {
  346. if (!$this->supports('savepoints')) {
  347. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  348. 'savepoints are not supported', __FUNCTION__);
  349. }
  350. $server_info = $this->getServerVersion();
  351. if (version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '5.0.3', '<')) {
  352. return MDB2_OK;
  353. }
  354. $query = 'RELEASE SAVEPOINT '.$savepoint;
  355. return $this->_doQuery($query, true);
  356. }
  357. if (!$this->supports('transactions')) {
  358. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  359. 'transactions are not supported', __FUNCTION__);
  360. }
  361. $result = $this->_doQuery('COMMIT', true);
  362. if (PEAR::isError($result)) {
  363. return $result;
  364. }
  365. if (!$this->start_transaction) {
  366. $query = 'SET AUTOCOMMIT = 1';
  367. $result = $this->_doQuery($query, true);
  368. if (PEAR::isError($result)) {
  369. return $result;
  370. }
  371. }
  372. $this->in_transaction = false;
  373. return MDB2_OK;
  374. }
  375. // }}}
  376. // {{{ rollback()
  377. /**
  378. * Cancel any database changes done during a transaction or since a specific
  379. * savepoint that is in progress. This function may only be called when
  380. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  381. * transaction is implicitly started after canceling the pending changes.
  382. *
  383. * @param string name of a savepoint to rollback to
  384. * @return mixed MDB2_OK on success, a MDB2 error on failure
  385. *
  386. * @access public
  387. */
  388. function rollback($savepoint = null)
  389. {
  390. $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  391. if (!$this->in_transaction) {
  392. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  393. 'rollback cannot be done changes are auto committed', __FUNCTION__);
  394. }
  395. if (!is_null($savepoint)) {
  396. if (!$this->supports('savepoints')) {
  397. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  398. 'savepoints are not supported', __FUNCTION__);
  399. }
  400. $query = 'ROLLBACK TO SAVEPOINT '.$savepoint;
  401. return $this->_doQuery($query, true);
  402. }
  403. $query = 'ROLLBACK';
  404. $result = $this->_doQuery($query, true);
  405. if (PEAR::isError($result)) {
  406. return $result;
  407. }
  408. if (!$this->start_transaction) {
  409. $query = 'SET AUTOCOMMIT = 1';
  410. $result = $this->_doQuery($query, true);
  411. if (PEAR::isError($result)) {
  412. return $result;
  413. }
  414. }
  415. $this->in_transaction = false;
  416. return MDB2_OK;
  417. }
  418. // }}}
  419. // {{{ function setTransactionIsolation()
  420. /**
  421. * Set the transacton isolation level.
  422. *
  423. * @param string standard isolation level
  424. * READ UNCOMMITTED (allows dirty reads)
  425. * READ COMMITTED (prevents dirty reads)
  426. * REPEATABLE READ (prevents nonrepeatable reads)
  427. * SERIALIZABLE (prevents phantom reads)
  428. * @param array some transaction options:
  429. * 'wait' => 'WAIT' | 'NO WAIT'
  430. * 'rw' => 'READ WRITE' | 'READ ONLY'
  431. *
  432. * @return mixed MDB2_OK on success, a MDB2 error on failure
  433. *
  434. * @access public
  435. * @since 2.1.1
  436. */
  437. function setTransactionIsolation($isolation, $options = array())
  438. {
  439. $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
  440. if (!$this->supports('transactions')) {
  441. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  442. 'transactions are not supported', __FUNCTION__);
  443. }
  444. switch ($isolation) {
  445. case 'READ UNCOMMITTED':
  446. case 'READ COMMITTED':
  447. case 'REPEATABLE READ':
  448. case 'SERIALIZABLE':
  449. break;
  450. default:
  451. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  452. 'isolation level is not supported: '.$isolation, __FUNCTION__);
  453. }
  454. $query = "SET SESSION TRANSACTION ISOLATION LEVEL $isolation";
  455. return $this->_doQuery($query, true);
  456. }
  457. // }}}
  458. // {{{ _doConnect()
  459. /**
  460. * do the grunt work of the connect
  461. *
  462. * @return connection on success or MDB2 Error Object on failure
  463. * @access protected
  464. */
  465. function _doConnect($username, $password, $persistent = false)
  466. {
  467. if (!PEAR::loadExtension($this->phptype)) {
  468. return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  469. 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
  470. }
  471. $params = array();
  472. $unix = ($this->dsn['protocol'] && $this->dsn['protocol'] == 'unix');
  473. if (empty($this->dsn['hostspec'])) {
  474. $this->dsn['hostspec'] = $unix ? '' : 'localhost';
  475. }
  476. if ($this->dsn['hostspec']) {
  477. $params[0] = $this->dsn['hostspec'] . ($this->dsn['port'] ? ':' . $this->dsn['port'] : '');
  478. } else {
  479. $params[0] = ':' . $this->dsn['socket'];
  480. }
  481. $params[] = $username ? $username : null;
  482. $params[] = $password ? $password : null;
  483. if (!$persistent) {
  484. if ($this->_isNewLinkSet()) {
  485. $params[] = true;
  486. } else {
  487. $params[] = false;
  488. }
  489. }
  490. if (version_compare(phpversion(), '4.3.0', '>=')) {
  491. $params[] = isset($this->dsn['client_flags'])
  492. ? $this->dsn['client_flags'] : null;
  493. }
  494. $connect_function = $persistent ? 'mysql_pconnect' : 'mysql_connect';
  495. $connection = @call_user_func_array($connect_function, $params);
  496. if (!$connection) {
  497. if (($err = @mysql_error()) != '') {
  498. return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
  499. $err, __FUNCTION__);
  500. } else {
  501. return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
  502. 'unable to establish a connection', __FUNCTION__);
  503. }
  504. }
  505. if (!empty($this->dsn['charset'])) {
  506. $result = $this->setCharset($this->dsn['charset'], $connection);
  507. if (PEAR::isError($result)) {
  508. $this->disconnect(false);
  509. return $result;
  510. }
  511. }
  512. return $connection;
  513. }
  514. // }}}
  515. // {{{ connect()
  516. /**
  517. * Connect to the database
  518. *
  519. * @return MDB2_OK on success, MDB2 Error Object on failure
  520. * @access public
  521. */
  522. function connect()
  523. {
  524. if (is_resource($this->connection)) {
  525. //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
  526. if (MDB2::areEquals($this->connected_dsn, $this->dsn)
  527. && $this->opened_persistent == $this->options['persistent']
  528. ) {
  529. return MDB2_OK;
  530. }
  531. $this->disconnect(false);
  532. }
  533. $connection = $this->_doConnect(
  534. $this->dsn['username'],
  535. $this->dsn['password'],
  536. $this->options['persistent']
  537. );
  538. if (PEAR::isError($connection)) {
  539. return $connection;
  540. }
  541. $this->connection = $connection;
  542. $this->connected_dsn = $this->dsn;
  543. $this->connected_database_name = '';
  544. $this->opened_persistent = $this->options['persistent'];
  545. $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
  546. if ($this->database_name) {
  547. if ($this->database_name != $this->connected_database_name) {
  548. if (!@mysql_select_db($this->database_name, $connection)) {
  549. $err = $this->raiseError(null, null, null,
  550. 'Could not select the database: '.$this->database_name, __FUNCTION__);
  551. return $err;
  552. }
  553. $this->connected_database_name = $this->database_name;
  554. }
  555. }
  556. $this->_getServerCapabilities();
  557. return MDB2_OK;
  558. }
  559. // }}}
  560. // {{{ setCharset()
  561. /**
  562. * Set the charset on the current connection
  563. *
  564. * @param string charset (or array(charset, collation))
  565. * @param resource connection handle
  566. *
  567. * @return true on success, MDB2 Error Object on failure
  568. */
  569. function setCharset($charset, $connection = null)
  570. {
  571. if (is_null($connection)) {
  572. $connection = $this->getConnection();
  573. if (PEAR::isError($connection)) {
  574. return $connection;
  575. }
  576. }
  577. $collation = null;
  578. if (is_array($charset) && 2 == count($charset)) {
  579. $collation = array_pop($charset);
  580. $charset = array_pop($charset);
  581. }
  582. $client_info = mysql_get_client_info();
  583. if (function_exists('mysql_set_charset') && version_compare($client_info, '5.0.6')) {
  584. if (!$result = mysql_set_charset($charset, $connection)) {
  585. $err = $this->raiseError(null, null, null,
  586. 'Could not set client character set', __FUNCTION__);
  587. return $err;
  588. }
  589. return $result;
  590. }
  591. $query = "SET NAMES '".mysql_real_escape_string($charset, $connection)."'";
  592. if (!is_null($collation)) {
  593. $query .= " COLLATE '".mysql_real_escape_string($collation, $connection)."'";
  594. }
  595. return $this->_doQuery($query, true, $connection);
  596. }
  597. // }}}
  598. // {{{ databaseExists()
  599. /**
  600. * check if given database name is exists?
  601. *
  602. * @param string $name name of the database that should be checked
  603. *
  604. * @return mixed true/false on success, a MDB2 error on failure
  605. * @access public
  606. */
  607. function databaseExists($name)
  608. {
  609. $connection = $this->_doConnect($this->dsn['username'],
  610. $this->dsn['password'],
  611. $this->options['persistent']);
  612. if (PEAR::isError($connection)) {
  613. return $connection;
  614. }
  615. $result = @mysql_select_db($name, $connection);
  616. @mysql_close($connection);
  617. return $result;
  618. }
  619. // }}}
  620. // {{{ disconnect()
  621. /**
  622. * Log out and disconnect from the database.
  623. *
  624. * @param boolean $force if the disconnect should be forced even if the
  625. * connection is opened persistently
  626. * @return mixed true on success, false if not connected and error
  627. * object on error
  628. * @access public
  629. */
  630. function disconnect($force = true)
  631. {
  632. if (is_resource($this->connection)) {
  633. if ($this->in_transaction) {
  634. $dsn = $this->dsn;
  635. $database_name = $this->database_name;
  636. $persistent = $this->options['persistent'];
  637. $this->dsn = $this->connected_dsn;
  638. $this->database_name = $this->connected_database_name;
  639. $this->options['persistent'] = $this->opened_persistent;
  640. $this->rollback();
  641. $this->dsn = $dsn;
  642. $this->database_name = $database_name;
  643. $this->options['persistent'] = $persistent;
  644. }
  645. if (!$this->opened_persistent || $force) {
  646. $ok = @mysql_close($this->connection);
  647. if (!$ok) {
  648. return $this->raiseError(MDB2_ERROR_DISCONNECT_FAILED,
  649. null, null, null, __FUNCTION__);
  650. }
  651. }
  652. } else {
  653. return false;
  654. }
  655. return parent::disconnect($force);
  656. }
  657. // }}}
  658. // {{{ standaloneQuery()
  659. /**
  660. * execute a query as DBA
  661. *
  662. * @param string $query the SQL query
  663. * @param mixed $types array that contains the types of the columns in
  664. * the result set
  665. * @param boolean $is_manip if the query is a manipulation query
  666. * @return mixed MDB2_OK on success, a MDB2 error on failure
  667. * @access public
  668. */
  669. function standaloneQuery($query, $types = null, $is_manip = false)
  670. {
  671. $user = $this->options['DBA_username']? $this->options['DBA_username'] : $this->dsn['username'];
  672. $pass = $this->options['DBA_password']? $this->options['DBA_password'] : $this->dsn['password'];
  673. $connection = $this->_doConnect($user, $pass, $this->options['persistent']);
  674. if (PEAR::isError($connection)) {
  675. return $connection;
  676. }
  677. $offset = $this->offset;
  678. $limit = $this->limit;
  679. $this->offset = $this->limit = 0;
  680. $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
  681. $result = $this->_doQuery($query, $is_manip, $connection, $this->database_name);
  682. if (!PEAR::isError($result)) {
  683. $result = $this->_affectedRows($connection, $result);
  684. }
  685. @mysql_close($connection);
  686. return $result;
  687. }
  688. // }}}
  689. // {{{ _doQuery()
  690. /**
  691. * Execute a query
  692. * @param string $query query
  693. * @param boolean $is_manip if the query is a manipulation query
  694. * @param resource $connection
  695. * @param string $database_name
  696. * @return result or error object
  697. * @access protected
  698. */
  699. function _doQuery($query, $is_manip = false, $connection = null, $database_name = null)
  700. {
  701. $this->last_query = $query;
  702. $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
  703. if ($result) {
  704. if (PEAR::isError($result)) {
  705. return $result;
  706. }
  707. $query = $result;
  708. }
  709. if ($this->options['disable_query']) {
  710. $result = $is_manip ? 0 : null;
  711. return $result;
  712. }
  713. if (is_null($connection)) {
  714. $connection = $this->getConnection();
  715. if (PEAR::isError($connection)) {
  716. return $connection;
  717. }
  718. }
  719. if (is_null($database_name)) {
  720. $database_name = $this->database_name;
  721. }
  722. if ($database_name) {
  723. if ($database_name != $this->connected_database_name) {
  724. if (!@mysql_select_db($database_name, $connection)) {
  725. $err = $this->raiseError(null, null, null,
  726. 'Could not select the database: '.$database_name, __FUNCTION__);
  727. return $err;
  728. }
  729. $this->connected_database_name = $database_name;
  730. }
  731. }
  732. $function = $this->options['result_buffering']
  733. ? 'mysql_query' : 'mysql_unbuffered_query';
  734. $result = @$function($query, $connection);
  735. if (!$result && 0 !== mysql_errno($connection)) {
  736. $err = $this->raiseError(null, null, null,
  737. 'Could not execute statement', __FUNCTION__);
  738. return $err;
  739. }
  740. $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
  741. return $result;
  742. }
  743. // }}}
  744. // {{{ _affectedRows()
  745. /**
  746. * Returns the number of rows affected
  747. *
  748. * @param resource $result
  749. * @param resource $connection
  750. * @return mixed MDB2 Error Object or the number of rows affected
  751. * @access private
  752. */
  753. function _affectedRows($connection, $result = null)
  754. {
  755. if (is_null($connection)) {
  756. $connection = $this->getConnection();
  757. if (PEAR::isError($connection)) {
  758. return $connection;
  759. }
  760. }
  761. return @mysql_affected_rows($connection);
  762. }
  763. // }}}
  764. // {{{ _modifyQuery()
  765. /**
  766. * Changes a query string for various DBMS specific reasons
  767. *
  768. * @param string $query query to modify
  769. * @param boolean $is_manip if it is a DML query
  770. * @param integer $limit limit the number of rows
  771. * @param integer $offset start reading from given offset
  772. * @return string modified query
  773. * @access protected
  774. */
  775. function _modifyQuery($query, $is_manip, $limit, $offset)
  776. {
  777. if ($this->options['portability'] & MDB2_PORTABILITY_DELETE_COUNT) {
  778. // "DELETE FROM table" gives 0 affected rows in MySQL.
  779. // This little hack lets you know how many rows were deleted.
  780. if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
  781. $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
  782. 'DELETE FROM \1 WHERE 1=1', $query);
  783. }
  784. }
  785. if ($limit > 0
  786. && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)
  787. ) {
  788. $query = rtrim($query);
  789. if (substr($query, -1) == ';') {
  790. $query = substr($query, 0, -1);
  791. }
  792. // LIMIT doesn't always come last in the query
  793. // @see http://dev.mysql.com/doc/refman/5.0/en/select.html
  794. $after = '';
  795. if (preg_match('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims', $query, $matches)) {
  796. $after = $matches[0];
  797. $query = preg_replace('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims', '', $query);
  798. } elseif (preg_match('/(\s+FOR\s+UPDATE\s*)$/i', $query, $matches)) {
  799. $after = $matches[0];
  800. $query = preg_replace('/(\s+FOR\s+UPDATE\s*)$/im', '', $query);
  801. } elseif (preg_match('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im', $query, $matches)) {
  802. $after = $matches[0];
  803. $query = preg_replace('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im', '', $query);
  804. }
  805. if ($is_manip) {
  806. return $query . " LIMIT $limit" . $after;
  807. } else {
  808. return $query . " LIMIT $offset, $limit" . $after;
  809. }
  810. }
  811. return $query;
  812. }
  813. // }}}
  814. // {{{ getServerVersion()
  815. /**
  816. * return version information about the server
  817. *
  818. * @param bool $native determines if the raw version string should be returned
  819. * @return mixed array/string with version information or MDB2 error object
  820. * @access public
  821. */
  822. function getServerVersion($native = false)
  823. {
  824. $connection = $this->getConnection();
  825. if (PEAR::isError($connection)) {
  826. return $connection;
  827. }
  828. if ($this->connected_server_info) {
  829. $server_info = $this->connected_server_info;
  830. } else {
  831. $server_info = @mysql_get_server_info($connection);
  832. }
  833. if (!$server_info) {
  834. return $this->raiseError(null, null, null,
  835. 'Could not get server information', __FUNCTION__);
  836. }
  837. // cache server_info
  838. $this->connected_server_info = $server_info;
  839. if (!$native) {
  840. $tmp = explode('.', $server_info, 3);
  841. if (isset($tmp[2]) && strpos($tmp[2], '-')) {
  842. $tmp2 = explode('-', @$tmp[2], 2);
  843. } else {
  844. $tmp2[0] = isset($tmp[2]) ? $tmp[2] : null;
  845. $tmp2[1] = null;
  846. }
  847. $server_info = array(
  848. 'major' => isset($tmp[0]) ? $tmp[0] : null,
  849. 'minor' => isset($tmp[1]) ? $tmp[1] : null,
  850. 'patch' => $tmp2[0],
  851. 'extra' => $tmp2[1],
  852. 'native' => $server_info,
  853. );
  854. }
  855. return $server_info;
  856. }
  857. // }}}
  858. // {{{ _getServerCapabilities()
  859. /**
  860. * Fetch some information about the server capabilities
  861. * (transactions, subselects, prepared statements, etc).
  862. *
  863. * @access private
  864. */
  865. function _getServerCapabilities()
  866. {
  867. if (!$this->server_capabilities_checked) {
  868. $this->server_capabilities_checked = true;
  869. //set defaults
  870. $this->supported['sub_selects'] = 'emulated';
  871. $this->supported['prepared_statements'] = 'emulated';
  872. $this->supported['triggers'] = false;
  873. $this->start_transaction = false;
  874. $this->varchar_max_length = 255;
  875. $server_info = $this->getServerVersion();
  876. if (is_array($server_info)) {
  877. $server_version = $server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'];
  878. if (!version_compare($server_version, '4.1.0', '<')) {
  879. $this->supported['sub_selects'] = true;
  880. $this->supported['prepared_statements'] = true;
  881. }
  882. // SAVEPOINTs were introduced in MySQL 4.0.14 and 4.1.1 (InnoDB)
  883. if (version_compare($server_version, '4.1.0', '>=')) {
  884. if (version_compare($server_version, '4.1.1', '<')) {
  885. $this->supported['savepoints'] = false;
  886. }
  887. } elseif (version_compare($server_version, '4.0.14', '<')) {
  888. $this->supported['savepoints'] = false;
  889. }
  890. if (!version_compare($server_version, '4.0.11', '<')) {
  891. $this->start_transaction = true;
  892. }
  893. if (!version_compare($server_version, '5.0.3', '<')) {
  894. $this->varchar_max_length = 65532;
  895. }
  896. if (!version_compare($server_version, '5.0.2', '<')) {
  897. $this->supported['triggers'] = true;
  898. }
  899. }
  900. }
  901. }
  902. // }}}
  903. // {{{ function _skipUserDefinedVariable($query, $position)
  904. /**
  905. * Utility method, used by prepare() to avoid misinterpreting MySQL user
  906. * defined variables (SELECT @x:=5) for placeholders.
  907. * Check if the placeholder is a false positive, i.e. if it is an user defined
  908. * variable instead. If so, skip it and advance the position, otherwise
  909. * return the current position, which is valid
  910. *
  911. * @param string $query
  912. * @param integer $position current string cursor position
  913. * @return integer $new_position
  914. * @access protected
  915. */
  916. function _skipUserDefinedVariable($query, $position)
  917. {
  918. $found = strpos(strrev(substr($query, 0, $position)), '@');
  919. if ($found === false) {
  920. return $position;
  921. }
  922. $pos = strlen($query) - strlen(substr($query, $position)) - $found - 1;
  923. $substring = substr($query, $pos, $position - $pos + 2);
  924. if (preg_match('/^@\w+\s*:=$/', $substring)) {
  925. return $position + 1; //found an user defined variable: skip it
  926. }
  927. return $position;
  928. }
  929. // }}}
  930. // {{{ prepare()
  931. /**
  932. * Prepares a query for multiple execution with execute().
  933. * With some database backends, this is emulated.
  934. * prepare() requires a generic query as string like
  935. * 'INSERT INTO numbers VALUES(?,?)' or
  936. * 'INSERT INTO numbers VALUES(:foo,:bar)'.
  937. * The ? and :name and are placeholders which can be set using
  938. * bindParam() and the query can be sent off using the execute() method.
  939. * The allowed format for :name can be set with the 'bindname_format' option.
  940. *
  941. * @param string $query the query to prepare
  942. * @param mixed $types array that contains the types of the placeholders
  943. * @param mixed $result_types array that contains the types of the columns in
  944. * the result set or MDB2_PREPARE_RESULT, if set to
  945. * MDB2_PREPARE_MANIP the query is handled as a manipulation query
  946. * @param mixed $lobs key (field) value (parameter) pair for all lob placeholders
  947. * @return mixed resource handle for the prepared query on success, a MDB2
  948. * error on failure
  949. * @access public
  950. * @see bindParam, execute
  951. */
  952. function prepare($query, $types = null, $result_types = null, $lobs = array())
  953. {
  954. // connect to get server capabilities (http://pear.php.net/bugs/16147)
  955. $connection = $this->getConnection();
  956. if (PEAR::isError($connection)) {
  957. return $connection;
  958. }
  959. if ($this->options['emulate_prepared']
  960. || $this->supported['prepared_statements'] !== true
  961. ) {
  962. return parent::prepare($query, $types, $result_types, $lobs);
  963. }
  964. $is_manip = ($result_types === MDB2_PREPARE_MANIP);
  965. $offset = $this->offset;
  966. $limit = $this->limit;
  967. $this->offset = $this->limit = 0;
  968. $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
  969. $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
  970. if ($result) {
  971. if (PEAR::isError($result)) {
  972. return $result;
  973. }
  974. $query = $result;
  975. }
  976. $placeholder_type_guess = $placeholder_type = null;
  977. $question = '?';
  978. $colon = ':';
  979. $positions = array();
  980. $position = 0;
  981. while ($position < strlen($query)) {
  982. $q_position = strpos($query, $question, $position);
  983. $c_position = strpos($query, $colon, $position);
  984. if ($q_position && $c_position) {
  985. $p_position = min($q_position, $c_position);
  986. } elseif ($q_position) {
  987. $p_position = $q_position;
  988. } elseif ($c_position) {
  989. $p_position = $c_position;
  990. } else {
  991. break;
  992. }
  993. if (is_null($placeholder_type)) {
  994. $placeholder_type_guess = $query[$p_position];
  995. }
  996. $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
  997. if (PEAR::isError($new_pos)) {
  998. return $new_pos;
  999. }
  1000. if ($new_pos != $position) {
  1001. $position = $new_pos;
  1002. continue; //evaluate again starting from the new position
  1003. }
  1004. //make sure this is not part of an user defined variable
  1005. $new_pos = $this->_skipUserDefinedVariable($query, $position);
  1006. if ($new_pos != $position) {
  1007. $position = $new_pos;
  1008. continue; //evaluate again starting from the new position
  1009. }
  1010. if ($query[$position] == $placeholder_type_guess) {
  1011. if (is_null($placeholder_type)) {
  1012. $placeholder_type = $query[$p_position];
  1013. $question = $colon = $placeholder_type;
  1014. }
  1015. if ($placeholder_type == ':') {
  1016. $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
  1017. $parameter = preg_replace($regexp, '\\1', $query);
  1018. if ($parameter === '') {
  1019. $err = $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
  1020. 'named parameter name must match "bindname_format" option', __FUNCTION__);
  1021. return $err;
  1022. }
  1023. $positions[$p_position] = $parameter;
  1024. $query = substr_replace($query, '?', $position, strlen($parameter)+1);
  1025. } else {
  1026. $positions[$p_position] = count($positions);
  1027. }
  1028. $position = $p_position + 1;
  1029. } else {
  1030. $position = $p_position;
  1031. }
  1032. }
  1033. static $prep_statement_counter = 1;
  1034. $statement_name = sprintf($this->options['statement_format'], $this->phptype, $prep_statement_counter++ . sha1(microtime() + mt_rand()));
  1035. $statement_name = substr(strtolower($statement_name), 0, $this->options['max_identifiers_length']);
  1036. $query = "PREPARE $statement_name FROM ".$this->quote($query, 'text');
  1037. $statement = $this->_doQuery($query, true, $connection);
  1038. if (PEAR::isError($statement)) {
  1039. return $statement;
  1040. }
  1041. $class_name = 'MDB2_Statement_'.$this->phptype;
  1042. $obj = new $class_name($this, $statement_name, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
  1043. $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
  1044. return $obj;
  1045. }
  1046. // }}}
  1047. // {{{ replace()
  1048. /**
  1049. * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
  1050. * query, except that if there is already a row in the table with the same
  1051. * key field values, the old row is deleted before the new row is inserted.
  1052. *
  1053. * The REPLACE type of query does not make part of the SQL standards. Since
  1054. * practically only MySQL implements it natively, this type of query is
  1055. * emulated through this method for other DBMS using standard types of
  1056. * queries inside a transaction to assure the atomicity of the operation.
  1057. *
  1058. * @access public
  1059. *
  1060. * @param string $table name of the table on which the REPLACE query will
  1061. * be executed.
  1062. * @param array $fields associative array that describes the fields and the
  1063. * values that will be inserted or updated in the specified table. The
  1064. * indexes of the array are the names of all the fields of the table. The
  1065. * values of the array are also associative arrays that describe the
  1066. * values and other properties of the table fields.
  1067. *
  1068. * Here follows a list of field properties that need to be specified:
  1069. *
  1070. * value:
  1071. * Value to be assigned to the specified field. This value may be
  1072. * of specified in database independent type format as this
  1073. * function can perform the necessary datatype conversions.
  1074. *
  1075. * Default:
  1076. * this property is required unless the Null property
  1077. * is set to 1.
  1078. *
  1079. * type
  1080. * Name of the type of the field. Currently, all types Metabase
  1081. * are supported except for clob and blob.
  1082. *
  1083. * Default: no type conversion
  1084. *
  1085. * null
  1086. * Boolean property that indicates that the value for this field
  1087. * should be set to null.
  1088. *
  1089. * The default value for fields missing in INSERT queries may be
  1090. * specified the definition of a table. Often, the default value
  1091. * is already null, but since the REPLACE may be emulated using
  1092. * an UPDATE query, make sure that all fields of the table are
  1093. * listed in this function argument array.
  1094. *
  1095. * Default: 0
  1096. *
  1097. * key
  1098. * Boolean property that indicates that this field should be
  1099. * handled as a primary key or at least as part of the compound
  1100. * unique index of the table that will determine the row that will
  1101. * updated if it exists or inserted a new row otherwise.
  1102. *
  1103. * This function will fail if no key field is specified or if the
  1104. * value of a key field is set to null because fields that are
  1105. * part of unique index they may not be null.
  1106. *
  1107. * Default: 0
  1108. *
  1109. * @see http://dev.mysql.com/doc/refman/5.0/en/replace.html
  1110. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1111. */
  1112. function replace($table, $fields)
  1113. {
  1114. $count = count($fields);
  1115. $query = $values = '';
  1116. $keys = $colnum = 0;
  1117. for (reset($fields); $colnum < $count; next($fields), $colnum++) {
  1118. $name = key($fields);
  1119. if ($colnum > 0) {
  1120. $query .= ',';
  1121. $values.= ',';
  1122. }
  1123. $query.= $this->quoteIdentifier($name, true);
  1124. if (isset($fields[$name]['null']) && $fields[$name]['null']) {
  1125. $value = 'NULL';
  1126. } else {
  1127. $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
  1128. $value = $this->quote($fields[$name]['value'], $type);
  1129. if (PEAR::isError($value)) {
  1130. return $value;
  1131. }
  1132. }
  1133. $values.= $value;
  1134. if (isset($fields[$name]['key']) && $fields[$name]['key']) {
  1135. if ($value === 'NULL') {
  1136. return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
  1137. 'key value '.$name.' may not be NULL', __FUNCTION__);
  1138. }
  1139. $keys++;
  1140. }
  1141. }
  1142. if ($keys == 0) {
  1143. return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
  1144. 'not specified which fields are keys', __FUNCTION__);
  1145. }
  1146. $connection = $this->getConnection();
  1147. if (PEAR::isError($connection)) {
  1148. return $connection;
  1149. }
  1150. $table = $this->quoteIdentifier($table, true);
  1151. $query = "REPLACE INTO $table ($query) VALUES ($values)";
  1152. $result = $this->_doQuery($query, true, $connection);
  1153. if (PEAR::isError($result)) {
  1154. return $result;
  1155. }
  1156. return $this->_affectedRows($connection, $result);
  1157. }
  1158. // }}}
  1159. // {{{ nextID()

Large files files are truncated, but you can click here to view the full file