MediaWiki  1.33.0
DatabaseTestHelper.php
Go to the documentation of this file.
1 <?php
2 
6 
12 
17  protected $testName = [];
18 
24  protected $lastSqls = [];
25 
27  protected $nextResult = [];
28 
30  protected $nextError = null;
32  protected $lastError = null;
33 
38  protected $tablesExists;
39 
43  protected $unionSupportsOrderAndLimit = true;
44 
45  public function __construct( $testName, array $opts = [] ) {
46  $this->testName = $testName;
47 
48  $this->profiler = null;
49  $this->trxProfiler = new TransactionProfiler();
50  $this->cliMode = $opts['cliMode'] ?? true;
51  $this->connLogger = new \Psr\Log\NullLogger();
52  $this->queryLogger = new \Psr\Log\NullLogger();
53  $this->errorLogger = function ( Exception $e ) {
54  wfWarn( get_class( $e ) . ": {$e->getMessage()}" );
55  };
56  $this->deprecationLogger = function ( $msg ) {
57  wfWarn( $msg );
58  };
59  $this->currentDomain = DatabaseDomain::newUnspecified();
60  $this->open( 'localhost', 'testuser', 'password', 'testdb', null, '' );
61  }
62 
68  public function getLastSqls() {
69  $lastSqls = implode( '; ', $this->lastSqls );
70  $this->lastSqls = [];
71 
72  return $lastSqls;
73  }
74 
75  public function setExistingTables( $tablesExists ) {
76  $this->tablesExists = (array)$tablesExists;
77  }
78 
82  public function forceNextResult( $res ) {
83  $this->nextResult = $res;
84  }
85 
92  public function forceNextQueryError( $errno, $error, $options = [] ) {
93  $this->nextError = [ 'errno' => $errno, 'error' => $error ] + $options;
94  }
95 
96  protected function addSql( $sql ) {
97  // clean up spaces before and after some words and the whole string
98  $this->lastSqls[] = trim( preg_replace(
99  '/\s{2,}(?=FROM|WHERE|GROUP BY|ORDER BY|LIMIT)|(?<=SELECT|INSERT|UPDATE)\s{2,}/',
100  ' ', $sql
101  ) );
102  }
103 
104  protected function checkFunctionName( $fname ) {
105  if ( $fname === 'Wikimedia\\Rdbms\\Database::close' ) {
106  return; // no $fname parameter
107  }
108 
109  // Handle some internal calls from the Database class
110  $check = $fname;
111  if ( preg_match(
112  '/^Wikimedia\\\\Rdbms\\\\Database::(?:query|beginIfImplied) \((.+)\)$/',
113  $fname,
114  $m
115  ) ) {
116  $check = $m[1];
117  }
118 
119  if ( substr( $check, 0, strlen( $this->testName ) ) !== $this->testName ) {
120  throw new MWException( 'function name does not start with test class. ' .
121  $fname . ' vs. ' . $this->testName . '. ' .
122  'Please provide __METHOD__ to database methods.' );
123  }
124  }
125 
126  function strencode( $s ) {
127  // Choose apos to avoid handling of escaping double quotes in quoted text
128  return str_replace( "'", "\'", $s );
129  }
130 
131  public function addIdentifierQuotes( $s ) {
132  // no escaping to avoid handling of double quotes in quoted text
133  return $s;
134  }
135 
136  public function query( $sql, $fname = '', $flags = 0 ) {
137  $this->checkFunctionName( $fname );
138 
139  return parent::query( $sql, $fname, $flags );
140  }
141 
142  public function tableExists( $table, $fname = __METHOD__ ) {
143  $tableRaw = $this->tableName( $table, 'raw' );
144  if ( isset( $this->sessionTempTables[$tableRaw] ) ) {
145  return true; // already known to exist
146  }
147 
148  $this->checkFunctionName( $fname );
149 
150  return in_array( $table, (array)$this->tablesExists );
151  }
152 
153  // Redeclare parent method to make it public
154  public function nativeReplace( $table, $rows, $fname ) {
155  parent::nativeReplace( $table, $rows, $fname );
156  }
157 
158  function getType() {
159  return 'test';
160  }
161 
162  function open( $server, $user, $password, $dbName, $schema, $tablePrefix ) {
163  $this->conn = (object)[ 'test' ];
164 
165  return true;
166  }
167 
168  function fetchObject( $res ) {
169  return false;
170  }
171 
172  function fetchRow( $res ) {
173  return false;
174  }
175 
176  function numRows( $res ) {
177  return -1;
178  }
179 
180  function numFields( $res ) {
181  return -1;
182  }
183 
184  function fieldName( $res, $n ) {
185  return 'test';
186  }
187 
188  function insertId() {
189  return -1;
190  }
191 
192  function dataSeek( $res, $row ) {
193  /* nop */
194  }
195 
196  function lastErrno() {
197  return $this->lastError ? $this->lastError['errno'] : -1;
198  }
199 
200  function lastError() {
201  return $this->lastError ? $this->lastError['error'] : 'test';
202  }
203 
204  protected function wasKnownStatementRollbackError() {
205  return $this->lastError['wasKnownStatementRollbackError'] ?? false;
206  }
207 
208  function fieldInfo( $table, $field ) {
209  return false;
210  }
211 
212  function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
213  return false;
214  }
215 
217  return -1;
218  }
219 
220  function getSoftwareLink() {
221  return 'test';
222  }
223 
224  function getServerVersion() {
225  return 'test';
226  }
227 
228  function getServerInfo() {
229  return 'test';
230  }
231 
232  function isOpen() {
233  return $this->conn ? true : false;
234  }
235 
236  function ping( &$rtt = null ) {
237  $rtt = 0.0;
238  return true;
239  }
240 
241  protected function closeConnection() {
242  return true;
243  }
244 
245  protected function doQuery( $sql ) {
246  $sql = preg_replace( '< /\* .+? \*/>', '', $sql );
247  $this->addSql( $sql );
248 
249  if ( $this->nextError ) {
250  $this->lastError = $this->nextError;
251  $this->nextError = null;
252  return false;
253  }
254 
256  $this->nextResult = [];
257  $this->lastError = null;
258 
259  return new FakeResultWrapper( $res );
260  }
261 
262  public function unionSupportsOrderAndLimit() {
264  }
265 
266  public function setUnionSupportsOrderAndLimit( $v ) {
267  $this->unionSupportsOrderAndLimit = (bool)$v;
268  }
269 }
DatabaseTestHelper\$testName
$testName
CLASS of the test suite, used to determine, if the function name is passed every time to query()
Definition: DatabaseTestHelper.php:17
DatabaseTestHelper\getType
getType()
Get the type of the DBMS, as it appears in $wgDBtype.
Definition: DatabaseTestHelper.php:158
DatabaseTestHelper\setUnionSupportsOrderAndLimit
setUnionSupportsOrderAndLimit( $v)
Definition: DatabaseTestHelper.php:266
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:48
query
For a write query
Definition: database.txt:26
DatabaseTestHelper\isOpen
isOpen()
Is a connection to the database open?
Definition: DatabaseTestHelper.php:232
DatabaseTestHelper\open
open( $server, $user, $password, $dbName, $schema, $tablePrefix)
Open a new connection to the database (closing any existing one)
Definition: DatabaseTestHelper.php:162
DatabaseTestHelper\numFields
numFields( $res)
Get the number of fields in a result object.
Definition: DatabaseTestHelper.php:180
DatabaseTestHelper\fieldInfo
fieldInfo( $table, $field)
mysql_fetch_field() wrapper Returns false if the field doesn't exist
Definition: DatabaseTestHelper.php:208
Wikimedia\Rdbms\Database\$password
string $password
Password used to establish the current connection.
Definition: Database.php:85
DatabaseTestHelper\getLastSqls
getLastSqls()
Returns SQL queries grouped by '; ' Clear the list of queries that have been done so far.
Definition: DatabaseTestHelper.php:68
DatabaseTestHelper\query
query( $sql, $fname='', $flags=0)
Run an SQL query and return the result.
Definition: DatabaseTestHelper.php:136
$s
$s
Definition: mergeMessageFileList.php:186
DatabaseTestHelper\$nextError
array null $nextError
Definition: DatabaseTestHelper.php:30
$res
$res
Definition: database.txt:21
DatabaseTestHelper\doQuery
doQuery( $sql)
Run a query and return a DBMS-dependent wrapper or boolean.
Definition: DatabaseTestHelper.php:245
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
DatabaseTestHelper\nativeReplace
nativeReplace( $table, $rows, $fname)
REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE statement.
Definition: DatabaseTestHelper.php:154
DatabaseTestHelper\$nextResult
array $nextResult
List of row arrays.
Definition: DatabaseTestHelper.php:27
DatabaseTestHelper\fetchRow
fetchRow( $res)
Fetch the next row from the given result object, in associative array form.
Definition: DatabaseTestHelper.php:172
DatabaseTestHelper\$lastError
array null $lastError
Definition: DatabaseTestHelper.php:32
DatabaseTestHelper\wasKnownStatementRollbackError
wasKnownStatementRollbackError()
Definition: DatabaseTestHelper.php:204
DatabaseTestHelper\tableExists
tableExists( $table, $fname=__METHOD__)
Query whether a given table exists.
Definition: DatabaseTestHelper.php:142
DatabaseTestHelper\forceNextQueryError
forceNextQueryError( $errno, $error, $options=[])
Definition: DatabaseTestHelper.php:92
DatabaseTestHelper\getSoftwareLink
getSoftwareLink()
Returns a wikitext link to the DB's website, e.g., return "[https://www.mysql.com/ MySQL]"; Should at...
Definition: DatabaseTestHelper.php:220
MWException
MediaWiki exception.
Definition: MWException.php:26
DatabaseTestHelper\strencode
strencode( $s)
Wrapper for addslashes()
Definition: DatabaseTestHelper.php:126
DatabaseTestHelper\unionSupportsOrderAndLimit
unionSupportsOrderAndLimit()
Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries within th...
Definition: DatabaseTestHelper.php:262
DatabaseTestHelper\lastError
lastError()
Get a description of the last error.
Definition: DatabaseTestHelper.php:200
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
Wikimedia\Rdbms\Database\$user
string $user
User that this instance is currently connected under the name of.
Definition: Database.php:83
DatabaseTestHelper\$tablesExists
$tablesExists
Array of tables to be considered as existing by tableExist() Use setExistingTables() to alter.
Definition: DatabaseTestHelper.php:38
DatabaseTestHelper\setExistingTables
setExistingTables( $tablesExists)
Definition: DatabaseTestHelper.php:75
array
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))
$fname
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
Definition: Setup.php:123
DatabaseTestHelper\ping
ping(&$rtt=null)
Ping the server and try to reconnect if it there is no connection.
Definition: DatabaseTestHelper.php:236
DatabaseTestHelper\numRows
numRows( $res)
Get the number of rows in a query result.
Definition: DatabaseTestHelper.php:176
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2162
DatabaseTestHelper\getServerInfo
getServerInfo()
A string describing the current software version, and possibly other details in a user-friendly way.
Definition: DatabaseTestHelper.php:228
DatabaseTestHelper\getServerVersion
getServerVersion()
A string describing the current software version, like from mysql_get_server_info().
Definition: DatabaseTestHelper.php:224
DatabaseTestHelper\addIdentifierQuotes
addIdentifierQuotes( $s)
Quotes an identifier, in order to make user controlled input safe.
Definition: DatabaseTestHelper.php:131
Wikimedia\Rdbms\Database\tableName
tableName( $name, $format='quoted')
Format a table name ready for use in constructing an SQL query.
Definition: Database.php:2410
DatabaseTestHelper\insertId
insertId()
Get the inserted value of an auto-increment row.
Definition: DatabaseTestHelper.php:188
DatabaseTestHelper\checkFunctionName
checkFunctionName( $fname)
Definition: DatabaseTestHelper.php:104
DatabaseTestHelper\fetchAffectedRowCount
fetchAffectedRowCount()
Definition: DatabaseTestHelper.php:216
DatabaseTestHelper\dataSeek
dataSeek( $res, $row)
Change the position of the cursor in a result object.
Definition: DatabaseTestHelper.php:192
DatabaseTestHelper
Helper for testing the methods from the Database class.
Definition: DatabaseTestHelper.php:11
DatabaseTestHelper\fieldName
fieldName( $res, $n)
Get a field name in a result object.
Definition: DatabaseTestHelper.php:184
DatabaseTestHelper\addSql
addSql( $sql)
Definition: DatabaseTestHelper.php:96
$rows
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction $rows
Definition: hooks.txt:2636
DatabaseTestHelper\indexInfo
indexInfo( $table, $index, $fname='Database::indexInfo')
Get information about an index into an object.
Definition: DatabaseTestHelper.php:212
$options
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1985
DatabaseTestHelper\$lastSqls
$lastSqls
Array of lastSqls passed to query(), This is an array since some methods in Database can do more than...
Definition: DatabaseTestHelper.php:24
DatabaseTestHelper\forceNextResult
forceNextResult( $res)
Definition: DatabaseTestHelper.php:82
Wikimedia\Rdbms\Database\$server
string $server
Server that this instance is currently connected to.
Definition: Database.php:81
DatabaseTestHelper\closeConnection
closeConnection()
Closes underlying database connection.
Definition: DatabaseTestHelper.php:241
true
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition: hooks.txt:1985
Wikimedia\Rdbms\Database\$flags
int $flags
Definition: Database.php:124
DatabaseTestHelper\$unionSupportsOrderAndLimit
$unionSupportsOrderAndLimit
Value to return from unionSupportsOrderAndLimit()
Definition: DatabaseTestHelper.php:43
wfWarn
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
Definition: GlobalFunctions.php:1092
object
globals will be eliminated from MediaWiki replaced by an application object which would be passed to constructors Whether that would be an convenient solution remains to be but certainly PHP makes such object oriented programming models easier than they were in previous versions For the time being MediaWiki programmers will have to work in an environment with some global context At the time of globals were initialised on startup by MediaWiki of these were configuration which are documented in DefaultSettings php There is no comprehensive documentation for the remaining however some of the most important ones are listed below They are typically initialised either in index php or in Setup php $wgTitle Title object created from the request URL $wgOut OutputPage object for HTTP response $wgUser User object for the user associated with the current request $wgLang Language object selected by user preferences $wgContLang Language object associated with the wiki being viewed $wgParser Parser object Parser extensions register their hooks here $wgRequest WebRequest object
Definition: globals.txt:25
DatabaseTestHelper\fetchObject
fetchObject( $res)
Fetch the next row from the given result object, in object form.
Definition: DatabaseTestHelper.php:168
DatabaseTestHelper\__construct
__construct( $testName, array $opts=[])
Definition: DatabaseTestHelper.php:45
Wikimedia\Rdbms\DatabaseDomain
Class to handle database/prefix specification for IDatabase domains.
Definition: DatabaseDomain.php:28
Wikimedia\Rdbms\TransactionProfiler
Helper class that detects high-contention DB queries via profiling calls.
Definition: TransactionProfiler.php:38
DatabaseTestHelper\lastErrno
lastErrno()
Get the last error number.
Definition: DatabaseTestHelper.php:196