Merge "Keep headers from jumping when expire interface is shown"
[lhc/web/wiklou.git] / tests / phpunit / includes / db / DatabaseSqliteTest.php
1 <?php
2
3 use Wikimedia\Rdbms\Blob;
4 use Wikimedia\Rdbms\Database;
5 use Wikimedia\Rdbms\DatabaseSqlite;
6
7 class DatabaseSqliteMock extends DatabaseSqlite {
8 private $lastQuery;
9
10 public static function newInstance( array $p = [] ) {
11 $p['dbFilePath'] = ':memory:';
12 $p['schema'] = false;
13
14 return Database::factory( 'SqliteMock', $p );
15 }
16
17 function query( $sql, $fname = '', $tempIgnore = false ) {
18 $this->lastQuery = $sql;
19
20 return true;
21 }
22
23 /**
24 * Override parent visibility to public
25 */
26 public function replaceVars( $s ) {
27 return parent::replaceVars( $s );
28 }
29 }
30
31 /**
32 * @group sqlite
33 * @group Database
34 * @group medium
35 */
36 class DatabaseSqliteTest extends MediaWikiTestCase {
37 /** @var DatabaseSqliteMock */
38 protected $db;
39
40 protected function setUp() {
41 parent::setUp();
42
43 if ( !Sqlite::isPresent() ) {
44 $this->markTestSkipped( 'No SQLite support detected' );
45 }
46 $this->db = DatabaseSqliteMock::newInstance();
47 if ( version_compare( $this->db->getServerVersion(), '3.6.0', '<' ) ) {
48 $this->markTestSkipped( "SQLite at least 3.6 required, {$this->db->getServerVersion()} found" );
49 }
50 }
51
52 private function replaceVars( $sql ) {
53 // normalize spacing to hide implementation details
54 return preg_replace( '/\s+/', ' ', $this->db->replaceVars( $sql ) );
55 }
56
57 private function assertResultIs( $expected, $res ) {
58 $this->assertNotNull( $res );
59 $i = 0;
60 foreach ( $res as $row ) {
61 foreach ( $expected[$i] as $key => $value ) {
62 $this->assertTrue( isset( $row->$key ) );
63 $this->assertEquals( $value, $row->$key );
64 }
65 $i++;
66 }
67 $this->assertEquals( count( $expected ), $i, 'Unexpected number of rows' );
68 }
69
70 public static function provideAddQuotes() {
71 return [
72 [ // #0: empty
73 '', "''"
74 ],
75 [ // #1: simple
76 'foo bar', "'foo bar'"
77 ],
78 [ // #2: including quote
79 'foo\'bar', "'foo''bar'"
80 ],
81 // #3: including \0 (must be represented as hex, per https://bugs.php.net/bug.php?id=63419)
82 [
83 "x\0y",
84 "x'780079'",
85 ],
86 [ // #4: blob object (must be represented as hex)
87 new Blob( "hello" ),
88 "x'68656c6c6f'",
89 ],
90 ];
91 }
92
93 /**
94 * @dataProvider provideAddQuotes()
95 * @covers DatabaseSqlite::addQuotes
96 */
97 public function testAddQuotes( $value, $expected ) {
98 // check quoting
99 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
100 $this->assertEquals( $expected, $db->addQuotes( $value ), 'string not quoted as expected' );
101
102 // ok, quoting works as expected, now try a round trip.
103 $re = $db->query( 'select ' . $db->addQuotes( $value ) );
104
105 $this->assertTrue( $re !== false, 'query failed' );
106
107 $row = $re->fetchRow();
108 if ( $row ) {
109 if ( $value instanceof Blob ) {
110 $value = $value->fetch();
111 }
112
113 $this->assertEquals( $value, $row[0], 'string mangled by the database' );
114 } else {
115 $this->fail( 'query returned no result' );
116 }
117 }
118
119 /**
120 * @covers DatabaseSqlite::replaceVars
121 */
122 public function testReplaceVars() {
123 $this->assertEquals( 'foo', $this->replaceVars( 'foo' ), "Don't break anything accidentally" );
124
125 $this->assertEquals(
126 "CREATE TABLE /**/foo (foo_key INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "
127 . "foo_bar TEXT, foo_name TEXT NOT NULL DEFAULT '', foo_int INTEGER, foo_int2 INTEGER );",
128 $this->replaceVars(
129 "CREATE TABLE /**/foo (foo_key int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT, "
130 . "foo_bar char(13), foo_name varchar(255) binary NOT NULL DEFAULT '', "
131 . "foo_int tinyint ( 8 ), foo_int2 int(16) ) ENGINE=MyISAM;"
132 )
133 );
134
135 $this->assertEquals(
136 "CREATE TABLE foo ( foo1 REAL, foo2 REAL, foo3 REAL );",
137 $this->replaceVars(
138 "CREATE TABLE foo ( foo1 FLOAT, foo2 DOUBLE( 1,10), foo3 DOUBLE PRECISION );"
139 )
140 );
141
142 $this->assertEquals( "CREATE TABLE foo ( foo_binary1 BLOB, foo_binary2 BLOB );",
143 $this->replaceVars( "CREATE TABLE foo ( foo_binary1 binary(16), foo_binary2 varbinary(32) );" )
144 );
145
146 $this->assertEquals( "CREATE TABLE text ( text_foo TEXT );",
147 $this->replaceVars( "CREATE TABLE text ( text_foo tinytext );" ),
148 'Table name changed'
149 );
150
151 $this->assertEquals( "CREATE TABLE foo ( foobar INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL );",
152 $this->replaceVars( "CREATE TABLE foo ( foobar INT PRIMARY KEY NOT NULL AUTO_INCREMENT );" )
153 );
154 $this->assertEquals( "CREATE TABLE foo ( foobar INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL );",
155 $this->replaceVars( "CREATE TABLE foo ( foobar INT PRIMARY KEY AUTO_INCREMENT NOT NULL );" )
156 );
157
158 $this->assertEquals( "CREATE TABLE enums( enum1 TEXT, myenum TEXT)",
159 $this->replaceVars( "CREATE TABLE enums( enum1 ENUM('A', 'B'), myenum ENUM ('X', 'Y'))" )
160 );
161
162 $this->assertEquals( "ALTER TABLE foo ADD COLUMN foo_bar INTEGER DEFAULT 42",
163 $this->replaceVars( "ALTER TABLE foo\nADD COLUMN foo_bar int(10) unsigned DEFAULT 42" )
164 );
165
166 $this->assertEquals( "DROP INDEX foo",
167 $this->replaceVars( "DROP INDEX /*i*/foo ON /*_*/bar" )
168 );
169
170 $this->assertEquals( "DROP INDEX foo -- dropping index",
171 $this->replaceVars( "DROP INDEX /*i*/foo ON /*_*/bar -- dropping index" )
172 );
173 $this->assertEquals( "INSERT OR IGNORE INTO foo VALUES ('bar')",
174 $this->replaceVars( "INSERT OR IGNORE INTO foo VALUES ('bar')" )
175 );
176 }
177
178 /**
179 * @covers DatabaseSqlite::tableName
180 */
181 public function testTableName() {
182 // @todo Moar!
183 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
184 $this->assertEquals( 'foo', $db->tableName( 'foo' ) );
185 $this->assertEquals( 'sqlite_master', $db->tableName( 'sqlite_master' ) );
186 $db->tablePrefix( 'foo' );
187 $this->assertEquals( 'sqlite_master', $db->tableName( 'sqlite_master' ) );
188 $this->assertEquals( 'foobar', $db->tableName( 'bar' ) );
189 }
190
191 /**
192 * @covers DatabaseSqlite::duplicateTableStructure
193 */
194 public function testDuplicateTableStructure() {
195 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
196 $db->query( 'CREATE TABLE foo(foo, barfoo)' );
197 $db->query( 'CREATE INDEX index1 ON foo(foo)' );
198 $db->query( 'CREATE UNIQUE INDEX index2 ON foo(barfoo)' );
199
200 $db->duplicateTableStructure( 'foo', 'bar' );
201 $this->assertEquals( 'CREATE TABLE "bar"(foo, barfoo)',
202 $db->selectField( 'sqlite_master', 'sql', [ 'name' => 'bar' ] ),
203 'Normal table duplication'
204 );
205 $indexList = $db->query( 'PRAGMA INDEX_LIST("bar")' );
206 $index = $indexList->next();
207 $this->assertEquals( 'bar_index1', $index->name );
208 $this->assertEquals( '0', $index->unique );
209 $index = $indexList->next();
210 $this->assertEquals( 'bar_index2', $index->name );
211 $this->assertEquals( '1', $index->unique );
212
213 $db->duplicateTableStructure( 'foo', 'baz', true );
214 $this->assertEquals( 'CREATE TABLE "baz"(foo, barfoo)',
215 $db->selectField( 'sqlite_temp_master', 'sql', [ 'name' => 'baz' ] ),
216 'Creation of temporary duplicate'
217 );
218 $indexList = $db->query( 'PRAGMA INDEX_LIST("baz")' );
219 $index = $indexList->next();
220 $this->assertEquals( 'baz_index1', $index->name );
221 $this->assertEquals( '0', $index->unique );
222 $index = $indexList->next();
223 $this->assertEquals( 'baz_index2', $index->name );
224 $this->assertEquals( '1', $index->unique );
225 $this->assertEquals( 0,
226 $db->selectField( 'sqlite_master', 'COUNT(*)', [ 'name' => 'baz' ] ),
227 'Create a temporary duplicate only'
228 );
229 }
230
231 /**
232 * @covers DatabaseSqlite::duplicateTableStructure
233 */
234 public function testDuplicateTableStructureVirtual() {
235 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
236 if ( $db->getFulltextSearchModule() != 'FTS3' ) {
237 $this->markTestSkipped( 'FTS3 not supported, cannot create virtual tables' );
238 }
239 $db->query( 'CREATE VIRTUAL TABLE "foo" USING FTS3(foobar)' );
240
241 $db->duplicateTableStructure( 'foo', 'bar' );
242 $this->assertEquals( 'CREATE VIRTUAL TABLE "bar" USING FTS3(foobar)',
243 $db->selectField( 'sqlite_master', 'sql', [ 'name' => 'bar' ] ),
244 'Duplication of virtual tables'
245 );
246
247 $db->duplicateTableStructure( 'foo', 'baz', true );
248 $this->assertEquals( 'CREATE VIRTUAL TABLE "baz" USING FTS3(foobar)',
249 $db->selectField( 'sqlite_master', 'sql', [ 'name' => 'baz' ] ),
250 "Can't create temporary virtual tables, should fall back to non-temporary duplication"
251 );
252 }
253
254 /**
255 * @covers DatabaseSqlite::deleteJoin
256 */
257 public function testDeleteJoin() {
258 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
259 $db->query( 'CREATE TABLE a (a_1)', __METHOD__ );
260 $db->query( 'CREATE TABLE b (b_1, b_2)', __METHOD__ );
261 $db->insert( 'a', [
262 [ 'a_1' => 1 ],
263 [ 'a_1' => 2 ],
264 [ 'a_1' => 3 ],
265 ],
266 __METHOD__
267 );
268 $db->insert( 'b', [
269 [ 'b_1' => 2, 'b_2' => 'a' ],
270 [ 'b_1' => 3, 'b_2' => 'b' ],
271 ],
272 __METHOD__
273 );
274 $db->deleteJoin( 'a', 'b', 'a_1', 'b_1', [ 'b_2' => 'a' ], __METHOD__ );
275 $res = $db->query( "SELECT * FROM a", __METHOD__ );
276 $this->assertResultIs( [
277 [ 'a_1' => 1 ],
278 [ 'a_1' => 3 ],
279 ],
280 $res
281 );
282 }
283
284 public function testEntireSchema() {
285 global $IP;
286
287 $result = Sqlite::checkSqlSyntax( "$IP/maintenance/tables.sql" );
288 if ( $result !== true ) {
289 $this->fail( $result );
290 }
291 $this->assertTrue( true ); // avoid test being marked as incomplete due to lack of assertions
292 }
293
294 /**
295 * Runs upgrades of older databases and compares results with current schema
296 * @todo Currently only checks list of tables
297 */
298 public function testUpgrades() {
299 global $IP, $wgVersion, $wgProfiler;
300
301 // Versions tested
302 $versions = [
303 // '1.13', disabled for now, was totally screwed up
304 // SQLite wasn't included in 1.14
305 '1.15',
306 '1.16',
307 '1.17',
308 '1.18',
309 ];
310
311 // Mismatches for these columns we can safely ignore
312 $ignoredColumns = [
313 'user_newtalk.user_last_timestamp', // r84185
314 'site_stats.ss_active_users', // T56888
315 ];
316
317 $currentDB = DatabaseSqlite::newStandaloneInstance( ':memory:' );
318 $currentDB->sourceFile( "$IP/maintenance/tables.sql" );
319
320 $profileToDb = false;
321 if ( isset( $wgProfiler['output'] ) ) {
322 $out = $wgProfiler['output'];
323 if ( $out === 'db' ) {
324 $profileToDb = true;
325 } elseif ( is_array( $out ) && in_array( 'db', $out ) ) {
326 $profileToDb = true;
327 }
328 }
329
330 if ( $profileToDb ) {
331 $currentDB->sourceFile( "$IP/maintenance/sqlite/archives/patch-profiling.sql" );
332 }
333 $currentTables = $this->getTables( $currentDB );
334 sort( $currentTables );
335
336 foreach ( $versions as $version ) {
337 $versions = "upgrading from $version to $wgVersion";
338 $db = $this->prepareTestDB( $version );
339 $tables = $this->getTables( $db );
340 $this->assertEquals( $currentTables, $tables, "Different tables $versions" );
341 foreach ( $tables as $table ) {
342 $currentCols = $this->getColumns( $currentDB, $table );
343 $cols = $this->getColumns( $db, $table );
344 $this->assertEquals(
345 array_keys( $currentCols ),
346 array_keys( $cols ),
347 "Mismatching columns for table \"$table\" $versions"
348 );
349 foreach ( $currentCols as $name => $column ) {
350 $fullName = "$table.$name";
351 $this->assertEquals(
352 (bool)$column->pk,
353 (bool)$cols[$name]->pk,
354 "PRIMARY KEY status does not match for column $fullName $versions"
355 );
356 if ( !in_array( $fullName, $ignoredColumns ) ) {
357 $this->assertEquals(
358 (bool)$column->notnull,
359 (bool)$cols[$name]->notnull,
360 "NOT NULL status does not match for column $fullName $versions"
361 );
362 $this->assertEquals(
363 $column->dflt_value,
364 $cols[$name]->dflt_value,
365 "Default values does not match for column $fullName $versions"
366 );
367 }
368 }
369 $currentIndexes = $this->getIndexes( $currentDB, $table );
370 $indexes = $this->getIndexes( $db, $table );
371 $this->assertEquals(
372 array_keys( $currentIndexes ),
373 array_keys( $indexes ),
374 "mismatching indexes for table \"$table\" $versions"
375 );
376 }
377 $db->close();
378 }
379 }
380
381 /**
382 * @covers DatabaseSqlite::insertId
383 */
384 public function testInsertIdType() {
385 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
386
387 $databaseCreation = $db->query( 'CREATE TABLE a ( a_1 )', __METHOD__ );
388 $this->assertInstanceOf( 'ResultWrapper', $databaseCreation, "Database creation" );
389
390 $insertion = $db->insert( 'a', [ 'a_1' => 10 ], __METHOD__ );
391 $this->assertTrue( $insertion, "Insertion worked" );
392
393 $this->assertInternalType( 'integer', $db->insertId(), "Actual typecheck" );
394 $this->assertTrue( $db->close(), "closing database" );
395 }
396
397 private function prepareTestDB( $version ) {
398 static $maint = null;
399 if ( $maint === null ) {
400 $maint = new FakeMaintenance();
401 $maint->loadParamsAndArgs( null, [ 'quiet' => 1 ] );
402 }
403
404 global $IP;
405 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
406 $db->sourceFile( "$IP/tests/phpunit/data/db/sqlite/tables-$version.sql" );
407 $updater = DatabaseUpdater::newForDB( $db, false, $maint );
408 $updater->doUpdates( [ 'core' ] );
409
410 return $db;
411 }
412
413 private function getTables( $db ) {
414 $list = array_flip( $db->listTables() );
415 $excluded = [
416 'external_user', // removed from core in 1.22
417 'math', // moved out of core in 1.18
418 'trackbacks', // removed from core in 1.19
419 'searchindex',
420 'searchindex_content',
421 'searchindex_segments',
422 'searchindex_segdir',
423 // FTS4 ready!!1
424 'searchindex_docsize',
425 'searchindex_stat',
426 ];
427 foreach ( $excluded as $t ) {
428 unset( $list[$t] );
429 }
430 $list = array_flip( $list );
431 sort( $list );
432
433 return $list;
434 }
435
436 private function getColumns( $db, $table ) {
437 $cols = [];
438 $res = $db->query( "PRAGMA table_info($table)" );
439 $this->assertNotNull( $res );
440 foreach ( $res as $col ) {
441 $cols[$col->name] = $col;
442 }
443 ksort( $cols );
444
445 return $cols;
446 }
447
448 private function getIndexes( $db, $table ) {
449 $indexes = [];
450 $res = $db->query( "PRAGMA index_list($table)" );
451 $this->assertNotNull( $res );
452 foreach ( $res as $index ) {
453 $res2 = $db->query( "PRAGMA index_info({$index->name})" );
454 $this->assertNotNull( $res2 );
455 $index->columns = [];
456 foreach ( $res2 as $col ) {
457 $index->columns[] = $col;
458 }
459 $indexes[$index->name] = $index;
460 }
461 ksort( $indexes );
462
463 return $indexes;
464 }
465
466 public function testCaseInsensitiveLike() {
467 // TODO: Test this for all databases
468 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
469 $res = $db->query( 'SELECT "a" LIKE "A" AS a' );
470 $row = $res->fetchRow();
471 $this->assertFalse( (bool)$row['a'] );
472 }
473
474 /**
475 * @covers DatabaseSqlite::numFields
476 */
477 public function testNumFields() {
478 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
479
480 $databaseCreation = $db->query( 'CREATE TABLE a ( a_1 )', __METHOD__ );
481 $this->assertInstanceOf( 'ResultWrapper', $databaseCreation, "Failed to create table a" );
482 $res = $db->select( 'a', '*' );
483 $this->assertEquals( 0, $db->numFields( $res ), "expects to get 0 fields for an empty table" );
484 $insertion = $db->insert( 'a', [ 'a_1' => 10 ], __METHOD__ );
485 $this->assertTrue( $insertion, "Insertion failed" );
486 $res = $db->select( 'a', '*' );
487 $this->assertEquals( 1, $db->numFields( $res ), "wrong number of fields" );
488
489 $this->assertTrue( $db->close(), "closing database" );
490 }
491
492 public function testToString() {
493 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
494
495 $toString = (string)$db;
496
497 $this->assertContains( 'SQLite ', $toString );
498 }
499 }