Add setCaller to BatchRowWriter
[mediawiki.git] / includes / utils / BatchRowWriter.php
blob8b07f1ad9228f9dcd831b49a331ea44ad95e194d
1 <?php
2 /**
3 * Updates database rows by primary key in batches.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @ingroup Maintenance
24 use MediaWiki\MediaWikiServices;
25 use Wikimedia\Rdbms\IDatabase;
27 class BatchRowWriter {
28 /**
29 * @var IDatabase The database to write to
31 protected $db;
33 /**
34 * @var string The name of the table to update
36 protected $table;
38 /**
39 * @var string|false A cluster name valid for use with LBFactory
41 protected $clusterName;
43 /**
44 * For debugging which method is using this class.
46 protected $caller;
48 /**
49 * @param IDatabase $db The database to write to
50 * @param string $table The name of the table to update
51 * @param string|false $clusterName A cluster name valid for use with LBFactory
53 public function __construct( IDatabase $db, $table, $clusterName = false ) {
54 $this->db = $db;
55 $this->table = $table;
56 $this->clusterName = $clusterName;
59 /**
60 * Use ->setCaller( __METHOD__ ) to indicate which code is using this
61 * class. Only used in debugging output.
62 * @since 1.36
64 * @param string $caller
65 * @return self
67 public function setCaller( $caller ) {
68 $this->caller = $caller;
69 return $this;
72 /**
73 * @param array[][] $updates Array of arrays each containing two keys, 'primaryKey'
74 * and 'changes'. primaryKey must contain a map of column names to values
75 * sufficient to uniquely identify the row. changes must contain a map of column
76 * names to update values to apply to the row.
77 * @phan-param array<int,array{primaryKey:array,changes:array}> $updates
79 public function write( array $updates ) {
80 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
81 $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__ );
83 $caller = __METHOD__;
84 if ( (string)$this->caller !== '' ) {
85 $caller .= " (for {$this->caller})";
88 foreach ( $updates as $update ) {
89 $this->db->update(
90 $this->table,
91 $update['changes'],
92 $update['primaryKey'],
93 $caller
97 $lbFactory->commitAndWaitForReplication( __METHOD__, $ticket );