3 class DatabaseSqliteMock
extends DatabaseSqlite
{
6 public static function newInstance( array $p = [] ) {
7 $p['dbFilePath'] = ':memory:';
10 return Database
::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 [ // #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 [ // #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 $row = $re->fetchRow();
105 if ( $value instanceof Blob
) {
106 $value = $value->fetch();
109 $this->assertEquals( $value, $row[0], 'string mangled by the database' );
111 $this->fail( 'query returned no result' );
116 * @covers DatabaseSqlite::replaceVars
118 public function testReplaceVars() {
119 $this->assertEquals( 'foo', $this->replaceVars( 'foo' ), "Don't break anything accidentally" );
122 "CREATE TABLE /**/foo (foo_key INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "
123 . "foo_bar TEXT, foo_name TEXT NOT NULL DEFAULT '', foo_int INTEGER, foo_int2 INTEGER );",
125 "CREATE TABLE /**/foo (foo_key int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT, "
126 . "foo_bar char(13), foo_name varchar(255) binary NOT NULL DEFAULT '', "
127 . "foo_int tinyint ( 8 ), foo_int2 int(16) ) ENGINE=MyISAM;"
132 "CREATE TABLE foo ( foo1 REAL, foo2 REAL, foo3 REAL );",
134 "CREATE TABLE foo ( foo1 FLOAT, foo2 DOUBLE( 1,10), foo3 DOUBLE PRECISION );"
138 $this->assertEquals( "CREATE TABLE foo ( foo_binary1 BLOB, foo_binary2 BLOB );",
139 $this->replaceVars( "CREATE TABLE foo ( foo_binary1 binary(16), foo_binary2 varbinary(32) );" )
142 $this->assertEquals( "CREATE TABLE text ( text_foo TEXT );",
143 $this->replaceVars( "CREATE TABLE text ( text_foo tinytext );" ),
147 $this->assertEquals( "CREATE TABLE foo ( foobar INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL );",
148 $this->replaceVars( "CREATE TABLE foo ( foobar INT PRIMARY KEY NOT NULL AUTO_INCREMENT );" )
150 $this->assertEquals( "CREATE TABLE foo ( foobar INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL );",
151 $this->replaceVars( "CREATE TABLE foo ( foobar INT PRIMARY KEY AUTO_INCREMENT NOT NULL );" )
154 $this->assertEquals( "CREATE TABLE enums( enum1 TEXT, myenum TEXT)",
155 $this->replaceVars( "CREATE TABLE enums( enum1 ENUM('A', 'B'), myenum ENUM ('X', 'Y'))" )
158 $this->assertEquals( "ALTER TABLE foo ADD COLUMN foo_bar INTEGER DEFAULT 42",
159 $this->replaceVars( "ALTER TABLE foo\nADD COLUMN foo_bar int(10) unsigned DEFAULT 42" )
162 $this->assertEquals( "DROP INDEX foo",
163 $this->replaceVars( "DROP INDEX /*i*/foo ON /*_*/bar" )
166 $this->assertEquals( "DROP INDEX foo -- dropping index",
167 $this->replaceVars( "DROP INDEX /*i*/foo ON /*_*/bar -- dropping index" )
169 $this->assertEquals( "INSERT OR IGNORE INTO foo VALUES ('bar')",
170 $this->replaceVars( "INSERT OR IGNORE INTO foo VALUES ('bar')" )
175 * @covers DatabaseSqlite::tableName
177 public function testTableName() {
179 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
180 $this->assertEquals( 'foo', $db->tableName( 'foo' ) );
181 $this->assertEquals( 'sqlite_master', $db->tableName( 'sqlite_master' ) );
182 $db->tablePrefix( 'foo' );
183 $this->assertEquals( 'sqlite_master', $db->tableName( 'sqlite_master' ) );
184 $this->assertEquals( 'foobar', $db->tableName( 'bar' ) );
188 * @covers DatabaseSqlite::duplicateTableStructure
190 public function testDuplicateTableStructure() {
191 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
192 $db->query( 'CREATE TABLE foo(foo, barfoo)' );
193 $db->query( 'CREATE INDEX index1 ON foo(foo)' );
194 $db->query( 'CREATE UNIQUE INDEX index2 ON foo(barfoo)' );
196 $db->duplicateTableStructure( 'foo', 'bar' );
197 $this->assertEquals( 'CREATE TABLE "bar"(foo, barfoo)',
198 $db->selectField( 'sqlite_master', 'sql', [ 'name' => 'bar' ] ),
199 'Normal table duplication'
201 $indexList = $db->query( 'PRAGMA INDEX_LIST("bar")' );
202 $index = $indexList->next();
203 $this->assertEquals( 'bar_index1', $index->name
);
204 $this->assertEquals( '0', $index->unique
);
205 $index = $indexList->next();
206 $this->assertEquals( 'bar_index2', $index->name
);
207 $this->assertEquals( '1', $index->unique
);
209 $db->duplicateTableStructure( 'foo', 'baz', true );
210 $this->assertEquals( 'CREATE TABLE "baz"(foo, barfoo)',
211 $db->selectField( 'sqlite_temp_master', 'sql', [ 'name' => 'baz' ] ),
212 'Creation of temporary duplicate'
214 $indexList = $db->query( 'PRAGMA INDEX_LIST("baz")' );
215 $index = $indexList->next();
216 $this->assertEquals( 'baz_index1', $index->name
);
217 $this->assertEquals( '0', $index->unique
);
218 $index = $indexList->next();
219 $this->assertEquals( 'baz_index2', $index->name
);
220 $this->assertEquals( '1', $index->unique
);
221 $this->assertEquals( 0,
222 $db->selectField( 'sqlite_master', 'COUNT(*)', [ 'name' => 'baz' ] ),
223 'Create a temporary duplicate only'
228 * @covers DatabaseSqlite::duplicateTableStructure
230 public function testDuplicateTableStructureVirtual() {
231 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
232 if ( $db->getFulltextSearchModule() != 'FTS3' ) {
233 $this->markTestSkipped( 'FTS3 not supported, cannot create virtual tables' );
235 $db->query( 'CREATE VIRTUAL TABLE "foo" USING FTS3(foobar)' );
237 $db->duplicateTableStructure( 'foo', 'bar' );
238 $this->assertEquals( 'CREATE VIRTUAL TABLE "bar" USING FTS3(foobar)',
239 $db->selectField( 'sqlite_master', 'sql', [ 'name' => 'bar' ] ),
240 'Duplication of virtual tables'
243 $db->duplicateTableStructure( 'foo', 'baz', true );
244 $this->assertEquals( 'CREATE VIRTUAL TABLE "baz" USING FTS3(foobar)',
245 $db->selectField( 'sqlite_master', 'sql', [ 'name' => 'baz' ] ),
246 "Can't create temporary virtual tables, should fall back to non-temporary duplication"
251 * @covers DatabaseSqlite::deleteJoin
253 public function testDeleteJoin() {
254 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
255 $db->query( 'CREATE TABLE a (a_1)', __METHOD__
);
256 $db->query( 'CREATE TABLE b (b_1, b_2)', __METHOD__
);
265 [ 'b_1' => 2, 'b_2' => 'a' ],
266 [ 'b_1' => 3, 'b_2' => 'b' ],
270 $db->deleteJoin( 'a', 'b', 'a_1', 'b_1', [ 'b_2' => 'a' ], __METHOD__
);
271 $res = $db->query( "SELECT * FROM a", __METHOD__
);
272 $this->assertResultIs( [
280 public function testEntireSchema() {
283 $result = Sqlite
::checkSqlSyntax( "$IP/maintenance/tables.sql" );
284 if ( $result !== true ) {
285 $this->fail( $result );
287 $this->assertTrue( true ); // avoid test being marked as incomplete due to lack of assertions
291 * Runs upgrades of older databases and compares results with current schema
292 * @todo Currently only checks list of tables
294 public function testUpgrades() {
295 global $IP, $wgVersion, $wgProfiler;
299 // '1.13', disabled for now, was totally screwed up
300 // SQLite wasn't included in 1.14
307 // Mismatches for these columns we can safely ignore
309 'user_newtalk.user_last_timestamp', // r84185
312 $currentDB = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
313 $currentDB->sourceFile( "$IP/maintenance/tables.sql" );
315 $profileToDb = false;
316 if ( isset( $wgProfiler['output'] ) ) {
317 $out = $wgProfiler['output'];
318 if ( $out === 'db' ) {
320 } elseif ( is_array( $out ) && in_array( 'db', $out ) ) {
325 if ( $profileToDb ) {
326 $currentDB->sourceFile( "$IP/maintenance/sqlite/archives/patch-profiling.sql" );
328 $currentTables = $this->getTables( $currentDB );
329 sort( $currentTables );
331 foreach ( $versions as $version ) {
332 $versions = "upgrading from $version to $wgVersion";
333 $db = $this->prepareTestDB( $version );
334 $tables = $this->getTables( $db );
335 $this->assertEquals( $currentTables, $tables, "Different tables $versions" );
336 foreach ( $tables as $table ) {
337 $currentCols = $this->getColumns( $currentDB, $table );
338 $cols = $this->getColumns( $db, $table );
340 array_keys( $currentCols ),
342 "Mismatching columns for table \"$table\" $versions"
344 foreach ( $currentCols as $name => $column ) {
345 $fullName = "$table.$name";
348 (bool)$cols[$name]->pk
,
349 "PRIMARY KEY status does not match for column $fullName $versions"
351 if ( !in_array( $fullName, $ignoredColumns ) ) {
353 (bool)$column->notnull
,
354 (bool)$cols[$name]->notnull
,
355 "NOT NULL status does not match for column $fullName $versions"
359 $cols[$name]->dflt_value
,
360 "Default values does not match for column $fullName $versions"
364 $currentIndexes = $this->getIndexes( $currentDB, $table );
365 $indexes = $this->getIndexes( $db, $table );
367 array_keys( $currentIndexes ),
368 array_keys( $indexes ),
369 "mismatching indexes for table \"$table\" $versions"
377 * @covers DatabaseSqlite::insertId
379 public function testInsertIdType() {
380 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
382 $databaseCreation = $db->query( 'CREATE TABLE a ( a_1 )', __METHOD__
);
383 $this->assertInstanceOf( 'ResultWrapper', $databaseCreation, "Database creation" );
385 $insertion = $db->insert( 'a', [ 'a_1' => 10 ], __METHOD__
);
386 $this->assertTrue( $insertion, "Insertion worked" );
388 $this->assertInternalType( 'integer', $db->insertId(), "Actual typecheck" );
389 $this->assertTrue( $db->close(), "closing database" );
392 private function prepareTestDB( $version ) {
393 static $maint = null;
394 if ( $maint === null ) {
395 $maint = new FakeMaintenance();
396 $maint->loadParamsAndArgs( null, [ 'quiet' => 1 ] );
400 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
401 $db->sourceFile( "$IP/tests/phpunit/data/db/sqlite/tables-$version.sql" );
402 $updater = DatabaseUpdater
::newForDB( $db, false, $maint );
403 $updater->doUpdates( [ 'core' ] );
408 private function getTables( $db ) {
409 $list = array_flip( $db->listTables() );
411 'external_user', // removed from core in 1.22
412 'math', // moved out of core in 1.18
413 'trackbacks', // removed from core in 1.19
415 'searchindex_content',
416 'searchindex_segments',
417 'searchindex_segdir',
419 'searchindex_docsize',
422 foreach ( $excluded as $t ) {
425 $list = array_flip( $list );
431 private function getColumns( $db, $table ) {
433 $res = $db->query( "PRAGMA table_info($table)" );
434 $this->assertNotNull( $res );
435 foreach ( $res as $col ) {
436 $cols[$col->name
] = $col;
443 private function getIndexes( $db, $table ) {
445 $res = $db->query( "PRAGMA index_list($table)" );
446 $this->assertNotNull( $res );
447 foreach ( $res as $index ) {
448 $res2 = $db->query( "PRAGMA index_info({$index->name})" );
449 $this->assertNotNull( $res2 );
450 $index->columns
= [];
451 foreach ( $res2 as $col ) {
452 $index->columns
[] = $col;
454 $indexes[$index->name
] = $index;
461 public function testCaseInsensitiveLike() {
462 // TODO: Test this for all databases
463 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
464 $res = $db->query( 'SELECT "a" LIKE "A" AS a' );
465 $row = $res->fetchRow();
466 $this->assertFalse( (bool)$row['a'] );
470 * @covers DatabaseSqlite::numFields
472 public function testNumFields() {
473 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
475 $databaseCreation = $db->query( 'CREATE TABLE a ( a_1 )', __METHOD__
);
476 $this->assertInstanceOf( 'ResultWrapper', $databaseCreation, "Failed to create table a" );
477 $res = $db->select( 'a', '*' );
478 $this->assertEquals( 0, $db->numFields( $res ), "expects to get 0 fields for an empty table" );
479 $insertion = $db->insert( 'a', [ 'a_1' => 10 ], __METHOD__
);
480 $this->assertTrue( $insertion, "Insertion failed" );
481 $res = $db->select( 'a', '*' );
482 $this->assertEquals( 1, $db->numFields( $res ), "wrong number of fields" );
484 $this->assertTrue( $db->close(), "closing database" );
487 public function testToString() {
488 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
490 $toString = (string)$db;
492 $this->assertContains( 'SQLite ', $toString );