Merge "parserTests: Add parser test with filename containing single quotes"
[lhc/web/wiklou.git] / maintenance / convertLinks.php
1 <?php
2 /**
3 * Convert from the old links schema (string->ID) to the new schema (ID->ID).
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
24 use MediaWiki\MediaWikiServices;
25
26 require_once __DIR__ . '/Maintenance.php';
27
28 /**
29 * Maintenance script to convert from the old links schema (string->ID)
30 * to the new schema (ID->ID).
31 *
32 * The wiki should be put into read-only mode while this script executes.
33 *
34 * @ingroup Maintenance
35 */
36 class ConvertLinks extends Maintenance {
37 private $logPerformance;
38
39 public function __construct() {
40 parent::__construct();
41 $this->addDescription(
42 'Convert from the old links schema (string->ID) to the new schema (ID->ID). '
43 . 'The wiki should be put into read-only mode while this script executes' );
44
45 $this->addArg( 'logperformance', "Log performance to perfLogFilename.", false );
46 $this->addArg(
47 'perfLogFilename',
48 "Filename where performance is logged if --logperformance was set "
49 . "(defaults to 'convLinksPerf.txt').",
50 false
51 );
52 $this->addArg(
53 'keep-links-table',
54 "Don't overwrite the old links table with the new one, leave the new table at links_temp.",
55 false
56 );
57 $this->addArg(
58 'nokeys',
59 /* (What about InnoDB?) */
60 "Don't create keys, and so allow duplicates in the new links table.\n"
61 . "This gives a huge speed improvement for very large links tables which are MyISAM.",
62 false
63 );
64 }
65
66 public function getDbType() {
67 return Maintenance::DB_ADMIN;
68 }
69
70 public function execute() {
71 $dbw = $this->getDB( DB_MASTER );
72
73 $type = $dbw->getType();
74 if ( $type != 'mysql' ) {
75 $this->output( "Link table conversion not necessary for $type\n" );
76
77 return;
78 }
79
80 # counters etc
81 $numBadLinks = $curRowsRead = 0;
82
83 # total tuples INSERTed into links_temp
84 $totalTuplesInserted = 0;
85
86 # whether or not to give progress reports while reading IDs from cur table
87 $reportCurReadProgress = true;
88
89 # number of rows between progress reports
90 $curReadReportInterval = 1000;
91
92 # whether or not to give progress reports during conversion
93 $reportLinksConvProgress = true;
94
95 # number of rows per INSERT
96 $linksConvInsertInterval = 1000;
97
98 $initialRowOffset = 0;
99
100 # not used yet; highest row number from links table to process
101 # $finalRowOffset = 0;
102
103 $overwriteLinksTable = !$this->hasOption( 'keep-links-table' );
104 $noKeys = $this->hasOption( 'noKeys' );
105 $this->logPerformance = $this->hasOption( 'logperformance' );
106 $perfLogFilename = $this->getArg( 'perfLogFilename', "convLinksPerf.txt" );
107
108 # --------------------------------------------------------------------
109
110 list( $cur, $links, $links_temp, $links_backup ) =
111 $dbw->tableNamesN( 'cur', 'links', 'links_temp', 'links_backup' );
112
113 if ( $dbw->tableExists( 'pagelinks' ) ) {
114 $this->output( "...have pagelinks; skipping old links table updates\n" );
115
116 return;
117 }
118
119 $res = $dbw->query( "SELECT l_from FROM $links LIMIT 1" );
120 if ( $dbw->fieldType( $res, 0 ) == "int" ) {
121 $this->output( "Schema already converted\n" );
122
123 return;
124 }
125
126 $res = $dbw->query( "SELECT COUNT(*) AS count FROM $links" );
127 $row = $dbw->fetchObject( $res );
128 $numRows = $row->count;
129
130 if ( $numRows == 0 ) {
131 $this->output( "Updating schema (no rows to convert)...\n" );
132 $this->createTempTable();
133 } else {
134 $fh = false;
135 if ( $this->logPerformance ) {
136 $fh = fopen( $perfLogFilename, "w" );
137 if ( !$fh ) {
138 $this->error( "Couldn't open $perfLogFilename" );
139 $this->logPerformance = false;
140 }
141 }
142 $baseTime = $startTime = microtime( true );
143 # Create a title -> cur_id map
144 $this->output( "Loading IDs from $cur table...\n" );
145 $this->performanceLog( $fh, "Reading $numRows rows from cur table...\n" );
146 $this->performanceLog( $fh, "rows read vs seconds elapsed:\n" );
147 $contentLang = MediaWikiServices::getInstance()->getContentLanguage();
148
149 $ids = [];
150 $lastId = 0;
151 do {
152 $res = $dbw->query(
153 "SELECT cur_namespace,cur_title,cur_id FROM $cur " .
154 "WHERE cur_id > $lastId ORDER BY cur_id LIMIT 10000"
155 );
156 foreach ( $res as $row ) {
157 $title = $row->cur_title;
158 if ( $row->cur_namespace ) {
159 $title = $contentLang->getNsText( $row->cur_namespace ) . ":$title";
160 }
161 $ids[$title] = $row->cur_id;
162 $curRowsRead++;
163 if ( $reportCurReadProgress ) {
164 if ( ( $curRowsRead % $curReadReportInterval ) == 0 ) {
165 $this->performanceLog(
166 $fh,
167 $curRowsRead . " " . ( microtime( true ) - $baseTime ) . "\n"
168 );
169 $this->output( "\t$curRowsRead rows of $cur table read.\n" );
170 }
171 }
172 $lastId = $row->cur_id;
173 }
174 } while ( $res->numRows() > 0 );
175 $this->output( "Finished loading IDs.\n\n" );
176 $this->performanceLog(
177 $fh,
178 "Took " . ( microtime( true ) - $baseTime ) . " seconds to load IDs.\n\n"
179 );
180
181 # --------------------------------------------------------------------
182
183 # Now, step through the links table (in chunks of $linksConvInsertInterval rows),
184 # convert, and write to the new table.
185 $this->createTempTable();
186 $this->performanceLog( $fh, "Resetting timer.\n\n" );
187 $baseTime = microtime( true );
188 $this->output( "Processing $numRows rows from $links table...\n" );
189 $this->performanceLog( $fh, "Processing $numRows rows from $links table...\n" );
190 $this->performanceLog( $fh, "rows inserted vs seconds elapsed:\n" );
191
192 for ( $rowOffset = $initialRowOffset; $rowOffset < $numRows;
193 $rowOffset += $linksConvInsertInterval
194 ) {
195 $sqlRead = "SELECT * FROM $links ";
196 $sqlRead = $dbw->limitResult( $sqlRead, $linksConvInsertInterval, $rowOffset );
197 $res = $dbw->query( $sqlRead );
198 if ( $noKeys ) {
199 $sqlWrite = [ "INSERT INTO $links_temp (l_from,l_to) VALUES " ];
200 } else {
201 $sqlWrite = [ "INSERT IGNORE INTO $links_temp (l_from,l_to) VALUES " ];
202 }
203
204 $tuplesAdded = 0; # no tuples added to INSERT yet
205 foreach ( $res as $row ) {
206 $fromTitle = $row->l_from;
207 if ( array_key_exists( $fromTitle, $ids ) ) { # valid title
208 $from = $ids[$fromTitle];
209 $to = $row->l_to;
210 if ( $tuplesAdded != 0 ) {
211 $sqlWrite[] = ",";
212 }
213 $sqlWrite[] = "($from,$to)";
214 $tuplesAdded++;
215 } else { # invalid title
216 $numBadLinks++;
217 }
218 }
219 # $this->output( "rowOffset: $rowOffset\ttuplesAdded: "
220 # . "$tuplesAdded\tnumBadLinks: $numBadLinks\n" );
221 if ( $tuplesAdded != 0 ) {
222 if ( $reportLinksConvProgress ) {
223 $this->output( "Inserting $tuplesAdded tuples into $links_temp..." );
224 }
225 $dbw->query( implode( "", $sqlWrite ) );
226 $totalTuplesInserted += $tuplesAdded;
227 if ( $reportLinksConvProgress ) {
228 $this->output( " done. Total $totalTuplesInserted tuples inserted.\n" );
229 $this->performanceLog(
230 $fh,
231 $totalTuplesInserted . " " . ( microtime( true ) - $baseTime ) . "\n"
232 );
233 }
234 }
235 }
236 $this->output( "$totalTuplesInserted valid titles and "
237 . "$numBadLinks invalid titles were processed.\n\n" );
238 $this->performanceLog(
239 $fh,
240 "$totalTuplesInserted valid titles and $numBadLinks invalid titles were processed.\n"
241 );
242 $this->performanceLog(
243 $fh,
244 "Total execution time: " . ( microtime( true ) - $startTime ) . " seconds.\n"
245 );
246 if ( $this->logPerformance ) {
247 fclose( $fh );
248 }
249 }
250 # --------------------------------------------------------------------
251
252 if ( $overwriteLinksTable ) {
253 # Check for existing links_backup, and delete it if it exists.
254 $this->output( "Dropping backup links table if it exists..." );
255 $dbw->query( "DROP TABLE IF EXISTS $links_backup", __METHOD__ );
256 $this->output( " done.\n" );
257
258 # Swap in the new table, and move old links table to links_backup
259 $this->output( "Swapping tables '$links' to '$links_backup'; '$links_temp' to '$links'..." );
260 $dbw->query( "RENAME TABLE links TO $links_backup, $links_temp TO $links", __METHOD__ );
261 $this->output( " done.\n\n" );
262
263 $this->output( "Conversion complete. The old table remains at $links_backup;\n" );
264 $this->output( "delete at your leisure.\n" );
265 } else {
266 $this->output( "Conversion complete. The converted table is at $links_temp;\n" );
267 $this->output( "the original links table is unchanged.\n" );
268 }
269 }
270
271 private function createTempTable() {
272 $dbConn = $this->getDB( DB_MASTER );
273
274 if ( !( $dbConn->isOpen() ) ) {
275 $this->output( "Opening connection to database failed.\n" );
276
277 return;
278 }
279 $links_temp = $dbConn->tableName( 'links_temp' );
280
281 $this->output( "Dropping temporary links table if it exists..." );
282 $dbConn->query( "DROP TABLE IF EXISTS $links_temp" );
283 $this->output( " done.\n" );
284
285 $this->output( "Creating temporary links table..." );
286 if ( $this->hasOption( 'noKeys' ) ) {
287 $dbConn->query( "CREATE TABLE $links_temp ( " .
288 "l_from int(8) unsigned NOT NULL default '0', " .
289 "l_to int(8) unsigned NOT NULL default '0')" );
290 } else {
291 $dbConn->query( "CREATE TABLE $links_temp ( " .
292 "l_from int(8) unsigned NOT NULL default '0', " .
293 "l_to int(8) unsigned NOT NULL default '0', " .
294 "UNIQUE KEY l_from(l_from,l_to), " .
295 "KEY (l_to))" );
296 }
297 $this->output( " done.\n\n" );
298 }
299
300 private function performanceLog( $fh, $text ) {
301 if ( $this->logPerformance ) {
302 fwrite( $fh, $text );
303 }
304 }
305 }
306
307 $maintClass = ConvertLinks::class;
308 require_once RUN_MAINTENANCE_IF_MAIN;