BatchRowWriter.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. /**
  3. * Updates database rows by primary key in batches.
  4. *
  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.
  9. *
  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.
  14. *
  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
  19. *
  20. * @file
  21. * @ingroup Maintenance
  22. */
  23. use MediaWiki\MediaWikiServices;
  24. use Wikimedia\Rdbms\IDatabase;
  25. class BatchRowWriter {
  26. /**
  27. * @var IDatabase $db The database to write to
  28. */
  29. protected $db;
  30. /**
  31. * @var string $table The name of the table to update
  32. */
  33. protected $table;
  34. /**
  35. * @var string $clusterName A cluster name valid for use with LBFactory
  36. */
  37. protected $clusterName;
  38. /**
  39. * @param IDatabase $db The database to write to
  40. * @param string $table The name of the table to update
  41. * @param string|bool $clusterName A cluster name valid for use with LBFactory
  42. */
  43. public function __construct( IDatabase $db, $table, $clusterName = false ) {
  44. $this->db = $db;
  45. $this->table = $table;
  46. $this->clusterName = $clusterName;
  47. }
  48. /**
  49. * @param array $updates Array of arrays each containing two keys, 'primaryKey'
  50. * and 'changes'. primaryKey must contain a map of column names to values
  51. * sufficient to uniquely identify the row changes must contain a map of column
  52. * names to update values to apply to the row.
  53. */
  54. public function write( array $updates ) {
  55. $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
  56. $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__ );
  57. foreach ( $updates as $update ) {
  58. $this->db->update(
  59. $this->table,
  60. $update['changes'],
  61. $update['primaryKey'],
  62. __METHOD__
  63. );
  64. }
  65. $lbFactory->commitAndWaitForReplication( __METHOD__, $ticket );
  66. }
  67. }