LCOV - differential code coverage report
Current view: top level - src/backend/access/gin - gininsert.c (source / functions) Coverage Total Hit UNC UBC GNC CBC DCB
Current: 4b3c9325757dfd8f2312e9f1a8decf4431f344ae vs e87b024bfb8dd55e3049b1b6e6ab4e810cf1abc8 Lines: 91.1 % 676 616 1 59 4 612 4
Current Date: 2026-11-28 16:48:44 +0900 Functions: 97.1 % 35 34 1 5 29
Baseline: lcov-20261128-baseline Branches: 71.8 % 266 191 75 191
Baseline Date: 2026-11-28 16:48:48 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(1,7] days: 100.0 % 10 10 2 8
(30,360] days: 92.9 % 14 13 1 2 11
(360..) days: 91.0 % 652 593 59 593
Function coverage date bins:
(1,7] days: 100.0 % 2 2 1 1
(360..) days: 97.0 % 33 32 1 4 28
Branch coverage date bins:
(1,7] days: 100.0 % 2 2 2
(30,360] days: 100.0 % 2 2 2
(360..) days: 71.4 % 262 187 75 187

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  *
                                  3                 :                :  * gininsert.c
                                  4                 :                :  *    insert routines for the postgres inverted index access method.
                                  5                 :                :  *
                                  6                 :                :  *
                                  7                 :                :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
                                  8                 :                :  * Portions Copyright (c) 1994, Regents of the University of California
                                  9                 :                :  *
                                 10                 :                :  * IDENTIFICATION
                                 11                 :                :  *          src/backend/access/gin/gininsert.c
                                 12                 :                :  *-------------------------------------------------------------------------
                                 13                 :                :  */
                                 14                 :                : 
                                 15                 :                : #include "postgres.h"
                                 16                 :                : 
                                 17                 :                : #include "access/gin_private.h"
                                 18                 :                : #include "access/gin_tuple.h"
                                 19                 :                : #include "access/parallel.h"
                                 20                 :                : #include "access/table.h"
                                 21                 :                : #include "access/tableam.h"
                                 22                 :                : #include "access/xloginsert.h"
                                 23                 :                : #include "catalog/index.h"
                                 24                 :                : #include "catalog/pg_collation.h"
                                 25                 :                : #include "commands/progress.h"
                                 26                 :                : #include "executor/instrument.h"
                                 27                 :                : #include "miscadmin.h"
                                 28                 :                : #include "nodes/execnodes.h"
                                 29                 :                : #include "pgstat.h"
                                 30                 :                : #include "storage/bufmgr.h"
                                 31                 :                : #include "storage/condition_variable.h"
                                 32                 :                : #include "storage/proc.h"
                                 33                 :                : #include "storage/predicate.h"
                                 34                 :                : #include "tcop/tcopprot.h"
                                 35                 :                : #include "utils/datum.h"
                                 36                 :                : #include "utils/memutils.h"
                                 37                 :                : #include "utils/builtins.h"
                                 38                 :                : #include "utils/rel.h"
                                 39                 :                : #include "utils/tuplesort.h"
                                 40                 :                : #include "utils/typcache.h"
                                 41                 :                : #include "utils/wait_event.h"
                                 42                 :                : 
                                 43                 :                : 
                                 44                 :                : /* Magic numbers for parallel state sharing */
                                 45                 :                : #define PARALLEL_KEY_GIN_SHARED         UINT64CONST(0xB000000000000001)
                                 46                 :                : #define PARALLEL_KEY_TUPLESORT          UINT64CONST(0xB000000000000002)
                                 47                 :                : #define PARALLEL_KEY_QUERY_TEXT         UINT64CONST(0xB000000000000003)
                                 48                 :                : #define PARALLEL_KEY_WAL_USAGE          UINT64CONST(0xB000000000000004)
                                 49                 :                : #define PARALLEL_KEY_BUFFER_USAGE       UINT64CONST(0xB000000000000005)
                                 50                 :                : 
                                 51                 :                : /*
                                 52                 :                :  * Status for index builds performed in parallel.  This is allocated in a
                                 53                 :                :  * dynamic shared memory segment.
                                 54                 :                :  */
                                 55                 :                : typedef struct GinBuildShared
                                 56                 :                : {
                                 57                 :                :     /*
                                 58                 :                :      * These fields are not modified during the build.  They primarily exist
                                 59                 :                :      * for the benefit of worker processes that need to create state
                                 60                 :                :      * corresponding to that used by the leader.
                                 61                 :                :      */
                                 62                 :                :     Oid         heaprelid;
                                 63                 :                :     Oid         indexrelid;
                                 64                 :                :     bool        isconcurrent;
                                 65                 :                :     int         scantuplesortstates;
                                 66                 :                : 
                                 67                 :                :     /* Query ID, for report in worker processes */
                                 68                 :                :     int64       queryid;
                                 69                 :                : 
                                 70                 :                :     /*
                                 71                 :                :      * workersdonecv is used to monitor the progress of workers.  All parallel
                                 72                 :                :      * participants must indicate that they are done before leader can use
                                 73                 :                :      * results built by the workers (and before leader can write the data into
                                 74                 :                :      * the index).
                                 75                 :                :      */
                                 76                 :                :     ConditionVariable workersdonecv;
                                 77                 :                : 
                                 78                 :                :     /*
                                 79                 :                :      * mutex protects all following fields
                                 80                 :                :      *
                                 81                 :                :      * These fields contain status information of interest to GIN index builds
                                 82                 :                :      * that must work just the same when an index is built in parallel.
                                 83                 :                :      */
                                 84                 :                :     slock_t     mutex;
                                 85                 :                : 
                                 86                 :                :     /*
                                 87                 :                :      * Mutable state that is maintained by workers, and reported back to
                                 88                 :                :      * leader at end of the scans.
                                 89                 :                :      *
                                 90                 :                :      * nparticipantsdone is number of worker processes finished.
                                 91                 :                :      *
                                 92                 :                :      * reltuples is the total number of input heap tuples.
                                 93                 :                :      *
                                 94                 :                :      * indtuples is the total number of tuples that made it into the index.
                                 95                 :                :      *
                                 96                 :                :      * brokenhotchain indicates if any worker detected a broken HOT chain
                                 97                 :                :      * during build.
                                 98                 :                :      */
                                 99                 :                :     int         nparticipantsdone;
                                100                 :                :     double      reltuples;
                                101                 :                :     double      indtuples;
                                102                 :                :     bool        brokenhotchain;
                                103                 :                : 
                                104                 :                :     /*
                                105                 :                :      * ParallelTableScanDescData data follows. Can't directly embed here, as
                                106                 :                :      * implementations of the parallel table scan desc interface might need
                                107                 :                :      * stronger alignment.
                                108                 :                :      */
                                109                 :                : } GinBuildShared;
                                110                 :                : 
                                111                 :                : /*
                                112                 :                :  * Return pointer to a GinBuildShared's parallel table scan.
                                113                 :                :  *
                                114                 :                :  * c.f. shm_toc_allocate as to why BUFFERALIGN is used, rather than just
                                115                 :                :  * MAXALIGN.
                                116                 :                :  */
                                117                 :                : #define ParallelTableScanFromGinBuildShared(shared) \
                                118                 :                :     (ParallelTableScanDesc) ((char *) (shared) + BUFFERALIGN(sizeof(GinBuildShared)))
                                119                 :                : 
                                120                 :                : /*
                                121                 :                :  * Status for leader in parallel index build.
                                122                 :                :  */
                                123                 :                : typedef struct GinLeader
                                124                 :                : {
                                125                 :                :     /* parallel context itself */
                                126                 :                :     ParallelContext *pcxt;
                                127                 :                : 
                                128                 :                :     /*
                                129                 :                :      * nparticipanttuplesorts is the exact number of worker processes
                                130                 :                :      * successfully launched, plus one leader process if it participates as a
                                131                 :                :      * worker (only DISABLE_LEADER_PARTICIPATION builds avoid leader
                                132                 :                :      * participating as a worker).
                                133                 :                :      */
                                134                 :                :     int         nparticipanttuplesorts;
                                135                 :                : 
                                136                 :                :     /*
                                137                 :                :      * Leader process convenience pointers to shared state (leader avoids TOC
                                138                 :                :      * lookups).
                                139                 :                :      *
                                140                 :                :      * GinBuildShared is the shared state for entire build.  sharedsort is the
                                141                 :                :      * shared, tuplesort-managed state passed to each process tuplesort.
                                142                 :                :      * snapshot is the snapshot used by the scan iff an MVCC snapshot is
                                143                 :                :      * required.
                                144                 :                :      */
                                145                 :                :     GinBuildShared *ginshared;
                                146                 :                :     Sharedsort *sharedsort;
                                147                 :                :     Snapshot    snapshot;
                                148                 :                :     WalUsage   *walusage;
                                149                 :                :     BufferUsage *bufferusage;
                                150                 :                : } GinLeader;
                                151                 :                : 
                                152                 :                : typedef struct
                                153                 :                : {
                                154                 :                :     GinState    ginstate;
                                155                 :                :     double      indtuples;
                                156                 :                :     GinStatsData buildStats;
                                157                 :                :     MemoryContext tmpCtx;
                                158                 :                :     MemoryContext funcCtx;
                                159                 :                :     BuildAccumulator accum;
                                160                 :                :     ItemPointerData tid;
                                161                 :                :     int         work_mem;
                                162                 :                : 
                                163                 :                :     /*
                                164                 :                :      * bs_leader is only present when a parallel index build is performed, and
                                165                 :                :      * only in the leader process.
                                166                 :                :      */
                                167                 :                :     GinLeader  *bs_leader;
                                168                 :                : 
                                169                 :                :     /* number of participating workers (including leader) */
                                170                 :                :     int         bs_num_workers;
                                171                 :                : 
                                172                 :                :     /* used to pass information from workers to leader */
                                173                 :                :     double      bs_numtuples;
                                174                 :                :     double      bs_reltuples;
                                175                 :                : 
                                176                 :                :     /*
                                177                 :                :      * The sortstate is used by workers (including the leader). It has to be
                                178                 :                :      * part of the build state, because that's the only thing passed to the
                                179                 :                :      * build callback etc.
                                180                 :                :      */
                                181                 :                :     Tuplesortstate *bs_sortstate;
                                182                 :                : 
                                183                 :                :     /*
                                184                 :                :      * The sortstate used only within a single worker for the first merge pass
                                185                 :                :      * happening there. In principle it doesn't need to be part of the build
                                186                 :                :      * state and we could pass it around directly, but it's more convenient
                                187                 :                :      * this way. And it's part of the build state, after all.
                                188                 :                :      */
                                189                 :                :     Tuplesortstate *bs_worker_sort;
                                190                 :                : } GinBuildState;
                                191                 :                : 
                                192                 :                : 
                                193                 :                : /* parallel index builds */
                                194                 :                : static void _gin_begin_parallel(GinBuildState *buildstate, Relation heap, Relation index,
                                195                 :                :                                 bool isconcurrent, int request);
                                196                 :                : static void _gin_end_parallel(GinLeader *ginleader, GinBuildState *state);
                                197                 :                : static Size _gin_parallel_estimate_shared(Relation heap, Snapshot snapshot);
                                198                 :                : static double _gin_parallel_heapscan(GinBuildState *state,
                                199                 :                :                                      bool *brokenhotchain);
                                200                 :                : static double _gin_parallel_merge(GinBuildState *state,
                                201                 :                :                                   IndexInfo *indexInfo);
                                202                 :                : static void _gin_leader_participate_as_worker(GinBuildState *buildstate,
                                203                 :                :                                               Relation heap, Relation index);
                                204                 :                : static void _gin_parallel_scan_and_build(GinBuildState *state,
                                205                 :                :                                          GinBuildShared *ginshared,
                                206                 :                :                                          Sharedsort *sharedsort,
                                207                 :                :                                          Relation heap, Relation index,
                                208                 :                :                                          int sortmem, bool progress);
                                209                 :                : 
                                210                 :                : static ItemPointer _gin_parse_tuple_items(GinTuple *a);
                                211                 :                : static Datum _gin_parse_tuple_key(GinTuple *a);
                                212                 :                : 
                                213                 :                : static GinTuple *_gin_build_tuple(OffsetNumber attrnum, unsigned char category,
                                214                 :                :                                   Datum key, int16 typlen, bool typbyval,
                                215                 :                :                                   ItemPointerData *items, uint32 nitems,
                                216                 :                :                                   Size *len);
                                217                 :                : 
                                218                 :                : /*
                                219                 :                :  * Adds array of item pointers to tuple's posting list, or
                                220                 :                :  * creates posting tree and tuple pointing to tree in case
                                221                 :                :  * of not enough space.  Max size of tuple is defined in
                                222                 :                :  * GinFormTuple().  Returns a new, modified index tuple.
                                223                 :                :  * items[] must be in sorted order with no duplicates.
                                224                 :                :  */
                                225                 :                : static IndexTuple
 5804 tgl@sss.pgh.pa.us         226                 :CBC      118121 : addItemPointersToLeafTuple(GinState *ginstate,
                                227                 :                :                            IndexTuple old,
                                228                 :                :                            ItemPointerData *items, uint32 nitem,
                                229                 :                :                            GinStatsData *buildStats, Buffer buffer)
                                230                 :                : {
                                231                 :                :     OffsetNumber attnum;
                                232                 :                :     Datum       key;
                                233                 :                :     GinNullCategory category;
                                234                 :                :     IndexTuple  res;
                                235                 :                :     ItemPointerData *newItems,
                                236                 :                :                *oldItems;
                                237                 :                :     int         oldNPosting,
                                238                 :                :                 newNPosting,
                                239                 :                :                 nwritten;
                                240                 :                :     GinPostingList *compressedList;
                                241                 :                : 
                                242         [ -  + ]:         118121 :     Assert(!GinIsPostingTree(old));
                                243                 :                : 
                                244                 :         118121 :     attnum = gintuple_get_attrnum(ginstate, old);
                                245                 :         118121 :     key = gintuple_get_key(ginstate, old, &category);
                                246                 :                : 
                                247                 :                :     /* merge the old and new posting lists */
 4693 heikki.linnakangas@i      248                 :         118121 :     oldItems = ginReadTuple(ginstate, attnum, old, &oldNPosting);
                                249                 :                : 
 4632                           250                 :         118121 :     newItems = ginMergeItemPointers(items, nitem,
                                251                 :                :                                     oldItems, oldNPosting,
                                252                 :                :                                     &newNPosting);
                                253                 :                : 
                                254                 :                :     /* Compress the posting list, and try to a build tuple with room for it */
 4693                           255                 :         118121 :     res = NULL;
  418 msawada@postgresql.o      256                 :         118121 :     compressedList = ginCompressPostingList(newItems, newNPosting, GinMaxItemSize, &nwritten);
                                257         [ +  + ]:         118121 :     if (nwritten == newNPosting)
                                258                 :                :     {
 4693 heikki.linnakangas@i      259                 :         118112 :         res = GinFormTuple(ginstate, attnum, key, category,
                                260                 :                :                            (char *) compressedList,
                                261                 :         118112 :                            SizeOfGinPostingList(compressedList),
                                262                 :                :                            newNPosting,
                                263                 :                :                            false);
                                264                 :                :     }
                                265                 :                : 
  418 msawada@postgresql.o      266                 :         118121 :     pfree(newItems);
                                267                 :         118121 :     pfree(compressedList);
                                268                 :                : 
 4693 heikki.linnakangas@i      269         [ +  + ]:         118121 :     if (!res)
                                270                 :                :     {
                                271                 :                :         /* posting list would be too big, convert to posting tree */
                                272                 :                :         BlockNumber postingRoot;
                                273                 :                : 
                                274                 :                :         /*
                                275                 :                :          * Initialize posting tree with the old tuple's posting list.  It's
                                276                 :                :          * surely small enough to fit on one posting-tree page, and should
                                277                 :                :          * already be in order with no duplicates.
                                278                 :                :          */
 5804 tgl@sss.pgh.pa.us         279                 :             15 :         postingRoot = createPostingTree(ginstate->index,
                                280                 :                :                                         oldItems,
                                281                 :                :                                         oldNPosting,
                                282                 :                :                                         buildStats,
                                283                 :                :                                         buffer);
                                284                 :                : 
                                285                 :                :         /* Now insert the TIDs-to-be-added into the posting tree */
 4756 heikki.linnakangas@i      286                 :             15 :         ginInsertItemPointers(ginstate->index, postingRoot,
                                287                 :                :                               items, nitem,
                                288                 :                :                               buildStats);
                                289                 :                : 
                                290                 :                :         /* And build a new posting-tree-only result tuple */
 4693                           291                 :             15 :         res = GinFormTuple(ginstate, attnum, key, category, NULL, 0, 0, true);
 5804 tgl@sss.pgh.pa.us         292                 :             15 :         GinSetPostingTree(res, postingRoot);
                                293                 :                :     }
 4693 heikki.linnakangas@i      294                 :         118121 :     pfree(oldItems);
                                295                 :                : 
 5804 tgl@sss.pgh.pa.us         296                 :         118121 :     return res;
                                297                 :                : }
                                298                 :                : 
                                299                 :                : /*
                                300                 :                :  * Build a fresh leaf tuple, either posting-list or posting-tree format
                                301                 :                :  * depending on whether the given items list will fit.
                                302                 :                :  * items[] must be in sorted order with no duplicates.
                                303                 :                :  *
                                304                 :                :  * This is basically the same logic as in addItemPointersToLeafTuple,
                                305                 :                :  * but working from slightly different input.
                                306                 :                :  */
                                307                 :                : static IndexTuple
                                308                 :         421318 : buildFreshLeafTuple(GinState *ginstate,
                                309                 :                :                     OffsetNumber attnum, Datum key, GinNullCategory category,
                                310                 :                :                     ItemPointerData *items, uint32 nitem,
                                311                 :                :                     GinStatsData *buildStats, Buffer buffer)
                                312                 :                : {
 4693 heikki.linnakangas@i      313                 :         421318 :     IndexTuple  res = NULL;
                                314                 :                :     GinPostingList *compressedList;
                                315                 :                :     int         nwritten;
                                316                 :                : 
                                317                 :                :     /* try to build a posting list tuple with all the items */
  418 msawada@postgresql.o      318                 :         421318 :     compressedList = ginCompressPostingList(items, nitem, GinMaxItemSize, &nwritten);
                                319         [ +  + ]:         421318 :     if (nwritten == nitem)
                                320                 :                :     {
 4693 heikki.linnakangas@i      321                 :         421261 :         res = GinFormTuple(ginstate, attnum, key, category,
                                322                 :                :                            (char *) compressedList,
                                323                 :         421261 :                            SizeOfGinPostingList(compressedList),
                                324                 :                :                            nitem, false);
                                325                 :                :     }
  418 msawada@postgresql.o      326                 :         421318 :     pfree(compressedList);
                                327                 :                : 
 5804 tgl@sss.pgh.pa.us         328         [ +  + ]:         421318 :     if (!res)
                                329                 :                :     {
                                330                 :                :         /* posting list would be too big, build posting tree */
                                331                 :                :         BlockNumber postingRoot;
                                332                 :                : 
                                333                 :                :         /*
                                334                 :                :          * Build posting-tree-only result tuple.  We do this first so as to
                                335                 :                :          * fail quickly if the key is too big.
                                336                 :                :          */
 4693 heikki.linnakangas@i      337                 :             57 :         res = GinFormTuple(ginstate, attnum, key, category, NULL, 0, 0, true);
                                338                 :                : 
                                339                 :                :         /*
                                340                 :                :          * Initialize a new posting tree with the TIDs.
                                341                 :                :          */
 4770                           342                 :             57 :         postingRoot = createPostingTree(ginstate->index, items, nitem,
                                343                 :                :                                         buildStats, buffer);
                                344                 :                : 
                                345                 :                :         /* And save the root link in the result tuple */
 5804 tgl@sss.pgh.pa.us         346                 :             57 :         GinSetPostingTree(res, postingRoot);
                                347                 :                :     }
                                348                 :                : 
 7515 teodor@sigaev.ru          349                 :         421318 :     return res;
                                350                 :                : }
                                351                 :                : 
                                352                 :                : /*
                                353                 :                :  * Insert one or more heap TIDs associated with the given key value.
                                354                 :                :  * This will either add a single key entry, or enlarge a pre-existing entry.
                                355                 :                :  *
                                356                 :                :  * During an index build, buildStats is non-null and the counters
                                357                 :                :  * it contains should be incremented as needed.
                                358                 :                :  */
                                359                 :                : void
 5804 tgl@sss.pgh.pa.us         360                 :         577527 : ginEntryInsert(GinState *ginstate,
                                361                 :                :                OffsetNumber attnum, Datum key, GinNullCategory category,
                                362                 :                :                ItemPointerData *items, uint32 nitem,
                                363                 :                :                GinStatsData *buildStats)
                                364                 :                : {
                                365                 :                :     GinBtreeData btree;
                                366                 :                :     GinBtreeEntryInsertData insertdata;
                                367                 :                :     GinBtreeStack *stack;
                                368                 :                :     IndexTuple  itup;
                                369                 :                :     Page        page;
                                370                 :                : 
 3391 peter_e@gmx.net           371                 :         577527 :     insertdata.isDelete = false;
                                372                 :                : 
 5804 tgl@sss.pgh.pa.us         373                 :         577527 :     ginPrepareEntryScan(&btree, attnum, key, category, ginstate);
 2796 heikki.linnakangas@i      374                 :         577527 :     btree.isBuild = (buildStats != NULL);
                                375                 :                : 
 1177 tmunro@postgresql.or      376                 :         577527 :     stack = ginFindLeafPage(&btree, false, false);
 3874 kgrittn@postgresql.o      377                 :         577527 :     page = BufferGetPage(stack->buffer);
                                378                 :                : 
 7360 bruce@momjian.us          379         [ +  + ]:         577527 :     if (btree.findItem(&btree, stack))
                                380                 :                :     {
                                381                 :                :         /* found pre-existing entry */
 7515 teodor@sigaev.ru          382                 :         156207 :         itup = (IndexTuple) PageGetItem(page, PageGetItemId(page, stack->off));
                                383                 :                : 
 7360 bruce@momjian.us          384         [ +  + ]:         156207 :         if (GinIsPostingTree(itup))
                                385                 :                :         {
                                386                 :                :             /* add entries to existing posting tree */
                                387                 :          38082 :             BlockNumber rootPostingTree = GinGetPostingTree(itup);
                                388                 :                : 
                                389                 :                :             /* release all stack */
 7515 teodor@sigaev.ru          390                 :          38082 :             LockBuffer(stack->buffer, GIN_UNLOCK);
 7360 bruce@momjian.us          391                 :          38082 :             freeGinBtreeStack(stack);
                                392                 :                : 
                                393                 :                :             /* insert into posting tree */
 4756 heikki.linnakangas@i      394                 :          38082 :             ginInsertItemPointers(ginstate->index, rootPostingTree,
                                395                 :                :                                   items, nitem,
                                396                 :                :                                   buildStats);
 7515 teodor@sigaev.ru          397                 :          38079 :             return;
                                398                 :                :         }
                                399                 :                : 
 2496 tmunro@postgresql.or      400                 :         118125 :         CheckForSerializableConflictIn(ginstate->index, NULL,
                                401                 :                :                                        BufferGetBlockNumber(stack->buffer));
                                402                 :                :         /* modify an existing leaf entry */
 5804 tgl@sss.pgh.pa.us         403                 :         118121 :         itup = addItemPointersToLeafTuple(ginstate, itup,
                                404                 :                :                                           items, nitem, buildStats, stack->buffer);
                                405                 :                : 
 3391 peter_e@gmx.net           406                 :         118121 :         insertdata.isDelete = true;
                                407                 :                :     }
                                408                 :                :     else
                                409                 :                :     {
 2496 tmunro@postgresql.or      410                 :         421320 :         CheckForSerializableConflictIn(ginstate->index, NULL,
                                411                 :                :                                        BufferGetBlockNumber(stack->buffer));
                                412                 :                :         /* no match, so construct a new leaf entry */
 5804 tgl@sss.pgh.pa.us         413                 :         421318 :         itup = buildFreshLeafTuple(ginstate, attnum, key, category,
                                414                 :                :                                    items, nitem, buildStats, stack->buffer);
                                415                 :                : 
                                416                 :                :         /*
                                417                 :                :          * nEntries counts leaf tuples, so increment it only when we make a
                                418                 :                :          * new one.
                                419                 :                :          */
 2581                           420         [ +  + ]:         421318 :         if (buildStats)
                                421                 :          90866 :             buildStats->nEntries++;
                                422                 :                :     }
                                423                 :                : 
                                424                 :                :     /* Insert the new or modified leaf tuple */
 4749 heikki.linnakangas@i      425                 :         539439 :     insertdata.entry = itup;
                                426                 :         539439 :     ginInsertValue(&btree, stack, &insertdata, buildStats);
 7360 bruce@momjian.us          427                 :         539437 :     pfree(itup);
                                428                 :                : }
                                429                 :                : 
                                430                 :                : /*
                                431                 :                :  * Extract index entries for a single indexable item, and add them to the
                                432                 :                :  * BuildAccumulator's state.
                                433                 :                :  *
                                434                 :                :  * This function is used only during initial index creation.
                                435                 :                :  */
                                436                 :                : static void
 5804 tgl@sss.pgh.pa.us         437                 :         541248 : ginHeapTupleBulkInsert(GinBuildState *buildstate, OffsetNumber attnum,
                                438                 :                :                        Datum value, bool isNull,
                                439                 :                :                        ItemPointer heapptr)
                                440                 :                : {
                                441                 :                :     Datum      *entries;
                                442                 :                :     GinNullCategory *categories;
                                443                 :                :     int32       nentries;
                                444                 :                :     MemoryContext oldCtx;
                                445                 :                : 
 7445 teodor@sigaev.ru          446                 :         541248 :     oldCtx = MemoryContextSwitchTo(buildstate->funcCtx);
 5804 tgl@sss.pgh.pa.us         447                 :         541248 :     entries = ginExtractEntries(buildstate->accum.ginstate, attnum,
                                448                 :                :                                 value, isNull,
                                449                 :                :                                 &nentries, &categories);
 7445 teodor@sigaev.ru          450                 :         541248 :     MemoryContextSwitchTo(oldCtx);
                                451                 :                : 
 5804 tgl@sss.pgh.pa.us         452                 :         541248 :     ginInsertBAEntries(&buildstate->accum, heapptr, attnum,
                                453                 :                :                        entries, categories, nentries);
                                454                 :                : 
                                455                 :         541248 :     buildstate->indtuples += nentries;
                                456                 :                : 
 7445 teodor@sigaev.ru          457                 :         541248 :     MemoryContextReset(buildstate->funcCtx);
 7515                           458                 :         541248 : }
                                459                 :                : 
                                460                 :                : static void
 2577 andres@anarazel.de        461                 :         525658 : ginBuildCallback(Relation index, ItemPointer tid, Datum *values,
                                462                 :                :                  bool *isnull, bool tupleIsAlive, void *state)
                                463                 :                : {
 7360 bruce@momjian.us          464                 :         525658 :     GinBuildState *buildstate = (GinBuildState *) state;
                                465                 :                :     MemoryContext oldCtx;
                                466                 :                :     int         i;
                                467                 :                : 
 7515 teodor@sigaev.ru          468                 :         525658 :     oldCtx = MemoryContextSwitchTo(buildstate->tmpCtx);
                                469                 :                : 
 6379 bruce@momjian.us          470         [ +  + ]:        1051730 :     for (i = 0; i < buildstate->ginstate.origTupdesc->natts; i++)
 5804 tgl@sss.pgh.pa.us         471                 :         526072 :         ginHeapTupleBulkInsert(buildstate, (OffsetNumber) (i + 1),
 2577 andres@anarazel.de        472                 :         526072 :                                values[i], isnull[i], tid);
                                473                 :                : 
                                474                 :                :     /* If we've maxed out our available memory, dump everything to the index */
  666 tgl@sss.pgh.pa.us         475         [ -  + ]:         525658 :     if (buildstate->accum.allocatedMemory >= maintenance_work_mem * (Size) 1024)
                                476                 :                :     {
                                477                 :                :         ItemPointerData *list;
                                478                 :                :         Datum       key;
                                479                 :                :         GinNullCategory category;
                                480                 :                :         uint32      nlist;
                                481                 :                :         OffsetNumber attnum;
                                482                 :                : 
 5963 tgl@sss.pgh.pa.us         483                 :UBC           0 :         ginBeginBAScan(&buildstate->accum);
 5804                           484                 :              0 :         while ((list = ginGetBAEntry(&buildstate->accum,
 3447                           485         [ #  # ]:              0 :                                      &attnum, &key, &category, &nlist)) != NULL)
                                486                 :                :         {
                                487                 :                :             /* there could be many entries, so be willing to abort here */
 6770                           488         [ #  # ]:              0 :             CHECK_FOR_INTERRUPTS();
 5804                           489                 :              0 :             ginEntryInsert(&buildstate->ginstate, attnum, key, category,
                                490                 :                :                            list, nlist, &buildstate->buildStats);
                                491                 :                :         }
                                492                 :                : 
 7515 teodor@sigaev.ru          493                 :              0 :         MemoryContextReset(buildstate->tmpCtx);
                                494                 :              0 :         ginInitBA(&buildstate->accum);
                                495                 :                :     }
                                496                 :                : 
 7515 teodor@sigaev.ru          497                 :CBC      525658 :     MemoryContextSwitchTo(oldCtx);
                                498                 :         525658 : }
                                499                 :                : 
                                500                 :                : /*
                                501                 :                :  * ginFlushBuildState
                                502                 :                :  *      Write all data from BuildAccumulator into the tuplesort.
                                503                 :                :  *
                                504                 :                :  * The number of TIDs written to the tuplesort at once is limited, to reduce
                                505                 :                :  * the amount of memory needed when merging the intermediate results later.
                                506                 :                :  * The leader will see up to two chunks per worker, so calculate the limit to
                                507                 :                :  * not need more than MaxAllocSize overall.
                                508                 :                :  *
                                509                 :                :  * We don't need to worry about overflowing maintenance_work_mem. We can't
                                510                 :                :  * build chunks larger than work_mem, and that limit was set so that workers
                                511                 :                :  * produce sufficiently small chunks.
                                512                 :                :  */
                                513                 :                : static void
  635 tomas.vondra@postgre      514                 :             53 : ginFlushBuildState(GinBuildState *buildstate, Relation index)
                                515                 :                : {
                                516                 :                :     ItemPointerData *list;
                                517                 :                :     Datum       key;
                                518                 :                :     GinNullCategory category;
                                519                 :                :     uint32      nlist;
                                520                 :                :     OffsetNumber attnum;
                                521                 :             53 :     TupleDesc   tdesc = RelationGetDescr(index);
                                522                 :                :     uint32      maxlen;
                                523                 :                : 
                                524                 :                :     /* maximum number of TIDs per chunk (two chunks per worker) */
  389                           525                 :             53 :     maxlen = MaxAllocSize / sizeof(ItemPointerData);
                                526                 :             53 :     maxlen /= (2 * buildstate->bs_num_workers);
                                527                 :                : 
  635                           528                 :             53 :     ginBeginBAScan(&buildstate->accum);
                                529                 :          24636 :     while ((list = ginGetBAEntry(&buildstate->accum,
                                530         [ +  + ]:          24636 :                                  &attnum, &key, &category, &nlist)) != NULL)
                                531                 :                :     {
                                532                 :                :         /* information about the key */
  402 drowley@postgresql.o      533                 :          24583 :         CompactAttribute *attr = TupleDescCompactAttr(tdesc, (attnum - 1));
                                534                 :                : 
                                535                 :                :         /* start of the chunk */
  389 tomas.vondra@postgre      536                 :          24583 :         uint32      offset = 0;
                                537                 :                : 
                                538                 :                :         /* split the entry into smaller chunk with up to maxlen items */
                                539         [ +  + ]:          49166 :         while (offset < nlist)
                                540                 :                :         {
                                541                 :                :             /* GIN tuple and tuple length */
                                542                 :                :             GinTuple   *tup;
                                543                 :                :             Size        tuplen;
                                544                 :          24583 :             uint32      len = Min(maxlen, nlist - offset);
                                545                 :                : 
                                546                 :                :             /* there could be many entries, so be willing to abort here */
                                547         [ +  + ]:          24583 :             CHECK_FOR_INTERRUPTS();
                                548                 :                : 
                                549                 :          24583 :             tup = _gin_build_tuple(attnum, category,
                                550                 :          24583 :                                    key, attr->attlen, attr->attbyval,
                                551                 :          24583 :                                    &list[offset], len,
                                552                 :                :                                    &tuplen);
                                553                 :                : 
                                554                 :          24583 :             offset += len;
                                555                 :                : 
                                556                 :          24583 :             tuplesort_putgintuple(buildstate->bs_worker_sort, tup, tuplen);
                                557                 :                : 
                                558                 :          24583 :             pfree(tup);
                                559                 :                :         }
                                560                 :                :     }
                                561                 :                : 
  635                           562                 :             53 :     MemoryContextReset(buildstate->tmpCtx);
                                563                 :             53 :     ginInitBA(&buildstate->accum);
                                564                 :             53 : }
                                565                 :                : 
                                566                 :                : /*
                                567                 :                :  * ginBuildCallbackParallel
                                568                 :                :  *      Callback for the parallel index build.
                                569                 :                :  *
                                570                 :                :  * This is similar to the serial build callback ginBuildCallback, but
                                571                 :                :  * instead of writing the accumulated entries into the index, each worker
                                572                 :                :  * writes them into a (local) tuplesort.
                                573                 :                :  *
                                574                 :                :  * The worker then sorts and combines these entries, before writing them
                                575                 :                :  * into a shared tuplesort for the leader (see _gin_parallel_scan_and_build
                                576                 :                :  * for the whole process).
                                577                 :                :  */
                                578                 :                : static void
                                579                 :          15176 : ginBuildCallbackParallel(Relation index, ItemPointer tid, Datum *values,
                                580                 :                :                          bool *isnull, bool tupleIsAlive, void *state)
                                581                 :                : {
                                582                 :          15176 :     GinBuildState *buildstate = (GinBuildState *) state;
                                583                 :                :     MemoryContext oldCtx;
                                584                 :                :     int         i;
                                585                 :                : 
                                586                 :          15176 :     oldCtx = MemoryContextSwitchTo(buildstate->tmpCtx);
                                587                 :                : 
                                588                 :                :     /*
                                589                 :                :      * if scan wrapped around - flush accumulated entries and start anew
                                590                 :                :      *
                                591                 :                :      * With parallel scans, we don't have a guarantee the scan does not start
                                592                 :                :      * half-way through the relation (serial builds disable sync scans and
                                593                 :                :      * always start from block 0, parallel scans require allow_sync=true).
                                594                 :                :      *
                                595                 :                :      * Building the posting lists assumes the TIDs are monotonic and never go
                                596                 :                :      * back, and the wrap around would break that. We handle that by detecting
                                597                 :                :      * the wraparound, and flushing all entries. This means we'll later see
                                598                 :                :      * two separate entries with non-overlapping TID lists (which can be
                                599                 :                :      * combined by merge sort).
                                600                 :                :      *
                                601                 :                :      * To detect a wraparound, we remember the last TID seen by each worker
                                602                 :                :      * (for any key). If the next TID seen by the worker is lower, the scan
                                603                 :                :      * must have wrapped around.
                                604                 :                :      */
                                605         [ -  + ]:          15176 :     if (ItemPointerCompare(tid, &buildstate->tid) < 0)
  635 tomas.vondra@postgre      606                 :UBC           0 :         ginFlushBuildState(buildstate, index);
                                607                 :                : 
                                608                 :                :     /* remember the TID we're about to process */
  635 tomas.vondra@postgre      609                 :CBC       15176 :     buildstate->tid = *tid;
                                610                 :                : 
                                611         [ +  + ]:          30352 :     for (i = 0; i < buildstate->ginstate.origTupdesc->natts; i++)
                                612                 :          15176 :         ginHeapTupleBulkInsert(buildstate, (OffsetNumber) (i + 1),
                                613                 :          15176 :                                values[i], isnull[i], tid);
                                614                 :                : 
                                615                 :                :     /*
                                616                 :                :      * If we've maxed out our available memory, dump everything to the
                                617                 :                :      * tuplesort. We use half the per-worker fraction of maintenance_work_mem,
                                618                 :                :      * the other half is used for the tuplesort.
                                619                 :                :      */
                                620         [ -  + ]:          15176 :     if (buildstate->accum.allocatedMemory >= buildstate->work_mem * (Size) 1024)
  635 tomas.vondra@postgre      621                 :UBC           0 :         ginFlushBuildState(buildstate, index);
                                622                 :                : 
  635 tomas.vondra@postgre      623                 :CBC       15176 :     MemoryContextSwitchTo(oldCtx);
                                624                 :          15176 : }
                                625                 :                : 
                                626                 :                : IndexBuildResult *
 3968 tgl@sss.pgh.pa.us         627                 :            222 : ginbuild(Relation heap, Relation index, IndexInfo *indexInfo)
                                628                 :                : {
                                629                 :                :     IndexBuildResult *result;
                                630                 :                :     double      reltuples;
                                631                 :                :     GinBuildState buildstate;
  635 tomas.vondra@postgre      632                 :            222 :     GinBuildState *state = &buildstate;
                                633                 :                :     Buffer      RootBuffer,
                                634                 :                :                 MetaBuffer;
                                635                 :                :     ItemPointerData *list;
                                636                 :                :     Datum       key;
                                637                 :                :     GinNullCategory category;
                                638                 :                :     uint32      nlist;
                                639                 :                :     MemoryContext oldCtx;
                                640                 :                :     OffsetNumber attnum;
                                641                 :                : 
 7515 teodor@sigaev.ru          642         [ -  + ]:            222 :     if (RelationGetNumberOfBlocks(index) != 0)
 7515 teodor@sigaev.ru          643         [ #  # ]:UBC           0 :         elog(ERROR, "index \"%s\" already contains data",
                                644                 :                :              RelationGetRelationName(index));
                                645                 :                : 
 7515 teodor@sigaev.ru          646                 :CBC         222 :     initGinState(&buildstate.ginstate, index);
 5886 tgl@sss.pgh.pa.us         647                 :            222 :     buildstate.indtuples = 0;
                                648                 :            222 :     memset(&buildstate.buildStats, 0, sizeof(GinStatsData));
                                649                 :                : 
                                650                 :                :     /* Initialize fields for parallel build too. */
  635 tomas.vondra@postgre      651                 :            222 :     buildstate.bs_numtuples = 0;
                                652                 :            222 :     buildstate.bs_reltuples = 0;
                                653                 :            222 :     buildstate.bs_leader = NULL;
                                654                 :            222 :     memset(&buildstate.tid, 0, sizeof(ItemPointerData));
                                655                 :                : 
                                656                 :                :     /* initialize the meta page */
 6458 tgl@sss.pgh.pa.us         657                 :            222 :     MetaBuffer = GinNewBuffer(index);
                                658                 :                : 
                                659                 :                :     /* initialize the root page */
                                660                 :            222 :     RootBuffer = GinNewBuffer(index);
                                661                 :                : 
 7515 teodor@sigaev.ru          662                 :            222 :     START_CRIT_SECTION();
 6458 tgl@sss.pgh.pa.us         663                 :            222 :     GinInitMetabuffer(MetaBuffer);
                                664                 :            222 :     MarkBufferDirty(MetaBuffer);
                                665                 :            222 :     GinInitBuffer(RootBuffer, GIN_LEAF);
                                666                 :            222 :     MarkBufferDirty(RootBuffer);
                                667                 :                : 
                                668                 :                : 
                                669                 :            222 :     UnlockReleaseBuffer(MetaBuffer);
                                670                 :            222 :     UnlockReleaseBuffer(RootBuffer);
 7515 teodor@sigaev.ru          671         [ -  + ]:            222 :     END_CRIT_SECTION();
                                672                 :                : 
                                673                 :                :     /* count the root as first entry page */
 5886 tgl@sss.pgh.pa.us         674                 :            222 :     buildstate.buildStats.nEntryPages++;
                                675                 :                : 
                                676                 :                :     /*
                                677                 :                :      * create a temporary memory context that is used to hold data not yet
                                678                 :                :      * dumped out to the index
                                679                 :                :      */
 7515 teodor@sigaev.ru          680                 :            222 :     buildstate.tmpCtx = AllocSetContextCreate(CurrentMemoryContext,
                                681                 :                :                                               "Gin build temporary context",
                                682                 :                :                                               ALLOCSET_DEFAULT_SIZES);
                                683                 :                : 
                                684                 :                :     /*
                                685                 :                :      * create a temporary memory context that is used for calling
                                686                 :                :      * ginExtractEntries(), and can be reset after each tuple
                                687                 :                :      */
 4262 tgl@sss.pgh.pa.us         688                 :            222 :     buildstate.funcCtx = AllocSetContextCreate(CurrentMemoryContext,
                                689                 :                :                                                "Gin build temporary context for user-defined function",
                                690                 :                :                                                ALLOCSET_DEFAULT_SIZES);
                                691                 :                : 
 7515 teodor@sigaev.ru          692                 :            222 :     buildstate.accum.ginstate = &buildstate.ginstate;
 7360 bruce@momjian.us          693                 :            222 :     ginInitBA(&buildstate.accum);
                                694                 :                : 
                                695                 :                :     /* Report table scan phase started */
  635 tomas.vondra@postgre      696                 :            222 :     pgstat_progress_update_param(PROGRESS_CREATEIDX_SUBPHASE,
                                697                 :                :                                  PROGRESS_GIN_PHASE_INDEXBUILD_TABLESCAN);
                                698                 :                : 
                                699                 :                :     /*
                                700                 :                :      * Attempt to launch parallel worker scan when required
                                701                 :                :      *
                                702                 :                :      * XXX plan_create_index_workers makes the number of workers dependent on
                                703                 :                :      * maintenance_work_mem, requiring 32MB for each worker. For GIN that's
                                704                 :                :      * reasonable too, because we sort the data just like btree. It does
                                705                 :                :      * ignore the memory used to accumulate data in memory (set by work_mem),
                                706                 :                :      * but there is no way to communicate that to plan_create_index_workers.
                                707                 :                :      */
                                708         [ +  + ]:            222 :     if (indexInfo->ii_ParallelWorkers > 0)
                                709                 :             18 :         _gin_begin_parallel(state, heap, index, indexInfo->ii_Concurrent,
                                710                 :                :                             indexInfo->ii_ParallelWorkers);
                                711                 :                : 
                                712                 :                :     /*
                                713                 :                :      * If parallel build requested and at least one worker process was
                                714                 :                :      * successfully launched, set up coordination state, wait for workers to
                                715                 :                :      * complete. Then read all tuples from the shared tuplesort and insert
                                716                 :                :      * them into the index.
                                717                 :                :      *
                                718                 :                :      * In serial mode, simply scan the table and build the index one index
                                719                 :                :      * tuple at a time.
                                720                 :                :      */
                                721         [ +  + ]:            222 :     if (state->bs_leader)
                                722                 :                :     {
                                723                 :                :         SortCoordinate coordinate;
                                724                 :                : 
  353 michael@paquier.xyz       725                 :             18 :         coordinate = palloc0_object(SortCoordinateData);
  635 tomas.vondra@postgre      726                 :             18 :         coordinate->isWorker = false;
                                727                 :             18 :         coordinate->nParticipants =
                                728                 :             18 :             state->bs_leader->nparticipanttuplesorts;
                                729                 :             18 :         coordinate->sharedsort = state->bs_leader->sharedsort;
                                730                 :                : 
                                731                 :                :         /*
                                732                 :                :          * Begin leader tuplesort.
                                733                 :                :          *
                                734                 :                :          * In cases where parallelism is involved, the leader receives the
                                735                 :                :          * same share of maintenance_work_mem as a serial sort (it is
                                736                 :                :          * generally treated in the same way as a serial sort once we return).
                                737                 :                :          * Parallel worker Tuplesortstates will have received only a fraction
                                738                 :                :          * of maintenance_work_mem, though.
                                739                 :                :          *
                                740                 :                :          * We rely on the lifetime of the Leader Tuplesortstate almost not
                                741                 :                :          * overlapping with any worker Tuplesortstate's lifetime.  There may
                                742                 :                :          * be some small overlap, but that's okay because we rely on leader
                                743                 :                :          * Tuplesortstate only allocating a small, fixed amount of memory
                                744                 :                :          * here. When its tuplesort_performsort() is called (by our caller),
                                745                 :                :          * and significant amounts of memory are likely to be used, all
                                746                 :                :          * workers must have already freed almost all memory held by their
                                747                 :                :          * Tuplesortstates (they are about to go away completely, too).  The
                                748                 :                :          * overall effect is that maintenance_work_mem always represents an
                                749                 :                :          * absolute high watermark on the amount of memory used by a CREATE
                                750                 :                :          * INDEX operation, regardless of the use of parallelism or any other
                                751                 :                :          * factor.
                                752                 :                :          */
                                753                 :             18 :         state->bs_sortstate =
                                754                 :             18 :             tuplesort_begin_index_gin(heap, index,
                                755                 :                :                                       maintenance_work_mem, coordinate,
                                756                 :                :                                       TUPLESORT_NONE);
                                757                 :                : 
                                758                 :                :         /* scan the relation in parallel and merge per-worker results */
    3                           759                 :             18 :         reltuples = _gin_parallel_merge(state, indexInfo);
                                760                 :                : 
  635                           761                 :             18 :         _gin_end_parallel(state->bs_leader, state);
                                762                 :                :     }
                                763                 :                :     else                        /* no parallel index build */
                                764                 :                :     {
                                765                 :                :         /*
                                766                 :                :          * Do the heap scan.  We disallow sync scan here because
                                767                 :                :          * dataPlaceToPage prefers to receive tuples in TID order.
                                768                 :                :          */
                                769                 :            204 :         reltuples = table_index_build_scan(heap, index, indexInfo, false, true,
                                770                 :                :                                            ginBuildCallback, &buildstate, NULL);
                                771                 :                : 
                                772                 :                :         /* dump remaining entries to the index */
                                773                 :            204 :         oldCtx = MemoryContextSwitchTo(buildstate.tmpCtx);
                                774                 :            204 :         ginBeginBAScan(&buildstate.accum);
                                775                 :          75969 :         while ((list = ginGetBAEntry(&buildstate.accum,
                                776         [ +  + ]:          75969 :                                      &attnum, &key, &category, &nlist)) != NULL)
                                777                 :                :         {
                                778                 :                :             /* there could be many entries, so be willing to abort here */
                                779         [ -  + ]:          75765 :             CHECK_FOR_INTERRUPTS();
                                780                 :          75765 :             ginEntryInsert(&buildstate.ginstate, attnum, key, category,
                                781                 :                :                            list, nlist, &buildstate.buildStats);
                                782                 :                :         }
                                783                 :            204 :         MemoryContextSwitchTo(oldCtx);
                                784                 :                :     }
                                785                 :                : 
 4262 tgl@sss.pgh.pa.us         786                 :            222 :     MemoryContextDelete(buildstate.funcCtx);
 7515 teodor@sigaev.ru          787                 :            222 :     MemoryContextDelete(buildstate.tmpCtx);
                                788                 :                : 
                                789                 :                :     /*
                                790                 :                :      * Update metapage stats
                                791                 :                :      */
 5886 tgl@sss.pgh.pa.us         792                 :            222 :     buildstate.buildStats.nTotalPages = RelationGetNumberOfBlocks(index);
 2796 heikki.linnakangas@i      793                 :            222 :     ginUpdateStats(index, &buildstate.buildStats, true);
                                794                 :                : 
                                795                 :                :     /*
                                796                 :                :      * We didn't write WAL records as we built the index, so if WAL-logging is
                                797                 :                :      * required, write all pages to the WAL now.
                                798                 :                :      */
                                799   [ +  +  +  +  :            222 :     if (RelationNeedsWAL(index))
                                        +  +  +  + ]
                                800                 :                :     {
                                801                 :            157 :         log_newpage_range(index, MAIN_FORKNUM,
                                802                 :                :                           0, RelationGetNumberOfBlocks(index),
                                803                 :                :                           true);
                                804                 :                :     }
                                805                 :                : 
                                806                 :                :     /*
                                807                 :                :      * Return statistics
                                808                 :                :      */
  353 michael@paquier.xyz       809                 :            222 :     result = palloc_object(IndexBuildResult);
                                810                 :                : 
 7507 tgl@sss.pgh.pa.us         811                 :            222 :     result->heap_tuples = reltuples;
                                812                 :            222 :     result->index_tuples = buildstate.indtuples;
                                813                 :                : 
 3968                           814                 :            222 :     return result;
                                815                 :                : }
                                816                 :                : 
                                817                 :                : /*
                                818                 :                :  *  ginbuildempty() -- build an empty gin index in the initialization fork
                                819                 :                :  */
                                820                 :                : void
                                821                 :              4 : ginbuildempty(Relation index)
                                822                 :                : {
                                823                 :                :     Buffer      RootBuffer,
                                824                 :                :                 MetaBuffer;
                                825                 :                : 
                                826                 :                :     /* An empty GIN index has two pages. */
 1193 tmunro@postgresql.or      827                 :              4 :     MetaBuffer = ExtendBufferedRel(BMR_REL(index), INIT_FORKNUM, NULL,
                                828                 :                :                                    EB_LOCK_FIRST | EB_SKIP_EXTENSION_LOCK);
                                829                 :              4 :     RootBuffer = ExtendBufferedRel(BMR_REL(index), INIT_FORKNUM, NULL,
                                830                 :                :                                    EB_LOCK_FIRST | EB_SKIP_EXTENSION_LOCK);
                                831                 :                : 
                                832                 :                :     /* Initialize and xlog metabuffer and root buffer. */
 5813 rhaas@postgresql.org      833                 :              4 :     START_CRIT_SECTION();
                                834                 :              4 :     GinInitMetabuffer(MetaBuffer);
                                835                 :              4 :     MarkBufferDirty(MetaBuffer);
 3313 tgl@sss.pgh.pa.us         836                 :              4 :     log_newpage_buffer(MetaBuffer, true);
 5813 rhaas@postgresql.org      837                 :              4 :     GinInitBuffer(RootBuffer, GIN_LEAF);
                                838                 :              4 :     MarkBufferDirty(RootBuffer);
 4742 heikki.linnakangas@i      839                 :              4 :     log_newpage_buffer(RootBuffer, false);
 5813 rhaas@postgresql.org      840         [ -  + ]:              4 :     END_CRIT_SECTION();
                                841                 :                : 
                                842                 :                :     /* Unlock and release the buffers. */
                                843                 :              4 :     UnlockReleaseBuffer(MetaBuffer);
                                844                 :              4 :     UnlockReleaseBuffer(RootBuffer);
                                845                 :              4 : }
                                846                 :                : 
                                847                 :                : /*
                                848                 :                :  * Insert index entries for a single indexable item during "normal"
                                849                 :                :  * (non-fast-update) insertion
                                850                 :                :  */
                                851                 :                : static void
 5804 tgl@sss.pgh.pa.us         852                 :          39092 : ginHeapTupleInsert(GinState *ginstate, OffsetNumber attnum,
                                853                 :                :                    Datum value, bool isNull,
                                854                 :                :                    ItemPointer item)
                                855                 :                : {
                                856                 :                :     Datum      *entries;
                                857                 :                :     GinNullCategory *categories;
                                858                 :                :     int32       i,
                                859                 :                :                 nentries;
                                860                 :                : 
                                861                 :          39092 :     entries = ginExtractEntries(ginstate, attnum, value, isNull,
                                862                 :                :                                 &nentries, &categories);
                                863                 :                : 
 7360 bruce@momjian.us          864         [ +  + ]:         281598 :     for (i = 0; i < nentries; i++)
                                865                 :                :     {
                                866                 :                :         /* there could be many entries, so be willing to abort here */
  260 heikki.linnakangas@i      867         [ +  + ]:         242517 :         CHECK_FOR_INTERRUPTS();
 5804 tgl@sss.pgh.pa.us         868                 :         242517 :         ginEntryInsert(ginstate, attnum, entries[i], categories[i],
                                869                 :                :                        item, 1, NULL);
                                870                 :                :     }
 7515 teodor@sigaev.ru          871                 :          39081 : }
                                872                 :                : 
                                873                 :                : bool
 3968 tgl@sss.pgh.pa.us         874                 :         215980 : gininsert(Relation index, Datum *values, bool *isnull,
                                875                 :                :           ItemPointer ht_ctid, Relation heapRel,
                                876                 :                :           IndexUniqueCheck checkUnique,
                                877                 :                :           bool indexUnchanged,
                                878                 :                :           IndexInfo *indexInfo)
                                879                 :                : {
 3579                           880                 :         215980 :     GinState   *ginstate = (GinState *) indexInfo->ii_AmCache;
                                881                 :                :     MemoryContext oldCtx;
                                882                 :                :     MemoryContext insertCtx;
                                883                 :                :     int         i;
                                884                 :                : 
                                885                 :                :     /* Initialize GinState cache if first call in this statement */
                                886         [ +  + ]:         215980 :     if (ginstate == NULL)
                                887                 :                :     {
                                888                 :          11470 :         oldCtx = MemoryContextSwitchTo(indexInfo->ii_Context);
  353 michael@paquier.xyz       889                 :          11470 :         ginstate = palloc_object(GinState);
 3579 tgl@sss.pgh.pa.us         890                 :          11470 :         initGinState(ginstate, index);
  730 peter@eisentraut.org      891                 :          11470 :         indexInfo->ii_AmCache = ginstate;
 3579 tgl@sss.pgh.pa.us         892                 :          11470 :         MemoryContextSwitchTo(oldCtx);
                                893                 :                :     }
                                894                 :                : 
 7515 teodor@sigaev.ru          895                 :         215980 :     insertCtx = AllocSetContextCreate(CurrentMemoryContext,
                                896                 :                :                                       "Gin insert temporary context",
                                897                 :                :                                       ALLOCSET_DEFAULT_SIZES);
                                898                 :                : 
                                899                 :         215980 :     oldCtx = MemoryContextSwitchTo(insertCtx);
                                900                 :                : 
 6379 bruce@momjian.us          901   [ +  -  -  +  :         215980 :     if (GinGetUseFastUpdate(index))
                                        +  +  +  + ]
 6458 tgl@sss.pgh.pa.us         902                 :         176885 :     {
                                903                 :                :         GinTupleCollector collector;
                                904                 :                : 
                                905                 :         176888 :         memset(&collector, 0, sizeof(GinTupleCollector));
                                906                 :                : 
 3579                           907         [ +  + ]:         433828 :         for (i = 0; i < ginstate->origTupdesc->natts; i++)
                                908                 :         256940 :             ginHeapTupleFastCollect(ginstate, &collector,
 5804                           909                 :         256940 :                                     (OffsetNumber) (i + 1),
                                910                 :         256940 :                                     values[i], isnull[i],
                                911                 :                :                                     ht_ctid);
                                912                 :                : 
 3579                           913                 :         176888 :         ginHeapTupleFastInsert(ginstate, &collector);
                                914                 :                :     }
                                915                 :                :     else
                                916                 :                :     {
                                917         [ +  + ]:          78173 :         for (i = 0; i < ginstate->origTupdesc->natts; i++)
                                918                 :          39092 :             ginHeapTupleInsert(ginstate, (OffsetNumber) (i + 1),
 5804                           919                 :          39092 :                                values[i], isnull[i],
                                920                 :                :                                ht_ctid);
                                921                 :                :     }
                                922                 :                : 
 7515 teodor@sigaev.ru          923                 :         215966 :     MemoryContextSwitchTo(oldCtx);
                                924                 :         215966 :     MemoryContextDelete(insertCtx);
                                925                 :                : 
 3968 tgl@sss.pgh.pa.us         926                 :         215966 :     return false;
                                927                 :                : }
                                928                 :                : 
                                929                 :                : /*
                                930                 :                :  * Create parallel context, and launch workers for leader.
                                931                 :                :  *
                                932                 :                :  * buildstate argument should be initialized (with the exception of the
                                933                 :                :  * tuplesort states, which may later be created based on shared
                                934                 :                :  * state initially set up here).
                                935                 :                :  *
                                936                 :                :  * isconcurrent indicates if operation is CREATE INDEX CONCURRENTLY.
                                937                 :                :  *
                                938                 :                :  * request is the target number of parallel worker processes to launch.
                                939                 :                :  *
                                940                 :                :  * Sets buildstate's GinLeader, which caller must use to shut down parallel
                                941                 :                :  * mode by passing it to _gin_end_parallel() at the very end of its index
                                942                 :                :  * build.  If not even a single worker process can be launched, this is
                                943                 :                :  * never set, and caller should proceed with a serial index build.
                                944                 :                :  */
                                945                 :                : static void
  635 tomas.vondra@postgre      946                 :             18 : _gin_begin_parallel(GinBuildState *buildstate, Relation heap, Relation index,
                                947                 :                :                     bool isconcurrent, int request)
                                948                 :                : {
                                949                 :                :     ParallelContext *pcxt;
                                950                 :                :     int         scantuplesortstates;
                                951                 :                :     Snapshot    snapshot;
                                952                 :                :     Size        estginshared;
                                953                 :                :     Size        estsort;
                                954                 :                :     GinBuildShared *ginshared;
                                955                 :                :     Sharedsort *sharedsort;
  353 michael@paquier.xyz       956                 :             18 :     GinLeader  *ginleader = palloc0_object(GinLeader);
                                957                 :                :     WalUsage   *walusage;
                                958                 :                :     BufferUsage *bufferusage;
  635 tomas.vondra@postgre      959                 :             18 :     bool        leaderparticipates = true;
                                960                 :                :     int         querylen;
                                961                 :                : 
                                962                 :                : #ifdef DISABLE_LEADER_PARTICIPATION
                                963                 :                :     leaderparticipates = false;
                                964                 :                : #endif
                                965                 :                : 
                                966                 :                :     /*
                                967                 :                :      * Enter parallel mode, and create context for parallel build of gin index
                                968                 :                :      */
                                969                 :             18 :     EnterParallelMode();
                                970         [ -  + ]:             18 :     Assert(request > 0);
                                971                 :             18 :     pcxt = CreateParallelContext("postgres", "_gin_parallel_build_main",
                                972                 :                :                                  request);
                                973                 :                : 
                                974                 :             18 :     scantuplesortstates = leaderparticipates ? request + 1 : request;
                                975                 :                : 
                                976                 :                :     /*
                                977                 :                :      * Prepare for scan of the base relation.  In a normal index build, we use
                                978                 :                :      * SnapshotAny because we must retrieve all tuples and do our own time
                                979                 :                :      * qual checks (because we have to index RECENTLY_DEAD tuples).  In a
                                980                 :                :      * concurrent build, we take a regular MVCC snapshot and index whatever's
                                981                 :                :      * live according to that.
                                982                 :                :      */
                                983         [ +  + ]:             18 :     if (!isconcurrent)
                                984                 :             14 :         snapshot = SnapshotAny;
                                985                 :                :     else
                                986                 :              4 :         snapshot = RegisterSnapshot(GetTransactionSnapshot());
                                987                 :                : 
                                988                 :                :     /*
                                989                 :                :      * Estimate size for our own PARALLEL_KEY_GIN_SHARED workspace.
                                990                 :                :      */
                                991                 :             18 :     estginshared = _gin_parallel_estimate_shared(heap, snapshot);
                                992                 :             18 :     shm_toc_estimate_chunk(&pcxt->estimator, estginshared);
                                993                 :             18 :     estsort = tuplesort_estimate_shared(scantuplesortstates);
                                994                 :             18 :     shm_toc_estimate_chunk(&pcxt->estimator, estsort);
                                995                 :                : 
                                996                 :             18 :     shm_toc_estimate_keys(&pcxt->estimator, 2);
                                997                 :                : 
                                998                 :                :     /*
                                999                 :                :      * Estimate space for WalUsage and BufferUsage -- PARALLEL_KEY_WAL_USAGE
                               1000                 :                :      * and PARALLEL_KEY_BUFFER_USAGE.
                               1001                 :                :      *
                               1002                 :                :      * If there are no extensions loaded that care, we could skip this.  We
                               1003                 :                :      * have no way of knowing whether anyone's looking at pgWalUsage or
                               1004                 :                :      * pgBufferUsage, so do it unconditionally.
                               1005                 :                :      */
                               1006                 :             18 :     shm_toc_estimate_chunk(&pcxt->estimator,
                               1007                 :                :                            mul_size(sizeof(WalUsage), pcxt->nworkers));
                               1008                 :             18 :     shm_toc_estimate_keys(&pcxt->estimator, 1);
                               1009                 :             18 :     shm_toc_estimate_chunk(&pcxt->estimator,
                               1010                 :                :                            mul_size(sizeof(BufferUsage), pcxt->nworkers));
                               1011                 :             18 :     shm_toc_estimate_keys(&pcxt->estimator, 1);
                               1012                 :                : 
                               1013                 :                :     /* Finally, estimate PARALLEL_KEY_QUERY_TEXT space */
                               1014         [ +  - ]:             18 :     if (debug_query_string)
                               1015                 :                :     {
                               1016                 :             18 :         querylen = strlen(debug_query_string);
                               1017                 :             18 :         shm_toc_estimate_chunk(&pcxt->estimator, querylen + 1);
                               1018                 :             18 :         shm_toc_estimate_keys(&pcxt->estimator, 1);
                               1019                 :                :     }
                               1020                 :                :     else
  635 tomas.vondra@postgre     1021                 :UBC           0 :         querylen = 0;           /* keep compiler quiet */
                               1022                 :                : 
                               1023                 :                :     /* Everyone's had a chance to ask for space, so now create the DSM */
  635 tomas.vondra@postgre     1024                 :CBC          18 :     InitializeParallelDSM(pcxt);
                               1025                 :                : 
                               1026                 :                :     /* If no DSM segment was available, back out (do serial build) */
                               1027         [ -  + ]:             18 :     if (pcxt->seg == NULL)
                               1028                 :                :     {
  635 tomas.vondra@postgre     1029         [ #  # ]:UBC           0 :         if (IsMVCCSnapshot(snapshot))
                               1030                 :              0 :             UnregisterSnapshot(snapshot);
                               1031                 :              0 :         DestroyParallelContext(pcxt);
                               1032                 :              0 :         ExitParallelMode();
                               1033                 :              0 :         return;
                               1034                 :                :     }
                               1035                 :                : 
                               1036                 :                :     /* Store shared build state, for which we reserved space */
  635 tomas.vondra@postgre     1037                 :CBC          18 :     ginshared = (GinBuildShared *) shm_toc_allocate(pcxt->toc, estginshared);
                               1038                 :                :     /* Initialize immutable state */
                               1039                 :             18 :     ginshared->heaprelid = RelationGetRelid(heap);
                               1040                 :             18 :     ginshared->indexrelid = RelationGetRelid(index);
                               1041                 :             18 :     ginshared->isconcurrent = isconcurrent;
                               1042                 :             18 :     ginshared->scantuplesortstates = scantuplesortstates;
    2 tomas.vondra@postgre     1043                 :GNC          18 :     ginshared->queryid = pgstat_get_my_query_id();
                               1044                 :                : 
  635 tomas.vondra@postgre     1045                 :CBC          18 :     ConditionVariableInit(&ginshared->workersdonecv);
                               1046                 :             18 :     SpinLockInit(&ginshared->mutex);
                               1047                 :                : 
                               1048                 :                :     /* Initialize mutable state */
                               1049                 :             18 :     ginshared->nparticipantsdone = 0;
                               1050                 :             18 :     ginshared->reltuples = 0.0;
                               1051                 :             18 :     ginshared->indtuples = 0.0;
    3                          1052                 :             18 :     ginshared->brokenhotchain = false;
                               1053                 :                : 
  635                          1054                 :             18 :     table_parallelscan_initialize(heap,
                               1055                 :                :                                   ParallelTableScanFromGinBuildShared(ginshared),
                               1056                 :                :                                   snapshot);
                               1057                 :                : 
                               1058                 :                :     /*
                               1059                 :                :      * Store shared tuplesort-private state, for which we reserved space.
                               1060                 :                :      * Then, initialize opaque state using tuplesort routine.
                               1061                 :                :      */
                               1062                 :             18 :     sharedsort = (Sharedsort *) shm_toc_allocate(pcxt->toc, estsort);
                               1063                 :             18 :     tuplesort_initialize_shared(sharedsort, scantuplesortstates,
                               1064                 :                :                                 pcxt->seg);
                               1065                 :                : 
                               1066                 :             18 :     shm_toc_insert(pcxt->toc, PARALLEL_KEY_GIN_SHARED, ginshared);
                               1067                 :             18 :     shm_toc_insert(pcxt->toc, PARALLEL_KEY_TUPLESORT, sharedsort);
                               1068                 :                : 
                               1069                 :                :     /* Store query string for workers */
                               1070         [ +  - ]:             18 :     if (debug_query_string)
                               1071                 :                :     {
                               1072                 :                :         char       *sharedquery;
                               1073                 :                : 
                               1074                 :             18 :         sharedquery = (char *) shm_toc_allocate(pcxt->toc, querylen + 1);
                               1075                 :             18 :         memcpy(sharedquery, debug_query_string, querylen + 1);
                               1076                 :             18 :         shm_toc_insert(pcxt->toc, PARALLEL_KEY_QUERY_TEXT, sharedquery);
                               1077                 :                :     }
                               1078                 :                : 
                               1079                 :                :     /*
                               1080                 :                :      * Allocate space for each worker's WalUsage and BufferUsage; no need to
                               1081                 :                :      * initialize.
                               1082                 :                :      */
                               1083                 :             18 :     walusage = shm_toc_allocate(pcxt->toc,
                               1084                 :             18 :                                 mul_size(sizeof(WalUsage), pcxt->nworkers));
                               1085                 :             18 :     shm_toc_insert(pcxt->toc, PARALLEL_KEY_WAL_USAGE, walusage);
                               1086                 :             18 :     bufferusage = shm_toc_allocate(pcxt->toc,
                               1087                 :             18 :                                    mul_size(sizeof(BufferUsage), pcxt->nworkers));
                               1088                 :             18 :     shm_toc_insert(pcxt->toc, PARALLEL_KEY_BUFFER_USAGE, bufferusage);
                               1089                 :                : 
                               1090                 :                :     /* Launch workers, saving status for leader/caller */
                               1091                 :             18 :     LaunchParallelWorkers(pcxt);
                               1092                 :             18 :     ginleader->pcxt = pcxt;
                               1093                 :             18 :     ginleader->nparticipanttuplesorts = pcxt->nworkers_launched;
                               1094         [ +  - ]:             18 :     if (leaderparticipates)
                               1095                 :             18 :         ginleader->nparticipanttuplesorts++;
                               1096                 :             18 :     ginleader->ginshared = ginshared;
                               1097                 :             18 :     ginleader->sharedsort = sharedsort;
                               1098                 :             18 :     ginleader->snapshot = snapshot;
                               1099                 :             18 :     ginleader->walusage = walusage;
                               1100                 :             18 :     ginleader->bufferusage = bufferusage;
                               1101                 :                : 
                               1102                 :                :     /* If no workers were successfully launched, back out (do serial build) */
                               1103         [ -  + ]:             18 :     if (pcxt->nworkers_launched == 0)
                               1104                 :                :     {
  635 tomas.vondra@postgre     1105                 :UBC           0 :         _gin_end_parallel(ginleader, NULL);
                               1106                 :              0 :         return;
                               1107                 :                :     }
                               1108                 :                : 
                               1109                 :                :     /* Save leader state now that it's clear build will be parallel */
  635 tomas.vondra@postgre     1110                 :CBC          18 :     buildstate->bs_leader = ginleader;
                               1111                 :                : 
                               1112                 :                :     /* Join heap scan ourselves */
                               1113         [ +  - ]:             18 :     if (leaderparticipates)
                               1114                 :             18 :         _gin_leader_participate_as_worker(buildstate, heap, index);
                               1115                 :                : 
                               1116                 :                :     /*
                               1117                 :                :      * Caller needs to wait for all launched workers when we return.  Make
                               1118                 :                :      * sure that the failure-to-start case will not hang forever.
                               1119                 :                :      */
                               1120                 :             18 :     WaitForParallelWorkersToAttach(pcxt);
                               1121                 :                : }
                               1122                 :                : 
                               1123                 :                : /*
                               1124                 :                :  * Shut down workers, destroy parallel context, and end parallel mode.
                               1125                 :                :  */
                               1126                 :                : static void
                               1127                 :             18 : _gin_end_parallel(GinLeader *ginleader, GinBuildState *state)
                               1128                 :                : {
                               1129                 :                :     int         i;
                               1130                 :                : 
                               1131                 :                :     /* Shutdown worker processes */
                               1132                 :             18 :     WaitForParallelWorkersToFinish(ginleader->pcxt);
                               1133                 :                : 
                               1134                 :                :     /*
                               1135                 :                :      * Next, accumulate WAL usage.  (This must wait for the workers to finish,
                               1136                 :                :      * or we might get incomplete data.)
                               1137                 :                :      */
                               1138         [ +  + ]:             53 :     for (i = 0; i < ginleader->pcxt->nworkers_launched; i++)
                               1139                 :             35 :         InstrAccumParallelQuery(&ginleader->bufferusage[i], &ginleader->walusage[i]);
                               1140                 :                : 
                               1141                 :                :     /* Free last reference to MVCC snapshot, if one was used */
                               1142         [ +  + ]:             18 :     if (IsMVCCSnapshot(ginleader->snapshot))
                               1143                 :              4 :         UnregisterSnapshot(ginleader->snapshot);
                               1144                 :             18 :     DestroyParallelContext(ginleader->pcxt);
                               1145                 :             18 :     ExitParallelMode();
                               1146                 :             18 : }
                               1147                 :                : 
                               1148                 :                : /*
                               1149                 :                :  * Within leader, wait for end of heap scan.
                               1150                 :                :  *
                               1151                 :                :  * When called, parallel heap scan started by _gin_begin_parallel() will
                               1152                 :                :  * already be underway within worker processes (when leader participates
                               1153                 :                :  * as a worker, we should end up here just as workers are finishing).
                               1154                 :                :  *
                               1155                 :                :  * Returns the total number of heap tuples scanned.  Also sets *brokenhotchain
                               1156                 :                :  * to whether any participant detected a broken HOT chain.
                               1157                 :                :  */
                               1158                 :                : static double
    3                          1159                 :             18 : _gin_parallel_heapscan(GinBuildState *state, bool *brokenhotchain)
                               1160                 :                : {
  635                          1161                 :             18 :     GinBuildShared *ginshared = state->bs_leader->ginshared;
                               1162                 :                :     int         nparticipanttuplesorts;
                               1163                 :                : 
                               1164                 :             18 :     nparticipanttuplesorts = state->bs_leader->nparticipanttuplesorts;
                               1165                 :                :     for (;;)
                               1166                 :                :     {
                               1167                 :             40 :         SpinLockAcquire(&ginshared->mutex);
                               1168         [ +  + ]:             40 :         if (ginshared->nparticipantsdone == nparticipanttuplesorts)
                               1169                 :                :         {
                               1170                 :                :             /* copy the data into leader state */
                               1171                 :             18 :             state->bs_reltuples = ginshared->reltuples;
                               1172                 :             18 :             state->bs_numtuples = ginshared->indtuples;
    3                          1173                 :             18 :             *brokenhotchain = ginshared->brokenhotchain;
                               1174                 :                : 
  635                          1175                 :             18 :             SpinLockRelease(&ginshared->mutex);
                               1176                 :             18 :             break;
                               1177                 :                :         }
                               1178                 :             22 :         SpinLockRelease(&ginshared->mutex);
                               1179                 :                : 
                               1180                 :             22 :         ConditionVariableSleep(&ginshared->workersdonecv,
                               1181                 :                :                                WAIT_EVENT_PARALLEL_CREATE_INDEX_SCAN);
                               1182                 :                :     }
                               1183                 :                : 
                               1184                 :             18 :     ConditionVariableCancelSleep();
                               1185                 :                : 
                               1186                 :             18 :     return state->bs_reltuples;
                               1187                 :                : }
                               1188                 :                : 
                               1189                 :                : /*
                               1190                 :                :  * Buffer used to accumulate TIDs from multiple GinTuples for the same key
                               1191                 :                :  * (we read these from the tuplesort, sorted by the key).
                               1192                 :                :  *
                               1193                 :                :  * This is similar to BuildAccumulator in that it's used to collect TIDs
                               1194                 :                :  * in memory before inserting them into the index, but it's much simpler
                               1195                 :                :  * as it only deals with a single index key at a time.
                               1196                 :                :  *
                               1197                 :                :  * When adding TIDs to the buffer, we make sure to keep them sorted, both
                               1198                 :                :  * during the initial table scan (and detecting when the scan wraps around),
                               1199                 :                :  * and during merging (where we do mergesort).
                               1200                 :                :  */
                               1201                 :                : typedef struct GinBuffer
                               1202                 :                : {
                               1203                 :                :     OffsetNumber attnum;
                               1204                 :                :     GinNullCategory category;
                               1205                 :                :     Datum       key;            /* 0 if no key (and keylen == 0) */
                               1206                 :                :     Size        keylen;         /* number of bytes (not typlen) */
                               1207                 :                : 
                               1208                 :                :     /* type info */
                               1209                 :                :     int16       typlen;
                               1210                 :                :     bool        typbyval;
                               1211                 :                : 
                               1212                 :                :     /* Number of TIDs to collect before attempt to write some out. */
                               1213                 :                :     int         maxitems;
                               1214                 :                : 
                               1215                 :                :     /* array of TID values */
                               1216                 :                :     int         nitems;
                               1217                 :                :     int         nfrozen;
                               1218                 :                :     SortSupport ssup;           /* for sorting/comparing keys */
                               1219                 :                :     ItemPointerData *items;
                               1220                 :                : } GinBuffer;
                               1221                 :                : 
                               1222                 :                : /*
                               1223                 :                :  * Check that TID array contains valid values, and that it's sorted (if we
                               1224                 :                :  * expect it to be).
                               1225                 :                :  */
                               1226                 :                : static void
                               1227                 :         147447 : AssertCheckItemPointers(GinBuffer *buffer)
                               1228                 :                : {
                               1229                 :                : #ifdef USE_ASSERT_CHECKING
                               1230                 :                :     /* we should not have a buffer with no TIDs to sort */
                               1231         [ -  + ]:         147447 :     Assert(buffer->items != NULL);
                               1232         [ -  + ]:         147447 :     Assert(buffer->nitems > 0);
                               1233                 :                : 
                               1234         [ +  + ]:        1712181 :     for (int i = 0; i < buffer->nitems; i++)
                               1235                 :                :     {
                               1236         [ -  + ]:        1564734 :         Assert(ItemPointerIsValid(&buffer->items[i]));
                               1237                 :                : 
                               1238                 :                :         /* don't check ordering for the first TID item */
                               1239         [ +  + ]:        1564734 :         if (i == 0)
                               1240                 :         147447 :             continue;
                               1241                 :                : 
                               1242         [ -  + ]:        1417287 :         Assert(ItemPointerCompare(&buffer->items[i - 1], &buffer->items[i]) < 0);
                               1243                 :                :     }
                               1244                 :                : #endif
                               1245                 :         147447 : }
                               1246                 :                : 
                               1247                 :                : /*
                               1248                 :                :  * GinBuffer checks
                               1249                 :                :  *
                               1250                 :                :  * Make sure the nitems/items fields are consistent (either the array is empty
                               1251                 :                :  * or not empty, the fields need to agree). If there are items, check ordering.
                               1252                 :                :  */
                               1253                 :                : static void
                               1254                 :          98281 : AssertCheckGinBuffer(GinBuffer *buffer)
                               1255                 :                : {
                               1256                 :                : #ifdef USE_ASSERT_CHECKING
                               1257                 :                :     /* if we have any items, the array must exist */
                               1258   [ +  +  -  + ]:          98281 :     Assert(!((buffer->nitems > 0) && (buffer->items == NULL)));
                               1259                 :                : 
                               1260                 :                :     /*
                               1261                 :                :      * The buffer may be empty, in which case we must not call the check of
                               1262                 :                :      * item pointers, because that assumes non-emptiness.
                               1263                 :                :      */
                               1264         [ +  + ]:          98281 :     if (buffer->nitems == 0)
                               1265                 :          39684 :         return;
                               1266                 :                : 
                               1267                 :                :     /* Make sure the item pointers are valid and sorted. */
                               1268                 :          58597 :     AssertCheckItemPointers(buffer);
                               1269                 :                : #endif
                               1270                 :                : }
                               1271                 :                : 
                               1272                 :                : /*
                               1273                 :                :  * GinBufferInit
                               1274                 :                :  *      Initialize buffer to store tuples for a GIN index.
                               1275                 :                :  *
                               1276                 :                :  * Initialize the buffer used to accumulate TID for a single key at a time
                               1277                 :                :  * (we process the data sorted), so we know when we received all data for
                               1278                 :                :  * a given key.
                               1279                 :                :  *
                               1280                 :                :  * Initializes sort support procedures for all index attributes.
                               1281                 :                :  */
                               1282                 :                : static GinBuffer *
                               1283                 :             71 : GinBufferInit(Relation index)
                               1284                 :                : {
  353 michael@paquier.xyz      1285                 :             71 :     GinBuffer  *buffer = palloc0_object(GinBuffer);
                               1286                 :                :     int         i,
                               1287                 :                :                 nKeys;
  635 tomas.vondra@postgre     1288                 :             71 :     TupleDesc   desc = RelationGetDescr(index);
                               1289                 :                : 
                               1290                 :                :     /*
                               1291                 :                :      * How many items can we fit into the memory limit? We don't want to end
                               1292                 :                :      * with too many TIDs. and 64kB seems more than enough. But maybe this
                               1293                 :                :      * should be tied to maintenance_work_mem or something like that?
                               1294                 :                :      */
  634                          1295                 :             71 :     buffer->maxitems = (64 * 1024L) / sizeof(ItemPointerData);
                               1296                 :                : 
  635                          1297                 :             71 :     nKeys = IndexRelationGetNumberOfKeyAttributes(index);
                               1298                 :                : 
  353 michael@paquier.xyz      1299                 :             71 :     buffer->ssup = palloc0_array(SortSupportData, nKeys);
                               1300                 :                : 
                               1301                 :                :     /*
                               1302                 :                :      * Lookup ordering operator for the index key data type, and initialize
                               1303                 :                :      * the sort support function.
                               1304                 :                :      */
  635 tomas.vondra@postgre     1305         [ +  + ]:            142 :     for (i = 0; i < nKeys; i++)
                               1306                 :                :     {
                               1307                 :                :         Oid         cmpFunc;
                               1308                 :             71 :         SortSupport sortKey = &buffer->ssup[i];
                               1309                 :             71 :         Form_pg_attribute att = TupleDescAttr(desc, i);
                               1310                 :                : 
                               1311                 :             71 :         sortKey->ssup_cxt = CurrentMemoryContext;
                               1312                 :             71 :         sortKey->ssup_collation = index->rd_indcollation[i];
                               1313                 :                : 
                               1314         [ +  - ]:             71 :         if (!OidIsValid(sortKey->ssup_collation))
                               1315                 :             71 :             sortKey->ssup_collation = DEFAULT_COLLATION_OID;
                               1316                 :                : 
                               1317                 :             71 :         sortKey->ssup_nulls_first = false;
                               1318                 :             71 :         sortKey->ssup_attno = i + 1;
                               1319                 :             71 :         sortKey->abbreviate = false;
                               1320                 :                : 
                               1321         [ -  + ]:             71 :         Assert(sortKey->ssup_attno != 0);
                               1322                 :                : 
                               1323                 :                :         /*
                               1324                 :                :          * If the compare proc isn't specified in the opclass definition, look
                               1325                 :                :          * up the index key type's default btree comparator.
                               1326                 :                :          */
                               1327                 :             71 :         cmpFunc = index_getprocid(index, i + 1, GIN_COMPARE_PROC);
                               1328         [ +  + ]:             71 :         if (cmpFunc == InvalidOid)
                               1329                 :                :         {
                               1330                 :                :             TypeCacheEntry *typentry;
                               1331                 :                : 
                               1332                 :              3 :             typentry = lookup_type_cache(att->atttypid,
                               1333                 :                :                                          TYPECACHE_CMP_PROC_FINFO);
                               1334         [ -  + ]:              3 :             if (!OidIsValid(typentry->cmp_proc_finfo.fn_oid))
  635 tomas.vondra@postgre     1335         [ #  # ]:UBC           0 :                 ereport(ERROR,
                               1336                 :                :                         (errcode(ERRCODE_UNDEFINED_FUNCTION),
                               1337                 :                :                          errmsg("could not identify a comparison function for type %s",
                               1338                 :                :                                 format_type_be(att->atttypid))));
                               1339                 :                : 
  635 tomas.vondra@postgre     1340                 :CBC           3 :             cmpFunc = typentry->cmp_proc_finfo.fn_oid;
                               1341                 :                :         }
                               1342                 :                : 
                               1343                 :             71 :         PrepareSortSupportComparisonShim(cmpFunc, sortKey);
                               1344                 :                :     }
                               1345                 :                : 
                               1346                 :             71 :     return buffer;
                               1347                 :                : }
                               1348                 :                : 
                               1349                 :                : /* Is the buffer empty, i.e. has no TID values in the array? */
                               1350                 :                : static bool
                               1351                 :         138158 : GinBufferIsEmpty(GinBuffer *buffer)
                               1352                 :                : {
                               1353                 :         138158 :     return (buffer->nitems == 0);
                               1354                 :                : }
                               1355                 :                : 
                               1356                 :                : /*
                               1357                 :                :  * GinBufferKeyEquals
                               1358                 :                :  *      Can the buffer store TIDs for the provided GIN tuple (same key)?
                               1359                 :                :  *
                               1360                 :                :  * Compare if the tuple matches the already accumulated data in the GIN
                               1361                 :                :  * buffer. Compare scalar fields first, before the actual key.
                               1362                 :                :  *
                               1363                 :                :  * Returns true if the key matches, and the TID belongs to the buffer, or
                               1364                 :                :  * false if the key does not match.
                               1365                 :                :  */
                               1366                 :                : static bool
                               1367                 :          49115 : GinBufferKeyEquals(GinBuffer *buffer, GinTuple *tup)
                               1368                 :                : {
                               1369                 :                :     int         r;
                               1370                 :                :     Datum       tupkey;
                               1371                 :                : 
                               1372                 :          49115 :     AssertCheckGinBuffer(buffer);
                               1373                 :                : 
                               1374         [ -  + ]:          49115 :     if (tup->attrnum != buffer->attnum)
  635 tomas.vondra@postgre     1375                 :UBC           0 :         return false;
                               1376                 :                : 
                               1377                 :                :     /* same attribute should have the same type info */
  635 tomas.vondra@postgre     1378         [ -  + ]:CBC       49115 :     Assert(tup->typbyval == buffer->typbyval);
                               1379         [ -  + ]:          49115 :     Assert(tup->typlen == buffer->typlen);
                               1380                 :                : 
                               1381         [ +  + ]:          49115 :     if (tup->category != buffer->category)
                               1382                 :             41 :         return false;
                               1383                 :                : 
                               1384                 :                :     /*
                               1385                 :                :      * For NULL/empty keys, this means equality, for normal keys we need to
                               1386                 :                :      * compare the actual key value.
                               1387                 :                :      */
                               1388         [ +  + ]:          49074 :     if (buffer->category != GIN_CAT_NORM_KEY)
                               1389                 :              9 :         return true;
                               1390                 :                : 
                               1391                 :                :     /*
                               1392                 :                :      * For the tuple, get either the first sizeof(Datum) bytes for byval
                               1393                 :                :      * types, or a pointer to the beginning of the data array.
                               1394                 :                :      */
                               1395         [ +  + ]:          49065 :     tupkey = (buffer->typbyval) ? *(Datum *) tup->data : PointerGetDatum(tup->data);
                               1396                 :                : 
                               1397                 :          49065 :     r = ApplySortComparator(buffer->key, false,
                               1398                 :                :                             tupkey, false,
                               1399                 :          49065 :                             &buffer->ssup[buffer->attnum - 1]);
                               1400                 :                : 
                               1401                 :          49065 :     return (r == 0);
                               1402                 :                : }
                               1403                 :                : 
                               1404                 :                : /*
                               1405                 :                :  * GinBufferShouldTrim
                               1406                 :                :  *      Should we trim the list of item pointers?
                               1407                 :                :  *
                               1408                 :                :  * By trimming we understand writing out and removing the tuple IDs that
                               1409                 :                :  * we know can't change by future merges. We can deduce the TID up to which
                               1410                 :                :  * this is guaranteed from the "first" TID in each GIN tuple, which provides
                               1411                 :                :  * a "horizon" (for a given key) thanks to the sort.
                               1412                 :                :  *
                               1413                 :                :  * We don't want to do this too often - compressing longer TID lists is more
                               1414                 :                :  * efficient. But we also don't want to accumulate too many TIDs, for two
                               1415                 :                :  * reasons. First, it consumes memory and we might exceed maintenance_work_mem
                               1416                 :                :  * (or whatever limit applies), even if that's unlikely because TIDs are very
                               1417                 :                :  * small so we can fit a lot of them. Second, and more importantly, long TID
                               1418                 :                :  * lists are an issue if the scan wraps around, because a key may get a very
                               1419                 :                :  * wide list (with min/max TID for that key), forcing "full" mergesorts for
                               1420                 :                :  * every list merged into it (instead of the efficient append).
                               1421                 :                :  *
                               1422                 :                :  * So we look at two things when deciding if to trim - if the resulting list
                               1423                 :                :  * (after adding TIDs from the new tuple) would be too long, and if there is
                               1424                 :                :  * enough TIDs to trim (with values less than "first" TID from the new tuple),
                               1425                 :                :  * we do the trim. By enough we mean at least 128 TIDs (mostly an arbitrary
                               1426                 :                :  * number).
                               1427                 :                :  *
                               1428                 :                :  * We try freezing TIDs at the beginning of the list first, before attempting
                               1429                 :                :  * to trim the buffer. This may allow trimming the data earlier, reducing the
                               1430                 :                :  * memory usage and excluding it from the mergesort.
                               1431                 :                :  */
                               1432                 :                : static bool
  634                          1433                 :          49166 : GinBufferShouldTrim(GinBuffer *buffer, GinTuple *tup)
                               1434                 :                : {
                               1435                 :                :     /*
                               1436                 :                :      * Check if the last TID in the current list is frozen. This is the case
                               1437                 :                :      * when merging non-overlapping lists, e.g. in each parallel worker.
                               1438                 :                :      */
  389                          1439   [ +  +  -  + ]:          58648 :     if ((buffer->nitems > 0) &&
                               1440                 :           9482 :         (ItemPointerCompare(&buffer->items[buffer->nitems - 1],
                               1441                 :           9482 :                             GinTupleGetFirst(tup)) == 0))
  389 tomas.vondra@postgre     1442                 :UBC           0 :         buffer->nfrozen = buffer->nitems;
                               1443                 :                : 
                               1444                 :                :     /*
                               1445                 :                :      * Now find the last TID we know to be frozen, i.e. the last TID right
                               1446                 :                :      * before the new GIN tuple.
                               1447                 :                :      *
                               1448                 :                :      * Start with the first not-yet-frozen tuple, and walk until we find the
                               1449                 :                :      * first TID that's higher. If we already know the whole list is frozen
                               1450                 :                :      * (i.e. nfrozen == nitems), this does nothing.
                               1451                 :                :      *
                               1452                 :                :      * XXX This might do a binary search for sufficiently long lists, but it
                               1453                 :                :      * does not seem worth the complexity. Overlapping lists should be rare
                               1454                 :                :      * common, TID comparisons are cheap, and we should quickly freeze most of
                               1455                 :                :      * the list.
                               1456                 :                :      */
  389 tomas.vondra@postgre     1457         [ +  + ]:CBC      103771 :     for (int i = buffer->nfrozen; i < buffer->nitems; i++)
                               1458                 :                :     {
                               1459                 :                :         /* Is the TID after the first TID of the new tuple? Can't freeze. */
                               1460         [ +  + ]:          63004 :         if (ItemPointerCompare(&buffer->items[i],
                               1461                 :          63004 :                                GinTupleGetFirst(tup)) > 0)
                               1462                 :           8399 :             break;
                               1463                 :                : 
                               1464                 :          54605 :         buffer->nfrozen++;
                               1465                 :                :     }
                               1466                 :                : 
                               1467                 :                :     /* not enough TIDs to trim (1024 is somewhat arbitrary number) */
  634                          1468         [ +  - ]:          49166 :     if (buffer->nfrozen < 1024)
                               1469                 :          49166 :         return false;
                               1470                 :                : 
                               1471                 :                :     /* no need to trim if we have not hit the memory limit yet */
  634 tomas.vondra@postgre     1472         [ #  # ]:UBC           0 :     if ((buffer->nitems + tup->nitems) < buffer->maxitems)
                               1473                 :              0 :         return false;
                               1474                 :                : 
                               1475                 :                :     /*
                               1476                 :                :      * OK, we have enough frozen TIDs to flush, and we have hit the memory
                               1477                 :                :      * limit, so it's time to write it out.
                               1478                 :                :      */
                               1479                 :              0 :     return true;
                               1480                 :                : }
                               1481                 :                : 
                               1482                 :                : /*
                               1483                 :                :  * GinBufferStoreTuple
                               1484                 :                :  *      Add data (especially TID list) from a GIN tuple to the buffer.
                               1485                 :                :  *
                               1486                 :                :  * The buffer is expected to be empty (in which case it's initialized), or
                               1487                 :                :  * having the same key. The TID values from the tuple are combined with the
                               1488                 :                :  * stored values using a merge sort.
                               1489                 :                :  *
                               1490                 :                :  * The tuples (for the same key) are expected to be sorted by first TID. But
                               1491                 :                :  * this does not guarantee the lists do not overlap, especially in the leader,
                               1492                 :                :  * because the workers process interleaving data. There should be no overlaps
                               1493                 :                :  * in a single worker - it could happen when the parallel scan wraps around,
                               1494                 :                :  * but we detect that and flush the data (see ginBuildCallbackParallel).
                               1495                 :                :  *
                               1496                 :                :  * By sorting the GinTuple not only by key, but also by the first TID, we make
                               1497                 :                :  * it more less likely the lists will overlap during merge. We merge them using
                               1498                 :                :  * mergesort, but it's cheaper to just append one list to the other.
                               1499                 :                :  *
                               1500                 :                :  * How often can the lists overlap? There should be no overlaps in workers,
                               1501                 :                :  * and in the leader we can see overlaps between lists built by different
                               1502                 :                :  * workers. But the workers merge the items as much as possible, so there
                               1503                 :                :  * should not be too many.
                               1504                 :                :  */
                               1505                 :                : static void
  635 tomas.vondra@postgre     1506                 :CBC       49166 : GinBufferStoreTuple(GinBuffer *buffer, GinTuple *tup)
                               1507                 :                : {
                               1508                 :                :     ItemPointerData *items;
                               1509                 :                :     Datum       key;
                               1510                 :                : 
                               1511                 :          49166 :     AssertCheckGinBuffer(buffer);
                               1512                 :                : 
  634                          1513                 :          49166 :     key = _gin_parse_tuple_key(tup);
                               1514                 :          49166 :     items = _gin_parse_tuple_items(tup);
                               1515                 :                : 
                               1516                 :                :     /* if the buffer is empty, set the fields (and copy the key) */
  635                          1517         [ +  + ]:          49166 :     if (GinBufferIsEmpty(buffer))
                               1518                 :                :     {
                               1519                 :          39684 :         buffer->category = tup->category;
                               1520                 :          39684 :         buffer->keylen = tup->keylen;
                               1521                 :          39684 :         buffer->attnum = tup->attrnum;
                               1522                 :                : 
                               1523                 :          39684 :         buffer->typlen = tup->typlen;
                               1524                 :          39684 :         buffer->typbyval = tup->typbyval;
                               1525                 :                : 
                               1526         [ +  + ]:          39684 :         if (tup->category == GIN_CAT_NORM_KEY)
                               1527                 :          39643 :             buffer->key = datumCopy(key, buffer->typbyval, buffer->typlen);
                               1528                 :                :         else
                               1529                 :             41 :             buffer->key = (Datum) 0;
                               1530                 :                :     }
                               1531                 :                : 
                               1532                 :                :     /* add the new TIDs into the buffer, combine using merge-sort */
                               1533                 :                :     {
                               1534                 :                :         int         nnew;
                               1535                 :                :         ItemPointer new;
                               1536                 :                : 
                               1537                 :                :         /*
                               1538                 :                :          * Resize the array - we do this first, because we'll dereference the
                               1539                 :                :          * first unfrozen TID, which would fail if the array is NULL. We'll
                               1540                 :                :          * still pass 0 as number of elements in that array though.
                               1541                 :                :          */
  634                          1542         [ +  + ]:          49166 :         if (buffer->items == NULL)
  103 michael@paquier.xyz      1543                 :GNC          51 :             buffer->items = palloc_array(ItemPointerData, buffer->nitems + tup->nitems);
                               1544                 :                :         else
                               1545                 :          49115 :             buffer->items = repalloc_array(buffer->items,
                               1546                 :                :                                            ItemPointerData, buffer->nitems + tup->nitems);
                               1547                 :                : 
  588 michael@paquier.xyz      1548                 :CBC       49166 :         new = ginMergeItemPointers(&buffer->items[buffer->nfrozen], /* first unfrozen */
  634 tomas.vondra@postgre     1549                 :          49166 :                                    (buffer->nitems - buffer->nfrozen),    /* num of unfrozen */
  635                          1550                 :          49166 :                                    items, tup->nitems, &nnew);
                               1551                 :                : 
  634                          1552         [ -  + ]:          49166 :         Assert(nnew == (tup->nitems + (buffer->nitems - buffer->nfrozen)));
                               1553                 :                : 
                               1554                 :          49166 :         memcpy(&buffer->items[buffer->nfrozen], new,
                               1555                 :                :                nnew * sizeof(ItemPointerData));
                               1556                 :                : 
                               1557                 :          49166 :         pfree(new);
                               1558                 :                : 
                               1559                 :          49166 :         buffer->nitems += tup->nitems;
                               1560                 :                : 
  635                          1561                 :          49166 :         AssertCheckItemPointers(buffer);
                               1562                 :                :     }
                               1563                 :                : 
                               1564                 :                :     /* free the decompressed TID list */
  634                          1565                 :          49166 :     pfree(items);
  635                          1566                 :          49166 : }
                               1567                 :                : 
                               1568                 :                : /*
                               1569                 :                :  * GinBufferReset
                               1570                 :                :  *      Reset the buffer into a state as if it contains no data.
                               1571                 :                :  */
                               1572                 :                : static void
                               1573                 :          39684 : GinBufferReset(GinBuffer *buffer)
                               1574                 :                : {
                               1575         [ -  + ]:          39684 :     Assert(!GinBufferIsEmpty(buffer));
                               1576                 :                : 
                               1577                 :                :     /* release byref values, do nothing for by-val ones */
                               1578   [ +  +  +  + ]:          39684 :     if ((buffer->category == GIN_CAT_NORM_KEY) && !buffer->typbyval)
                               1579                 :          25851 :         pfree(DatumGetPointer(buffer->key));
                               1580                 :                : 
                               1581                 :                :     /*
                               1582                 :                :      * Not required, but makes it more likely to trigger NULL dereference if
                               1583                 :                :      * using the value incorrectly, etc.
                               1584                 :                :      */
                               1585                 :          39684 :     buffer->key = (Datum) 0;
                               1586                 :                : 
                               1587                 :          39684 :     buffer->attnum = 0;
                               1588                 :          39684 :     buffer->category = 0;
                               1589                 :          39684 :     buffer->keylen = 0;
                               1590                 :          39684 :     buffer->nitems = 0;
  634                          1591                 :          39684 :     buffer->nfrozen = 0;
                               1592                 :                : 
  635                          1593                 :          39684 :     buffer->typlen = 0;
                               1594                 :          39684 :     buffer->typbyval = 0;
                               1595                 :          39684 : }
                               1596                 :                : 
                               1597                 :                : /*
                               1598                 :                :  * GinBufferTrim
                               1599                 :                :  *      Discard the "frozen" part of the TID list (which should have been
                               1600                 :                :  *      written to disk/index before this call).
                               1601                 :                :  */
                               1602                 :                : static void
  634 tomas.vondra@postgre     1603                 :UBC           0 : GinBufferTrim(GinBuffer *buffer)
                               1604                 :                : {
                               1605   [ #  #  #  # ]:              0 :     Assert((buffer->nfrozen > 0) && (buffer->nfrozen <= buffer->nitems));
                               1606                 :                : 
                               1607                 :              0 :     memmove(&buffer->items[0], &buffer->items[buffer->nfrozen],
                               1608                 :              0 :             sizeof(ItemPointerData) * (buffer->nitems - buffer->nfrozen));
                               1609                 :                : 
                               1610                 :              0 :     buffer->nitems -= buffer->nfrozen;
                               1611                 :              0 :     buffer->nfrozen = 0;
                               1612                 :              0 : }
                               1613                 :                : 
                               1614                 :                : /*
                               1615                 :                :  * GinBufferFree
                               1616                 :                :  *      Release memory associated with the GinBuffer (including TID array).
                               1617                 :                :  */
                               1618                 :                : static void
  635 tomas.vondra@postgre     1619                 :CBC          71 : GinBufferFree(GinBuffer *buffer)
                               1620                 :                : {
                               1621         [ +  + ]:             71 :     if (buffer->items)
                               1622                 :             51 :         pfree(buffer->items);
                               1623                 :                : 
                               1624                 :                :     /* release byref values, do nothing for by-val ones */
                               1625         [ -  + ]:             71 :     if (!GinBufferIsEmpty(buffer) &&
  635 tomas.vondra@postgre     1626   [ #  #  #  # ]:UBC           0 :         (buffer->category == GIN_CAT_NORM_KEY) && !buffer->typbyval)
                               1627                 :              0 :         pfree(DatumGetPointer(buffer->key));
                               1628                 :                : 
  635 tomas.vondra@postgre     1629                 :CBC          71 :     pfree(buffer);
                               1630                 :             71 : }
                               1631                 :                : 
                               1632                 :                : /*
                               1633                 :                :  * GinBufferCanAddKey
                               1634                 :                :  *      Check if a given GIN tuple can be added to the current buffer.
                               1635                 :                :  *
                               1636                 :                :  * Returns true if the buffer is either empty or for the same index key.
                               1637                 :                :  */
                               1638                 :                : static bool
                               1639                 :          49166 : GinBufferCanAddKey(GinBuffer *buffer, GinTuple *tup)
                               1640                 :                : {
                               1641                 :                :     /* empty buffer can accept data for any key */
                               1642         [ +  + ]:          49166 :     if (GinBufferIsEmpty(buffer))
                               1643                 :             51 :         return true;
                               1644                 :                : 
                               1645                 :                :     /* otherwise just data for the same key */
                               1646                 :          49115 :     return GinBufferKeyEquals(buffer, tup);
                               1647                 :                : }
                               1648                 :                : 
                               1649                 :                : /*
                               1650                 :                :  * Wait for all participants to finish the heap scan, then merge their
                               1651                 :                :  * sorted GIN tuples in the leader.  Combine TID lists for the same index
                               1652                 :                :  * attribute, null category, and key, writing the TIDs to the index in
                               1653                 :                :  * batches.
                               1654                 :                :  *
                               1655                 :                :  * Return the total number of live heap tuples reported by the participants.
                               1656                 :                :  * Set indexInfo->ii_BrokenHotChain if any participant detected a potentially
                               1657                 :                :  * broken HOT chain.
                               1658                 :                :  */
                               1659                 :                : static double
    3                          1660                 :             18 : _gin_parallel_merge(GinBuildState *state, IndexInfo *indexInfo)
                               1661                 :                : {
                               1662                 :                :     GinTuple   *tup;
                               1663                 :                :     Size        tuplen;
  635                          1664                 :             18 :     double      reltuples = 0;
                               1665                 :                :     GinBuffer  *buffer;
                               1666                 :                : 
                               1667                 :                :     /* GIN tuples from workers, merged by leader */
                               1668                 :             18 :     double      numtuples = 0;
                               1669                 :                : 
                               1670                 :                :     /* wait for workers to scan table and produce partial results */
    3                          1671                 :             18 :     reltuples = _gin_parallel_heapscan(state, &indexInfo->ii_BrokenHotChain);
                               1672                 :                : 
                               1673                 :                :     /* Execute the sort */
  635                          1674                 :             18 :     pgstat_progress_update_param(PROGRESS_CREATEIDX_SUBPHASE,
                               1675                 :                :                                  PROGRESS_GIN_PHASE_PERFORMSORT_2);
                               1676                 :                : 
                               1677                 :                :     /* do the actual sort in the leader */
                               1678                 :             18 :     tuplesort_performsort(state->bs_sortstate);
                               1679                 :                : 
                               1680                 :                :     /*
                               1681                 :                :      * Initialize buffer to combine entries for the same key.
                               1682                 :                :      *
                               1683                 :                :      * The leader is allowed to use the whole maintenance_work_mem buffer to
                               1684                 :                :      * combine data. The parallel workers already completed.
                               1685                 :                :      */
                               1686                 :             18 :     buffer = GinBufferInit(state->ginstate.index);
                               1687                 :                : 
                               1688                 :                :     /*
                               1689                 :                :      * Set the progress target for the next phase.  Reset the block number
                               1690                 :                :      * values set by table_index_build_scan
                               1691                 :                :      */
                               1692                 :                :     {
                               1693                 :             18 :         const int   progress_index[] = {
                               1694                 :                :             PROGRESS_CREATEIDX_SUBPHASE,
                               1695                 :                :             PROGRESS_CREATEIDX_TUPLES_TOTAL,
                               1696                 :                :             PROGRESS_SCAN_BLOCKS_TOTAL,
                               1697                 :                :             PROGRESS_SCAN_BLOCKS_DONE
                               1698                 :                :         };
                               1699                 :             18 :         const int64 progress_vals[] = {
                               1700                 :                :             PROGRESS_GIN_PHASE_MERGE_2,
                               1701                 :             18 :             state->bs_numtuples,
                               1702                 :                :             0, 0
                               1703                 :                :         };
                               1704                 :                : 
                               1705                 :             18 :         pgstat_progress_update_multi_param(4, progress_index, progress_vals);
                               1706                 :                :     }
                               1707                 :                : 
                               1708                 :                :     /*
                               1709                 :                :      * Read the GIN tuples from the shared tuplesort, sorted by category and
                               1710                 :                :      * key. That probably gives us order matching how data is organized in the
                               1711                 :                :      * index.
                               1712                 :                :      *
                               1713                 :                :      * We don't insert the GIN tuples right away, but instead accumulate as
                               1714                 :                :      * many TIDs for the same key as possible, and then insert that at once.
                               1715                 :                :      * This way we don't need to decompress/recompress the posting lists, etc.
                               1716                 :                :      */
                               1717         [ +  + ]:          24601 :     while ((tup = tuplesort_getgintuple(state->bs_sortstate, &tuplen, true)) != NULL)
                               1718                 :                :     {
                               1719                 :                :         MemoryContext oldCtx;
                               1720                 :                : 
                               1721         [ -  + ]:          24583 :         CHECK_FOR_INTERRUPTS();
                               1722                 :                : 
                               1723                 :                :         /*
                               1724                 :                :          * If the buffer can accept the new GIN tuple, just store it there and
                               1725                 :                :          * we're done. If it's a different key (or maybe too much data) flush
                               1726                 :                :          * the current contents into the index first.
                               1727                 :                :          */
                               1728         [ +  + ]:          24583 :         if (!GinBufferCanAddKey(buffer, tup))
                               1729                 :                :         {
                               1730                 :                :             /*
                               1731                 :                :              * Buffer is not empty and it's storing a different key - flush
                               1732                 :                :              * the data into the insert, and start a new entry for current
                               1733                 :                :              * GinTuple.
                               1734                 :                :              */
                               1735                 :          15084 :             AssertCheckItemPointers(buffer);
                               1736                 :                : 
  575                          1737                 :          15084 :             oldCtx = MemoryContextSwitchTo(state->tmpCtx);
                               1738                 :                : 
  635                          1739                 :          15084 :             ginEntryInsert(&state->ginstate,
                               1740                 :          15084 :                            buffer->attnum, buffer->key, buffer->category,
                               1741                 :          15084 :                            buffer->items, buffer->nitems, &state->buildStats);
                               1742                 :                : 
  575                          1743                 :          15084 :             MemoryContextSwitchTo(oldCtx);
                               1744                 :          15084 :             MemoryContextReset(state->tmpCtx);
                               1745                 :                : 
                               1746                 :                :             /* discard the existing data */
  635                          1747                 :          15084 :             GinBufferReset(buffer);
                               1748                 :                :         }
                               1749                 :                : 
                               1750                 :                :         /*
                               1751                 :                :          * We're about to add a GIN tuple to the buffer - check the memory
                               1752                 :                :          * limit first, and maybe write out some of the data into the index
                               1753                 :                :          * first, if needed (and possible). We only flush the part of the TID
                               1754                 :                :          * list that we know won't change, and only if there's enough data for
                               1755                 :                :          * compression to work well.
                               1756                 :                :          */
  634                          1757         [ -  + ]:          24583 :         if (GinBufferShouldTrim(buffer, tup))
                               1758                 :                :         {
  634 tomas.vondra@postgre     1759         [ #  # ]:UBC           0 :             Assert(buffer->nfrozen > 0);
                               1760                 :                : 
                               1761                 :                :             /*
                               1762                 :                :              * Buffer is not empty and it's storing a different key - flush
                               1763                 :                :              * the data into the insert, and start a new entry for current
                               1764                 :                :              * GinTuple.
                               1765                 :                :              */
                               1766                 :              0 :             AssertCheckItemPointers(buffer);
                               1767                 :                : 
  575                          1768                 :              0 :             oldCtx = MemoryContextSwitchTo(state->tmpCtx);
                               1769                 :                : 
  634                          1770                 :              0 :             ginEntryInsert(&state->ginstate,
                               1771                 :              0 :                            buffer->attnum, buffer->key, buffer->category,
                               1772                 :              0 :                            buffer->items, buffer->nfrozen, &state->buildStats);
                               1773                 :                : 
  575                          1774                 :              0 :             MemoryContextSwitchTo(oldCtx);
                               1775                 :              0 :             MemoryContextReset(state->tmpCtx);
                               1776                 :                : 
                               1777                 :                :             /* truncate the data we've just discarded */
  634                          1778                 :              0 :             GinBufferTrim(buffer);
                               1779                 :                :         }
                               1780                 :                : 
                               1781                 :                :         /*
                               1782                 :                :          * Remember data for the current tuple (either remember the new key,
                               1783                 :                :          * or append if to the existing data).
                               1784                 :                :          */
  635 tomas.vondra@postgre     1785                 :CBC       24583 :         GinBufferStoreTuple(buffer, tup);
                               1786                 :                : 
                               1787                 :                :         /* Report progress */
                               1788                 :          24583 :         pgstat_progress_update_param(PROGRESS_CREATEIDX_TUPLES_DONE,
                               1789                 :                :                                      ++numtuples);
                               1790                 :                :     }
                               1791                 :                : 
                               1792                 :                :     /* flush data remaining in the buffer (for the last key) */
                               1793         [ +  + ]:             18 :     if (!GinBufferIsEmpty(buffer))
                               1794                 :                :     {
                               1795                 :             17 :         AssertCheckItemPointers(buffer);
                               1796                 :                : 
                               1797                 :             17 :         ginEntryInsert(&state->ginstate,
                               1798                 :             17 :                        buffer->attnum, buffer->key, buffer->category,
                               1799                 :             17 :                        buffer->items, buffer->nitems, &state->buildStats);
                               1800                 :                : 
                               1801                 :                :         /* discard the existing data */
                               1802                 :             17 :         GinBufferReset(buffer);
                               1803                 :                :     }
                               1804                 :                : 
                               1805                 :                :     /* release all the memory */
                               1806                 :             18 :     GinBufferFree(buffer);
                               1807                 :                : 
                               1808                 :             18 :     tuplesort_end(state->bs_sortstate);
                               1809                 :                : 
                               1810                 :             18 :     return reltuples;
                               1811                 :                : }
                               1812                 :                : 
                               1813                 :                : /*
                               1814                 :                :  * Returns size of shared memory required to store state for a parallel
                               1815                 :                :  * gin index build based on the snapshot its parallel scan will use.
                               1816                 :                :  */
                               1817                 :                : static Size
                               1818                 :             18 : _gin_parallel_estimate_shared(Relation heap, Snapshot snapshot)
                               1819                 :                : {
                               1820                 :                :     /* c.f. shm_toc_allocate as to why BUFFERALIGN is used */
                               1821                 :             18 :     return add_size(BUFFERALIGN(sizeof(GinBuildShared)),
                               1822                 :                :                     table_parallelscan_estimate(heap, snapshot));
                               1823                 :                : }
                               1824                 :                : 
                               1825                 :                : /*
                               1826                 :                :  * Within leader, participate as a parallel worker.
                               1827                 :                :  */
                               1828                 :                : static void
                               1829                 :             18 : _gin_leader_participate_as_worker(GinBuildState *buildstate, Relation heap, Relation index)
                               1830                 :                : {
                               1831                 :             18 :     GinLeader  *ginleader = buildstate->bs_leader;
                               1832                 :                :     int         sortmem;
                               1833                 :                : 
                               1834                 :                :     /*
                               1835                 :                :      * Might as well use reliable figure when doling out maintenance_work_mem
                               1836                 :                :      * (when requested number of workers were not launched, this will be
                               1837                 :                :      * somewhat higher than it is for other workers).
                               1838                 :                :      */
                               1839                 :             18 :     sortmem = maintenance_work_mem / ginleader->nparticipanttuplesorts;
                               1840                 :                : 
                               1841                 :                :     /* Perform work common to all participants */
                               1842                 :             18 :     _gin_parallel_scan_and_build(buildstate, ginleader->ginshared,
                               1843                 :                :                                  ginleader->sharedsort, heap, index,
                               1844                 :                :                                  sortmem, true);
                               1845                 :             18 : }
                               1846                 :                : 
                               1847                 :                : /*
                               1848                 :                :  * _gin_process_worker_data
                               1849                 :                :  *      First phase of the key merging, happening in the worker.
                               1850                 :                :  *
                               1851                 :                :  * Depending on the number of distinct keys, the TID lists produced by the
                               1852                 :                :  * callback may be very short (due to frequent evictions in the callback).
                               1853                 :                :  * But combining many tiny lists is expensive, so we try to do as much as
                               1854                 :                :  * possible in the workers and only then pass the results to the leader.
                               1855                 :                :  *
                               1856                 :                :  * We read the tuples sorted by the key, and merge them into larger lists.
                               1857                 :                :  * At the moment there's no memory limit, so this will just produce one
                               1858                 :                :  * huge (sorted) list per key in each worker. Which means the leader will
                               1859                 :                :  * do a very limited number of mergesorts, which is good.
                               1860                 :                :  */
                               1861                 :                : static void
                               1862                 :             53 : _gin_process_worker_data(GinBuildState *state, Tuplesortstate *worker_sort,
                               1863                 :                :                          bool progress)
                               1864                 :                : {
                               1865                 :                :     GinTuple   *tup;
                               1866                 :                :     Size        tuplen;
                               1867                 :                : 
                               1868                 :                :     GinBuffer  *buffer;
                               1869                 :                : 
                               1870                 :                :     /*
                               1871                 :                :      * Initialize buffer to combine entries for the same key.
                               1872                 :                :      *
                               1873                 :                :      * The workers are limited to the same amount of memory as during the sort
                               1874                 :                :      * in ginBuildCallbackParallel. But this probably should be the 32MB used
                               1875                 :                :      * during planning, just like there.
                               1876                 :                :      */
                               1877                 :             53 :     buffer = GinBufferInit(state->ginstate.index);
                               1878                 :                : 
                               1879                 :                :     /* sort the raw per-worker data */
                               1880         [ +  + ]:             53 :     if (progress)
                               1881                 :             18 :         pgstat_progress_update_param(PROGRESS_CREATEIDX_SUBPHASE,
                               1882                 :                :                                      PROGRESS_GIN_PHASE_PERFORMSORT_1);
                               1883                 :                : 
                               1884                 :             53 :     tuplesort_performsort(state->bs_worker_sort);
                               1885                 :                : 
                               1886         [ +  + ]:             53 :     if (progress)
                               1887                 :             18 :         pgstat_progress_update_param(PROGRESS_CREATEIDX_SUBPHASE,
                               1888                 :                :                                      PROGRESS_GIN_PHASE_MERGE_1);
                               1889                 :                : 
                               1890                 :                :     /*
                               1891                 :                :      * Read the GIN tuples from the shared tuplesort, sorted by the key, and
                               1892                 :                :      * merge them into larger chunks for the leader to combine.
                               1893                 :                :      */
                               1894         [ +  + ]:          24636 :     while ((tup = tuplesort_getgintuple(worker_sort, &tuplen, true)) != NULL)
                               1895                 :                :     {
                               1896                 :                : 
                               1897         [ +  + ]:          24583 :         CHECK_FOR_INTERRUPTS();
                               1898                 :                : 
                               1899                 :                :         /*
                               1900                 :                :          * If the buffer can accept the new GIN tuple, just store it there and
                               1901                 :                :          * we're done. If it's a different key (or maybe too much data) flush
                               1902                 :                :          * the current contents into the index first.
                               1903                 :                :          */
                               1904         [ +  + ]:          24583 :         if (!GinBufferCanAddKey(buffer, tup))
                               1905                 :                :         {
                               1906                 :                :             GinTuple   *ntup;
                               1907                 :                :             Size        ntuplen;
                               1908                 :                : 
                               1909                 :                :             /*
                               1910                 :                :              * Buffer is not empty and it's storing a different key - flush
                               1911                 :                :              * the data into the insert, and start a new entry for current
                               1912                 :                :              * GinTuple.
                               1913                 :                :              */
                               1914                 :          24549 :             AssertCheckItemPointers(buffer);
                               1915                 :                : 
                               1916                 :          24549 :             ntup = _gin_build_tuple(buffer->attnum, buffer->category,
                               1917                 :          24549 :                                     buffer->key, buffer->typlen, buffer->typbyval,
                               1918                 :          24549 :                                     buffer->items, buffer->nitems, &ntuplen);
                               1919                 :                : 
                               1920                 :          24549 :             tuplesort_putgintuple(state->bs_sortstate, ntup, ntuplen);
                               1921                 :          24549 :             state->bs_numtuples++;
                               1922                 :                : 
                               1923                 :          24549 :             pfree(ntup);
                               1924                 :                : 
                               1925                 :                :             /* discard the existing data */
                               1926                 :          24549 :             GinBufferReset(buffer);
                               1927                 :                :         }
                               1928                 :                : 
                               1929                 :                :         /*
                               1930                 :                :          * We're about to add a GIN tuple to the buffer - check the memory
                               1931                 :                :          * limit first, and maybe write out some of the data into the index
                               1932                 :                :          * first, if needed (and possible). We only flush the part of the TID
                               1933                 :                :          * list that we know won't change, and only if there's enough data for
                               1934                 :                :          * compression to work well.
                               1935                 :                :          */
  634                          1936         [ -  + ]:          24583 :         if (GinBufferShouldTrim(buffer, tup))
                               1937                 :                :         {
                               1938                 :                :             GinTuple   *ntup;
                               1939                 :                :             Size        ntuplen;
                               1940                 :                : 
  634 tomas.vondra@postgre     1941         [ #  # ]:UBC           0 :             Assert(buffer->nfrozen > 0);
                               1942                 :                : 
                               1943                 :                :             /*
                               1944                 :                :              * Buffer is not empty and it's storing a different key - flush
                               1945                 :                :              * the data into the insert, and start a new entry for current
                               1946                 :                :              * GinTuple.
                               1947                 :                :              */
                               1948                 :              0 :             AssertCheckItemPointers(buffer);
                               1949                 :                : 
                               1950                 :              0 :             ntup = _gin_build_tuple(buffer->attnum, buffer->category,
                               1951                 :              0 :                                     buffer->key, buffer->typlen, buffer->typbyval,
                               1952                 :              0 :                                     buffer->items, buffer->nfrozen, &ntuplen);
                               1953                 :                : 
                               1954                 :              0 :             tuplesort_putgintuple(state->bs_sortstate, ntup, ntuplen);
   53 michael@paquier.xyz      1955                 :UNC           0 :             state->bs_numtuples++;
                               1956                 :                : 
  634 tomas.vondra@postgre     1957                 :UBC           0 :             pfree(ntup);
                               1958                 :                : 
                               1959                 :                :             /* truncate the data we've just discarded */
                               1960                 :              0 :             GinBufferTrim(buffer);
                               1961                 :                :         }
                               1962                 :                : 
                               1963                 :                :         /*
                               1964                 :                :          * Remember data for the current tuple (either remember the new key,
                               1965                 :                :          * or append if to the existing data).
                               1966                 :                :          */
  635 tomas.vondra@postgre     1967                 :CBC       24583 :         GinBufferStoreTuple(buffer, tup);
                               1968                 :                :     }
                               1969                 :                : 
                               1970                 :                :     /* flush data remaining in the buffer (for the last key) */
                               1971         [ +  + ]:             53 :     if (!GinBufferIsEmpty(buffer))
                               1972                 :                :     {
                               1973                 :                :         GinTuple   *ntup;
                               1974                 :                :         Size        ntuplen;
                               1975                 :                : 
                               1976                 :             34 :         AssertCheckItemPointers(buffer);
                               1977                 :                : 
                               1978                 :             34 :         ntup = _gin_build_tuple(buffer->attnum, buffer->category,
                               1979                 :             34 :                                 buffer->key, buffer->typlen, buffer->typbyval,
                               1980                 :             34 :                                 buffer->items, buffer->nitems, &ntuplen);
                               1981                 :                : 
                               1982                 :             34 :         tuplesort_putgintuple(state->bs_sortstate, ntup, ntuplen);
                               1983                 :             34 :         state->bs_numtuples++;
                               1984                 :                : 
                               1985                 :             34 :         pfree(ntup);
                               1986                 :                : 
                               1987                 :                :         /* discard the existing data */
                               1988                 :             34 :         GinBufferReset(buffer);
                               1989                 :                :     }
                               1990                 :                : 
                               1991                 :                :     /* release all the memory */
                               1992                 :             53 :     GinBufferFree(buffer);
                               1993                 :                : 
                               1994                 :             53 :     tuplesort_end(worker_sort);
                               1995                 :             53 : }
                               1996                 :                : 
                               1997                 :                : /*
                               1998                 :                :  * Perform a worker's portion of a parallel GIN index build sort.
                               1999                 :                :  *
                               2000                 :                :  * This generates a tuplesort for the worker portion of the table.
                               2001                 :                :  *
                               2002                 :                :  * sortmem is the amount of working memory to use within each worker,
                               2003                 :                :  * expressed in KBs.
                               2004                 :                :  *
                               2005                 :                :  * When this returns, workers are done, and need only release resources.
                               2006                 :                :  *
                               2007                 :                :  * Before feeding data into a shared tuplesort (for the leader process),
                               2008                 :                :  * the workers process data in two phases.
                               2009                 :                :  *
                               2010                 :                :  * 1) A worker reads a portion of rows from the table, accumulates entries
                               2011                 :                :  * in memory, and flushes them into a private tuplesort (e.g. because of
                               2012                 :                :  * using too much memory).
                               2013                 :                :  *
                               2014                 :                :  * 2) The private tuplesort gets sorted (by key and TID), the worker reads
                               2015                 :                :  * the data again, and combines the entries as much as possible. This has
                               2016                 :                :  * to happen eventually, and this way it's done in workers in parallel.
                               2017                 :                :  *
                               2018                 :                :  * Finally, the combined entries are written into the shared tuplesort, so
                               2019                 :                :  * that the leader can process them.
                               2020                 :                :  *
                               2021                 :                :  * How well this works (compared to just writing entries into the shared
                               2022                 :                :  * tuplesort) depends on the data set. For large tables with many distinct
                               2023                 :                :  * keys this helps a lot. With many distinct keys it's likely the buffers has
                               2024                 :                :  * to be flushed often, generating many entries with the same key and short
                               2025                 :                :  * TID lists. These entries need to be sorted and merged at some point,
                               2026                 :                :  * before writing them to the index. The merging is quite expensive, it can
                               2027                 :                :  * easily be ~50% of a serial build, and doing as much of it in the workers
                               2028                 :                :  * means it's parallelized. The leader still has to merge results from the
                               2029                 :                :  * workers, but it's much more efficient to merge few large entries than
                               2030                 :                :  * many tiny ones.
                               2031                 :                :  *
                               2032                 :                :  * This also reduces the amount of data the workers pass to the leader through
                               2033                 :                :  * the shared tuplesort. OTOH the workers need more space for the private sort,
                               2034                 :                :  * possibly up to 2x of the data, if no entries be merged in a worker. But this
                               2035                 :                :  * is very unlikely, and the only consequence is inefficiency, so we ignore it.
                               2036                 :                :  */
                               2037                 :                : static void
                               2038                 :             53 : _gin_parallel_scan_and_build(GinBuildState *state,
                               2039                 :                :                              GinBuildShared *ginshared, Sharedsort *sharedsort,
                               2040                 :                :                              Relation heap, Relation index,
                               2041                 :                :                              int sortmem, bool progress)
                               2042                 :                : {
                               2043                 :                :     SortCoordinate coordinate;
                               2044                 :                :     TableScanDesc scan;
                               2045                 :                :     double      reltuples;
                               2046                 :                :     IndexInfo  *indexInfo;
                               2047                 :                : 
                               2048                 :                :     /* Initialize local tuplesort coordination state */
  353 michael@paquier.xyz      2049                 :             53 :     coordinate = palloc0_object(SortCoordinateData);
  635 tomas.vondra@postgre     2050                 :             53 :     coordinate->isWorker = true;
                               2051                 :             53 :     coordinate->nParticipants = -1;
                               2052                 :             53 :     coordinate->sharedsort = sharedsort;
                               2053                 :                : 
                               2054                 :                :     /* remember how much space is allowed for the accumulated entries */
                               2055                 :             53 :     state->work_mem = (sortmem / 2);
                               2056                 :                : 
                               2057                 :                :     /* remember how many workers participate in the build */
  389                          2058                 :             53 :     state->bs_num_workers = ginshared->scantuplesortstates;
                               2059                 :                : 
                               2060                 :                :     /* Begin "partial" tuplesort */
  635                          2061                 :             53 :     state->bs_sortstate = tuplesort_begin_index_gin(heap, index,
                               2062                 :                :                                                     state->work_mem,
                               2063                 :                :                                                     coordinate,
                               2064                 :                :                                                     TUPLESORT_NONE);
                               2065                 :                : 
                               2066                 :                :     /* Local per-worker sort of raw-data */
                               2067                 :             53 :     state->bs_worker_sort = tuplesort_begin_index_gin(heap, index,
                               2068                 :                :                                                       state->work_mem,
                               2069                 :                :                                                       NULL,
                               2070                 :                :                                                       TUPLESORT_NONE);
                               2071                 :                : 
                               2072                 :                :     /* Join parallel scan */
                               2073                 :             53 :     indexInfo = BuildIndexInfo(index);
                               2074                 :             53 :     indexInfo->ii_Concurrent = ginshared->isconcurrent;
                               2075                 :                : 
                               2076                 :             53 :     scan = table_beginscan_parallel(heap,
                               2077                 :                :                                     ParallelTableScanFromGinBuildShared(ginshared),
                               2078                 :                :                                     SO_NONE);
                               2079                 :                : 
                               2080                 :             53 :     reltuples = table_index_build_scan(heap, index, indexInfo, true, progress,
                               2081                 :                :                                        ginBuildCallbackParallel, state, scan);
                               2082                 :                : 
                               2083                 :                :     /* write remaining accumulated entries */
                               2084                 :             53 :     ginFlushBuildState(state, index);
                               2085                 :                : 
                               2086                 :                :     /*
                               2087                 :                :      * Do the first phase of in-worker processing - sort the data produced by
                               2088                 :                :      * the callback, and combine them into much larger chunks and place that
                               2089                 :                :      * into the shared tuplestore for leader to process.
                               2090                 :                :      */
                               2091                 :             53 :     _gin_process_worker_data(state, state->bs_worker_sort, progress);
                               2092                 :                : 
                               2093                 :                :     /* sort the GIN tuples built by this worker */
                               2094                 :             53 :     tuplesort_performsort(state->bs_sortstate);
                               2095                 :                : 
                               2096                 :             53 :     state->bs_reltuples += reltuples;
                               2097                 :                : 
                               2098                 :                :     /*
                               2099                 :                :      * Done.  Record ambuild statistics, and whether we encountered a broken
                               2100                 :                :      * HOT chain.
                               2101                 :                :      */
                               2102                 :             53 :     SpinLockAcquire(&ginshared->mutex);
                               2103                 :             53 :     ginshared->nparticipantsdone++;
                               2104                 :             53 :     ginshared->reltuples += state->bs_reltuples;
                               2105                 :             53 :     ginshared->indtuples += state->bs_numtuples;
    3                          2106         [ +  + ]:             53 :     if (indexInfo->ii_BrokenHotChain)
                               2107                 :              1 :         ginshared->brokenhotchain = true;
  635                          2108                 :             53 :     SpinLockRelease(&ginshared->mutex);
                               2109                 :                : 
                               2110                 :                :     /* Notify leader */
                               2111                 :             53 :     ConditionVariableSignal(&ginshared->workersdonecv);
                               2112                 :                : 
                               2113                 :             53 :     tuplesort_end(state->bs_sortstate);
                               2114                 :             53 : }
                               2115                 :                : 
                               2116                 :                : /*
                               2117                 :                :  * Perform work within a launched parallel process.
                               2118                 :                :  */
                               2119                 :                : void
                               2120                 :             35 : _gin_parallel_build_main(dsm_segment *seg, shm_toc *toc)
                               2121                 :                : {
                               2122                 :                :     char       *sharedquery;
                               2123                 :                :     GinBuildShared *ginshared;
                               2124                 :                :     Sharedsort *sharedsort;
                               2125                 :                :     GinBuildState buildstate;
                               2126                 :                :     Relation    heapRel;
                               2127                 :                :     Relation    indexRel;
                               2128                 :                :     LOCKMODE    heapLockmode;
                               2129                 :                :     LOCKMODE    indexLockmode;
                               2130                 :                :     WalUsage   *walusage;
                               2131                 :                :     BufferUsage *bufferusage;
                               2132                 :                :     int         sortmem;
                               2133                 :                : 
                               2134                 :                :     /*
                               2135                 :                :      * The only possible status flag that can be set to the parallel worker is
                               2136                 :                :      * PROC_IN_SAFE_IC.
                               2137                 :                :      */
                               2138   [ +  +  -  + ]:             35 :     Assert((MyProc->statusFlags == 0) ||
                               2139                 :                :            (MyProc->statusFlags == PROC_IN_SAFE_IC));
                               2140                 :                : 
                               2141                 :                :     /* Set debug_query_string for individual workers first */
                               2142                 :             35 :     sharedquery = shm_toc_lookup(toc, PARALLEL_KEY_QUERY_TEXT, true);
                               2143                 :             35 :     debug_query_string = sharedquery;
                               2144                 :                : 
                               2145                 :                :     /* Report the query string from leader */
                               2146                 :             35 :     pgstat_report_activity(STATE_RUNNING, debug_query_string);
                               2147                 :                : 
                               2148                 :                :     /* Look up gin shared state */
                               2149                 :             35 :     ginshared = shm_toc_lookup(toc, PARALLEL_KEY_GIN_SHARED, false);
                               2150                 :                : 
                               2151                 :                :     /* Open relations using lock modes known to be obtained by index.c */
                               2152         [ +  + ]:             35 :     if (!ginshared->isconcurrent)
                               2153                 :                :     {
                               2154                 :             27 :         heapLockmode = ShareLock;
                               2155                 :             27 :         indexLockmode = AccessExclusiveLock;
                               2156                 :                :     }
                               2157                 :                :     else
                               2158                 :                :     {
                               2159                 :              8 :         heapLockmode = ShareUpdateExclusiveLock;
                               2160                 :              8 :         indexLockmode = RowExclusiveLock;
                               2161                 :                :     }
                               2162                 :                : 
                               2163                 :                :     /* Track query ID */
    2 tomas.vondra@postgre     2164                 :GNC          35 :     pgstat_report_query_id(ginshared->queryid, false);
                               2165                 :                : 
                               2166                 :                :     /* Open relations within worker */
  635 tomas.vondra@postgre     2167                 :CBC          35 :     heapRel = table_open(ginshared->heaprelid, heapLockmode);
                               2168                 :             35 :     indexRel = index_open(ginshared->indexrelid, indexLockmode);
                               2169                 :                : 
                               2170                 :                :     /* initialize the GIN build state */
                               2171                 :             35 :     initGinState(&buildstate.ginstate, indexRel);
                               2172                 :             35 :     buildstate.indtuples = 0;
                               2173                 :                : 
                               2174                 :                :     /* Initialize counters used to report tuple counts to the leader */
  121                          2175                 :             35 :     buildstate.bs_numtuples = 0;
                               2176                 :             35 :     buildstate.bs_reltuples = 0;
                               2177                 :                : 
  635                          2178                 :             35 :     memset(&buildstate.buildStats, 0, sizeof(GinStatsData));
                               2179                 :             35 :     memset(&buildstate.tid, 0, sizeof(ItemPointerData));
                               2180                 :                : 
                               2181                 :                :     /*
                               2182                 :                :      * create a temporary memory context that is used to hold data not yet
                               2183                 :                :      * dumped out to the index
                               2184                 :                :      */
                               2185                 :             35 :     buildstate.tmpCtx = AllocSetContextCreate(CurrentMemoryContext,
                               2186                 :                :                                               "Gin build temporary context",
                               2187                 :                :                                               ALLOCSET_DEFAULT_SIZES);
                               2188                 :                : 
                               2189                 :                :     /*
                               2190                 :                :      * create a temporary memory context that is used for calling
                               2191                 :                :      * ginExtractEntries(), and can be reset after each tuple
                               2192                 :                :      */
                               2193                 :             35 :     buildstate.funcCtx = AllocSetContextCreate(CurrentMemoryContext,
                               2194                 :                :                                                "Gin build temporary context for user-defined function",
                               2195                 :                :                                                ALLOCSET_DEFAULT_SIZES);
                               2196                 :                : 
                               2197                 :             35 :     buildstate.accum.ginstate = &buildstate.ginstate;
                               2198                 :             35 :     ginInitBA(&buildstate.accum);
                               2199                 :                : 
                               2200                 :                : 
                               2201                 :                :     /* Look up shared state private to tuplesort.c */
                               2202                 :             35 :     sharedsort = shm_toc_lookup(toc, PARALLEL_KEY_TUPLESORT, false);
                               2203                 :             35 :     tuplesort_attach_shared(sharedsort, seg);
                               2204                 :                : 
                               2205                 :                :     /* Prepare to track buffer usage during parallel execution */
                               2206                 :             35 :     InstrStartParallelQuery();
                               2207                 :                : 
                               2208                 :                :     /*
                               2209                 :                :      * Might as well use reliable figure when doling out maintenance_work_mem
                               2210                 :                :      * (when requested number of workers were not launched, this will be
                               2211                 :                :      * somewhat higher than it is for other workers).
                               2212                 :                :      */
                               2213                 :             35 :     sortmem = maintenance_work_mem / ginshared->scantuplesortstates;
                               2214                 :                : 
                               2215                 :             35 :     _gin_parallel_scan_and_build(&buildstate, ginshared, sharedsort,
                               2216                 :                :                                  heapRel, indexRel, sortmem, false);
                               2217                 :                : 
                               2218                 :                :     /* Report WAL/buffer usage during parallel execution */
                               2219                 :             35 :     bufferusage = shm_toc_lookup(toc, PARALLEL_KEY_BUFFER_USAGE, false);
                               2220                 :             35 :     walusage = shm_toc_lookup(toc, PARALLEL_KEY_WAL_USAGE, false);
                               2221                 :             35 :     InstrEndParallelQuery(&bufferusage[ParallelWorkerNumber],
                               2222                 :             35 :                           &walusage[ParallelWorkerNumber]);
                               2223                 :                : 
                               2224                 :             35 :     index_close(indexRel, indexLockmode);
                               2225                 :             35 :     table_close(heapRel, heapLockmode);
                               2226                 :             35 : }
                               2227                 :                : 
                               2228                 :                : /*
                               2229                 :                :  * Used to keep track of compressed TID lists when building a GIN tuple.
                               2230                 :                :  */
                               2231                 :                : typedef struct
                               2232                 :                : {
                               2233                 :                :     dlist_node  node;           /* linked list pointers */
                               2234                 :                :     GinPostingList *seg;
                               2235                 :                : } GinSegmentInfo;
                               2236                 :                : 
                               2237                 :                : /*
                               2238                 :                :  * _gin_build_tuple
                               2239                 :                :  *      Serialize the state for an index key into a tuple for tuplesort.
                               2240                 :                :  *
                               2241                 :                :  * The tuple has a number of scalar fields (mostly matching the build state),
                               2242                 :                :  * and then a data array that stores the key first, and then the TID list.
                               2243                 :                :  *
                               2244                 :                :  * For by-reference data types, we store the actual data. For by-val types
                               2245                 :                :  * we simply copy the whole Datum, so that we don't have to care about stuff
                               2246                 :                :  * like endianness etc. We could make it a little bit smaller, but it's not
                               2247                 :                :  * worth it - it's a tiny fraction of the data, and we need to MAXALIGN the
                               2248                 :                :  * start of the TID list anyway. So we wouldn't save anything. (This would
                               2249                 :                :  * not be a good idea for the permanent in-index data, since we'd prefer
                               2250                 :                :  * that that not depend on sizeof(Datum). But this is just a transient
                               2251                 :                :  * representation to use while sorting the data.)
                               2252                 :                :  *
                               2253                 :                :  * The TID list is serialized as compressed - it's highly compressible, and
                               2254                 :                :  * we already have ginCompressPostingList for this purpose. The list may be
                               2255                 :                :  * pretty long, so we compress it into multiple segments and then copy all
                               2256                 :                :  * of that into the GIN tuple.
                               2257                 :                :  */
                               2258                 :                : static GinTuple *
                               2259                 :          49166 : _gin_build_tuple(OffsetNumber attrnum, unsigned char category,
                               2260                 :                :                  Datum key, int16 typlen, bool typbyval,
                               2261                 :                :                  ItemPointerData *items, uint32 nitems,
                               2262                 :                :                  Size *len)
                               2263                 :                : {
                               2264                 :                :     GinTuple   *tuple;
                               2265                 :                :     char       *ptr;
                               2266                 :                : 
                               2267                 :                :     Size        tuplen;
                               2268                 :                :     Size        keylen;
                               2269                 :                : 
                               2270                 :                :     dlist_mutable_iter iter;
                               2271                 :                :     dlist_head  segments;
                               2272                 :                :     int         ncompressed;
                               2273                 :                :     Size        compresslen;
                               2274                 :                : 
                               2275                 :                :     /*
                               2276                 :                :      * Calculate how long is the key value. Only keys with GIN_CAT_NORM_KEY
                               2277                 :                :      * have actual non-empty key. We include varlena headers and \0 bytes for
                               2278                 :                :      * strings, to make it easier to access the data in-line.
                               2279                 :                :      *
                               2280                 :                :      * For byval types we simply copy the whole Datum. We could store just the
                               2281                 :                :      * necessary bytes, but this is simpler to work with and not worth the
                               2282                 :                :      * extra complexity. Moreover we still need to do the MAXALIGN to allow
                               2283                 :                :      * direct access to items pointers.
                               2284                 :                :      *
                               2285                 :                :      * XXX Note that for byval types we store the whole datum, no matter what
                               2286                 :                :      * the typlen value is.
                               2287                 :                :      */
                               2288         [ +  + ]:          49166 :     if (category != GIN_CAT_NORM_KEY)
                               2289                 :             50 :         keylen = 0;
                               2290         [ +  + ]:          49116 :     else if (typbyval)
                               2291                 :          14278 :         keylen = sizeof(Datum);
                               2292         [ -  + ]:          34838 :     else if (typlen > 0)
  635 tomas.vondra@postgre     2293                 :UBC           0 :         keylen = typlen;
  635 tomas.vondra@postgre     2294         [ +  - ]:CBC       34838 :     else if (typlen == -1)
  480 peter@eisentraut.org     2295                 :          34838 :         keylen = VARSIZE_ANY(DatumGetPointer(key));
  635 tomas.vondra@postgre     2296         [ #  # ]:UBC           0 :     else if (typlen == -2)
                               2297                 :              0 :         keylen = strlen(DatumGetPointer(key)) + 1;
                               2298                 :                :     else
                               2299         [ #  # ]:              0 :         elog(ERROR, "unexpected typlen value (%d)", typlen);
                               2300                 :                : 
                               2301                 :                :     /* compress the item pointers */
  634 tomas.vondra@postgre     2302                 :CBC       49166 :     ncompressed = 0;
                               2303                 :          49166 :     compresslen = 0;
                               2304                 :          49166 :     dlist_init(&segments);
                               2305                 :                : 
                               2306                 :                :     /* generate compressed segments of TID list chunks */
                               2307         [ +  + ]:          98332 :     while (ncompressed < nitems)
                               2308                 :                :     {
                               2309                 :                :         int         cnt;
  353 michael@paquier.xyz      2310                 :          49166 :         GinSegmentInfo *seginfo = palloc_object(GinSegmentInfo);
                               2311                 :                : 
  634 tomas.vondra@postgre     2312                 :          98332 :         seginfo->seg = ginCompressPostingList(&items[ncompressed],
                               2313                 :          49166 :                                               (nitems - ncompressed),
                               2314                 :                :                                               UINT16_MAX,
                               2315                 :                :                                               &cnt);
                               2316                 :                : 
                               2317                 :          49166 :         ncompressed += cnt;
                               2318                 :          49166 :         compresslen += SizeOfGinPostingList(seginfo->seg);
                               2319                 :                : 
                               2320                 :          49166 :         dlist_push_tail(&segments, &seginfo->node);
                               2321                 :                :     }
                               2322                 :                : 
                               2323                 :                :     /*
                               2324                 :                :      * Determine GIN tuple length with all the data included. Be careful about
                               2325                 :                :      * alignment, to allow direct access to compressed segments (those require
                               2326                 :                :      * only SHORTALIGN).
                               2327                 :                :      */
                               2328                 :          49166 :     tuplen = SHORTALIGN(offsetof(GinTuple, data) + keylen) + compresslen;
                               2329                 :                : 
  635                          2330                 :          49166 :     *len = tuplen;
                               2331                 :                : 
                               2332                 :                :     /*
                               2333                 :                :      * Allocate space for the whole GIN tuple.
                               2334                 :                :      *
                               2335                 :                :      * The palloc0 is needed - writetup_index_gin will write the whole tuple
                               2336                 :                :      * to disk, so we need to make sure the padding bytes are defined
                               2337                 :                :      * (otherwise valgrind would report this).
                               2338                 :                :      */
                               2339                 :          49166 :     tuple = palloc0(tuplen);
                               2340                 :                : 
                               2341                 :          49166 :     tuple->tuplen = tuplen;
                               2342                 :          49166 :     tuple->attrnum = attrnum;
                               2343                 :          49166 :     tuple->category = category;
                               2344                 :          49166 :     tuple->keylen = keylen;
                               2345                 :          49166 :     tuple->nitems = nitems;
                               2346                 :                : 
                               2347                 :                :     /* key type info */
                               2348                 :          49166 :     tuple->typlen = typlen;
                               2349                 :          49166 :     tuple->typbyval = typbyval;
                               2350                 :                : 
                               2351                 :                :     /*
                               2352                 :                :      * Copy the key and items into the tuple. First the key value, which we
                               2353                 :                :      * can simply copy right at the beginning of the data array.
                               2354                 :                :      */
                               2355         [ +  + ]:          49166 :     if (category == GIN_CAT_NORM_KEY)
                               2356                 :                :     {
                               2357         [ +  + ]:          49116 :         if (typbyval)
                               2358                 :                :         {
                               2359                 :          14278 :             memcpy(tuple->data, &key, sizeof(Datum));
                               2360                 :                :         }
                               2361         [ -  + ]:          34838 :         else if (typlen > 0) /* byref, fixed length */
                               2362                 :                :         {
  635 tomas.vondra@postgre     2363                 :UBC           0 :             memcpy(tuple->data, DatumGetPointer(key), typlen);
                               2364                 :                :         }
  635 tomas.vondra@postgre     2365         [ +  - ]:CBC       34838 :         else if (typlen == -1)
                               2366                 :                :         {
                               2367                 :          34838 :             memcpy(tuple->data, DatumGetPointer(key), keylen);
                               2368                 :                :         }
  635 tomas.vondra@postgre     2369         [ #  # ]:UBC           0 :         else if (typlen == -2)
                               2370                 :                :         {
                               2371                 :              0 :             memcpy(tuple->data, DatumGetPointer(key), keylen);
                               2372                 :                :         }
                               2373                 :                :     }
                               2374                 :                : 
                               2375                 :                :     /* finally, copy the TIDs into the array */
  635 tomas.vondra@postgre     2376                 :CBC       49166 :     ptr = (char *) tuple + SHORTALIGN(offsetof(GinTuple, data) + keylen);
                               2377                 :                : 
                               2378                 :                :     /* copy in the compressed data, and free the segments */
  634                          2379   [ +  -  +  + ]:          98332 :     dlist_foreach_modify(iter, &segments)
                               2380                 :                :     {
                               2381                 :          49166 :         GinSegmentInfo *seginfo = dlist_container(GinSegmentInfo, node, iter.cur);
                               2382                 :                : 
                               2383                 :          49166 :         memcpy(ptr, seginfo->seg, SizeOfGinPostingList(seginfo->seg));
                               2384                 :                : 
                               2385                 :          49166 :         ptr += SizeOfGinPostingList(seginfo->seg);
                               2386                 :                : 
                               2387                 :          49166 :         dlist_delete(&seginfo->node);
                               2388                 :                : 
                               2389                 :          49166 :         pfree(seginfo->seg);
                               2390                 :          49166 :         pfree(seginfo);
                               2391                 :                :     }
                               2392                 :                : 
  635                          2393                 :          49166 :     return tuple;
                               2394                 :                : }
                               2395                 :                : 
                               2396                 :                : /*
                               2397                 :                :  * _gin_parse_tuple_key
                               2398                 :                :  *      Return a Datum representing the key stored in the tuple.
                               2399                 :                :  *
                               2400                 :                :  * Most of the tuple fields are directly accessible, the only thing that
                               2401                 :                :  * needs more care is the key and the TID list.
                               2402                 :                :  *
                               2403                 :                :  * For the key, this returns a regular Datum representing it. It's either the
                               2404                 :                :  * actual key value, or a pointer to the beginning of the data array (which is
                               2405                 :                :  * where the data was copied by _gin_build_tuple).
                               2406                 :                :  */
                               2407                 :                : static Datum
  634                          2408                 :         221114 : _gin_parse_tuple_key(GinTuple *a)
                               2409                 :                : {
                               2410                 :                :     Datum       key;
                               2411                 :                : 
  635                          2412         [ +  + ]:         221114 :     if (a->category != GIN_CAT_NORM_KEY)
                               2413                 :             50 :         return (Datum) 0;
                               2414                 :                : 
                               2415         [ +  + ]:         221064 :     if (a->typbyval)
                               2416                 :                :     {
                               2417                 :          47106 :         memcpy(&key, a->data, a->keylen);
                               2418                 :          47106 :         return key;
                               2419                 :                :     }
                               2420                 :                : 
                               2421                 :         173958 :     return PointerGetDatum(a->data);
                               2422                 :                : }
                               2423                 :                : 
                               2424                 :                : /*
                               2425                 :                :  * _gin_parse_tuple_items
                               2426                 :                :  *      Return a pointer to a palloc'd array of decompressed TID array.
                               2427                 :                :  */
                               2428                 :                : static ItemPointer
  634                          2429                 :          49166 : _gin_parse_tuple_items(GinTuple *a)
                               2430                 :                : {
                               2431                 :                :     int         len;
                               2432                 :                :     char       *ptr;
                               2433                 :                :     int         ndecoded;
                               2434                 :                :     ItemPointer items;
                               2435                 :                : 
                               2436                 :          49166 :     len = a->tuplen - SHORTALIGN(offsetof(GinTuple, data) + a->keylen);
                               2437                 :          49166 :     ptr = (char *) a + SHORTALIGN(offsetof(GinTuple, data) + a->keylen);
                               2438                 :                : 
                               2439                 :          49166 :     items = ginPostingListDecodeAllSegments((GinPostingList *) ptr, len, &ndecoded);
                               2440                 :                : 
                               2441         [ -  + ]:          49166 :     Assert(ndecoded == a->nitems);
                               2442                 :                : 
  361 peter@eisentraut.org     2443                 :          49166 :     return items;
                               2444                 :                : }
                               2445                 :                : 
                               2446                 :                : /*
                               2447                 :                :  * _gin_compare_tuples
                               2448                 :                :  *      Compare GIN tuples, used by tuplesort during parallel index build.
                               2449                 :                :  *
                               2450                 :                :  * The scalar fields (attrnum, category) are compared first, the key value is
                               2451                 :                :  * compared last. The comparisons are done using type-specific sort support
                               2452                 :                :  * functions.
                               2453                 :                :  *
                               2454                 :                :  * If the key value matches, we compare the first TID value in the TID list,
                               2455                 :                :  * which means the tuples are merged in an order in which they are most
                               2456                 :                :  * likely to be simply concatenated. (This "first" TID will also allow us
                               2457                 :                :  * to determine a point up to which the list is fully determined and can be
                               2458                 :                :  * written into the index to enforce a memory limit etc.)
                               2459                 :                :  */
                               2460                 :                : int
  635 tomas.vondra@postgre     2461                 :          86062 : _gin_compare_tuples(GinTuple *a, GinTuple *b, SortSupport ssup)
                               2462                 :                : {
                               2463                 :                :     int         r;
                               2464                 :                :     Datum       keya,
                               2465                 :                :                 keyb;
                               2466                 :                : 
                               2467         [ -  + ]:          86062 :     if (a->attrnum < b->attrnum)
  635 tomas.vondra@postgre     2468                 :UBC           0 :         return -1;
                               2469                 :                : 
  635 tomas.vondra@postgre     2470         [ -  + ]:CBC       86062 :     if (a->attrnum > b->attrnum)
  635 tomas.vondra@postgre     2471                 :UBC           0 :         return 1;
                               2472                 :                : 
  635 tomas.vondra@postgre     2473         [ +  + ]:CBC       86062 :     if (a->category < b->category)
                               2474                 :             57 :         return -1;
                               2475                 :                : 
                               2476         [ +  + ]:          86005 :     if (a->category > b->category)
                               2477                 :             17 :         return 1;
                               2478                 :                : 
                               2479         [ +  + ]:          85988 :     if (a->category == GIN_CAT_NORM_KEY)
                               2480                 :                :     {
  634                          2481                 :          85974 :         keya = _gin_parse_tuple_key(a);
                               2482                 :          85974 :         keyb = _gin_parse_tuple_key(b);
                               2483                 :                : 
  635                          2484                 :          85974 :         r = ApplySortComparator(keya, false,
                               2485                 :                :                                 keyb, false,
                               2486                 :          85974 :                                 &ssup[a->attrnum - 1]);
                               2487                 :                : 
                               2488                 :                :         /* if the key is the same, consider the first TID in the array */
                               2489         [ +  + ]:         101794 :         return (r != 0) ? r : ItemPointerCompare(GinTupleGetFirst(a),
                               2490                 :          15820 :                                                  GinTupleGetFirst(b));
                               2491                 :                :     }
                               2492                 :                : 
                               2493                 :             14 :     return ItemPointerCompare(GinTupleGetFirst(a),
                               2494                 :             14 :                               GinTupleGetFirst(b));
                               2495                 :                : }
        

Generated by: LCOV version 2.0-1