runBatchedQuery.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. /**
  3. * Run a database query in batches and wait for replica DBs. This is used on large
  4. * wikis to prevent replication lag from going through the roof when executing
  5. * large write queries.
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License along
  18. * with this program; if not, write to the Free Software Foundation, Inc.,
  19. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  20. * http://www.gnu.org/copyleft/gpl.html
  21. *
  22. * @file
  23. * @ingroup Maintenance
  24. */
  25. require_once __DIR__ . '/Maintenance.php';
  26. /**
  27. * Maintenance script to run a database query in batches and wait for replica DBs.
  28. *
  29. * @ingroup Maintenance
  30. */
  31. class BatchedQueryRunner extends Maintenance {
  32. public function __construct() {
  33. parent::__construct();
  34. $this->addDescription(
  35. "Run a query repeatedly until it affects 0 rows, and wait for replica DBs in between.\n" .
  36. "NOTE: You need to set a LIMIT clause yourself." );
  37. }
  38. public function execute() {
  39. if ( !$this->hasArg() ) {
  40. $this->error( "No query specified. Specify the query as a command line parameter.", true );
  41. }
  42. $query = $this->getArg();
  43. $n = 1;
  44. $dbw = $this->getDB( DB_MASTER );
  45. do {
  46. $this->output( "Batch $n: " );
  47. $n++;
  48. $dbw->query( $query, __METHOD__ );
  49. $affected = $dbw->affectedRows();
  50. $this->output( "$affected rows\n" );
  51. wfWaitForSlaves();
  52. } while ( $affected > 0 );
  53. }
  54. public function getDbType() {
  55. return Maintenance::DB_ADMIN;
  56. }
  57. }
  58. $maintClass = "BatchedQueryRunner";
  59. require_once RUN_MAINTENANCE_IF_MAIN;