aboutsummaryrefslogtreecommitdiffstats
path: root/tests/phpunit/includes/db/DatabaseTestHelper.php
blob: 9e09d58617126640ca1bf36f24a303121f8a4bb8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
<?php

use MediaWiki\Tests\Unit\Libs\Rdbms\AddQuoterMock;
use MediaWiki\Tests\Unit\Libs\Rdbms\SQLPlatformTestHelper;
use Psr\Log\NullLogger;
use Wikimedia\ObjectCache\HashBagOStuff;
use Wikimedia\Rdbms\Database;
use Wikimedia\Rdbms\Database\DatabaseFlags;
use Wikimedia\Rdbms\DatabaseDomain;
use Wikimedia\Rdbms\FakeResultWrapper;
use Wikimedia\Rdbms\QueryStatus;
use Wikimedia\Rdbms\Replication\ReplicationReporter;
use Wikimedia\Rdbms\TransactionProfiler;
use Wikimedia\RequestTimeout\RequestTimeout;

/**
 * Helper for testing the methods from the Database class
 * @since 1.22
 */
class DatabaseTestHelper extends Database {

	/**
	 * @var string __CLASS__ of the test suite,
	 * used to determine, if the function name is passed every time to query()
	 */
	protected string $testName;

	/**
	 * @var string[] Array of lastSqls passed to query(),
	 * This is an array since some methods in Database can do more than one
	 * query. Cleared when calling getLastSqls().
	 */
	protected $lastSqls = [];

	/** @var array Stack of result maps */
	protected $nextResMapQueue = [];

	/** @var array|null */
	protected $lastResMap = null;

	/**
	 * @var string[] Array of tables to be considered as existing by tableExist()
	 * Use setExistingTables() to alter.
	 */
	protected $tablesExists;

	/** @var int[] */
	protected $forcedAffectedCountQueue = [];

	public function __construct( string $testName, array $opts = [] ) {
		$params = $opts + [
			'host' => null,
			'user' => null,
			'password' => null,
			'dbname' => null,
			'schema' => null,
			'tablePrefix' => '',
			'flags' => 0,
			'cliMode' => true,
			'agent' => '',
			'serverName' => null,
			'topologyRole' => null,
			'srvCache' => new HashBagOStuff(),
			'profiler' => null,
			'trxProfiler' => new TransactionProfiler(),
			'logger' => new NullLogger(),
			'errorLogger' => static function ( Exception $e ) {
				wfWarn( get_class( $e ) . ': ' . $e->getMessage() );
			},
			'deprecationLogger' => static function ( $msg ) {
				wfWarn( $msg );
			},
			'criticalSectionProvider' =>
				RequestTimeout::singleton()->createCriticalSectionProvider( 120 )
		];
		parent::__construct( $params );

		$this->testName = $testName;
		$this->platform = new SQLPlatformTestHelper( new AddQuoterMock() );
		$this->flagsHolder = new DatabaseFlags( 0 );
		$this->replicationReporter = new ReplicationReporter(
			$params['topologyRole'],
			$params['logger'],
			$params['srvCache']
		);

		$this->currentDomain = DatabaseDomain::newUnspecified();
		$this->open( 'localhost', 'testuser', 'password', 'testdb', null, '' );
	}

	/**
	 * Returns SQL queries grouped by '; '
	 * Clear the list of queries that have been done so far.
	 * @return string
	 */
	public function getLastSqls() {
		$lastSqls = implode( '; ', $this->lastSqls );
		$this->lastSqls = [];

		return $lastSqls;
	}

	public function setExistingTables( $tablesExists ) {
		$this->tablesExists = (array)$tablesExists;
	}

	/**
	 * @param mixed $res Use an array of row arrays to set row result
	 * @param int $errno Error number
	 * @param string $error Error text
	 * @param array $options
	 *  - isKnownStatementRollbackError: Return value for isKnownStatementRollbackError()
	 */
	public function forceNextResult( $res, $errno = 0, $error = '', $options = [] ) {
		$this->nextResMapQueue[] = [
			'res' => $res,
			'errno' => $errno,
			'error' => $error
		] + $options;
	}

