Source for file sqlite.php
Documentation is available at sqlite.php
/* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
// +----------------------------------------------------------------------+
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2004 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.02 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Urs Gehrig <urs@circle.ch> |
// | Mika Tuupola <tuupola@appelsiini.net> |
// | Maintainer: Daniel Convissor <danielc@php.net> |
// +----------------------------------------------------------------------+
// $Id: sqlite.php,v 1.65 2004/04/07 04:56:58 danielc Exp $
require_once 'DB/common.php';
* Database independent query interface definition for the SQLite
* @version $Id: sqlite.php,v 1.65 2004/04/07 04:56:58 danielc Exp $
* @author Urs Gehrig <urs@circle.ch>
* @author Mika Tuupola <tuupola@appelsiini.net>
* Constructor for this class.
* Error codes according to sqlite_exec. Error Codes specification is
* in the {@link http://sqlite.org/c_interface.html online manual}.
* This errorhandling based on sqlite_exec is not yet implemented.
// SQLite data types, http://www.sqlite.org/datatypes.html
$this->keywords = array (
* Connect to a database represented by a file.
* @param $dsn the data source name; the file is taken as
* database; "sqlite://root:@host/test.db?mode=0644"
* @param $persistent (optional) whether the connection should
* @return int DB_OK on success, a DB error on failure
function connect($dsninfo, $persistent = false )
if ($dsninfo['database']) {
if (!touch($dsninfo['database'])) {
if (!isset ($dsninfo['mode']) ||
$mode = octdec($dsninfo['mode']);
if (!chmod($dsninfo['database'], $mode)) {
if (!is_file($dsninfo['database'])) {
$connect_function = $persistent ? 'sqlite_popen' : 'sqlite_open';
if (!($conn = @$connect_function($dsninfo['database']))) {
* Log out and disconnect from the database.
* @return bool true on success, false if not connected.
* @todo fix return values
* Send a query to SQLite and returns the results as a SQLite resource
* @return mixed returns a valid SQLite result for successful SELECT
* queries, DB_OK for other successful queries. A DB error is
$query = $this->_modifyQuery ($query);
$result = @sqlite_query ($query, $this->connection);
$this->_lasterror = isset ($php_errormsg) ? $php_errormsg : '';
/* sqlite_query() seems to allways return a resource */
/* so cant use that. Using $ismanip instead */
$numRows = $this->numRows($result);
/* if numRows() returned PEAR_Error */
* Move the internal sqlite result pointer to the next available result.
* @param a valid sqlite result resource
* @return true if a result is available otherwise return false
* Fetch a row and insert the data into an existing array.
* Formating of the array and the data therein are configurable.
* See DB_result::fetchInto() for more information.
* @param resource $result query result identifier
* @param array $arr (reference) array where data from the row
* @param int $fetchmode how the resulting array should be indexed
* @param int $rownum the row number to fetch
* @return mixed DB_OK on success, null when end of result set is
* @see DB_result::fetchInto()
function fetchInto ($result, &$arr, $fetchmode, $rownum=null )
if (!@sqlite_seek ($this->result, $rownum)) {
$arr = @sqlite_fetch_array ($result, SQLITE_ASSOC );
$arr = @sqlite_fetch_array ($result, SQLITE_NUM );
/* See: http://bugs.php.net/bug.php?id=22328 */
* Even though this DBMS already trims output, we do this because
* a field might have intentional whitespace at the end that
* gets removed by DB_PORTABILITY_RTRIM under another driver.
$this->_rtrimArrayValues ($arr);
$this->_convertNullArrayValuesToEmpty ($arr);
* Free the internal resources associated with $result.
* @param $result SQLite result identifier
* @return bool true on success, false if $result is invalid
* Gets the number of columns in a result set.
* @return number of columns in a result set
$cols = @sqlite_num_fields ($result);
* Gets the number of rows affected by a query.
* @return number of rows affected by the last query
$rows = @sqlite_num_rows ($result);
* Gets the number of rows affected by a query.
* @return number of rows affected by the last query
* Get the native error string of the last error (if any) that
* occured on the current connection.
* This is used to retrieve more meaningfull error messages DB_pgsql
* way since sqlite_last_error() does not provide adequate info.
* @return string native SQLite error message
return($this->_lasterror);
* Determine PEAR::DB error code from the database's text error message.
* @param string $errormsg error message returned from the database
* @return integer an error number from a DB error constant
if (!isset ($error_regexps)) {
foreach ($error_regexps as $regexp => $code) {
// Fall back to DB_ERROR if there was no mapping.
* @param string $seq_name name of the sequence to be deleted
* @return int DB_OK on success. DB_Error if problems.
* @see DB_common::dropSequence()
$seqname = $this->getSequenceName ($seq_name);
return $this->query(" DROP TABLE $seqname" );
* @param string $seq_name name of the new sequence
* @return int DB_OK on success. A DB_Error object is returned if
* @see DB_common::createSequence()
$seqname = $this->getSequenceName ($seq_name);
$query = 'CREATE TABLE ' . $seqname .
' (id INTEGER UNSIGNED PRIMARY KEY) ';
$result = $this->query($query);
$query = " CREATE TRIGGER ${seqname}_cleanup AFTER INSERT ON $seqname
DELETE FROM $seqname WHERE id<LAST_INSERT_ROWID();
$result = $this->query($query);
* Returns the next free id in a sequence
* @param string $seq_name name of the sequence
* @param boolean $ondemand when true, the seqence is automatically
* created if it does not exist
* @return int the next id number in the sequence. DB_Error if problem.
* @see DB_common::nextID()
function nextId($seq_name, $ondemand = true )
$seqname = $this->getSequenceName ($seq_name);
$this->pushErrorHandling (PEAR_ERROR_RETURN );
$result = $this->query(" INSERT INTO $seqname VALUES (NULL)" );
$this->popErrorHandling ();
$id = @sqlite_last_insert_rowid ($this->connection);
} elseif ($ondemand && DB::isError($result) &&
* Returns the query needed to get some backend info.
* Refer to the online manual at http://sqlite.org/sqlite.html.
* @param string $type What kind of info you want to retrieve
* @return string The SQL query string
return $this->raiseError('no key specified', null , null , null ,
'Argument has to be an array.');
return 'SELECT * FROM sqlite_master;';
return "SELECT name FROM sqlite_master WHERE type='table' "
. 'UNION ALL SELECT name FROM sqlite_temp_master '
. "WHERE type='table' ORDER BY name;";
return 'SELECT sql FROM (SELECT * FROM sqlite_master UNION ALL '
. 'SELECT * FROM sqlite_temp_master) '
. "WHERE type!='meta' ORDER BY tbl_name, type DESC, name;";
* $res = $db->query($db->getSpecialQuery('schema_x', array('table' => 'table3')));
return 'SELECT sql FROM (SELECT * FROM sqlite_master UNION ALL '
. 'SELECT * FROM sqlite_temp_master) '
. " WHERE tbl_name LIKE '{$args['table']}' AND type!='meta' "
. 'ORDER BY type DESC, name;';
* SQLite does not support ALTER TABLE; this is a helper query
* to handle this. 'table' represents the table name, 'rows'
* the news rows to create, 'save' the row(s) to keep _with_
* 'rows' => "id INTEGER PRIMARY KEY, firstname TEXT, surname TEXT, datetime TEXT",
* 'save' => "NULL, titel, content, datetime"
* $res = $db->query( $db->getSpecialQuery('alter', $args));
$rows = strtr($args['rows'], $this->keywords);
" CREATE TEMPORARY TABLE {$args['table']}_backup ({$args['rows']})" ,
" INSERT INTO {$args['table']}_backup SELECT {$args['save']} FROM {$args['table']}" ,
" DROP TABLE {$args['table']}" ,
" CREATE TABLE {$args['table']} ({$args['rows']})" ,
" INSERT INTO {$args['table']} SELECT {$rows} FROM {$args['table']}_backup" ,
" DROP TABLE {$args['table']}_backup" ,
// This is a dirty hack, since the above query will no get executed with a single
// query call; so here the query method will be called directly and return a select instead.
return " SELECT * FROM {$args['table']};";
* Get the file stats for the current database.
* Possible arguments are dev, ino, mode, nlink, uid, gid, rdev, size,
* atime, mtime, ctime, blksize, blocks or a numeric key between
* @param string $arg Array key for stats()
* @return mixed array on an unspecified key, integer on a passed arg and
* false at a stats error.
$stats = stat($this->dsn['database']);
if (((int) $arg <= 12 ) & ((int) $arg >= 0 )) {
* Escape a string according to the current DBMS's standards
* In SQLite, this makes things safe for inserts/updates, but may
* cause problems when performing text comparisons against columns
* containing binary data. See the
* {@link http://php.net/sqlite_escape_string PHP manual} for more info.
* @param string $str the string to be escaped
* @return string the escaped string
* @see DB_common::escapeSimple()
return @sqlite_escape_string ($str);
// {{{ modifyLimitQuery()
$query = $query . " LIMIT $count OFFSET $from";
* "DELETE FROM table" gives 0 affected rows in SQLite.
* This little hack lets you know how many rows were deleted.
* @param string $query The SQL query string
* @return string The SQL query string
function _modifyQuery ($query)
if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
'DELETE FROM \1 WHERE 1=1', $query);
// {{{ sqliteRaiseError()
* Gather information about an error, then use that info to create a
* DB error object and finally return that object.
* @param integer $errno PEAR error number (usually a DB constant) if
* manually raising an error
* @return object DB error object
* @see DB_common::raiseError()
$errorcode = @sqlite_last_error ($this->connection);
return $this->raiseError($errno, null , null , $userinfo, $native);
Documentation generated on Mon, 11 Mar 2019 10:14:55 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.
|