00001 <?php
00013 class DatabaseSqlite extends DatabaseBase {
00014
00015 var $mAffectedRows;
00016 var $mLastResult;
00017 var $mDatabaseFile;
00018 var $mName;
00019
00024 function __construct( $server = false, $user = false, $password = false, $dbName = false, $failFunction = false, $flags = 0 ) {
00025 $this->mFailFunction = $failFunction;
00026 $this->mFlags = $flags;
00027 $this->mName = $dbName;
00028 $this->open( $server, $user, $password, $dbName );
00029 }
00030
00031 function getType() {
00032 return 'sqlite';
00033 }
00034
00038 function implicitGroupby() { return false; }
00039
00040 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 ) {
00041 return new DatabaseSqlite( $server, $user, $password, $dbName, $failFunction, $flags );
00042 }
00043
00047 function open( $server, $user, $pass, $dbName ) {
00048 global $wgSQLiteDataDir;
00049
00050 $fileName = self::generateFileName( $wgSQLiteDataDir, $dbName );
00051 if ( !is_readable( $fileName ) ) {
00052 throw new DBConnectionError( $this, "SQLite database not accessible" ); $this->mConn = false;
00053 }
00054 $this->openFile( $fileName );
00055 return $this->mConn;
00056 }
00057
00062 function openFile( $fileName ) {
00063 $this->mDatabaseFile = $fileName;
00064 try {
00065 if ( $this->mFlags & DBO_PERSISTENT ) {
00066 $this->mConn = new PDO( "sqlite:$fileName", '', '',
00067 array( PDO::ATTR_PERSISTENT => true ) );
00068 } else {
00069 $this->mConn = new PDO( "sqlite:$fileName", '', '' );
00070 }
00071 } catch ( PDOException $e ) {
00072 $err = $e->getMessage();
00073 }
00074 if ( $this->mConn === false ) {
00075 wfDebug( "DB connection error: $err\n" );
00076 if ( !$this->mFailFunction ) {
00077 throw new DBConnectionError( $this, $err );
00078 } else {
00079 return false;
00080 }
00081
00082 }
00083 $this->mOpened = !!$this->mConn;
00084 # set error codes only, don't raise exceptions
00085 if ( $this->mOpened ) {
00086 $this->mConn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
00087 return true;
00088 }
00089 }
00090
00094 function close() {
00095 $this->mOpened = false;
00096 if ( is_object( $this->mConn ) ) {
00097 if ( $this->trxLevel() ) $this->commit();
00098 $this->mConn = null;
00099 }
00100 return true;
00101 }
00102
00109 public static function generateFileName( $dir, $dbName ) {
00110 return "$dir/$dbName.sqlite";
00111 }
00112
00117 function getFulltextSearchModule() {
00118 $table = 'dummy_search_test';
00119 $this->query( "DROP TABLE IF EXISTS $table", __METHOD__ );
00120 if ( $this->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__, true ) ) {
00121 $this->query( "DROP TABLE IF EXISTS $table", __METHOD__ );
00122 return 'FTS3';
00123 }
00124 return false;
00125 }
00126
00130 function doQuery( $sql ) {
00131 $res = $this->mConn->query( $sql );
00132 if ( $res === false ) {
00133 return false;
00134 } else {
00135 $r = $res instanceof ResultWrapper ? $res->result : $res;
00136 $this->mAffectedRows = $r->rowCount();
00137 $res = new ResultWrapper( $this, $r->fetchAll() );
00138 }
00139 return $res;
00140 }
00141
00142 function freeResult( $res ) {
00143 if ( $res instanceof ResultWrapper )
00144 $res->result = null;
00145 else
00146 $res = null;
00147 }
00148
00149 function fetchObject( $res ) {
00150 if ( $res instanceof ResultWrapper )
00151 $r =& $res->result;
00152 else
00153 $r =& $res;
00154
00155 $cur = current( $r );
00156 if ( is_array( $cur ) ) {
00157 next( $r );
00158 $obj = new stdClass;
00159 foreach ( $cur as $k => $v )
00160 if ( !is_numeric( $k ) )
00161 $obj->$k = $v;
00162
00163 return $obj;
00164 }
00165 return false;
00166 }
00167
00168 function fetchRow( $res ) {
00169 if ( $res instanceof ResultWrapper )
00170 $r =& $res->result;
00171 else
00172 $r =& $res;
00173
00174 $cur = current( $r );
00175 if ( is_array( $cur ) ) {
00176 next( $r );
00177 return $cur;
00178 }
00179 return false;
00180 }
00181
00185 function numRows( $res ) {
00186 $r = $res instanceof ResultWrapper ? $res->result : $res;
00187 return count( $r );
00188 }
00189
00190 function numFields( $res ) {
00191 $r = $res instanceof ResultWrapper ? $res->result : $res;
00192 return is_array( $r ) ? count( $r[0] ) : 0;
00193 }
00194
00195 function fieldName( $res, $n ) {
00196 $r = $res instanceof ResultWrapper ? $res->result : $res;
00197 if ( is_array( $r ) ) {
00198 $keys = array_keys( $r[0] );
00199 return $keys[$n];
00200 }
00201 return false;
00202 }
00203
00207 function tableName( $name ) {
00208 return str_replace( '`', '', parent::tableName( $name ) );
00209 }
00210
00214 function indexName( $index ) {
00215 return $index;
00216 }
00217
00221 function insertId() {
00222 return $this->mConn->lastInsertId();
00223 }
00224
00225 function dataSeek( $res, $row ) {
00226 if ( $res instanceof ResultWrapper )
00227 $r =& $res->result;
00228 else
00229 $r =& $res;
00230 reset( $r );
00231 if ( $row > 0 )
00232 for ( $i = 0; $i < $row; $i++ )
00233 next( $r );
00234 }
00235
00236 function lastError() {
00237 if ( !is_object( $this->mConn ) )
00238 return "Cannot return last error, no db connection";
00239 $e = $this->mConn->errorInfo();
00240 return isset( $e[2] ) ? $e[2] : '';
00241 }
00242
00243 function lastErrno() {
00244 if ( !is_object( $this->mConn ) ) {
00245 return "Cannot return last error, no db connection";
00246 } else {
00247 $info = $this->mConn->errorInfo();
00248 return $info[1];
00249 }
00250 }
00251
00252 function affectedRows() {
00253 return $this->mAffectedRows;
00254 }
00255
00261 function indexInfo( $table, $index, $fname = 'DatabaseSqlite::indexExists' ) {
00262 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
00263 $res = $this->query( $sql, $fname );
00264 if ( !$res ) {
00265 return null;
00266 }
00267 if ( $res->numRows() == 0 ) {
00268 return false;
00269 }
00270 $info = array();
00271 foreach ( $res as $row ) {
00272 $info[] = $row->name;
00273 }
00274 return $info;
00275 }
00276
00277 function indexUnique( $table, $index, $fname = 'DatabaseSqlite::indexUnique' ) {
00278 $row = $this->selectRow( 'sqlite_master', '*',
00279 array(
00280 'type' => 'index',
00281 'name' => $this->indexName( $index ),
00282 ), $fname );
00283 if ( !$row || !isset( $row->sql ) ) {
00284 return null;
00285 }
00286
00287
00288 $indexPos = strpos( $row->sql, 'INDEX' );
00289 if ( $indexPos === false ) {
00290 return null;
00291 }
00292 $firstPart = substr( $row->sql, 0, $indexPos );
00293 $options = explode( ' ', $firstPart );
00294 return in_array( 'UNIQUE', $options );
00295 }
00296
00300 function makeSelectOptions( $options ) {
00301 foreach ( $options as $k => $v )
00302 if ( is_numeric( $k ) && $v == 'FOR UPDATE' )
00303 $options[$k] = '';
00304 return parent::makeSelectOptions( $options );
00305 }
00306
00310 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
00311 if ( !count( $a ) ) return true;
00312 if ( !is_array( $options ) ) $options = array( $options );
00313
00314 # SQLite uses OR IGNORE not just IGNORE
00315 foreach ( $options as $k => $v )
00316 if ( $v == 'IGNORE' )
00317 $options[$k] = 'OR IGNORE';
00318
00319 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
00320 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
00321 $ret = true;
00322 foreach ( $a as $k => $v )
00323 if ( !parent::insert( $table, $v, "$fname/multi-row", $options ) )
00324 $ret = false;
00325 } else {
00326 $ret = parent::insert( $table, $a, "$fname/single-row", $options );
00327 }
00328
00329 return $ret;
00330 }
00331
00332 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseSqlite::replace' ) {
00333 if ( !count( $rows ) ) return true;
00334
00335 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
00336 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
00337 $ret = true;
00338 foreach ( $rows as $k => $v )
00339 if ( !parent::replace( $table, $uniqueIndexes, $v, "$fname/multi-row" ) )
00340 $ret = false;
00341 } else {
00342 $ret = parent::replace( $table, $uniqueIndexes, $rows, "$fname/single-row" );
00343 }
00344
00345 return $ret;
00346 }
00347
00352 function textFieldSize( $table, $field ) {
00353 return - 1;
00354 }
00355
00356 function unionSupportsOrderAndLimit() {
00357 return false;
00358 }
00359
00360 function unionQueries( $sqls, $all ) {
00361 $glue = $all ? ' UNION ALL ' : ' UNION ';
00362 return implode( $glue, $sqls );
00363 }
00364
00365 function wasDeadlock() {
00366 return $this->lastErrno() == 5;
00367 }
00368
00369 function wasErrorReissuable() {
00370 return $this->lastErrno() == 17;
00371 }
00372
00373 function wasReadOnlyError() {
00374 return $this->lastErrno() == 8;
00375 }
00376
00380 function getSoftwareLink() {
00381 return "[http://sqlite.org/ SQLite]";
00382 }
00383
00387 function getServerVersion() {
00388 $ver = $this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
00389 return $ver;
00390 }
00391
00395 function fieldExists( $table, $field, $fname = '' ) {
00396 $info = $this->fieldInfo( $table, $field );
00397 return (bool)$info;
00398 }
00399
00404 function fieldInfo( $table, $field ) {
00405 $tableName = $this->tableName( $table );
00406 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
00407 $res = $this->query( $sql, __METHOD__ );
00408 foreach ( $res as $row ) {
00409 if ( $row->name == $field ) {
00410 return new SQLiteField( $row, $tableName );
00411 }
00412 }
00413 return false;
00414 }
00415
00416 function begin( $fname = '' ) {
00417 if ( $this->mTrxLevel == 1 ) $this->commit();
00418 $this->mConn->beginTransaction();
00419 $this->mTrxLevel = 1;
00420 }
00421
00422 function commit( $fname = '' ) {
00423 if ( $this->mTrxLevel == 0 ) return;
00424 $this->mConn->commit();
00425 $this->mTrxLevel = 0;
00426 }
00427
00428 function rollback( $fname = '' ) {
00429 if ( $this->mTrxLevel == 0 ) return;
00430 $this->mConn->rollBack();
00431 $this->mTrxLevel = 0;
00432 }
00433
00434 function limitResultForUpdate( $sql, $num ) {
00435 return $this->limitResult( $sql, $num );
00436 }
00437
00438 function strencode( $s ) {
00439 return substr( $this->addQuotes( $s ), 1, - 1 );
00440 }
00441
00442 function encodeBlob( $b ) {
00443 return new Blob( $b );
00444 }
00445
00446 function decodeBlob( $b ) {
00447 if ( $b instanceof Blob ) {
00448 $b = $b->fetch();
00449 }
00450 return $b;
00451 }
00452
00453 function addQuotes( $s ) {
00454 if ( $s instanceof Blob ) {
00455 return "x'" . bin2hex( $s->fetch() ) . "'";
00456 } else {
00457 return $this->mConn->quote( $s );
00458 }
00459 }
00460
00461 function quote_ident( $s ) {
00462 return $s;
00463 }
00464
00465 function buildLike() {
00466 $params = func_get_args();
00467 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
00468 $params = $params[0];
00469 }
00470 return parent::buildLike( $params ) . "ESCAPE '\' ";
00471 }
00472
00476 public function getLag() {
00477 return 0;
00478 }
00479
00484 public function setup_database() {
00485 global $IP;
00486
00487 # Process common MySQL/SQLite table definitions
00488 $err = $this->sourceFile( "$IP/maintenance/tables.sql" );
00489 if ( $err !== true ) {
00490 echo " <b>FAILED</b></li>";
00491 dieout( htmlspecialchars( $err ) );
00492 }
00493 echo " done.</li>";
00494
00495 # Use DatabasePostgres's code to populate interwiki from MySQL template
00496 $f = fopen( "$IP/maintenance/interwiki.sql", 'r' );
00497 if ( $f == false ) {
00498 dieout( "Could not find the interwiki.sql file." );
00499 }
00500
00501 $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
00502 while ( !feof( $f ) ) {
00503 $line = fgets( $f, 1024 );
00504 $matches = array();
00505 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) continue;
00506 $this->query( "$sql $matches[1],$matches[2])" );
00507 }
00508 }
00509
00510 public function getSearchEngine() {
00511 return "SearchSqlite";
00512 }
00513
00517 public function deadlockLoop( ) {
00518 $args = func_get_args();
00519 $function = array_shift( $args );
00520 return call_user_func_array( $function, $args );
00521 }
00522
00523 protected function replaceVars( $s ) {
00524 $s = parent::replaceVars( $s );
00525 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
00526
00527
00528
00529 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
00530
00531 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
00532
00533 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\([\s\d]*\)|\b)/i', 'INTEGER', $s );
00534
00535 $s = preg_replace( '/\bvarchar\(\d+\)/i', 'TEXT', $s );
00536
00537 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
00538
00539 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
00540
00541 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
00542
00543 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
00544
00545 $s = preg_replace( '/enum\([^)]*\)/i', 'BLOB', $s );
00546
00547 $s = preg_replace( '/\bbinary\b/i', '', $s );
00548
00549 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
00550
00551 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
00552 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
00553
00554 $s = preg_replace( '/\(\d+\)/', '', $s );
00555
00556 $s = preg_replace( '/\bfulltext\b/i', '', $s );
00557 }
00558 return $s;
00559 }
00560
00561
00562
00563
00564 function buildConcat( $stringList ) {
00565 return '(' . implode( ') || (', $stringList ) . ')';
00566 }
00567
00568 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
00569 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name='$oldName' AND type='table'", $fname );
00570 $obj = $this->fetchObject( $res );
00571 if ( !$obj ) {
00572 throw new MWException( "Couldn't retrieve structure for table $oldName" );
00573 }
00574 $sql = $obj->sql;
00575 $sql = preg_replace( '/\b' . preg_quote( $oldName ) . '\b/', $newName, $sql, 1 );
00576 return $this->query( $sql, $fname );
00577 }
00578
00579 }
00580
00585 class DatabaseSqliteStandalone extends DatabaseSqlite {
00586 public function __construct( $fileName, $flags = 0 ) {
00587 $this->mFlags = $flags;
00588 $this->openFile( $fileName );
00589 }
00590 }
00591
00595 class SQLiteField {
00596 private $info, $tableName;
00597 function __construct( $info, $tableName ) {
00598 $this->info = $info;
00599 $this->tableName = $tableName;
00600 }
00601
00602 function name() {
00603 return $this->info->name;
00604 }
00605
00606 function tableName() {
00607 return $this->tableName;
00608 }
00609
00610 function defaultValue() {
00611 if ( is_string( $this->info->dflt_value ) ) {
00612
00613 if ( preg_match( '/^\'(.*)\'$', $this->info->dflt_value ) ) {
00614 return str_replace( "''", "'", $this->info->dflt_value );
00615 }
00616 }
00617 return $this->info->dflt_value;
00618 }
00619
00620 function maxLength() {
00621 return -1;
00622 }
00623
00624 function nullable() {
00625
00626 return true;
00627 }
00628
00629 # isKey(), isMultipleKey() not implemented, MySQL-specific concept.
00630 # Suggest removal from base class [TS]
00631
00632 function type() {
00633 return $this->info->type;
00634 }
00635
00636 }