3 * Convert from the old links schema (string->ID) to the new schema (ID->ID).
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.
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.
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
21 * @ingroup Maintenance
24 use MediaWiki\MediaWikiServices
;
26 require_once __DIR__
. '/Maintenance.php';
29 * Maintenance script to convert from the old links schema (string->ID)
30 * to the new schema (ID->ID).
32 * The wiki should be put into read-only mode while this script executes.
34 * @ingroup Maintenance
36 class ConvertLinks
extends Maintenance
{
37 private $logPerformance;
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' );
45 $this->addArg( 'logperformance', "Log performance to perfLogFilename.", false );
48 "Filename where performance is logged if --logperformance was set "
49 . "(defaults to 'convLinksPerf.txt').",
54 "Don't overwrite the old links table with the new one, leave the new table at links_temp.",
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.",
66 public function getDbType() {
67 return Maintenance
::DB_ADMIN
;
70 public function execute() {
71 $dbw = $this->getDB( DB_MASTER
);
73 $type = $dbw->getType();
74 if ( $type != 'mysql' ) {
75 $this->output( "Link table conversion not necessary for $type\n" );
81 $numBadLinks = $curRowsRead = 0;
83 # total tuples INSERTed into links_temp
84 $totalTuplesInserted = 0;
86 # whether or not to give progress reports while reading IDs from cur table
87 $reportCurReadProgress = true;
89 # number of rows between progress reports
90 $curReadReportInterval = 1000;
92 # whether or not to give progress reports during conversion
93 $reportLinksConvProgress = true;
95 # number of rows per INSERT
96 $linksConvInsertInterval = 1000;
98 $initialRowOffset = 0;
100 # not used yet; highest row number from links table to process
101 # $finalRowOffset = 0;
103 $this->logPerformance
= $this->hasOption( 'logperformance' );
104 $perfLogFilename = $this->getArg( 1, "convLinksPerf.txt" );
105 $overwriteLinksTable = !$this->hasOption( 'keep-links-table' );
106 $noKeys = $this->hasOption( 'noKeys' );
108 # --------------------------------------------------------------------
110 list( $cur, $links, $links_temp, $links_backup ) =
111 $dbw->tableNamesN( 'cur', 'links', 'links_temp', 'links_backup' );
113 if ( $dbw->tableExists( 'pagelinks' ) ) {
114 $this->output( "...have pagelinks; skipping old links table updates\n" );
119 $res = $dbw->query( "SELECT l_from FROM $links LIMIT 1" );
120 // @phan-suppress-next-line PhanUndeclaredMethod
121 if ( $dbw->fieldType( $res, 0 ) == "int" ) {
122 $this->output( "Schema already converted\n" );
127 $res = $dbw->query( "SELECT COUNT(*) AS count FROM $links" );
128 $row = $dbw->fetchObject( $res );
129 $numRows = $row->count
;
131 if ( $numRows == 0 ) {
132 $this->output( "Updating schema (no rows to convert)...\n" );
133 $this->createTempTable();
136 if ( $this->logPerformance
) {
137 $fh = fopen( $perfLogFilename, "w" );
139 $this->error( "Couldn't open $perfLogFilename" );
140 $this->logPerformance
= false;
143 $baseTime = $startTime = microtime( true );
144 # Create a title -> cur_id map
145 $this->output( "Loading IDs from $cur table...\n" );
146 $this->performanceLog( $fh, "Reading $numRows rows from cur table...\n" );
147 $this->performanceLog( $fh, "rows read vs seconds elapsed:\n" );
148 $contentLang = MediaWikiServices
::getInstance()->getContentLanguage();
154 "SELECT cur_namespace,cur_title,cur_id FROM $cur " .
155 "WHERE cur_id > $lastId ORDER BY cur_id LIMIT 10000"
157 foreach ( $res as $row ) {
158 $title = $row->cur_title
;
159 if ( $row->cur_namespace
) {
160 $title = $contentLang->getNsText( $row->cur_namespace
) . ":$title";
162 $ids[$title] = $row->cur_id
;
164 if ( $reportCurReadProgress ) {
165 if ( ( $curRowsRead %
$curReadReportInterval ) == 0 ) {
166 $this->performanceLog(
168 $curRowsRead . " " . ( microtime( true ) - $baseTime ) . "\n"
170 $this->output( "\t$curRowsRead rows of $cur table read.\n" );
173 $lastId = $row->cur_id
;
175 } while ( $res->numRows() > 0 );
176 $this->output( "Finished loading IDs.\n\n" );
177 $this->performanceLog(
179 "Took " . ( microtime( true ) - $baseTime ) . " seconds to load IDs.\n\n"
182 # --------------------------------------------------------------------
184 # Now, step through the links table (in chunks of $linksConvInsertInterval rows),
185 # convert, and write to the new table.
186 $this->createTempTable();
187 $this->performanceLog( $fh, "Resetting timer.\n\n" );
188 $baseTime = microtime( true );
189 $this->output( "Processing $numRows rows from $links table...\n" );
190 $this->performanceLog( $fh, "Processing $numRows rows from $links table...\n" );
191 $this->performanceLog( $fh, "rows inserted vs seconds elapsed:\n" );
193 for ( $rowOffset = $initialRowOffset; $rowOffset < $numRows;
194 $rowOffset +
= $linksConvInsertInterval
196 $sqlRead = "SELECT * FROM $links ";
197 $sqlRead = $dbw->limitResult( $sqlRead, $linksConvInsertInterval, $rowOffset );
198 $res = $dbw->query( $sqlRead );
200 $sqlWrite = [ "INSERT INTO $links_temp (l_from,l_to) VALUES " ];
202 $sqlWrite = [ "INSERT IGNORE INTO $links_temp (l_from,l_to) VALUES " ];
205 $tuplesAdded = 0; # no tuples added to INSERT yet
206 foreach ( $res as $row ) {
207 $fromTitle = $row->l_from
;
208 if ( array_key_exists( $fromTitle, $ids ) ) { # valid title
209 $from = $ids[$fromTitle];
211 if ( $tuplesAdded != 0 ) {
214 $sqlWrite[] = "($from,$to)";
216 } else { # invalid title
220 # $this->output( "rowOffset: $rowOffset\ttuplesAdded: "
221 # . "$tuplesAdded\tnumBadLinks: $numBadLinks\n" );
222 if ( $tuplesAdded != 0 ) {
223 if ( $reportLinksConvProgress ) {
224 $this->output( "Inserting $tuplesAdded tuples into $links_temp..." );
226 $dbw->query( implode( "", $sqlWrite ) );
227 $totalTuplesInserted +
= $tuplesAdded;
228 if ( $reportLinksConvProgress ) {
229 $this->output( " done. Total $totalTuplesInserted tuples inserted.\n" );
230 $this->performanceLog(
232 $totalTuplesInserted . " " . ( microtime( true ) - $baseTime ) . "\n"
237 $this->output( "$totalTuplesInserted valid titles and "
238 . "$numBadLinks invalid titles were processed.\n\n" );
239 $this->performanceLog(
241 "$totalTuplesInserted valid titles and $numBadLinks invalid titles were processed.\n"
243 $this->performanceLog(
245 "Total execution time: " . ( microtime( true ) - $startTime ) . " seconds.\n"
247 if ( $this->logPerformance
) {
251 # --------------------------------------------------------------------
253 if ( $overwriteLinksTable ) {
254 # Check for existing links_backup, and delete it if it exists.
255 $this->output( "Dropping backup links table if it exists..." );
256 $dbw->query( "DROP TABLE IF EXISTS $links_backup", __METHOD__
);
257 $this->output( " done.\n" );
259 # Swap in the new table, and move old links table to links_backup
260 $this->output( "Swapping tables '$links' to '$links_backup'; '$links_temp' to '$links'..." );
261 $dbw->query( "RENAME TABLE links TO $links_backup, $links_temp TO $links", __METHOD__
);
262 $this->output( " done.\n\n" );
264 $this->output( "Conversion complete. The old table remains at $links_backup;\n" );
265 $this->output( "delete at your leisure.\n" );
267 $this->output( "Conversion complete. The converted table is at $links_temp;\n" );
268 $this->output( "the original links table is unchanged.\n" );
272 private function createTempTable() {
273 $dbConn = $this->getDB( DB_MASTER
);
275 if ( !( $dbConn->isOpen() ) ) {
276 $this->output( "Opening connection to database failed.\n" );
280 $links_temp = $dbConn->tableName( 'links_temp' );
282 $this->output( "Dropping temporary links table if it exists..." );
283 $dbConn->query( "DROP TABLE IF EXISTS $links_temp" );
284 $this->output( " done.\n" );
286 $this->output( "Creating temporary links table..." );
287 if ( $this->hasOption( 'noKeys' ) ) {
288 $dbConn->query( "CREATE TABLE $links_temp ( " .
289 "l_from int(8) unsigned NOT NULL default '0', " .
290 "l_to int(8) unsigned NOT NULL default '0')" );
292 $dbConn->query( "CREATE TABLE $links_temp ( " .
293 "l_from int(8) unsigned NOT NULL default '0', " .
294 "l_to int(8) unsigned NOT NULL default '0', " .
295 "UNIQUE KEY l_from(l_from,l_to), " .
298 $this->output( " done.\n\n" );
301 private function performanceLog( $fh, $text ) {
302 if ( $this->logPerformance
) {
303 fwrite( $fh, $text );
308 $maintClass = ConvertLinks
::class;
309 require_once RUN_MAINTENANCE_IF_MAIN
;