aboutsummaryrefslogtreecommitdiffstats
path: root/maintenance/includes/UndoLog.php
blob: 8ead9bff51729e07d76390b217f30bec664b1840 (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
<?php

namespace MediaWiki\Maintenance;

use Wikimedia\Rdbms\IDatabase;

/**
 * Update a database while optionally writing SQL that reverses the update to
 * a file.
 */
class UndoLog {
	private $file;
	private $dbw;

	/**
	 * @param string|null $fileName
	 * @param IDatabase $dbw
	 */
	public function __construct( $fileName, IDatabase $dbw ) {
		if ( $fileName !== null ) {
			$this->file = fopen( $fileName, 'a' );
			if ( !$this->file ) {
				throw new \RuntimeException( 'Unable to open undo log' );
			}
		}
		$this->dbw = $dbw;
	}

	/**
	 * @param string $table
	 * @param array $newValues
	 * @param array $oldValues
	 * @param string $fname
	 * @return bool
	 */
	public function update( $table, array $newValues, array $oldValues, $fname ) {
		$this->dbw->newUpdateQueryBuilder()
			->update( $table )
			->set( $newValues )
			->where( $oldValues )
			->caller( $fname )->execute();

		$updated = (bool)$this->dbw->affectedRows();
		if ( $this->file && $updated ) {
			$table = $this->dbw->tableName( $table );
			fwrite(
				$this->file,
				"UPDATE $table" .
					' SET ' . $this->dbw->makeList( $oldValues, IDatabase::LIST_SET ) .
					' WHERE ' . $this->dbw->makeList( $newValues, IDatabase::LIST_AND ) . ";\n"
			);
		}
		return $updated;
	}
}