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. require_once 'common.php';
  30. /**
  31. * The methods PEAR DB uses to interact with PHP's sqlite extension
  32. * for interacting with SQLite databases
  33. *
  34. * These methods overload the ones declared in DB_common.
  35. *
  36. * NOTICE: This driver needs PHP's track_errors ini setting to be on.
  37. * It is automatically turned on when connecting to the database.
  38. * Make sure your scripts don't turn it off.
  39. *
  40. * @category Database
  41. * @package DB
  42. * @author Urs Gehrig <urs@circle.ch>
  43. * @author Mika Tuupola <tuupola@appelsiini.net>
  44. * @author Daniel Convissor <danielc@php.net>
  45. * @copyright 1997-2007 The PHP Group
  46. * @license http://www.php.net/license/3_0.txt PHP License 3.0 3.0
  47. * @version Release: 1.9.2
  48. * @link http://pear.php.net/package/DB
  49. */
  50. class DB_sqlite extends DB_common
  51. {
  52. // {{{ properties
  53. /**
  54. * The DB driver type (mysql, oci8, odbc, etc.)
  55. * @var string
  56. */
  57. public $phptype = 'sqlite';
  58. /**
  59. * The database syntax variant to be used (db2, access, etc.), if any
  60. * @var string
  61. */
  62. public $dbsyntax = 'sqlite';
  63. /**
  64. * The capabilities of this DB implementation
  65. *
  66. * The 'new_link' element contains the PHP version that first provided
  67. * new_link support for this DBMS. Contains false if it's unsupported.
  68. *
  69. * Meaning of the 'limit' element:
  70. * + 'emulate' = emulate with fetch row by number
  71. * + 'alter' = alter the query
  72. * + false = skip rows
  73. *
  74. * @var array
  75. */
  76. public $features = array(
  77. 'limit' => 'alter',
  78. 'new_link' => false,
  79. 'numrows' => true,
  80. 'pconnect' => true,
  81. 'prepare' => false,
  82. 'ssl' => false,
  83. 'transactions' => false,
  84. );
  85. /**
  86. * A mapping of native error codes to DB error codes
  87. *
  88. * {@internal Error codes according to sqlite_exec. See the online
  89. * manual at http://sqlite.org/c_interface.html for info.
  90. * This error handling based on sqlite_exec is not yet implemented.}}
  91. *
  92. * @var array
  93. */
  94. public $errorcode_map = array();
  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 ((new 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|object
  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. * Produces a DB_Error object regarding the current problem
  234. *
  235. * @param int $errno if the error is being manually raised pass a
  236. * DB_ERROR* constant here. If this isn't passed
  237. * the error information gathered from the DBMS.
  238. *
  239. * @return object the DB_Error object
  240. *
  241. * @see DB_common::raiseError(),
  242. * DB_sqlite::errorNative(), DB_sqlite::errorCode()
  243. */
  244. public function sqliteRaiseError($errno = null)
  245. {
  246. $native = $this->errorNative();
  247. if ($errno === null) {
  248. $errno = $this->errorCode($native);
  249. }
  250. $errorcode = @sqlite_last_error($this->connection);
  251. $userinfo = "$errorcode ** $this->last_query";
  252. return $this->raiseError($errno, null, null, $userinfo, $native);
  253. }
  254. // }}}
  255. // {{{ simpleQuery()
  256. /**
  257. * Gets the DBMS' native error message produced by the last query
  258. *
  259. * {@internal This is used to retrieve more meaningfull error messages
  260. * because sqlite_last_error() does not provide adequate info.}}
  261. *
  262. * @return string the DBMS' error message
  263. */
  264. public function errorNative()
  265. {
  266. return $this->_lasterror;
  267. }
  268. // }}}
  269. // {{{ nextResult()
  270. /**
  271. * Determines PEAR::DB error code from the database's text error message
  272. *
  273. * @param string $errormsg the error message returned from the database
  274. *
  275. * @return integer the DB error number
  276. */
  277. public function errorCode($errormsg)
  278. {
  279. static $error_regexps;
  280. // PHP 5.2+ prepends the function name to $php_errormsg, so we need
  281. // this hack to work around it, per bug #9599.
  282. $errormsg = preg_replace('/^sqlite[a-z_]+\(\): /', '', $errormsg);
  283. if (!isset($error_regexps)) {
  284. $error_regexps = array(
  285. '/^no such table:/' => DB_ERROR_NOSUCHTABLE,
  286. '/^no such index:/' => DB_ERROR_NOT_FOUND,
  287. '/^(table|index) .* already exists$/' => DB_ERROR_ALREADY_EXISTS,
  288. '/PRIMARY KEY must be unique/i' => DB_ERROR_CONSTRAINT,
  289. '/is not unique/' => DB_ERROR_CONSTRAINT,
  290. '/columns .* are not unique/i' => DB_ERROR_CONSTRAINT,
  291. '/uniqueness constraint failed/' => DB_ERROR_CONSTRAINT,
  292. '/may not be NULL/' => DB_ERROR_CONSTRAINT_NOT_NULL,
  293. '/^no such column:/' => DB_ERROR_NOSUCHFIELD,
  294. '/no column named/' => DB_ERROR_NOSUCHFIELD,
  295. '/column not present in both tables/i' => DB_ERROR_NOSUCHFIELD,
  296. '/^near ".*": syntax error$/' => DB_ERROR_SYNTAX,
  297. '/[0-9]+ values for [0-9]+ columns/i' => DB_ERROR_VALUE_COUNT_ON_ROW,
  298. );
  299. }
  300. foreach ($error_regexps as $regexp => $code) {
  301. if (preg_match($regexp, $errormsg)) {
  302. return $code;
  303. }
  304. }
  305. // Fall back to DB_ERROR if there was no mapping.
  306. return DB_ERROR;
  307. }
  308. // }}}
  309. // {{{ fetchInto()
  310. /**
  311. * Disconnects from the database server
  312. *
  313. * @return bool|void
  314. */
  315. public function disconnect()
  316. {
  317. $ret = @sqlite_close($this->connection);
  318. $this->connection = null;
  319. return $ret;
  320. }
  321. // }}}
  322. // {{{ freeResult()
  323. /**
  324. * Sends a query to the database server
  325. *
  326. * NOTICE: This method needs PHP's track_errors ini setting to be on.
  327. * It is automatically turned on when connecting to the database.
  328. * Make sure your scripts don't turn it off.
  329. *
  330. * @param string the SQL query string
  331. *
  332. * @return mixed + a PHP result resrouce for successful SELECT queries
  333. * + the DB_OK constant for other successful queries
  334. * + a DB_Error object on failure
  335. */
  336. public function simpleQuery($query)
  337. {
  338. $ismanip = $this->_checkManip($query);
  339. $this->last_query = $query;
  340. $query = $this->modifyQuery($query);
  341. $php_errormsg = '';
  342. $result = @sqlite_query($query, $this->connection);
  343. $this->_lasterror = $php_errormsg ? $php_errormsg : '';
  344. $this->result = $result;
  345. if (!$this->result) {
  346. return $this->sqliteRaiseError(null);
  347. }
  348. // sqlite_query() seems to allways return a resource
  349. // so cant use that. Using $ismanip instead
  350. if (!$ismanip) {
  351. $numRows = $this->numRows($result);
  352. if (is_object($numRows)) {
  353. // we've got PEAR_Error
  354. return $numRows;
  355. }
  356. return $result;
  357. }
  358. return DB_OK;
  359. }
  360. // }}}
  361. // {{{ numCols()
  362. /**
  363. * Changes a query string for various DBMS specific reasons
  364. *
  365. * This little hack lets you know how many rows were deleted
  366. * when running a "DELETE FROM table" query. Only implemented
  367. * if the DB_PORTABILITY_DELETE_COUNT portability option is on.
  368. *
  369. * @param string $query the query string to modify
  370. *
  371. * @return string the modified query string
  372. *
  373. * @access protected
  374. * @see DB_common::setOption()
  375. */
  376. public function modifyQuery($query)
  377. {
  378. if ($this->options['portability'] & DB_PORTABILITY_DELETE_COUNT) {
  379. if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
  380. $query = preg_replace(
  381. '/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
  382. 'DELETE FROM \1 WHERE 1=1',
  383. $query
  384. );
  385. }
  386. }
  387. return $query;
  388. }
  389. // }}}
  390. // {{{ numRows()
  391. /**
  392. * Gets the number of rows in a result set
  393. *
  394. * This method is not meant to be called directly. Use
  395. * DB_result::numRows() instead. It can't be declared "protected"
  396. * because DB_result is a separate object.
  397. *
  398. * @param resource $result PHP's query result resource
  399. *
  400. * @return int|object
  401. *
  402. * @see DB_result::numRows()
  403. */
  404. public function numRows($result)
  405. {
  406. $rows = @sqlite_num_rows($result);
  407. if ($rows === null) {
  408. return $this->sqliteRaiseError();
  409. }
  410. return $rows;
  411. }
  412. // }}}
  413. // {{{ affected()
  414. /**
  415. * Move the internal sqlite result pointer to the next available result
  416. *
  417. * @param resource $result the valid sqlite result resource
  418. *
  419. * @return bool true if a result is available otherwise return false
  420. */
  421. public function nextResult($result)
  422. {
  423. return false;
  424. }
  425. // }}}
  426. // {{{ dropSequence()
  427. /**
  428. * Places a row from the result set into the given array
  429. *
  430. * Formating of the array and the data therein are configurable.
  431. * See DB_result::fetchInto() for more information.
  432. *
  433. * This method is not meant to be called directly. Use
  434. * DB_result::fetchInto() instead. It can't be declared "protected"
  435. * because DB_result is a separate object.
  436. *
  437. * @param resource $result the query result resource
  438. * @param array $arr the referenced array to put the data in
  439. * @param int $fetchmode how the resulting array should be indexed
  440. * @param int $rownum the row number to fetch (0 = first row)
  441. *
  442. * @return mixed DB_OK on success, NULL when the end of a result set is
  443. * reached or on failure
  444. *
  445. * @see DB_result::fetchInto()
  446. */
  447. public function fetchInto($result, &$arr, $fetchmode, $rownum = null)
  448. {
  449. if ($rownum !== null) {
  450. if (!@sqlite_seek($this->result, $rownum)) {
  451. return null;
  452. }
  453. }
  454. if ($fetchmode & DB_FETCHMODE_ASSOC) {
  455. $arr = @sqlite_fetch_array($result, SQLITE_ASSOC);
  456. if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
  457. $arr = array_change_key_case($arr, CASE_LOWER);
  458. }
  459. /* Remove extraneous " characters from the fields in the result.
  460. * Fixes bug #11716. */
  461. if (is_array($arr) && count($arr) > 0) {
  462. $strippedArr = array();
  463. foreach ($arr as $field => $value) {
  464. $strippedArr[trim($field, '"')] = $value;
  465. }
  466. $arr = $strippedArr;
  467. }
  468. } else {
  469. $arr = @sqlite_fetch_array($result, SQLITE_NUM);
  470. }
  471. if (!$arr) {
  472. return null;
  473. }
  474. if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
  475. /*
  476. * Even though this DBMS already trims output, we do this because
  477. * a field might have intentional whitespace at the end that
  478. * gets removed by DB_PORTABILITY_RTRIM under another driver.
  479. */
  480. $this->_rtrimArrayValues($arr);
  481. }
  482. if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
  483. $this->_convertNullArrayValuesToEmpty($arr);
  484. }
  485. return DB_OK;
  486. }
  487. /**
  488. * Deletes the result set and frees the memory occupied by the result set
  489. *
  490. * This method is not meant to be called directly. Use
  491. * DB_result::free() instead. It can't be declared "protected"
  492. * because DB_result is a separate object.
  493. *
  494. * @param resource $result PHP's query result resource
  495. *
  496. * @return bool TRUE on success, FALSE if $result is invalid
  497. *
  498. * @see DB_result::free()
  499. */
  500. public function freeResult(&$result)
  501. {
  502. // XXX No native free?
  503. if (!is_resource($result)) {
  504. return false;
  505. }
  506. $result = null;
  507. return true;
  508. }
  509. // }}}
  510. // {{{ nextId()
  511. /**
  512. * Gets the number of columns in a result set
  513. *
  514. * This method is not meant to be called directly. Use
  515. * DB_result::numCols() instead. It can't be declared "protected"
  516. * because DB_result is a separate object.
  517. *
  518. * @param resource $result PHP's query result resource
  519. *
  520. * @return int|object
  521. *
  522. * @see DB_result::numCols()
  523. */
  524. public function numCols($result)
  525. {
  526. $cols = @sqlite_num_fields($result);
  527. if (!$cols) {
  528. return $this->sqliteRaiseError();
  529. }
  530. return $cols;
  531. }
  532. // }}}
  533. // {{{ getDbFileStats()
  534. /**
  535. * Determines the number of rows affected by a data maniuplation query
  536. *
  537. * 0 is returned for queries that don't manipulate data.
  538. *
  539. * @return int the number of rows. A DB_Error object on failure.
  540. */
  541. public function affectedRows()
  542. {
  543. return @sqlite_changes($this->connection);
  544. }
  545. // }}}
  546. // {{{ escapeSimple()
  547. /**
  548. * Deletes a sequence
  549. *
  550. * @param string $seq_name name of the sequence to be deleted
  551. *
  552. * @return int DB_OK on success. A DB_Error object on failure.
  553. *
  554. * @see DB_common::dropSequence(), DB_common::getSequenceName(),
  555. * DB_sqlite::nextID(), DB_sqlite::createSequence()
  556. */
  557. public function dropSequence($seq_name)
  558. {
  559. return $this->query('DROP TABLE ' . $this->getSequenceName($seq_name));
  560. }
  561. // }}}
  562. // {{{ modifyLimitQuery()
  563. /**
  564. * Returns the next free id in a sequence
  565. *
  566. * @param string $seq_name name of the sequence
  567. * @param boolean $ondemand when true, the seqence is automatically
  568. * created if it does not exist
  569. *
  570. * @return int|object
  571. * A DB_Error object on failure.
  572. *
  573. * @see DB_common::nextID(), DB_common::getSequenceName(),
  574. * DB_sqlite::createSequence(), DB_sqlite::dropSequence()
  575. */
  576. public function nextId($seq_name, $ondemand = true)
  577. {
  578. $seqname = $this->getSequenceName($seq_name);
  579. do {
  580. $repeat = 0;
  581. $this->pushErrorHandling(PEAR_ERROR_RETURN);
  582. $result = $this->query("INSERT INTO $seqname (id) VALUES (NULL)");
  583. $this->popErrorHandling();
  584. if ($result === DB_OK) {
  585. $id = @sqlite_last_insert_rowid($this->connection);
  586. if ($id != 0) {
  587. return $id;
  588. }
  589. } elseif ($ondemand && DB::isError($result) &&
  590. $result->getCode() == DB_ERROR_NOSUCHTABLE) {
  591. $result = $this->createSequence($seq_name);
  592. if (DB::isError($result)) {
  593. return $this->raiseError($result);
  594. } else {
  595. $repeat = 1;
  596. }
  597. }
  598. } while ($repeat);
  599. return $this->raiseError($result);
  600. }
  601. // }}}
  602. // {{{ modifyQuery()
  603. /**
  604. * Creates a new sequence
  605. *
  606. * @param string $seq_name name of the new sequence
  607. *
  608. * @return int DB_OK on success. A DB_Error object on failure.
  609. *
  610. * @see DB_common::createSequence(), DB_common::getSequenceName(),
  611. * DB_sqlite::nextID(), DB_sqlite::dropSequence()
  612. */
  613. public function createSequence($seq_name)
  614. {
  615. $seqname = $this->getSequenceName($seq_name);
  616. $query = 'CREATE TABLE ' . $seqname .
  617. ' (id INTEGER UNSIGNED PRIMARY KEY) ';
  618. $result = $this->query($query);
  619. if (DB::isError($result)) {
  620. return ($result);
  621. }
  622. $query = "CREATE TRIGGER ${seqname}_cleanup AFTER INSERT ON $seqname
  623. BEGIN
  624. DELETE FROM $seqname WHERE id<LAST_INSERT_ROWID();
  625. END ";
  626. $result = $this->query($query);
  627. //if (DB::isError($result)) {
  628. return ($result);
  629. //}
  630. }
  631. // }}}
  632. // {{{ sqliteRaiseError()
  633. /**
  634. * Get the file stats for the current database
  635. *
  636. * Possible arguments are dev, ino, mode, nlink, uid, gid, rdev, size,
  637. * atime, mtime, ctime, blksize, blocks or a numeric key between
  638. * 0 and 12.
  639. *
  640. * @param string $arg the array key for stats()
  641. *
  642. * @return mixed an array on an unspecified key, integer on a passed
  643. * arg and false at a stats error
  644. */
  645. public function getDbFileStats($arg = '')
  646. {
  647. $stats = stat($this->dsn['database']);
  648. if ($stats == false) {
  649. return false;
  650. }
  651. if (is_array($stats)) {
  652. if (is_numeric($arg)) {
  653. if (((int)$arg <= 12) & ((int)$arg >= 0)) {
  654. return false;
  655. }
  656. return $stats[$arg];
  657. }
  658. if (array_key_exists(trim($arg), $stats)) {
  659. return $stats[$arg];
  660. }
  661. }
  662. return $stats;
  663. }
  664. // }}}
  665. // {{{ errorNative()
  666. /**
  667. * Escapes a string according to the current DBMS's standards
  668. *
  669. * In SQLite, this makes things safe for inserts/updates, but may
  670. * cause problems when performing text comparisons against columns
  671. * containing binary data. See the
  672. * {@link http://php.net/sqlite_escape_string PHP manual} for more info.
  673. *
  674. * @param string $str the string to be escaped
  675. *
  676. * @return string the escaped string
  677. *
  678. * @since Method available since Release 1.6.1
  679. * @see DB_common::escapeSimple()
  680. */
  681. public function escapeSimple($str)
  682. {
  683. return @sqlite_escape_string($str);
  684. }
  685. // }}}
  686. // {{{ errorCode()
  687. /**
  688. * Adds LIMIT clauses to a query string according to current DBMS standards
  689. *
  690. * @param string $query the query to modify
  691. * @param int $from the row to start to fetching (0 = the first row)
  692. * @param int $count the numbers of rows to fetch
  693. * @param mixed $params array, string or numeric data to be used in
  694. * execution of the statement. Quantity of items
  695. * passed must match quantity of placeholders in
  696. * query: meaning 1 placeholder for non-array
  697. * parameters or 1 placeholder per array element.
  698. *
  699. * @return string the query string with LIMIT clauses added
  700. *
  701. * @access protected
  702. */
  703. public function modifyLimitQuery($query, $from, $count, $params = array())
  704. {
  705. return "$query LIMIT $count OFFSET $from";
  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|object
  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. */