3 use Wikimedia\Rdbms\Blob
;
4 use Wikimedia\Rdbms\Database
;
5 use Wikimedia\Rdbms\DatabaseSqlite
;
6 use Wikimedia\Rdbms\ResultWrapper
;
8 class DatabaseSqliteMock
extends DatabaseSqlite
{
9 public static function newInstance( array $p = [] ) {
10 $p['dbFilePath'] = ':memory:';
13 return Database
::factory( 'SqliteMock', $p );
16 function query( $sql, $fname = '', $tempIgnore = false ) {
21 * Override parent visibility to public
23 public function replaceVars( $s ) {
24 return parent
::replaceVars( $s );
33 class DatabaseSqliteTest
extends MediaWikiTestCase
{
34 /** @var DatabaseSqliteMock */
37 protected function setUp() {
40 if ( !Sqlite
::isPresent() ) {
41 $this->markTestSkipped( 'No SQLite support detected' );
43 $this->db
= DatabaseSqliteMock
::newInstance();
44 if ( version_compare( $this->db
->getServerVersion(), '3.6.0', '<' ) ) {
45 $this->markTestSkipped( "SQLite at least 3.6 required, {$this->db->getServerVersion()} found" );
49 private function replaceVars( $sql ) {
50 // normalize spacing to hide implementation details
51 return preg_replace( '/\s+/', ' ', $this->db
->replaceVars( $sql ) );
54 private function assertResultIs( $expected, $res ) {
55 $this->assertNotNull( $res );
57 foreach ( $res as $row ) {
58 foreach ( $expected[$i] as $key => $value ) {
59 $this->assertTrue( isset( $row->$key ) );
60 $this->assertEquals( $value, $row->$key );
64 $this->assertEquals( count( $expected ), $i, 'Unexpected number of rows' );
67 public static function provideAddQuotes() {
73 'foo bar', "'foo bar'"
75 [ // #2: including quote
76 'foo\'bar', "'foo''bar'"
78 // #3: including \0 (must be represented as hex, per https://bugs.php.net/bug.php?id=63419)
83 [ // #4: blob object (must be represented as hex)
95 * @dataProvider provideAddQuotes()
96 * @covers DatabaseSqlite::addQuotes
98 public function testAddQuotes( $value, $expected ) {
100 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
101 $this->assertEquals( $expected, $db->addQuotes( $value ), 'string not quoted as expected' );
103 // ok, quoting works as expected, now try a round trip.
104 $re = $db->query( 'select ' . $db->addQuotes( $value ) );
106 $this->assertTrue( $re !== false, 'query failed' );
108 $row = $re->fetchRow();
110 if ( $value instanceof Blob
) {
111 $value = $value->fetch();
114 $this->assertEquals( $value, $row[0], 'string mangled by the database' );
116 $this->fail( 'query returned no result' );
121 * @covers DatabaseSqlite::replaceVars
123 public function testReplaceVars() {
124 $this->assertEquals( 'foo', $this->replaceVars( 'foo' ), "Don't break anything accidentally" );
127 "CREATE TABLE /**/foo (foo_key INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "
128 . "foo_bar TEXT, foo_name TEXT NOT NULL DEFAULT '', foo_int INTEGER, foo_int2 INTEGER );",
130 "CREATE TABLE /**/foo (foo_key int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT, "
131 . "foo_bar char(13), foo_name varchar(255) binary NOT NULL DEFAULT '', "
132 . "foo_int tinyint ( 8 ), foo_int2 int(16) ) ENGINE=MyISAM;"
137 "CREATE TABLE foo ( foo1 REAL, foo2 REAL, foo3 REAL );",
139 "CREATE TABLE foo ( foo1 FLOAT, foo2 DOUBLE( 1,10), foo3 DOUBLE PRECISION );"
143 $this->assertEquals( "CREATE TABLE foo ( foo_binary1 BLOB, foo_binary2 BLOB );",
144 $this->replaceVars( "CREATE TABLE foo ( foo_binary1 binary(16), foo_binary2 varbinary(32) );" )
147 $this->assertEquals( "CREATE TABLE text ( text_foo TEXT );",
148 $this->replaceVars( "CREATE TABLE text ( text_foo tinytext );" ),
152 $this->assertEquals( "CREATE TABLE foo ( foobar INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL );",
153 $this->replaceVars( "CREATE TABLE foo ( foobar INT PRIMARY KEY NOT NULL AUTO_INCREMENT );" )
155 $this->assertEquals( "CREATE TABLE foo ( foobar INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL );",
156 $this->replaceVars( "CREATE TABLE foo ( foobar INT PRIMARY KEY AUTO_INCREMENT NOT NULL );" )
159 $this->assertEquals( "CREATE TABLE enums( enum1 TEXT, myenum TEXT)",
160 $this->replaceVars( "CREATE TABLE enums( enum1 ENUM('A', 'B'), myenum ENUM ('X', 'Y'))" )
163 $this->assertEquals( "ALTER TABLE foo ADD COLUMN foo_bar INTEGER DEFAULT 42",
164 $this->replaceVars( "ALTER TABLE foo\nADD COLUMN foo_bar int(10) unsigned DEFAULT 42" )
167 $this->assertEquals( "DROP INDEX foo",
168 $this->replaceVars( "DROP INDEX /*i*/foo ON /*_*/bar" )
171 $this->assertEquals( "DROP INDEX foo -- dropping index",
172 $this->replaceVars( "DROP INDEX /*i*/foo ON /*_*/bar -- dropping index" )
174 $this->assertEquals( "INSERT OR IGNORE INTO foo VALUES ('bar')",
175 $this->replaceVars( "INSERT OR IGNORE INTO foo VALUES ('bar')" )
180 * @covers DatabaseSqlite::tableName
182 public function testTableName() {
184 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
185 $this->assertEquals( 'foo', $db->tableName( 'foo' ) );
186 $this->assertEquals( 'sqlite_master', $db->tableName( 'sqlite_master' ) );
187 $db->tablePrefix( 'foo' );
188 $this->assertEquals( 'sqlite_master', $db->tableName( 'sqlite_master' ) );
189 $this->assertEquals( 'foobar', $db->tableName( 'bar' ) );
193 * @covers DatabaseSqlite::duplicateTableStructure
195 public function testDuplicateTableStructure() {
196 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
197 $db->query( 'CREATE TABLE foo(foo, barfoo)' );
198 $db->query( 'CREATE INDEX index1 ON foo(foo)' );
199 $db->query( 'CREATE UNIQUE INDEX index2 ON foo(barfoo)' );
201 $db->duplicateTableStructure( 'foo', 'bar' );
202 $this->assertEquals( 'CREATE TABLE "bar"(foo, barfoo)',
203 $db->selectField( 'sqlite_master', 'sql', [ 'name' => 'bar' ] ),
204 'Normal table duplication'
206 $indexList = $db->query( 'PRAGMA INDEX_LIST("bar")' );
207 $index = $indexList->next();
208 $this->assertEquals( 'bar_index1', $index->name
);
209 $this->assertEquals( '0', $index->unique
);
210 $index = $indexList->next();
211 $this->assertEquals( 'bar_index2', $index->name
);
212 $this->assertEquals( '1', $index->unique
);
214 $db->duplicateTableStructure( 'foo', 'baz', true );
215 $this->assertEquals( 'CREATE TABLE "baz"(foo, barfoo)',
216 $db->selectField( 'sqlite_temp_master', 'sql', [ 'name' => 'baz' ] ),
217 'Creation of temporary duplicate'
219 $indexList = $db->query( 'PRAGMA INDEX_LIST("baz")' );
220 $index = $indexList->next();
221 $this->assertEquals( 'baz_index1', $index->name
);
222 $this->assertEquals( '0', $index->unique
);
223 $index = $indexList->next();
224 $this->assertEquals( 'baz_index2', $index->name
);
225 $this->assertEquals( '1', $index->unique
);
226 $this->assertEquals( 0,
227 $db->selectField( 'sqlite_master', 'COUNT(*)', [ 'name' => 'baz' ] ),
228 'Create a temporary duplicate only'
233 * @covers DatabaseSqlite::duplicateTableStructure
235 public function testDuplicateTableStructureVirtual() {
236 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
237 if ( $db->getFulltextSearchModule() != 'FTS3' ) {
238 $this->markTestSkipped( 'FTS3 not supported, cannot create virtual tables' );
240 $db->query( 'CREATE VIRTUAL TABLE "foo" USING FTS3(foobar)' );
242 $db->duplicateTableStructure( 'foo', 'bar' );
243 $this->assertEquals( 'CREATE VIRTUAL TABLE "bar" USING FTS3(foobar)',
244 $db->selectField( 'sqlite_master', 'sql', [ 'name' => 'bar' ] ),
245 'Duplication of virtual tables'
248 $db->duplicateTableStructure( 'foo', 'baz', true );
249 $this->assertEquals( 'CREATE VIRTUAL TABLE "baz" USING FTS3(foobar)',
250 $db->selectField( 'sqlite_master', 'sql', [ 'name' => 'baz' ] ),
251 "Can't create temporary virtual tables, should fall back to non-temporary duplication"
256 * @covers DatabaseSqlite::deleteJoin
258 public function testDeleteJoin() {
259 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
260 $db->query( 'CREATE TABLE a (a_1)', __METHOD__
);
261 $db->query( 'CREATE TABLE b (b_1, b_2)', __METHOD__
);
270 [ 'b_1' => 2, 'b_2' => 'a' ],
271 [ 'b_1' => 3, 'b_2' => 'b' ],
275 $db->deleteJoin( 'a', 'b', 'a_1', 'b_1', [ 'b_2' => 'a' ], __METHOD__
);
276 $res = $db->query( "SELECT * FROM a", __METHOD__
);
277 $this->assertResultIs( [
288 public function testEntireSchema() {
291 $result = Sqlite
::checkSqlSyntax( "$IP/maintenance/tables.sql" );
292 if ( $result !== true ) {
293 $this->fail( $result );
295 $this->assertTrue( true ); // avoid test being marked as incomplete due to lack of assertions
299 * Runs upgrades of older databases and compares results with current schema
300 * @todo Currently only checks list of tables
303 public function testUpgrades() {
304 global $IP, $wgVersion, $wgProfiler;
308 // '1.13', disabled for now, was totally screwed up
309 // SQLite wasn't included in 1.14
321 // Mismatches for these columns we can safely ignore
323 'user_newtalk.user_last_timestamp', // r84185
326 $currentDB = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
327 $currentDB->sourceFile( "$IP/maintenance/tables.sql" );
329 $profileToDb = false;
330 if ( isset( $wgProfiler['output'] ) ) {
331 $out = $wgProfiler['output'];
332 if ( $out === 'db' ) {
334 } elseif ( is_array( $out ) && in_array( 'db', $out ) ) {
339 if ( $profileToDb ) {
340 $currentDB->sourceFile( "$IP/maintenance/sqlite/archives/patch-profiling.sql" );
342 $currentTables = $this->getTables( $currentDB );
343 sort( $currentTables );
345 foreach ( $versions as $version ) {
346 $versions = "upgrading from $version to $wgVersion";
347 $db = $this->prepareTestDB( $version );
348 $tables = $this->getTables( $db );
349 $this->assertEquals( $currentTables, $tables, "Different tables $versions" );
350 foreach ( $tables as $table ) {
351 $currentCols = $this->getColumns( $currentDB, $table );
352 $cols = $this->getColumns( $db, $table );
354 array_keys( $currentCols ),
356 "Mismatching columns for table \"$table\" $versions"
358 foreach ( $currentCols as $name => $column ) {
359 $fullName = "$table.$name";
362 (bool)$cols[$name]->pk
,
363 "PRIMARY KEY status does not match for column $fullName $versions"
365 if ( !in_array( $fullName, $ignoredColumns ) ) {
367 (bool)$column->notnull
,
368 (bool)$cols[$name]->notnull
,
369 "NOT NULL status does not match for column $fullName $versions"
373 $cols[$name]->dflt_value
,
374 "Default values does not match for column $fullName $versions"
378 $currentIndexes = $this->getIndexes( $currentDB, $table );
379 $indexes = $this->getIndexes( $db, $table );
381 array_keys( $currentIndexes ),
382 array_keys( $indexes ),
383 "mismatching indexes for table \"$table\" $versions"
391 * @covers DatabaseSqlite::insertId
393 public function testInsertIdType() {
394 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
396 $databaseCreation = $db->query( 'CREATE TABLE a ( a_1 )', __METHOD__
);
397 $this->assertInstanceOf( ResultWrapper
::class, $databaseCreation, "Database creation" );
399 $insertion = $db->insert( 'a', [ 'a_1' => 10 ], __METHOD__
);
400 $this->assertTrue( $insertion, "Insertion worked" );
402 $this->assertInternalType( 'integer', $db->insertId(), "Actual typecheck" );
403 $this->assertTrue( $db->close(), "closing database" );
406 private function prepareTestDB( $version ) {
407 static $maint = null;
408 if ( $maint === null ) {
409 $maint = new FakeMaintenance();
410 $maint->loadParamsAndArgs( null, [ 'quiet' => 1 ] );
414 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
415 $db->sourceFile( "$IP/tests/phpunit/data/db/sqlite/tables-$version.sql" );
416 $updater = DatabaseUpdater
::newForDB( $db, false, $maint );
417 $updater->doUpdates( [ 'core' ] );
422 private function getTables( $db ) {
423 $list = array_flip( $db->listTables() );
425 'external_user', // removed from core in 1.22
426 'math', // moved out of core in 1.18
427 'trackbacks', // removed from core in 1.19
429 'searchindex_content',
430 'searchindex_segments',
431 'searchindex_segdir',
433 'searchindex_docsize',
436 foreach ( $excluded as $t ) {
439 $list = array_flip( $list );
445 private function getColumns( $db, $table ) {
447 $res = $db->query( "PRAGMA table_info($table)" );
448 $this->assertNotNull( $res );
449 foreach ( $res as $col ) {
450 $cols[$col->name
] = $col;
457 private function getIndexes( $db, $table ) {
459 $res = $db->query( "PRAGMA index_list($table)" );
460 $this->assertNotNull( $res );
461 foreach ( $res as $index ) {
462 $res2 = $db->query( "PRAGMA index_info({$index->name})" );
463 $this->assertNotNull( $res2 );
464 $index->columns
= [];
465 foreach ( $res2 as $col ) {
466 $index->columns
[] = $col;
468 $indexes[$index->name
] = $index;
475 public function testCaseInsensitiveLike() {
476 // TODO: Test this for all databases
477 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
478 $res = $db->query( 'SELECT "a" LIKE "A" AS a' );
479 $row = $res->fetchRow();
480 $this->assertFalse( (bool)$row['a'] );
484 * @covers DatabaseSqlite::numFields
486 public function testNumFields() {
487 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
489 $databaseCreation = $db->query( 'CREATE TABLE a ( a_1 )', __METHOD__
);
490 $this->assertInstanceOf( ResultWrapper
::class, $databaseCreation, "Failed to create table a" );
491 $res = $db->select( 'a', '*' );
492 $this->assertEquals( 0, $db->numFields( $res ), "expects to get 0 fields for an empty table" );
493 $insertion = $db->insert( 'a', [ 'a_1' => 10 ], __METHOD__
);
494 $this->assertTrue( $insertion, "Insertion failed" );
495 $res = $db->select( 'a', '*' );
496 $this->assertEquals( 1, $db->numFields( $res ), "wrong number of fields" );
498 $this->assertTrue( $db->close(), "closing database" );
502 * @covers \Wikimedia\Rdbms\DatabaseSqlite::__toString
504 public function testToString() {
505 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
507 $toString = (string)$db;
509 $this->assertContains( 'SQLite ', $toString );
513 * @covers \Wikimedia\Rdbms\DatabaseSqlite::getAttributes()
515 public function testsAttributes() {
516 $attributes = Database
::attributesFromType( 'sqlite' );
517 $this->assertTrue( $attributes[Database
::ATTR_DB_LEVEL_LOCKING
] );