Coverage Report

Created: 2026-12-01 07:00

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/postgres/src/backend/access/gin/gininsert.c
Line
Count
Source
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
0
#define PARALLEL_KEY_GIN_SHARED     UINT64CONST(0xB000000000000001)
46
0
#define PARALLEL_KEY_TUPLESORT      UINT64CONST(0xB000000000000002)
47
0
#define PARALLEL_KEY_QUERY_TEXT     UINT64CONST(0xB000000000000003)
48
0
#define PARALLEL_KEY_WAL_USAGE      UINT64CONST(0xB000000000000004)
49
0
#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
0
  (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
226
addItemPointersToLeafTuple(GinState *ginstate,
227
               IndexTuple old,
228
               ItemPointerData *items, uint32 nitem,
229
               GinStatsData *buildStats, Buffer buffer)
230
0
{
231
0
  OffsetNumber attnum;
232
0
  Datum   key;
233
0
  GinNullCategory category;
234
0
  IndexTuple  res;
235
0
  ItemPointerData *newItems,
236
0
         *oldItems;
237
0
  int     oldNPosting,
238
0
        newNPosting,
239
0
        nwritten;
240
0
  GinPostingList *compressedList;
241
242
0
  Assert(!GinIsPostingTree(old));
243
244
0
  attnum = gintuple_get_attrnum(ginstate, old);
245
0
  key = gintuple_get_key(ginstate, old, &category);
246
247
  /* merge the old and new posting lists */
248
0
  oldItems = ginReadTuple(ginstate, attnum, old, &oldNPosting);
249
250
0
  newItems = ginMergeItemPointers(items, nitem,
251
0
                  oldItems, oldNPosting,
252
0
                  &newNPosting);
253
254
  /* Compress the posting list, and try to a build tuple with room for it */
255
0
  res = NULL;
256
0
  compressedList = ginCompressPostingList(newItems, newNPosting, GinMaxItemSize, &nwritten);
257
0
  if (nwritten == newNPosting)
258
0
  {
259
0
    res = GinFormTuple(ginstate, attnum, key, category,
260
0
               (char *) compressedList,
261
0
               SizeOfGinPostingList(compressedList),
262
0
               newNPosting,
263
0
               false);
264
0
  }
265
266
0
  pfree(newItems);
267
0
  pfree(compressedList);
268
269
0
  if (!res)
270
0
  {
271
    /* posting list would be too big, convert to posting tree */
272
0
    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
     */
279
0
    postingRoot = createPostingTree(ginstate->index,
280
0
                    oldItems,
281
0
                    oldNPosting,
282
0
                    buildStats,
283
0
                    buffer);
284
285
    /* Now insert the TIDs-to-be-added into the posting tree */
286
0
    ginInsertItemPointers(ginstate->index, postingRoot,
287
0
                items, nitem,
288
0
                buildStats);
289
290
    /* And build a new posting-tree-only result tuple */
291
0
    res = GinFormTuple(ginstate, attnum, key, category, NULL, 0, 0, true);
292
0
    GinSetPostingTree(res, postingRoot);
293
0
  }
294
0
  pfree(oldItems);
295
296
0
  return res;
297
0
}
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
buildFreshLeafTuple(GinState *ginstate,
309
          OffsetNumber attnum, Datum key, GinNullCategory category,
310
          ItemPointerData *items, uint32 nitem,
311
          GinStatsData *buildStats, Buffer buffer)
312
0
{
313
0
  IndexTuple  res = NULL;
314
0
  GinPostingList *compressedList;
315
0
  int     nwritten;
316
317
  /* try to build a posting list tuple with all the items */
318
0
  compressedList = ginCompressPostingList(items, nitem, GinMaxItemSize, &nwritten);
319
0
  if (nwritten == nitem)
320
0
  {
321
0
    res = GinFormTuple(ginstate, attnum, key, category,
322
0
               (char *) compressedList,
323
0
               SizeOfGinPostingList(compressedList),
324
0
               nitem, false);
325
0
  }
326
0
  pfree(compressedList);
327
328
0
  if (!res)
329
0
  {
330
    /* posting list would be too big, build posting tree */
331
0
    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
     */
337
0
    res = GinFormTuple(ginstate, attnum, key, category, NULL, 0, 0, true);
338
339
    /*
340
     * Initialize a new posting tree with the TIDs.
341
     */
342
0
    postingRoot = createPostingTree(ginstate->index, items, nitem,
343
0
                    buildStats, buffer);
344
345
    /* And save the root link in the result tuple */
346
0
    GinSetPostingTree(res, postingRoot);
347
0
  }
348
349
0
  return res;
350
0
}
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
360
ginEntryInsert(GinState *ginstate,
361
         OffsetNumber attnum, Datum key, GinNullCategory category,
362
         ItemPointerData *items, uint32 nitem,
363
         GinStatsData *buildStats)
364
0
{
365
0
  GinBtreeData btree;
366
0
  GinBtreeEntryInsertData insertdata;
367
0
  GinBtreeStack *stack;
368
0
  IndexTuple  itup;
369
0
  Page    page;
370
371
0
  insertdata.isDelete = false;
372
373
0
  ginPrepareEntryScan(&btree, attnum, key, category, ginstate);
374
0
  btree.isBuild = (buildStats != NULL);
375
376
0
  stack = ginFindLeafPage(&btree, false, false);
377
0
  page = BufferGetPage(stack->buffer);
378
379
0
  if (btree.findItem(&btree, stack))
380
0
  {
381
    /* found pre-existing entry */
382
0
    itup = (IndexTuple) PageGetItem(page, PageGetItemId(page, stack->off));
383
384
0
    if (GinIsPostingTree(itup))
385
0
    {
386
      /* add entries to existing posting tree */
387
0
      BlockNumber rootPostingTree = GinGetPostingTree(itup);
388
389
      /* release all stack */
390
0
      LockBuffer(stack->buffer, GIN_UNLOCK);
391
0
      freeGinBtreeStack(stack);
392
393
      /* insert into posting tree */
394
0
      ginInsertItemPointers(ginstate->index, rootPostingTree,
395
0
                  items, nitem,
396
0
                  buildStats);
397
0
      return;
398
0
    }
399
400
0
    CheckForSerializableConflictIn(ginstate->index, NULL,
401
0
                     BufferGetBlockNumber(stack->buffer));
402
    /* modify an existing leaf entry */
403
0
    itup = addItemPointersToLeafTuple(ginstate, itup,
404
0
                      items, nitem, buildStats, stack->buffer);
405
406
0
    insertdata.isDelete = true;
407
0
  }
408
0
  else
409
0
  {
410
0
    CheckForSerializableConflictIn(ginstate->index, NULL,
411
0
                     BufferGetBlockNumber(stack->buffer));
412
    /* no match, so construct a new leaf entry */
413
0
    itup = buildFreshLeafTuple(ginstate, attnum, key, category,
414
0
                   items, nitem, buildStats, stack->buffer);
415
416
    /*
417
     * nEntries counts leaf tuples, so increment it only when we make a
418
     * new one.
419
     */
420
0
    if (buildStats)
421
0
      buildStats->nEntries++;
422
0
  }
423
424
  /* Insert the new or modified leaf tuple */
425
0
  insertdata.entry = itup;
426
0
  ginInsertValue(&btree, stack, &insertdata, buildStats);
427
0
  pfree(itup);
428
0
}
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
437
ginHeapTupleBulkInsert(GinBuildState *buildstate, OffsetNumber attnum,
438
             Datum value, bool isNull,
439
             ItemPointer heapptr)
440
0
{
441
0
  Datum    *entries;
442
0
  GinNullCategory *categories;
443
0
  int32   nentries;
444
0
  MemoryContext oldCtx;
445
446
0
  oldCtx = MemoryContextSwitchTo(buildstate->funcCtx);
447
0
  entries = ginExtractEntries(buildstate->accum.ginstate, attnum,
448
0
                value, isNull,
449
0
                &nentries, &categories);
450
0
  MemoryContextSwitchTo(oldCtx);
451
452
0
  ginInsertBAEntries(&buildstate->accum, heapptr, attnum,
453
0
             entries, categories, nentries);
454
455
0
  buildstate->indtuples += nentries;
456
457
0
  MemoryContextReset(buildstate->funcCtx);
458
0
}
459
460
static void
461
ginBuildCallback(Relation index, ItemPointer tid, Datum *values,
462
         bool *isnull, bool tupleIsAlive, void *state)
463
0
{
464
0
  GinBuildState *buildstate = (GinBuildState *) state;
465
0
  MemoryContext oldCtx;
466
0
  int     i;
467
468
0
  oldCtx = MemoryContextSwitchTo(buildstate->tmpCtx);
469
470
0
  for (i = 0; i < buildstate->ginstate.origTupdesc->natts; i++)
471
0
    ginHeapTupleBulkInsert(buildstate, (OffsetNumber) (i + 1),
472
0
                 values[i], isnull[i], tid);
473
474
  /* If we've maxed out our available memory, dump everything to the index */
475
0
  if (buildstate->accum.allocatedMemory >= maintenance_work_mem * (Size) 1024)
476
0
  {
477
0
    ItemPointerData *list;
478
0
    Datum   key;
479
0
    GinNullCategory category;
480
0
    uint32    nlist;
481
0
    OffsetNumber attnum;
482
483
0
    ginBeginBAScan(&buildstate->accum);
484
0
    while ((list = ginGetBAEntry(&buildstate->accum,
485
0
                   &attnum, &key, &category, &nlist)) != NULL)
486
0
    {
487
      /* there could be many entries, so be willing to abort here */
488
0
      CHECK_FOR_INTERRUPTS();
489
0
      ginEntryInsert(&buildstate->ginstate, attnum, key, category,
490
0
               list, nlist, &buildstate->buildStats);
491
0
    }
492
493
0
    MemoryContextReset(buildstate->tmpCtx);
494
0
    ginInitBA(&buildstate->accum);
495
0
  }
496
497
0
  MemoryContextSwitchTo(oldCtx);
498
0
}
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
514
ginFlushBuildState(GinBuildState *buildstate, Relation index)
515
0
{
516
0
  ItemPointerData *list;
517
0
  Datum   key;
518
0
  GinNullCategory category;
519
0
  uint32    nlist;
520
0
  OffsetNumber attnum;
521
0
  TupleDesc tdesc = RelationGetDescr(index);
522
0
  uint32    maxlen;
523
524
  /* maximum number of TIDs per chunk (two chunks per worker) */
525
0
  maxlen = MaxAllocSize / sizeof(ItemPointerData);
526
0
  maxlen /= (2 * buildstate->bs_num_workers);
527
528
0
  ginBeginBAScan(&buildstate->accum);
529
0
  while ((list = ginGetBAEntry(&buildstate->accum,
530
0
                 &attnum, &key, &category, &nlist)) != NULL)
531
0
  {
532
    /* information about the key */
533
0
    CompactAttribute *attr = TupleDescCompactAttr(tdesc, (attnum - 1));
534
535
    /* start of the chunk */
536
0
    uint32    offset = 0;
537
538
    /* split the entry into smaller chunk with up to maxlen items */
539
0
    while (offset < nlist)
540
0
    {
541
      /* GIN tuple and tuple length */
542
0
      GinTuple   *tup;
543
0
      Size    tuplen;
544
0
      uint32    len = Min(maxlen, nlist - offset);
545
546
      /* there could be many entries, so be willing to abort here */
547
0
      CHECK_FOR_INTERRUPTS();
548
549
0
      tup = _gin_build_tuple(attnum, category,
550
0
                   key, attr->attlen, attr->attbyval,
551
0
                   &list[offset], len,
552
0
                   &tuplen);
553
554
0
      offset += len;
555
556
0
      tuplesort_putgintuple(buildstate->bs_worker_sort, tup, tuplen);
557
558
0
      pfree(tup);
559
0
    }
560
0
  }
561
562
0
  MemoryContextReset(buildstate->tmpCtx);
563
0
  ginInitBA(&buildstate->accum);
564
0
}
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
ginBuildCallbackParallel(Relation index, ItemPointer tid, Datum *values,
580
             bool *isnull, bool tupleIsAlive, void *state)
581
0
{
582
0
  GinBuildState *buildstate = (GinBuildState *) state;
583
0
  MemoryContext oldCtx;
584
0
  int     i;
585
586
0
  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
0
  if (ItemPointerCompare(tid, &buildstate->tid) < 0)
606
0
    ginFlushBuildState(buildstate, index);
607
608
  /* remember the TID we're about to process */
609
0
  buildstate->tid = *tid;
610
611
0
  for (i = 0; i < buildstate->ginstate.origTupdesc->natts; i++)
612
0
    ginHeapTupleBulkInsert(buildstate, (OffsetNumber) (i + 1),
613
0
                 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
0
  if (buildstate->accum.allocatedMemory >= buildstate->work_mem * (Size) 1024)
621
0
    ginFlushBuildState(buildstate, index);
622
623
0
  MemoryContextSwitchTo(oldCtx);
624
0
}
625
626
IndexBuildResult *
627
ginbuild(Relation heap, Relation index, IndexInfo *indexInfo)
628
0
{
629
0
  IndexBuildResult *result;
630
0
  double    reltuples;
631
0
  GinBuildState buildstate;
632
0
  GinBuildState *state = &buildstate;
633
0
  Buffer    RootBuffer,
634
0
        MetaBuffer;
635
0
  ItemPointerData *list;
636
0
  Datum   key;
637
0
  GinNullCategory category;
638
0
  uint32    nlist;
639
0
  MemoryContext oldCtx;
640
0
  OffsetNumber attnum;
641
642
0
  if (RelationGetNumberOfBlocks(index) != 0)
643
0
    elog(ERROR, "index \"%s\" already contains data",
644
0
       RelationGetRelationName(index));
645
646
0
  initGinState(&buildstate.ginstate, index);
647
0
  buildstate.indtuples = 0;
648
0
  memset(&buildstate.buildStats, 0, sizeof(GinStatsData));
649
650
  /* Initialize fields for parallel build too. */
651
0
  buildstate.bs_numtuples = 0;
652
0
  buildstate.bs_reltuples = 0;
653
0
  buildstate.bs_leader = NULL;
654
0
  memset(&buildstate.tid, 0, sizeof(ItemPointerData));
655
656
  /* initialize the meta page */
657
0
  MetaBuffer = GinNewBuffer(index);
658
659
  /* initialize the root page */
660
0
  RootBuffer = GinNewBuffer(index);
661
662
0
  START_CRIT_SECTION();
663
0
  GinInitMetabuffer(MetaBuffer);
664
0
  MarkBufferDirty(MetaBuffer);
665
0
  GinInitBuffer(RootBuffer, GIN_LEAF);
666
0
  MarkBufferDirty(RootBuffer);
667
668
669
0
  UnlockReleaseBuffer(MetaBuffer);
670
0
  UnlockReleaseBuffer(RootBuffer);
671
0
  END_CRIT_SECTION();
672
673
  /* count the root as first entry page */
674
0
  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
   */
680
0
  buildstate.tmpCtx = AllocSetContextCreate(CurrentMemoryContext,
681
0
                        "Gin build temporary context",
682
0
                        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
   */
688
0
  buildstate.funcCtx = AllocSetContextCreate(CurrentMemoryContext,
689
0
                         "Gin build temporary context for user-defined function",
690
0
                         ALLOCSET_DEFAULT_SIZES);
691
692
0
  buildstate.accum.ginstate = &buildstate.ginstate;
693
0
  ginInitBA(&buildstate.accum);
694
695
  /* Report table scan phase started */
696
0
  pgstat_progress_update_param(PROGRESS_CREATEIDX_SUBPHASE,
697
0
                 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
0
  if (indexInfo->ii_ParallelWorkers > 0)
709
0
    _gin_begin_parallel(state, heap, index, indexInfo->ii_Concurrent,
710
0
              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
0
  if (state->bs_leader)
722
0
  {
723
0
    SortCoordinate coordinate;
724
725
0
    coordinate = palloc0_object(SortCoordinateData);
726
0
    coordinate->isWorker = false;
727
0
    coordinate->nParticipants =
728
0
      state->bs_leader->nparticipanttuplesorts;
729
0
    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
0
    state->bs_sortstate =
754
0
      tuplesort_begin_index_gin(heap, index,
755
0
                    maintenance_work_mem, coordinate,
756
0
                    TUPLESORT_NONE);
757
758
    /* scan the relation in parallel and merge per-worker results */
759
0
    reltuples = _gin_parallel_merge(state, indexInfo);
760
761
0
    _gin_end_parallel(state->bs_leader, state);
762
0
  }
763
0
  else            /* no parallel index build */
764
0
  {
765
    /*
766
     * Do the heap scan.  We disallow sync scan here because
767
     * dataPlaceToPage prefers to receive tuples in TID order.
768
     */
769
0
    reltuples = table_index_build_scan(heap, index, indexInfo, false, true,
770
0
                       ginBuildCallback, &buildstate, NULL);
771
772
    /* dump remaining entries to the index */
773
0
    oldCtx = MemoryContextSwitchTo(buildstate.tmpCtx);
774
0
    ginBeginBAScan(&buildstate.accum);
775
0
    while ((list = ginGetBAEntry(&buildstate.accum,
776
0
                   &attnum, &key, &category, &nlist)) != NULL)
777
0
    {
778
      /* there could be many entries, so be willing to abort here */
779
0
      CHECK_FOR_INTERRUPTS();
780
0
      ginEntryInsert(&buildstate.ginstate, attnum, key, category,
781
0
               list, nlist, &buildstate.buildStats);
782
0
    }
783
0
    MemoryContextSwitchTo(oldCtx);
784
0
  }
785
786
0
  MemoryContextDelete(buildstate.funcCtx);
787
0
  MemoryContextDelete(buildstate.tmpCtx);
788
789
  /*
790
   * Update metapage stats
791
   */
792
0
  buildstate.buildStats.nTotalPages = RelationGetNumberOfBlocks(index);
793
0
  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
0
  if (RelationNeedsWAL(index))
800
0
  {
801
0
    log_newpage_range(index, MAIN_FORKNUM,
802
0
              0, RelationGetNumberOfBlocks(index),
803
0
              true);
804
0
  }
805
806
  /*
807
   * Return statistics
808
   */
809
0
  result = palloc_object(IndexBuildResult);
810
811
0
  result->heap_tuples = reltuples;
812
0
  result->index_tuples = buildstate.indtuples;
813
814
0
  return result;
815
0
}
816
817
/*
818
 *  ginbuildempty() -- build an empty gin index in the initialization fork
819
 */
820
void
821
ginbuildempty(Relation index)
822
0
{
823
0
  Buffer    RootBuffer,
824
0
        MetaBuffer;
825
826
  /* An empty GIN index has two pages. */
827
0
  MetaBuffer = ExtendBufferedRel(BMR_REL(index), INIT_FORKNUM, NULL,
828
0
                   EB_LOCK_FIRST | EB_SKIP_EXTENSION_LOCK);
829
0
  RootBuffer = ExtendBufferedRel(BMR_REL(index), INIT_FORKNUM, NULL,
830
0
                   EB_LOCK_FIRST | EB_SKIP_EXTENSION_LOCK);
831
832
  /* Initialize and xlog metabuffer and root buffer. */
833
0
  START_CRIT_SECTION();
834
0
  GinInitMetabuffer(MetaBuffer);
835
0
  MarkBufferDirty(MetaBuffer);
836
0
  log_newpage_buffer(MetaBuffer, true);
837
0
  GinInitBuffer(RootBuffer, GIN_LEAF);
838
0
  MarkBufferDirty(RootBuffer);
839
0
  log_newpage_buffer(RootBuffer, false);
840
0
  END_CRIT_SECTION();
841
842
  /* Unlock and release the buffers. */
843
0
  UnlockReleaseBuffer(MetaBuffer);
844
0
  UnlockReleaseBuffer(RootBuffer);
845
0
}
846
847
/*
848
 * Insert index entries for a single indexable item during "normal"
849
 * (non-fast-update) insertion
850
 */
851
static void
852
ginHeapTupleInsert(GinState *ginstate, OffsetNumber attnum,
853
           Datum value, bool isNull,
854
           ItemPointer item)
855
0
{
856
0
  Datum    *entries;
857
0
  GinNullCategory *categories;
858
0
  int32   i,
859
0
        nentries;
860
861
0
  entries = ginExtractEntries(ginstate, attnum, value, isNull,
862
0
                &nentries, &categories);
863
864
0
  for (i = 0; i < nentries; i++)
865
0
  {
866
    /* there could be many entries, so be willing to abort here */
867
0
    CHECK_FOR_INTERRUPTS();
868
0
    ginEntryInsert(ginstate, attnum, entries[i], categories[i],
869
0
             item, 1, NULL);
870
0
  }
871
0
}
872
873
bool
874
gininsert(Relation index, Datum *values, bool *isnull,
875
      ItemPointer ht_ctid, Relation heapRel,
876
      IndexUniqueCheck checkUnique,
877
      bool indexUnchanged,
878
      IndexInfo *indexInfo)
879
0
{
880
0
  GinState   *ginstate = (GinState *) indexInfo->ii_AmCache;
881
0
  MemoryContext oldCtx;
882
0
  MemoryContext insertCtx;
883
0
  int     i;
884
885
  /* Initialize GinState cache if first call in this statement */
886
0
  if (ginstate == NULL)
887
0
  {
888
0
    oldCtx = MemoryContextSwitchTo(indexInfo->ii_Context);
889
0
    ginstate = palloc_object(GinState);
890
0
    initGinState(ginstate, index);
891
0
    indexInfo->ii_AmCache = ginstate;
892
0
    MemoryContextSwitchTo(oldCtx);
893
0
  }
894
895
0
  insertCtx = AllocSetContextCreate(CurrentMemoryContext,
896
0
                    "Gin insert temporary context",
897
0
                    ALLOCSET_DEFAULT_SIZES);
898
899
0
  oldCtx = MemoryContextSwitchTo(insertCtx);
900
901
0
  if (GinGetUseFastUpdate(index))
902
0
  {
903
0
    GinTupleCollector collector;
904
905
0
    memset(&collector, 0, sizeof(GinTupleCollector));
906
907
0
    for (i = 0; i < ginstate->origTupdesc->natts; i++)
908
0
      ginHeapTupleFastCollect(ginstate, &collector,
909
0
                  (OffsetNumber) (i + 1),
910
0
                  values[i], isnull[i],
911
0
                  ht_ctid);
912
913
0
    ginHeapTupleFastInsert(ginstate, &collector);
914
0
  }
915
0
  else
916
0
  {
917
0
    for (i = 0; i < ginstate->origTupdesc->natts; i++)
918
0
      ginHeapTupleInsert(ginstate, (OffsetNumber) (i + 1),
919
0
                 values[i], isnull[i],
920
0
                 ht_ctid);
921
0
  }
922
923
0
  MemoryContextSwitchTo(oldCtx);
924
0
  MemoryContextDelete(insertCtx);
925
926
0
  return false;
927
0
}
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
946
_gin_begin_parallel(GinBuildState *buildstate, Relation heap, Relation index,
947
          bool isconcurrent, int request)
948
0
{
949
0
  ParallelContext *pcxt;
950
0
  int     scantuplesortstates;
951
0
  Snapshot  snapshot;
952
0
  Size    estginshared;
953
0
  Size    estsort;
954
0
  GinBuildShared *ginshared;
955
0
  Sharedsort *sharedsort;
956
0
  GinLeader  *ginleader = palloc0_object(GinLeader);
957
0
  WalUsage   *walusage;
958
0
  BufferUsage *bufferusage;
959
0
  bool    leaderparticipates = true;
960
0
  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
0
  EnterParallelMode();
970
0
  Assert(request > 0);
971
0
  pcxt = CreateParallelContext("postgres", "_gin_parallel_build_main",
972
0
                 request);
973
974
0
  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
0
  if (!isconcurrent)
984
0
    snapshot = SnapshotAny;
985
0
  else
986
0
    snapshot = RegisterSnapshot(GetTransactionSnapshot());
987
988
  /*
989
   * Estimate size for our own PARALLEL_KEY_GIN_SHARED workspace.
990
   */
991
0
  estginshared = _gin_parallel_estimate_shared(heap, snapshot);
992
0
  shm_toc_estimate_chunk(&pcxt->estimator, estginshared);
993
0
  estsort = tuplesort_estimate_shared(scantuplesortstates);
994
0
  shm_toc_estimate_chunk(&pcxt->estimator, estsort);
995
996
0
  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
0
  shm_toc_estimate_chunk(&pcxt->estimator,
1007
0
               mul_size(sizeof(WalUsage), pcxt->nworkers));
1008
0
  shm_toc_estimate_keys(&pcxt->estimator, 1);
1009
0
  shm_toc_estimate_chunk(&pcxt->estimator,
1010
0
               mul_size(sizeof(BufferUsage), pcxt->nworkers));
1011
0
  shm_toc_estimate_keys(&pcxt->estimator, 1);
1012
1013
  /* Finally, estimate PARALLEL_KEY_QUERY_TEXT space */
1014
0
  if (debug_query_string)
1015
0
  {
1016
0
    querylen = strlen(debug_query_string);
1017
0
    shm_toc_estimate_chunk(&pcxt->estimator, querylen + 1);
1018
0
    shm_toc_estimate_keys(&pcxt->estimator, 1);
1019
0
  }
1020
0
  else
1021
0
    querylen = 0;     /* keep compiler quiet */
1022
1023
  /* Everyone's had a chance to ask for space, so now create the DSM */
1024
0
  InitializeParallelDSM(pcxt);
1025
1026
  /* If no DSM segment was available, back out (do serial build) */
1027
0
  if (pcxt->seg == NULL)
1028
0
  {
1029
0
    if (IsMVCCSnapshot(snapshot))
1030
0
      UnregisterSnapshot(snapshot);
1031
0
    DestroyParallelContext(pcxt);
1032
0
    ExitParallelMode();
1033
0
    return;
1034
0
  }
1035
1036
  /* Store shared build state, for which we reserved space */
1037
0
  ginshared = (GinBuildShared *) shm_toc_allocate(pcxt->toc, estginshared);
1038
  /* Initialize immutable state */
1039
0
  ginshared->heaprelid = RelationGetRelid(heap);
1040
0
  ginshared->indexrelid = RelationGetRelid(index);
1041
0
  ginshared->isconcurrent = isconcurrent;
1042
0
  ginshared->scantuplesortstates = scantuplesortstates;
1043
0
  ginshared->queryid = pgstat_get_my_query_id();
1044
1045
0
  ConditionVariableInit(&ginshared->workersdonecv);
1046
0
  SpinLockInit(&ginshared->mutex);
1047
1048
  /* Initialize mutable state */
1049
0
  ginshared->nparticipantsdone = 0;
1050
0
  ginshared->reltuples = 0.0;
1051
0
  ginshared->indtuples = 0.0;
1052
0
  ginshared->brokenhotchain = false;
1053
1054
0
  table_parallelscan_initialize(heap,
1055
0
                  ParallelTableScanFromGinBuildShared(ginshared),
1056
0
                  snapshot);
1057
1058
  /*
1059
   * Store shared tuplesort-private state, for which we reserved space.
1060
   * Then, initialize opaque state using tuplesort routine.
1061
   */
1062
0
  sharedsort = (Sharedsort *) shm_toc_allocate(pcxt->toc, estsort);
1063
0
  tuplesort_initialize_shared(sharedsort, scantuplesortstates,
1064
0
                pcxt->seg);
1065
1066
0
  shm_toc_insert(pcxt->toc, PARALLEL_KEY_GIN_SHARED, ginshared);
1067
0
  shm_toc_insert(pcxt->toc, PARALLEL_KEY_TUPLESORT, sharedsort);
1068
1069
  /* Store query string for workers */
1070
0
  if (debug_query_string)
1071
0
  {
1072
0
    char     *sharedquery;
1073
1074
0
    sharedquery = (char *) shm_toc_allocate(pcxt->toc, querylen + 1);
1075
0
    memcpy(sharedquery, debug_query_string, querylen + 1);
1076
0
    shm_toc_insert(pcxt->toc, PARALLEL_KEY_QUERY_TEXT, sharedquery);
1077
0
  }
1078
1079
  /*
1080
   * Allocate space for each worker's WalUsage and BufferUsage; no need to
1081
   * initialize.
1082
   */
1083
0
  walusage = shm_toc_allocate(pcxt->toc,
1084
0
                mul_size(sizeof(WalUsage), pcxt->nworkers));
1085
0
  shm_toc_insert(pcxt->toc, PARALLEL_KEY_WAL_USAGE, walusage);
1086
0
  bufferusage = shm_toc_allocate(pcxt->toc,
1087
0
                   mul_size(sizeof(BufferUsage), pcxt->nworkers));
1088
0
  shm_toc_insert(pcxt->toc, PARALLEL_KEY_BUFFER_USAGE, bufferusage);
1089
1090
  /* Launch workers, saving status for leader/caller */
1091
0
  LaunchParallelWorkers(pcxt);
1092
0
  ginleader->pcxt = pcxt;
1093
0
  ginleader->nparticipanttuplesorts = pcxt->nworkers_launched;
1094
0
  if (leaderparticipates)
1095
0
    ginleader->nparticipanttuplesorts++;
1096
0
  ginleader->ginshared = ginshared;
1097
0
  ginleader->sharedsort = sharedsort;
1098
0
  ginleader->snapshot = snapshot;
1099
0
  ginleader->walusage = walusage;
1100
0
  ginleader->bufferusage = bufferusage;
1101
1102
  /* If no workers were successfully launched, back out (do serial build) */
1103
0
  if (pcxt->nworkers_launched == 0)
1104
0
  {
1105
0
    _gin_end_parallel(ginleader, NULL);
1106
0
    return;
1107
0
  }
1108
1109
  /* Save leader state now that it's clear build will be parallel */
1110
0
  buildstate->bs_leader = ginleader;
1111
1112
  /* Join heap scan ourselves */
1113
0
  if (leaderparticipates)
1114
0
    _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
0
  WaitForParallelWorkersToAttach(pcxt);
1121
0
}
1122
1123
/*
1124
 * Shut down workers, destroy parallel context, and end parallel mode.
1125
 */
1126
static void
1127
_gin_end_parallel(GinLeader *ginleader, GinBuildState *state)
1128
0
{
1129
0
  int     i;
1130
1131
  /* Shutdown worker processes */
1132
0
  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
0
  for (i = 0; i < ginleader->pcxt->nworkers_launched; i++)
1139
0
    InstrAccumParallelQuery(&ginleader->bufferusage[i], &ginleader->walusage[i]);
1140
1141
  /* Free last reference to MVCC snapshot, if one was used */
1142
0
  if (IsMVCCSnapshot(ginleader->snapshot))
1143
0
    UnregisterSnapshot(ginleader->snapshot);
1144
0
  DestroyParallelContext(ginleader->pcxt);
1145
0
  ExitParallelMode();
1146
0
}
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
1159
_gin_parallel_heapscan(GinBuildState *state, bool *brokenhotchain)
1160
0
{
1161
0
  GinBuildShared *ginshared = state->bs_leader->ginshared;
1162
0
  int     nparticipanttuplesorts;
1163
1164
0
  nparticipanttuplesorts = state->bs_leader->nparticipanttuplesorts;
1165
0
  for (;;)
1166
0
  {
1167
0
    SpinLockAcquire(&ginshared->mutex);
1168
0
    if (ginshared->nparticipantsdone == nparticipanttuplesorts)
1169
0
    {
1170
      /* copy the data into leader state */
1171
0
      state->bs_reltuples = ginshared->reltuples;
1172
0
      state->bs_numtuples = ginshared->indtuples;
1173
0
      *brokenhotchain = ginshared->brokenhotchain;
1174
1175
0
      SpinLockRelease(&ginshared->mutex);
1176
0
      break;
1177
0
    }
1178
0
    SpinLockRelease(&ginshared->mutex);
1179
1180
0
    ConditionVariableSleep(&ginshared->workersdonecv,
1181
0
                 WAIT_EVENT_PARALLEL_CREATE_INDEX_SCAN);
1182
0
  }
1183
1184
0
  ConditionVariableCancelSleep();
1185
1186
0
  return state->bs_reltuples;
1187
0
}
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
AssertCheckItemPointers(GinBuffer *buffer)
1228
0
{
1229
#ifdef USE_ASSERT_CHECKING
1230
  /* we should not have a buffer with no TIDs to sort */
1231
  Assert(buffer->items != NULL);
1232
  Assert(buffer->nitems > 0);
1233
1234
  for (int i = 0; i < buffer->nitems; i++)
1235
  {
1236
    Assert(ItemPointerIsValid(&buffer->items[i]));
1237
1238
    /* don't check ordering for the first TID item */
1239
    if (i == 0)
1240
      continue;
1241
1242
    Assert(ItemPointerCompare(&buffer->items[i - 1], &buffer->items[i]) < 0);
1243
  }
1244
#endif
1245
0
}
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
AssertCheckGinBuffer(GinBuffer *buffer)
1255
0
{
1256
#ifdef USE_ASSERT_CHECKING
1257
  /* if we have any items, the array must exist */
1258
  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
  if (buffer->nitems == 0)
1265
    return;
1266
1267
  /* Make sure the item pointers are valid and sorted. */
1268
  AssertCheckItemPointers(buffer);
1269
#endif
1270
0
}
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
GinBufferInit(Relation index)
1284
0
{
1285
0
  GinBuffer  *buffer = palloc0_object(GinBuffer);
1286
0
  int     i,
1287
0
        nKeys;
1288
0
  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
   */
1295
0
  buffer->maxitems = (64 * 1024L) / sizeof(ItemPointerData);
1296
1297
0
  nKeys = IndexRelationGetNumberOfKeyAttributes(index);
1298
1299
0
  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
   */
1305
0
  for (i = 0; i < nKeys; i++)
1306
0
  {
1307
0
    Oid     cmpFunc;
1308
0
    SortSupport sortKey = &buffer->ssup[i];
1309
0
    Form_pg_attribute att = TupleDescAttr(desc, i);
1310
1311
0
    sortKey->ssup_cxt = CurrentMemoryContext;
1312
0
    sortKey->ssup_collation = index->rd_indcollation[i];
1313
1314
0
    if (!OidIsValid(sortKey->ssup_collation))
1315
0
      sortKey->ssup_collation = DEFAULT_COLLATION_OID;
1316
1317
0
    sortKey->ssup_nulls_first = false;
1318
0
    sortKey->ssup_attno = i + 1;
1319
0
    sortKey->abbreviate = false;
1320
1321
0
    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
0
    cmpFunc = index_getprocid(index, i + 1, GIN_COMPARE_PROC);
1328
0
    if (cmpFunc == InvalidOid)
1329
0
    {
1330
0
      TypeCacheEntry *typentry;
1331
1332
0
      typentry = lookup_type_cache(att->atttypid,
1333
0
                     TYPECACHE_CMP_PROC_FINFO);
1334
0
      if (!OidIsValid(typentry->cmp_proc_finfo.fn_oid))
1335
0
        ereport(ERROR,
1336
0
            (errcode(ERRCODE_UNDEFINED_FUNCTION),
1337
0
             errmsg("could not identify a comparison function for type %s",
1338
0
                format_type_be(att->atttypid))));
1339
1340
0
      cmpFunc = typentry->cmp_proc_finfo.fn_oid;
1341
0
    }
1342
1343
0
    PrepareSortSupportComparisonShim(cmpFunc, sortKey);
1344
0
  }
1345
1346
0
  return buffer;
1347
0
}
1348
1349
/* Is the buffer empty, i.e. has no TID values in the array? */
1350
static bool
1351
GinBufferIsEmpty(GinBuffer *buffer)
1352
0
{
1353
0
  return (buffer->nitems == 0);
1354
0
}
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
GinBufferKeyEquals(GinBuffer *buffer, GinTuple *tup)
1368
0
{
1369
0
  int     r;
1370
0
  Datum   tupkey;
1371
1372
0
  AssertCheckGinBuffer(buffer);
1373
1374
0
  if (tup->attrnum != buffer->attnum)
1375
0
    return false;
1376
1377
  /* same attribute should have the same type info */
1378
0
  Assert(tup->typbyval == buffer->typbyval);
1379
0
  Assert(tup->typlen == buffer->typlen);
1380
1381
0
  if (tup->category != buffer->category)
1382
0
    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
0
  if (buffer->category != GIN_CAT_NORM_KEY)
1389
0
    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
0
  tupkey = (buffer->typbyval) ? *(Datum *) tup->data : PointerGetDatum(tup->data);
1396
1397
0
  r = ApplySortComparator(buffer->key, false,
1398
0
              tupkey, false,
1399
0
              &buffer->ssup[buffer->attnum - 1]);
1400
1401
0
  return (r == 0);
1402
0
}
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
1433
GinBufferShouldTrim(GinBuffer *buffer, GinTuple *tup)
1434
0
{
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
   */
1439
0
  if ((buffer->nitems > 0) &&
1440
0
    (ItemPointerCompare(&buffer->items[buffer->nitems - 1],
1441
0
              GinTupleGetFirst(tup)) == 0))
1442
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
   */
1457
0
  for (int i = buffer->nfrozen; i < buffer->nitems; i++)
1458
0
  {
1459
    /* Is the TID after the first TID of the new tuple? Can't freeze. */
1460
0
    if (ItemPointerCompare(&buffer->items[i],
1461
0
                 GinTupleGetFirst(tup)) > 0)
1462
0
      break;
1463
1464
0
    buffer->nfrozen++;
1465
0
  }
1466
1467
  /* not enough TIDs to trim (1024 is somewhat arbitrary number) */
1468
0
  if (buffer->nfrozen < 1024)
1469
0
    return false;
1470
1471
  /* no need to trim if we have not hit the memory limit yet */
1472
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
0
}
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
1506
GinBufferStoreTuple(GinBuffer *buffer, GinTuple *tup)
1507
0
{
1508
0
  ItemPointerData *items;
1509
0
  Datum   key;
1510
1511
0
  AssertCheckGinBuffer(buffer);
1512
1513
0
  key = _gin_parse_tuple_key(tup);
1514
0
  items = _gin_parse_tuple_items(tup);
1515
1516
  /* if the buffer is empty, set the fields (and copy the key) */
1517
0
  if (GinBufferIsEmpty(buffer))
1518
0
  {
1519
0
    buffer->category = tup->category;
1520
0
    buffer->keylen = tup->keylen;
1521
0
    buffer->attnum = tup->attrnum;
1522
1523
0
    buffer->typlen = tup->typlen;
1524
0
    buffer->typbyval = tup->typbyval;
1525
1526
0
    if (tup->category == GIN_CAT_NORM_KEY)
1527
0
      buffer->key = datumCopy(key, buffer->typbyval, buffer->typlen);
1528
0
    else
1529
0
      buffer->key = (Datum) 0;
1530
0
  }
1531
1532
  /* add the new TIDs into the buffer, combine using merge-sort */
1533
0
  {
1534
0
    int     nnew;
1535
0
    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
     */
1542
0
    if (buffer->items == NULL)
1543
0
      buffer->items = palloc_array(ItemPointerData, buffer->nitems + tup->nitems);
1544
0
    else
1545
0
      buffer->items = repalloc_array(buffer->items,
1546
0
                       ItemPointerData, buffer->nitems + tup->nitems);
1547
1548
0
    new = ginMergeItemPointers(&buffer->items[buffer->nfrozen], /* first unfrozen */
1549
0
                   (buffer->nitems - buffer->nfrozen),  /* num of unfrozen */
1550
0
                   items, tup->nitems, &nnew);
1551
1552
0
    Assert(nnew == (tup->nitems + (buffer->nitems - buffer->nfrozen)));
1553
1554
0
    memcpy(&buffer->items[buffer->nfrozen], new,
1555
0
         nnew * sizeof(ItemPointerData));
1556
1557
0
    pfree(new);
1558
1559
0
    buffer->nitems += tup->nitems;
1560
1561
0
    AssertCheckItemPointers(buffer);
1562
0
  }
1563
1564
  /* free the decompressed TID list */
1565
0
  pfree(items);
1566
0
}
1567
1568
/*
1569
 * GinBufferReset
1570
 *    Reset the buffer into a state as if it contains no data.
1571
 */
1572
static void
1573
GinBufferReset(GinBuffer *buffer)
1574
0
{
1575
0
  Assert(!GinBufferIsEmpty(buffer));
1576
1577
  /* release byref values, do nothing for by-val ones */
1578
0
  if ((buffer->category == GIN_CAT_NORM_KEY) && !buffer->typbyval)
1579
0
    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
0
  buffer->key = (Datum) 0;
1586
1587
0
  buffer->attnum = 0;
1588
0
  buffer->category = 0;
1589
0
  buffer->keylen = 0;
1590
0
  buffer->nitems = 0;
1591
0
  buffer->nfrozen = 0;
1592
1593
0
  buffer->typlen = 0;
1594
0
  buffer->typbyval = 0;
1595
0
}
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
1603
GinBufferTrim(GinBuffer *buffer)
1604
0
{
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
1619
GinBufferFree(GinBuffer *buffer)
1620
0
{
1621
0
  if (buffer->items)
1622
0
    pfree(buffer->items);
1623
1624
  /* release byref values, do nothing for by-val ones */
1625
0
  if (!GinBufferIsEmpty(buffer) &&
1626
0
    (buffer->category == GIN_CAT_NORM_KEY) && !buffer->typbyval)
1627
0
    pfree(DatumGetPointer(buffer->key));
1628
1629
0
  pfree(buffer);
1630
0
}
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
GinBufferCanAddKey(GinBuffer *buffer, GinTuple *tup)
1640
0
{
1641
  /* empty buffer can accept data for any key */
1642
0
  if (GinBufferIsEmpty(buffer))
1643
0
    return true;
1644
1645
  /* otherwise just data for the same key */
1646
0
  return GinBufferKeyEquals(buffer, tup);
1647
0
}
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
1660
_gin_parallel_merge(GinBuildState *state, IndexInfo *indexInfo)
1661
0
{
1662
0
  GinTuple   *tup;
1663
0
  Size    tuplen;
1664
0
  double    reltuples = 0;
1665
0
  GinBuffer  *buffer;
1666
1667
  /* GIN tuples from workers, merged by leader */
1668
0
  double    numtuples = 0;
1669
1670
  /* wait for workers to scan table and produce partial results */
1671
0
  reltuples = _gin_parallel_heapscan(state, &indexInfo->ii_BrokenHotChain);
1672
1673
  /* Execute the sort */
1674
0
  pgstat_progress_update_param(PROGRESS_CREATEIDX_SUBPHASE,
1675
0
                 PROGRESS_GIN_PHASE_PERFORMSORT_2);
1676
1677
  /* do the actual sort in the leader */
1678
0
  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
0
  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
0
  {
1693
0
    const int progress_index[] = {
1694
0
      PROGRESS_CREATEIDX_SUBPHASE,
1695
0
      PROGRESS_CREATEIDX_TUPLES_TOTAL,
1696
0
      PROGRESS_SCAN_BLOCKS_TOTAL,
1697
0
      PROGRESS_SCAN_BLOCKS_DONE
1698
0
    };
1699
0
    const int64 progress_vals[] = {
1700
0
      PROGRESS_GIN_PHASE_MERGE_2,
1701
0
      state->bs_numtuples,
1702
0
      0, 0
1703
0
    };
1704
1705
0
    pgstat_progress_update_multi_param(4, progress_index, progress_vals);
1706
0
  }
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
0
  while ((tup = tuplesort_getgintuple(state->bs_sortstate, &tuplen, true)) != NULL)
1718
0
  {
1719
0
    MemoryContext oldCtx;
1720
1721
0
    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
0
    if (!GinBufferCanAddKey(buffer, tup))
1729
0
    {
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
0
      AssertCheckItemPointers(buffer);
1736
1737
0
      oldCtx = MemoryContextSwitchTo(state->tmpCtx);
1738
1739
0
      ginEntryInsert(&state->ginstate,
1740
0
               buffer->attnum, buffer->key, buffer->category,
1741
0
               buffer->items, buffer->nitems, &state->buildStats);
1742
1743
0
      MemoryContextSwitchTo(oldCtx);
1744
0
      MemoryContextReset(state->tmpCtx);
1745
1746
      /* discard the existing data */
1747
0
      GinBufferReset(buffer);
1748
0
    }
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
     */
1757
0
    if (GinBufferShouldTrim(buffer, tup))
1758
0
    {
1759
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
1768
0
      oldCtx = MemoryContextSwitchTo(state->tmpCtx);
1769
1770
0
      ginEntryInsert(&state->ginstate,
1771
0
               buffer->attnum, buffer->key, buffer->category,
1772
0
               buffer->items, buffer->nfrozen, &state->buildStats);
1773
1774
0
      MemoryContextSwitchTo(oldCtx);
1775
0
      MemoryContextReset(state->tmpCtx);
1776
1777
      /* truncate the data we've just discarded */
1778
0
      GinBufferTrim(buffer);
1779
0
    }
1780
1781
    /*
1782
     * Remember data for the current tuple (either remember the new key,
1783
     * or append if to the existing data).
1784
     */
1785
0
    GinBufferStoreTuple(buffer, tup);
1786
1787
    /* Report progress */
1788
0
    pgstat_progress_update_param(PROGRESS_CREATEIDX_TUPLES_DONE,
1789
0
                   ++numtuples);
1790
0
  }
1791
1792
  /* flush data remaining in the buffer (for the last key) */
1793
0
  if (!GinBufferIsEmpty(buffer))
1794
0
  {
1795
0
    AssertCheckItemPointers(buffer);
1796
1797
0
    ginEntryInsert(&state->ginstate,
1798
0
             buffer->attnum, buffer->key, buffer->category,
1799
0
             buffer->items, buffer->nitems, &state->buildStats);
1800
1801
    /* discard the existing data */
1802
0
    GinBufferReset(buffer);
1803
0
  }
1804
1805
  /* release all the memory */
1806
0
  GinBufferFree(buffer);
1807
1808
0
  tuplesort_end(state->bs_sortstate);
1809
1810
0
  return reltuples;
1811
0
}
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
_gin_parallel_estimate_shared(Relation heap, Snapshot snapshot)
1819
0
{
1820
  /* c.f. shm_toc_allocate as to why BUFFERALIGN is used */
1821
0
  return add_size(BUFFERALIGN(sizeof(GinBuildShared)),
1822
0
          table_parallelscan_estimate(heap, snapshot));
1823
0
}
1824
1825
/*
1826
 * Within leader, participate as a parallel worker.
1827
 */
1828
static void
1829
_gin_leader_participate_as_worker(GinBuildState *buildstate, Relation heap, Relation index)
1830
0
{
1831
0
  GinLeader  *ginleader = buildstate->bs_leader;
1832
0
  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
0
  sortmem = maintenance_work_mem / ginleader->nparticipanttuplesorts;
1840
1841
  /* Perform work common to all participants */
1842
0
  _gin_parallel_scan_and_build(buildstate, ginleader->ginshared,
1843
0
                 ginleader->sharedsort, heap, index,
1844
0
                 sortmem, true);
1845
0
}
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
_gin_process_worker_data(GinBuildState *state, Tuplesortstate *worker_sort,
1863
             bool progress)
1864
0
{
1865
0
  GinTuple   *tup;
1866
0
  Size    tuplen;
1867
1868
0
  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
0
  buffer = GinBufferInit(state->ginstate.index);
1878
1879
  /* sort the raw per-worker data */
1880
0
  if (progress)
1881
0
    pgstat_progress_update_param(PROGRESS_CREATEIDX_SUBPHASE,
1882
0
                   PROGRESS_GIN_PHASE_PERFORMSORT_1);
1883
1884
0
  tuplesort_performsort(state->bs_worker_sort);
1885
1886
0
  if (progress)
1887
0
    pgstat_progress_update_param(PROGRESS_CREATEIDX_SUBPHASE,
1888
0
                   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
0
  while ((tup = tuplesort_getgintuple(worker_sort, &tuplen, true)) != NULL)
1895
0
  {
1896
1897
0
    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
0
    if (!GinBufferCanAddKey(buffer, tup))
1905
0
    {
1906
0
      GinTuple   *ntup;
1907
0
      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
0
      AssertCheckItemPointers(buffer);
1915
1916
0
      ntup = _gin_build_tuple(buffer->attnum, buffer->category,
1917
0
                  buffer->key, buffer->typlen, buffer->typbyval,
1918
0
                  buffer->items, buffer->nitems, &ntuplen);
1919
1920
0
      tuplesort_putgintuple(state->bs_sortstate, ntup, ntuplen);
1921
0
      state->bs_numtuples++;
1922
1923
0
      pfree(ntup);
1924
1925
      /* discard the existing data */
1926
0
      GinBufferReset(buffer);
1927
0
    }
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
     */
1936
0
    if (GinBufferShouldTrim(buffer, tup))
1937
0
    {
1938
0
      GinTuple   *ntup;
1939
0
      Size    ntuplen;
1940
1941
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);
1955
0
      state->bs_numtuples++;
1956
1957
0
      pfree(ntup);
1958
1959
      /* truncate the data we've just discarded */
1960
0
      GinBufferTrim(buffer);
1961
0
    }
1962
1963
    /*
1964
     * Remember data for the current tuple (either remember the new key,
1965
     * or append if to the existing data).
1966
     */
1967
0
    GinBufferStoreTuple(buffer, tup);
1968
0
  }
1969
1970
  /* flush data remaining in the buffer (for the last key) */
1971
0
  if (!GinBufferIsEmpty(buffer))
1972
0
  {
1973
0
    GinTuple   *ntup;
1974
0
    Size    ntuplen;
1975
1976
0
    AssertCheckItemPointers(buffer);
1977
1978
0
    ntup = _gin_build_tuple(buffer->attnum, buffer->category,
1979
0
                buffer->key, buffer->typlen, buffer->typbyval,
1980
0
                buffer->items, buffer->nitems, &ntuplen);
1981
1982
0
    tuplesort_putgintuple(state->bs_sortstate, ntup, ntuplen);
1983
0
    state->bs_numtuples++;
1984
1985
0
    pfree(ntup);
1986
1987
    /* discard the existing data */
1988
0
    GinBufferReset(buffer);
1989
0
  }
1990
1991
  /* release all the memory */
1992
0
  GinBufferFree(buffer);
1993
1994
0
  tuplesort_end(worker_sort);
1995
0
}
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
_gin_parallel_scan_and_build(GinBuildState *state,
2039
               GinBuildShared *ginshared, Sharedsort *sharedsort,
2040
               Relation heap, Relation index,
2041
               int sortmem, bool progress)
2042
0
{
2043
0
  SortCoordinate coordinate;
2044
0
  TableScanDesc scan;
2045
0
  double    reltuples;
2046
0
  IndexInfo  *indexInfo;
2047
2048
  /* Initialize local tuplesort coordination state */
2049
0
  coordinate = palloc0_object(SortCoordinateData);
2050
0
  coordinate->isWorker = true;
2051
0
  coordinate->nParticipants = -1;
2052
0
  coordinate->sharedsort = sharedsort;
2053
2054
  /* remember how much space is allowed for the accumulated entries */
2055
0
  state->work_mem = (sortmem / 2);
2056
2057
  /* remember how many workers participate in the build */
2058
0
  state->bs_num_workers = ginshared->scantuplesortstates;
2059
2060
  /* Begin "partial" tuplesort */
2061
0
  state->bs_sortstate = tuplesort_begin_index_gin(heap, index,
2062
0
                          state->work_mem,
2063
0
                          coordinate,
2064
0
                          TUPLESORT_NONE);
2065
2066
  /* Local per-worker sort of raw-data */
2067
0
  state->bs_worker_sort = tuplesort_begin_index_gin(heap, index,
2068
0
                            state->work_mem,
2069
0
                            NULL,
2070
0
                            TUPLESORT_NONE);
2071
2072
  /* Join parallel scan */
2073
0
  indexInfo = BuildIndexInfo(index);
2074
0
  indexInfo->ii_Concurrent = ginshared->isconcurrent;
2075
2076
0
  scan = table_beginscan_parallel(heap,
2077
0
                  ParallelTableScanFromGinBuildShared(ginshared),
2078
0
                  SO_NONE);
2079
2080
0
  reltuples = table_index_build_scan(heap, index, indexInfo, true, progress,
2081
0
                     ginBuildCallbackParallel, state, scan);
2082
2083
  /* write remaining accumulated entries */
2084
0
  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
0
  _gin_process_worker_data(state, state->bs_worker_sort, progress);
2092
2093
  /* sort the GIN tuples built by this worker */
2094
0
  tuplesort_performsort(state->bs_sortstate);
2095
2096
0
  state->bs_reltuples += reltuples;
2097
2098
  /*
2099
   * Done.  Record ambuild statistics, and whether we encountered a broken
2100
   * HOT chain.
2101
   */
2102
0
  SpinLockAcquire(&ginshared->mutex);
2103
0
  ginshared->nparticipantsdone++;
2104
0
  ginshared->reltuples += state->bs_reltuples;
2105
0
  ginshared->indtuples += state->bs_numtuples;
2106
0
  if (indexInfo->ii_BrokenHotChain)
2107
0
    ginshared->brokenhotchain = true;
2108
0
  SpinLockRelease(&ginshared->mutex);
2109
2110
  /* Notify leader */
2111
0
  ConditionVariableSignal(&ginshared->workersdonecv);
2112
2113
0
  tuplesort_end(state->bs_sortstate);
2114
0
}
2115
2116
/*
2117
 * Perform work within a launched parallel process.
2118
 */
2119
void
2120
_gin_parallel_build_main(dsm_segment *seg, shm_toc *toc)
2121
0
{
2122
0
  char     *sharedquery;
2123
0
  GinBuildShared *ginshared;
2124
0
  Sharedsort *sharedsort;
2125
0
  GinBuildState buildstate;
2126
0
  Relation  heapRel;
2127
0
  Relation  indexRel;
2128
0
  LOCKMODE  heapLockmode;
2129
0
  LOCKMODE  indexLockmode;
2130
0
  WalUsage   *walusage;
2131
0
  BufferUsage *bufferusage;
2132
0
  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
0
  Assert((MyProc->statusFlags == 0) ||
2139
0
       (MyProc->statusFlags == PROC_IN_SAFE_IC));
2140
2141
  /* Set debug_query_string for individual workers first */
2142
0
  sharedquery = shm_toc_lookup(toc, PARALLEL_KEY_QUERY_TEXT, true);
2143
0
  debug_query_string = sharedquery;
2144
2145
  /* Report the query string from leader */
2146
0
  pgstat_report_activity(STATE_RUNNING, debug_query_string);
2147
2148
  /* Look up gin shared state */
2149
0
  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
0
  if (!ginshared->isconcurrent)
2153
0
  {
2154
0
    heapLockmode = ShareLock;
2155
0
    indexLockmode = AccessExclusiveLock;
2156
0
  }
2157
0
  else
2158
0
  {
2159
0
    heapLockmode = ShareUpdateExclusiveLock;
2160
0
    indexLockmode = RowExclusiveLock;
2161
0
  }
2162
2163
  /* Track query ID */
2164
0
  pgstat_report_query_id(ginshared->queryid, false);
2165
2166
  /* Open relations within worker */
2167
0
  heapRel = table_open(ginshared->heaprelid, heapLockmode);
2168
0
  indexRel = index_open(ginshared->indexrelid, indexLockmode);
2169
2170
  /* initialize the GIN build state */
2171
0
  initGinState(&buildstate.ginstate, indexRel);
2172
0
  buildstate.indtuples = 0;
2173
2174
  /* Initialize counters used to report tuple counts to the leader */
2175
0
  buildstate.bs_numtuples = 0;
2176
0
  buildstate.bs_reltuples = 0;
2177
2178
0
  memset(&buildstate.buildStats, 0, sizeof(GinStatsData));
2179
0
  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
0
  buildstate.tmpCtx = AllocSetContextCreate(CurrentMemoryContext,
2186
0
                        "Gin build temporary context",
2187
0
                        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
0
  buildstate.funcCtx = AllocSetContextCreate(CurrentMemoryContext,
2194
0
                         "Gin build temporary context for user-defined function",
2195
0
                         ALLOCSET_DEFAULT_SIZES);
2196
2197
0
  buildstate.accum.ginstate = &buildstate.ginstate;
2198
0
  ginInitBA(&buildstate.accum);
2199
2200
2201
  /* Look up shared state private to tuplesort.c */
2202
0
  sharedsort = shm_toc_lookup(toc, PARALLEL_KEY_TUPLESORT, false);
2203
0
  tuplesort_attach_shared(sharedsort, seg);
2204
2205
  /* Prepare to track buffer usage during parallel execution */
2206
0
  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
0
  sortmem = maintenance_work_mem / ginshared->scantuplesortstates;
2214
2215
0
  _gin_parallel_scan_and_build(&buildstate, ginshared, sharedsort,
2216
0
                 heapRel, indexRel, sortmem, false);
2217
2218
  /* Report WAL/buffer usage during parallel execution */
2219
0
  bufferusage = shm_toc_lookup(toc, PARALLEL_KEY_BUFFER_USAGE, false);
2220
0
  walusage = shm_toc_lookup(toc, PARALLEL_KEY_WAL_USAGE, false);
2221
0
  InstrEndParallelQuery(&bufferusage[ParallelWorkerNumber],
2222
0
              &walusage[ParallelWorkerNumber]);
2223
2224
0
  index_close(indexRel, indexLockmode);
2225
0
  table_close(heapRel, heapLockmode);
2226
0
}
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
_gin_build_tuple(OffsetNumber attrnum, unsigned char category,
2260
         Datum key, int16 typlen, bool typbyval,
2261
         ItemPointerData *items, uint32 nitems,
2262
         Size *len)
2263
0
{
2264
0
  GinTuple   *tuple;
2265
0
  char     *ptr;
2266
2267
0
  Size    tuplen;
2268
0
  Size    keylen;
2269
2270
0
  dlist_mutable_iter iter;
2271
0
  dlist_head  segments;
2272
0
  int     ncompressed;
2273
0
  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
0
  if (category != GIN_CAT_NORM_KEY)
2289
0
    keylen = 0;
2290
0
  else if (typbyval)
2291
0
    keylen = sizeof(Datum);
2292
0
  else if (typlen > 0)
2293
0
    keylen = typlen;
2294
0
  else if (typlen == -1)
2295
0
    keylen = VARSIZE_ANY(DatumGetPointer(key));
2296
0
  else if (typlen == -2)
2297
0
    keylen = strlen(DatumGetPointer(key)) + 1;
2298
0
  else
2299
0
    elog(ERROR, "unexpected typlen value (%d)", typlen);
2300
2301
  /* compress the item pointers */
2302
0
  ncompressed = 0;
2303
0
  compresslen = 0;
2304
0
  dlist_init(&segments);
2305
2306
  /* generate compressed segments of TID list chunks */
2307
0
  while (ncompressed < nitems)
2308
0
  {
2309
0
    int     cnt;
2310
0
    GinSegmentInfo *seginfo = palloc_object(GinSegmentInfo);
2311
2312
0
    seginfo->seg = ginCompressPostingList(&items[ncompressed],
2313
0
                        (nitems - ncompressed),
2314
0
                        UINT16_MAX,
2315
0
                        &cnt);
2316
2317
0
    ncompressed += cnt;
2318
0
    compresslen += SizeOfGinPostingList(seginfo->seg);
2319
2320
0
    dlist_push_tail(&segments, &seginfo->node);
2321
0
  }
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
0
  tuplen = SHORTALIGN(offsetof(GinTuple, data) + keylen) + compresslen;
2329
2330
0
  *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
0
  tuple = palloc0(tuplen);
2340
2341
0
  tuple->tuplen = tuplen;
2342
0
  tuple->attrnum = attrnum;
2343
0
  tuple->category = category;
2344
0
  tuple->keylen = keylen;
2345
0
  tuple->nitems = nitems;
2346
2347
  /* key type info */
2348
0
  tuple->typlen = typlen;
2349
0
  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
0
  if (category == GIN_CAT_NORM_KEY)
2356
0
  {
2357
0
    if (typbyval)
2358
0
    {
2359
0
      memcpy(tuple->data, &key, sizeof(Datum));
2360
0
    }
2361
0
    else if (typlen > 0) /* byref, fixed length */
2362
0
    {
2363
0
      memcpy(tuple->data, DatumGetPointer(key), typlen);
2364
0
    }
2365
0
    else if (typlen == -1)
2366
0
    {
2367
0
      memcpy(tuple->data, DatumGetPointer(key), keylen);
2368
0
    }
2369
0
    else if (typlen == -2)
2370
0
    {
2371
0
      memcpy(tuple->data, DatumGetPointer(key), keylen);
2372
0
    }
2373
0
  }
2374
2375
  /* finally, copy the TIDs into the array */
2376
0
  ptr = (char *) tuple + SHORTALIGN(offsetof(GinTuple, data) + keylen);
2377
2378
  /* copy in the compressed data, and free the segments */
2379
0
  dlist_foreach_modify(iter, &segments)
2380
0
  {
2381
0
    GinSegmentInfo *seginfo = dlist_container(GinSegmentInfo, node, iter.cur);
2382
2383
0
    memcpy(ptr, seginfo->seg, SizeOfGinPostingList(seginfo->seg));
2384
2385
0
    ptr += SizeOfGinPostingList(seginfo->seg);
2386
2387
0
    dlist_delete(&seginfo->node);
2388
2389
0
    pfree(seginfo->seg);
2390
0
    pfree(seginfo);
2391
0
  }
2392
2393
0
  return tuple;
2394
0
}
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
2408
_gin_parse_tuple_key(GinTuple *a)
2409
0
{
2410
0
  Datum   key;
2411
2412
0
  if (a->category != GIN_CAT_NORM_KEY)
2413
0
    return (Datum) 0;
2414
2415
0
  if (a->typbyval)
2416
0
  {
2417
0
    memcpy(&key, a->data, a->keylen);
2418
0
    return key;
2419
0
  }
2420
2421
0
  return PointerGetDatum(a->data);
2422
0
}
2423
2424
/*
2425
 * _gin_parse_tuple_items
2426
 *    Return a pointer to a palloc'd array of decompressed TID array.
2427
 */
2428
static ItemPointer
2429
_gin_parse_tuple_items(GinTuple *a)
2430
0
{
2431
0
  int     len;
2432
0
  char     *ptr;
2433
0
  int     ndecoded;
2434
0
  ItemPointer items;
2435
2436
0
  len = a->tuplen - SHORTALIGN(offsetof(GinTuple, data) + a->keylen);
2437
0
  ptr = (char *) a + SHORTALIGN(offsetof(GinTuple, data) + a->keylen);
2438
2439
0
  items = ginPostingListDecodeAllSegments((GinPostingList *) ptr, len, &ndecoded);
2440
2441
0
  Assert(ndecoded == a->nitems);
2442
2443
0
  return items;
2444
0
}
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
2461
_gin_compare_tuples(GinTuple *a, GinTuple *b, SortSupport ssup)
2462
0
{
2463
0
  int     r;
2464
0
  Datum   keya,
2465
0
        keyb;
2466
2467
0
  if (a->attrnum < b->attrnum)
2468
0
    return -1;
2469
2470
0
  if (a->attrnum > b->attrnum)
2471
0
    return 1;
2472
2473
0
  if (a->category < b->category)
2474
0
    return -1;
2475
2476
0
  if (a->category > b->category)
2477
0
    return 1;
2478
2479
0
  if (a->category == GIN_CAT_NORM_KEY)
2480
0
  {
2481
0
    keya = _gin_parse_tuple_key(a);
2482
0
    keyb = _gin_parse_tuple_key(b);
2483
2484
0
    r = ApplySortComparator(keya, false,
2485
0
                keyb, false,
2486
0
                &ssup[a->attrnum - 1]);
2487
2488
    /* if the key is the same, consider the first TID in the array */
2489
0
    return (r != 0) ? r : ItemPointerCompare(GinTupleGetFirst(a),
2490
0
                         GinTupleGetFirst(b));
2491
0
  }
2492
2493
0
  return ItemPointerCompare(GinTupleGetFirst(a),
2494
0
                GinTupleGetFirst(b));
2495
0
}