PageRenderTime 46ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/includes/pear/MDB2/Driver/pdoSqlite.php

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