wiki.techinc.nl/includes/db/DatabaseSqlite.php

1033 lines
24 KiB
PHP
Raw Normal View History

2008-05-07 23:40:14 +00:00
<?php
/**
2010-08-01 21:13:44 +00:00
* This is the SQLite database abstraction layer.
* See maintenance/sqlite/README for development notes and other specific information
2010-08-01 21:13:44 +00:00
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
2010-08-01 21:13:44 +00:00
* @ingroup Database
2008-05-07 23:40:14 +00:00
*/
/**
* @ingroup Database
2008-05-07 23:40:14 +00:00
*/
class DatabaseSqlite extends DatabaseBase {
/** @var bool Whether full text is enabled */
private static $fulltextEnabled = null;
/** @var string File name for SQLite database file */
public $mDatabaseFile;
/** @var int The number of rows affected as an integer */
protected $mAffectedRows;
/** @var resource */
protected $mLastResult;
2008-05-07 23:40:14 +00:00
/** @var PDO */
2011-05-28 17:52:12 +00:00
protected $mConn;
/** @var FSLockManager (hopefully on the same server as the DB) */
protected $lockMgr;
function __construct( $p = null ) {
global $wgSharedDB, $wgSQLiteDataDir;
if ( !is_array( $p ) ) { // legacy calling pattern
wfDeprecated( __METHOD__ . " method called without parameter array.", "1.22" );
$args = func_get_args();
$p = array(
'host' => isset( $args[0] ) ? $args[0] : false,
'user' => isset( $args[1] ) ? $args[1] : false,
'password' => isset( $args[2] ) ? $args[2] : false,
'dbname' => isset( $args[3] ) ? $args[3] : false,
'flags' => isset( $args[4] ) ? $args[4] : 0,
'tablePrefix' => isset( $args[5] ) ? $args[5] : 'get from global',
'schema' => 'get from global',
'foreign' => isset( $args[6] ) ? $args[6] : false
);
}
$this->mDBname = $p['dbname'];
parent::__construct( $p );
// parent doesn't open when $user is false, but we can work with $dbName
if ( $p['dbname'] && !$this->isOpen() ) {
if ( $this->open( $p['host'], $p['user'], $p['password'], $p['dbname'] ) ) {
if ( $wgSharedDB ) {
$this->attachDatabase( $wgSharedDB );
}
}
2010-06-26 12:10:47 +00:00
}
$this->lockMgr = new FSLockManager( array( 'lockDirectory' => "$wgSQLiteDataDir/locks" ) );
2008-05-07 23:40:14 +00:00
}
2011-05-28 17:52:12 +00:00
/**
* @return string
*/
function getType() {
return 'sqlite';
}
2008-05-07 23:40:14 +00:00
/**
* @todo Check if it should be true like parent class
2011-05-28 17:52:12 +00:00
*
* @return bool
2008-05-07 23:40:14 +00:00
*/
2011-05-28 17:52:12 +00:00
function implicitGroupby() {
return false;
}
2008-05-07 23:40:14 +00:00
/** Open an SQLite database and return a resource handle to it
* NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
2011-05-28 18:58:51 +00:00
*
* @param string $server
* @param string $user
* @param string $pass
* @param string $dbName
2011-05-28 18:58:51 +00:00
*
* @throws DBConnectionError
2011-05-28 18:58:51 +00:00
* @return PDO
2008-05-07 23:40:14 +00:00
*/
2009-09-15 21:05:30 +00:00
function open( $server, $user, $pass, $dbName ) {
global $wgSQLiteDataDir;
$this->close();
$fileName = self::generateFileName( $wgSQLiteDataDir, $dbName );
if ( !is_readable( $fileName ) ) {
$this->mConn = false;
2010-06-11 12:51:23 +00:00
throw new DBConnectionError( $this, "SQLite database not accessible" );
2008-05-07 23:40:14 +00:00
}
$this->openFile( $fileName );
2008-05-07 23:40:14 +00:00
return $this->mConn;
}
/**
* Opens a database file
2011-05-28 17:52:12 +00:00
*
* @param string $fileName
* @throws DBConnectionError
* @return PDO|bool SQL connection or false if failed
*/
function openFile( $fileName ) {
$err = false;
$this->mDatabaseFile = $fileName;
try {
if ( $this->mFlags & DBO_PERSISTENT ) {
$this->mConn = new PDO( "sqlite:$fileName", '', '',
array( PDO::ATTR_PERSISTENT => true ) );
} else {
$this->mConn = new PDO( "sqlite:$fileName", '', '' );
}
} catch ( PDOException $e ) {
$err = $e->getMessage();
}
if ( !$this->mConn ) {
wfDebug( "DB connection error: $err\n" );
throw new DBConnectionError( $this, $err );
}
$this->mOpened = !!$this->mConn;
# set error codes only, don't raise exceptions
if ( $this->mOpened ) {
$this->mConn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
# Enforce LIKE to be case sensitive, just like MySQL
$this->query( 'PRAGMA case_sensitive_like = 1' );
return $this->mConn;
}
return false;
}
2008-05-07 23:40:14 +00:00
/**
* Does not actually close the connection, just destroys the reference for GC to do its work
2011-05-11 23:11:41 +00:00
* @return bool
2008-05-07 23:40:14 +00:00
*/
protected function closeConnection() {
$this->mConn = null;
2008-05-07 23:40:14 +00:00
return true;
}
/**
* Generates a database file name. Explicitly public for installer.
* @param string $dir Directory where database resides
* @param string $dbName Database name
* @return string
*/
public static function generateFileName( $dir, $dbName ) {
return "$dir/$dbName.sqlite";
}
/**
* Check if the searchindext table is FTS enabled.
2012-02-10 15:37:33 +00:00
* @return bool False if not enabled.
*/
function checkForEnabledSearch() {
if ( self::$fulltextEnabled === null ) {
self::$fulltextEnabled = false;
$table = $this->tableName( 'searchindex' );
$res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__ );
if ( $res ) {
$row = $res->fetchRow();
self::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
}
}
return self::$fulltextEnabled;
}
/**
* Returns version of currently supported SQLite fulltext search module or false if none present.
* @return string
*/
static function getFulltextSearchModule() {
static $cachedResult = null;
if ( $cachedResult !== null ) {
return $cachedResult;
}
$cachedResult = false;
$table = 'dummy_search_test';
$db = new DatabaseSqliteStandalone( ':memory:' );
if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__, true ) ) {
$cachedResult = 'FTS3';
}
$db->close();
return $cachedResult;
}
2010-06-26 12:10:47 +00:00
/**
* Attaches external database to our connection, see http://sqlite.org/lang_attach.html
* for details.
2011-05-28 17:52:12 +00:00
*
* @param string $name Database name to be used in queries like
* SELECT foo FROM dbname.table
* @param bool|string $file Database file name. If omitted, will be generated
* using $name and $wgSQLiteDataDir
* @param string $fname Calling function name
2011-05-28 17:52:12 +00:00
* @return ResultWrapper
2010-06-26 12:10:47 +00:00
*/
function attachDatabase( $name, $file = false, $fname = __METHOD__ ) {
2010-06-26 12:10:47 +00:00
global $wgSQLiteDataDir;
if ( !$file ) {
$file = self::generateFileName( $wgSQLiteDataDir, $name );
}
$file = $this->addQuotes( $file );
2010-06-26 12:10:47 +00:00
return $this->query( "ATTACH DATABASE $file AS $name", $fname );
}
/**
* @see DatabaseBase::isWriteQuery()
2011-05-11 23:11:41 +00:00
*
* @param string $sql
2011-05-11 23:11:41 +00:00
* @return bool
*/
function isWriteQuery( $sql ) {
return parent::isWriteQuery( $sql ) && !preg_match( '/^ATTACH\b/i', $sql );
}
2008-05-07 23:40:14 +00:00
/**
* SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
2011-05-28 17:52:12 +00:00
*
* @param string $sql
* @return bool|ResultWrapper
2008-05-07 23:40:14 +00:00
*/
protected function doQuery( $sql ) {
2009-09-15 21:05:30 +00:00
$res = $this->mConn->query( $sql );
if ( $res === false ) {
return false;
} else {
2008-05-07 23:40:14 +00:00
$r = $res instanceof ResultWrapper ? $res->result : $res;
$this->mAffectedRows = $r->rowCount();
2009-09-15 21:05:30 +00:00
$res = new ResultWrapper( $this, $r->fetchAll() );
2008-05-07 23:40:14 +00:00
}
2008-05-07 23:40:14 +00:00
return $res;
}
2011-05-28 17:52:12 +00:00
/**
* @param ResultWrapper|mixed $res
2011-05-28 17:52:12 +00:00
*/
2009-09-15 21:05:30 +00:00
function freeResult( $res ) {
2010-08-25 15:38:32 +00:00
if ( $res instanceof ResultWrapper ) {
$res->result = null;
2010-08-25 15:38:32 +00:00
} else {
$res = null;
2010-08-25 15:38:32 +00:00
}
2008-05-07 23:40:14 +00:00
}
2011-05-28 17:52:12 +00:00
/**
* @param ResultWrapper|array $res
* @return stdClass|bool
2011-05-28 17:52:12 +00:00
*/
2010-01-17 20:47:23 +00:00
function fetchObject( $res ) {
2010-08-25 15:38:32 +00:00
if ( $res instanceof ResultWrapper ) {
2009-09-15 21:05:30 +00:00
$r =& $res->result;
2010-08-25 15:38:32 +00:00
} else {
2009-09-15 21:05:30 +00:00
$r =& $res;
2010-08-25 15:38:32 +00:00
}
2009-09-15 21:05:30 +00:00
$cur = current( $r );
if ( is_array( $cur ) ) {
next( $r );
2008-05-07 23:40:14 +00:00
$obj = new stdClass;
2010-08-25 15:38:32 +00:00
foreach ( $cur as $k => $v ) {
if ( !is_numeric( $k ) ) {
2009-09-15 21:05:30 +00:00
$obj->$k = $v;
2010-08-25 15:38:32 +00:00
}
}
2009-09-15 21:05:30 +00:00
2008-05-07 23:40:14 +00:00
return $obj;
}
2008-05-07 23:40:14 +00:00
return false;
}
2011-05-28 17:52:12 +00:00
/**
* @param ResultWrapper|mixed $res
* @return array|bool
2011-05-28 17:52:12 +00:00
*/
2010-01-17 20:47:23 +00:00
function fetchRow( $res ) {
2010-08-25 15:38:32 +00:00
if ( $res instanceof ResultWrapper ) {
2009-09-15 21:05:30 +00:00
$r =& $res->result;
2010-08-25 15:38:32 +00:00
} else {
2009-09-15 21:05:30 +00:00
$r =& $res;
2010-08-25 15:38:32 +00:00
}
2010-01-17 20:47:23 +00:00
$cur = current( $r );
if ( is_array( $cur ) ) {
next( $r );
2008-05-07 23:40:14 +00:00
return $cur;
}
2008-05-07 23:40:14 +00:00
return false;
}
/**
* The PDO::Statement class implements the array interface so count() will work
2011-05-28 17:52:12 +00:00
*
* @param ResultWrapper|array $res
2011-05-28 17:52:12 +00:00
* @return int
2008-05-07 23:40:14 +00:00
*/
2009-09-15 21:05:30 +00:00
function numRows( $res ) {
2008-05-07 23:40:14 +00:00
$r = $res instanceof ResultWrapper ? $res->result : $res;
2009-09-15 21:05:30 +00:00
return count( $r );
2008-05-07 23:40:14 +00:00
}
2011-05-28 17:52:12 +00:00
/**
* @param ResultWrapper $res
2011-05-28 17:52:12 +00:00
* @return int
*/
2009-09-15 21:05:30 +00:00
function numFields( $res ) {
2008-05-07 23:40:14 +00:00
$r = $res instanceof ResultWrapper ? $res->result : $res;
if ( is_array($r) && count( $r ) > 0 ){
// The size of the result array is twice the number of fields. (Bug: 65578)
return count( $r[0] ) / 2 ;
} else {
// If the result is empty return 0
return 0;
}
2008-05-07 23:40:14 +00:00
}
2011-05-28 17:52:12 +00:00
/**
* @param ResultWrapper $res
* @param int $n
2011-05-28 17:52:12 +00:00
* @return bool
*/
2009-09-15 21:05:30 +00:00
function fieldName( $res, $n ) {
2008-05-07 23:40:14 +00:00
$r = $res instanceof ResultWrapper ? $res->result : $res;
2009-09-15 21:05:30 +00:00
if ( is_array( $r ) ) {
$keys = array_keys( $r[0] );
2008-05-07 23:40:14 +00:00
return $keys[$n];
}
2011-05-28 17:52:12 +00:00
return false;
2008-05-07 23:40:14 +00:00
}
/**
* Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
2011-05-28 17:52:12 +00:00
*
* @param string $name
* @param string $format
2011-05-28 17:52:12 +00:00
* @return string
2008-05-07 23:40:14 +00:00
*/
function tableName( $name, $format = 'quoted' ) {
// table names starting with sqlite_ are reserved
2011-05-28 17:52:12 +00:00
if ( strpos( $name, 'sqlite_' ) === 0 ) {
return $name;
}
return str_replace( '"', '', parent::tableName( $name, $format ) );
2008-05-07 23:40:14 +00:00
}
/**
* Index names have DB scope
2011-05-28 17:52:12 +00:00
*
* @param string $index
2011-05-28 17:52:12 +00:00
* @return string
*/
function indexName( $index ) {
return $index;
}
2008-05-07 23:40:14 +00:00
/**
* This must be called after nextSequenceVal
2011-05-28 17:52:12 +00:00
*
* @return int
2008-05-07 23:40:14 +00:00
*/
function insertId() {
// PDO::lastInsertId yields a string :(
return intval( $this->mConn->lastInsertId() );
2008-05-07 23:40:14 +00:00
}
2011-05-28 17:52:12 +00:00
/**
* @param ResultWrapper|array $res
* @param int $row
2011-05-28 17:52:12 +00:00
*/
2009-09-15 21:05:30 +00:00
function dataSeek( $res, $row ) {
2010-08-25 15:38:32 +00:00
if ( $res instanceof ResultWrapper ) {
2009-09-15 21:05:30 +00:00
$r =& $res->result;
2010-08-25 15:38:32 +00:00
} else {
2009-09-15 21:05:30 +00:00
$r =& $res;
2010-08-25 15:38:32 +00:00
}
2009-09-15 21:05:30 +00:00
reset( $r );
2010-08-25 15:38:32 +00:00
if ( $row > 0 ) {
for ( $i = 0; $i < $row; $i++ ) {
2009-09-15 21:05:30 +00:00
next( $r );
2010-08-25 15:38:32 +00:00
}
}
2008-05-07 23:40:14 +00:00
}
2011-05-28 17:52:12 +00:00
/**
* @return string
*/
2008-05-07 23:40:14 +00:00
function lastError() {
2010-08-25 15:38:32 +00:00
if ( !is_object( $this->mConn ) ) {
2009-09-15 21:05:30 +00:00
return "Cannot return last error, no db connection";
2010-08-25 15:38:32 +00:00
}
2008-05-07 23:40:14 +00:00
$e = $this->mConn->errorInfo();
2009-09-15 21:05:30 +00:00
return isset( $e[2] ) ? $e[2] : '';
2008-05-07 23:40:14 +00:00
}
2011-05-28 17:52:12 +00:00
/**
* @return string
*/
2008-05-07 23:40:14 +00:00
function lastErrno() {
2009-09-15 21:05:30 +00:00
if ( !is_object( $this->mConn ) ) {
return "Cannot return last error, no db connection";
} else {
$info = $this->mConn->errorInfo();
return $info[1];
}
2008-05-07 23:40:14 +00:00
}
2011-05-28 17:52:12 +00:00
/**
* @return int
*/
2008-05-07 23:40:14 +00:00
function affectedRows() {
return $this->mAffectedRows;
}
/**
* Returns information about an index
* Returns false if the index does not exist
2008-05-07 23:40:14 +00:00
* - if errors are explicitly ignored, returns NULL on failure
2011-05-28 17:52:12 +00:00
*
* @param string $table
* @param string $index
* @param string $fname
2011-05-28 17:52:12 +00:00
* @return array
2008-05-07 23:40:14 +00:00
*/
function indexInfo( $table, $index, $fname = __METHOD__ ) {
$sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
$res = $this->query( $sql, $fname );
if ( !$res ) {
return null;
}
if ( $res->numRows() == 0 ) {
return false;
}
$info = array();
foreach ( $res as $row ) {
$info[] = $row->name;
}
return $info;
2008-05-07 23:40:14 +00:00
}
2011-05-28 17:52:12 +00:00
/**
* @param string $table
* @param string $index
* @param string $fname
2011-05-28 17:52:12 +00:00
* @return bool|null
*/
function indexUnique( $table, $index, $fname = __METHOD__ ) {
2009-09-15 21:05:30 +00:00
$row = $this->selectRow( 'sqlite_master', '*',
array(
'type' => 'index',
'name' => $this->indexName( $index ),
), $fname );
if ( !$row || !isset( $row->sql ) ) {
return null;
}
// $row->sql will be of the form CREATE [UNIQUE] INDEX ...
$indexPos = strpos( $row->sql, 'INDEX' );
if ( $indexPos === false ) {
return null;
}
$firstPart = substr( $row->sql, 0, $indexPos );
$options = explode( ' ', $firstPart );
return in_array( 'UNIQUE', $options );
2008-05-07 23:40:14 +00:00
}
/**
* Filter the options used in SELECT statements
2011-05-28 17:52:12 +00:00
*
* @param array $options
2011-05-28 17:52:12 +00:00
* @return array
2008-05-07 23:40:14 +00:00
*/
2009-09-15 21:05:30 +00:00
function makeSelectOptions( $options ) {
2010-08-25 15:38:32 +00:00
foreach ( $options as $k => $v ) {
if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' || $v == 'LOCK IN SHARE MODE' ) ) {
2009-09-15 21:05:30 +00:00
$options[$k] = '';
2010-08-25 15:38:32 +00:00
}
}
2009-09-15 21:05:30 +00:00
return parent::makeSelectOptions( $options );
2008-05-07 23:40:14 +00:00
}
/**
* @param array $options
* @return string
2008-05-07 23:40:14 +00:00
*/
protected function makeUpdateOptionsArray( $options ) {
$options = parent::makeUpdateOptionsArray( $options );
$options = self::fixIgnore( $options );
return $options;
}
2008-05-07 23:40:14 +00:00
/**
* @param array $options
* @return array
*/
static function fixIgnore( $options ) {
2008-05-07 23:40:14 +00:00
# SQLite uses OR IGNORE not just IGNORE
2010-08-25 15:38:32 +00:00
foreach ( $options as $k => $v ) {
if ( $v == 'IGNORE' ) {
2009-09-15 21:05:30 +00:00
$options[$k] = 'OR IGNORE';
2010-08-25 15:38:32 +00:00
}
}
return $options;
}
/**
* @param array $options
* @return string
*/
2011-05-02 21:38:48 +00:00
function makeInsertOptions( $options ) {
$options = self::fixIgnore( $options );
return parent::makeInsertOptions( $options );
}
/**
* Based on generic method (parent) with some prior SQLite-sepcific adjustments
* @param string $table
* @param array $a
* @param string $fname
* @param array $options
2012-02-09 21:33:27 +00:00
* @return bool
*/
function insert( $table, $a, $fname = __METHOD__, $options = array() ) {
if ( !count( $a ) ) {
return true;
}
2008-05-07 23:40:14 +00:00
# SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
2009-09-15 21:05:30 +00:00
if ( isset( $a[0] ) && is_array( $a[0] ) ) {
2008-05-07 23:40:14 +00:00
$ret = true;
2010-10-14 20:53:04 +00:00
foreach ( $a as $v ) {
2010-08-25 15:38:32 +00:00
if ( !parent::insert( $table, $v, "$fname/multi-row", $options ) ) {
2009-09-15 21:05:30 +00:00
$ret = false;
2010-08-25 15:38:32 +00:00
}
}
2009-09-15 21:05:30 +00:00
} else {
$ret = parent::insert( $table, $a, "$fname/single-row", $options );
2008-05-07 23:40:14 +00:00
}
return $ret;
}
2011-05-28 17:52:12 +00:00
/**
* @param string $table
* @param array $uniqueIndexes Unused
* @param string|array $rows
* @param string $fname
2011-05-28 17:52:12 +00:00
* @return bool|ResultWrapper
*/
function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
if ( !count( $rows ) ) {
return true;
}
# SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
$ret = true;
2010-10-14 20:53:04 +00:00
foreach ( $rows as $v ) {
if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
$ret = false;
2010-08-25 15:38:32 +00:00
}
}
} else {
$ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
}
return $ret;
}
/**
* Returns the size of a text field, or -1 for "unlimited"
* In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
2011-05-28 17:52:12 +00:00
*
* @param string $table
* @param string $field
2011-05-28 17:52:12 +00:00
* @return int
*/
2009-09-15 21:05:30 +00:00
function textFieldSize( $table, $field ) {
2011-01-11 14:30:03 +00:00
return -1;
2008-05-07 23:40:14 +00:00
}
2011-05-28 17:52:12 +00:00
/**
* @return bool
*/
function unionSupportsOrderAndLimit() {
return false;
}
2011-05-28 17:52:12 +00:00
/**
* @param string $sqls
* @param bool $all Whether to "UNION ALL" or not
2011-05-28 17:52:12 +00:00
* @return string
*/
function unionQueries( $sqls, $all ) {
$glue = $all ? ' UNION ALL ' : ' UNION ';
return implode( $glue, $sqls );
}
2011-05-28 17:52:12 +00:00
/**
* @return bool
*/
2008-05-07 23:40:14 +00:00
function wasDeadlock() {
return $this->lastErrno() == 5; // SQLITE_BUSY
2008-05-07 23:40:14 +00:00
}
2011-05-28 17:52:12 +00:00
/**
* @return bool
*/
function wasErrorReissuable() {
return $this->lastErrno() == 17; // SQLITE_SCHEMA;
}
2011-05-28 17:52:12 +00:00
/**
* @return bool
*/
function wasReadOnlyError() {
return $this->lastErrno() == 8; // SQLITE_READONLY;
}
2008-05-07 23:40:14 +00:00
/**
* @return string wikitext of a link to the server software's web site
*/
public function getSoftwareLink() {
return "[{{int:version-db-sqlite-url}} SQLite]";
2008-05-07 23:40:14 +00:00
}
/**
* @return string Version information from the database
*/
function getServerVersion() {
2009-09-15 21:05:30 +00:00
$ver = $this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
return $ver;
2008-05-07 23:40:14 +00:00
}
/**
* @return string User-friendly database information
*/
public function getServerInfo() {
return wfMessage( self::getFulltextSearchModule()
? 'sqlite-has-fts'
: 'sqlite-no-fts', $this->getServerVersion() )->text();
}
/**
* Get information about a given field
* Returns false if the field does not exist.
2011-05-11 23:11:41 +00:00
*
* @param string $table
* @param string $field
2012-02-10 15:37:33 +00:00
* @return SQLiteField|bool False on failure
*/
2009-09-15 21:05:30 +00:00
function fieldInfo( $table, $field ) {
$tableName = $this->tableName( $table );
$sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
$res = $this->query( $sql, __METHOD__ );
foreach ( $res as $row ) {
if ( $row->name == $field ) {
return new SQLiteField( $row, $tableName );
}
}
return false;
}
2008-05-07 23:40:14 +00:00
protected function doBegin( $fname = '' ) {
2011-05-28 17:52:12 +00:00
if ( $this->mTrxLevel == 1 ) {
$this->commit( __METHOD__ );
2011-05-28 17:52:12 +00:00
}
try {
$this->mConn->beginTransaction();
} catch ( PDOException $e ) {
throw new DBUnexpectedError( $this, 'Error in BEGIN query: ' . $e->getMessage() );
}
2008-05-07 23:40:14 +00:00
$this->mTrxLevel = 1;
}
protected function doCommit( $fname = '' ) {
2011-05-28 17:52:12 +00:00
if ( $this->mTrxLevel == 0 ) {
return;
}
try {
$this->mConn->commit();
} catch ( PDOException $e ) {
throw new DBUnexpectedError( $this, 'Error in COMMIT query: ' . $e->getMessage() );
}
2008-05-07 23:40:14 +00:00
$this->mTrxLevel = 0;
}
protected function doRollback( $fname = '' ) {
2011-05-28 17:52:12 +00:00
if ( $this->mTrxLevel == 0 ) {
return;
}
2008-05-07 23:40:14 +00:00
$this->mConn->rollBack();
$this->mTrxLevel = 0;
}
2011-05-28 17:52:12 +00:00
/**
* @param string $s
2011-05-28 17:52:12 +00:00
* @return string
*/
2009-09-15 21:05:30 +00:00
function strencode( $s ) {
return substr( $this->addQuotes( $s ), 1, -1 );
2008-05-07 23:40:14 +00:00
}
2011-05-28 17:52:12 +00:00
/**
* @param string $b
2011-05-28 17:52:12 +00:00
* @return Blob
*/
2009-09-15 21:05:30 +00:00
function encodeBlob( $b ) {
return new Blob( $b );
2008-05-07 23:40:14 +00:00
}
2011-05-28 17:52:12 +00:00
/**
* @param Blob|string $b
2011-05-28 17:52:12 +00:00
* @return string
*/
2009-09-15 21:05:30 +00:00
function decodeBlob( $b ) {
if ( $b instanceof Blob ) {
$b = $b->fetch();
}
2008-05-07 23:40:14 +00:00
return $b;
}
2011-05-28 17:52:12 +00:00
/**
* @param Blob|string $s
2011-05-28 17:52:12 +00:00
* @return string
*/
2009-09-15 21:05:30 +00:00
function addQuotes( $s ) {
if ( $s instanceof Blob ) {
return "x'" . bin2hex( $s->fetch() ) . "'";
} elseif ( is_bool( $s ) ) {
return (int)$s;
} elseif ( strpos( $s, "\0" ) !== false ) {
// SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
// This is a known limitation of SQLite's mprintf function which PDO should work around,
// but doesn't. I have reported this to php.net as bug #63419:
// https://bugs.php.net/bug.php?id=63419
// There was already a similar report for SQLite3::escapeString, bug #62361:
// https://bugs.php.net/bug.php?id=62361
return "x'" . bin2hex( $s ) . "'";
} else {
2009-09-15 21:05:30 +00:00
return $this->mConn->quote( $s );
}
2008-05-07 23:40:14 +00:00
}
2011-05-28 17:52:12 +00:00
/**
* @return string
*/
function buildLike() {
$params = func_get_args();
if ( count( $params ) > 0 && is_array( $params[0] ) ) {
$params = $params[0];
}
return parent::buildLike( $params ) . "ESCAPE '\' ";
}
2011-05-28 17:52:12 +00:00
/**
* @return string
*/
2008-08-18 15:36:53 +00:00
public function getSearchEngine() {
return "SearchSqlite";
2008-08-18 15:36:53 +00:00
}
2008-05-07 23:40:14 +00:00
/**
* No-op version of deadlockLoop
*
2012-02-09 21:33:27 +00:00
* @return mixed
*/
public function deadlockLoop( /*...*/ ) {
$args = func_get_args();
$function = array_shift( $args );
return call_user_func_array( $function, $args );
}
2011-05-11 23:11:41 +00:00
/**
* @param string $s
2011-05-11 23:11:41 +00:00
* @return string
*/
protected function replaceVars( $s ) {
$s = parent::replaceVars( $s );
if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
// CREATE TABLE hacks to allow schema file sharing with MySQL
2009-09-15 21:05:30 +00:00
// binary/varbinary column type -> blob
$s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
// no such thing as unsigned
$s = preg_replace( '/\b(un)?signed\b/i', '', $s );
// INT -> INTEGER
$s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
// floating point types -> REAL
$s = preg_replace(
'/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
'REAL',
$s
);
// varchar -> TEXT
$s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
// TEXT normalization
$s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
// BLOB normalization
$s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
// BOOL -> INTEGER
$s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
// DATETIME -> TEXT
$s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
// No ENUM type
$s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
// binary collation type -> nothing
$s = preg_replace( '/\bbinary\b/i', '', $s );
// auto_increment -> autoincrement
$s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
// No explicit options
$s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
// AUTOINCREMENT should immedidately follow PRIMARY KEY
$s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
} elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
// No truncated indexes
$s = preg_replace( '/\(\d+\)/', '', $s );
// No FULLTEXT
$s = preg_replace( '/\bfulltext\b/i', '', $s );
} elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
// DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
$s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
}
return $s;
}
public function lock( $lockName, $method, $timeout = 5 ) {
global $wgSQLiteDataDir;
if ( !is_dir( "$wgSQLiteDataDir/locks" ) ) { // create dir as needed
if ( !is_writable( $wgSQLiteDataDir ) || !mkdir( "$wgSQLiteDataDir/locks" ) ) {
throw new DBError( "Cannot create directory \"$wgSQLiteDataDir/locks\"." );
}
}
return $this->lockMgr->lock( array( $lockName ), LockManager::LOCK_EX, $timeout )->isOK();
}
public function unlock( $lockName, $method ) {
return $this->lockMgr->unlock( array( $lockName ), LockManager::LOCK_EX )->isOK();
}
/**
* Build a concatenation list to feed into a SQL query
2011-05-11 23:11:41 +00:00
*
* @param string[] $stringList
2011-05-11 23:11:41 +00:00
* @return string
*/
function buildConcat( $stringList ) {
return '(' . implode( ') || (', $stringList ) . ')';
}
2009-06-26 15:38:43 +00:00
public function buildGroupConcatField(
$delim, $table, $field, $conds = '', $join_conds = array()
) {
$fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
}
2011-05-28 17:52:12 +00:00
/**
* @throws MWException
* @param string $oldName
* @param string $newName
* @param bool $temporary
* @param string $fname
2011-05-28 17:52:12 +00:00
* @return bool|ResultWrapper
*/
function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
$res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
$this->addQuotes( $oldName ) . " AND type='table'", $fname );
$obj = $this->fetchObject( $res );
if ( !$obj ) {
throw new MWException( "Couldn't retrieve structure for table $oldName" );
}
$sql = $obj->sql;
$sql = preg_replace(
'/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/',
$this->addIdentifierQuotes( $newName ),
$sql,
1
);
if ( $temporary ) {
2011-02-26 17:04:26 +00:00
if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
} else {
$sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
}
2011-02-26 14:30:52 +00:00
}
return $this->query( $sql, $fname );
}
/**
* List all tables on the database
*
* @param string $prefix Only show tables with this prefix, e.g. mw_
* @param string $fname Calling function name
2011-05-11 23:11:41 +00:00
*
* @return array
*/
function listTables( $prefix = null, $fname = __METHOD__ ) {
$result = $this->select(
'sqlite_master',
'name',
"type='table'"
);
$endArray = array();
foreach ( $result as $table ) {
$vars = get_object_vars( $table );
$table = array_pop( $vars );
if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
if ( strpos( $table, 'sqlite_' ) !== 0 ) {
$endArray[] = $table;
}
}
}
return $endArray;
}
} // end DatabaseSqlite class
2008-05-07 23:40:14 +00:00
/**
* This class allows simple acccess to a SQLite database independently from main database settings
* @ingroup Database
*/
class DatabaseSqliteStandalone extends DatabaseSqlite {
public function __construct( $fileName, $flags = 0 ) {
$this->mFlags = $flags;
$this->tablePrefix( null );
$this->openFile( $fileName );
}
}
2008-05-07 23:40:14 +00:00
/**
* @ingroup Database
2008-05-07 23:40:14 +00:00
*/
class SQLiteField implements Field {
private $info, $tableName;
function __construct( $info, $tableName ) {
$this->info = $info;
$this->tableName = $tableName;
}
2008-05-07 23:40:14 +00:00
function name() {
return $this->info->name;
2008-05-07 23:40:14 +00:00
}
function tableName() {
return $this->tableName;
2008-05-07 23:40:14 +00:00
}
function defaultValue() {
if ( is_string( $this->info->dflt_value ) ) {
// Typically quoted
if ( preg_match( '/^\'(.*)\'$', $this->info->dflt_value ) ) {
return str_replace( "''", "'", $this->info->dflt_value );
}
}
return $this->info->dflt_value;
}
2011-05-28 17:52:12 +00:00
/**
* @return bool
*/
function isNullable() {
2010-11-19 20:34:44 +00:00
return !$this->info->notnull;
}
function type() {
return $this->info->type;
}
} // end SQLiteField