3 use Wikimedia\Rdbms\Blob
;
5 class DatabaseSqliteMock
extends DatabaseSqlite
{
8 public static function newInstance( array $p = [] ) {
9 $p['dbFilePath'] = ':memory:';
12 return Database
::factory( 'SqliteMock', $p );
15 function query( $sql, $fname = '', $tempIgnore = false ) {
16 $this->lastQuery
= $sql;
22 * Override parent visibility to public
24 public function replaceVars( $s ) {
25 return parent
::replaceVars( $s );
34 class DatabaseSqliteTest
extends MediaWikiTestCase
{
35 /** @var DatabaseSqliteMock */
38 protected function setUp() {
41 if ( !Sqlite
::isPresent() ) {
42 $this->markTestSkipped( 'No SQLite support detected' );
44 $this->db
= DatabaseSqliteMock
::newInstance();
45 if ( version_compare( $this->db
->getServerVersion(), '3.6.0', '<' ) ) {
46 $this->markTestSkipped( "SQLite at least 3.6 required, {$this->db->getServerVersion()} found" );
50 private function replaceVars( $sql ) {
51 // normalize spacing to hide implementation details
52 return preg_replace( '/\s+/', ' ', $this->db
->replaceVars( $sql ) );
55 private function assertResultIs( $expected, $res ) {
56 $this->assertNotNull( $res );
58 foreach ( $res as $row ) {
59 foreach ( $expected[$i] as $key => $value ) {
60 $this->assertTrue( isset( $row->$key ) );
61 $this->assertEquals( $value, $row->$key );
65 $this->assertEquals( count( $expected ), $i, 'Unexpected number of rows' );
68 public static function provideAddQuotes() {
74 'foo bar', "'foo bar'"
76 [ // #2: including quote
77 'foo\'bar', "'foo''bar'"
79 // #3: including \0 (must be represented as hex, per https://bugs.php.net/bug.php?id=63419)
84 [ // #4: blob object (must be represented as hex)
92 * @dataProvider provideAddQuotes()
93 * @covers DatabaseSqlite::addQuotes
95 public function testAddQuotes( $value, $expected ) {
97 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
98 $this->assertEquals( $expected, $db->addQuotes( $value ), 'string not quoted as expected' );
100 // ok, quoting works as expected, now try a round trip.
101 $re = $db->query( 'select ' . $db->addQuotes( $value ) );
103 $this->assertTrue( $re !== false, 'query failed' );
105 $row = $re->fetchRow();
107 if ( $value instanceof Blob
) {
108 $value = $value->fetch();
111 $this->assertEquals( $value, $row[0], 'string mangled by the database' );
113 $this->fail( 'query returned no result' );
118 * @covers DatabaseSqlite::replaceVars
120 public function testReplaceVars() {
121 $this->assertEquals( 'foo', $this->replaceVars( 'foo' ), "Don't break anything accidentally" );
124 "CREATE TABLE /**/foo (foo_key INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "
125 . "foo_bar TEXT, foo_name TEXT NOT NULL DEFAULT '', foo_int INTEGER, foo_int2 INTEGER );",
127 "CREATE TABLE /**/foo (foo_key int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT, "
128 . "foo_bar char(13), foo_name varchar(255) binary NOT NULL DEFAULT '', "
129 . "foo_int tinyint ( 8 ), foo_int2 int(16) ) ENGINE=MyISAM;"
134 "CREATE TABLE foo ( foo1 REAL, foo2 REAL, foo3 REAL );",
136 "CREATE TABLE foo ( foo1 FLOAT, foo2 DOUBLE( 1,10), foo3 DOUBLE PRECISION );"
140 $this->assertEquals( "CREATE TABLE foo ( foo_binary1 BLOB, foo_binary2 BLOB );",
141 $this->replaceVars( "CREATE TABLE foo ( foo_binary1 binary(16), foo_binary2 varbinary(32) );" )
144 $this->assertEquals( "CREATE TABLE text ( text_foo TEXT );",
145 $this->replaceVars( "CREATE TABLE text ( text_foo tinytext );" ),
149 $this->assertEquals( "CREATE TABLE foo ( foobar INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL );",
150 $this->replaceVars( "CREATE TABLE foo ( foobar INT PRIMARY KEY NOT NULL AUTO_INCREMENT );" )
152 $this->assertEquals( "CREATE TABLE foo ( foobar INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL );",
153 $this->replaceVars( "CREATE TABLE foo ( foobar INT PRIMARY KEY AUTO_INCREMENT NOT NULL );" )
156 $this->assertEquals( "CREATE TABLE enums( enum1 TEXT, myenum TEXT)",
157 $this->replaceVars( "CREATE TABLE enums( enum1 ENUM('A', 'B'), myenum ENUM ('X', 'Y'))" )
160 $this->assertEquals( "ALTER TABLE foo ADD COLUMN foo_bar INTEGER DEFAULT 42",
161 $this->replaceVars( "ALTER TABLE foo\nADD COLUMN foo_bar int(10) unsigned DEFAULT 42" )
164 $this->assertEquals( "DROP INDEX foo",
165 $this->replaceVars( "DROP INDEX /*i*/foo ON /*_*/bar" )
168 $this->assertEquals( "DROP INDEX foo -- dropping index",
169 $this->replaceVars( "DROP INDEX /*i*/foo ON /*_*/bar -- dropping index" )
171 $this->assertEquals( "INSERT OR IGNORE INTO foo VALUES ('bar')",
172 $this->replaceVars( "INSERT OR IGNORE INTO foo VALUES ('bar')" )
177 * @covers DatabaseSqlite::tableName
179 public function testTableName() {
181 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
182 $this->assertEquals( 'foo', $db->tableName( 'foo' ) );
183 $this->assertEquals( 'sqlite_master', $db->tableName( 'sqlite_master' ) );
184 $db->tablePrefix( 'foo' );
185 $this->assertEquals( 'sqlite_master', $db->tableName( 'sqlite_master' ) );
186 $this->assertEquals( 'foobar', $db->tableName( 'bar' ) );
190 * @covers DatabaseSqlite::duplicateTableStructure
192 public function testDuplicateTableStructure() {
193 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
194 $db->query( 'CREATE TABLE foo(foo, barfoo)' );
195 $db->query( 'CREATE INDEX index1 ON foo(foo)' );
196 $db->query( 'CREATE UNIQUE INDEX index2 ON foo(barfoo)' );
198 $db->duplicateTableStructure( 'foo', 'bar' );
199 $this->assertEquals( 'CREATE TABLE "bar"(foo, barfoo)',
200 $db->selectField( 'sqlite_master', 'sql', [ 'name' => 'bar' ] ),
201 'Normal table duplication'
203 $indexList = $db->query( 'PRAGMA INDEX_LIST("bar")' );
204 $index = $indexList->next();
205 $this->assertEquals( 'bar_index1', $index->name
);
206 $this->assertEquals( '0', $index->unique
);
207 $index = $indexList->next();
208 $this->assertEquals( 'bar_index2', $index->name
);
209 $this->assertEquals( '1', $index->unique
);
211 $db->duplicateTableStructure( 'foo', 'baz', true );
212 $this->assertEquals( 'CREATE TABLE "baz"(foo, barfoo)',
213 $db->selectField( 'sqlite_temp_master', 'sql', [ 'name' => 'baz' ] ),
214 'Creation of temporary duplicate'
216 $indexList = $db->query( 'PRAGMA INDEX_LIST("baz")' );
217 $index = $indexList->next();
218 $this->assertEquals( 'baz_index1', $index->name
);
219 $this->assertEquals( '0', $index->unique
);
220 $index = $indexList->next();
221 $this->assertEquals( 'baz_index2', $index->name
);
222 $this->assertEquals( '1', $index->unique
);
223 $this->assertEquals( 0,
224 $db->selectField( 'sqlite_master', 'COUNT(*)', [ 'name' => 'baz' ] ),
225 'Create a temporary duplicate only'
230 * @covers DatabaseSqlite::duplicateTableStructure
232 public function testDuplicateTableStructureVirtual() {
233 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
234 if ( $db->getFulltextSearchModule() != 'FTS3' ) {
235 $this->markTestSkipped( 'FTS3 not supported, cannot create virtual tables' );
237 $db->query( 'CREATE VIRTUAL TABLE "foo" USING FTS3(foobar)' );
239 $db->duplicateTableStructure( 'foo', 'bar' );
240 $this->assertEquals( 'CREATE VIRTUAL TABLE "bar" USING FTS3(foobar)',
241 $db->selectField( 'sqlite_master', 'sql', [ 'name' => 'bar' ] ),
242 'Duplication of virtual tables'
245 $db->duplicateTableStructure( 'foo', 'baz', true );
246 $this->assertEquals( 'CREATE VIRTUAL TABLE "baz" USING FTS3(foobar)',
247 $db->selectField( 'sqlite_master', 'sql', [ 'name' => 'baz' ] ),
248 "Can't create temporary virtual tables, should fall back to non-temporary duplication"
253 * @covers DatabaseSqlite::deleteJoin
255 public function testDeleteJoin() {
256 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
257 $db->query( 'CREATE TABLE a (a_1)', __METHOD__
);
258 $db->query( 'CREATE TABLE b (b_1, b_2)', __METHOD__
);
267 [ 'b_1' => 2, 'b_2' => 'a' ],
268 [ 'b_1' => 3, 'b_2' => 'b' ],
272 $db->deleteJoin( 'a', 'b', 'a_1', 'b_1', [ 'b_2' => 'a' ], __METHOD__
);
273 $res = $db->query( "SELECT * FROM a", __METHOD__
);
274 $this->assertResultIs( [
282 public function testEntireSchema() {
285 $result = Sqlite
::checkSqlSyntax( "$IP/maintenance/tables.sql" );
286 if ( $result !== true ) {
287 $this->fail( $result );
289 $this->assertTrue( true ); // avoid test being marked as incomplete due to lack of assertions
293 * Runs upgrades of older databases and compares results with current schema
294 * @todo Currently only checks list of tables
296 public function testUpgrades() {
297 global $IP, $wgVersion, $wgProfiler;
301 // '1.13', disabled for now, was totally screwed up
302 // SQLite wasn't included in 1.14
309 // Mismatches for these columns we can safely ignore
311 'user_newtalk.user_last_timestamp', // r84185
314 $currentDB = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
315 $currentDB->sourceFile( "$IP/maintenance/tables.sql" );
317 $profileToDb = false;
318 if ( isset( $wgProfiler['output'] ) ) {
319 $out = $wgProfiler['output'];
320 if ( $out === 'db' ) {
322 } elseif ( is_array( $out ) && in_array( 'db', $out ) ) {
327 if ( $profileToDb ) {
328 $currentDB->sourceFile( "$IP/maintenance/sqlite/archives/patch-profiling.sql" );
330 $currentTables = $this->getTables( $currentDB );
331 sort( $currentTables );
333 foreach ( $versions as $version ) {
334 $versions = "upgrading from $version to $wgVersion";
335 $db = $this->prepareTestDB( $version );
336 $tables = $this->getTables( $db );
337 $this->assertEquals( $currentTables, $tables, "Different tables $versions" );
338 foreach ( $tables as $table ) {
339 $currentCols = $this->getColumns( $currentDB, $table );
340 $cols = $this->getColumns( $db, $table );
342 array_keys( $currentCols ),
344 "Mismatching columns for table \"$table\" $versions"
346 foreach ( $currentCols as $name => $column ) {
347 $fullName = "$table.$name";
350 (bool)$cols[$name]->pk
,
351 "PRIMARY KEY status does not match for column $fullName $versions"
353 if ( !in_array( $fullName, $ignoredColumns ) ) {
355 (bool)$column->notnull
,
356 (bool)$cols[$name]->notnull
,
357 "NOT NULL status does not match for column $fullName $versions"
361 $cols[$name]->dflt_value
,
362 "Default values does not match for column $fullName $versions"
366 $currentIndexes = $this->getIndexes( $currentDB, $table );
367 $indexes = $this->getIndexes( $db, $table );
369 array_keys( $currentIndexes ),
370 array_keys( $indexes ),
371 "mismatching indexes for table \"$table\" $versions"
379 * @covers DatabaseSqlite::insertId
381 public function testInsertIdType() {
382 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
384 $databaseCreation = $db->query( 'CREATE TABLE a ( a_1 )', __METHOD__
);
385 $this->assertInstanceOf( 'ResultWrapper', $databaseCreation, "Database creation" );
387 $insertion = $db->insert( 'a', [ 'a_1' => 10 ], __METHOD__
);
388 $this->assertTrue( $insertion, "Insertion worked" );
390 $this->assertInternalType( 'integer', $db->insertId(), "Actual typecheck" );
391 $this->assertTrue( $db->close(), "closing database" );
394 private function prepareTestDB( $version ) {
395 static $maint = null;
396 if ( $maint === null ) {
397 $maint = new FakeMaintenance();
398 $maint->loadParamsAndArgs( null, [ 'quiet' => 1 ] );
402 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
403 $db->sourceFile( "$IP/tests/phpunit/data/db/sqlite/tables-$version.sql" );
404 $updater = DatabaseUpdater
::newForDB( $db, false, $maint );
405 $updater->doUpdates( [ 'core' ] );
410 private function getTables( $db ) {
411 $list = array_flip( $db->listTables() );
413 'external_user', // removed from core in 1.22
414 'math', // moved out of core in 1.18
415 'trackbacks', // removed from core in 1.19
417 'searchindex_content',
418 'searchindex_segments',
419 'searchindex_segdir',
421 'searchindex_docsize',
424 foreach ( $excluded as $t ) {
427 $list = array_flip( $list );
433 private function getColumns( $db, $table ) {
435 $res = $db->query( "PRAGMA table_info($table)" );
436 $this->assertNotNull( $res );
437 foreach ( $res as $col ) {
438 $cols[$col->name
] = $col;
445 private function getIndexes( $db, $table ) {
447 $res = $db->query( "PRAGMA index_list($table)" );
448 $this->assertNotNull( $res );
449 foreach ( $res as $index ) {
450 $res2 = $db->query( "PRAGMA index_info({$index->name})" );
451 $this->assertNotNull( $res2 );
452 $index->columns
= [];
453 foreach ( $res2 as $col ) {
454 $index->columns
[] = $col;
456 $indexes[$index->name
] = $index;
463 public function testCaseInsensitiveLike() {
464 // TODO: Test this for all databases
465 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
466 $res = $db->query( 'SELECT "a" LIKE "A" AS a' );
467 $row = $res->fetchRow();
468 $this->assertFalse( (bool)$row['a'] );
472 * @covers DatabaseSqlite::numFields
474 public function testNumFields() {
475 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
477 $databaseCreation = $db->query( 'CREATE TABLE a ( a_1 )', __METHOD__
);
478 $this->assertInstanceOf( 'ResultWrapper', $databaseCreation, "Failed to create table a" );
479 $res = $db->select( 'a', '*' );
480 $this->assertEquals( 0, $db->numFields( $res ), "expects to get 0 fields for an empty table" );
481 $insertion = $db->insert( 'a', [ 'a_1' => 10 ], __METHOD__
);
482 $this->assertTrue( $insertion, "Insertion failed" );
483 $res = $db->select( 'a', '*' );
484 $this->assertEquals( 1, $db->numFields( $res ), "wrong number of fields" );
486 $this->assertTrue( $db->close(), "closing database" );
489 public function testToString() {
490 $db = DatabaseSqlite
::newStandaloneInstance( ':memory:' );
492 $toString = (string)$db;
494 $this->assertContains( 'SQLite ', $toString );