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
{
11 public static function newInstance( array $p = [] ) {
12 $p['dbFilePath'] = ':memory:';
15 return Database
::factory( 'SqliteMock', $p );
18 function query( $sql, $fname = '', $tempIgnore = false ) {
19 $this->lastQuery
= $sql;
25 * Override parent visibility to public
27 public function replaceVars( $s ) {
28 return parent
::replaceVars( $s );
37 class DatabaseSqliteTest
extends MediaWikiTestCase
{
38 /** @var DatabaseSqliteMock */
41 protected function setUp() {
44 if ( !Sqlite
::isPresent() ) {
45 $this->markTestSkipped( 'No SQLite support detected' );
47 $this->db
= DatabaseSqliteMock
::newInstance();
48 if ( version_compare( $this->db
->getServerVersion(), '3.6.0', '<' ) ) {
49 $this->markTestSkipped( "SQLite at least 3.6 required, {$this->db->getServerVersion()} found" );
53 private function replaceVars( $sql ) {
54 // normalize spacing to hide implementation details
55 return preg_replace( '/\s+/', ' ', $this->db
->replaceVars( $sql ) );
58 private function assertResultIs( $expected, $res ) {
59 $this->assertNotNull( $res );
61 foreach ( $res as $row ) {
62 foreach ( $expected[$i] as $key => $value ) {
63 $this->assertTrue( isset( $row->$key ) );
64 $this->assertEquals( $value, $row->$key );
68 $this->assertEquals( count( $expected ), $i, 'Unexpected number of rows' );
71 public static function provideAddQuotes() {
77 'foo bar', "'foo bar'"
79 [ // #2: including quote
80 'foo\'bar', "'foo''bar'"
82 // #3: including \0 (must be represented as hex, per https://bugs.php.net/bug.php?id=63419)
87 [ // #4: blob object (must be represented as hex)
99 * @dataProvider provideAddQuotes()
100 * @covers DatabaseSqlite::addQuotes
102 public function testAddQuotes( $value, $expected ) {
104 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
105 $this->assertEquals( $expected, $db->addQuotes( $value ), 'string not quoted as expected' );
107 // ok, quoting works as expected, now try a round trip.
108 $re = $db->query( 'select ' . $db->addQuotes( $value ) );
110 $this->assertTrue( $re !== false, 'query failed' );
112 $row = $re->fetchRow();
114 if ( $value instanceof Blob
) {
115 $value = $value->fetch();
118 $this->assertEquals( $value, $row[0], 'string mangled by the database' );
120 $this->fail( 'query returned no result' );
125 * @covers DatabaseSqlite::replaceVars
127 public function testReplaceVars() {
128 $this->assertEquals( 'foo', $this->replaceVars( 'foo' ), "Don't break anything accidentally" );
131 "CREATE TABLE /**/foo (foo_key INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "
132 . "foo_bar TEXT, foo_name TEXT NOT NULL DEFAULT '', foo_int INTEGER, foo_int2 INTEGER );",
134 "CREATE TABLE /**/foo (foo_key int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT, "
135 . "foo_bar char(13), foo_name varchar(255) binary NOT NULL DEFAULT '', "
136 . "foo_int tinyint ( 8 ), foo_int2 int(16) ) ENGINE=MyISAM;"
141 "CREATE TABLE foo ( foo1 REAL, foo2 REAL, foo3 REAL );",
143 "CREATE TABLE foo ( foo1 FLOAT, foo2 DOUBLE( 1,10), foo3 DOUBLE PRECISION );"
147 $this->assertEquals( "CREATE TABLE foo ( foo_binary1 BLOB, foo_binary2 BLOB );",
148 $this->replaceVars( "CREATE TABLE foo ( foo_binary1 binary(16), foo_binary2 varbinary(32) );" )
151 $this->assertEquals( "CREATE TABLE text ( text_foo TEXT );",
152 $this->replaceVars( "CREATE TABLE text ( text_foo tinytext );" ),
156 $this->assertEquals( "CREATE TABLE foo ( foobar INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL );",
157 $this->replaceVars( "CREATE TABLE foo ( foobar INT PRIMARY KEY NOT NULL AUTO_INCREMENT );" )
159 $this->assertEquals( "CREATE TABLE foo ( foobar INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL );",
160 $this->replaceVars( "CREATE TABLE foo ( foobar INT PRIMARY KEY AUTO_INCREMENT NOT NULL );" )
163 $this->assertEquals( "CREATE TABLE enums( enum1 TEXT, myenum TEXT)",
164 $this->replaceVars( "CREATE TABLE enums( enum1 ENUM('A', 'B'), myenum ENUM ('X', 'Y'))" )
167 $this->assertEquals( "ALTER TABLE foo ADD COLUMN foo_bar INTEGER DEFAULT 42",
168 $this->replaceVars( "ALTER TABLE foo\nADD COLUMN foo_bar int(10) unsigned DEFAULT 42" )
171 $this->assertEquals( "DROP INDEX foo",
172 $this->replaceVars( "DROP INDEX /*i*/foo ON /*_*/bar" )
175 $this->assertEquals( "DROP INDEX foo -- dropping index",
176 $this->replaceVars( "DROP INDEX /*i*/foo ON /*_*/bar -- dropping index" )
178 $this->assertEquals( "INSERT OR IGNORE INTO foo VALUES ('bar')",
179 $this->replaceVars( "INSERT OR IGNORE INTO foo VALUES ('bar')" )
184 * @covers DatabaseSqlite::tableName
186 public function testTableName() {
188 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
189 $this->assertEquals( 'foo', $db->tableName( 'foo' ) );
190 $this->assertEquals( 'sqlite_master', $db->tableName( 'sqlite_master' ) );
191 $db->tablePrefix( 'foo' );
192 $this->assertEquals( 'sqlite_master', $db->tableName( 'sqlite_master' ) );
193 $this->assertEquals( 'foobar', $db->tableName( 'bar' ) );
197 * @covers DatabaseSqlite::duplicateTableStructure
199 public function testDuplicateTableStructure() {
200 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
201 $db->query( 'CREATE TABLE foo(foo, barfoo)' );
202 $db->query( 'CREATE INDEX index1 ON foo(foo)' );
203 $db->query( 'CREATE UNIQUE INDEX index2 ON foo(barfoo)' );
205 $db->duplicateTableStructure( 'foo', 'bar' );
206 $this->assertEquals( 'CREATE TABLE "bar"(foo, barfoo)',
207 $db->selectField( 'sqlite_master', 'sql', [ 'name' => 'bar' ] ),
208 'Normal table duplication'
210 $indexList = $db->query( 'PRAGMA INDEX_LIST("bar")' );
211 $index = $indexList->next();
212 $this->assertEquals( 'bar_index1', $index->name
);
213 $this->assertEquals( '0', $index->unique
);
214 $index = $indexList->next();
215 $this->assertEquals( 'bar_index2', $index->name
);
216 $this->assertEquals( '1', $index->unique
);
218 $db->duplicateTableStructure( 'foo', 'baz', true );
219 $this->assertEquals( 'CREATE TABLE "baz"(foo, barfoo)',
220 $db->selectField( 'sqlite_temp_master', 'sql', [ 'name' => 'baz' ] ),
221 'Creation of temporary duplicate'
223 $indexList = $db->query( 'PRAGMA INDEX_LIST("baz")' );
224 $index = $indexList->next();
225 $this->assertEquals( 'baz_index1', $index->name
);
226 $this->assertEquals( '0', $index->unique
);
227 $index = $indexList->next();
228 $this->assertEquals( 'baz_index2', $index->name
);
229 $this->assertEquals( '1', $index->unique
);
230 $this->assertEquals( 0,
231 $db->selectField( 'sqlite_master', 'COUNT(*)', [ 'name' => 'baz' ] ),
232 'Create a temporary duplicate only'
237 * @covers DatabaseSqlite::duplicateTableStructure
239 public function testDuplicateTableStructureVirtual() {
240 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
241 if ( $db->getFulltextSearchModule() != 'FTS3' ) {
242 $this->markTestSkipped( 'FTS3 not supported, cannot create virtual tables' );
244 $db->query( 'CREATE VIRTUAL TABLE "foo" USING FTS3(foobar)' );
246 $db->duplicateTableStructure( 'foo', 'bar' );
247 $this->assertEquals( 'CREATE VIRTUAL TABLE "bar" USING FTS3(foobar)',
248 $db->selectField( 'sqlite_master', 'sql', [ 'name' => 'bar' ] ),
249 'Duplication of virtual tables'
252 $db->duplicateTableStructure( 'foo', 'baz', true );
253 $this->assertEquals( 'CREATE VIRTUAL TABLE "baz" USING FTS3(foobar)',
254 $db->selectField( 'sqlite_master', 'sql', [ 'name' => 'baz' ] ),
255 "Can't create temporary virtual tables, should fall back to non-temporary duplication"
260 * @covers DatabaseSqlite::deleteJoin
262 public function testDeleteJoin() {
263 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
264 $db->query( 'CREATE TABLE a (a_1)', __METHOD__
);
265 $db->query( 'CREATE TABLE b (b_1, b_2)', __METHOD__
);
274 [ 'b_1' => 2, 'b_2' => 'a' ],
275 [ 'b_1' => 3, 'b_2' => 'b' ],
279 $db->deleteJoin( 'a', 'b', 'a_1', 'b_1', [ 'b_2' => 'a' ], __METHOD__
);
280 $res = $db->query( "SELECT * FROM a", __METHOD__
);
281 $this->assertResultIs( [
292 public function testEntireSchema() {
295 $result = Sqlite
::checkSqlSyntax( "$IP/maintenance/tables.sql" );
296 if ( $result !== true ) {
297 $this->fail( $result );
299 $this->assertTrue( true ); // avoid test being marked as incomplete due to lack of assertions
303 * Runs upgrades of older databases and compares results with current schema
304 * @todo Currently only checks list of tables
307 public function testUpgrades() {
308 global $IP, $wgVersion, $wgProfiler;
312 // '1.13', disabled for now, was totally screwed up
313 // SQLite wasn't included in 1.14
325 // Mismatches for these columns we can safely ignore
327 'user_newtalk.user_last_timestamp', // r84185
330 $currentDB = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
331 $currentDB->sourceFile( "$IP/maintenance/tables.sql" );
333 $profileToDb = false;
334 if ( isset( $wgProfiler['output'] ) ) {
335 $out = $wgProfiler['output'];
336 if ( $out === 'db' ) {
338 } elseif ( is_array( $out ) && in_array( 'db', $out ) ) {
343 if ( $profileToDb ) {
344 $currentDB->sourceFile( "$IP/maintenance/sqlite/archives/patch-profiling.sql" );
346 $currentTables = $this->getTables( $currentDB );
347 sort( $currentTables );
349 foreach ( $versions as $version ) {
350 $versions = "upgrading from $version to $wgVersion";
351 $db = $this->prepareTestDB( $version );
352 $tables = $this->getTables( $db );
353 $this->assertEquals( $currentTables, $tables, "Different tables $versions" );
354 foreach ( $tables as $table ) {
355 $currentCols = $this->getColumns( $currentDB, $table );
356 $cols = $this->getColumns( $db, $table );
358 array_keys( $currentCols ),
360 "Mismatching columns for table \"$table\" $versions"
362 foreach ( $currentCols as $name => $column ) {
363 $fullName = "$table.$name";
366 (bool)$cols[$name]->pk
,
367 "PRIMARY KEY status does not match for column $fullName $versions"
369 if ( !in_array( $fullName, $ignoredColumns ) ) {
371 (bool)$column->notnull
,
372 (bool)$cols[$name]->notnull
,
373 "NOT NULL status does not match for column $fullName $versions"
377 $cols[$name]->dflt_value
,
378 "Default values does not match for column $fullName $versions"
382 $currentIndexes = $this->getIndexes( $currentDB, $table );
383 $indexes = $this->getIndexes( $db, $table );
385 array_keys( $currentIndexes ),
386 array_keys( $indexes ),
387 "mismatching indexes for table \"$table\" $versions"
395 * @covers DatabaseSqlite::insertId
397 public function testInsertIdType() {
398 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
400 $databaseCreation = $db->query( 'CREATE TABLE a ( a_1 )', __METHOD__
);
401 $this->assertInstanceOf( ResultWrapper
::class, $databaseCreation, "Database creation" );
403 $insertion = $db->insert( 'a', [ 'a_1' => 10 ], __METHOD__
);
404 $this->assertTrue( $insertion, "Insertion worked" );
406 $this->assertInternalType( 'integer', $db->insertId(), "Actual typecheck" );
407 $this->assertTrue( $db->close(), "closing database" );
410 private function prepareTestDB( $version ) {
411 static $maint = null;
412 if ( $maint === null ) {
413 $maint = new FakeMaintenance();
414 $maint->loadParamsAndArgs( null, [ 'quiet' => 1 ] );
418 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
419 $db->sourceFile( "$IP/tests/phpunit/data/db/sqlite/tables-$version.sql" );
420 $updater = DatabaseUpdater
::newForDB( $db, false, $maint );
421 $updater->doUpdates( [ 'core' ] );
426 private function getTables( $db ) {
427 $list = array_flip( $db->listTables() );
429 'external_user', // removed from core in 1.22
430 'math', // moved out of core in 1.18
431 'trackbacks', // removed from core in 1.19
433 'searchindex_content',
434 'searchindex_segments',
435 'searchindex_segdir',
437 'searchindex_docsize',
440 foreach ( $excluded as $t ) {
443 $list = array_flip( $list );
449 private function getColumns( $db, $table ) {
451 $res = $db->query( "PRAGMA table_info($table)" );
452 $this->assertNotNull( $res );
453 foreach ( $res as $col ) {
454 $cols[$col->name
] = $col;
461 private function getIndexes( $db, $table ) {
463 $res = $db->query( "PRAGMA index_list($table)" );
464 $this->assertNotNull( $res );
465 foreach ( $res as $index ) {
466 $res2 = $db->query( "PRAGMA index_info({$index->name})" );
467 $this->assertNotNull( $res2 );
468 $index->columns
= [];
469 foreach ( $res2 as $col ) {
470 $index->columns
[] = $col;
472 $indexes[$index->name
] = $index;
479 public function testCaseInsensitiveLike() {
480 // TODO: Test this for all databases
481 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
482 $res = $db->query( 'SELECT "a" LIKE "A" AS a' );
483 $row = $res->fetchRow();
484 $this->assertFalse( (bool)$row['a'] );
488 * @covers DatabaseSqlite::numFields
490 public function testNumFields() {
491 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
493 $databaseCreation = $db->query( 'CREATE TABLE a ( a_1 )', __METHOD__
);
494 $this->assertInstanceOf( ResultWrapper
::class, $databaseCreation, "Failed to create table a" );
495 $res = $db->select( 'a', '*' );
496 $this->assertEquals( 0, $db->numFields( $res ), "expects to get 0 fields for an empty table" );
497 $insertion = $db->insert( 'a', [ 'a_1' => 10 ], __METHOD__
);
498 $this->assertTrue( $insertion, "Insertion failed" );
499 $res = $db->select( 'a', '*' );
500 $this->assertEquals( 1, $db->numFields( $res ), "wrong number of fields" );
502 $this->assertTrue( $db->close(), "closing database" );
506 * @covers \Wikimedia\Rdbms\DatabaseSqlite::__toString
508 public function testToString() {
509 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
511 $toString = (string)$db;
513 $this->assertContains( 'SQLite ', $toString );