Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 72
0.00% covered (danger)
0.00%
0 / 6
CRAP
0.00% covered (danger)
0.00%
0 / 1
TableCleanup
0.00% covered (danger)
0.00%
0 / 71
0.00% covered (danger)
0.00%
0 / 6
210
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 execute
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 init
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 progress
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
6
 runTable
0.00% covered (danger)
0.00%
0 / 31
0.00% covered (danger)
0.00%
0 / 1
56
 hexChar
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * Generic class to cleanup a database table.
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
24use MediaWiki\WikiMap\WikiMap;
25
26require_once __DIR__ . '/Maintenance.php';
27
28/**
29 * Generic class to cleanup a database table. Already subclasses Maintenance.
30 *
31 * @ingroup Maintenance
32 */
33class TableCleanup extends Maintenance {
34    protected $defaultParams = [
35        'table' => 'page',
36        'conds' => [],
37        'index' => 'page_id',
38        'callback' => 'processRow',
39    ];
40
41    protected $dryrun = false;
42    protected $reportInterval = 100;
43
44    protected int $processed;
45    protected int $updated;
46    protected int $count;
47    protected float $startTime;
48    protected string $table;
49
50    public function __construct() {
51        parent::__construct();
52        $this->addOption( 'dry-run', 'Perform a dry run' );
53        $this->addOption( 'reporting-interval', 'How often to print status line' );
54        $this->setBatchSize( 100 );
55    }
56
57    public function execute() {
58        $this->reportInterval = $this->getOption( 'reporting-interval', $this->reportInterval );
59
60        $this->dryrun = $this->hasOption( 'dry-run' );
61
62        if ( $this->dryrun ) {
63            $this->output( "Checking for bad titles...\n" );
64        } else {
65            $this->output( "Checking and fixing bad titles...\n" );
66        }
67
68        $this->runTable( $this->defaultParams );
69    }
70
71    protected function init( $count, $table ) {
72        $this->processed = 0;
73        $this->updated = 0;
74        $this->count = $count;
75        $this->startTime = microtime( true );
76        $this->table = $table;
77    }
78
79    /**
80     * @param int $updated
81     */
82    protected function progress( $updated ) {
83        $this->updated += $updated;
84        $this->processed++;
85        if ( $this->processed % $this->reportInterval != 0 ) {
86            return;
87        }
88        $portion = $this->processed / $this->count;
89        $updateRate = $this->updated / $this->processed;
90
91        $now = microtime( true );
92        $delta = $now - $this->startTime;
93        $estimatedTotalTime = $delta / $portion;
94        $eta = $this->startTime + $estimatedTotalTime;
95
96        $this->output(
97            sprintf( "%s %s: %6.2f%% done on %s; ETA %s [%d/%d] %.2f/sec <%.2f%% updated>\n",
98                WikiMap::getCurrentWikiDbDomain()->getId(),
99                wfTimestamp( TS_DB, intval( $now ) ),
100                $portion * 100.0,
101                $this->table,
102                wfTimestamp( TS_DB, intval( $eta ) ),
103                $this->processed,
104                $this->count,
105                $this->processed / $delta,
106                $updateRate * 100.0
107            )
108        );
109        flush();
110    }
111
112    /**
113     * @param array $params
114     */
115    public function runTable( $params ) {
116        $dbr = $this->getReplicaDB();
117
118        if ( array_diff( array_keys( $params ),
119            [ 'table', 'conds', 'index', 'callback' ] )
120        ) {
121            $this->fatalError( __METHOD__ . ': Missing parameter ' . implode( ', ', $params ) );
122        }
123
124        $table = $params['table'];
125        // count(*) would melt the DB for huge tables, we can estimate here
126        $count = $dbr->estimateRowCount( $table, '*', '', __METHOD__ );
127        $this->init( $count, $table );
128        $this->output( "Processing $table...\n" );
129
130        $index = (array)$params['index'];
131        $indexConds = [];
132        $callback = [ $this, $params['callback'] ];
133
134        while ( true ) {
135            $conds = array_merge( $params['conds'], $indexConds );
136            $res = $dbr->newSelectQueryBuilder()
137                ->select( '*' )
138                ->from( $table )
139                ->where( $conds )
140                ->orderBy( implode( ',', $index ) )
141                ->limit( $this->getBatchSize() )
142                ->caller( __METHOD__ )->fetchResultSet();
143            if ( !$res->numRows() ) {
144                // Done
145                break;
146            }
147
148            foreach ( $res as $row ) {
149                call_user_func( $callback, $row );
150            }
151
152            if ( $res->numRows() < $this->getBatchSize() ) {
153                // Done
154                break;
155            }
156
157            // Update the conditions to select the next batch.
158            $conds = [];
159            foreach ( $index as $field ) {
160                // @phan-suppress-next-line PhanPossiblyUndeclaredVariable $res has at at least one item
161                $conds[ $field ] = $row->$field;
162            }
163            $indexConds = [ $dbr->buildComparison( '>', $conds ) ];
164        }
165
166        $this->output( "Finished $table... $this->updated of $this->processed rows updated\n" );
167    }
168
169    /**
170     * @param string[] $matches
171     * @return string
172     */
173    protected function hexChar( $matches ) {
174        return sprintf( "\\x%02x", ord( $matches[1] ) );
175    }
176}