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