MediaWiki REL1_33
DatabaseSqliteTest.php
Go to the documentation of this file.
1<?php
2
7
15 protected $db;
16
17 protected function setUp() {
18 parent::setUp();
19
20 if ( !Sqlite::isPresent() ) {
21 $this->markTestSkipped( 'No SQLite support detected' );
22 }
24 if ( version_compare( $this->db->getServerVersion(), '3.6.0', '<' ) ) {
25 $this->markTestSkipped( "SQLite at least 3.6 required, {$this->db->getServerVersion()} found" );
26 }
27 }
28
29 private function replaceVars( $sql ) {
30 // normalize spacing to hide implementation details
31 return preg_replace( '/\s+/', ' ', $this->db->replaceVars( $sql ) );
32 }
33
34 private function assertResultIs( $expected, $res ) {
35 $this->assertNotNull( $res );
36 $i = 0;
37 foreach ( $res as $row ) {
38 foreach ( $expected[$i] as $key => $value ) {
39 $this->assertTrue( isset( $row->$key ) );
40 $this->assertEquals( $value, $row->$key );
41 }
42 $i++;
43 }
44 $this->assertEquals( count( $expected ), $i, 'Unexpected number of rows' );
45 }
46
47 public static function provideAddQuotes() {
48 return [
49 [ // #0: empty
50 '', "''"
51 ],
52 [ // #1: simple
53 'foo bar', "'foo bar'"
54 ],
55 [ // #2: including quote
56 'foo\'bar', "'foo''bar'"
57 ],
58 // #3: including \0 (must be represented as hex, per https://bugs.php.net/bug.php?id=63419)
59 [
60 "x\0y",
61 "x'780079'",
62 ],
63 [ // #4: blob object (must be represented as hex)
64 new Blob( "hello" ),
65 "x'68656c6c6f'",
66 ],
67 [ // #5: null
68 null,
69 "''",
70 ],
71 ];
72 }
73
78 public function testAddQuotes( $value, $expected ) {
79 // check quoting
80 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
81 $this->assertEquals( $expected, $db->addQuotes( $value ), 'string not quoted as expected' );
82
83 // ok, quoting works as expected, now try a round trip.
84 $re = $db->query( 'select ' . $db->addQuotes( $value ) );
85
86 $this->assertTrue( $re !== false, 'query failed' );
87
88 $row = $re->fetchRow();
89 if ( $row ) {
90 if ( $value instanceof Blob ) {
91 $value = $value->fetch();
92 }
93
94 $this->assertEquals( $value, $row[0], 'string mangled by the database' );
95 } else {
96 $this->fail( 'query returned no result' );
97 }
98 }
99
103 public function testReplaceVars() {
104 $this->assertEquals( 'foo', $this->replaceVars( 'foo' ), "Don't break anything accidentally" );
105
106 $this->assertEquals(
107 "CREATE TABLE /**/foo (foo_key INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "
108 . "foo_bar TEXT, foo_name TEXT NOT NULL DEFAULT '', foo_int INTEGER, foo_int2 INTEGER );",
109 $this->replaceVars(
110 "CREATE TABLE /**/foo (foo_key int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT, "
111 . "foo_bar char(13), foo_name varchar(255) binary NOT NULL DEFAULT '', "
112 . "foo_int tinyint ( 8 ), foo_int2 int(16) ) ENGINE=MyISAM;"
113 )
114 );
115
116 $this->assertEquals(
117 "CREATE TABLE foo ( foo1 REAL, foo2 REAL, foo3 REAL );",
118 $this->replaceVars(
119 "CREATE TABLE foo ( foo1 FLOAT, foo2 DOUBLE( 1,10), foo3 DOUBLE PRECISION );"
120 )
121 );
122
123 $this->assertEquals( "CREATE TABLE foo ( foo_binary1 BLOB, foo_binary2 BLOB );",
124 $this->replaceVars( "CREATE TABLE foo ( foo_binary1 binary(16), foo_binary2 varbinary(32) );" )
125 );
126
127 $this->assertEquals( "CREATE TABLE text ( text_foo TEXT );",
128 $this->replaceVars( "CREATE TABLE text ( text_foo tinytext );" ),
129 'Table name changed'
130 );
131
132 $this->assertEquals( "CREATE TABLE foo ( foobar INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL );",
133 $this->replaceVars( "CREATE TABLE foo ( foobar INT PRIMARY KEY NOT NULL AUTO_INCREMENT );" )
134 );
135 $this->assertEquals( "CREATE TABLE foo ( foobar INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL );",
136 $this->replaceVars( "CREATE TABLE foo ( foobar INT PRIMARY KEY AUTO_INCREMENT NOT NULL );" )
137 );
138
139 $this->assertEquals( "CREATE TABLE enums( enum1 TEXT, myenum TEXT)",
140 $this->replaceVars( "CREATE TABLE enums( enum1 ENUM('A', 'B'), myenum ENUM ('X', 'Y'))" )
141 );
142
143 $this->assertEquals( "ALTER TABLE foo ADD COLUMN foo_bar INTEGER DEFAULT 42",
144 $this->replaceVars( "ALTER TABLE foo\nADD COLUMN foo_bar int(10) unsigned DEFAULT 42" )
145 );
146
147 $this->assertEquals( "DROP INDEX foo",
148 $this->replaceVars( "DROP INDEX /*i*/foo ON /*_*/bar" )
149 );
150
151 $this->assertEquals( "DROP INDEX foo -- dropping index",
152 $this->replaceVars( "DROP INDEX /*i*/foo ON /*_*/bar -- dropping index" )
153 );
154 $this->assertEquals( "INSERT OR IGNORE INTO foo VALUES ('bar')",
155 $this->replaceVars( "INSERT OR IGNORE INTO foo VALUES ('bar')" )
156 );
157 }
158
162 public function testTableName() {
163 // @todo Moar!
164 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
165 $this->assertEquals( 'foo', $db->tableName( 'foo' ) );
166 $this->assertEquals( 'sqlite_master', $db->tableName( 'sqlite_master' ) );
167 $db->tablePrefix( 'foo_' );
168 $this->assertEquals( 'sqlite_master', $db->tableName( 'sqlite_master' ) );
169 $this->assertEquals( 'foo_bar', $db->tableName( 'bar' ) );
170 }
171
175 public function testDuplicateTableStructure() {
176 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
177 $db->query( 'CREATE TABLE foo(foo, barfoo)' );
178 $db->query( 'CREATE INDEX index1 ON foo(foo)' );
179 $db->query( 'CREATE UNIQUE INDEX index2 ON foo(barfoo)' );
180
181 $db->duplicateTableStructure( 'foo', 'bar' );
182 $this->assertEquals( 'CREATE TABLE "bar"(foo, barfoo)',
183 $db->selectField( 'sqlite_master', 'sql', [ 'name' => 'bar' ] ),
184 'Normal table duplication'
185 );
186 $indexList = $db->query( 'PRAGMA INDEX_LIST("bar")' );
187 $index = $indexList->next();
188 $this->assertEquals( 'bar_index1', $index->name );
189 $this->assertEquals( '0', $index->unique );
190 $index = $indexList->next();
191 $this->assertEquals( 'bar_index2', $index->name );
192 $this->assertEquals( '1', $index->unique );
193
194 $db->duplicateTableStructure( 'foo', 'baz', true );
195 $this->assertEquals( 'CREATE TABLE "baz"(foo, barfoo)',
196 $db->selectField( 'sqlite_temp_master', 'sql', [ 'name' => 'baz' ] ),
197 'Creation of temporary duplicate'
198 );
199 $indexList = $db->query( 'PRAGMA INDEX_LIST("baz")' );
200 $index = $indexList->next();
201 $this->assertEquals( 'baz_index1', $index->name );
202 $this->assertEquals( '0', $index->unique );
203 $index = $indexList->next();
204 $this->assertEquals( 'baz_index2', $index->name );
205 $this->assertEquals( '1', $index->unique );
206 $this->assertEquals( 0,
207 $db->selectField( 'sqlite_master', 'COUNT(*)', [ 'name' => 'baz' ] ),
208 'Create a temporary duplicate only'
209 );
210 }
211
216 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
217 if ( $db->getFulltextSearchModule() != 'FTS3' ) {
218 $this->markTestSkipped( 'FTS3 not supported, cannot create virtual tables' );
219 }
220 $db->query( 'CREATE VIRTUAL TABLE "foo" USING FTS3(foobar)' );
221
222 $db->duplicateTableStructure( 'foo', 'bar' );
223 $this->assertEquals( 'CREATE VIRTUAL TABLE "bar" USING FTS3(foobar)',
224 $db->selectField( 'sqlite_master', 'sql', [ 'name' => 'bar' ] ),
225 'Duplication of virtual tables'
226 );
227
228 $db->duplicateTableStructure( 'foo', 'baz', true );
229 $this->assertEquals( 'CREATE VIRTUAL TABLE "baz" USING FTS3(foobar)',
230 $db->selectField( 'sqlite_master', 'sql', [ 'name' => 'baz' ] ),
231 "Can't create temporary virtual tables, should fall back to non-temporary duplication"
232 );
233 }
234
238 public function testDeleteJoin() {
239 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
240 $db->query( 'CREATE TABLE a (a_1)', __METHOD__ );
241 $db->query( 'CREATE TABLE b (b_1, b_2)', __METHOD__ );
242 $db->insert( 'a', [
243 [ 'a_1' => 1 ],
244 [ 'a_1' => 2 ],
245 [ 'a_1' => 3 ],
246 ],
247 __METHOD__
248 );
249 $db->insert( 'b', [
250 [ 'b_1' => 2, 'b_2' => 'a' ],
251 [ 'b_1' => 3, 'b_2' => 'b' ],
252 ],
253 __METHOD__
254 );
255 $db->deleteJoin( 'a', 'b', 'a_1', 'b_1', [ 'b_2' => 'a' ], __METHOD__ );
256 $res = $db->query( "SELECT * FROM a", __METHOD__ );
257 $this->assertResultIs( [
258 [ 'a_1' => 1 ],
259 [ 'a_1' => 3 ],
260 ],
261 $res
262 );
263 }
264
268 public function testEntireSchema() {
269 global $IP;
270
271 $result = Sqlite::checkSqlSyntax( "$IP/maintenance/tables.sql" );
272 if ( $result !== true ) {
273 $this->fail( $result );
274 }
275 $this->assertTrue( true ); // avoid test being marked as incomplete due to lack of assertions
276 }
277
283 public function testUpgrades() {
284 global $IP, $wgVersion, $wgProfiler;
285
286 // Versions tested
287 $versions = [
288 // '1.13', disabled for now, was totally screwed up
289 // SQLite wasn't included in 1.14
290 '1.15',
291 '1.16',
292 '1.17',
293 '1.18',
294 '1.19',
295 '1.20',
296 '1.21',
297 '1.22',
298 '1.23',
299 ];
300
301 // Mismatches for these columns we can safely ignore
302 $ignoredColumns = [
303 'user_newtalk.user_last_timestamp', // r84185
304 ];
305
306 $currentDB = DatabaseSqlite::newStandaloneInstance( ':memory:' );
307 $currentDB->sourceFile( "$IP/maintenance/tables.sql" );
308
309 $profileToDb = false;
310 if ( isset( $wgProfiler['output'] ) ) {
311 $out = $wgProfiler['output'];
312 if ( $out === 'db' ) {
313 $profileToDb = true;
314 } elseif ( is_array( $out ) && in_array( 'db', $out ) ) {
315 $profileToDb = true;
316 }
317 }
318
319 if ( $profileToDb ) {
320 $currentDB->sourceFile( "$IP/maintenance/sqlite/archives/patch-profiling.sql" );
321 }
322 $currentTables = $this->getTables( $currentDB );
323 sort( $currentTables );
324
325 foreach ( $versions as $version ) {
326 $versions = "upgrading from $version to $wgVersion";
327 $db = $this->prepareTestDB( $version );
328 $tables = $this->getTables( $db );
329 $this->assertEquals( $currentTables, $tables, "Different tables $versions" );
330 foreach ( $tables as $table ) {
331 $currentCols = $this->getColumns( $currentDB, $table );
332 $cols = $this->getColumns( $db, $table );
333 $this->assertEquals(
334 array_keys( $currentCols ),
335 array_keys( $cols ),
336 "Mismatching columns for table \"$table\" $versions"
337 );
338 foreach ( $currentCols as $name => $column ) {
339 $fullName = "$table.$name";
340 $this->assertEquals(
341 (bool)$column->pk,
342 (bool)$cols[$name]->pk,
343 "PRIMARY KEY status does not match for column $fullName $versions"
344 );
345 if ( !in_array( $fullName, $ignoredColumns ) ) {
346 $this->assertEquals(
347 (bool)$column->notnull,
348 (bool)$cols[$name]->notnull,
349 "NOT NULL status does not match for column $fullName $versions"
350 );
351 $this->assertEquals(
352 $column->dflt_value,
353 $cols[$name]->dflt_value,
354 "Default values does not match for column $fullName $versions"
355 );
356 }
357 }
358 $currentIndexes = $this->getIndexes( $currentDB, $table );
359 $indexes = $this->getIndexes( $db, $table );
360 $this->assertEquals(
361 array_keys( $currentIndexes ),
362 array_keys( $indexes ),
363 "mismatching indexes for table \"$table\" $versions"
364 );
365 }
366 $db->close();
367 }
368 }
369
373 public function testInsertIdType() {
374 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
375
376 $databaseCreation = $db->query( 'CREATE TABLE a ( a_1 )', __METHOD__ );
377 $this->assertInstanceOf( ResultWrapper::class, $databaseCreation, "Database creation" );
378
379 $insertion = $db->insert( 'a', [ 'a_1' => 10 ], __METHOD__ );
380 $this->assertTrue( $insertion, "Insertion worked" );
381
382 $this->assertInternalType( 'integer', $db->insertId(), "Actual typecheck" );
383 $this->assertTrue( $db->close(), "closing database" );
384 }
385
389 public function testInsertAffectedRows() {
390 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
391 $db->query( 'CREATE TABLE testInsertAffectedRows ( foo )', __METHOD__ );
392
393 $insertion = $db->insert(
394 'testInsertAffectedRows',
395 [
396 [ 'foo' => 10 ],
397 [ 'foo' => 12 ],
398 [ 'foo' => 1555 ],
399 ],
400 __METHOD__
401 );
402 $this->assertTrue( $insertion, "Insertion worked" );
403
404 $this->assertSame( 3, $db->affectedRows() );
405 $this->assertTrue( $db->close(), "closing database" );
406 }
407
408 private function prepareTestDB( $version ) {
409 static $maint = null;
410 if ( $maint === null ) {
411 $maint = new FakeMaintenance();
412 $maint->loadParamsAndArgs( null, [ 'quiet' => 1 ] );
413 }
414
415 global $IP;
416 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
417 $db->sourceFile( "$IP/tests/phpunit/data/db/sqlite/tables-$version.sql" );
418 $updater = DatabaseUpdater::newForDB( $db, false, $maint );
419 $updater->doUpdates( [ 'core' ] );
420
421 return $db;
422 }
423
424 private function getTables( $db ) {
425 $list = array_flip( $db->listTables() );
426 $excluded = [
427 'external_user', // removed from core in 1.22
428 'math', // moved out of core in 1.18
429 'trackbacks', // removed from core in 1.19
430 'searchindex',
431 'searchindex_content',
432 'searchindex_segments',
433 'searchindex_segdir',
434 // FTS4 ready!!1
435 'searchindex_docsize',
436 'searchindex_stat',
437 ];
438 foreach ( $excluded as $t ) {
439 unset( $list[$t] );
440 }
441 $list = array_flip( $list );
442 sort( $list );
443
444 return $list;
445 }
446
447 private function getColumns( $db, $table ) {
448 $cols = [];
449 $res = $db->query( "PRAGMA table_info($table)" );
450 $this->assertNotNull( $res );
451 foreach ( $res as $col ) {
452 $cols[$col->name] = $col;
453 }
454 ksort( $cols );
455
456 return $cols;
457 }
458
459 private function getIndexes( $db, $table ) {
460 $indexes = [];
461 $res = $db->query( "PRAGMA index_list($table)" );
462 $this->assertNotNull( $res );
463 foreach ( $res as $index ) {
464 $res2 = $db->query( "PRAGMA index_info({$index->name})" );
465 $this->assertNotNull( $res2 );
466 $index->columns = [];
467 foreach ( $res2 as $col ) {
468 $index->columns[] = $col;
469 }
470 $indexes[$index->name] = $index;
471 }
472 ksort( $indexes );
473
474 return $indexes;
475 }
476
480 public function testCaseInsensitiveLike() {
481 // TODO: Test this for all databases
482 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
483 $res = $db->query( 'SELECT "a" LIKE "A" AS a' );
484 $row = $res->fetchRow();
485 $this->assertFalse( (bool)$row['a'] );
486 }
487
491 public function testNumFields() {
492 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
493
494 $databaseCreation = $db->query( 'CREATE TABLE a ( a_1 )', __METHOD__ );
495 $this->assertInstanceOf( ResultWrapper::class, $databaseCreation, "Failed to create table a" );
496 $res = $db->select( 'a', '*' );
497 $this->assertEquals( 0, $db->numFields( $res ), "expects to get 0 fields for an empty table" );
498 $insertion = $db->insert( 'a', [ 'a_1' => 10 ], __METHOD__ );
499 $this->assertTrue( $insertion, "Insertion failed" );
500 $res = $db->select( 'a', '*' );
501 $this->assertEquals( 1, $db->numFields( $res ), "wrong number of fields" );
502
503 $this->assertTrue( $db->close(), "closing database" );
504 }
505
509 public function testToString() {
510 $db = DatabaseSqlite::newStandaloneInstance( ':memory:' );
511
512 $toString = (string)$db;
513
514 $this->assertContains( 'SQLite ', $toString );
515 }
516
520 public function testsAttributes() {
521 $attributes = Database::attributesFromType( 'sqlite' );
522 $this->assertTrue( $attributes[Database::ATTR_DB_LEVEL_LOCKING] );
523 }
524}
525
527 public static function newInstance( array $p = [] ) {
528 $p['dbFilePath'] = ':memory:';
529 $p['schema'] = false;
530
531 return Database::factory( 'SqliteMock', $p );
532 }
533
534 function query( $sql, $fname = '', $flags = 0 ) {
535 return true;
536 }
537
541 public function replaceVars( $s ) {
542 return parent::replaceVars( $s );
543 }
544}
and that you know you can do these things To protect your we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights These restrictions translate to certain responsibilities for you if you distribute copies of the or if you modify it For if you distribute copies of such a whether gratis or for a you must give the recipients all the rights that you have You must make sure that receive or can get the source code And you must show them these terms so they know their rights We protect your rights with two and(2) offer you this license which gives you legal permission to copy
$wgProfiler
Profiler configuration.
$wgVersion
MediaWiki version number.
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
Definition Setup.php:123
replaceVars( $s)
Override parent visibility to public.
query( $sql, $fname='', $flags=0)
Run an SQL query and return the result.
static newInstance(array $p=[])
sqlite Database medium
testCaseInsensitiveLike()
@coversNothing
testDuplicateTableStructureVirtual()
DatabaseSqlite::duplicateTableStructure.
testInsertIdType()
DatabaseSqlite::insertId.
assertResultIs( $expected, $res)
testAddQuotes( $value, $expected)
provideAddQuotes() DatabaseSqlite::addQuotes
testUpgrades()
Runs upgrades of older databases and compares results with current schema.
testInsertAffectedRows()
DatabaseSqlite::insert.
testToString()
\Wikimedia\Rdbms\DatabaseSqlite::__toString
testReplaceVars()
DatabaseSqlite::replaceVars.
DatabaseSqliteMock $db
testTableName()
DatabaseSqlite::tableName.
testEntireSchema()
@coversNothing
testNumFields()
DatabaseSqlite::numFields.
testDuplicateTableStructure()
DatabaseSqlite::duplicateTableStructure.
testsAttributes()
\Wikimedia\Rdbms\DatabaseSqlite::getAttributes()
testDeleteJoin()
DatabaseSqlite::deleteJoin.
static newForDB(IMaintainableDatabase $db, $shared=false, Maintenance $maintenance=null)
Fake maintenance wrapper, mostly used for the web installer/updater.
static isPresent()
Checks whether PHP has SQLite support.
Definition sqlite.inc:38
static checkSqlSyntax( $files)
Checks given files for correctness of SQL syntax.
Definition sqlite.inc:50
tableName( $name, $format='quoted')
Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks.
static getFulltextSearchModule()
Returns version of currently supported SQLite fulltext search module or false if none present.
listTables( $prefix=null, $fname=__METHOD__)
List all tables on the database.
duplicateTableStructure( $oldName, $newName, $temporary=false, $fname=__METHOD__)
insertId()
This must be called after nextSequenceVal.
insert( $table, $a, $fname=__METHOD__, $options=[])
Based on generic method (parent) with some prior SQLite-sepcific adjustments.
Relational database abstraction object.
Definition Database.php:49
tablePrefix( $prefix=null)
Get/set the table prefix.
Definition Database.php:607
select( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname=__METHOD__)
DELETE where the condition is a join.
affectedRows()
Get the number of rows affected by the last write query.
sourceFile( $filename, callable $lineCallback=null, callable $resultCallback=null, $fname=false, callable $inputCallback=null)
Read and execute SQL commands from a file.
close()
Close the database connection.
Definition Database.php:943
selectField( $table, $var, $cond='', $fname=__METHOD__, $options=[], $join_conds=[])
A SELECT wrapper which returns a single field from a single result row.
Result wrapper for grabbing data queried from an IDatabase object.
$res
Definition database.txt:21
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition hooks.txt:855
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
Definition hooks.txt:181
this hook is for auditing only RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist & $tables
Definition hooks.txt:996
$IP
Definition update.php:3
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
$page->newPageUpdater($user) $updater