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