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-2007 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,v 1.118 2007/11/26 22:57:18 aharvey Exp $
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-2007 The PHP Group
49 * @license http://www.php.net/license/3_0.txt PHP License 3.0 3.0
50 * @version Release: 1.7.14RC1
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 return $this->sqliteRaiseError(DB_ERROR_ACCESS_VIOLATION);
211 if ($dsn['database'] !== ':memory:') {
212 if (!file_exists($dsn['database'])) {
213 if (!touch($dsn['database'])) {
214 return $this->sqliteRaiseError(DB_ERROR_NOT_FOUND);
216 if (!isset($dsn['mode']) ||
217 !is_numeric($dsn['mode']))
221 $mode = octdec($dsn['mode']);
223 if (!chmod($dsn['database'], $mode)) {
224 return $this->sqliteRaiseError(DB_ERROR_NOT_FOUND);
226 if (!file_exists($dsn['database'])) {
227 return $this->sqliteRaiseError(DB_ERROR_NOT_FOUND);
230 if (!is_file($dsn['database'])) {
231 return $this->sqliteRaiseError(DB_ERROR_INVALID);
233 if (!is_readable($dsn['database'])) {
234 return $this->sqliteRaiseError(DB_ERROR_ACCESS_VIOLATION);
238 $connect_function = $persistent ? 'sqlite_popen' : 'sqlite_open';
240 // track_errors must remain on for simpleQuery()
241 @ini_set('track_errors', 1);
244 if (!$this->connection = @$connect_function($dsn['database'])) {
245 return $this->raiseError(DB_ERROR_NODBSELECTED,
256 * Disconnects from the database server
258 * @return bool TRUE on success, FALSE on failure
260 function disconnect()
262 $ret = @sqlite_close($this->connection);
263 $this->connection = null;
271 * Sends a query to the database server
273 * NOTICE: This method needs PHP's track_errors ini setting to be on.
274 * It is automatically turned on when connecting to the database.
275 * Make sure your scripts don't turn it off.
277 * @param string the SQL query string
279 * @return mixed + a PHP result resrouce for successful SELECT queries
280 * + the DB_OK constant for other successful queries
281 * + a DB_Error object on failure
283 function simpleQuery($query)
285 $ismanip = $this->_checkManip($query);
286 $this->last_query = $query;
287 $query = $this->modifyQuery($query);
291 $result = @sqlite_query($query, $this->connection);
292 $this->_lasterror = $php_errormsg ? $php_errormsg : '';
294 $this->result = $result;
295 if (!$this->result) {
296 return $this->sqliteRaiseError(null);
299 // sqlite_query() seems to allways return a resource
300 // so cant use that. Using $ismanip instead
302 $numRows = $this->numRows($result);
303 if (is_object($numRows)) {
304 // we've got PEAR_Error
316 * Move the internal sqlite result pointer to the next available result
318 * @param resource $result the valid sqlite result resource
320 * @return bool true if a result is available otherwise return false
322 function nextResult($result)
331 * Places a row from the result set into the given array
333 * Formating of the array and the data therein are configurable.
334 * See DB_result::fetchInto() for more information.
336 * This method is not meant to be called directly. Use
337 * DB_result::fetchInto() instead. It can't be declared "protected"
338 * because DB_result is a separate object.
340 * @param resource $result the query result resource
341 * @param array $arr the referenced array to put the data in
342 * @param int $fetchmode how the resulting array should be indexed
343 * @param int $rownum the row number to fetch (0 = first row)
345 * @return mixed DB_OK on success, NULL when the end of a result set is
346 * reached or on failure
348 * @see DB_result::fetchInto()
350 function fetchInto($result, &$arr, $fetchmode, $rownum = null)
352 if ($rownum !== null) {
353 if (!@sqlite_seek($this->result, $rownum)) {
357 if ($fetchmode & DB_FETCHMODE_ASSOC) {
358 $arr = @sqlite_fetch_array($result, SQLITE_ASSOC);
359 if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
360 $arr = array_change_key_case($arr, CASE_LOWER);
363 /* Remove extraneous " characters from the fields in the result.
364 * Fixes bug #11716. */
365 if (is_array($arr) && count($arr) > 0) {
366 $strippedArr = array();
367 foreach ($arr as $field => $value) {
368 $strippedArr[trim($field, '"')] = $value;
373 $arr = @sqlite_fetch_array($result, SQLITE_NUM);
378 if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
380 * Even though this DBMS already trims output, we do this because
381 * a field might have intentional whitespace at the end that
382 * gets removed by DB_PORTABILITY_RTRIM under another driver.
384 $this->_rtrimArrayValues($arr);
386 if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
387 $this->_convertNullArrayValuesToEmpty($arr);
396 * Deletes the result set and frees the memory occupied by the result set
398 * This method is not meant to be called directly. Use
399 * DB_result::free() instead. It can't be declared "protected"
400 * because DB_result is a separate object.
402 * @param resource $result PHP's query result resource
404 * @return bool TRUE on success, FALSE if $result is invalid
406 * @see DB_result::free()
408 function freeResult(&$result)
410 // XXX No native free?
411 if (!is_resource($result)) {
422 * Gets the number of columns in a result set
424 * This method is not meant to be called directly. Use
425 * DB_result::numCols() instead. It can't be declared "protected"
426 * because DB_result is a separate object.
428 * @param resource $result PHP's query result resource
430 * @return int the number of columns. A DB_Error object on failure.
432 * @see DB_result::numCols()
434 function numCols($result)
436 $cols = @sqlite_num_fields($result);
438 return $this->sqliteRaiseError();
447 * Gets the number of rows in a result set
449 * This method is not meant to be called directly. Use
450 * DB_result::numRows() instead. It can't be declared "protected"
451 * because DB_result is a separate object.
453 * @param resource $result PHP's query result resource
455 * @return int the number of rows. A DB_Error object on failure.
457 * @see DB_result::numRows()
459 function numRows($result)
461 $rows = @sqlite_num_rows($result);
462 if ($rows === null) {
463 return $this->sqliteRaiseError();
472 * Determines the number of rows affected by a data maniuplation query
474 * 0 is returned for queries that don't manipulate data.
476 * @return int the number of rows. A DB_Error object on failure.
478 function affectedRows()
480 return @sqlite_changes($this->connection);
484 // {{{ dropSequence()
489 * @param string $seq_name name of the sequence to be deleted
491 * @return int DB_OK on success. A DB_Error object on failure.
493 * @see DB_common::dropSequence(), DB_common::getSequenceName(),
494 * DB_sqlite::nextID(), DB_sqlite::createSequence()
496 function dropSequence($seq_name)
498 return $this->query('DROP TABLE ' . $this->getSequenceName($seq_name));
502 * Creates a new sequence
504 * @param string $seq_name name of the new sequence
506 * @return int DB_OK on success. A DB_Error object on failure.
508 * @see DB_common::createSequence(), DB_common::getSequenceName(),
509 * DB_sqlite::nextID(), DB_sqlite::dropSequence()
511 function createSequence($seq_name)
513 $seqname = $this->getSequenceName($seq_name);
514 $query = 'CREATE TABLE ' . $seqname .
515 ' (id INTEGER UNSIGNED PRIMARY KEY) ';
516 $result = $this->query($query);
517 if (DB::isError($result)) {
520 $query = "CREATE TRIGGER ${seqname}_cleanup AFTER INSERT ON $seqname
522 DELETE FROM $seqname WHERE id<LAST_INSERT_ROWID();
524 $result = $this->query($query);
525 if (DB::isError($result)) {
534 * Returns the next free id in a sequence
536 * @param string $seq_name name of the sequence
537 * @param boolean $ondemand when true, the seqence is automatically
538 * created if it does not exist
540 * @return int the next id number in the sequence.
541 * A DB_Error object on failure.
543 * @see DB_common::nextID(), DB_common::getSequenceName(),
544 * DB_sqlite::createSequence(), DB_sqlite::dropSequence()
546 function nextId($seq_name, $ondemand = true)
548 $seqname = $this->getSequenceName($seq_name);
552 $this->pushErrorHandling(PEAR_ERROR_RETURN);
553 $result = $this->query("INSERT INTO $seqname (id) VALUES (NULL)");
554 $this->popErrorHandling();
555 if ($result === DB_OK) {
556 $id = @sqlite_last_insert_rowid($this->connection);
560 } elseif ($ondemand && DB::isError($result) &&
561 $result->getCode() == DB_ERROR_NOSUCHTABLE)
563 $result = $this->createSequence($seq_name);
564 if (DB::isError($result)) {
565 return $this->raiseError($result);
572 return $this->raiseError($result);
576 // {{{ getDbFileStats()
579 * Get the file stats for the current database
581 * Possible arguments are dev, ino, mode, nlink, uid, gid, rdev, size,
582 * atime, mtime, ctime, blksize, blocks or a numeric key between
585 * @param string $arg the array key for stats()
587 * @return mixed an array on an unspecified key, integer on a passed
588 * arg and false at a stats error
590 function getDbFileStats($arg = '')
592 $stats = stat($this->dsn['database']);
593 if ($stats == false) {
596 if (is_array($stats)) {
597 if (is_numeric($arg)) {
598 if (((int)$arg <= 12) & ((int)$arg >= 0)) {
601 return $stats[$arg ];
603 if (array_key_exists(trim($arg), $stats)) {
604 return $stats[$arg ];
611 // {{{ escapeSimple()
614 * Escapes a string according to the current DBMS's standards
616 * In SQLite, this makes things safe for inserts/updates, but may
617 * cause problems when performing text comparisons against columns
618 * containing binary data. See the
619 * {@link http://php.net/sqlite_escape_string PHP manual} for more info.
621 * @param string $str the string to be escaped
623 * @return string the escaped string
625 * @since Method available since Release 1.6.1
626 * @see DB_common::escapeSimple()
628 function escapeSimple($str)
630 return @sqlite_escape_string($str);
634 // {{{ modifyLimitQuery()
637 * Adds LIMIT clauses to a query string according to current DBMS standards
639 * @param string $query the query to modify
640 * @param int $from the row to start to fetching (0 = the first row)
641 * @param int $count the numbers of rows to fetch
642 * @param mixed $params array, string or numeric data to be used in
643 * execution of the statement. Quantity of items
644 * passed must match quantity of placeholders in
645 * query: meaning 1 placeholder for non-array
646 * parameters or 1 placeholder per array element.
648 * @return string the query string with LIMIT clauses added
652 function modifyLimitQuery($query, $from, $count, $params = array())
654 return "$query LIMIT $count OFFSET $from";
661 * Changes a query string for various DBMS specific reasons
663 * This little hack lets you know how many rows were deleted
664 * when running a "DELETE FROM table" query. Only implemented
665 * if the DB_PORTABILITY_DELETE_COUNT portability option is on.
667 * @param string $query the query string to modify
669 * @return string the modified query string
672 * @see DB_common::setOption()
674 function modifyQuery($query)
676 if ($this->options['portability'] & DB_PORTABILITY_DELETE_COUNT) {
677 if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
678 $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
679 'DELETE FROM \1 WHERE 1=1', $query);
686 // {{{ sqliteRaiseError()
689 * Produces a DB_Error object regarding the current problem
691 * @param int $errno if the error is being manually raised pass a
692 * DB_ERROR* constant here. If this isn't passed
693 * the error information gathered from the DBMS.
695 * @return object the DB_Error object
697 * @see DB_common::raiseError(),
698 * DB_sqlite::errorNative(), DB_sqlite::errorCode()
700 function sqliteRaiseError($errno = null)
702 $native = $this->errorNative();
703 if ($errno === null) {
704 $errno = $this->errorCode($native);
707 $errorcode = @sqlite_last_error($this->connection);
708 $userinfo = "$errorcode ** $this->last_query";
710 return $this->raiseError($errno, null, null, $userinfo, $native);
717 * Gets the DBMS' native error message produced by the last query
719 * {@internal This is used to retrieve more meaningfull error messages
720 * because sqlite_last_error() does not provide adequate info.}}
722 * @return string the DBMS' error message
724 function errorNative()
726 return $this->_lasterror;
733 * Determines PEAR::DB error code from the database's text error message
735 * @param string $errormsg the error message returned from the database
737 * @return integer the DB error number
739 function errorCode($errormsg)
741 static $error_regexps;
743 // PHP 5.2+ prepends the function name to $php_errormsg, so we need
744 // this hack to work around it, per bug #9599.
745 $errormsg = preg_replace('/^sqlite[a-z_]+\(\): /', '', $errormsg);
747 if (!isset($error_regexps)) {
748 $error_regexps = array(
749 '/^no such table:/' => DB_ERROR_NOSUCHTABLE,
750 '/^no such index:/' => DB_ERROR_NOT_FOUND,
751 '/^(table|index) .* already exists$/' => DB_ERROR_ALREADY_EXISTS,
752 '/PRIMARY KEY must be unique/i' => DB_ERROR_CONSTRAINT,
753 '/is not unique/' => DB_ERROR_CONSTRAINT,
754 '/columns .* are not unique/i' => DB_ERROR_CONSTRAINT,
755 '/uniqueness constraint failed/' => DB_ERROR_CONSTRAINT,
756 '/may not be NULL/' => DB_ERROR_CONSTRAINT_NOT_NULL,
757 '/^no such column:/' => DB_ERROR_NOSUCHFIELD,
758 '/no column named/' => DB_ERROR_NOSUCHFIELD,
759 '/column not present in both tables/i' => DB_ERROR_NOSUCHFIELD,
760 '/^near ".*": syntax error$/' => DB_ERROR_SYNTAX,
761 '/[0-9]+ values for [0-9]+ columns/i' => DB_ERROR_VALUE_COUNT_ON_ROW,
764 foreach ($error_regexps as $regexp => $code) {
765 if (preg_match($regexp, $errormsg)) {
769 // Fall back to DB_ERROR if there was no mapping.
777 * Returns information about a table
779 * @param string $result a string containing the name of a table
780 * @param int $mode a valid tableInfo mode
782 * @return array an associative array with the information requested.
783 * A DB_Error object on failure.
785 * @see DB_common::tableInfo()
786 * @since Method available since Release 1.7.0
788 function tableInfo($result, $mode = null)
790 if (is_string($result)) {
792 * Probably received a table name.
793 * Create a result resource identifier.
795 $id = @sqlite_array_query($this->connection,
796 "PRAGMA table_info('$result');",
800 $this->last_query = '';
801 return $this->raiseError(DB_ERROR_NOT_CAPABLE, null, null, null,
802 'This DBMS can not obtain tableInfo' .
803 ' from result sets');
806 if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
807 $case_func = 'strtolower';
809 $case_func = 'strval';
816 $res['num_fields'] = $count;
819 for ($i = 0; $i < $count; $i++) {
820 if (strpos($id[$i]['type'], '(') !== false) {
821 $bits = explode('(', $id[$i]['type']);
823 $len = rtrim($bits[1],')');
825 $type = $id[$i]['type'];
831 $flags .= 'primary_key ';
833 if ($id[$i]['notnull']) {
834 $flags .= 'not_null ';
836 if ($id[$i]['dflt_value'] !== null) {
837 $flags .= 'default_' . rawurlencode($id[$i]['dflt_value']);
839 $flags = trim($flags);
842 'table' => $case_func($result),
843 'name' => $case_func($id[$i]['name']),
849 if ($mode & DB_TABLEINFO_ORDER) {
850 $res['order'][$res[$i]['name']] = $i;
852 if ($mode & DB_TABLEINFO_ORDERTABLE) {
853 $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
861 // {{{ getSpecialQuery()
864 * Obtains the query string needed for listing a given type of objects
866 * @param string $type the kind of objects you want to retrieve
867 * @param array $args SQLITE DRIVER ONLY: a private array of arguments
868 * used by the getSpecialQuery(). Do not use
871 * @return string the SQL query string or null if the driver doesn't
872 * support the object type requested
875 * @see DB_common::getListOf()
877 function getSpecialQuery($type, $args = array())
879 if (!is_array($args)) {
880 return $this->raiseError('no key specified', null, null, null,
881 'Argument has to be an array.');
886 return 'SELECT * FROM sqlite_master;';
888 return "SELECT name FROM sqlite_master WHERE type='table' "
889 . 'UNION ALL SELECT name FROM sqlite_temp_master '
890 . "WHERE type='table' ORDER BY name;";
892 return 'SELECT sql FROM (SELECT * FROM sqlite_master '
893 . 'UNION ALL SELECT * FROM sqlite_temp_master) '
894 . "WHERE type!='meta' "
895 . 'ORDER BY tbl_name, type DESC, name;';
900 * $res = $db->query($db->getSpecialQuery('schema_x',
901 * array('table' => 'table3')));
903 return 'SELECT sql FROM (SELECT * FROM sqlite_master '
904 . 'UNION ALL SELECT * FROM sqlite_temp_master) '
905 . "WHERE tbl_name LIKE '{$args['table']}' "
906 . "AND type!='meta' "
907 . 'ORDER BY type DESC, name;';
910 * SQLite does not support ALTER TABLE; this is a helper query
911 * to handle this. 'table' represents the table name, 'rows'
912 * the news rows to create, 'save' the row(s) to keep _with_
918 * 'rows' => "id INTEGER PRIMARY KEY, firstname TEXT, surname TEXT, datetime TEXT",
919 * 'save' => "NULL, titel, content, datetime"
921 * $res = $db->query( $db->getSpecialQuery('alter', $args));
923 $rows = strtr($args['rows'], $this->keywords);
927 "CREATE TEMPORARY TABLE {$args['table']}_backup ({$args['rows']})",
928 "INSERT INTO {$args['table']}_backup SELECT {$args['save']} FROM {$args['table']}",
929 "DROP TABLE {$args['table']}",
930 "CREATE TABLE {$args['table']} ({$args['rows']})",
931 "INSERT INTO {$args['table']} SELECT {$rows} FROM {$args['table']}_backup",
932 "DROP TABLE {$args['table']}_backup",
937 * This is a dirty hack, since the above query will not get
938 * executed with a single query call so here the query method
939 * will be called directly and return a select instead.
941 foreach ($q as $query) {
942 $this->query($query);
944 return "SELECT * FROM {$args['table']};";