3 class DatabaseSqliteMock
extends DatabaseSqlite
{
6 public static function newInstance( array $p = array() ) {
7 $p['dbFilePath'] = ':memory:';
10 return DatabaseBase
::factory( 'SqliteMock', $p );
13 function query( $sql, $fname = '', $tempIgnore = false ) {
14 $this->lastQuery
= $sql;
20 * Override parent visibility to public
22 public function replaceVars( $s ) {
23 return parent
::replaceVars( $s );
32 class DatabaseSqliteTest
extends MediaWikiTestCase
{
33 /** @var DatabaseSqliteMock */
36 protected function setUp() {
39 if ( !Sqlite
::isPresent() ) {
40 $this->markTestSkipped( 'No SQLite support detected' );
42 $this->db
= DatabaseSqliteMock
::newInstance();
43 if ( version_compare( $this->db
->getServerVersion(), '3.6.0', '<' ) ) {
44 $this->markTestSkipped( "SQLite at least 3.6 required, {$this->db->getServerVersion()} found" );
48 private function replaceVars( $sql ) {
49 // normalize spacing to hide implementation details
50 return preg_replace( '/\s+/', ' ', $this->db
->replaceVars( $sql ) );
53 private function assertResultIs( $expected, $res ) {
54 $this->assertNotNull( $res );
56 foreach ( $res as $row ) {
57 foreach ( $expected[$i] as $key => $value ) {
58 $this->assertTrue( isset( $row->$key ) );
59 $this->assertEquals( $value, $row->$key );
63 $this->assertEquals( count( $expected ), $i, 'Unexpected number of rows' );
66 public static function provideAddQuotes() {
72 'foo bar', "'foo bar'"
74 array( // #2: including quote
75 'foo\'bar', "'foo''bar'"
77 // #3: including \0 (must be represented as hex, per https://bugs.php.net/bug.php?id=63419)
82 array( // #4: blob object (must be represented as hex)
90 * @dataProvider provideAddQuotes()
91 * @covers DatabaseSqlite::addQuotes
93 public function testAddQuotes( $value, $expected ) {
95 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
96 $this->assertEquals( $expected, $db->addQuotes( $value ), 'string not quoted as expected' );
98 // ok, quoting works as expected, now try a round trip.
99 $re = $db->query( 'select ' . $db->addQuotes( $value ) );
101 $this->assertTrue( $re !== false, 'query failed' );
103 if ( $row = $re->fetchRow() ) {
104 if ( $value instanceof Blob
) {
105 $value = $value->fetch();
108 $this->assertEquals( $value, $row[0], 'string mangled by the database' );
110 $this->fail( 'query returned no result' );
115 * @covers DatabaseSqlite::replaceVars
117 public function testReplaceVars() {
118 $this->assertEquals( 'foo', $this->replaceVars( 'foo' ), "Don't break anything accidentally" );
121 "CREATE TABLE /**/foo (foo_key INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "
122 . "foo_bar TEXT, foo_name TEXT NOT NULL DEFAULT '', foo_int INTEGER, foo_int2 INTEGER );",
124 "CREATE TABLE /**/foo (foo_key int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT, "
125 . "foo_bar char(13), foo_name varchar(255) binary NOT NULL DEFAULT '', "
126 . "foo_int tinyint ( 8 ), foo_int2 int(16) ) ENGINE=MyISAM;"
131 "CREATE TABLE foo ( foo1 REAL, foo2 REAL, foo3 REAL );",
133 "CREATE TABLE foo ( foo1 FLOAT, foo2 DOUBLE( 1,10), foo3 DOUBLE PRECISION );"
137 $this->assertEquals( "CREATE TABLE foo ( foo_binary1 BLOB, foo_binary2 BLOB );",
138 $this->replaceVars( "CREATE TABLE foo ( foo_binary1 binary(16), foo_binary2 varbinary(32) );" )
141 $this->assertEquals( "CREATE TABLE text ( text_foo TEXT );",
142 $this->replaceVars( "CREATE TABLE text ( text_foo tinytext );" ),
146 $this->assertEquals( "CREATE TABLE foo ( foobar INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL );",
147 $this->replaceVars( "CREATE TABLE foo ( foobar INT PRIMARY KEY NOT NULL AUTO_INCREMENT );" )
149 $this->assertEquals( "CREATE TABLE foo ( foobar INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL );",
150 $this->replaceVars( "CREATE TABLE foo ( foobar INT PRIMARY KEY AUTO_INCREMENT NOT NULL );" )
153 $this->assertEquals( "CREATE TABLE enums( enum1 TEXT, myenum TEXT)",
154 $this->replaceVars( "CREATE TABLE enums( enum1 ENUM('A', 'B'), myenum ENUM ('X', 'Y'))" )
157 $this->assertEquals( "ALTER TABLE foo ADD COLUMN foo_bar INTEGER DEFAULT 42",
158 $this->replaceVars( "ALTER TABLE foo\nADD COLUMN foo_bar int(10) unsigned DEFAULT 42" )
161 $this->assertEquals( "DROP INDEX foo",
162 $this->replaceVars( "DROP INDEX /*i*/foo ON /*_*/bar" )
165 $this->assertEquals( "DROP INDEX foo -- dropping index",
166 $this->replaceVars( "DROP INDEX /*i*/foo ON /*_*/bar -- dropping index" )
168 $this->assertEquals( "INSERT OR IGNORE INTO foo VALUES ('bar')",
169 $this->replaceVars( "INSERT OR IGNORE INTO foo VALUES ('bar')" )
174 * @covers DatabaseSqlite::tableName
176 public function testTableName() {
178 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
179 $this->assertEquals( 'foo', $db->tableName( 'foo' ) );
180 $this->assertEquals( 'sqlite_master', $db->tableName( 'sqlite_master' ) );
181 $db->tablePrefix( 'foo' );
182 $this->assertEquals( 'sqlite_master', $db->tableName( 'sqlite_master' ) );
183 $this->assertEquals( 'foobar', $db->tableName( 'bar' ) );
187 * @covers DatabaseSqlite::duplicateTableStructure
189 public function testDuplicateTableStructure() {
190 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
191 $db->query( 'CREATE TABLE foo(foo, barfoo)' );
193 $db->duplicateTableStructure( 'foo', 'bar' );
194 $this->assertEquals( 'CREATE TABLE "bar"(foo, barfoo)',
195 $db->selectField( 'sqlite_master', 'sql', array( 'name' => 'bar' ) ),
196 'Normal table duplication'
199 $db->duplicateTableStructure( 'foo', 'baz', true );
200 $this->assertEquals( 'CREATE TABLE "baz"(foo, barfoo)',
201 $db->selectField( 'sqlite_temp_master', 'sql', array( 'name' => 'baz' ) ),
202 'Creation of temporary duplicate'
204 $this->assertEquals( 0,
205 $db->selectField( 'sqlite_master', 'COUNT(*)', array( 'name' => 'baz' ) ),
206 'Create a temporary duplicate only'
211 * @covers DatabaseSqlite::duplicateTableStructure
213 public function testDuplicateTableStructureVirtual() {
214 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
215 if ( $db->getFulltextSearchModule() != 'FTS3' ) {
216 $this->markTestSkipped( 'FTS3 not supported, cannot create virtual tables' );
218 $db->query( 'CREATE VIRTUAL TABLE "foo" USING FTS3(foobar)' );
220 $db->duplicateTableStructure( 'foo', 'bar' );
221 $this->assertEquals( 'CREATE VIRTUAL TABLE "bar" USING FTS3(foobar)',
222 $db->selectField( 'sqlite_master', 'sql', array( 'name' => 'bar' ) ),
223 'Duplication of virtual tables'
226 $db->duplicateTableStructure( 'foo', 'baz', true );
227 $this->assertEquals( 'CREATE VIRTUAL TABLE "baz" USING FTS3(foobar)',
228 $db->selectField( 'sqlite_master', 'sql', array( 'name' => 'baz' ) ),
229 "Can't create temporary virtual tables, should fall back to non-temporary duplication"
234 * @covers DatabaseSqlite::deleteJoin
236 public function testDeleteJoin() {
237 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
238 $db->query( 'CREATE TABLE a (a_1)', __METHOD__
);
239 $db->query( 'CREATE TABLE b (b_1, b_2)', __METHOD__
);
240 $db->insert( 'a', array(
247 $db->insert( 'b', array(
248 array( 'b_1' => 2, 'b_2' => 'a' ),
249 array( 'b_1' => 3, 'b_2' => 'b' ),
253 $db->deleteJoin( 'a', 'b', 'a_1', 'b_1', array( 'b_2' => 'a' ), __METHOD__
);
254 $res = $db->query( "SELECT * FROM a", __METHOD__
);
255 $this->assertResultIs( array(
263 public function testEntireSchema() {
266 $result = Sqlite
::checkSqlSyntax( "$IP/maintenance/tables.sql" );
267 if ( $result !== true ) {
268 $this->fail( $result );
270 $this->assertTrue( true ); // avoid test being marked as incomplete due to lack of assertions
274 * Runs upgrades of older databases and compares results with current schema
275 * @todo Currently only checks list of tables
277 public function testUpgrades() {
278 global $IP, $wgVersion, $wgProfiler;
282 //'1.13', disabled for now, was totally screwed up
283 // SQLite wasn't included in 1.14
290 // Mismatches for these columns we can safely ignore
291 $ignoredColumns = array(
292 'user_newtalk.user_last_timestamp', // r84185
295 $currentDB = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
296 $currentDB->sourceFile( "$IP/maintenance/tables.sql" );
298 $profileToDb = false;
299 if ( isset( $wgProfiler['output'] ) ) {
300 $out = $wgProfiler['output'];
301 if ( $out === 'db' ) {
303 } elseif ( is_array( $out ) && in_array( 'db', $out ) ) {
308 if ( $profileToDb ) {
309 $currentDB->sourceFile( "$IP/maintenance/sqlite/archives/patch-profiling.sql" );
311 $currentTables = $this->getTables( $currentDB );
312 sort( $currentTables );
314 foreach ( $versions as $version ) {
315 $versions = "upgrading from $version to $wgVersion";
316 $db = $this->prepareDB( $version );
317 $tables = $this->getTables( $db );
318 $this->assertEquals( $currentTables, $tables, "Different tables $versions" );
319 foreach ( $tables as $table ) {
320 $currentCols = $this->getColumns( $currentDB, $table );
321 $cols = $this->getColumns( $db, $table );
323 array_keys( $currentCols ),
325 "Mismatching columns for table \"$table\" $versions"
327 foreach ( $currentCols as $name => $column ) {
328 $fullName = "$table.$name";
331 (bool)$cols[$name]->pk
,
332 "PRIMARY KEY status does not match for column $fullName $versions"
334 if ( !in_array( $fullName, $ignoredColumns ) ) {
336 (bool)$column->notnull
,
337 (bool)$cols[$name]->notnull
,
338 "NOT NULL status does not match for column $fullName $versions"
342 $cols[$name]->dflt_value
,
343 "Default values does not match for column $fullName $versions"
347 $currentIndexes = $this->getIndexes( $currentDB, $table );
348 $indexes = $this->getIndexes( $db, $table );
350 array_keys( $currentIndexes ),
351 array_keys( $indexes ),
352 "mismatching indexes for table \"$table\" $versions"
360 * @covers DatabaseSqlite::insertId
362 public function testInsertIdType() {
363 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
365 $databaseCreation = $db->query( 'CREATE TABLE a ( a_1 )', __METHOD__
);
366 $this->assertInstanceOf( 'ResultWrapper', $databaseCreation, "Database creation" );
368 $insertion = $db->insert( 'a', array( 'a_1' => 10 ), __METHOD__
);
369 $this->assertTrue( $insertion, "Insertion worked" );
371 $this->assertInternalType( 'integer', $db->insertId(), "Actual typecheck" );
372 $this->assertTrue( $db->close(), "closing database" );
375 private function prepareDB( $version ) {
376 static $maint = null;
377 if ( $maint === null ) {
378 $maint = new FakeMaintenance();
379 $maint->loadParamsAndArgs( null, array( 'quiet' => 1 ) );
383 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
384 $db->sourceFile( "$IP/tests/phpunit/data/db/sqlite/tables-$version.sql" );
385 $updater = DatabaseUpdater
::newForDB( $db, false, $maint );
386 $updater->doUpdates( array( 'core' ) );
391 private function getTables( $db ) {
392 $list = array_flip( $db->listTables() );
394 'external_user', // removed from core in 1.22
395 'math', // moved out of core in 1.18
396 'trackbacks', // removed from core in 1.19
398 'searchindex_content',
399 'searchindex_segments',
400 'searchindex_segdir',
402 'searchindex_docsize',
405 foreach ( $excluded as $t ) {
408 $list = array_flip( $list );
414 private function getColumns( $db, $table ) {
416 $res = $db->query( "PRAGMA table_info($table)" );
417 $this->assertNotNull( $res );
418 foreach ( $res as $col ) {
419 $cols[$col->name
] = $col;
426 private function getIndexes( $db, $table ) {
428 $res = $db->query( "PRAGMA index_list($table)" );
429 $this->assertNotNull( $res );
430 foreach ( $res as $index ) {
431 $res2 = $db->query( "PRAGMA index_info({$index->name})" );
432 $this->assertNotNull( $res2 );
433 $index->columns
= array();
434 foreach ( $res2 as $col ) {
435 $index->columns
[] = $col;
437 $indexes[$index->name
] = $index;
444 public function testCaseInsensitiveLike() {
445 // TODO: Test this for all databases
446 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
447 $res = $db->query( 'SELECT "a" LIKE "A" AS a' );
448 $row = $res->fetchRow();
449 $this->assertFalse( (bool)$row['a'] );
453 * @covers DatabaseSqlite::numFields
455 public function testNumFields() {
456 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
458 $databaseCreation = $db->query( 'CREATE TABLE a ( a_1 )', __METHOD__
);
459 $this->assertInstanceOf( 'ResultWrapper', $databaseCreation, "Failed to create table a" );
460 $res = $db->select( 'a', '*' );
461 $this->assertEquals( 0, $db->numFields( $res ), "expects to get 0 fields for an empty table" );
462 $insertion = $db->insert( 'a', array( 'a_1' => 10 ), __METHOD__
);
463 $this->assertTrue( $insertion, "Insertion failed" );
464 $res = $db->select( 'a', '*' );
465 $this->assertEquals( 1, $db->numFields( $res ), "wrong number of fields" );
467 $this->assertTrue( $db->close(), "closing database" );