3 namespace MediaWiki\Tests
;
5 use MediaWiki\Logger\LoggerFactory
;
6 use Wikimedia\ObjectCache\HashBagOStuff
;
7 use Wikimedia\ObjectCache\WANObjectCache
;
8 use Wikimedia\Rdbms\Database
;
9 use Wikimedia\Rdbms\FakeResultWrapper
;
10 use Wikimedia\Rdbms\IDatabase
;
11 use Wikimedia\Rdbms\QueryBuilderFromRawSql
;
12 use Wikimedia\Rdbms\QueryStatus
;
13 use Wikimedia\Rdbms\Replication\ReplicationReporter
;
14 use Wikimedia\Rdbms\TransactionProfiler
;
17 * A default-constructible Database subclass that doesn't access any services so
18 * should be safe to use in unit tests.
20 * The best way to validate a database query is by actually running it against
21 * a real database. So the acceptable use cases for this class are narrow. It
22 * may be useful for testing query-building services, or queries against tables
23 * that don't actually exist. It can be used for service injection when there
24 * is only a minor dependency on the database, for example for quoting.
26 * Query collection and fake result generation could easily be added if there is
31 class MockDatabase
extends Database
{
33 private $nextInsertId = 0;
35 public function __construct( $options = [] ) {
36 // Use a real logger because tests need logging, maybe more than production
37 $logger = $options['logger'] ?? LoggerFactory
::getInstance( 'MockDatabase' );
39 parent
::__construct( $options +
[
43 'trxProfiler' => new TransactionProfiler
,
45 'errorLogger' => $logger,
46 'deprecationLogger' => $logger,
54 $this->replicationReporter
= new ReplicationReporter(
55 $options['topologyRole'] ?? IDatabase
::ROLE_STREAMING_MASTER
,
57 $options['srvCache'] ??
new WANObjectCache( [
58 'cache' => new HashBagOStuff(),
64 protected function open( $server, $user, $password, $db, $schema, $tablePrefix ) {
67 public function isOpen() {
71 public function indexInfo( $table, $index, $fname = __METHOD__
) {
72 throw new \
RuntimeException( 'Not implemented' );
75 public function strencode( $s ) {
76 return addslashes( $s );
79 protected function closeConnection() {
82 protected function doSingleStatementQuery( string $sql ): QueryStatus
{
83 $query = QueryBuilderFromRawSql
::buildQuery( $sql, 0 );
84 if ( $query->isWriteQuery() ) {
85 return new QueryStatus( true, 0, 0, '' );
87 return new QueryStatus( new FakeResultWrapper( [] ), 0, 0, '' );
91 public function tableExists( $table, $fname = __METHOD__
) {
95 protected function lastInsertId() {
96 return $this->nextInsertId++
;
99 public function fieldInfo( $table, $field ) {
100 throw new \
RuntimeException( 'Not implemented' );
103 public function getType() {
107 public function lastErrno() {
111 public function lastError() {
115 public function getSoftwareLink() {
119 public function getServerVersion() {