sqlite.php 30 KB

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