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