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