3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
6 * The PEAR DB driver for PHP's sqlite extension
7 * for interacting with SQLite databases
11 * LICENSE: This source file is subject to version 3.0 of the PHP license
12 * that is available through the world-wide-web at the following URI:
13 * http://www.php.net/license/3_0.txt. If you did not receive a copy of
14 * the PHP License and are unable to obtain it through the web, please
15 * send a note to license@php.net so we can mail you a copy immediately.
19 * @author Urs Gehrig <urs@circle.ch>
20 * @author Mika Tuupola <tuupola@appelsiini.net>
21 * @author Daniel Convissor <danielc@php.net>
22 * @copyright 1997-2005 The PHP Group
23 * @license http://www.php.net/license/3_0.txt PHP License 3.0 3.0
24 * @version CVS: $Id: sqlite.php 12 2005-10-02 11:36:35Z sparc $
25 * @link http://pear.php.net/package/DB
29 * Obtain the DB_common class so it can be extended from
31 require_once 'DB/common.php';
34 * The methods PEAR DB uses to interact with PHP's sqlite extension
35 * for interacting with SQLite databases
37 * These methods overload the ones declared in DB_common.
39 * NOTICE: This driver needs PHP's track_errors ini setting to be on.
40 * It is automatically turned on when connecting to the database.
41 * Make sure your scripts don't turn it off.
45 * @author Urs Gehrig <urs@circle.ch>
46 * @author Mika Tuupola <tuupola@appelsiini.net>
47 * @author Daniel Convissor <danielc@php.net>
48 * @copyright 1997-2005 The PHP Group
49 * @license http://www.php.net/license/3_0.txt PHP License 3.0 3.0
50 * @version Release: @package_version@
51 * @link http://pear.php.net/package/DB
53 class DB_sqlite extends DB_common
58 * The DB driver type (mysql, oci8, odbc, etc.)
61 var $phptype = 'sqlite';
64 * The database syntax variant to be used (db2, access, etc.), if any
67 var $dbsyntax = 'sqlite';
70 * The capabilities of this DB implementation
72 * The 'new_link' element contains the PHP version that first provided
73 * new_link support for this DBMS. Contains false if it's unsupported.
75 * Meaning of the 'limit' element:
76 * + 'emulate' = emulate with fetch row by number
77 * + 'alter' = alter the query
82 var $features = array(
89 'transactions' => false,
93 * A mapping of native error codes to DB error codes
95 * {@internal Error codes according to sqlite_exec. See the online
96 * manual at http://sqlite.org/c_interface.html for info.
97 * This error handling based on sqlite_exec is not yet implemented.}}
101 var $errorcode_map = array(
105 * The raw database connection created by PHP
111 * The DSN information for connecting to a database
120 * @link http://www.sqlite.org/datatypes.html
124 var $keywords = array (
144 * The most recent error message from $php_errormsg
148 var $_lasterror = '';
155 * This constructor calls <kbd>$this->DB_common()</kbd>
168 * Connect to the database server, log in and open the database
170 * Don't call this method directly. Use DB::connect() instead.
172 * PEAR DB's sqlite driver supports the following extra DSN options:
173 * + mode The permissions for the database file, in four digit
174 * chmod octal format (eg "0600").
176 * Example of connecting to a database in read-only mode:
178 * require_once 'DB.php';
180 * $dsn = 'sqlite:///path/and/name/of/db/file?mode=0400';
182 * 'portability' => DB_PORTABILITY_ALL,
185 * $db =& DB::connect($dsn, $options);
186 * if (PEAR::isError($db)) {
187 * die($db->getMessage());
191 * @param array $dsn the data source name
192 * @param bool $persistent should the connection be persistent?
194 * @return int DB_OK on success. A DB_Error object on failure.
196 function connect($dsn, $persistent = false)
198 if (!PEAR::loadExtension('sqlite')) {
199 return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
203 if ($dsn['dbsyntax']) {
204 $this->dbsyntax = $dsn['dbsyntax'];
207 if ($dsn['database']) {
208 if (!file_exists($dsn['database'])) {
209 if (!touch($dsn['database'])) {
210 return $this->sqliteRaiseError(DB_ERROR_NOT_FOUND);
212 if (!isset($dsn['mode']) ||
213 !is_numeric($dsn['mode']))
217 $mode = octdec($dsn['mode']);
219 if (!chmod($dsn['database'], $mode)) {
220 return $this->sqliteRaiseError(DB_ERROR_NOT_FOUND);
222 if (!file_exists($dsn['database'])) {
223 return $this->sqliteRaiseError(DB_ERROR_NOT_FOUND);
226 if (!is_file($dsn['database'])) {
227 return $this->sqliteRaiseError(DB_ERROR_INVALID);
229 if (!is_readable($dsn['database'])) {
230 return $this->sqliteRaiseError(DB_ERROR_ACCESS_VIOLATION);
233 return $this->sqliteRaiseError(DB_ERROR_ACCESS_VIOLATION);
236 $connect_function = $persistent ? 'sqlite_popen' : 'sqlite_open';
238 // track_errors must remain on for simpleQuery()
239 ini_set('track_errors', 1);
242 if (!$this->connection = @$connect_function($dsn['database'])) {
243 return $this->raiseError(DB_ERROR_NODBSELECTED,
254 * Disconnects from the database server
256 * @return bool TRUE on success, FALSE on failure
258 function disconnect()
260 $ret = @sqlite_close($this->connection);
261 $this->connection = null;
269 * Sends a query to the database server
271 * NOTICE: This method needs PHP's track_errors ini setting to be on.
272 * It is automatically turned on when connecting to the database.
273 * Make sure your scripts don't turn it off.
275 * @param string the SQL query string
277 * @return mixed + a PHP result resrouce for successful SELECT queries
278 * + the DB_OK constant for other successful queries
279 * + a DB_Error object on failure
281 function simpleQuery($query)
283 $ismanip = DB::isManip($query);
284 $this->last_query = $query;
285 $query = $this->modifyQuery($query);
289 $result = @sqlite_query($query, $this->connection);
290 $this->_lasterror = $php_errormsg ? $php_errormsg : '';
292 $this->result = $result;
293 if (!$this->result) {
294 return $this->sqliteRaiseError(null);
297 // sqlite_query() seems to allways return a resource
298 // so cant use that. Using $ismanip instead
300 $numRows = $this->numRows($result);
301 if (is_object($numRows)) {
302 // we've got PEAR_Error
314 * Move the internal sqlite result pointer to the next available result
316 * @param resource $result the valid sqlite result resource
318 * @return bool true if a result is available otherwise return false
320 function nextResult($result)
329 * Places a row from the result set into the given array
331 * Formating of the array and the data therein are configurable.
332 * See DB_result::fetchInto() for more information.
334 * This method is not meant to be called directly. Use
335 * DB_result::fetchInto() instead. It can't be declared "protected"
336 * because DB_result is a separate object.
338 * @param resource $result the query result resource
339 * @param array $arr the referenced array to put the data in
340 * @param int $fetchmode how the resulting array should be indexed
341 * @param int $rownum the row number to fetch (0 = first row)
343 * @return mixed DB_OK on success, NULL when the end of a result set is
344 * reached or on failure
346 * @see DB_result::fetchInto()
348 function fetchInto($result, &$arr, $fetchmode, $rownum = null)
350 if ($rownum !== null) {
351 if (!@sqlite_seek($this->result, $rownum)) {
355 if ($fetchmode & DB_FETCHMODE_ASSOC) {
356 $arr = @sqlite_fetch_array($result, SQLITE_ASSOC);
357 if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
358 $arr = array_change_key_case($arr, CASE_LOWER);
361 $arr = @sqlite_fetch_array($result, SQLITE_NUM);
366 if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
368 * Even though this DBMS already trims output, we do this because
369 * a field might have intentional whitespace at the end that
370 * gets removed by DB_PORTABILITY_RTRIM under another driver.
372 $this->_rtrimArrayValues($arr);
374 if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
375 $this->_convertNullArrayValuesToEmpty($arr);
384 * Deletes the result set and frees the memory occupied by the result set
386 * This method is not meant to be called directly. Use
387 * DB_result::free() instead. It can't be declared "protected"
388 * because DB_result is a separate object.
390 * @param resource $result PHP's query result resource
392 * @return bool TRUE on success, FALSE if $result is invalid
394 * @see DB_result::free()
396 function freeResult(&$result)
398 // XXX No native free?
399 if (!is_resource($result)) {
410 * Gets the number of columns in a result set
412 * This method is not meant to be called directly. Use
413 * DB_result::numCols() instead. It can't be declared "protected"
414 * because DB_result is a separate object.
416 * @param resource $result PHP's query result resource
418 * @return int the number of columns. A DB_Error object on failure.
420 * @see DB_result::numCols()
422 function numCols($result)
424 $cols = @sqlite_num_fields($result);
426 return $this->sqliteRaiseError();
435 * Gets the number of rows in a result set
437 * This method is not meant to be called directly. Use
438 * DB_result::numRows() instead. It can't be declared "protected"
439 * because DB_result is a separate object.
441 * @param resource $result PHP's query result resource
443 * @return int the number of rows. A DB_Error object on failure.
445 * @see DB_result::numRows()
447 function numRows($result)
449 $rows = @sqlite_num_rows($result);
450 if ($rows === null) {
451 return $this->sqliteRaiseError();
460 * Determines the number of rows affected by a data maniuplation query
462 * 0 is returned for queries that don't manipulate data.
464 * @return int the number of rows. A DB_Error object on failure.
466 function affectedRows()
468 return @sqlite_changes($this->connection);
472 // {{{ dropSequence()
477 * @param string $seq_name name of the sequence to be deleted
479 * @return int DB_OK on success. A DB_Error object on failure.
481 * @see DB_common::dropSequence(), DB_common::getSequenceName(),
482 * DB_sqlite::nextID(), DB_sqlite::createSequence()
484 function dropSequence($seq_name)
486 return $this->query('DROP TABLE ' . $this->getSequenceName($seq_name));
490 * Creates a new sequence
492 * @param string $seq_name name of the new sequence
494 * @return int DB_OK on success. A DB_Error object on failure.
496 * @see DB_common::createSequence(), DB_common::getSequenceName(),
497 * DB_sqlite::nextID(), DB_sqlite::dropSequence()
499 function createSequence($seq_name)
501 $seqname = $this->getSequenceName($seq_name);
502 $query = 'CREATE TABLE ' . $seqname .
503 ' (id INTEGER UNSIGNED PRIMARY KEY) ';
504 $result = $this->query($query);
505 if (DB::isError($result)) {
508 $query = "CREATE TRIGGER ${seqname}_cleanup AFTER INSERT ON $seqname
510 DELETE FROM $seqname WHERE id<LAST_INSERT_ROWID();
512 $result = $this->query($query);
513 if (DB::isError($result)) {
522 * Returns the next free id in a sequence
524 * @param string $seq_name name of the sequence
525 * @param boolean $ondemand when true, the seqence is automatically
526 * created if it does not exist
528 * @return int the next id number in the sequence.
529 * A DB_Error object on failure.
531 * @see DB_common::nextID(), DB_common::getSequenceName(),
532 * DB_sqlite::createSequence(), DB_sqlite::dropSequence()
534 function nextId($seq_name, $ondemand = true)
536 $seqname = $this->getSequenceName($seq_name);
540 $this->pushErrorHandling(PEAR_ERROR_RETURN);
541 $result = $this->query("INSERT INTO $seqname (id) VALUES (NULL)");
542 $this->popErrorHandling();
543 if ($result === DB_OK) {
544 $id = @sqlite_last_insert_rowid($this->connection);
548 } elseif ($ondemand && DB::isError($result) &&
549 $result->getCode() == DB_ERROR_NOSUCHTABLE)
551 $result = $this->createSequence($seq_name);
552 if (DB::isError($result)) {
553 return $this->raiseError($result);
560 return $this->raiseError($result);
564 // {{{ getDbFileStats()
567 * Get the file stats for the current database
569 * Possible arguments are dev, ino, mode, nlink, uid, gid, rdev, size,
570 * atime, mtime, ctime, blksize, blocks or a numeric key between
573 * @param string $arg the array key for stats()
575 * @return mixed an array on an unspecified key, integer on a passed
576 * arg and false at a stats error
578 function getDbFileStats($arg = '')
580 $stats = stat($this->dsn['database']);
581 if ($stats == false) {
584 if (is_array($stats)) {
585 if (is_numeric($arg)) {
586 if (((int)$arg <= 12) & ((int)$arg >= 0)) {
589 return $stats[$arg ];
591 if (array_key_exists(trim($arg), $stats)) {
592 return $stats[$arg ];
599 // {{{ escapeSimple()
602 * Escapes a string according to the current DBMS's standards
604 * In SQLite, this makes things safe for inserts/updates, but may
605 * cause problems when performing text comparisons against columns
606 * containing binary data. See the
607 * {@link http://php.net/sqlite_escape_string PHP manual} for more info.
609 * @param string $str the string to be escaped
611 * @return string the escaped string
613 * @since Method available since Release 1.6.1
614 * @see DB_common::escapeSimple()
616 function escapeSimple($str)
618 return @sqlite_escape_string($str);
622 // {{{ modifyLimitQuery()
625 * Adds LIMIT clauses to a query string according to current DBMS standards
627 * @param string $query the query to modify
628 * @param int $from the row to start to fetching (0 = the first row)
629 * @param int $count the numbers of rows to fetch
630 * @param mixed $params array, string or numeric data to be used in
631 * execution of the statement. Quantity of items
632 * passed must match quantity of placeholders in
633 * query: meaning 1 placeholder for non-array
634 * parameters or 1 placeholder per array element.
636 * @return string the query string with LIMIT clauses added
640 function modifyLimitQuery($query, $from, $count, $params = array())
642 return "$query LIMIT $count OFFSET $from";
649 * Changes a query string for various DBMS specific reasons
651 * This little hack lets you know how many rows were deleted
652 * when running a "DELETE FROM table" query. Only implemented
653 * if the DB_PORTABILITY_DELETE_COUNT portability option is on.
655 * @param string $query the query string to modify
657 * @return string the modified query string
660 * @see DB_common::setOption()
662 function modifyQuery($query)
664 if ($this->options['portability'] & DB_PORTABILITY_DELETE_COUNT) {
665 if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
666 $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
667 'DELETE FROM \1 WHERE 1=1', $query);
674 // {{{ sqliteRaiseError()
677 * Produces a DB_Error object regarding the current problem
679 * @param int $errno if the error is being manually raised pass a
680 * DB_ERROR* constant here. If this isn't passed
681 * the error information gathered from the DBMS.
683 * @return object the DB_Error object
685 * @see DB_common::raiseError(),
686 * DB_sqlite::errorNative(), DB_sqlite::errorCode()
688 function sqliteRaiseError($errno = null)
690 $native = $this->errorNative();
691 if ($errno === null) {
692 $errno = $this->errorCode($native);
695 $errorcode = @sqlite_last_error($this->connection);
696 $userinfo = "$errorcode ** $this->last_query";
698 return $this->raiseError($errno, null, null, $userinfo, $native);
705 * Gets the DBMS' native error message produced by the last query
707 * {@internal This is used to retrieve more meaningfull error messages
708 * because sqlite_last_error() does not provide adequate info.}}
710 * @return string the DBMS' error message
712 function errorNative()
714 return $this->_lasterror;
721 * Determines PEAR::DB error code from the database's text error message
723 * @param string $errormsg the error message returned from the database
725 * @return integer the DB error number
727 function errorCode($errormsg)
729 static $error_regexps;
730 if (!isset($error_regexps)) {
731 $error_regexps = array(
732 '/^no such table:/' => DB_ERROR_NOSUCHTABLE,
733 '/^no such index:/' => DB_ERROR_NOT_FOUND,
734 '/^(table|index) .* already exists$/' => DB_ERROR_ALREADY_EXISTS,
735 '/PRIMARY KEY must be unique/i' => DB_ERROR_CONSTRAINT,
736 '/is not unique/' => DB_ERROR_CONSTRAINT,
737 '/columns .* are not unique/i' => DB_ERROR_CONSTRAINT,
738 '/uniqueness constraint failed/' => DB_ERROR_CONSTRAINT,
739 '/may not be NULL/' => DB_ERROR_CONSTRAINT_NOT_NULL,
740 '/^no such column:/' => DB_ERROR_NOSUCHFIELD,
741 '/column not present in both tables/i' => DB_ERROR_NOSUCHFIELD,
742 '/^near ".*": syntax error$/' => DB_ERROR_SYNTAX,
743 '/[0-9]+ values for [0-9]+ columns/i' => DB_ERROR_VALUE_COUNT_ON_ROW,
746 foreach ($error_regexps as $regexp => $code) {
747 if (preg_match($regexp, $errormsg)) {
751 // Fall back to DB_ERROR if there was no mapping.
759 * Returns information about a table
761 * @param string $result a string containing the name of a table
762 * @param int $mode a valid tableInfo mode
764 * @return array an associative array with the information requested.
765 * A DB_Error object on failure.
767 * @see DB_common::tableInfo()
768 * @since Method available since Release 1.7.0
770 function tableInfo($result, $mode = null)
772 if (is_string($result)) {
774 * Probably received a table name.
775 * Create a result resource identifier.
777 $id = @sqlite_array_query($this->connection,
778 "PRAGMA table_info('$result');",
782 $this->last_query = '';
783 return $this->raiseError(DB_ERROR_NOT_CAPABLE, null, null, null,
784 'This DBMS can not obtain tableInfo' .
785 ' from result sets');
788 if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
789 $case_func = 'strtolower';
791 $case_func = 'strval';
798 $res['num_fields'] = $count;
801 for ($i = 0; $i < $count; $i++) {
802 if (strpos($id[$i]['type'], '(') !== false) {
803 $bits = explode('(', $id[$i]['type']);
805 $len = rtrim($bits[1],')');
807 $type = $id[$i]['type'];
813 $flags .= 'primary_key ';
815 if ($id[$i]['notnull']) {
816 $flags .= 'not_null ';
818 if ($id[$i]['dflt_value'] !== null) {
819 $flags .= 'default_' . rawurlencode($id[$i]['dflt_value']);
821 $flags = trim($flags);
824 'table' => $case_func($result),
825 'name' => $case_func($id[$i]['name']),
831 if ($mode & DB_TABLEINFO_ORDER) {
832 $res['order'][$res[$i]['name']] = $i;
834 if ($mode & DB_TABLEINFO_ORDERTABLE) {
835 $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
843 // {{{ getSpecialQuery()
846 * Obtains the query string needed for listing a given type of objects
848 * @param string $type the kind of objects you want to retrieve
849 * @param array $args SQLITE DRIVER ONLY: a private array of arguments
850 * used by the getSpecialQuery(). Do not use
853 * @return string the SQL query string or null if the driver doesn't
854 * support the object type requested
857 * @see DB_common::getListOf()
859 function getSpecialQuery($type, $args = array())
861 if (!is_array($args)) {
862 return $this->raiseError('no key specified', null, null, null,
863 'Argument has to be an array.');
868 return 'SELECT * FROM sqlite_master;';
870 return "SELECT name FROM sqlite_master WHERE type='table' "
871 . 'UNION ALL SELECT name FROM sqlite_temp_master '
872 . "WHERE type='table' ORDER BY name;";
874 return 'SELECT sql FROM (SELECT * FROM sqlite_master '
875 . 'UNION ALL SELECT * FROM sqlite_temp_master) '
876 . "WHERE type!='meta' "
877 . 'ORDER BY tbl_name, type DESC, name;';
882 * $res = $db->query($db->getSpecialQuery('schema_x',
883 * array('table' => 'table3')));
885 return 'SELECT sql FROM (SELECT * FROM sqlite_master '
886 . 'UNION ALL SELECT * FROM sqlite_temp_master) '
887 . "WHERE tbl_name LIKE '{$args['table']}' "
888 . "AND type!='meta' "
889 . 'ORDER BY type DESC, name;';
892 * SQLite does not support ALTER TABLE; this is a helper query
893 * to handle this. 'table' represents the table name, 'rows'
894 * the news rows to create, 'save' the row(s) to keep _with_
900 * 'rows' => "id INTEGER PRIMARY KEY, firstname TEXT, surname TEXT, datetime TEXT",
901 * 'save' => "NULL, titel, content, datetime"
903 * $res = $db->query( $db->getSpecialQuery('alter', $args));
905 $rows = strtr($args['rows'], $this->keywords);
909 "CREATE TEMPORARY TABLE {$args['table']}_backup ({$args['rows']})",
910 "INSERT INTO {$args['table']}_backup SELECT {$args['save']} FROM {$args['table']}",
911 "DROP TABLE {$args['table']}",
912 "CREATE TABLE {$args['table']} ({$args['rows']})",
913 "INSERT INTO {$args['table']} SELECT {$rows} FROM {$args['table']}_backup",
914 "DROP TABLE {$args['table']}_backup",
919 * This is a dirty hack, since the above query will not get
920 * executed with a single query call so here the query method
921 * will be called directly and return a select instead.
923 foreach ($q as $query) {
924 $this->query($query);
926 return "SELECT * FROM {$args['table']};";