Don't check namespace in SpecialWantedtemplates
[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 = array() ) {
7 $p['dbFilePath'] = ':memory:';
8 $p['schema'] = false;
9
10 return DatabaseBase::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 array(
68 array( // #0: empty
69 '', "''"
70 ),
71 array( // #1: simple
72 'foo bar', "'foo bar'"
73 ),
74 array( // #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 array(
79 "x\0y",
80 "x'780079'",
81 ),
82 array( // #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 if ( $row = $re->fetchRow() ) {
104 if ( $value instanceof Blob ) {
105 $value = $value->fetch();
106 }
107
108 $this->assertEquals( $value, $row[0], 'string mangled by the database' );
109 } else {
110 $this->fail( 'query returned no result' );
111 }
112 }
113
114 /**
115 * @covers DatabaseSqlite::replaceVars
116 */
117 public function testReplaceVars() {
118 $this->assertEquals( 'foo', $this->replaceVars( 'foo' ), "Don't break anything accidentally" );
119
120 $this->assertEquals(
121 "CREATE TABLE /**/foo (foo_key INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "
122 . "foo_bar TEXT, foo_name TEXT NOT NULL DEFAULT '', foo_int INTEGER, foo_int2 INTEGER );",
123 $this->replaceVars(
124 "CREATE TABLE /**/foo (foo_key int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT, "
125 . "foo_bar char(13), foo_name varchar(255) binary NOT NULL DEFAULT '', "
126 . "foo_int tinyint ( 8 ), foo_int2 int(16) ) ENGINE=MyISAM;"
127 )
128 );
129
130 $this->assertEquals(
131 "CREATE TABLE foo ( foo1 REAL, foo2 REAL, foo3 REAL );",
132 $this->replaceVars(
133 "CREATE TABLE foo ( foo1 FLOAT, foo2 DOUBLE( 1,10), foo3 DOUBLE PRECISION );"
134 )
135 );
136
137 $this->assertEquals( "CREATE TABLE foo ( foo_binary1 BLOB, foo_binary2 BLOB );",
138 $this->replaceVars( "CREATE TABLE foo ( foo_binary1 binary(16), foo_binary2 varbinary(32) );" )
139 );
140
141 $this->assertEquals( "CREATE TABLE text ( text_foo TEXT );",
142 $this->replaceVars( "CREATE TABLE text ( text_foo tinytext );" ),
143 'Table name changed'
144 );
145
146 $this->assertEquals( "CREATE TABLE foo ( foobar INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL );",
147 $this->replaceVars( "CREATE TABLE foo ( foobar INT PRIMARY KEY NOT NULL AUTO_INCREMENT );" )
148 );
149 $this->assertEquals( "CREATE TABLE foo ( foobar INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL );",
150 $this->replaceVars( "CREATE TABLE foo ( foobar INT PRIMARY KEY AUTO_INCREMENT NOT NULL );" )
151 );
152
153 $this->assertEquals( "CREATE TABLE enums( enum1 TEXT, myenum TEXT)",
154 $this->replaceVars( "CREATE TABLE enums( enum1 ENUM('A', 'B'), myenum ENUM ('X', 'Y'))" )
155 );
156
157 $this->assertEquals( "ALTER TABLE foo ADD COLUMN foo_bar INTEGER DEFAULT 42",
158 $this->replaceVars( "ALTER TABLE foo\nADD COLUMN foo_bar int(10) unsigned DEFAULT 42" )
159 );
160
161 $this->assertEquals( "DROP INDEX foo",
162 $this->replaceVars( "DROP INDEX /*i*/foo ON /*_*/bar" )
163 );
164
165 $this->assertEquals( "DROP INDEX foo -- dropping index",
166 $this->replaceVars( "DROP INDEX /*i*/foo ON /*_*/bar -- dropping index" )
167 );
168 $this->assertEquals( "INSERT OR IGNORE INTO foo VALUES ('bar')",
169 $this->replaceVars( "INSERT OR IGNORE INTO foo VALUES ('bar')" )
170 );
171 }
172
173 /**
174 * @covers DatabaseSqlite::tableName
175 */
176 public function testTableName() {
177 // @todo Moar!
178 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
179 $this->assertEquals( 'foo', $db->tableName( 'foo' ) );
180 $this->assertEquals( 'sqlite_master', $db->tableName( 'sqlite_master' ) );
181 $db->tablePrefix( 'foo' );
182 $this->assertEquals( 'sqlite_master', $db->tableName( 'sqlite_master' ) );
183 $this->assertEquals( 'foobar', $db->tableName( 'bar' ) );
184 }
185
186 /**
187 * @covers DatabaseSqlite::duplicateTableStructure
188 */
189 public function testDuplicateTableStructure() {
190 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
191 $db->query( 'CREATE TABLE foo(foo, barfoo)' );
192
193 $db->duplicateTableStructure( 'foo', 'bar' );
194 $this->assertEquals( 'CREATE TABLE "bar"(foo, barfoo)',
195 $db->selectField( 'sqlite_master', 'sql', array( 'name' => 'bar' ) ),
196 'Normal table duplication'
197 );
198
199 $db->duplicateTableStructure( 'foo', 'baz', true );
200 $this->assertEquals( 'CREATE TABLE "baz"(foo, barfoo)',
201 $db->selectField( 'sqlite_temp_master', 'sql', array( 'name' => 'baz' ) ),
202 'Creation of temporary duplicate'
203 );
204 $this->assertEquals( 0,
205 $db->selectField( 'sqlite_master', 'COUNT(*)', array( 'name' => 'baz' ) ),
206 'Create a temporary duplicate only'
207 );
208 }
209
210 /**
211 * @covers DatabaseSqlite::duplicateTableStructure
212 */
213 public function testDuplicateTableStructureVirtual() {
214 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
215 if ( $db->getFulltextSearchModule() != 'FTS3' ) {
216 $this->markTestSkipped( 'FTS3 not supported, cannot create virtual tables' );
217 }
218 $db->query( 'CREATE VIRTUAL TABLE "foo" USING FTS3(foobar)' );
219
220 $db->duplicateTableStructure( 'foo', 'bar' );
221 $this->assertEquals( 'CREATE VIRTUAL TABLE "bar" USING FTS3(foobar)',
222 $db->selectField( 'sqlite_master', 'sql', array( 'name' => 'bar' ) ),
223 'Duplication of virtual tables'
224 );
225
226 $db->duplicateTableStructure( 'foo', 'baz', true );
227 $this->assertEquals( 'CREATE VIRTUAL TABLE "baz" USING FTS3(foobar)',
228 $db->selectField( 'sqlite_master', 'sql', array( 'name' => 'baz' ) ),
229 "Can't create temporary virtual tables, should fall back to non-temporary duplication"
230 );
231 }
232
233 /**
234 * @covers DatabaseSqlite::deleteJoin
235 */
236 public function testDeleteJoin() {
237 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
238 $db->query( 'CREATE TABLE a (a_1)', __METHOD__ );
239 $db->query( 'CREATE TABLE b (b_1, b_2)', __METHOD__ );
240 $db->insert( 'a', array(
241 array( 'a_1' => 1 ),
242 array( 'a_1' => 2 ),
243 array( 'a_1' => 3 ),
244 ),
245 __METHOD__
246 );
247 $db->insert( 'b', array(
248 array( 'b_1' => 2, 'b_2' => 'a' ),
249 array( 'b_1' => 3, 'b_2' => 'b' ),
250 ),
251 __METHOD__
252 );
253 $db->deleteJoin( 'a', 'b', 'a_1', 'b_1', array( 'b_2' => 'a' ), __METHOD__ );
254 $res = $db->query( "SELECT * FROM a", __METHOD__ );
255 $this->assertResultIs( array(
256 array( 'a_1' => 1 ),
257 array( 'a_1' => 3 ),
258 ),
259 $res
260 );
261 }
262
263 public function testEntireSchema() {
264 global $IP;
265
266 $result = Sqlite::checkSqlSyntax( "$IP/maintenance/tables.sql" );
267 if ( $result !== true ) {
268 $this->fail( $result );
269 }
270 $this->assertTrue( true ); // avoid test being marked as incomplete due to lack of assertions
271 }
272
273 /**
274 * Runs upgrades of older databases and compares results with current schema
275 * @todo Currently only checks list of tables
276 */
277 public function testUpgrades() {
278 global $IP, $wgVersion, $wgProfiler;
279
280 // Versions tested
281 $versions = array(
282 //'1.13', disabled for now, was totally screwed up
283 // SQLite wasn't included in 1.14
284 '1.15',
285 '1.16',
286 '1.17',
287 '1.18',
288 );
289
290 // Mismatches for these columns we can safely ignore
291 $ignoredColumns = array(
292 'user_newtalk.user_last_timestamp', // r84185
293 );
294
295 $currentDB = DatabaseSqlite::newStandaloneInstance( ':memory:' );
296 $currentDB->sourceFile( "$IP/maintenance/tables.sql" );
297
298 $profileToDb = false;
299 if ( isset( $wgProfiler['output'] ) ) {
300 $out = $wgProfiler['output'];
301 if ( $out === 'db' ) {
302 $profileToDb = true;
303 } elseif ( is_array( $out ) && in_array( 'db', $out ) ) {
304 $profileToDb = true;
305 }
306 }
307
308 if ( $profileToDb ) {
309 $currentDB->sourceFile( "$IP/maintenance/sqlite/archives/patch-profiling.sql" );
310 }
311 $currentTables = $this->getTables( $currentDB );
312 sort( $currentTables );
313
314 foreach ( $versions as $version ) {
315 $versions = "upgrading from $version to $wgVersion";
316 $db = $this->prepareDB( $version );
317 $tables = $this->getTables( $db );
318 $this->assertEquals( $currentTables, $tables, "Different tables $versions" );
319 foreach ( $tables as $table ) {
320 $currentCols = $this->getColumns( $currentDB, $table );
321 $cols = $this->getColumns( $db, $table );
322 $this->assertEquals(
323 array_keys( $currentCols ),
324 array_keys( $cols ),
325 "Mismatching columns for table \"$table\" $versions"
326 );
327 foreach ( $currentCols as $name => $column ) {
328 $fullName = "$table.$name";
329 $this->assertEquals(
330 (bool)$column->pk,
331 (bool)$cols[$name]->pk,
332 "PRIMARY KEY status does not match for column $fullName $versions"
333 );
334 if ( !in_array( $fullName, $ignoredColumns ) ) {
335 $this->assertEquals(
336 (bool)$column->notnull,
337 (bool)$cols[$name]->notnull,
338 "NOT NULL status does not match for column $fullName $versions"
339 );
340 $this->assertEquals(
341 $column->dflt_value,
342 $cols[$name]->dflt_value,
343 "Default values does not match for column $fullName $versions"
344 );
345 }
346 }
347 $currentIndexes = $this->getIndexes( $currentDB, $table );
348 $indexes = $this->getIndexes( $db, $table );
349 $this->assertEquals(
350 array_keys( $currentIndexes ),
351 array_keys( $indexes ),
352 "mismatching indexes for table \"$table\" $versions"
353 );
354 }
355 $db->close();
356 }
357 }
358
359 /**
360 * @covers DatabaseSqlite::insertId
361 */
362 public function testInsertIdType() {
363 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
364
365 $databaseCreation = $db->query( 'CREATE TABLE a ( a_1 )', __METHOD__ );
366 $this->assertInstanceOf( 'ResultWrapper', $databaseCreation, "Database creation" );
367
368 $insertion = $db->insert( 'a', array( 'a_1' => 10 ), __METHOD__ );
369 $this->assertTrue( $insertion, "Insertion worked" );
370
371 $this->assertInternalType( 'integer', $db->insertId(), "Actual typecheck" );
372 $this->assertTrue( $db->close(), "closing database" );
373 }
374
375 private function prepareDB( $version ) {
376 static $maint = null;
377 if ( $maint === null ) {
378 $maint = new FakeMaintenance();
379 $maint->loadParamsAndArgs( null, array( 'quiet' => 1 ) );
380 }
381
382 global $IP;
383 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
384 $db->sourceFile( "$IP/tests/phpunit/data/db/sqlite/tables-$version.sql" );
385 $updater = DatabaseUpdater::newForDB( $db, false, $maint );
386 $updater->doUpdates( array( 'core' ) );
387
388 return $db;
389 }
390
391 private function getTables( $db ) {
392 $list = array_flip( $db->listTables() );
393 $excluded = array(
394 'external_user', // removed from core in 1.22
395 'math', // moved out of core in 1.18
396 'trackbacks', // removed from core in 1.19
397 'searchindex',
398 'searchindex_content',
399 'searchindex_segments',
400 'searchindex_segdir',
401 // FTS4 ready!!1
402 'searchindex_docsize',
403 'searchindex_stat',
404 );
405 foreach ( $excluded as $t ) {
406 unset( $list[$t] );
407 }
408 $list = array_flip( $list );
409 sort( $list );
410
411 return $list;
412 }
413
414 private function getColumns( $db, $table ) {
415 $cols = array();
416 $res = $db->query( "PRAGMA table_info($table)" );
417 $this->assertNotNull( $res );
418 foreach ( $res as $col ) {
419 $cols[$col->name] = $col;
420 }
421 ksort( $cols );
422
423 return $cols;
424 }
425
426 private function getIndexes( $db, $table ) {
427 $indexes = array();
428 $res = $db->query( "PRAGMA index_list($table)" );
429 $this->assertNotNull( $res );
430 foreach ( $res as $index ) {
431 $res2 = $db->query( "PRAGMA index_info({$index->name})" );
432 $this->assertNotNull( $res2 );
433 $index->columns = array();
434 foreach ( $res2 as $col ) {
435 $index->columns[] = $col;
436 }
437 $indexes[$index->name] = $index;
438 }
439 ksort( $indexes );
440
441 return $indexes;
442 }
443
444 public function testCaseInsensitiveLike() {
445 // TODO: Test this for all databases
446 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
447 $res = $db->query( 'SELECT "a" LIKE "A" AS a' );
448 $row = $res->fetchRow();
449 $this->assertFalse( (bool)$row['a'] );
450 }
451
452 /**
453 * @covers DatabaseSqlite::numFields
454 */
455 public function testNumFields() {
456 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
457
458 $databaseCreation = $db->query( 'CREATE TABLE a ( a_1 )', __METHOD__ );
459 $this->assertInstanceOf( 'ResultWrapper', $databaseCreation, "Failed to create table a" );
460 $res = $db->select( 'a', '*' );
461 $this->assertEquals( 0, $db->numFields( $res ), "expects to get 0 fields for an empty table" );
462 $insertion = $db->insert( 'a', array( 'a_1' => 10 ), __METHOD__ );
463 $this->assertTrue( $insertion, "Insertion failed" );
464 $res = $db->select( 'a', '*' );
465 $this->assertEquals( 1, $db->numFields( $res ), "wrong number of fields" );
466
467 $this->assertTrue( $db->close(), "closing database" );
468 }
469 }