sqlite.php 39 KB

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