Debian Codegraph @

extensions/Linter/includes/Database.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 namespace MediaWiki\Linter;
22
23 use MediaWiki\Config\ServiceOptions;
24 use MediaWiki\Json\FormatJson;
25 use MediaWiki\Logger\LoggerFactory;
26 use stdClass;
27 use Wikimedia\Rdbms\IDatabase;
28 use Wikimedia\Rdbms\IReadableDatabase;
29 use Wikimedia\Rdbms\LBFactory;
30 use Wikimedia\Rdbms\SelectQueryBuilder;
31
32 /**
33 * Database logic
34 */
35 class Database {
36 public const CONSTRUCTOR_OPTIONS = [];
37
38 /**
39 * Maximum number of errors to save per category,
40 * for a page, the rest are just dropped
41 */
42 public const MAX_PER_CAT = 20;
43 public const MAX_ACCURATE_COUNT = 20;
44
45 /**
46 * The linter_tag field has a maximum length of 32 characters, linter_template field a maximum of 255 characters
47 * so to ensure the length is not exceeded, the tag and template strings are truncated a few bytes below that limit
48 */
49 public const MAX_TAG_LENGTH = 30;
50 public const MAX_TEMPLATE_LENGTH = 250;
51
52 private ServiceOptions $options;
53 private CategoryManager $categoryManager;
54 private LBFactory $dbLoadBalancerFactory;
55
56 /**
57 * @param ServiceOptions $options
58 * @param CategoryManager $categoryManager
59 * @param LBFactory $dbLoadBalancerFactory
60 */
61 public function __construct(
62 ServiceOptions $options,
63 CategoryManager $categoryManager,
64 LBFactory $dbLoadBalancerFactory
65 ) {
66 $options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
67 $this->options = $options;
68 $this->categoryManager = $categoryManager;
69 $this->dbLoadBalancerFactory = $dbLoadBalancerFactory;
70 }
71
72 /**
73 * @param int $mode DB_PRIMARY or DB_REPLICA
74 * @return IDatabase
75 */
76 public function getDBConnectionRef( int $mode ): IDatabase {
77 return $this->dbLoadBalancerFactory->getMainLB()->getConnection( $mode );
78 }
79
80 /**
81 * @return IReadableDatabase
82 */
83 public function getReplicaDBConnection(): IReadableDatabase {
84 return $this->dbLoadBalancerFactory->getReplicaDatabase();
85 }
86
87 /**
88 * Get a specific LintError by id
89 *
90 * @param int $id linter_id
91 * @return bool|LintError
92 */
93 public function getFromId( int $id ) {
94 $row = $this->getReplicaDBConnection()->newSelectQueryBuilder()
95 ->select( [ 'linter_cat', 'linter_params', 'linter_start', 'linter_end' ] )
96 ->from( 'linter' )
97 ->where( [ 'linter_id' => $id ] )
98 ->caller( __METHOD__ )
99 ->fetchRow();
100
101 if ( $row ) {
102 $row->linter_id = $id;
103 return self::makeLintError( $this->categoryManager, $row );
104 } else {
105 return false;
106 }
107 }
108
109 /**
110 * Turn a database row into a LintError object
111 *
112 * @param CategoryManager $categoryManager
113 * @param stdClass $row
114 * @return LintError|bool false on error
115 */
116 public static function makeLintError( CategoryManager $categoryManager, $row ) {
117 try {
118 $name = $categoryManager->getCategoryName( $row->linter_cat );
119 } catch ( MissingCategoryException $e ) {
120 LoggerFactory::getInstance( 'Linter' )->error(
121 'Could not find name for id: {linter_cat}',
122 [ 'linter_cat' => $row->linter_cat ]
123 );
124 return false;
125 }
126 return new LintError(
127 $name,
128 [ (int)$row->linter_start, (int)$row->linter_end ],
129 $row->linter_params,
130 $row->linter_cat,
131 (int)$row->linter_id
132 );
133 }
134
135 /**
136 * Get all the lint errors for a page
137 *
138 * @param int $pageId
139 * @return LintError[]
140 */
141 public function getForPage( int $pageId ) {
142 $rows = $this->getReplicaDBConnection()->newSelectQueryBuilder()
143 ->select( [ 'linter_id', 'linter_cat', 'linter_start', 'linter_end', 'linter_params' ] )
144 ->from( 'linter' )
145 ->where( [ 'linter_page' => $pageId ] )
146 ->caller( __METHOD__ )
147 ->fetchResultSet();
148
149 $result = [];
150 foreach ( $rows as $row ) {
151 $error = self::makeLintError( $this->categoryManager, $row );
152 if ( !$error ) {
153 continue;
154 }
155 $result[$error->id()] = $error;
156 }
157
158 return $result;
159 }
160
161 /**
162 * Convert a LintError object into an array for
163 * inserting/querying in the database
164 *
165 * @param int $pageId
166 * @param int $namespaceId
167 * @param LintError $error
168 * @return array
169 */
170 private function buildErrorRow( int $pageId, int $namespaceId, LintError $error ) {
171 $result = [
172 'linter_page' => $pageId,
173 'linter_cat' => $this->categoryManager->getCategoryId( $error->category, $error->catId ),
174 'linter_params' => FormatJson::encode( $error->params, false, FormatJson::ALL_OK ),
175 'linter_start' => $error->location[ 0 ],
176 'linter_end' => $error->location[ 1 ],
177 'linter_namespace' => $namespaceId
178 ];
179
180 $templateInfo = $error->templateInfo ?? '';
181 if ( is_array( $templateInfo ) ) {
182 if ( isset( $templateInfo[ 'multiPartTemplateBlock' ] ) ) {
183 $templateInfo = 'multi-part-template-block';
184 } else {
185 $templateInfo = $templateInfo[ 'name' ] ?? '';
186 }
187 }
188 $templateInfo = mb_strcut( $templateInfo, 0, self::MAX_TEMPLATE_LENGTH );
189 $result[ 'linter_template' ] = $templateInfo;
190
191 $tagInfo = $error->tagInfo ?? '';
192 $tagInfo = mb_strcut( $tagInfo, 0, self::MAX_TAG_LENGTH );
193 $result[ 'linter_tag' ] = $tagInfo;
194
195 return $result;
196 }
197
198 /**
199 * @param LintError[] $errors
200 * @return array
201 */
202 private function countByCat( array $errors ) {
203 $count = [];
204 foreach ( $errors as $error ) {
205 if ( !isset( $count[$error->category] ) ) {
206 $count[$error->category] = 1;
207 } else {
208 $count[$error->category] += 1;
209 }
210 }
211
212 return $count;
213 }
214
215 /**
216 * Save the specified lint errors in the
217 * database
218 *
219 * @param int $pageId
220 * @param int $namespaceId
221 * @param LintError[] $errors
222 * @return array [ 'deleted' => [ cat => count ], 'added' => [ cat => count ] ]
223 */
224 public function setForPage( int $pageId, int $namespaceId, $errors ) {
225 $previous = $this->getForPage( $pageId );
226 $dbw = $this->getDBConnectionRef( DB_PRIMARY );
227 if ( !$previous && !$errors ) {
228 return [ 'deleted' => [], 'added' => [] ];
229 } elseif ( !$previous && $errors ) {
230 $toInsert = array_values( $errors );
231 $toDelete = [];
232 } elseif ( $previous && !$errors ) {
233 $dbw->newDeleteQueryBuilder()
234 ->deleteFrom( 'linter' )
235 ->where( [ 'linter_page' => $pageId ] )
236 ->caller( __METHOD__ )
237 ->execute();
238 return [ 'deleted' => $this->countByCat( $previous ), 'added' => [] ];
239 } else {
240 $toInsert = [];
241 $toDelete = $previous;
242 // Diff previous and errors
243 foreach ( $errors as $error ) {
244 $uniqueId = $error->id();
245 if ( isset( $previous[$uniqueId] ) ) {
246 unset( $toDelete[$uniqueId] );
247 } else {
248 $toInsert[] = $error;
249 }
250 }
251 }
252
253 if ( $toDelete ) {
254 $ids = [];
255 foreach ( $toDelete as $lintError ) {
256 if ( $lintError->lintId ) {
257 $ids[] = $lintError->lintId;
258 }
259 }
260 $dbw->newDeleteQueryBuilder()
261 ->deleteFrom( 'linter' )
262 ->where( [ 'linter_id' => $ids ] )
263 ->caller( __METHOD__ )
264 ->execute();
265 }
266
267 if ( $toInsert ) {
268 // Insert into db, ignoring any duplicate key errors
269 // since they're the same lint error
270 $dbw->newInsertQueryBuilder()
271 ->insertInto( 'linter' )
272 ->ignore()
273 ->rows(
274 array_map( function ( LintError $error ) use ( $pageId, $namespaceId ) {
275 return $this->buildErrorRow( $pageId, $namespaceId, $error );
276 }, $toInsert )
277 )
278 ->caller( __METHOD__ )
279 ->execute();
280 }
281
282 return [
283 'deleted' => $this->countByCat( $toDelete ),
284 'added' => $this->countByCat( $toInsert ),
285 ];
286 }
287
288 /**
289 * Get an estimate of how many rows are there for the
290 * specified category with EXPLAIN SELECT COUNT(*).
291 * If the category actually has no rows, then 0 will
292 * be returned.
293 *
294 * @param int $catId
295 * @return int
296 */
297 private function getTotalsEstimate( $catId ) {
298 $dbr = $this->getReplicaDBConnection();
299 // First see if there are no rows, or a moderate number
300 // within the limit specified by the MAX_ACCURATE_COUNT.
301 // The distinction between 0, a few and a lot is important
302 // to determine first, as estimateRowCount seem to never
303 // return 0 or accurate low error counts.
304 $rows = $dbr->newSelectQueryBuilder()
305 ->select( '*' )
306 ->from( 'linter' )
307 ->where( [ 'linter_cat' => $catId ] )
308 // Select 1 more so we can see if we're over the max limit
309 ->limit( self::MAX_ACCURATE_COUNT + 1 )
310 ->caller( __METHOD__ )
311 ->fetchRowCount();
312 // Return an accurate count if the number of errors is
313 // below the maximum accurate count limit
314 if ( $rows <= self::MAX_ACCURATE_COUNT ) {
315 return $rows;
316 }
317 // Now we can just estimate if the maximum accurate count limit
318 // was returned, which isn't the actual count but the limit reached
319 return $dbr->newSelectQueryBuilder()
320 ->select( '*' )
321 ->from( 'linter' )
322 ->where( [ 'linter_cat' => $catId ] )
323 ->caller( __METHOD__ )
324 ->estimateRowCount();
325 }
326
327 /**
328 * This uses COUNT(*), which is accurate, but can be significantly
329 * slower depending upon how many rows are in the database.
330 *
331 * @param int $pageId
332 * @return int[]
333 */
334 public function getTotalsForPage( int $pageId ): array {
335 $rows = $this->getReplicaDBConnection()->newSelectQueryBuilder()
336 ->select( [ 'linter_cat', 'COUNT(*) AS count' ] )
337 ->from( 'linter' )
338 ->where( [ 'linter_page' => $pageId ] )
339 ->caller( __METHOD__ )
340 ->groupBy( 'linter_cat' )
341 ->fetchResultSet();
342
343 // Initialize zero values
344 $categories = $this->categoryManager->getVisibleCategories();
345 $ret = array_fill_keys( $categories, 0 );
346 foreach ( $rows as $row ) {
347 try {
348 $catName = $this->categoryManager->getCategoryName( $row->linter_cat );
349 } catch ( MissingCategoryException $e ) {
350 continue;
351 }
352 // Only set visible categories. Alternatively, we could add another
353 // where clause to the selection above.
354 if ( !in_array( $catName, $categories, true ) ) {
355 continue;
356 }
357 $ret[$catName] = (int)$row->count;
358 }
359 return $ret;
360 }
361
362 /**
363 * @return int[]
364 */
365 public function getTotals() {
366 $ret = [];
367 foreach ( $this->categoryManager->getVisibleCategories() as $cat ) {
368 $id = $this->categoryManager->getCategoryId( $cat );
369 $ret[$cat] = $this->getTotalsEstimate( $id );
370 }
371
372 return $ret;
373 }
374
375 /**
376 * This code migrates namespace ID identified by the Linter records linter_page
377 * field and populates the new linter_namespace field if it is unpopulated.
378 * This code is intended to be run once though it could be run multiple times
379 * using `--force` if needed via the maintenance script.
380 * It is safe to run more than once, and will quickly exit if no records need updating.
381 *
382 * @param int $pageBatchSize
383 * @param int $linterBatchSize
384 * @param int $sleep
385 * @return int number of pages updated, each with one or more linter records
386 */
387 public function migrateNamespace(
388 int $pageBatchSize, int $linterBatchSize, int $sleep
389 ): int {
390 if ( $sleep < 0 ) {
391 $sleep = 0;
392 }
393
394 $logger = LoggerFactory::getInstance( 'Linter' );
395
396 $lbFactory = $this->dbLoadBalancerFactory;
397 $dbw = $this->getDBConnectionRef( DB_PRIMARY );
398 $dbread = $this->getDBConnectionRef( DB_REPLICA );
399
400 $logger->info( "Migrate namespace starting\n" );
401
402 $updated = 0;
403 $lastElement = 0;
404 do {
405 // Gather some unique pageId values in linter table records into an array
406 $linterPages = [];
407
408 $result = $dbw->newSelectQueryBuilder()
409 ->select( 'linter_page' )
410 ->distinct()
411 ->from( 'linter' )
412 ->where( $dbw->expr( 'linter_page', '>', $lastElement ) )
413 ->andWhere( [ 'linter_namespace' => null ] )
414 ->orderBy( 'linter_page' )
415 ->limit( $linterBatchSize )
416 ->caller( __METHOD__ )
417 ->fetchResultSet();
418
419 foreach ( $result as $row ) {
420 $lastElement = intval( $row->linter_page );
421 $linterPages[] = $lastElement;
422 }
423 $linterPagesLength = count( $linterPages );
424
425 $pageStartIndex = 0;
426 do {
427 $pageIdBatch = array_slice( $linterPages, $pageStartIndex, $pageBatchSize );
428
429 if ( count( $pageIdBatch ) > 0 ) {
430
431 $pageResults = $dbread->newSelectQueryBuilder()
432 ->select( [ 'page_id', 'page_namespace' ] )
433 ->from( 'page' )
434 ->where( [ 'page_id' => $pageIdBatch ] )
435 ->caller( __METHOD__ )
436 ->fetchResultSet();
437
438 foreach ( $pageResults as $pageRow ) {
439 $pageId = intval( $pageRow->page_id );
440 $namespaceId = intval( $pageRow->page_namespace );
441
442 // If a record about to be updated has been removed by another process,
443 // the update will not error, and continue updating the existing records.
444 $dbw->newUpdateQueryBuilder()
445 ->update( 'linter' )
446 ->set( [ 'linter_namespace' => $namespaceId ] )
447 ->where( [
448 'linter_namespace' => null,
449 'linter_page' => $pageId
450 ] )
451 ->caller( __METHOD__ )
452 ->execute();
453 $updated += $dbw->affectedRows();
454 }
455
456 // Sleep between batches for replication to catch up
457 $lbFactory->waitForReplication();
458 sleep( $sleep );
459 }
460
461 $pageStartIndex += $pageBatchSize;
462 } while ( $linterPagesLength > $pageStartIndex );
463
464 $logger->info( 'Migrated ' . $updated . " page IDs\n" );
465
466 } while ( $linterPagesLength > 0 );
467
468 $logger->info( "Migrate namespace finished!\n" );
469
470 return $updated;
471 }
472
473 /**
474 * This code migrates the content of Linter record linter_params to linter_template and
475 * linter_tag fields if they are unpopulated or stale.
476 * This code should only be run once and thereafter disabled but must run to completion.
477 * It can be restarted if interrupted and will pick up where new divergences are found.
478 * Note: When linter_params are not set, the content is set to '[]' indicating no content
479 * and the code also handles a null linter_params field if found.
480 * This code is only run once by maintenance script migrateTagTemplate.php
481 *
482 * @param int $batchSize
483 * @param int $sleep
484 * @return int
485 */
486 public function migrateTemplateAndTagInfo(
487 int $batchSize, int $sleep
488 ): int {
489 if ( $sleep < 0 ) {
490 $sleep = 0;
491 }
492
493 $logger = LoggerFactory::getInstance( 'Linter' );
494
495 $lbFactory = $this->dbLoadBalancerFactory;
496 $dbw = $this->getDBConnectionRef( DB_PRIMARY );
497
498 $logger->info( "Migration of linter_params field to linter_tag and linter_template fields starting\n" );
499
500 $updated = 0;
501 $lastElement = 0;
502 do {
503 $results = $dbw->newSelectQueryBuilder()
504 ->select( [ 'linter_id', 'linter_params', 'linter_template', 'linter_tag' ] )
505 ->from( 'linter' )
506 ->where( [
507 $dbw->expr( "linter_params", '!=', '[]' ),
508 $dbw->expr( "linter_params", '!=', null ),
509 $dbw->expr( "linter_id", '>', $lastElement )
510 ] )
511 ->orderBy( 'linter_id', selectQueryBuilder::SORT_ASC )
512 ->limit( $batchSize )
513 ->caller( __METHOD__ )
514 ->fetchResultSet();
515 $linterBatchLength = 0;
516
517 foreach ( $results as $row ) {
518 $linter_id = intval( $row->linter_id );
519 $lastElement = $linter_id;
520 $linter_params = FormatJson::decode( $row->linter_params );
521 $templateInfo = $linter_params->templateInfo ?? '';
522 if ( is_object( $templateInfo ) ) {
523 if ( isset( $templateInfo->multiPartTemplateBlock ) ) {
524 $templateInfo = 'multi-part-template-block';
525 } else {
526 $templateInfo = $templateInfo->name ?? '';
527 }
528 }
529 $templateInfo = mb_strcut( $templateInfo, 0, self::MAX_TEMPLATE_LENGTH );
530
531 $tagInfo = $linter_params->name ?? '';
532 $tagInfo = mb_strcut( $tagInfo, 0, self::MAX_TAG_LENGTH );
533
534 // compare the content of linter_params to the template and tag field contents
535 // and if they diverge, update the field with the correct template and tag info.
536 // This behavior allows this function to be restarted should it be interrupted
537 // and avoids repeating database record updates that are already correct due to
538 // having been populated when the error record was created with the new recordLintError
539 // write code that populates the template and tag fields, or for records populated
540 // during a previous but interrupted run of this migrate code.
541 if ( $templateInfo != $row->linter_template || $tagInfo != $row->linter_tag ) {
542 // If the record about to be updated has been removed by another process,
543 // the update will not do anything and just return with no records updated.
544 $dbw->newUpdateQueryBuilder()
545 ->update( 'linter' )
546 ->set( [ 'linter_template' => $templateInfo, 'linter_tag' => $tagInfo, ] )
547 ->where( [ 'linter_id' => $linter_id ] )
548 ->caller( __METHOD__ )
549 ->execute();
550 $updated += $dbw->affectedRows();
551 }
552 $linterBatchLength++;
553 }
554
555 // Sleep between batches for replication to catch up
556 $lbFactory->waitForReplication();
557 if ( $sleep > 0 ) {
558 sleep( $sleep );
559 }
560
561 $logger->info( 'Migrated ' . $updated . " linter IDs\n" );
562
563 } while ( $linterBatchLength > 0 );
564
565 $logger->info( "Migrate linter_params to linter_tag and linter_template fields finished!\n" );
566
567 return $updated;
568 }
569
570 }