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