sqlite.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. /**
  4. * The PEAR DB driver for PHP's sqlite extension
  5. * for interacting with SQLite databases
  6. *
  7. * PHP version 5
  8. *
  9. * LICENSE: This source file is subject to version 3.0 of the PHP license
  10. * that is available through the world-wide-web at the following URI:
  11. * http://www.php.net/license/3_0.txt. If you did not receive a copy of
  12. * the PHP License and are unable to obtain it through the web, please
  13. * send a note to license@php.net so we can mail you a copy immediately.
  14. *
  15. * @category Database
  16. * @package DB
  17. * @author Urs Gehrig <urs@circle.ch>
  18. * @author Mika Tuupola <tuupola@appelsiini.net>
  19. * @author Daniel Convissor <danielc@php.net>
  20. * @copyright 1997-2007 The PHP Group
  21. * @license http://www.php.net/license/3_0.txt PHP License 3.0 3.0
  22. * @version CVS: $Id$
  23. * @link http://pear.php.net/package/DB
  24. */
  25. /**
  26. * Obtain the DB_common class so it can be extended from
  27. */
  28. require_once 'DB/common.php';
  29. /**
  30. * The methods PEAR DB uses to interact with PHP's sqlite extension
  31. * for interacting with SQLite databases
  32. *
  33. * These methods overload the ones declared in DB_common.
  34. *
  35. * NOTICE: This driver needs PHP's track_errors ini setting to be on.
  36. * It is automatically turned on when connecting to the database.
  37. * Make sure your scripts don't turn it off.
  38. *
  39. * @category Database
  40. * @package DB
  41. * @author Urs Gehrig <urs@circle.ch>
  42. * @author Mika Tuupola <tuupola@appelsiini.net>
  43. * @author Daniel Convissor <danielc@php.net>
  44. * @copyright 1997-2007 The PHP Group
  45. * @license http://www.php.net/license/3_0.txt PHP License 3.0 3.0
  46. * @version Release: 1.8.2
  47. * @link http://pear.php.net/package/DB
  48. */
  49. class DB_sqlite extends DB_common
  50. {
  51. // {{{ properties
  52. /**
  53. * The DB driver type (mysql, oci8, odbc, etc.)
  54. * @var string
  55. */
  56. var $phptype = 'sqlite';
  57. /**
  58. * The database syntax variant to be used (db2, access, etc.), if any
  59. * @var string
  60. */
  61. var $dbsyntax = 'sqlite';
  62. /**
  63. * The capabilities of this DB implementation
  64. *
  65. * The 'new_link' element contains the PHP version that first provided
  66. * new_link support for this DBMS. Contains false if it's unsupported.
  67. *
  68. * Meaning of the 'limit' element:
  69. * + 'emulate' = emulate with fetch row by number
  70. * + 'alter' = alter the query
  71. * + false = skip rows
  72. *
  73. * @var array
  74. */
  75. var $features = array(
  76. 'limit' => 'alter',
  77. 'new_link' => false,
  78. 'numrows' => true,
  79. 'pconnect' => true,
  80. 'prepare' => false,
  81. 'ssl' => false,
  82. 'transactions' => false,
  83. );
  84. /**
  85. * A mapping of native error codes to DB error codes
  86. *
  87. * {@internal Error codes according to sqlite_exec. See the online
  88. * manual at http://sqlite.org/c_interface.html for info.
  89. * This error handling based on sqlite_exec is not yet implemented.}}
  90. *
  91. * @var array
  92. */
  93. var $errorcode_map = array(
  94. );
  95. /**
  96. * The raw database connection created by PHP
  97. * @var resource
  98. */
  99. var $connection;
  100. /**
  101. * The DSN information for connecting to a database
  102. * @var array
  103. */
  104. var $dsn = array();
  105. /**
  106. * SQLite data types
  107. *
  108. * @link http://www.sqlite.org/datatypes.html
  109. *
  110. * @var array
  111. */
  112. var $keywords = array (
  113. 'BLOB' => '',
  114. 'BOOLEAN' => '',
  115. 'CHARACTER' => '',
  116. 'CLOB' => '',
  117. 'FLOAT' => '',
  118. 'INTEGER' => '',
  119. 'KEY' => '',
  120. 'NATIONAL' => '',
  121. 'NUMERIC' => '',
  122. 'NVARCHAR' => '',
  123. 'PRIMARY' => '',
  124. 'TEXT' => '',
  125. 'TIMESTAMP' => '',
  126. 'UNIQUE' => '',
  127. 'VARCHAR' => '',
  128. 'VARYING' => '',
  129. );
  130. /**
  131. * The most recent error message from $php_errormsg
  132. * @var string
  133. * @access private
  134. */
  135. var $_lasterror = '';
  136. // }}}
  137. // {{{ constructor
  138. /**
  139. * This constructor calls <kbd>$this->DB_common()</kbd>
  140. *
  141. * @return void
  142. */
  143. function DB_sqlite()
  144. {
  145. $this->DB_common();
  146. }
  147. // }}}
  148. // {{{ connect()
  149. /**
  150. * Connect to the database server, log in and open the database
  151. *
  152. * Don't call this method directly. Use DB::connect() instead.
  153. *
  154. * PEAR DB's sqlite driver supports the following extra DSN options:
  155. * + mode The permissions for the database file, in four digit
  156. * chmod octal format (eg "0600").
  157. *
  158. * Example of connecting to a database in read-only mode:
  159. * <code>
  160. * require_once 'DB.php';
  161. *
  162. * $dsn = 'sqlite:///path/and/name/of/db/file?mode=0400';
  163. * $options = array(
  164. * 'portability' => DB_PORTABILITY_ALL,
  165. * );
  166. *
  167. * $db = DB::connect($dsn, $options);
  168. * if (PEAR::isError($db)) {
  169. * die($db->getMessage());
  170. * }
  171. * </code>
  172. *
  173. * @param array $dsn the data source name
  174. * @param bool $persistent should the connection be persistent?
  175. *
  176. * @return int DB_OK on success. A DB_Error object on failure.
  177. */
  178. function connect($dsn, $persistent = false)
  179. {
  180. if (!PEAR::loadExtension('sqlite')) {
  181. return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
  182. }
  183. $this->dsn = $dsn;
  184. if ($dsn['dbsyntax']) {
  185. $this->dbsyntax = $dsn['dbsyntax'];
  186. }
  187. if (!$dsn['database']) {
  188. return $this->sqliteRaiseError(DB_ERROR_ACCESS_VIOLATION);
  189. }
  190. if ($dsn['database'] !== ':memory:') {
  191. if (!file_exists($dsn['database'])) {
  192. if (!touch($dsn['database'])) {
  193. return $this->sqliteRaiseError(DB_ERROR_NOT_FOUND);
  194. }
  195. if (!isset($dsn['mode']) ||
  196. !is_numeric($dsn['mode']))
  197. {
  198. $mode = 0644;
  199. } else {
  200. $mode = octdec($dsn['mode']);
  201. }
  202. if (!chmod($dsn['database'], $mode)) {
  203. return $this->sqliteRaiseError(DB_ERROR_NOT_FOUND);
  204. }
  205. if (!file_exists($dsn['database'])) {
  206. return $this->sqliteRaiseError(DB_ERROR_NOT_FOUND);
  207. }
  208. }
  209. if (!is_file($dsn['database'])) {
  210. return $this->sqliteRaiseError(DB_ERROR_INVALID);
  211. }
  212. if (!is_readable($dsn['database'])) {
  213. return $this->sqliteRaiseError(DB_ERROR_ACCESS_VIOLATION);
  214. }
  215. }
  216. $connect_function = $persistent ? 'sqlite_popen' : 'sqlite_open';
  217. // track_errors must remain on for simpleQuery()
  218. @ini_set('track_errors', 1);
  219. $php_errormsg = '';
  220. if (!$this->connection = @$connect_function($dsn['database'])) {
  221. return $this->raiseError(DB_ERROR_NODBSELECTED,
  222. null, null, null,
  223. $php_errormsg);
  224. }
  225. return DB_OK;
  226. }
  227. // }}}
  228. // {{{ disconnect()
  229. /**
  230. * Disconnects from the database server
  231. *
  232. * @return bool TRUE on success, FALSE on failure
  233. */
  234. function disconnect()
  235. {
  236. $ret = @sqlite_close($this->connection);
  237. $this->connection = null;
  238. return $ret;
  239. }
  240. // }}}
  241. // {{{ simpleQuery()
  242. /**
  243. * Sends a query to the database server
  244. *
  245. * NOTICE: This method needs PHP's track_errors ini setting to be on.
  246. * It is automatically turned on when connecting to the database.
  247. * Make sure your scripts don't turn it off.
  248. *
  249. * @param string the SQL query string
  250. *
  251. * @return mixed + a PHP result resrouce for successful SELECT queries
  252. * + the DB_OK constant for other successful queries
  253. * + a DB_Error object on failure
  254. */
  255. function simpleQuery($query)
  256. {
  257. $ismanip = $this->_checkManip($query);
  258. $this->last_query = $query;
  259. $query = $this->modifyQuery($query);
  260. $php_errormsg = '';
  261. $result = @sqlite_query($query, $this->connection);
  262. $this->_lasterror = $php_errormsg ? $php_errormsg : '';
  263. $this->result = $result;
  264. if (!$this->result) {
  265. return $this->sqliteRaiseError(null);
  266. }
  267. // sqlite_query() seems to allways return a resource
  268. // so cant use that. Using $ismanip instead
  269. if (!$ismanip) {
  270. $numRows = $this->numRows($result);
  271. if (is_object($numRows)) {
  272. // we've got PEAR_Error
  273. return $numRows;
  274. }
  275. return $result;
  276. }
  277. return DB_OK;
  278. }
  279. // }}}
  280. // {{{ nextResult()
  281. /**
  282. * Move the internal sqlite result pointer to the next available result
  283. *
  284. * @param resource $result the valid sqlite result resource
  285. *
  286. * @return bool true if a result is available otherwise return false
  287. */
  288. function nextResult($result)
  289. {
  290. return false;
  291. }
  292. // }}}
  293. // {{{ fetchInto()
  294. /**
  295. * Places a row from the result set into the given array
  296. *
  297. * Formating of the array and the data therein are configurable.
  298. * See DB_result::fetchInto() for more information.
  299. *
  300. * This method is not meant to be called directly. Use
  301. * DB_result::fetchInto() instead. It can't be declared "protected"
  302. * because DB_result is a separate object.
  303. *
  304. * @param resource $result the query result resource
  305. * @param array $arr the referenced array to put the data in
  306. * @param int $fetchmode how the resulting array should be indexed
  307. * @param int $rownum the row number to fetch (0 = first row)
  308. *
  309. * @return mixed DB_OK on success, NULL when the end of a result set is
  310. * reached or on failure
  311. *
  312. * @see DB_result::fetchInto()
  313. */
  314. function fetchInto($result, &$arr, $fetchmode, $rownum = null)
  315. {
  316. if ($rownum !== null) {
  317. if (!@sqlite_seek($this->result, $rownum)) {
  318. return null;
  319. }
  320. }
  321. if ($fetchmode & DB_FETCHMODE_ASSOC) {
  322. $arr = @sqlite_fetch_array($result, SQLITE_ASSOC);
  323. if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
  324. $arr = array_change_key_case($arr, CASE_LOWER);
  325. }
  326. /* Remove extraneous " characters from the fields in the result.
  327. * Fixes bug #11716. */
  328. if (is_array($arr) && count($arr) > 0) {
  329. $strippedArr = array();
  330. foreach ($arr as $field => $value) {
  331. $strippedArr[trim($field, '"')] = $value;
  332. }
  333. $arr = $strippedArr;
  334. }
  335. } else {
  336. $arr = @sqlite_fetch_array($result, SQLITE_NUM);
  337. }
  338. if (!$arr) {
  339. return null;
  340. }
  341. if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
  342. /*
  343. * Even though this DBMS already trims output, we do this because
  344. * a field might have intentional whitespace at the end that
  345. * gets removed by DB_PORTABILITY_RTRIM under another driver.
  346. */
  347. $this->_rtrimArrayValues($arr);
  348. }
  349. if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
  350. $this->_convertNullArrayValuesToEmpty($arr);
  351. }
  352. return DB_OK;
  353. }
  354. // }}}
  355. // {{{ freeResult()
  356. /**
  357. * Deletes the result set and frees the memory occupied by the result set
  358. *
  359. * This method is not meant to be called directly. Use
  360. * DB_result::free() instead. It can't be declared "protected"
  361. * because DB_result is a separate object.
  362. *
  363. * @param resource $result PHP's query result resource
  364. *
  365. * @return bool TRUE on success, FALSE if $result is invalid
  366. *
  367. * @see DB_result::free()
  368. */
  369. function freeResult(&$result)
  370. {
  371. // XXX No native free?
  372. if (!is_resource($result)) {
  373. return false;
  374. }
  375. $result = null;
  376. return true;
  377. }
  378. // }}}
  379. // {{{ numCols()
  380. /**
  381. * Gets the number of columns in a result set
  382. *
  383. * This method is not meant to be called directly. Use
  384. * DB_result::numCols() instead. It can't be declared "protected"
  385. * because DB_result is a separate object.
  386. *
  387. * @param resource $result PHP's query result resource
  388. *
  389. * @return int the number of columns. A DB_Error object on failure.
  390. *
  391. * @see DB_result::numCols()
  392. */
  393. function numCols($result)
  394. {
  395. $cols = @sqlite_num_fields($result);
  396. if (!$cols) {
  397. return $this->sqliteRaiseError();
  398. }
  399. return $cols;
  400. }
  401. // }}}
  402. // {{{ numRows()
  403. /**
  404. * Gets the number of rows in a result set
  405. *
  406. * This method is not meant to be called directly. Use
  407. * DB_result::numRows() instead. It can't be declared "protected"
  408. * because DB_result is a separate object.
  409. *
  410. * @param resource $result PHP's query result resource
  411. *
  412. * @return int the number of rows. A DB_Error object on failure.
  413. *
  414. * @see DB_result::numRows()
  415. */
  416. function numRows($result)
  417. {
  418. $rows = @sqlite_num_rows($result);
  419. if ($rows === null) {
  420. return $this->sqliteRaiseError();
  421. }
  422. return $rows;
  423. }
  424. // }}}
  425. // {{{ affected()
  426. /**
  427. * Determines the number of rows affected by a data maniuplation query
  428. *
  429. * 0 is returned for queries that don't manipulate data.
  430. *
  431. * @return int the number of rows. A DB_Error object on failure.
  432. */
  433. function affectedRows()
  434. {
  435. return @sqlite_changes($this->connection);
  436. }
  437. // }}}
  438. // {{{ dropSequence()
  439. /**
  440. * Deletes a sequence
  441. *
  442. * @param string $seq_name name of the sequence to be deleted
  443. *
  444. * @return int DB_OK on success. A DB_Error object on failure.
  445. *
  446. * @see DB_common::dropSequence(), DB_common::getSequenceName(),
  447. * DB_sqlite::nextID(), DB_sqlite::createSequence()
  448. */
  449. function dropSequence($seq_name)
  450. {
  451. return $this->query('DROP TABLE ' . $this->getSequenceName($seq_name));
  452. }
  453. /**
  454. * Creates a new sequence
  455. *
  456. * @param string $seq_name name of the new sequence
  457. *
  458. * @return int DB_OK on success. A DB_Error object on failure.
  459. *
  460. * @see DB_common::createSequence(), DB_common::getSequenceName(),
  461. * DB_sqlite::nextID(), DB_sqlite::dropSequence()
  462. */
  463. function createSequence($seq_name)
  464. {
  465. $seqname = $this->getSequenceName($seq_name);
  466. $query = 'CREATE TABLE ' . $seqname .
  467. ' (id INTEGER UNSIGNED PRIMARY KEY) ';
  468. $result = $this->query($query);
  469. if (DB::isError($result)) {
  470. return($result);
  471. }
  472. $query = "CREATE TRIGGER ${seqname}_cleanup AFTER INSERT ON $seqname
  473. BEGIN
  474. DELETE FROM $seqname WHERE id<LAST_INSERT_ROWID();
  475. END ";
  476. $result = $this->query($query);
  477. if (DB::isError($result)) {
  478. return($result);
  479. }
  480. }
  481. // }}}
  482. // {{{ nextId()
  483. /**
  484. * Returns the next free id in a sequence
  485. *
  486. * @param string $seq_name name of the sequence
  487. * @param boolean $ondemand when true, the seqence is automatically
  488. * created if it does not exist
  489. *
  490. * @return int the next id number in the sequence.
  491. * A DB_Error object on failure.
  492. *
  493. * @see DB_common::nextID(), DB_common::getSequenceName(),
  494. * DB_sqlite::createSequence(), DB_sqlite::dropSequence()
  495. */
  496. function nextId($seq_name, $ondemand = true)
  497. {
  498. $seqname = $this->getSequenceName($seq_name);
  499. do {
  500. $repeat = 0;
  501. $this->pushErrorHandling(PEAR_ERROR_RETURN);
  502. $result = $this->query("INSERT INTO $seqname (id) VALUES (NULL)");
  503. $this->popErrorHandling();
  504. if ($result === DB_OK) {
  505. $id = @sqlite_last_insert_rowid($this->connection);
  506. if ($id != 0) {
  507. return $id;
  508. }
  509. } elseif ($ondemand && DB::isError($result) &&
  510. $result->getCode() == DB_ERROR_NOSUCHTABLE)
  511. {
  512. $result = $this->createSequence($seq_name);
  513. if (DB::isError($result)) {
  514. return $this->raiseError($result);
  515. } else {
  516. $repeat = 1;
  517. }
  518. }
  519. } while ($repeat);
  520. return $this->raiseError($result);
  521. }
  522. // }}}
  523. // {{{ getDbFileStats()
  524. /**
  525. * Get the file stats for the current database
  526. *
  527. * Possible arguments are dev, ino, mode, nlink, uid, gid, rdev, size,
  528. * atime, mtime, ctime, blksize, blocks or a numeric key between
  529. * 0 and 12.
  530. *
  531. * @param string $arg the array key for stats()
  532. *
  533. * @return mixed an array on an unspecified key, integer on a passed
  534. * arg and false at a stats error
  535. */
  536. function getDbFileStats($arg = '')
  537. {
  538. $stats = stat($this->dsn['database']);
  539. if ($stats == false) {
  540. return false;
  541. }
  542. if (is_array($stats)) {
  543. if (is_numeric($arg)) {
  544. if (((int)$arg <= 12) & ((int)$arg >= 0)) {
  545. return false;
  546. }
  547. return $stats[$arg ];
  548. }
  549. if (array_key_exists(trim($arg), $stats)) {
  550. return $stats[$arg ];
  551. }
  552. }
  553. return $stats;
  554. }
  555. // }}}
  556. // {{{ escapeSimple()
  557. /**
  558. * Escapes a string according to the current DBMS's standards
  559. *
  560. * In SQLite, this makes things safe for inserts/updates, but may
  561. * cause problems when performing text comparisons against columns
  562. * containing binary data. See the
  563. * {@link http://php.net/sqlite_escape_string PHP manual} for more info.
  564. *
  565. * @param string $str the string to be escaped
  566. *
  567. * @return string the escaped string
  568. *
  569. * @since Method available since Release 1.6.1
  570. * @see DB_common::escapeSimple()
  571. */
  572. function escapeSimple($str)
  573. {
  574. return @sqlite_escape_string($str);
  575. }
  576. // }}}
  577. // {{{ modifyLimitQuery()
  578. /**
  579. * Adds LIMIT clauses to a query string according to current DBMS standards
  580. *
  581. * @param string $query the query to modify
  582. * @param int $from the row to start to fetching (0 = the first row)
  583. * @param int $count the numbers of rows to fetch
  584. * @param mixed $params array, string or numeric data to be used in
  585. * execution of the statement. Quantity of items
  586. * passed must match quantity of placeholders in
  587. * query: meaning 1 placeholder for non-array
  588. * parameters or 1 placeholder per array element.
  589. *
  590. * @return string the query string with LIMIT clauses added
  591. *
  592. * @access protected
  593. */
  594. function modifyLimitQuery($query, $from, $count, $params = array())
  595. {
  596. return "$query LIMIT $count OFFSET $from";
  597. }
  598. // }}}
  599. // {{{ modifyQuery()
  600. /**
  601. * Changes a query string for various DBMS specific reasons
  602. *
  603. * This little hack lets you know how many rows were deleted
  604. * when running a "DELETE FROM table" query. Only implemented
  605. * if the DB_PORTABILITY_DELETE_COUNT portability option is on.
  606. *
  607. * @param string $query the query string to modify
  608. *
  609. * @return string the modified query string
  610. *
  611. * @access protected
  612. * @see DB_common::setOption()
  613. */
  614. function modifyQuery($query)
  615. {
  616. if ($this->options['portability'] & DB_PORTABILITY_DELETE_COUNT) {
  617. if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
  618. $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
  619. 'DELETE FROM \1 WHERE 1=1', $query);
  620. }
  621. }
  622. return $query;
  623. }
  624. // }}}
  625. // {{{ sqliteRaiseError()
  626. /**
  627. * Produces a DB_Error object regarding the current problem
  628. *
  629. * @param int $errno if the error is being manually raised pass a
  630. * DB_ERROR* constant here. If this isn't passed
  631. * the error information gathered from the DBMS.
  632. *
  633. * @return object the DB_Error object
  634. *
  635. * @see DB_common::raiseError(),
  636. * DB_sqlite::errorNative(), DB_sqlite::errorCode()
  637. */
  638. function sqliteRaiseError($errno = null)
  639. {
  640. $native = $this->errorNative();
  641. if ($errno === null) {
  642. $errno = $this->errorCode($native);
  643. }
  644. $errorcode = @sqlite_last_error($this->connection);
  645. $userinfo = "$errorcode ** $this->last_query";
  646. return $this->raiseError($errno, null, null, $userinfo, $native);
  647. }
  648. // }}}
  649. // {{{ errorNative()
  650. /**
  651. * Gets the DBMS' native error message produced by the last query
  652. *
  653. * {@internal This is used to retrieve more meaningfull error messages
  654. * because sqlite_last_error() does not provide adequate info.}}
  655. *
  656. * @return string the DBMS' error message
  657. */
  658. function errorNative()
  659. {
  660. return $this->_lasterror;
  661. }
  662. // }}}
  663. // {{{ errorCode()
  664. /**
  665. * Determines PEAR::DB error code from the database's text error message
  666. *
  667. * @param string $errormsg the error message returned from the database
  668. *
  669. * @return integer the DB error number
  670. */
  671. function errorCode($errormsg)
  672. {
  673. static $error_regexps;
  674. // PHP 5.2+ prepends the function name to $php_errormsg, so we need
  675. // this hack to work around it, per bug #9599.
  676. $errormsg = preg_replace('/^sqlite[a-z_]+\(\): /', '', $errormsg);
  677. if (!isset($error_regexps)) {
  678. $error_regexps = array(
  679. '/^no such table:/' => DB_ERROR_NOSUCHTABLE,
  680. '/^no such index:/' => DB_ERROR_NOT_FOUND,
  681. '/^(table|index) .* already exists$/' => DB_ERROR_ALREADY_EXISTS,
  682. '/PRIMARY KEY must be unique/i' => DB_ERROR_CONSTRAINT,
  683. '/is not unique/' => DB_ERROR_CONSTRAINT,
  684. '/columns .* are not unique/i' => DB_ERROR_CONSTRAINT,
  685. '/uniqueness constraint failed/' => DB_ERROR_CONSTRAINT,
  686. '/may not be NULL/' => DB_ERROR_CONSTRAINT_NOT_NULL,
  687. '/^no such column:/' => DB_ERROR_NOSUCHFIELD,
  688. '/no column named/' => DB_ERROR_NOSUCHFIELD,
  689. '/column not present in both tables/i' => DB_ERROR_NOSUCHFIELD,
  690. '/^near ".*": syntax error$/' => DB_ERROR_SYNTAX,
  691. '/[0-9]+ values for [0-9]+ columns/i' => DB_ERROR_VALUE_COUNT_ON_ROW,
  692. );
  693. }
  694. foreach ($error_regexps as $regexp => $code) {
  695. if (preg_match($regexp, $errormsg)) {
  696. return $code;
  697. }
  698. }
  699. // Fall back to DB_ERROR if there was no mapping.
  700. return DB_ERROR;
  701. }
  702. // }}}
  703. // {{{ tableInfo()
  704. /**
  705. * Returns information about a table
  706. *
  707. * @param string $result a string containing the name of a table
  708. * @param int $mode a valid tableInfo mode
  709. *
  710. * @return array an associative array with the information requested.
  711. * A DB_Error object on failure.
  712. *
  713. * @see DB_common::tableInfo()
  714. * @since Method available since Release 1.7.0
  715. */
  716. function tableInfo($result, $mode = null)
  717. {
  718. if (is_string($result)) {
  719. /*
  720. * Probably received a table name.
  721. * Create a result resource identifier.
  722. */
  723. $id = @sqlite_array_query($this->connection,
  724. "PRAGMA table_info('$result');",
  725. SQLITE_ASSOC);
  726. $got_string = true;
  727. } else {
  728. $this->last_query = '';
  729. return $this->raiseError(DB_ERROR_NOT_CAPABLE, null, null, null,
  730. 'This DBMS can not obtain tableInfo' .
  731. ' from result sets');
  732. }
  733. if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
  734. $case_func = 'strtolower';
  735. } else {
  736. $case_func = 'strval';
  737. }
  738. $count = count($id);
  739. $res = array();
  740. if ($mode) {
  741. $res['num_fields'] = $count;
  742. }
  743. for ($i = 0; $i < $count; $i++) {
  744. if (strpos($id[$i]['type'], '(') !== false) {
  745. $bits = explode('(', $id[$i]['type']);
  746. $type = $bits[0];
  747. $len = rtrim($bits[1],')');
  748. } else {
  749. $type = $id[$i]['type'];
  750. $len = 0;
  751. }
  752. $flags = '';
  753. if ($id[$i]['pk']) {
  754. $flags .= 'primary_key ';
  755. if (strtoupper($type) == 'INTEGER') {
  756. $flags .= 'auto_increment ';
  757. }
  758. }
  759. if ($id[$i]['notnull']) {
  760. $flags .= 'not_null ';
  761. }
  762. if ($id[$i]['dflt_value'] !== null) {
  763. $flags .= 'default_' . rawurlencode($id[$i]['dflt_value']);
  764. }
  765. $flags = trim($flags);
  766. $res[$i] = array(
  767. 'table' => $case_func($result),
  768. 'name' => $case_func($id[$i]['name']),
  769. 'type' => $type,
  770. 'len' => $len,
  771. 'flags' => $flags,
  772. );
  773. if ($mode & DB_TABLEINFO_ORDER) {
  774. $res['order'][$res[$i]['name']] = $i;
  775. }
  776. if ($mode & DB_TABLEINFO_ORDERTABLE) {
  777. $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
  778. }
  779. }
  780. return $res;
  781. }
  782. // }}}
  783. // {{{ getSpecialQuery()
  784. /**
  785. * Obtains the query string needed for listing a given type of objects
  786. *
  787. * @param string $type the kind of objects you want to retrieve
  788. * @param array $args SQLITE DRIVER ONLY: a private array of arguments
  789. * used by the getSpecialQuery(). Do not use
  790. * this directly.
  791. *
  792. * @return string the SQL query string or null if the driver doesn't
  793. * support the object type requested
  794. *
  795. * @access protected
  796. * @see DB_common::getListOf()
  797. */
  798. function getSpecialQuery($type, $args = array())
  799. {
  800. if (!is_array($args)) {
  801. return $this->raiseError('no key specified', null, null, null,
  802. 'Argument has to be an array.');
  803. }
  804. switch ($type) {
  805. case 'master':
  806. return 'SELECT * FROM sqlite_master;';
  807. case 'tables':
  808. return "SELECT name FROM sqlite_master WHERE type='table' "
  809. . 'UNION ALL SELECT name FROM sqlite_temp_master '
  810. . "WHERE type='table' ORDER BY name;";
  811. case 'schema':
  812. return 'SELECT sql FROM (SELECT * FROM sqlite_master '
  813. . 'UNION ALL SELECT * FROM sqlite_temp_master) '
  814. . "WHERE type!='meta' "
  815. . 'ORDER BY tbl_name, type DESC, name;';
  816. case 'schemax':
  817. case 'schema_x':
  818. /*
  819. * Use like:
  820. * $res = $db->query($db->getSpecialQuery('schema_x',
  821. * array('table' => 'table3')));
  822. */
  823. return 'SELECT sql FROM (SELECT * FROM sqlite_master '
  824. . 'UNION ALL SELECT * FROM sqlite_temp_master) '
  825. . "WHERE tbl_name LIKE '{$args['table']}' "
  826. . "AND type!='meta' "
  827. . 'ORDER BY type DESC, name;';
  828. case 'alter':
  829. /*
  830. * SQLite does not support ALTER TABLE; this is a helper query
  831. * to handle this. 'table' represents the table name, 'rows'
  832. * the news rows to create, 'save' the row(s) to keep _with_
  833. * the data.
  834. *
  835. * Use like:
  836. * $args = array(
  837. * 'table' => $table,
  838. * 'rows' => "id INTEGER PRIMARY KEY, firstname TEXT, surname TEXT, datetime TEXT",
  839. * 'save' => "NULL, titel, content, datetime"
  840. * );
  841. * $res = $db->query( $db->getSpecialQuery('alter', $args));
  842. */
  843. $rows = strtr($args['rows'], $this->keywords);
  844. $q = array(
  845. 'BEGIN TRANSACTION',
  846. "CREATE TEMPORARY TABLE {$args['table']}_backup ({$args['rows']})",
  847. "INSERT INTO {$args['table']}_backup SELECT {$args['save']} FROM {$args['table']}",
  848. "DROP TABLE {$args['table']}",
  849. "CREATE TABLE {$args['table']} ({$args['rows']})",
  850. "INSERT INTO {$args['table']} SELECT {$rows} FROM {$args['table']}_backup",
  851. "DROP TABLE {$args['table']}_backup",
  852. 'COMMIT',
  853. );
  854. /*
  855. * This is a dirty hack, since the above query will not get
  856. * executed with a single query call so here the query method
  857. * will be called directly and return a select instead.
  858. */
  859. foreach ($q as $query) {
  860. $this->query($query);
  861. }
  862. return "SELECT * FROM {$args['table']};";
  863. default:
  864. return null;
  865. }
  866. }
  867. // }}}
  868. }
  869. /*
  870. * Local variables:
  871. * tab-width: 4
  872. * c-basic-offset: 4
  873. * End:
  874. */
  875. ?>