Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
90.40% covered (success)
90.40%
386 / 427
53.85% covered (warning)
53.85%
7 / 13
CRAP
0.00% covered (danger)
0.00%
0 / 1
ThreadItemStore
90.40% covered (success)
90.40%
386 / 427
53.85% covered (warning)
53.85%
7 / 13
66.51
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 findNewestRevisionsByName
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
2.03
 findNewestRevisionsById
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
1
 findNewestRevisionsByHeading
92.31% covered (success)
92.31%
60 / 65
0.00% covered (danger)
0.00%
0 / 1
5.01
 findNewestRevisionsByQuery
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 fetchItems
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
4
 fetchItemsResultSet
100.00% covered (success)
100.00%
32 / 32
100.00% covered (success)
100.00%
1 / 1
1
 fetchRevisionAndPageForItems
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
4
 getThreadItemFromRow
85.00% covered (warning)
85.00%
34 / 40
0.00% covered (danger)
0.00%
0 / 1
11.41
 findThreadItemsInCurrentRevision
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
12
 getIdsNamesBuilder
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
 findOrInsertId
38.89% covered (danger)
38.89%
7 / 18
0.00% covered (danger)
0.00%
0 / 1
7.65
 insertThreadItems
98.03% covered (success)
98.03%
199 / 203
0.00% covered (danger)
0.00%
0 / 1
24
1<?php
2
3namespace MediaWiki\Extension\DiscussionTools;
4
5use Exception;
6use MediaWiki\Extension\DiscussionTools\ThreadItem\CommentItem;
7use MediaWiki\Extension\DiscussionTools\ThreadItem\DatabaseCommentItem;
8use MediaWiki\Extension\DiscussionTools\ThreadItem\DatabaseHeadingItem;
9use MediaWiki\Extension\DiscussionTools\ThreadItem\DatabaseThreadItem;
10use MediaWiki\Extension\DiscussionTools\ThreadItem\HeadingItem;
11use MediaWiki\Language\Language;
12use MediaWiki\Page\PageStore;
13use MediaWiki\Revision\RevisionRecord;
14use MediaWiki\Revision\RevisionStore;
15use MediaWiki\Title\TitleFormatter;
16use MediaWiki\Title\TitleValue;
17use MediaWiki\User\ActorStore;
18use MediaWiki\Utils\MWTimestamp;
19use stdClass;
20use Wikimedia\NormalizedException\NormalizedException;
21use Wikimedia\Rdbms\DBError;
22use Wikimedia\Rdbms\IDatabase;
23use Wikimedia\Rdbms\IExpression;
24use Wikimedia\Rdbms\ILBFactory;
25use Wikimedia\Rdbms\ILoadBalancer;
26use Wikimedia\Rdbms\IReadableDatabase;
27use Wikimedia\Rdbms\IResultWrapper;
28use Wikimedia\Rdbms\LikeValue;
29use Wikimedia\Rdbms\ReadOnlyMode;
30use Wikimedia\Rdbms\SelectQueryBuilder;
31use Wikimedia\Timestamp\TimestampException;
32
33/**
34 * Stores and fetches ThreadItemSets from the database.
35 */
36class ThreadItemStore {
37
38    public function __construct(
39        private readonly ILBFactory $dbProvider,
40        private readonly ReadOnlyMode $readOnlyMode,
41        private readonly PageStore $pageStore,
42        private readonly RevisionStore $revStore,
43        private readonly TitleFormatter $titleFormatter,
44        private readonly ActorStore $actorStore,
45        private readonly Language $language,
46    ) {
47    }
48
49    /**
50     * Find the thread items with the given name in the newest revision of every page in which they
51     * have appeared.
52     *
53     * @param string|string[] $itemName
54     * @param int|null $limit
55     * @return DatabaseThreadItem[]
56     */
57    public function findNewestRevisionsByName( $itemName, ?int $limit = 50 ): array {
58        // Disallow querying for headings of sections that contain no comments.
59        // They all share the same name, so this would return a huge useless list on most wikis.
60        // (But we still store them, as we might need this data elsewhere.)
61        $itemName = array_diff( (array)$itemName, [ 'h-' ] );
62        if ( !$itemName ) {
63            return [];
64        }
65
66        $where = [ 'it_itemname' => $itemName ];
67        return $this->fetchItems( __METHOD__, $where, $limit );
68    }
69
70    /**
71     * Find the thread items with the given ID in the newest revision of every page in which they have
72     * appeared.
73     *
74     * @param string|string[] $itemId
75     * @param int|null $limit
76     * @return DatabaseThreadItem[]
77     */
78    public function findNewestRevisionsById( $itemId, ?int $limit = 50 ): array {
79        $dbr = $this->dbProvider->getReplicaDatabase();
80
81        // First find the name associated with the ID; then find by name. Otherwise we wouldn't find the
82        // latest revision in case comment ID changed, e.g. the comment was moved elsewhere on the page.
83        $itemNameQueryBuilder = $this->getIdsNamesBuilder()
84            ->where( [
85                'itid_itemid' => $itemId,
86                $dbr->expr( 'it_itemname', '!=', 'h-' ),
87            ] )
88            ->field( 'it_itemname' );
89            // I think there may be more than 1 only in case of headings?
90            // For comments, any ID corresponds to just 1 name.
91            // Not sure how bad it is to not have limit( 1 ) here?
92            // It might scan a bunch of rows...
93            // ->limit( 1 );
94
95        $where = [
96            'it_itemname IN (' . $itemNameQueryBuilder->getSQL() . ')',
97        ];
98
99        return $this->fetchItems( __METHOD__, $where, $limit );
100    }
101
102    /**
103     * Find heading items matching some text which:
104     *
105     *  1. appeared at some point in the history of the targetpage, or if this returns no results:
106     *  2. currently appear on a subpage of the target page, or if this returns no results:
107     *  3. currently appears on any page, but only if it is a unique match
108     *
109     * @param string|string[] $heading Heading text to match
110     * @param int $articleId Article ID of the target page
111     * @param TitleValue $title Title of the target page
112     * @param int|null $limit
113     * @return DatabaseThreadItem[]
114     */
115    public function findNewestRevisionsByHeading(
116        $heading, int $articleId, TitleValue $title, ?int $limit = 50
117    ): array {
118        // Mirrors CommentParser::truncateForId
119        $heading = trim( $this->language->truncateForDatabase( $heading, 80, '' ), '_' );
120
121        $dbr = $this->dbProvider->getReplicaDatabase();
122
123        // 1. Try to find items which have appeared on the page at some point
124        //    in its history.
125        $itemIdInPageHistoryQueryBuilder = $this->getIdsNamesBuilder()
126            ->caller( __METHOD__ . ' case 1' )
127            ->join( 'revision', null, [ 'rev_id = itr_revision_id' ] )
128            ->where( $dbr->expr( 'itid_itemid', IExpression::LIKE, new LikeValue(
129                'h-' . $heading . '-',
130                $dbr->anyString()
131            ) ) )
132            // Has once appeared on the specified page ID
133            ->where( [ 'rev_page' => $articleId ] )
134            ->field( 'itid_itemid' );
135
136        $threadItems = $this->findNewestRevisionsByQuery( __METHOD__ . ' case 1',
137            $itemIdInPageHistoryQueryBuilder, $limit );
138
139        if ( count( $threadItems ) ) {
140            return $threadItems;
141        }
142
143        // 2. If the thread item's database hasn't been back-filled with historical revisions
144        //    then approach (1) may not work, instead look for matching headings the currently
145        //    appear on subpages, which matches the archiving convention on most wikis.
146        $itemIdInSubPageQueryBuilder = $this->getIdsNamesBuilder()
147            ->caller( __METHOD__ . ' case 2' )
148            ->join( 'page', null, [ 'page_id = itp_page_id' ] )
149            ->where( $dbr->expr( 'itid_itemid', IExpression::LIKE, new LikeValue(
150                'h-' . $heading . '-',
151                $dbr->anyString()
152            ) ) )
153            ->where( $dbr->expr( 'page_title', IExpression::LIKE, new LikeValue(
154                $title->getText() . '/',
155                $dbr->anyString()
156            ) ) )
157            ->where( [ 'page_namespace' => $title->getNamespace() ] )
158            ->field( 'itid_itemid' );
159
160        $threadItems = $this->findNewestRevisionsByQuery( __METHOD__ . ' case 2',
161            $itemIdInSubPageQueryBuilder, $limit );
162
163        if ( count( $threadItems ) ) {
164            return $threadItems;
165        }
166
167        // 3. Look for an "exact" match of the heading on any page. Because we are searching
168        //    so broadly, only return if there is exactly one match to the heading name.
169        $itemIdInAnyPageQueryBuilder = $this->getIdsNamesBuilder()
170            ->caller( __METHOD__ . ' case 3' )
171            ->join( 'page', null, [ 'page_id = itp_page_id', 'page_latest = itr_revision_id' ] )
172            ->where( $dbr->expr( 'itid_itemid', IExpression::LIKE, new LikeValue(
173                'h-' . $heading . '-',
174                $dbr->anyString()
175            ) ) )
176            ->field( 'itid_itemid' )
177            // We only care if there is one, or more than one result
178            ->limit( 2 );
179
180        // Check there is only one result in the sub-query
181        $itemIds = $itemIdInAnyPageQueryBuilder->fetchFieldValues();
182        if ( count( $itemIds ) === 1 ) {
183            return $this->findNewestRevisionsByQuery( __METHOD__ . ' case 3', $itemIds[ 0 ] );
184        }
185
186        // 4. If there are no matches, check if the "talk" page has ever had any discussions
187        //    on it (comments, not just headings). If not then throw an error instead of
188        //    returning an empty list. This prevents the "topic could not be found" message
189        //    from showing in the frontend. (T374598)
190        $anyItemsInPageHistoryQueryBuilder = $this->getIdsNamesBuilder()
191            ->caller( __METHOD__ . ' case 4' )
192            ->join( 'revision', null, [ 'rev_id = itr_revision_id' ] )
193            // Only comments, as non-talk headings are recorded
194            ->where( $dbr->expr( 'itid_itemid', IExpression::LIKE, new LikeValue(
195                'c-',
196                $dbr->anyString()
197            ) ) )
198            // On the specified page ID
199            ->where( [ 'rev_page' => $articleId ] )
200            ->field( 'itid_itemid' )
201            ->limit( 1 );
202
203        // Check there is only one result in the sub-query
204        $itemIds = $anyItemsInPageHistoryQueryBuilder->fetchFieldValues();
205        if ( count( $itemIds ) === 0 ) {
206            throw new PageNeverHadThreadsException(
207                "Page {page} has never contained any discussions",
208                [ 'page' => $articleId ]
209            );
210        }
211
212        return [];
213    }
214
215    /**
216     * @param string $fname
217     * @param SelectQueryBuilder|string $itemIdOrQueryBuilder Sub-query which returns item ID's, or an itemID
218     * @param int|null $limit
219     * @return DatabaseThreadItem[]
220     */
221    private function findNewestRevisionsByQuery( string $fname, $itemIdOrQueryBuilder, ?int $limit = 50 ): array {
222        if ( $itemIdOrQueryBuilder instanceof SelectQueryBuilder ) {
223            $where = [ 'itid_itemid IN (' . $itemIdOrQueryBuilder->getSQL() . ')' ];
224        } else {
225            $where = [ 'itid_itemid' => $itemIdOrQueryBuilder ];
226        }
227
228        return $this->fetchItems( $fname, $where, $limit );
229    }
230
231    /**
232     * @return DatabaseThreadItem[]
233     */
234    private function fetchItems( string $fname, array $where, ?int $limit ): array {
235        $queryBuilder = $this->getIdsNamesBuilder()->caller( $fname )
236            ->where( $where );
237
238        if ( $limit !== null ) {
239            $queryBuilder->limit( $limit );
240        }
241
242        $result = $this->fetchItemsResultSet( $queryBuilder );
243        $revs = $this->fetchRevisionAndPageForItems( $result );
244
245        $threadItems = [];
246        foreach ( $result as $row ) {
247            $threadItem = $this->getThreadItemFromRow( $row, null, $revs );
248            if ( $threadItem ) {
249                $threadItems[] = $threadItem;
250            }
251        }
252        return $threadItems;
253    }
254
255    private function fetchItemsResultSet( SelectQueryBuilder $queryBuilder ): IResultWrapper {
256        $queryBuilder
257            ->fields( [
258                'itr_id',
259                'it_itemname',
260                'it_timestamp',
261                'it_actor',
262                'itid_itemid',
263                'itr_parent_id',
264                'itr_transcludedfrom',
265                'itr_level',
266                'itr_headinglevel',
267                'itr_revision_id',
268            ] )
269            // PageStore fields for the transcluded-from page
270            ->leftJoin( 'page', null, [ 'page_id = itr_transcludedfrom' ] )
271            ->fields( $this->pageStore->getSelectFields() )
272            // ActorStore fields for the author
273            ->leftJoin( 'actor', null, [ 'actor_id = it_actor' ] )
274            ->fields( [ 'actor_id', 'actor_name', 'actor_user' ] )
275            // Parent item ID (the string, not just the primary key)
276            ->leftJoin(
277                $this->getIdsNamesBuilder()
278                    ->caller( __METHOD__ )
279                    ->fields( [
280                        'itr_parent__itr_id' => 'itr_id',
281                        'itr_parent__itid_itemid' => 'itid_itemid',
282                    ] ),
283                null,
284                [ 'itr_parent_id = itr_parent__itr_id' ]
285            )
286            ->field( 'itr_parent__itid_itemid' );
287
288        return $queryBuilder->fetchResultSet();
289    }
290
291    /**
292     * @return stdClass[]
293     */
294    private function fetchRevisionAndPageForItems( IResultWrapper $result ): array {
295        // This could theoretically be done in the same query as fetchItemsResultSet(),
296        // but the resulting query would be two screens long
297        // and we'd have to alias a lot of fields to avoid conflicts.
298        $revs = [];
299        foreach ( $result as $row ) {
300            $revs[ $row->itr_revision_id ] = null;
301        }
302        $revQueryBuilder = $this->dbProvider->getReplicaDatabase()->newSelectQueryBuilder()
303            ->caller( __METHOD__ )
304            ->queryInfo( $this->revStore->getQueryInfo( [ 'page' ] ) )
305            ->fields( $this->pageStore->getSelectFields() )
306            ->where( $revs ? [ 'rev_id' => array_keys( $revs ) ] : '0=1' );
307        $revResult = $revQueryBuilder->fetchResultSet();
308        foreach ( $revResult as $row ) {
309            $revs[ $row->rev_id ] = $row;
310        }
311        return $revs;
312    }
313
314    private function getThreadItemFromRow(
315        stdClass $row, ?DatabaseThreadItemSet $set, array $revs
316    ): ?DatabaseThreadItem {
317        if ( $revs[ $row->itr_revision_id ] === null ) {
318            // We didn't find the 'revision' table row at all, this revision is deleted.
319            // (The page may or may not have other non-deleted revisions.)
320            // Pretend the thread item doesn't exist to avoid leaking data to users who shouldn't see it.
321            // TODO Allow privileged users to see it (we'd need to query from 'archive')
322            return null;
323        }
324
325        $revRow = $revs[$row->itr_revision_id];
326        $page = $this->pageStore->newPageRecordFromRow( $revRow );
327        $rev = $this->revStore->newRevisionFromRow( $revRow );
328        if ( $rev->isDeleted( RevisionRecord::DELETED_TEXT ) ) {
329            // This revision is revision-deleted.
330            // TODO Allow privileged users to see it
331            return null;
332        }
333
334        if ( $set && $row->itr_parent__itid_itemid ) {
335            $parent = $set->findCommentById( $row->itr_parent__itid_itemid );
336        } else {
337            $parent = null;
338        }
339
340        if ( $row->itr_transcludedfrom && $row->page_id ) {
341            $transcludedFrom = $this->titleFormatter->getPrefixedText(
342                $this->pageStore->newPageRecordFromRow( $row ) );
343        } else {
344            $transcludedFrom = $row->itr_transcludedfrom === '0';
345        }
346
347        if ( $row->it_timestamp !== null && $row->it_actor !== null ) {
348            $author = $this->actorStore->newActorFromRow( $row )->getName();
349
350            $item = new DatabaseCommentItem(
351                $page,
352                $rev,
353                $row->it_itemname,
354                $row->itid_itemid,
355                $parent,
356                $transcludedFrom,
357                (int)$row->itr_level,
358                $row->it_timestamp,
359                $author
360            );
361        } else {
362            $item = new DatabaseHeadingItem(
363                $page,
364                $rev,
365                $row->it_itemname,
366                $row->itid_itemid,
367                $parent,
368                $transcludedFrom,
369                (int)$row->itr_level,
370                $row->itr_headinglevel === null ? null : (int)$row->itr_headinglevel
371            );
372        }
373
374        if ( $parent ) {
375            $parent->addReply( $item );
376        }
377        return $item;
378    }
379
380    /**
381     * Find the thread item set for the given revision, assuming that it is the current revision of
382     * its page.
383     */
384    public function findThreadItemsInCurrentRevision( int $revId ): DatabaseThreadItemSet {
385        $queryBuilder = $this->getIdsNamesBuilder()
386            ->caller( __METHOD__ )
387            ->where( [ 'itr_revision_id' => $revId ] )
388            // We must process parents before their children in the loop later
389            ->orderBy( 'itr_id', SelectQueryBuilder::SORT_ASC );
390
391        $result = $this->fetchItemsResultSet( $queryBuilder );
392        $revs = $this->fetchRevisionAndPageForItems( $result );
393
394        $set = new DatabaseThreadItemSet();
395        foreach ( $result as $row ) {
396            $threadItem = $this->getThreadItemFromRow( $row, $set, $revs );
397            if ( $threadItem ) {
398                $set->addThreadItem( $threadItem );
399                $set->updateIdAndNameMaps( $threadItem );
400            }
401        }
402        return $set;
403    }
404
405    private function getIdsNamesBuilder(): SelectQueryBuilder {
406        $dbr = $this->dbProvider->getReplicaDatabase();
407
408        $queryBuilder = $dbr->newSelectQueryBuilder()
409            ->from( 'discussiontools_items' )
410            ->join( 'discussiontools_item_pages', null, [ 'itp_items_id = it_id' ] )
411            ->join( 'discussiontools_item_revisions', null, [
412                'itr_items_id = it_id',
413                // Only the latest revision of the items with each name
414                'itr_revision_id = itp_newest_revision_id',
415            ] )
416            ->join( 'discussiontools_item_ids', null, [ 'itid_id = itr_itemid_id' ] );
417
418        return $queryBuilder;
419    }
420
421    /**
422     * @param callable $find Function that does a SELECT and returns primary key field
423     * @param callable $insert Function that does an INSERT IGNORE and returns last insert ID
424     * @param bool &$didInsert Set to true if the insert succeeds
425     * @param RevisionRecord $rev For error logging
426     * @return int Return value of whichever function succeeded
427     */
428    private function findOrInsertId(
429        callable $find, callable $insert, bool &$didInsert, RevisionRecord $rev
430    ) {
431        $dbw = $this->dbProvider->getPrimaryDatabase();
432
433        $id = $find( $dbw );
434        if ( !$id ) {
435            $id = $insert( $dbw );
436            if ( $id ) {
437                $didInsert = true;
438            } else {
439                // Maybe it's there, but we can't see it due to REPEATABLE_READ?
440                // Try again in another connection. (T339882, T322701)
441                $dbwAnother = $this->dbProvider->getMainLB()
442                    ->getConnection( DB_PRIMARY, [], false, ILoadBalancer::CONN_TRX_AUTOCOMMIT );
443                $id = $find( $dbwAnother );
444                if ( !$id ) {
445                    throw new NormalizedException(
446                        "Database can't find our row and won't let us insert it on page {page} revision {revision}",
447                        [
448                            'page' => $rev->getPageId(),
449                            'revision' => $rev->getId(),
450                        ]
451                    );
452                }
453            }
454        }
455        return $id;
456    }
457
458    /**
459     * Store the thread item set.
460     *
461     * @param RevisionRecord $rev
462     * @param ContentThreadItemSet $threadItemSet
463     * @throws TimestampException
464     * @throws DBError
465     * @throws Exception
466     */
467    public function insertThreadItems( RevisionRecord $rev, ContentThreadItemSet $threadItemSet ): bool {
468        if ( $this->readOnlyMode->isReadOnly() ) {
469            return false;
470        }
471
472        $dbw = $this->dbProvider->getPrimaryDatabase();
473        $didInsert = false;
474        $method = __METHOD__;
475
476        // Map of item IDs (strings) to their discussiontools_item_ids.itid_id field values (ints)
477        $itemIdsIds = [];
478        '@phan-var array<string,int> $itemIdsIds';
479        // Map of item IDs (strings) to their discussiontools_items.it_id field values (ints)
480        $itemsIds = [];
481        '@phan-var array<string,int> $itemsIds';
482
483        // Insert or find discussiontools_item_ids rows, fill in itid_id field values.
484        // (This is not in a transaction. Orphaned rows in this table are harmlessly ignored,
485        // and long transactions caused performance issues on Wikimedia wikis: T315353#8218914.)
486        foreach ( $threadItemSet->getThreadItems() as $item ) {
487            $itemIdsId = $this->findOrInsertId(
488                static function ( IReadableDatabase $dbw ) use ( $item, $method ) {
489                    $ids = [ $item->getId() ];
490                    if ( $item->getLegacyId() !== null ) {
491                        // Avoid duplicates if the item exists under the legacy ID
492                        // (i.e. with trailing underscores in the title part).
493                        // The actual fixing of IDs is done by a maintenance script
494                        // FixTrailingWhitespaceIds, as archived talk pages are unlikely
495                        // to be edited again in the future.
496                        // Once FixTrailingWhitespaceIds has run on and enough time has
497                        // passed, we can remove all legacy ID code (again).
498                        $ids[] = $item->getLegacyId();
499                    }
500                    return $dbw->newSelectQueryBuilder()
501                        ->from( 'discussiontools_item_ids' )
502                        ->field( 'itid_id' )
503                        ->where( [ 'itid_itemid' => $ids ] )
504                        ->caller( $method )
505                        ->fetchField();
506                },
507                static function ( IDatabase $dbw ) use ( $item, $method ) {
508                    $dbw->newInsertQueryBuilder()
509                        ->table( 'discussiontools_item_ids' )
510                        ->row( [ 'itid_itemid' => $item->getId() ] )
511                        ->ignore()
512                        ->caller( $method )
513                        ->execute();
514                    return $dbw->affectedRows() ? $dbw->insertId() : null;
515                },
516                $didInsert,
517                $rev
518            );
519            $itemIdsIds[ $item->getId() ] = $itemIdsId;
520        }
521
522        // Insert or find discussiontools_items rows, fill in it_id field values.
523        // (This is not in a transaction. Orphaned rows in this table are harmlessly ignored,
524        // and long transactions caused performance issues on Wikimedia wikis: T315353#8218914.)
525        foreach ( $threadItemSet->getThreadItems() as $item ) {
526            $itemsId = $this->findOrInsertId(
527                static function ( IReadableDatabase $dbw ) use ( $item, $method ) {
528                    return $dbw->newSelectQueryBuilder()
529                        ->from( 'discussiontools_items' )
530                        ->field( 'it_id' )
531                        ->where( [ 'it_itemname' => $item->getName() ] )
532                        ->caller( $method )
533                        ->fetchField();
534                },
535                function ( IDatabase $dbw ) use ( $item, $method ) {
536                    $dbw->newInsertQueryBuilder()
537                        ->table( 'discussiontools_items' )
538                        ->row(
539                            [
540                                'it_itemname' => $item->getName(),
541                            ] +
542                            ( $item instanceof CommentItem ? [
543                                'it_timestamp' =>
544                                    $dbw->timestamp( $item->getTimestampString() ),
545                                'it_actor' =>
546                                    $this->actorStore->findActorIdByName( $item->getAuthor(), $dbw ),
547                            ] : [] )
548                        )
549                        ->ignore()
550                        ->caller( $method )
551                        ->execute();
552                    return $dbw->affectedRows() ? $dbw->insertId() : null;
553                },
554                $didInsert,
555                $rev
556            );
557            $itemsIds[ $item->getId() ] = $itemsId;
558        }
559
560        // Insert or update discussiontools_item_pages and discussiontools_item_revisions rows.
561        // This IS in a transaction. We don't really want rows for different items on the same
562        // page to point to different revisions.
563        $dbw->doAtomicSection( $method, /** @throws TimestampException */ function ( IDatabase $dbw ) use (
564            $method, $rev, $threadItemSet, $itemsIds, $itemIdsIds, &$didInsert
565        ) {
566            // Map of item IDs (strings) to their discussiontools_item_revisions.itr_id field values (ints)
567            $itemRevisionsIds = [];
568            '@phan-var array<string,int> $itemRevisionsIds';
569
570            $revUpdateRows = [];
571            // Insert or update discussiontools_item_pages rows.
572            foreach ( $threadItemSet->getThreadItems() as $item ) {
573                // Update (or insert) the references to oldest/newest item revision.
574                // The page revision we're processing is usually the newest one, but it doesn't have to be
575                // (in case of backfilling using the maintenance script, or in case of revisions being
576                // imported), so we need all these funky queries to see if we need to update oldest/newest.
577
578                $itemPagesRow = $dbw->newSelectQueryBuilder()
579                    ->from( 'discussiontools_item_pages' )
580                    ->join( 'revision', 'revision_oldest', [ 'itp_oldest_revision_id = revision_oldest.rev_id' ] )
581                    ->join( 'revision', 'revision_newest', [ 'itp_newest_revision_id = revision_newest.rev_id' ] )
582                    ->field( 'itp_id' )
583                    ->field( 'itp_oldest_revision_id' )
584                    ->field( 'itp_newest_revision_id' )
585                    ->field( 'revision_oldest.rev_timestamp', 'oldest_rev_timestamp' )
586                    ->field( 'revision_newest.rev_timestamp', 'newest_rev_timestamp' )
587                    ->where( [
588                        'itp_items_id' => $itemsIds[ $item->getId() ],
589                        'itp_page_id' => $rev->getPageId(),
590                    ] )
591                    ->caller( $method )
592                    ->fetchRow();
593                if ( $itemPagesRow === false ) {
594                    $dbw->newInsertQueryBuilder()
595                        ->table( 'discussiontools_item_pages' )
596                        ->row( [
597                            'itp_items_id' => $itemsIds[ $item->getId() ],
598                            'itp_page_id' => $rev->getPageId(),
599                            'itp_oldest_revision_id' => $rev->getId(),
600                            'itp_newest_revision_id' => $rev->getId(),
601                        ] )
602                        ->ignore()
603                        ->caller( $method )
604                        ->execute();
605                } else {
606                    $oldestTime = ( new MWTimestamp( $itemPagesRow->oldest_rev_timestamp ) )->getTimestamp( TS_MW );
607                    $newestTime = ( new MWTimestamp( $itemPagesRow->newest_rev_timestamp ) )->getTimestamp( TS_MW );
608                    $currentTime = $rev->getTimestamp();
609
610                    $oldestId = (int)$itemPagesRow->itp_oldest_revision_id;
611                    $newestId = (int)$itemPagesRow->itp_newest_revision_id;
612                    $currentId = $rev->getId();
613
614                    $updatePageField = null;
615                    if ( [ $oldestTime, $oldestId ] > [ $currentTime, $currentId ] ) {
616                        $updatePageField = 'itp_oldest_revision_id';
617                    } elseif ( [ $newestTime, $newestId ] < [ $currentTime, $currentId ] ) {
618                        $updatePageField = 'itp_newest_revision_id';
619                    }
620                    if ( $updatePageField ) {
621                        $dbw->newUpdateQueryBuilder()
622                            ->table( 'discussiontools_item_pages' )
623                            ->set( [ $updatePageField => $rev->getId() ] )
624                            ->where( [ 'itp_id' => $itemPagesRow->itp_id ] )
625                            ->caller( $method )
626                            ->execute();
627                        if ( $oldestId !== $newestId ) {
628                            // This causes most rows in discussiontools_item_revisions referring to the previously
629                            // oldest/newest revision to be unused, so try re-using them.
630                            $revUpdateRows[ $itemsIds[ $item->getId() ] ] = $itemPagesRow->$updatePageField;
631                        }
632                    }
633                }
634            }
635
636            // Insert or update discussiontools_item_revisions rows, fill in itr_id field values.
637            foreach ( $threadItemSet->getThreadItems() as $item ) {
638                $transcl = $item->getTranscludedFrom();
639                $newOrUpdateRevRow =
640                    [
641                        'itr_itemid_id' => $itemIdsIds[ $item->getId() ],
642                        'itr_revision_id' => $rev->getId(),
643                        'itr_items_id' => $itemsIds[ $item->getId() ],
644                        'itr_parent_id' =>
645                            // This assumes that parent items were processed first
646                            $item->getParent() ? $itemRevisionsIds[ $item->getParent()->getId() ] : null,
647                        'itr_transcludedfrom' =>
648                            $transcl === false ? null : (
649                                $transcl === true ? 0 :
650                                    $this->pageStore->getPageByText( $transcl )->getId()
651                            ),
652                        'itr_level' => $item->getLevel(),
653                    ] +
654                    ( $item instanceof HeadingItem ? [
655                        'itr_headinglevel' => $item->isPlaceholderHeading() ? null : $item->getHeadingLevel(),
656                    ] : [] );
657
658                $itemRevisionsConds = [
659                    'itr_itemid_id' => $itemIdsIds[ $item->getId() ],
660                    'itr_items_id' => $itemsIds[ $item->getId() ],
661                    'itr_revision_id' => $rev->getId(),
662                ];
663                $itemRevisionsId = $dbw->newSelectQueryBuilder()
664                    ->from( 'discussiontools_item_revisions' )
665                    ->field( 'itr_id' )
666                    ->where( $itemRevisionsConds )
667                    ->caller( $method )
668                    ->fetchField();
669                if ( $itemRevisionsId === false ) {
670                    $itemRevisionsUpdateId = null;
671                    if ( isset( $revUpdateRows[ $itemsIds[ $item->getId() ] ] ) ) {
672                        $itemRevisionsUpdateId = $dbw->newSelectQueryBuilder()
673                            ->from( 'discussiontools_item_revisions' )
674                            ->field( 'itr_id' )
675                            ->where( [
676                                'itr_revision_id' => $revUpdateRows[ $itemsIds[ $item->getId() ] ],
677                                // We only keep up to 2 discussiontools_item_revisions rows with the same
678                                // (itr_itemid_id, itr_items_id) pair, for the oldest and newest revision known.
679                                // Here we find any rows we don't want to keep and re-use them.
680                                'itr_itemid_id' => $itemIdsIds[ $item->getId() ],
681                                'itr_items_id' => $itemsIds[ $item->getId() ],
682                            ] )
683                            ->caller( $method )
684                            ->fetchField();
685                        // The row to re-use may not be found if it has a different itr_itemid_id than the row
686                        // we want to add.
687                    }
688                    if ( $itemRevisionsUpdateId ) {
689                        $dbw->newUpdateQueryBuilder()
690                            ->table( 'discussiontools_item_revisions' )
691                            ->set( $newOrUpdateRevRow )
692                            ->where( [ 'itr_id' => $itemRevisionsUpdateId ] )
693                            ->caller( $method )
694                            ->execute();
695                        $itemRevisionsId = $itemRevisionsUpdateId;
696                        $didInsert = true;
697                    } else {
698                        $itemRevisionsId = $this->findOrInsertId(
699                            static function ( IReadableDatabase $dbw ) use ( $itemRevisionsConds, $method ) {
700                                return $dbw->newSelectQueryBuilder()
701                                    ->from( 'discussiontools_item_revisions' )
702                                    ->field( 'itr_id' )
703                                    ->where( $itemRevisionsConds )
704                                    ->caller( $method )
705                                    ->fetchField();
706                            },
707                            static function ( IDatabase $dbw ) use ( $newOrUpdateRevRow, $method ) {
708                                $dbw->newInsertQueryBuilder()
709                                    ->table( 'discussiontools_item_revisions' )
710                                    ->row( $newOrUpdateRevRow )
711                                    // Fix rows with corrupted itr_items_id=0,
712                                    // which are causing conflicts (T339882, T343859#9185559)
713                                    ->onDuplicateKeyUpdate()
714                                    ->uniqueIndexFields( [ 'itr_itemid_id', 'itr_revision_id' ] )
715                                    // Omit redundant updates to avoid warnings (T353432)
716                                    ->set( array_diff_key(
717                                        $newOrUpdateRevRow,
718                                        [ 'itr_itemid_id' => true, 'itr_revision_id' => true ]
719                                    ) )
720                                    ->caller( $method )
721                                    ->execute();
722                                return $dbw->affectedRows() ? $dbw->insertId() : null;
723                            },
724                            $didInsert,
725                            $rev
726                        );
727                    }
728                }
729
730                $itemRevisionsIds[ $item->getId() ] = $itemRevisionsId;
731            }
732        }, $dbw::ATOMIC_CANCELABLE );
733
734        return $didInsert;
735    }
736}