	protected function addSql( $sql ) {
		// clean up spaces before and after some words and the whole string
		$this->lastSqls[] = trim( preg_replace(
			'/\s{2,}(?=FROM|WHERE|GROUP BY|ORDER BY|LIMIT)|(?<=SELECT|INSERT|UPDATE)\s{2,}/',
			' ', $sql
		) );
	}

	protected function checkFunctionName( $fname ) {
		if ( $fname === 'Wikimedia\\Rdbms\\Database::close' ) {
			return; // no $fname parameter
		}

		// Handle some internal calls from the Database class
		$check = $fname;
		if ( preg_match(
			'/^Wikimedia\\\\Rdbms\\\\Database::(?:query|beginIfImplied) \((.+)\)$/',
			$fname,
			$m
		) ) {
			$check = $m[1];
		}

		if ( !str_starts_with( $check, $this->testName ) ) {
			throw new LogicException( 'function name does not start with test class. ' .
				$fname . ' vs. ' . $this->testName . '. ' .
				'Please provide __METHOD__ to database methods.' );
		}
	}

	public function strencode( $s ) {
		// Choose apos to avoid handling of escaping double quotes in quoted text
		return str_replace( "'", "\'", $s );
	}

	public function query( $sql, $fname = '', $flags = 0 ) {
		$this->checkFunctionName( $fname );

		return parent::query( $sql, $fname, $flags );
	}

	public function tableExists( $table, $fname = __METHOD__ ) {
		[ $db, $pt ] = $this->platform->getDatabaseAndTableIdentifier( $table );
		if ( isset( $this->sessionTempTables[$db][$pt] ) ) {
			return true; // already known to exist
		}

		$this->checkFunctionName( $fname );

		return in_array( $table, (array)$this->tablesExists );
	}

	public function getType() {
		return 'test';
	}

	public function open( $server, $user, $password, $db, $schema, $tablePrefix ) {
		$this->conn = (object)[ 'test' ];

		return true;
	}

	protected function lastInsertId() {
		return -1;
	}

	public function lastErrno() {
		return $this->lastResMap ? $this->lastResMap['errno'] : -1;
	}

	public function lastError() {
		return $this->lastResMap ? $this->lastResMap['error'] : 'test';
	}

	protected function isKnownStatementRollbackError( $errno ) {
		return ( $this->lastResMap['errno'] ?? 0 ) === $errno
			? ( $this->lastResMap['isKnownStatementRollbackError'] ?? false )
			: false;
	}

	public function fieldInfo( $table, $field ) {
		return false;
	}

	public function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
		return false;
	}

	public function getSoftwareLink() {
		return 'test';
	}

	public function getServerVersion() {
		return 'test';
	}

	public function getServerInfo() {
		return 'test';
	}

	public function ping( &$rtt = null ) {
		$rtt = 0.0;
		return true;
	}

	protected function closeConnection() {
		return true;
	}

	public function setNextQueryAffectedRowCounts( array $counts ) {
		$this->forcedAffectedCountQueue = $counts;
	}

	protected function doSingleStatementQuery( string $sql ): QueryStatus {
		$sql = preg_replace( '< /\* .+?  \*/>', '', $sql );
		$this->addSql( $sql );

		if ( $this->nextResMapQueue ) {
			$this->lastResMap = array_shift( $this->nextResMapQueue );
			if ( !$this->lastResMap['errno'] && $this->forcedAffectedCountQueue ) {
				$count = array_shift( $this->forcedAffectedCountQueue );
				$this->lastQueryAffectedRows = $count;
			}
		} else {
			$this->lastResMap = [ 'res' => [], 'errno' => 0, 'error' => '' ];
		}
		$res = $this->lastResMap['res'];

		return new QueryStatus(
			is_bool( $res ) ? $res : new FakeResultWrapper( $res ),
			$this->affectedRows(),
			$this->lastError(),
			$this->lastErrno()
		);
	}
}