PageRenderTime 52ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

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

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