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