PageRenderTime 69ms CodeModel.GetById 36ms RepoModel.GetById 1ms app.codeStats 0ms

/includes/pear/MDB2/Driver/sqlite.php

https://bitbucket.org/Yason/armory
PHP | 1082 lines | 1027 code | 1 blank | 54 comment | 1 complexity | e2d5003fe196587ea37d14c75480421e MD5 | raw file
Possible License(s): GPL-3.0
  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: sqlite.php,v 1.165 2008/11/30 14:28:01 afz Exp $
  47. //
  48. /**
  49. * MDB2 SQLite driver
  50. *
  51. * @package MDB2
  52. * @category Database
  53. * @author Lukas Smith <smith@pooteeweet.org>
  54. */
  55. class MDB2_Driver_sqlite extends MDB2_Driver_Common
  56. {
  57. // {{{ properties
  58. var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => "'", 'escape_pattern' => false);
  59. var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"');
  60. var $_lasterror = '';
  61. var $fix_assoc_fields_names = false;
  62. // }}}
  63. // {{{ constructor
  64. /**
  65. * Constructor
  66. */
  67. function __construct()
  68. {
  69. parent::__construct();
  70. $this->phptype = 'sqlite';
  71. $this->dbsyntax = 'sqlite';
  72. $this->supported['sequences'] = 'emulated';
  73. $this->supported['indexes'] = true;
  74. $this->supported['affected_rows'] = true;
  75. $this->supported['summary_functions'] = true;
  76. $this->supported['order_by_text'] = true;
  77. $this->supported['current_id'] = 'emulated';
  78. $this->supported['limit_queries'] = true;
  79. $this->supported['LOBs'] = true;
  80. $this->supported['replace'] = true;
  81. $this->supported['transactions'] = true;
  82. $this->supported['savepoints'] = false;
  83. $this->supported['sub_selects'] = true;
  84. $this->supported['triggers'] = true;
  85. $this->supported['auto_increment'] = true;
  86. $this->supported['primary_key'] = false; // requires alter table implementation
  87. $this->supported['result_introspection'] = false; // not implemented
  88. $this->supported['prepared_statements'] = 'emulated';
  89. $this->supported['identifier_quoting'] = true;
  90. $this->supported['pattern_escaping'] = false;
  91. $this->supported['new_link'] = false;
  92. $this->options['DBA_username'] = false;
  93. $this->options['DBA_password'] = false;
  94. $this->options['base_transaction_name'] = '___php_MDB2_sqlite_auto_commit_off';
  95. $this->options['fixed_float'] = 0;
  96. $this->options['database_path'] = '';
  97. $this->options['database_extension'] = '';
  98. $this->options['server_version'] = '';
  99. $this->options['max_identifiers_length'] = 128; //no real limit
  100. }
  101. // }}}
  102. // {{{ errorInfo()
  103. /**
  104. * This method is used to collect information about an error
  105. *
  106. * @param integer $error
  107. * @return array
  108. * @access public
  109. */
  110. function errorInfo($error = null)
  111. {
  112. $native_code = null;
  113. if ($this->connection) {
  114. $native_code = @sqlite_last_error($this->connection);
  115. }
  116. $native_msg = $this->_lasterror
  117. ? html_entity_decode($this->_lasterror) : @sqlite_error_string($native_code);
  118. // PHP 5.2+ prepends the function name to $php_errormsg, so we need
  119. // this hack to work around it, per bug #9599.
  120. $native_msg = preg_replace('/^sqlite[a-z_]+\(\)[^:]*: /', '', $native_msg);
  121. if (is_null($error)) {
  122. static $error_regexps;
  123. if (empty($error_regexps)) {
  124. $error_regexps = array(
  125. '/^no such table:/' => MDB2_ERROR_NOSUCHTABLE,
  126. '/^no such index:/' => MDB2_ERROR_NOT_FOUND,
  127. '/^(table|index) .* already exists$/' => MDB2_ERROR_ALREADY_EXISTS,
  128. '/PRIMARY KEY must be unique/i' => MDB2_ERROR_CONSTRAINT,
  129. '/is not unique/' => MDB2_ERROR_CONSTRAINT,
  130. '/columns .* are not unique/i' => MDB2_ERROR_CONSTRAINT,
  131. '/uniqueness constraint failed/' => MDB2_ERROR_CONSTRAINT,
  132. '/may not be NULL/' => MDB2_ERROR_CONSTRAINT_NOT_NULL,
  133. '/^no such column:/' => MDB2_ERROR_NOSUCHFIELD,
  134. '/no column named/' => MDB2_ERROR_NOSUCHFIELD,
  135. '/column not present in both tables/i' => MDB2_ERROR_NOSUCHFIELD,
  136. '/^near ".*": syntax error$/' => MDB2_ERROR_SYNTAX,
  137. '/[0-9]+ values for [0-9]+ columns/i' => MDB2_ERROR_VALUE_COUNT_ON_ROW,
  138. );
  139. }
  140. foreach ($error_regexps as $regexp => $code) {
  141. if (preg_match($regexp, $native_msg)) {
  142. $error = $code;
  143. break;
  144. }
  145. }
  146. }
  147. return array($error, $native_code, $native_msg);
  148. }
  149. // }}}
  150. // {{{ escape()
  151. /**
  152. * Quotes a string so it can be safely used in a query. It will quote
  153. * the text so it can safely be used within a query.
  154. *
  155. * @param string the input string to quote
  156. * @param bool escape wildcards
  157. *
  158. * @return string quoted string
  159. *
  160. * @access public
  161. */
  162. function escape($text, $escape_wildcards = false)
  163. {
  164. $text = @sqlite_escape_string($text);
  165. return $text;
  166. }
  167. // }}}
  168. // {{{ beginTransaction()
  169. /**
  170. * Start a transaction or set a savepoint.
  171. *
  172. * @param string name of a savepoint to set
  173. * @return mixed MDB2_OK on success, a MDB2 error on failure
  174. *
  175. * @access public
  176. */
  177. function beginTransaction($savepoint = null)
  178. {
  179. $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  180. if (!is_null($savepoint)) {
  181. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  182. 'savepoints are not supported', __FUNCTION__);
  183. } elseif ($this->in_transaction) {
  184. return MDB2_OK; //nothing to do
  185. }
  186. if (!$this->destructor_registered && $this->opened_persistent) {
  187. $this->destructor_registered = true;
  188. register_shutdown_function('MDB2_closeOpenTransactions');
  189. }
  190. $query = 'BEGIN TRANSACTION '.$this->options['base_transaction_name'];
  191. $result =& $this->_doQuery($query, true);
  192. if (PEAR::isError($result)) {
  193. return $result;
  194. }
  195. $this->in_transaction = true;
  196. return MDB2_OK;
  197. }
  198. // }}}
  199. // {{{ commit()
  200. /**
  201. * Commit the database changes done during a transaction that is in
  202. * progress or release a savepoint. This function may only be called when
  203. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  204. * transaction is implicitly started after committing the pending changes.
  205. *
  206. * @param string name of a savepoint to release
  207. * @return mixed MDB2_OK on success, a MDB2 error on failure
  208. *
  209. * @access public
  210. */
  211. function commit($savepoint = null)
  212. {
  213. $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  214. if (!$this->in_transaction) {
  215. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  216. 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
  217. }
  218. if (!is_null($savepoint)) {
  219. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  220. 'savepoints are not supported', __FUNCTION__);
  221. }
  222. $query = 'COMMIT TRANSACTION '.$this->options['base_transaction_name'];
  223. $result =& $this->_doQuery($query, true);
  224. if (PEAR::isError($result)) {
  225. return $result;
  226. }
  227. $this->in_transaction = false;
  228. return MDB2_OK;
  229. }
  230. // }}}
  231. // {{{
  232. /**
  233. * Cancel any database changes done during a transaction or since a specific
  234. * savepoint that is in progress. This function may only be called when
  235. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  236. * transaction is implicitly started after canceling the pending changes.
  237. *
  238. * @param string name of a savepoint to rollback to
  239. * @return mixed MDB2_OK on success, a MDB2 error on failure
  240. *
  241. * @access public
  242. */
  243. function rollback($savepoint = null)
  244. {
  245. $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  246. if (!$this->in_transaction) {
  247. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  248. 'rollback cannot be done changes are auto committed', __FUNCTION__);
  249. }
  250. if (!is_null($savepoint)) {
  251. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  252. 'savepoints are not supported', __FUNCTION__);
  253. }
  254. $query = 'ROLLBACK TRANSACTION '.$this->options['base_transaction_name'];
  255. $result =& $this->_doQuery($query, true);
  256. if (PEAR::isError($result)) {
  257. return $result;
  258. }
  259. $this->in_transaction = false;
  260. return MDB2_OK;
  261. }
  262. // }}}
  263. // {{{ function setTransactionIsolation()
  264. /**
  265. * Set the transacton isolation level.
  266. *
  267. * @param string standard isolation level
  268. * READ UNCOMMITTED (allows dirty reads)
  269. * READ COMMITTED (prevents dirty reads)
  270. * REPEATABLE READ (prevents nonrepeatable reads)
  271. * SERIALIZABLE (prevents phantom reads)
  272. * @return mixed MDB2_OK on success, a MDB2 error on failure
  273. *
  274. * @access public
  275. * @since 2.1.1
  276. */
  277. function setTransactionIsolation($isolation)
  278. {
  279. $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
  280. switch ($isolation) {
  281. case 'READ UNCOMMITTED':
  282. $isolation = 0;
  283. break;
  284. case 'READ COMMITTED':
  285. case 'REPEATABLE READ':
  286. case 'SERIALIZABLE':
  287. $isolation = 1;
  288. break;
  289. default:
  290. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  291. 'isolation level is not supported: '.$isolation, __FUNCTION__);
  292. }
  293. $query = "PRAGMA read_uncommitted=$isolation";
  294. return $this->_doQuery($query, true);
  295. }
  296. // }}}
  297. // {{{ getDatabaseFile()
  298. /**
  299. * Builds the string with path+dbname+extension
  300. *
  301. * @return string full database path+file
  302. * @access protected
  303. */
  304. function _getDatabaseFile($database_name)
  305. {
  306. if ($database_name === '' || $database_name === ':memory:') {
  307. return $database_name;
  308. }
  309. return $this->options['database_path'].$database_name.$this->options['database_extension'];
  310. }
  311. // }}}
  312. // {{{ connect()
  313. /**
  314. * Connect to the database
  315. *
  316. * @return true on success, MDB2 Error Object on failure
  317. **/
  318. function connect()
  319. {
  320. $database_file = $this->_getDatabaseFile($this->database_name);
  321. if (is_resource($this->connection)) {
  322. //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
  323. if (MDB2::areEquals($this->connected_dsn, $this->dsn)
  324. && $this->connected_database_name == $database_file
  325. && $this->opened_persistent == $this->options['persistent']
  326. ) {
  327. return MDB2_OK;
  328. }
  329. $this->disconnect(false);
  330. }
  331. if (!PEAR::loadExtension($this->phptype)) {
  332. return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  333. 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
  334. }
  335. if (empty($this->database_name)) {
  336. return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
  337. 'unable to establish a connection', __FUNCTION__);
  338. }
  339. if ($database_file !== ':memory:') {
  340. if (!file_exists($database_file)) {
  341. if (!touch($database_file)) {
  342. return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  343. 'Could not create database file', __FUNCTION__);
  344. }
  345. if (!isset($this->dsn['mode'])
  346. || !is_numeric($this->dsn['mode'])
  347. ) {
  348. $mode = 0644;
  349. } else {
  350. $mode = octdec($this->dsn['mode']);
  351. }
  352. if (!chmod($database_file, $mode)) {
  353. return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  354. 'Could not be chmodded database file', __FUNCTION__);
  355. }
  356. if (!file_exists($database_file)) {
  357. return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  358. 'Could not be found database file', __FUNCTION__);
  359. }
  360. }
  361. if (!is_file($database_file)) {
  362. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  363. 'Database is a directory name', __FUNCTION__);
  364. }
  365. if (!is_readable($database_file)) {
  366. return $this->raiseError(MDB2_ERROR_ACCESS_VIOLATION, null, null,
  367. 'Could not read database file', __FUNCTION__);
  368. }
  369. }
  370. $connect_function = ($this->options['persistent'] ? 'sqlite_popen' : 'sqlite_open');
  371. $php_errormsg = '';
  372. if (version_compare('5.1.0', PHP_VERSION, '>')) {
  373. @ini_set('track_errors', true);
  374. $connection = @$connect_function($database_file);
  375. @ini_restore('track_errors');
  376. } else {
  377. $connection = @$connect_function($database_file, 0666, $php_errormsg);
  378. }
  379. $this->_lasterror = $php_errormsg;
  380. if (!$connection) {
  381. return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
  382. 'unable to establish a connection', __FUNCTION__);
  383. }
  384. if ($this->fix_assoc_fields_names ||
  385. $this->options['portability'] & MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES)
  386. {
  387. @sqlite_query("PRAGMA short_column_names = 1", $connection);
  388. $this->fix_assoc_fields_names = true;
  389. }
  390. $this->connection = $connection;
  391. $this->connected_dsn = $this->dsn;
  392. $this->connected_database_name = $database_file;
  393. $this->opened_persistent = $this->getoption('persistent');
  394. $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
  395. return MDB2_OK;
  396. }
  397. // }}}
  398. // {{{ databaseExists()
  399. /**
  400. * check if given database name is exists?
  401. *
  402. * @param string $name name of the database that should be checked
  403. *
  404. * @return mixed true/false on success, a MDB2 error on failure
  405. * @access public
  406. */
  407. function databaseExists($name)
  408. {
  409. $database_file = $this->_getDatabaseFile($name);
  410. $result = file_exists($database_file);
  411. return $result;
  412. }
  413. // }}}
  414. // {{{ disconnect()
  415. /**
  416. * Log out and disconnect from the database.
  417. *
  418. * @param boolean $force if the disconnect should be forced even if the
  419. * connection is opened persistently
  420. * @return mixed true on success, false if not connected and error
  421. * object on error
  422. * @access public
  423. */
  424. function disconnect($force = true)
  425. {
  426. if (is_resource($this->connection)) {
  427. if ($this->in_transaction) {
  428. $dsn = $this->dsn;
  429. $database_name = $this->database_name;
  430. $persistent = $this->options['persistent'];
  431. $this->dsn = $this->connected_dsn;
  432. $this->database_name = $this->connected_database_name;
  433. $this->options['persistent'] = $this->opened_persistent;
  434. $this->rollback();
  435. $this->dsn = $dsn;
  436. $this->database_name = $database_name;
  437. $this->options['persistent'] = $persistent;
  438. }
  439. if (!$this->opened_persistent || $force) {
  440. @sqlite_close($this->connection);
  441. }
  442. } else {
  443. return false;
  444. }
  445. return parent::disconnect($force);
  446. }
  447. // }}}
  448. // {{{ _doQuery()
  449. /**
  450. * Execute a query
  451. * @param string $query query
  452. * @param boolean $is_manip if the query is a manipulation query
  453. * @param resource $connection
  454. * @param string $database_name
  455. * @return result or error object
  456. * @access protected
  457. */
  458. function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
  459. {
  460. $this->last_query = $query;
  461. $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
  462. if ($result) {
  463. if (PEAR::isError($result)) {
  464. return $result;
  465. }
  466. $query = $result;
  467. }
  468. if ($this->options['disable_query']) {
  469. $result = $is_manip ? 0 : null;
  470. return $result;
  471. }
  472. if (is_null($connection)) {
  473. $connection = $this->getConnection();
  474. if (PEAR::isError($connection)) {
  475. return $connection;
  476. }
  477. }
  478. $function = $this->options['result_buffering']
  479. ? 'sqlite_query' : 'sqlite_unbuffered_query';
  480. $php_errormsg = '';
  481. if (version_compare('5.1.0', PHP_VERSION, '>')) {
  482. @ini_set('track_errors', true);
  483. do {
  484. $result = @$function($query.';', $connection);
  485. } while (sqlite_last_error($connection) == SQLITE_SCHEMA);
  486. @ini_restore('track_errors');
  487. } else {
  488. do {
  489. $result = @$function($query.';', $connection, SQLITE_BOTH, $php_errormsg);
  490. } while (sqlite_last_error($connection) == SQLITE_SCHEMA);
  491. }
  492. $this->_lasterror = $php_errormsg;
  493. if (!$result) {
  494. $err =& $this->raiseError(null, null, null,
  495. 'Could not execute statement', __FUNCTION__);
  496. return $err;
  497. }
  498. $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
  499. return $result;
  500. }
  501. // }}}
  502. // {{{ _affectedRows()
  503. /**
  504. * Returns the number of rows affected
  505. *
  506. * @param resource $result
  507. * @param resource $connection
  508. * @return mixed MDB2 Error Object or the number of rows affected
  509. * @access private
  510. */
  511. function _affectedRows($connection, $result = null)
  512. {
  513. if (is_null($connection)) {
  514. $connection = $this->getConnection();
  515. if (PEAR::isError($connection)) {
  516. return $connection;
  517. }
  518. }
  519. return @sqlite_changes($connection);
  520. }
  521. // }}}
  522. // {{{ _modifyQuery()
  523. /**
  524. * Changes a query string for various DBMS specific reasons
  525. *
  526. * @param string $query query to modify
  527. * @param boolean $is_manip if it is a DML query
  528. * @param integer $limit limit the number of rows
  529. * @param integer $offset start reading from given offset
  530. * @return string modified query
  531. * @access protected
  532. */
  533. function _modifyQuery($query, $is_manip, $limit, $offset)
  534. {
  535. if ($this->options['portability'] & MDB2_PORTABILITY_DELETE_COUNT) {
  536. if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
  537. $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
  538. 'DELETE FROM \1 WHERE 1=1', $query);
  539. }
  540. }
  541. if ($limit > 0
  542. && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)
  543. ) {
  544. $query = rtrim($query);
  545. if (substr($query, -1) == ';') {
  546. $query = substr($query, 0, -1);
  547. }
  548. if ($is_manip) {
  549. $query.= " LIMIT $limit";
  550. } else {
  551. $query.= " LIMIT $offset,$limit";
  552. }
  553. }
  554. return $query;
  555. }
  556. // }}}
  557. // {{{ getServerVersion()
  558. /**
  559. * return version information about the server
  560. *
  561. * @param bool $native determines if the raw version string should be returned
  562. * @return mixed array/string with version information or MDB2 error object
  563. * @access public
  564. */
  565. function getServerVersion($native = false)
  566. {
  567. $server_info = false;
  568. if ($this->connected_server_info) {
  569. $server_info = $this->connected_server_info;
  570. } elseif ($this->options['server_version']) {
  571. $server_info = $this->options['server_version'];
  572. } elseif (function_exists('sqlite_libversion')) {
  573. $server_info = @sqlite_libversion();
  574. }
  575. if (!$server_info) {
  576. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  577. 'Requires either the "server_version" option or the sqlite_libversion() function', __FUNCTION__);
  578. }
  579. // cache server_info
  580. $this->connected_server_info = $server_info;
  581. if (!$native) {
  582. $tmp = explode('.', $server_info, 3);
  583. $server_info = array(
  584. 'major' => isset($tmp[0]) ? $tmp[0] : null,
  585. 'minor' => isset($tmp[1]) ? $tmp[1] : null,
  586. 'patch' => isset($tmp[2]) ? $tmp[2] : null,
  587. 'extra' => null,
  588. 'native' => $server_info,
  589. );
  590. }
  591. return $server_info;
  592. }
  593. // }}}
  594. // {{{ replace()
  595. /**
  596. * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
  597. * query, except that if there is already a row in the table with the same
  598. * key field values, the old row is deleted before the new row is inserted.
  599. *
  600. * The REPLACE type of query does not make part of the SQL standards. Since
  601. * practically only SQLite implements it natively, this type of query is
  602. * emulated through this method for other DBMS using standard types of
  603. * queries inside a transaction to assure the atomicity of the operation.
  604. *
  605. * @access public
  606. *
  607. * @param string $table name of the table on which the REPLACE query will
  608. * be executed.
  609. * @param array $fields associative array that describes the fields and the
  610. * values that will be inserted or updated in the specified table. The
  611. * indexes of the array are the names of all the fields of the table. The
  612. * values of the array are also associative arrays that describe the
  613. * values and other properties of the table fields.
  614. *
  615. * Here follows a list of field properties that need to be specified:
  616. *
  617. * value:
  618. * Value to be assigned to the specified field. This value may be
  619. * of specified in database independent type format as this
  620. * function can perform the necessary datatype conversions.
  621. *
  622. * Default:
  623. * this property is required unless the Null property
  624. * is set to 1.
  625. *
  626. * type
  627. * Name of the type of the field. Currently, all types Metabase
  628. * are supported except for clob and blob.
  629. *
  630. * Default: no type conversion
  631. *
  632. * null
  633. * Boolean property that indicates that the value for this field
  634. * should be set to null.
  635. *
  636. * The default value for fields missing in INSERT queries may be
  637. * specified the definition of a table. Often, the default value
  638. * is already null, but since the REPLACE may be emulated using
  639. * an UPDATE query, make sure that all fields of the table are
  640. * listed in this function argument array.
  641. *
  642. * Default: 0
  643. *
  644. * key
  645. * Boolean property that indicates that this field should be
  646. * handled as a primary key or at least as part of the compound
  647. * unique index of the table that will determine the row that will
  648. * updated if it exists or inserted a new row otherwise.
  649. *
  650. * This function will fail if no key field is specified or if the
  651. * value of a key field is set to null because fields that are
  652. * part of unique index they may not be null.
  653. *
  654. * Default: 0
  655. *
  656. * @return mixed MDB2_OK on success, a MDB2 error on failure
  657. */
  658. function replace($table, $fields)
  659. {
  660. $count = count($fields);
  661. $query = $values = '';
  662. $keys = $colnum = 0;
  663. for (reset($fields); $colnum < $count; next($fields), $colnum++) {
  664. $name = key($fields);
  665. if ($colnum > 0) {
  666. $query .= ',';
  667. $values.= ',';
  668. }
  669. $query.= $this->quoteIdentifier($name, true);
  670. if (isset($fields[$name]['null']) && $fields[$name]['null']) {
  671. $value = 'NULL';
  672. } else {
  673. $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
  674. $value = $this->quote($fields[$name]['value'], $type);
  675. if (PEAR::isError($value)) {
  676. return $value;
  677. }
  678. }
  679. $values.= $value;
  680. if (isset($fields[$name]['key']) && $fields[$name]['key']) {
  681. if ($value === 'NULL') {
  682. return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
  683. 'key value '.$name.' may not be NULL', __FUNCTION__);
  684. }
  685. $keys++;
  686. }
  687. }
  688. if ($keys == 0) {
  689. return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
  690. 'not specified which fields are keys', __FUNCTION__);
  691. }
  692. $connection = $this->getConnection();
  693. if (PEAR::isError($connection)) {
  694. return $connection;
  695. }
  696. $table = $this->quoteIdentifier($table, true);
  697. $query = "REPLACE INTO $table ($query) VALUES ($values)";
  698. $result =& $this->_doQuery($query, true, $connection);
  699. if (PEAR::isError($result)) {
  700. return $result;
  701. }
  702. return $this->_affectedRows($connection, $result);
  703. }
  704. // }}}
  705. // {{{ nextID()
  706. /**
  707. * Returns the next free id of a sequence
  708. *
  709. * @param string $seq_name name of the sequence
  710. * @param boolean $ondemand when true the sequence is
  711. * automatic created, if it
  712. * not exists
  713. *
  714. * @return mixed MDB2 Error Object or id
  715. * @access public
  716. */
  717. function nextID($seq_name, $ondemand = true)
  718. {
  719. $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
  720. $seqcol_name = $this->options['seqcol_name'];
  721. $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
  722. $this->pushErrorHandling(PEAR_ERROR_RETURN);
  723. $this->expectError(MDB2_ERROR_NOSUCHTABLE);
  724. $result =& $this->_doQuery($query, true);
  725. $this->popExpect();
  726. $this->popErrorHandling();
  727. if (PEAR::isError($result)) {
  728. if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
  729. $this->loadModule('Manager', null, true);
  730. $result = $this->manager->createSequence($seq_name);
  731. if (PEAR::isError($result)) {
  732. return $this->raiseError($result, null, null,
  733. 'on demand sequence '.$seq_name.' could not be created', __FUNCTION__);
  734. } else {
  735. return $this->nextID($seq_name, false);
  736. }
  737. }
  738. return $result;
  739. }
  740. $value = $this->lastInsertID();
  741. if (is_numeric($value)) {
  742. $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
  743. $result =& $this->_doQuery($query, true);
  744. if (PEAR::isError($result)) {
  745. $this->warnings[] = 'nextID: could not delete previous sequence table values from '.$seq_name;
  746. }
  747. }
  748. return $value;
  749. }
  750. // }}}
  751. // {{{ lastInsertID()
  752. /**
  753. * Returns the autoincrement ID if supported or $id or fetches the current
  754. * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
  755. *
  756. * @param string $table name of the table into which a new row was inserted
  757. * @param string $field name of the field into which a new row was inserted
  758. * @return mixed MDB2 Error Object or id
  759. * @access public
  760. */
  761. function lastInsertID($table = null, $field = null)
  762. {
  763. $connection = $this->getConnection();
  764. if (PEAR::isError($connection)) {
  765. return $connection;
  766. }
  767. $value = @sqlite_last_insert_rowid($connection);
  768. if (!$value) {
  769. return $this->raiseError(null, null, null,
  770. 'Could not get last insert ID', __FUNCTION__);
  771. }
  772. return $value;
  773. }
  774. // }}}
  775. // {{{ currID()
  776. /**
  777. * Returns the current id of a sequence
  778. *
  779. * @param string $seq_name name of the sequence
  780. * @return mixed MDB2 Error Object or id
  781. * @access public
  782. */
  783. function currID($seq_name)
  784. {
  785. $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
  786. $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
  787. $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
  788. return $this->queryOne($query, 'integer');
  789. }
  790. }
  791. /**
  792. * MDB2 SQLite result driver
  793. *
  794. * @package MDB2
  795. * @category Database
  796. * @author Lukas Smith <smith@pooteeweet.org>
  797. */
  798. class MDB2_Result_sqlite extends MDB2_Result_Common
  799. {
  800. // }}}
  801. // {{{ fetchRow()
  802. /**
  803. * Fetch a row and insert the data into an existing array.
  804. *
  805. * @param int $fetchmode how the array data should be indexed
  806. * @param int $rownum number of the row where the data can be found
  807. * @return int data array on success, a MDB2 error on failure
  808. * @access public
  809. */
  810. function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
  811. {
  812. if (!is_null($rownum)) {
  813. $seek = $this->seek($rownum);
  814. if (PEAR::isError($seek)) {
  815. return $seek;
  816. }
  817. }
  818. if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
  819. $fetchmode = $this->db->fetchmode;
  820. }
  821. if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
  822. $row = @sqlite_fetch_array($this->result, SQLITE_ASSOC);
  823. if (is_array($row)
  824. && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
  825. ) {
  826. $row = array_change_key_case($row, $this->db->options['field_case']);
  827. }
  828. } else {
  829. $row = @sqlite_fetch_array($this->result, SQLITE_NUM);
  830. }
  831. if (!$row) {
  832. if ($this->result === false) {
  833. $err =& $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  834. 'resultset has already been freed', __FUNCTION__);
  835. return $err;
  836. }
  837. $null = null;
  838. return $null;
  839. }
  840. $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
  841. $rtrim = false;
  842. if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
  843. if (empty($this->types)) {
  844. $mode += MDB2_PORTABILITY_RTRIM;
  845. } else {
  846. $rtrim = true;
  847. }
  848. }
  849. if ($mode) {
  850. $this->db->_fixResultArrayValues($row, $mode);
  851. }
  852. if (!empty($this->types)) {
  853. $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
  854. }
  855. if (!empty($this->values)) {
  856. $this->_assignBindColumns($row);
  857. }
  858. if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
  859. $object_class = $this->db->options['fetch_class'];
  860. if ($object_class == 'stdClass') {
  861. $row = (object) $row;
  862. } else {
  863. $row = &new $object_class($row);
  864. }
  865. }
  866. ++$this->rownum;
  867. return $row;
  868. }
  869. // }}}
  870. // {{{ _getColumnNames()
  871. /**
  872. * Retrieve the names of columns returned by the DBMS in a query result.
  873. *
  874. * @return mixed Array variable that holds the names of columns as keys
  875. * or an MDB2 error on failure.
  876. * Some DBMS may not return any columns when the result set
  877. * does not contain any rows.
  878. * @access private
  879. */
  880. function _getColumnNames()
  881. {
  882. $columns = array();
  883. $numcols = $this->numCols();
  884. if (PEAR::isError($numcols)) {
  885. return $numcols;
  886. }
  887. for ($column = 0; $column < $numcols; $column++) {
  888. $column_name = @sqlite_field_name($this->result, $column);
  889. $columns[$column_name] = $column;
  890. }
  891. if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  892. $columns = array_change_key_case($columns, $this->db->options['field_case']);
  893. }
  894. return $columns;
  895. }
  896. // }}}
  897. // {{{ numCols()
  898. /**
  899. * Count the number of columns returned by the DBMS in a query result.
  900. *
  901. * @access public
  902. * @return mixed integer value with the number of columns, a MDB2 error
  903. * on failure
  904. */
  905. function numCols()
  906. {
  907. $cols = @sqlite_num_fields($this->result);
  908. if (is_null($cols)) {
  909. if ($this->result === false) {
  910. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  911. 'resultset has already been freed', __FUNCTION__);
  912. } elseif (is_null($this->result)) {
  913. return count($this->types);
  914. }
  915. return $this->db->raiseError(null, null, null,
  916. 'Could not get column count', __FUNCTION__);
  917. }
  918. return $cols;
  919. }
  920. }
  921. /**
  922. * MDB2 SQLite buffered result driver
  923. *
  924. * @package MDB2
  925. * @category Database
  926. * @author Lukas Smith <smith@pooteeweet.org>
  927. */
  928. class MDB2_BufferedResult_sqlite extends MDB2_Result_sqlite
  929. {
  930. // {{{ seek()
  931. /**
  932. * Seek to a specific row in a result set
  933. *
  934. * @param int $rownum number of the row where the data can be found
  935. * @return mixed MDB2_OK on success, a MDB2 error on failure
  936. * @access public
  937. */
  938. function seek($rownum = 0)
  939. {
  940. if (!@sqlite_seek($this->result, $rownum)) {
  941. if ($this->result === false) {
  942. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  943. 'resultset has already been freed', __FUNCTION__);
  944. } elseif (is_null($this->result)) {
  945. return MDB2_OK;
  946. }
  947. return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
  948. 'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
  949. }
  950. $this->rownum = $rownum - 1;
  951. return MDB2_OK;
  952. }
  953. // }}}
  954. // {{{ valid()
  955. /**
  956. * Check if the end of the result set has been reached
  957. *
  958. * @return mixed true or false on sucess, a MDB2 error on failure
  959. * @access public
  960. */
  961. function valid()
  962. {
  963. $numrows = $this->numRows();
  964. if (PEAR::isError($numrows)) {
  965. return $numrows;
  966. }
  967. return $this->rownum < ($numrows - 1);
  968. }
  969. // }}}
  970. // {{{ numRows()
  971. /**
  972. * Returns the number of rows in a result object
  973. *
  974. * @return mixed MDB2 Error Object or the number of rows
  975. * @access public
  976. */
  977. function numRows()
  978. {
  979. $rows = @sqlite_num_rows($this->result);
  980. if (is_null($rows)) {
  981. if ($this->result === false) {
  982. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  983. 'resultset has already been freed', __FUNCTION__);
  984. } elseif (is_null($this->result)) {
  985. return 0;
  986. }
  987. return $this->db->raiseError(null, null, null,
  988. 'Could not get row count', __FUNCTION__);
  989. }
  990. return $rows;
  991. }
  992. }
  993. /**
  994. * MDB2 SQLite statement driver
  995. *
  996. * @package MDB2
  997. * @category Database
  998. * @author Lukas Smith <smith@pooteeweet.org>
  999. */
  1000. class MDB2_Statement_sqlite extends MDB2_Statement_Common
  1001. {
  1002. }
  1003. ?>