Merge "Export: Use BCP 47 language code for attribute xml:lang"
[lhc/web/wiklou.git] / tests / phpunit / includes / db / DatabaseSqliteTest.php
1 <?php
2
3 class DatabaseSqliteMock extends DatabaseSqlite {
4 private $lastQuery;
5
6 public static function newInstance( array $p = [] ) {
7 $p['dbFilePath'] = ':memory:';
8 $p['schema'] = false;
9
10 return Database::factory( 'SqliteMock', $p );
11 }
12
13 function query( $sql, $fname = '', $tempIgnore = false ) {
14 $this->lastQuery = $sql;
15
16 return true;
17 }
18
19 /**
20 * Override parent visibility to public
21 */
22 public function replaceVars( $s ) {
23 return parent::replaceVars( $s );
24 }
25 }
26
27 /**
28 * @group sqlite
29 * @group Database
30 * @group medium
31 */
32 class DatabaseSqliteTest extends MediaWikiTestCase {
33 /** @var DatabaseSqliteMock */
34 protected $db;
35
36 protected function setUp() {
37 parent::setUp();
38
39 if ( !Sqlite::isPresent() ) {
40 $this->markTestSkipped( 'No SQLite support detected' );
41 }
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" );
45 }
46 }
47
48 private function replaceVars( $sql ) {
49 // normalize spacing to hide implementation details
50 return preg_replace( '/\s+/', ' ', $this->db->replaceVars( $sql ) );
51 }
52
53 private function assertResultIs( $expected, $res ) {
54 $this->assertNotNull( $res );
55 $i = 0;
56 foreach ( $res as $row ) {
57 foreach ( $expected[$i] as $key => $value ) {
58 $this->assertTrue( isset( $row->$key ) );
59 $this->assertEquals( $value, $row->$key );
60 }
61 $i++;
62 }
63 $this->assertEquals( count( $expected ), $i, 'Unexpected number of rows' );
64 }
65
66 public static function provideAddQuotes() {
67 return [
68 [ // #0: empty
69 '', "''"
70 ],
71 [ // #1: simple
72 'foo bar', "'foo bar'"
73 ],
74 [ // #2: including quote
75 'foo\'bar', "'foo''bar'"
76 ],
77 // #3: including \0 (must be represented as hex, per https://bugs.php.net/bug.php?id=63419)
78 [
79 "x\0y",
80 "x'780079'",
81 ],
82 [ // #4: blob object (must be represented as hex)
83 new Blob( "hello" ),
84 "x'68656c6c6f'",
85 ],
86 ];
87 }
88
89 /**
90 * @dataProvider provideAddQuotes()
91 * @covers DatabaseSqlite::addQuotes
92 */
93 public function testAddQuotes( $value, $expected ) {
94 // check quoting
95 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
96 $this->assertEquals( $expected, $db->addQuotes( $value ), 'string not quoted as expected' );
97
98 // ok, quoting works as expected, now try a round trip.
99 $re = $db->query( 'select ' . $db->addQuotes( $value ) );
100
101 $this->assertTrue( $re !== false, 'query failed' );
102
103 $row = $re->fetchRow();
104 if ( $row ) {
105 if ( $value instanceof Blob ) {
106 $value = $value->fetch();
107 }
108
109 $this->assertEquals( $value, $row[0], 'string mangled by the database' );
110 } else {
111 $this->fail( 'query returned no result' );
112 }
113 }
114
115 /**
116 * @covers DatabaseSqlite::replaceVars
117 */
118 public function testReplaceVars() {
119 $this->assertEquals( 'foo', $this->replaceVars( 'foo' ), "Don't break anything accidentally" );
120
121 $this->assertEquals(
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 );",
124 $this->replaceVars(
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;"
128 )
129 );
130
131 $this->assertEquals(
132 "CREATE TABLE foo ( foo1 REAL, foo2 REAL, foo3 REAL );",
133 $this->replaceVars(
134 "CREATE TABLE foo ( foo1 FLOAT, foo2 DOUBLE( 1,10), foo3 DOUBLE PRECISION );"
135 )
136 );
137
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) );" )
140 );
141
142 $this->assertEquals( "CREATE TABLE text ( text_foo TEXT );",
143 $this->replaceVars( "CREATE TABLE text ( text_foo tinytext );" ),
144 'Table name changed'
145 );
146
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 );" )
149 );
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 );" )
152 );
153
154 $this->assertEquals( "CREATE TABLE enums( enum1 TEXT, myenum TEXT)",
155 $this->replaceVars( "CREATE TABLE enums( enum1 ENUM('A', 'B'), myenum ENUM ('X', 'Y'))" )
156 );
157
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" )
160 );
161
162 $this->assertEquals( "DROP INDEX foo",
163 $this->replaceVars( "DROP INDEX /*i*/foo ON /*_*/bar" )
164 );
165
166 $this->assertEquals( "DROP INDEX foo -- dropping index",
167 $this->replaceVars( "DROP INDEX /*i*/foo ON /*_*/bar -- dropping index" )
168 );
169 $this->assertEquals( "INSERT OR IGNORE INTO foo VALUES ('bar')",
170 $this->replaceVars( "INSERT OR IGNORE INTO foo VALUES ('bar')" )
171 );
172 }
173
174 /**
175 * @covers DatabaseSqlite::tableName
176 */
177 public function testTableName() {
178 // @todo Moar!
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' ) );
185 }
186
187 /**
188 * @covers DatabaseSqlite::duplicateTableStructure
189 */
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)' );
195
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'
200 );
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 );
208
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'
213 );
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'
224 );
225 }
226
227 /**
228 * @covers DatabaseSqlite::duplicateTableStructure
229 */
230 public function testDuplicateTableStructureVirtual() {
231 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
232 if ( $db->getFulltextSearchModule() != 'FTS3' ) {
233 $this->markTestSkipped( 'FTS3 not supported, cannot create virtual tables' );
234 }
235 $db->query( 'CREATE VIRTUAL TABLE "foo" USING FTS3(foobar)' );
236
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'
241 );
242
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"
247 );
248 }
249
250 /**
251 * @covers DatabaseSqlite::deleteJoin
252 */
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__ );
257 $db->insert( 'a', [
258 [ 'a_1' => 1 ],
259 [ 'a_1' => 2 ],
260 [ 'a_1' => 3 ],
261 ],
262 __METHOD__
263 );
264 $db->insert( 'b', [
265 [ 'b_1' => 2, 'b_2' => 'a' ],
266 [ 'b_1' => 3, 'b_2' => 'b' ],
267 ],
268 __METHOD__
269 );
270 $db->deleteJoin( 'a', 'b', 'a_1', 'b_1', [ 'b_2' => 'a' ], __METHOD__ );
271 $res = $db->query( "SELECT * FROM a", __METHOD__ );
272 $this->assertResultIs( [
273 [ 'a_1' => 1 ],
274 [ 'a_1' => 3 ],
275 ],
276 $res
277 );
278 }
279
280 public function testEntireSchema() {
281 global $IP;
282
283 $result = Sqlite::checkSqlSyntax( "$IP/maintenance/tables.sql" );
284 if ( $result !== true ) {
285 $this->fail( $result );
286 }
287 $this->assertTrue( true ); // avoid test being marked as incomplete due to lack of assertions
288 }
289
290 /**
291 * Runs upgrades of older databases and compares results with current schema
292 * @todo Currently only checks list of tables
293 */
294 public function testUpgrades() {
295 global $IP, $wgVersion, $wgProfiler;
296
297 // Versions tested
298 $versions = [
299 // '1.13', disabled for now, was totally screwed up
300 // SQLite wasn't included in 1.14
301 '1.15',
302 '1.16',
303 '1.17',
304 '1.18',
305 ];
306
307 // Mismatches for these columns we can safely ignore
308 $ignoredColumns = [
309 'user_newtalk.user_last_timestamp', // r84185
310 ];
311
312 $currentDB = DatabaseSqlite::newStandaloneInstance( ':memory:' );
313 $currentDB->sourceFile( "$IP/maintenance/tables.sql" );
314
315 $profileToDb = false;
316 if ( isset( $wgProfiler['output'] ) ) {
317 $out = $wgProfiler['output'];
318 if ( $out === 'db' ) {
319 $profileToDb = true;
320 } elseif ( is_array( $out ) && in_array( 'db', $out ) ) {
321 $profileToDb = true;
322 }
323 }
324
325 if ( $profileToDb ) {
326 $currentDB->sourceFile( "$IP/maintenance/sqlite/archives/patch-profiling.sql" );
327 }
328 $currentTables = $this->getTables( $currentDB );
329 sort( $currentTables );
330
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 );
339 $this->assertEquals(
340 array_keys( $currentCols ),
341 array_keys( $cols ),
342 "Mismatching columns for table \"$table\" $versions"
343 );
344 foreach ( $currentCols as $name => $column ) {
345 $fullName = "$table.$name";
346 $this->assertEquals(
347 (bool)$column->pk,
348 (bool)$cols[$name]->pk,
349 "PRIMARY KEY status does not match for column $fullName $versions"
350 );
351 if ( !in_array( $fullName, $ignoredColumns ) ) {
352 $this->assertEquals(
353 (bool)$column->notnull,
354 (bool)$cols[$name]->notnull,
355 "NOT NULL status does not match for column $fullName $versions"
356 );
357 $this->assertEquals(
358 $column->dflt_value,
359 $cols[$name]->dflt_value,
360 "Default values does not match for column $fullName $versions"
361 );
362 }
363 }
364 $currentIndexes = $this->getIndexes( $currentDB, $table );
365 $indexes = $this->getIndexes( $db, $table );
366 $this->assertEquals(
367 array_keys( $currentIndexes ),
368 array_keys( $indexes ),
369 "mismatching indexes for table \"$table\" $versions"
370 );
371 }
372 $db->close();
373 }
374 }
375
376 /**
377 * @covers DatabaseSqlite::insertId
378 */
379 public function testInsertIdType() {
380 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
381
382 $databaseCreation = $db->query( 'CREATE TABLE a ( a_1 )', __METHOD__ );
383 $this->assertInstanceOf( 'ResultWrapper', $databaseCreation, "Database creation" );
384
385 $insertion = $db->insert( 'a', [ 'a_1' => 10 ], __METHOD__ );
386 $this->assertTrue( $insertion, "Insertion worked" );
387
388 $this->assertInternalType( 'integer', $db->insertId(), "Actual typecheck" );
389 $this->assertTrue( $db->close(), "closing database" );
390 }
391
392 private function prepareTestDB( $version ) {
393 static $maint = null;
394 if ( $maint === null ) {
395 $maint = new FakeMaintenance();
396 $maint->loadParamsAndArgs( null, [ 'quiet' => 1 ] );
397 }
398
399 global $IP;
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' ] );
404
405 return $db;
406 }
407
408 private function getTables( $db ) {
409 $list = array_flip( $db->listTables() );
410 $excluded = [
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
414 'searchindex',
415 'searchindex_content',
416 'searchindex_segments',
417 'searchindex_segdir',
418 // FTS4 ready!!1
419 'searchindex_docsize',
420 'searchindex_stat',
421 ];
422 foreach ( $excluded as $t ) {
423 unset( $list[$t] );
424 }
425 $list = array_flip( $list );
426 sort( $list );
427
428 return $list;
429 }
430
431 private function getColumns( $db, $table ) {
432 $cols = [];
433 $res = $db->query( "PRAGMA table_info($table)" );
434 $this->assertNotNull( $res );
435 foreach ( $res as $col ) {
436 $cols[$col->name] = $col;
437 }
438 ksort( $cols );
439
440 return $cols;
441 }
442
443 private function getIndexes( $db, $table ) {
444 $indexes = [];
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;
453 }
454 $indexes[$index->name] = $index;
455 }
456 ksort( $indexes );
457
458 return $indexes;
459 }
460
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'] );
467 }
468
469 /**
470 * @covers DatabaseSqlite::numFields
471 */
472 public function testNumFields() {
473 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
474
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" );
483
484 $this->assertTrue( $db->close(), "closing database" );
485 }
486
487 public function testToString() {
488 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
489
490 $toString = (string)$db;
491
492 $this->assertContains( 'SQLite ', $toString );
493 }
494 }