PostgreSQL Source Code  git master
gin_private.h File Reference
#include "access/amapi.h"
#include "access/gin.h"
#include "access/ginblock.h"
#include "access/itup.h"
#include "fmgr.h"
#include "storage/bufmgr.h"
#include "lib/rbtree.h"
Include dependency graph for gin_private.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  GinOptions
 
struct  GinState
 
struct  GinBtreeStack
 
struct  GinBtreeData
 
struct  GinBtreeEntryInsertData
 
struct  GinBtreeDataLeafInsertData
 
struct  GinScanKeyData
 
struct  GinScanEntryData
 
struct  GinScanOpaqueData
 
struct  GinEntryAccumulator
 
struct  BuildAccumulator
 
struct  GinTupleCollector
 

Macros

#define GIN_DEFAULT_USE_FASTUPDATE   true
 
#define GinGetUseFastUpdate(relation)
 
#define GinGetPendingListCleanupSize(relation)
 
#define GIN_UNLOCK   BUFFER_LOCK_UNLOCK
 
#define GIN_SHARE   BUFFER_LOCK_SHARE
 
#define GIN_EXCLUSIVE   BUFFER_LOCK_EXCLUSIVE
 

Typedefs

typedef struct GinOptions GinOptions
 
typedef struct GinState GinState
 
typedef struct GinBtreeStack GinBtreeStack
 
typedef struct GinBtreeDataGinBtree
 
typedef struct GinBtreeData GinBtreeData
 
typedef struct GinVacuumState GinVacuumState
 
typedef struct GinScanKeyDataGinScanKey
 
typedef struct GinScanEntryDataGinScanEntry
 
typedef struct GinScanKeyData GinScanKeyData
 
typedef struct GinScanEntryData GinScanEntryData
 
typedef struct GinScanOpaqueData GinScanOpaqueData
 
typedef GinScanOpaqueDataGinScanOpaque
 
typedef struct GinEntryAccumulator GinEntryAccumulator
 
typedef struct GinTupleCollector GinTupleCollector
 

Enumerations

enum  GinPlaceToPageRC { GPTP_NO_WORK, GPTP_INSERT, GPTP_SPLIT }
 

Functions

byteaginoptions (Datum reloptions, bool validate)
 
void initGinState (GinState *state, Relation index)
 
Buffer GinNewBuffer (Relation index)
 
void GinInitBuffer (Buffer b, uint32 f)
 
void GinInitPage (Page page, uint32 f, Size pageSize)
 
void GinInitMetabuffer (Buffer b)
 
int ginCompareEntries (GinState *ginstate, OffsetNumber attnum, Datum a, GinNullCategory categorya, Datum b, GinNullCategory categoryb)
 
int ginCompareAttEntries (GinState *ginstate, OffsetNumber attnuma, Datum a, GinNullCategory categorya, OffsetNumber attnumb, Datum b, GinNullCategory categoryb)
 
DatumginExtractEntries (GinState *ginstate, OffsetNumber attnum, Datum value, bool isNull, int32 *nentries, GinNullCategory **categories)
 
OffsetNumber gintuple_get_attrnum (GinState *ginstate, IndexTuple tuple)
 
Datum gintuple_get_key (GinState *ginstate, IndexTuple tuple, GinNullCategory *category)
 
IndexBuildResultginbuild (Relation heap, Relation index, struct IndexInfo *indexInfo)
 
void ginbuildempty (Relation index)
 
bool gininsert (Relation index, Datum *values, bool *isnull, ItemPointer ht_ctid, Relation heapRel, IndexUniqueCheck checkUnique, struct IndexInfo *indexInfo)
 
void ginEntryInsert (GinState *ginstate, OffsetNumber attnum, Datum key, GinNullCategory category, ItemPointerData *items, uint32 nitem, GinStatsData *buildStats)
 
GinBtreeStackginFindLeafPage (GinBtree btree, bool searchMode, bool rootConflictCheck, Snapshot snapshot)
 
Buffer ginStepRight (Buffer buffer, Relation index, int lockmode)
 
void freeGinBtreeStack (GinBtreeStack *stack)
 
void ginInsertValue (GinBtree btree, GinBtreeStack *stack, void *insertdata, GinStatsData *buildStats)
 
IndexTuple GinFormTuple (GinState *ginstate, OffsetNumber attnum, Datum key, GinNullCategory category, Pointer data, Size dataSize, int nipd, bool errorTooBig)
 
void ginPrepareEntryScan (GinBtree btree, OffsetNumber attnum, Datum key, GinNullCategory category, GinState *ginstate)
 
void ginEntryFillRoot (GinBtree btree, Page root, BlockNumber lblkno, Page lpage, BlockNumber rblkno, Page rpage)
 
ItemPointer ginReadTuple (GinState *ginstate, OffsetNumber attnum, IndexTuple itup, int *nitems)
 
ItemPointer GinDataLeafPageGetItems (Page page, int *nitems, ItemPointerData advancePast)
 
int GinDataLeafPageGetItemsToTbm (Page page, TIDBitmap *tbm)
 
BlockNumber createPostingTree (Relation index, ItemPointerData *items, uint32 nitems, GinStatsData *buildStats, Buffer entrybuffer)
 
void GinDataPageAddPostingItem (Page page, PostingItem *data, OffsetNumber offset)
 
void GinPageDeletePostingItem (Page page, OffsetNumber offset)
 
void ginInsertItemPointers (Relation index, BlockNumber rootBlkno, ItemPointerData *items, uint32 nitem, GinStatsData *buildStats)
 
GinBtreeStackginScanBeginPostingTree (GinBtree btree, Relation index, BlockNumber rootBlkno, Snapshot snapshot)
 
void ginDataFillRoot (GinBtree btree, Page root, BlockNumber lblkno, Page lpage, BlockNumber rblkno, Page rpage)
 
void ginVacuumPostingTreeLeaf (Relation rel, Buffer buf, GinVacuumState *gvs)
 
IndexScanDesc ginbeginscan (Relation rel, int nkeys, int norderbys)
 
void ginendscan (IndexScanDesc scan)
 
void ginrescan (IndexScanDesc scan, ScanKey key, int nscankeys, ScanKey orderbys, int norderbys)
 
void ginNewScanKey (IndexScanDesc scan)
 
void ginFreeScanKeys (GinScanOpaque so)
 
int64 gingetbitmap (IndexScanDesc scan, TIDBitmap *tbm)
 
void ginInitConsistentFunction (GinState *ginstate, GinScanKey key)
 
IndexBulkDeleteResultginbulkdelete (IndexVacuumInfo *info, IndexBulkDeleteResult *stats, IndexBulkDeleteCallback callback, void *callback_state)
 
IndexBulkDeleteResultginvacuumcleanup (IndexVacuumInfo *info, IndexBulkDeleteResult *stats)
 
ItemPointer ginVacuumItemPointers (GinVacuumState *gvs, ItemPointerData *items, int nitem, int *nremaining)
 
bool ginvalidate (Oid opclassoid)
 
void ginInitBA (BuildAccumulator *accum)
 
void ginInsertBAEntries (BuildAccumulator *accum, ItemPointer heapptr, OffsetNumber attnum, Datum *entries, GinNullCategory *categories, int32 nentries)
 
void ginBeginBAScan (BuildAccumulator *accum)
 
ItemPointerDataginGetBAEntry (BuildAccumulator *accum, OffsetNumber *attnum, Datum *key, GinNullCategory *category, uint32 *n)
 
void ginHeapTupleFastInsert (GinState *ginstate, GinTupleCollector *collector)
 
void ginHeapTupleFastCollect (GinState *ginstate, GinTupleCollector *collector, OffsetNumber attnum, Datum value, bool isNull, ItemPointer ht_ctid)
 
void ginInsertCleanup (GinState *ginstate, bool full_clean, bool fill_fsm, bool forceCleanup, IndexBulkDeleteResult *stats)
 
GinPostingListginCompressPostingList (const ItemPointer ptrs, int nptrs, int maxsize, int *nwritten)
 
int ginPostingListDecodeAllSegmentsToTbm (GinPostingList *ptr, int totalsize, TIDBitmap *tbm)
 
ItemPointer ginPostingListDecodeAllSegments (GinPostingList *ptr, int len, int *ndecoded)
 
ItemPointer ginPostingListDecode (GinPostingList *ptr, int *ndecoded)
 
ItemPointer ginMergeItemPointers (ItemPointerData *a, uint32 na, ItemPointerData *b, uint32 nb, int *nmerged)
 
static int ginCompareItemPointers (ItemPointer a, ItemPointer b)
 
int ginTraverseLock (Buffer buffer, bool searchMode)
 

Macro Definition Documentation

◆ GIN_DEFAULT_USE_FASTUPDATE

#define GIN_DEFAULT_USE_FASTUPDATE   true

Definition at line 31 of file gin_private.h.

◆ GIN_EXCLUSIVE

◆ GIN_SHARE

◆ GIN_UNLOCK

◆ GinGetPendingListCleanupSize

#define GinGetPendingListCleanupSize (   relation)
Value:
((relation)->rd_options && \
((GinOptions *) (relation)->rd_options)->pendingListCleanupSize != -1 ? \
((GinOptions *) (relation)->rd_options)->pendingListCleanupSize : \
int gin_pending_list_limit
Definition: ginfast.c:38

Definition at line 35 of file gin_private.h.

Referenced by ginHeapTupleFastInsert().

◆ GinGetUseFastUpdate

#define GinGetUseFastUpdate (   relation)
Value:
((relation)->rd_options ? \
((GinOptions *) (relation)->rd_options)->useFastUpdate : GIN_DEFAULT_USE_FASTUPDATE)
#define GIN_DEFAULT_USE_FASTUPDATE
Definition: gin_private.h:31

Definition at line 32 of file gin_private.h.

Referenced by gininsert().

Typedef Documentation

◆ GinBtree

Definition at line 133 of file gin_private.h.

◆ GinBtreeData

◆ GinBtreeStack

◆ GinEntryAccumulator

◆ GinOptions

◆ GinScanEntry

Definition at line 258 of file gin_private.h.

◆ GinScanEntryData

◆ GinScanKey

Definition at line 256 of file gin_private.h.

◆ GinScanKeyData

◆ GinScanOpaque

◆ GinScanOpaqueData

◆ GinState

◆ GinTupleCollector

◆ GinVacuumState

Definition at line 235 of file gin_private.h.

Enumeration Type Documentation

◆ GinPlaceToPageRC

Enumerator
GPTP_NO_WORK 
GPTP_INSERT 
GPTP_SPLIT 

Definition at line 136 of file gin_private.h.

Function Documentation

◆ createPostingTree()

BlockNumber createPostingTree ( Relation  index,
ItemPointerData items,
uint32  nitems,
GinStatsData buildStats,
Buffer  entrybuffer 
)

Definition at line 1766 of file gindatapage.c.

References BufferGetBlockNumber(), BufferGetPage, DEBUG2, elog, END_CRIT_SECTION, GIN_COMPRESSED, GIN_DATA, GIN_LEAF, ginCompressPostingList(), GinDataLeafPageGetPostingList, GinDataPageMaxDataSize, GinDataPageSetDataSize, GinInitPage(), ginInsertItemPointers(), GinNewBuffer(), GinPageGetOpaque, GinPostingListSegmentMaxSize, InvalidBlockNumber, MarkBufferDirty(), GinStatsData::nDataPages, PageRestoreTempPage(), PageSetLSN, palloc(), pfree(), PredicateLockPageSplit(), REGBUF_WILL_INIT, RelationNeedsWAL, ginxlogCreatePostingTree::size, SizeOfGinPostingList, START_CRIT_SECTION, UnlockReleaseBuffer(), XLOG_GIN_CREATE_PTREE, XLogBeginInsert(), XLogInsert(), XLogRegisterBuffer(), and XLogRegisterData().

Referenced by addItemPointersToLeafTuple(), and buildFreshLeafTuple().

1768 {
1769  BlockNumber blkno;
1770  Buffer buffer;
1771  Page tmppage;
1772  Page page;
1773  Pointer ptr;
1774  int nrootitems;
1775  int rootsize;
1776  bool is_build = (buildStats != NULL);
1777 
1778  /* Construct the new root page in memory first. */
1779  tmppage = (Page) palloc(BLCKSZ);
1780  GinInitPage(tmppage, GIN_DATA | GIN_LEAF | GIN_COMPRESSED, BLCKSZ);
1781  GinPageGetOpaque(tmppage)->rightlink = InvalidBlockNumber;
1782 
1783  /*
1784  * Write as many of the items to the root page as fit. In segments of max
1785  * GinPostingListSegmentMaxSize bytes each.
1786  */
1787  nrootitems = 0;
1788  rootsize = 0;
1789  ptr = (Pointer) GinDataLeafPageGetPostingList(tmppage);
1790  while (nrootitems < nitems)
1791  {
1792  GinPostingList *segment;
1793  int npacked;
1794  int segsize;
1795 
1796  segment = ginCompressPostingList(&items[nrootitems],
1797  nitems - nrootitems,
1799  &npacked);
1800  segsize = SizeOfGinPostingList(segment);
1801  if (rootsize + segsize > GinDataPageMaxDataSize)
1802  break;
1803 
1804  memcpy(ptr, segment, segsize);
1805  ptr += segsize;
1806  rootsize += segsize;
1807  nrootitems += npacked;
1808  pfree(segment);
1809  }
1810  GinDataPageSetDataSize(tmppage, rootsize);
1811 
1812  /*
1813  * All set. Get a new physical page, and copy the in-memory page to it.
1814  */
1815  buffer = GinNewBuffer(index);
1816  page = BufferGetPage(buffer);
1817  blkno = BufferGetBlockNumber(buffer);
1818 
1819  /*
1820  * Copy any predicate locks from the entry tree leaf (containing posting
1821  * list) to the posting tree.
1822  */
1823  PredicateLockPageSplit(index, BufferGetBlockNumber(entrybuffer), blkno);
1824 
1826 
1827  PageRestoreTempPage(tmppage, page);
1828  MarkBufferDirty(buffer);
1829 
1830  if (RelationNeedsWAL(index) && !is_build)
1831  {
1832  XLogRecPtr recptr;
1834 
1835  data.size = rootsize;
1836 
1837  XLogBeginInsert();
1838  XLogRegisterData((char *) &data, sizeof(ginxlogCreatePostingTree));
1839 
1841  rootsize);
1843 
1844  recptr = XLogInsert(RM_GIN_ID, XLOG_GIN_CREATE_PTREE);
1845  PageSetLSN(page, recptr);
1846  }
1847 
1848  UnlockReleaseBuffer(buffer);
1849 
1850  END_CRIT_SECTION();
1851 
1852  /* During index build, count the newly-added data page */
1853  if (buildStats)
1854  buildStats->nDataPages++;
1855 
1856  elog(DEBUG2, "created GIN posting tree with %d items", nrootitems);
1857 
1858  /*
1859  * Add any remaining TIDs to the newly-created posting tree.
1860  */
1861  if (nitems > nrootitems)
1862  {
1863  ginInsertItemPointers(index, blkno,
1864  items + nrootitems,
1865  nitems - nrootitems,
1866  buildStats);
1867  }
1868 
1869  return blkno;
1870 }
GinPostingList * ginCompressPostingList(const ItemPointer ipd, int nipd, int maxsize, int *nwritten)
Buffer GinNewBuffer(Relation index)
Definition: ginutil.c:292
#define GinPostingListSegmentMaxSize
Definition: gindatapage.c:34
void ginInsertItemPointers(Relation index, BlockNumber rootBlkno, ItemPointerData *items, uint32 nitem, GinStatsData *buildStats)
Definition: gindatapage.c:1899
void PageRestoreTempPage(Page tempPage, Page oldPage)
Definition: bufpage.c:410
void GinInitPage(Page page, uint32 f, Size pageSize)
Definition: ginutil.c:338
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1458
void XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Definition: xloginsert.c:213
#define END_CRIT_SECTION()
Definition: miscadmin.h:134
#define REGBUF_WILL_INIT
Definition: xloginsert.h:33
#define START_CRIT_SECTION()
Definition: miscadmin.h:132
uint32 BlockNumber
Definition: block.h:31
#define GinPageGetOpaque(page)
Definition: ginblock.h:110
#define GIN_COMPRESSED
Definition: ginblock.h:48
#define GIN_DATA
Definition: ginblock.h:40
#define GinDataPageSetDataSize(page, size)
Definition: ginblock.h:313
void pfree(void *pointer)
Definition: mcxt.c:1031
char * Pointer
Definition: c.h:335
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3376
#define XLOG_GIN_CREATE_PTREE
Definition: ginxlog.h:19
#define DEBUG2
Definition: elog.h:24
#define BufferGetPage(buffer)
Definition: bufmgr.h:159
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:323
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:415
#define GinDataLeafPageGetPostingList(page)
Definition: ginblock.h:282
BlockNumber nDataPages
Definition: gin.h:46
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define InvalidBlockNumber
Definition: block.h:33
#define RelationNeedsWAL(relation)
Definition: rel.h:516
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition: bufmgr.c:2613
#define GinDataPageMaxDataSize
Definition: ginblock.h:323
void * palloc(Size size)
Definition: mcxt.c:924
#define SizeOfGinPostingList(plist)
Definition: ginblock.h:346
#define elog(elevel,...)
Definition: elog.h:226
void XLogBeginInsert(void)
Definition: xloginsert.c:120
#define PageSetLSN(page, lsn)
Definition: bufpage.h:368
int Buffer
Definition: buf.h:23
void PredicateLockPageSplit(Relation relation, BlockNumber oldblkno, BlockNumber newblkno)
Definition: predicate.c:3118
Pointer Page
Definition: bufpage.h:78
#define GIN_LEAF
Definition: ginblock.h:41

◆ freeGinBtreeStack()

void freeGinBtreeStack ( GinBtreeStack stack)

Definition at line 201 of file ginbtree.c.

References GinBtreeStack::buffer, InvalidBuffer, GinBtreeStack::parent, pfree(), and ReleaseBuffer().

Referenced by entryLoadMoreItems(), ginEntryInsert(), ginFinishSplit(), ginInsertValue(), scanPostingTree(), and startScanEntry().

202 {
203  while (stack)
204  {
205  GinBtreeStack *tmp = stack->parent;
206 
207  if (stack->buffer != InvalidBuffer)
208  ReleaseBuffer(stack->buffer);
209 
210  pfree(stack);
211  stack = tmp;
212  }
213 }
#define InvalidBuffer
Definition: buf.h:25
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3353
void pfree(void *pointer)
Definition: mcxt.c:1031
struct GinBtreeStack * parent
Definition: gin_private.h:130

◆ ginBeginBAScan()

void ginBeginBAScan ( BuildAccumulator accum)

Definition at line 257 of file ginbulk.c.

References LeftRightWalk, rbt_begin_iterate(), BuildAccumulator::tree, and BuildAccumulator::tree_walk.

Referenced by ginbuild(), ginBuildCallback(), and ginInsertCleanup().

258 {
259  rbt_begin_iterate(accum->tree, LeftRightWalk, &accum->tree_walk);
260 }
void rbt_begin_iterate(RBTree *rbt, RBTOrderControl ctrl, RBTreeIterator *iter)
Definition: rbtree.c:740
RBTreeIterator tree_walk
Definition: gin_private.h:412

◆ ginbeginscan()

IndexScanDesc ginbeginscan ( Relation  rel,
int  nkeys,
int  norderbys 
)

Definition at line 25 of file ginscan.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, CurrentMemoryContext, GinScanOpaqueData::ginstate, IndexScanDescData::indexRelation, initGinState(), GinScanOpaqueData::keyCtx, GinScanOpaqueData::keys, GinScanOpaqueData::nkeys, IndexScanDescData::opaque, palloc(), RelationGetIndexScan(), and GinScanOpaqueData::tempCtx.

Referenced by ginhandler().

26 {
27  IndexScanDesc scan;
28  GinScanOpaque so;
29 
30  /* no order by operators allowed */
31  Assert(norderbys == 0);
32 
33  scan = RelationGetIndexScan(rel, nkeys, norderbys);
34 
35  /* allocate private workspace */
36  so = (GinScanOpaque) palloc(sizeof(GinScanOpaqueData));
37  so->keys = NULL;
38  so->nkeys = 0;
40  "Gin scan temporary context",
43  "Gin scan key context",
45  initGinState(&so->ginstate, scan->indexRelation);
46 
47  scan->opaque = so;
48 
49  return scan;
50 }
#define AllocSetContextCreate
Definition: memutils.h:169
Relation indexRelation
Definition: relscan.h:103
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:191
GinScanOpaqueData * GinScanOpaque
Definition: gin_private.h:364
MemoryContext keyCtx
Definition: gin_private.h:359
void initGinState(GinState *state, Relation index)
Definition: ginutil.c:89
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
GinScanKey keys
Definition: gin_private.h:352
MemoryContext tempCtx
Definition: gin_private.h:349
#define Assert(condition)
Definition: c.h:732
void * palloc(Size size)
Definition: mcxt.c:924
IndexScanDesc RelationGetIndexScan(Relation indexRelation, int nkeys, int norderbys)
Definition: genam.c:80

◆ ginbuild()

IndexBuildResult* ginbuild ( Relation  heap,
Relation  index,
struct IndexInfo indexInfo 
)

Definition at line 317 of file gininsert.c.

References GinBuildState::accum, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, attnum, GinBuildState::buildStats, CHECK_FOR_INTERRUPTS, CurrentMemoryContext, elog, END_CRIT_SECTION, ERROR, GinBuildState::funcCtx, GIN_LEAF, ginBeginBAScan(), ginBuildCallback(), ginEntryInsert(), ginGetBAEntry(), ginInitBA(), GinInitBuffer(), GinInitMetabuffer(), GinNewBuffer(), GinBuildState::ginstate, BuildAccumulator::ginstate, ginUpdateStats(), IndexBuildResult::heap_tuples, IndexBuildResult::index_tuples, GinBuildState::indtuples, initGinState(), sort-test::key, sort-test::list, log_newpage_range(), MAIN_FORKNUM, MarkBufferDirty(), MemoryContextDelete(), MemoryContextSwitchTo(), GinStatsData::nEntryPages, palloc(), RelationGetNumberOfBlocks, RelationGetRelationName, RelationNeedsWAL, reltuples, START_CRIT_SECTION, table_index_build_scan(), GinBuildState::tmpCtx, and UnlockReleaseBuffer().

Referenced by ginhandler().

318 {
319  IndexBuildResult *result;
320  double reltuples;
321  GinBuildState buildstate;
322  Buffer RootBuffer,
323  MetaBuffer;
325  Datum key;
326  GinNullCategory category;
327  uint32 nlist;
328  MemoryContext oldCtx;
330 
331  if (RelationGetNumberOfBlocks(index) != 0)
332  elog(ERROR, "index \"%s\" already contains data",
333  RelationGetRelationName(index));
334 
335  initGinState(&buildstate.ginstate, index);
336  buildstate.indtuples = 0;
337  memset(&buildstate.buildStats, 0, sizeof(GinStatsData));
338 
339  /* initialize the meta page */
340  MetaBuffer = GinNewBuffer(index);
341 
342  /* initialize the root page */
343  RootBuffer = GinNewBuffer(index);
344 
346  GinInitMetabuffer(MetaBuffer);
347  MarkBufferDirty(MetaBuffer);
348  GinInitBuffer(RootBuffer, GIN_LEAF);
349  MarkBufferDirty(RootBuffer);
350 
351 
352  UnlockReleaseBuffer(MetaBuffer);
353  UnlockReleaseBuffer(RootBuffer);
355 
356  /* count the root as first entry page */
357  buildstate.buildStats.nEntryPages++;
358 
359  /*
360  * create a temporary memory context that is used to hold data not yet
361  * dumped out to the index
362  */
364  "Gin build temporary context",
366 
367  /*
368  * create a temporary memory context that is used for calling
369  * ginExtractEntries(), and can be reset after each tuple
370  */
372  "Gin build temporary context for user-defined function",
374 
375  buildstate.accum.ginstate = &buildstate.ginstate;
376  ginInitBA(&buildstate.accum);
377 
378  /*
379  * Do the heap scan. We disallow sync scan here because dataPlaceToPage
380  * prefers to receive tuples in TID order.
381  */
382  reltuples = table_index_build_scan(heap, index, indexInfo, false, true,
383  ginBuildCallback, (void *) &buildstate,
384  NULL);
385 
386  /* dump remaining entries to the index */
387  oldCtx = MemoryContextSwitchTo(buildstate.tmpCtx);
388  ginBeginBAScan(&buildstate.accum);
389  while ((list = ginGetBAEntry(&buildstate.accum,
390  &attnum, &key, &category, &nlist)) != NULL)
391  {
392  /* there could be many entries, so be willing to abort here */
394  ginEntryInsert(&buildstate.ginstate, attnum, key, category,
395  list, nlist, &buildstate.buildStats);
396  }
397  MemoryContextSwitchTo(oldCtx);
398 
399  MemoryContextDelete(buildstate.funcCtx);
400  MemoryContextDelete(buildstate.tmpCtx);
401 
402  /*
403  * Update metapage stats
404  */
406  ginUpdateStats(index, &buildstate.buildStats, true);
407 
408  /*
409  * We didn't write WAL records as we built the index, so if WAL-logging is
410  * required, write all pages to the WAL now.
411  */
412  if (RelationNeedsWAL(index))
413  {
415  0, RelationGetNumberOfBlocks(index),
416  true);
417  }
418 
419  /*
420  * Return statistics
421  */
422  result = (IndexBuildResult *) palloc(sizeof(IndexBuildResult));
423 
424  result->heap_tuples = reltuples;
425  result->index_tuples = buildstate.indtuples;
426 
427  return result;
428 }
BlockNumber nEntryPages
Definition: gin.h:45
Buffer GinNewBuffer(Relation index)
Definition: ginutil.c:292
void GinInitMetabuffer(Buffer b)
Definition: ginutil.c:357
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:169
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1458
#define END_CRIT_SECTION()
Definition: miscadmin.h:134
GinStatsData buildStats
Definition: gininsert.c:35
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define START_CRIT_SECTION()
Definition: miscadmin.h:132
double indtuples
Definition: gininsert.c:34
static void ginBuildCallback(Relation index, HeapTuple htup, Datum *values, bool *isnull, bool tupleIsAlive, void *state)
Definition: gininsert.c:276
uint16 OffsetNumber
Definition: off.h:24
GinState ginstate
Definition: gininsert.c:33
void ginEntryInsert(GinState *ginstate, OffsetNumber attnum, Datum key, GinNullCategory category, ItemPointerData *items, uint32 nitem, GinStatsData *buildStats)
Definition: gininsert.c:180
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3376
#define ERROR
Definition: elog.h:43
signed char GinNullCategory
Definition: ginblock.h:210
static double table_index_build_scan(Relation table_rel, Relation index_rel, struct IndexInfo *index_info, bool allow_sync, bool progress, IndexBuildCallback callback, void *callback_state, TableScanDesc scan)
Definition: tableam.h:1500
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:191
BuildAccumulator accum
Definition: gininsert.c:38
void initGinState(GinState *state, Relation index)
Definition: ginutil.c:89
#define RelationGetRelationName(relation)
Definition: rel.h:448
unsigned int uint32
Definition: c.h:358
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
GinState * ginstate
Definition: gin_private.h:407
uintptr_t Datum
Definition: postgres.h:367
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:198
int16 attnum
Definition: pg_attribute.h:79
void GinInitBuffer(Buffer b, uint32 f)
Definition: ginutil.c:351
BlockNumber nTotalPages
Definition: gin.h:44
ItemPointerData * ginGetBAEntry(BuildAccumulator *accum, OffsetNumber *attnum, Datum *key, GinNullCategory *category, uint32 *n)
Definition: ginbulk.c:268
#define RelationNeedsWAL(relation)
Definition: rel.h:516
void ginBeginBAScan(BuildAccumulator *accum)
Definition: ginbulk.c:257
void log_newpage_range(Relation rel, ForkNumber forkNum, BlockNumber startblk, BlockNumber endblk, bool page_std)
Definition: xloginsert.c:1042
void ginUpdateStats(Relation index, const GinStatsData *stats, bool is_build)
Definition: ginutil.c:665
void * palloc(Size size)
Definition: mcxt.c:924
MemoryContext tmpCtx
Definition: gininsert.c:36
#define elog(elevel,...)
Definition: elog.h:226
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
MemoryContext funcCtx
Definition: gininsert.c:37
int Buffer
Definition: buf.h:23
float4 reltuples
Definition: pg_class.h:63
double index_tuples
Definition: genam.h:33
double heap_tuples
Definition: genam.h:32
void ginInitBA(BuildAccumulator *accum)
Definition: ginbulk.c:109
#define GIN_LEAF
Definition: ginblock.h:41

◆ ginbuildempty()

void ginbuildempty ( Relation  index)

Definition at line 434 of file gininsert.c.

References BUFFER_LOCK_EXCLUSIVE, END_CRIT_SECTION, GIN_LEAF, GinInitBuffer(), GinInitMetabuffer(), INIT_FORKNUM, LockBuffer(), log_newpage_buffer(), MarkBufferDirty(), P_NEW, RBM_NORMAL, ReadBufferExtended(), START_CRIT_SECTION, and UnlockReleaseBuffer().

Referenced by ginhandler().

435 {
436  Buffer RootBuffer,
437  MetaBuffer;
438 
439  /* An empty GIN index has two pages. */
440  MetaBuffer =
442  LockBuffer(MetaBuffer, BUFFER_LOCK_EXCLUSIVE);
443  RootBuffer =
445  LockBuffer(RootBuffer, BUFFER_LOCK_EXCLUSIVE);
446 
447  /* Initialize and xlog metabuffer and root buffer. */
449  GinInitMetabuffer(MetaBuffer);
450  MarkBufferDirty(MetaBuffer);
451  log_newpage_buffer(MetaBuffer, true);
452  GinInitBuffer(RootBuffer, GIN_LEAF);
453  MarkBufferDirty(RootBuffer);
454  log_newpage_buffer(RootBuffer, false);
456 
457  /* Unlock and release the buffers. */
458  UnlockReleaseBuffer(MetaBuffer);
459  UnlockReleaseBuffer(RootBuffer);
460 }
void GinInitMetabuffer(Buffer b)
Definition: ginutil.c:357
XLogRecPtr log_newpage_buffer(Buffer buffer, bool page_std)
Definition: xloginsert.c:1009
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1458
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:642
#define END_CRIT_SECTION()
Definition: miscadmin.h:134
#define START_CRIT_SECTION()
Definition: miscadmin.h:132
#define P_NEW
Definition: bufmgr.h:81
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:88
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3376
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3590
void GinInitBuffer(Buffer b, uint32 f)
Definition: ginutil.c:351
int Buffer
Definition: buf.h:23
#define GIN_LEAF
Definition: ginblock.h:41

◆ ginbulkdelete()

IndexBulkDeleteResult* ginbulkdelete ( IndexVacuumInfo info,
IndexBulkDeleteResult stats,
IndexBulkDeleteCallback  callback,
void *  callback_state 
)

Definition at line 545 of file ginvacuum.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, DataPageDeleteStack::blkno, BufferGetPage, GinVacuumState::callback, GinVacuumState::callback_state, CurrentMemoryContext, END_CRIT_SECTION, FirstOffsetNumber, GIN_EXCLUSIVE, GIN_ROOT_BLKNO, GIN_SHARE, GIN_UNLOCK, GinGetDownlink, ginInsertCleanup(), GinPageGetOpaque, GinPageIsData, GinPageIsLeaf, GinVacuumState::ginstate, ginVacuumEntryPage(), ginVacuumPostingTree(), i, GinVacuumState::index, IndexVacuumInfo::index, initGinState(), InvalidBlockNumber, IsAutoVacuumWorkerProcess(), LockBuffer(), MAIN_FORKNUM, MarkBufferDirty(), MemoryContextDelete(), IndexBulkDeleteResult::num_index_tuples, PageGetItem, PageGetItemId, PageGetMaxOffsetNumber, PageRestoreTempPage(), palloc0(), RBM_NORMAL, ReadBufferExtended(), GinVacuumState::result, START_CRIT_SECTION, GinVacuumState::strategy, IndexVacuumInfo::strategy, GinVacuumState::tmpCxt, UnlockReleaseBuffer(), vacuum_delay_point(), and xlogVacuumPage().

Referenced by ginhandler().

547 {
548  Relation index = info->index;
549  BlockNumber blkno = GIN_ROOT_BLKNO;
550  GinVacuumState gvs;
551  Buffer buffer;
552  BlockNumber rootOfPostingTree[BLCKSZ / (sizeof(IndexTupleData) + sizeof(ItemId))];
553  uint32 nRoot;
554 
556  "Gin vacuum temporary context",
558  gvs.index = index;
559  gvs.callback = callback;
560  gvs.callback_state = callback_state;
561  gvs.strategy = info->strategy;
562  initGinState(&gvs.ginstate, index);
563 
564  /* first time through? */
565  if (stats == NULL)
566  {
567  /* Yes, so initialize stats to zeroes */
569 
570  /*
571  * and cleanup any pending inserts
572  */
574  false, true, stats);
575  }
576 
577  /* we'll re-count the tuples each time */
578  stats->num_index_tuples = 0;
579  gvs.result = stats;
580 
581  buffer = ReadBufferExtended(index, MAIN_FORKNUM, blkno,
582  RBM_NORMAL, info->strategy);
583 
584  /* find leaf page */
585  for (;;)
586  {
587  Page page = BufferGetPage(buffer);
588  IndexTuple itup;
589 
590  LockBuffer(buffer, GIN_SHARE);
591 
592  Assert(!GinPageIsData(page));
593 
594  if (GinPageIsLeaf(page))
595  {
596  LockBuffer(buffer, GIN_UNLOCK);
597  LockBuffer(buffer, GIN_EXCLUSIVE);
598 
599  if (blkno == GIN_ROOT_BLKNO && !GinPageIsLeaf(page))
600  {
601  LockBuffer(buffer, GIN_UNLOCK);
602  continue; /* check it one more */
603  }
604  break;
605  }
606 
608 
609  itup = (IndexTuple) PageGetItem(page, PageGetItemId(page, FirstOffsetNumber));
610  blkno = GinGetDownlink(itup);
611  Assert(blkno != InvalidBlockNumber);
612 
613  UnlockReleaseBuffer(buffer);
614  buffer = ReadBufferExtended(index, MAIN_FORKNUM, blkno,
615  RBM_NORMAL, info->strategy);
616  }
617 
618  /* right now we found leftmost page in entry's BTree */
619 
620  for (;;)
621  {
622  Page page = BufferGetPage(buffer);
623  Page resPage;
624  uint32 i;
625 
626  Assert(!GinPageIsData(page));
627 
628  resPage = ginVacuumEntryPage(&gvs, buffer, rootOfPostingTree, &nRoot);
629 
630  blkno = GinPageGetOpaque(page)->rightlink;
631 
632  if (resPage)
633  {
635  PageRestoreTempPage(resPage, page);
636  MarkBufferDirty(buffer);
637  xlogVacuumPage(gvs.index, buffer);
638  UnlockReleaseBuffer(buffer);
640  }
641  else
642  {
643  UnlockReleaseBuffer(buffer);
644  }
645 
647 
648  for (i = 0; i < nRoot; i++)
649  {
650  ginVacuumPostingTree(&gvs, rootOfPostingTree[i]);
652  }
653 
654  if (blkno == InvalidBlockNumber) /* rightmost page */
655  break;
656 
657  buffer = ReadBufferExtended(index, MAIN_FORKNUM, blkno,
658  RBM_NORMAL, info->strategy);
659  LockBuffer(buffer, GIN_EXCLUSIVE);
660  }
661 
663 
664  return gvs.result;
665 }
#define GIN_UNLOCK
Definition: gin_private.h:43
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:169
void PageRestoreTempPage(Page tempPage, Page oldPage)
Definition: bufpage.c:410
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1458
Relation index
Definition: ginvacuum.c:30
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:642
BufferAccessStrategy strategy
Definition: ginvacuum.c:35
#define END_CRIT_SECTION()
Definition: miscadmin.h:134
BufferAccessStrategy strategy
Definition: genam.h:52
#define START_CRIT_SECTION()
Definition: miscadmin.h:132
Relation index
Definition: genam.h:46
uint32 BlockNumber
Definition: block.h:31
#define GinPageGetOpaque(page)
Definition: ginblock.h:110
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:357
IndexBulkDeleteResult * result
Definition: ginvacuum.c:31
Definition: type.h:89
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3376
static void xlogVacuumPage(Relation index, Buffer buffer)
Definition: ginvacuum.c:90
static void callback(struct sockaddr *addr, struct sockaddr *mask, void *unused)
Definition: test_ifaddrs.c:48
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:191
static Page ginVacuumEntryPage(GinVacuumState *gvs, Buffer buffer, BlockNumber *roots, uint32 *nroot)
Definition: ginvacuum.c:436
IndexBulkDeleteCallback callback
Definition: ginvacuum.c:32
#define FirstOffsetNumber
Definition: off.h:27
IndexTupleData * IndexTuple
Definition: itup.h:53
void initGinState(GinState *state, Relation index)
Definition: ginutil.c:89
unsigned int uint32
Definition: c.h:358
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
#define GinPageIsLeaf(page)
Definition: ginblock.h:112
void * callback_state
Definition: ginvacuum.c:33
#define BufferGetPage(buffer)
Definition: bufmgr.h:159
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3278
#define GIN_SHARE
Definition: gin_private.h:44
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:235
void * palloc0(Size size)
Definition: mcxt.c:955
struct IndexTupleData IndexTupleData
#define GIN_EXCLUSIVE
Definition: gin_private.h:45
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3590
#define GinGetDownlink(itup)
Definition: ginblock.h:261
void ginInsertCleanup(GinState *ginstate, bool full_clean, bool fill_fsm, bool forceCleanup, IndexBulkDeleteResult *stats)
Definition: ginfast.c:780
#define GinPageIsData(page)
Definition: ginblock.h:115
#define Assert(condition)
Definition: c.h:732
#define InvalidBlockNumber
Definition: block.h:33
int i
static void ginVacuumPostingTree(GinVacuumState *gvs, BlockNumber rootBlkno)
Definition: ginvacuum.c:389
void vacuum_delay_point(void)
Definition: vacuum.c:1931
MemoryContext tmpCxt
Definition: ginvacuum.c:36
double num_index_tuples
Definition: genam.h:77
int Buffer
Definition: buf.h:23
#define PageGetItem(page, itemId)
Definition: bufpage.h:340
#define GIN_ROOT_BLKNO
Definition: ginblock.h:52
Pointer Page
Definition: bufpage.h:78
GinState ginstate
Definition: ginvacuum.c:34

◆ ginCompareAttEntries()

int ginCompareAttEntries ( GinState ginstate,
OffsetNumber  attnuma,
Datum  a,
GinNullCategory  categorya,
OffsetNumber  attnumb,
Datum  b,
GinNullCategory  categoryb 
)

Definition at line 411 of file ginutil.c.

References ginCompareEntries().

Referenced by cmpEntryAccumulator(), entryIsMoveRight(), entryLocateEntry(), and entryLocateLeafEntry().

414 {
415  /* attribute number is the first sort key */
416  if (attnuma != attnumb)
417  return (attnuma < attnumb) ? -1 : 1;
418 
419  return ginCompareEntries(ginstate, attnuma, a, categorya, b, categoryb);
420 }
int ginCompareEntries(GinState *ginstate, OffsetNumber attnum, Datum a, GinNullCategory categorya, Datum b, GinNullCategory categoryb)
Definition: ginutil.c:389

◆ ginCompareEntries()

int ginCompareEntries ( GinState ginstate,
OffsetNumber  attnum,
Datum  a,
GinNullCategory  categorya,
Datum  b,
GinNullCategory  categoryb 
)

Definition at line 389 of file ginutil.c.

References GinState::compareFn, DatumGetInt32, FunctionCall2Coll(), GIN_CAT_NORM_KEY, and GinState::supportCollation.

Referenced by collectMatchBitmap(), collectMatchesForHeapRow(), ginCompareAttEntries(), and ginFillScanEntry().

392 {
393  /* if not of same null category, sort by that first */
394  if (categorya != categoryb)
395  return (categorya < categoryb) ? -1 : 1;
396 
397  /* all null items in same category are equal */
398  if (categorya != GIN_CAT_NORM_KEY)
399  return 0;
400 
401  /* both not null, so safe to call the compareFn */
402  return DatumGetInt32(FunctionCall2Coll(&ginstate->compareFn[attnum - 1],
403  ginstate->supportCollation[attnum - 1],
404  a, b));
405 }
Oid supportCollation[INDEX_MAX_KEYS]
Definition: gin_private.h:82
#define DatumGetInt32(X)
Definition: postgres.h:472
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1150
#define GIN_CAT_NORM_KEY
Definition: ginblock.h:212
int16 attnum
Definition: pg_attribute.h:79
FmgrInfo compareFn[INDEX_MAX_KEYS]
Definition: gin_private.h:73

◆ ginCompareItemPointers()

static int ginCompareItemPointers ( ItemPointer  a,
ItemPointer  b 
)
inlinestatic

Definition at line 461 of file gin_private.h.

References GinItemPointerGetBlockNumber, GinItemPointerGetOffsetNumber, and ginTraverseLock().

Referenced by addItemsToLeaf(), dataBeginPlaceToPageLeaf(), dataIsMoveRight(), dataLocateItem(), entryGetItem(), entryLoadMoreItems(), ginCombineData(), GinDataLeafPageGetItems(), ginMergeItemPointers(), ginPostingListDecodeAllSegments(), keyGetItem(), qsortCompareItemPointers(), and scanGetItem().

462 {
463  uint64 ia = (uint64) GinItemPointerGetBlockNumber(a) << 32 | GinItemPointerGetOffsetNumber(a);
464  uint64 ib = (uint64) GinItemPointerGetBlockNumber(b) << 32 | GinItemPointerGetOffsetNumber(b);
465 
466  if (ia == ib)
467  return 0;
468  else if (ia > ib)
469  return 1;
470  else
471  return -1;
472 }
#define GinItemPointerGetOffsetNumber(pointer)
Definition: ginblock.h:147
#define GinItemPointerGetBlockNumber(pointer)
Definition: ginblock.h:144

◆ ginCompressPostingList()

GinPostingList* ginCompressPostingList ( const ItemPointer  ptrs,
int  nptrs,
int  maxsize,
int *  nwritten 
)

Definition at line 180 of file ginpostinglist.c.

References Assert, buf, generate_unaccent_rules::bytes(), GinPostingList::bytes, encode_varbyte(), GinPostingList::first, ginPostingListDecode(), i, itemptr_to_uint64(), GinPostingList::nbytes, offsetof, palloc(), pfree(), SHORTALIGN, SHORTALIGN_DOWN, SizeOfGinPostingList, and val.

Referenced by addItemPointersToLeafTuple(), buildFreshLeafTuple(), createPostingTree(), ginRedoRecompress(), ginVacuumEntryPage(), ginVacuumPostingTreeLeaf(), and leafRepackItems().

182 {
183  uint64 prev;
184  int totalpacked = 0;
185  int maxbytes;
186  GinPostingList *result;
187  unsigned char *ptr;
188  unsigned char *endptr;
189 
190  maxsize = SHORTALIGN_DOWN(maxsize);
191 
192  result = palloc(maxsize);
193 
194  maxbytes = maxsize - offsetof(GinPostingList, bytes);
195  Assert(maxbytes > 0);
196 
197  /* Store the first special item */
198  result->first = ipd[0];
199 
200  prev = itemptr_to_uint64(&result->first);
201 
202  ptr = result->bytes;
203  endptr = result->bytes + maxbytes;
204  for (totalpacked = 1; totalpacked < nipd; totalpacked++)
205  {
206  uint64 val = itemptr_to_uint64(&ipd[totalpacked]);
207  uint64 delta = val - prev;
208 
209  Assert(val > prev);
210 
211  if (endptr - ptr >= 6)
212  encode_varbyte(delta, &ptr);
213  else
214  {
215  /*
216  * There are less than 6 bytes left. Have to check if the next
217  * item fits in that space before writing it out.
218  */
219  unsigned char buf[6];
220  unsigned char *p = buf;
221 
222  encode_varbyte(delta, &p);
223  if (p - buf > (endptr - ptr))
224  break; /* output is full */
225 
226  memcpy(ptr, buf, p - buf);
227  ptr += (p - buf);
228  }
229  prev = val;
230  }
231  result->nbytes = ptr - result->bytes;
232 
233  /*
234  * If we wrote an odd number of bytes, zero out the padding byte at the
235  * end.
236  */
237  if (result->nbytes != SHORTALIGN(result->nbytes))
238  result->bytes[result->nbytes] = 0;
239 
240  if (nwritten)
241  *nwritten = totalpacked;
242 
243  Assert(SizeOfGinPostingList(result) <= maxsize);
244 
245  /*
246  * Check that the encoded segment decodes back to the original items.
247  */
248 #if defined (CHECK_ENCODING_ROUNDTRIP)
249  {
250  int ndecoded;
251  ItemPointer tmp = ginPostingListDecode(result, &ndecoded);
252  int i;
253 
254  Assert(ndecoded == totalpacked);
255  for (i = 0; i < ndecoded; i++)
256  Assert(memcmp(&tmp[i], &ipd[i], sizeof(ItemPointerData)) == 0);
257  pfree(tmp);
258  }
259 #endif
260 
261  return result;
262 }
ItemPointer ginPostingListDecode(GinPostingList *plist, int *ndecoded)
def bytes(source, encoding='ascii', errors='strict')
#define SHORTALIGN_DOWN(LEN)
Definition: c.h:693
ItemPointerData first
Definition: ginblock.h:341
void pfree(void *pointer)
Definition: mcxt.c:1031
unsigned char bytes[FLEXIBLE_ARRAY_MEMBER]
Definition: ginblock.h:343
static char * buf
Definition: pg_test_fsync.c:68
uint16 nbytes
Definition: ginblock.h:342
#define Assert(condition)
Definition: c.h:732
static uint64 itemptr_to_uint64(const ItemPointer iptr)
static void encode_varbyte(uint64 val, unsigned char **ptr)
void * palloc(Size size)
Definition: mcxt.c:924
#define SizeOfGinPostingList(plist)
Definition: ginblock.h:346
int i
#define SHORTALIGN(LEN)
Definition: c.h:681
long val
Definition: informix.c:689
#define offsetof(type, field)
Definition: c.h:655

◆ ginDataFillRoot()

void ginDataFillRoot ( GinBtree  btree,
Page  root,
BlockNumber  lblkno,
Page  lpage,
BlockNumber  rblkno,
Page  rpage 
)

Definition at line 1340 of file gindatapage.c.

References GinDataPageAddPostingItem(), GinDataPageGetRightBound, InvalidOffsetNumber, PostingItem::key, and PostingItemSetBlockNumber.

Referenced by ginPrepareDataScan().

1341 {
1342  PostingItem li,
1343  ri;
1344 
1345  li.key = *GinDataPageGetRightBound(lpage);
1346  PostingItemSetBlockNumber(&li, lblkno);
1348 
1349  ri.key = *GinDataPageGetRightBound(rpage);
1350  PostingItemSetBlockNumber(&ri, rblkno);
1352 }
#define PostingItemSetBlockNumber(pointer, blockNumber)
Definition: ginblock.h:196
void GinDataPageAddPostingItem(Page page, PostingItem *data, OffsetNumber offset)
Definition: gindatapage.c:377
ItemPointerData key
Definition: ginblock.h:190
#define InvalidOffsetNumber
Definition: off.h:26
#define GinDataPageGetRightBound(page)
Definition: ginblock.h:292

◆ GinDataLeafPageGetItems()

ItemPointer GinDataLeafPageGetItems ( Page  page,
int *  nitems,
ItemPointerData  advancePast 
)

Definition at line 135 of file gindatapage.c.

References dataLeafPageGetUncompressed(), GinPostingList::first, ginCompareItemPointers(), GinDataLeafPageGetPostingList, GinDataLeafPageGetPostingListSize, GinNextPostingListSegment, GinPageIsCompressed, ginPostingListDecodeAllSegments(), ItemPointerIsValid, next, and palloc().

Referenced by entryLoadMoreItems(), and startScanEntry().

136 {
137  ItemPointer result;
138 
139  if (GinPageIsCompressed(page))
140  {
143  Pointer endptr = ((Pointer) seg) + len;
145 
146  /* Skip to the segment containing advancePast+1 */
147  if (ItemPointerIsValid(&advancePast))
148  {
149  next = GinNextPostingListSegment(seg);
150  while ((Pointer) next < endptr &&
151  ginCompareItemPointers(&next->first, &advancePast) <= 0)
152  {
153  seg = next;
154  next = GinNextPostingListSegment(seg);
155  }
156  len = endptr - (Pointer) seg;
157  }
158 
159  if (len > 0)
160  result = ginPostingListDecodeAllSegments(seg, len, nitems);
161  else
162  {
163  result = NULL;
164  *nitems = 0;
165  }
166  }
167  else
168  {
169  ItemPointer tmp = dataLeafPageGetUncompressed(page, nitems);
170 
171  result = palloc((*nitems) * sizeof(ItemPointerData));
172  memcpy(result, tmp, (*nitems) * sizeof(ItemPointerData));
173  }
174 
175  return result;
176 }
#define ItemPointerIsValid(pointer)
Definition: itemptr.h:82
static int32 next
Definition: blutils.c:213
#define GinPageIsCompressed(page)
Definition: ginblock.h:121
ItemPointerData first
Definition: ginblock.h:341
char * Pointer
Definition: c.h:335
#define GinNextPostingListSegment(cur)
Definition: ginblock.h:347
#define GinDataLeafPageGetPostingListSize(page)
Definition: ginblock.h:284
#define GinDataLeafPageGetPostingList(page)
Definition: ginblock.h:282
size_t Size
Definition: c.h:466
static int ginCompareItemPointers(ItemPointer a, ItemPointer b)
Definition: gin_private.h:461
void * palloc(Size size)
Definition: mcxt.c:924
ItemPointer ginPostingListDecodeAllSegments(GinPostingList *segment, int len, int *ndecoded_out)
static ItemPointer dataLeafPageGetUncompressed(Page page, int *nitems)
Definition: gindatapage.c:211

◆ GinDataLeafPageGetItemsToTbm()

int GinDataLeafPageGetItemsToTbm ( Page  page,
TIDBitmap tbm 
)

Definition at line 182 of file gindatapage.c.

References dataLeafPageGetUncompressed(), GinDataLeafPageGetPostingList, GinDataLeafPageGetPostingListSize, GinPageIsCompressed, ginPostingListDecodeAllSegmentsToTbm(), and tbm_add_tuples().

Referenced by scanPostingTree().

183 {
184  ItemPointer uncompressed;
185  int nitems;
186 
187  if (GinPageIsCompressed(page))
188  {
191 
192  nitems = ginPostingListDecodeAllSegmentsToTbm(segment, len, tbm);
193  }
194  else
195  {
196  uncompressed = dataLeafPageGetUncompressed(page, &nitems);
197 
198  if (nitems > 0)
199  tbm_add_tuples(tbm, uncompressed, nitems, false);
200  }
201 
202  return nitems;
203 }
int ginPostingListDecodeAllSegmentsToTbm(GinPostingList *ptr, int len, TIDBitmap *tbm)
void tbm_add_tuples(TIDBitmap *tbm, const ItemPointer tids, int ntids, bool recheck)
Definition: tidbitmap.c:376
#define GinPageIsCompressed(page)
Definition: ginblock.h:121
#define GinDataLeafPageGetPostingListSize(page)
Definition: ginblock.h:284
#define GinDataLeafPageGetPostingList(page)
Definition: ginblock.h:282
size_t Size
Definition: c.h:466
static ItemPointer dataLeafPageGetUncompressed(Page page, int *nitems)
Definition: gindatapage.c:211

◆ GinDataPageAddPostingItem()

void GinDataPageAddPostingItem ( Page  page,
PostingItem data,
OffsetNumber  offset 
)

Definition at line 377 of file gindatapage.c.

References Assert, GinDataPageGetPostingItem, GinDataPageSetDataSize, GinPageGetOpaque, GinPageIsLeaf, InvalidBlockNumber, InvalidOffsetNumber, memmove, and PostingItemGetBlockNumber.

Referenced by dataExecPlaceToPageInternal(), ginDataFillRoot(), and ginRedoInsertData().

378 {
379  OffsetNumber maxoff = GinPageGetOpaque(page)->maxoff;
380  char *ptr;
381 
383  Assert(!GinPageIsLeaf(page));
384 
385  if (offset == InvalidOffsetNumber)
386  {
387  ptr = (char *) GinDataPageGetPostingItem(page, maxoff + 1);
388  }
389  else
390  {
391  ptr = (char *) GinDataPageGetPostingItem(page, offset);
392  if (offset != maxoff + 1)
393  memmove(ptr + sizeof(PostingItem),
394  ptr,
395  (maxoff - offset + 1) * sizeof(PostingItem));
396  }
397  memcpy(ptr, data, sizeof(PostingItem));
398 
399  maxoff++;
400  GinPageGetOpaque(page)->maxoff = maxoff;
401 
402  /*
403  * Also set pd_lower to the end of the posting items, to follow the
404  * "standard" page layout, so that we can squeeze out the unused space
405  * from full-page images.
406  */
407  GinDataPageSetDataSize(page, maxoff * sizeof(PostingItem));
408 }
#define GinPageGetOpaque(page)
Definition: ginblock.h:110
uint16 OffsetNumber
Definition: off.h:24
#define GinDataPageSetDataSize(page, size)
Definition: ginblock.h:313
#define GinDataPageGetPostingItem(page, i)
Definition: ginblock.h:302
#define memmove(d, s, c)
Definition: c.h:1224
#define GinPageIsLeaf(page)
Definition: ginblock.h:112
#define InvalidOffsetNumber
Definition: off.h:26
#define PostingItemGetBlockNumber(pointer)
Definition: ginblock.h:193
#define Assert(condition)
Definition: c.h:732
#define InvalidBlockNumber
Definition: block.h:33

◆ ginendscan()

void ginendscan ( IndexScanDesc  scan)

Definition at line 429 of file ginscan.c.

References ginFreeScanKeys(), GinScanOpaqueData::keyCtx, MemoryContextDelete(), IndexScanDescData::opaque, pfree(), and GinScanOpaqueData::tempCtx.

Referenced by ginhandler().

430 {
431  GinScanOpaque so = (GinScanOpaque) scan->opaque;
432 
433  ginFreeScanKeys(so);
434 
437 
438  pfree(so);
439 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
void pfree(void *pointer)
Definition: mcxt.c:1031
GinScanOpaqueData * GinScanOpaque
Definition: gin_private.h:364
MemoryContext keyCtx
Definition: gin_private.h:359
MemoryContext tempCtx
Definition: gin_private.h:349
void ginFreeScanKeys(GinScanOpaque so)
Definition: ginscan.c:232

◆ ginEntryFillRoot()

void ginEntryFillRoot ( GinBtree  btree,
Page  root,
BlockNumber  lblkno,
Page  lpage,
BlockNumber  rblkno,
Page  rpage 
)

Definition at line 721 of file ginentrypage.c.

References elog, ERROR, getRightMostTuple(), GinFormInteriorTuple(), IndexTupleSize, InvalidOffsetNumber, PageAddItem, and pfree().

Referenced by ginPrepareEntryScan().

724 {
725  IndexTuple itup;
726 
727  itup = GinFormInteriorTuple(getRightMostTuple(lpage), lpage, lblkno);
728  if (PageAddItem(root, (Item) itup, IndexTupleSize(itup), InvalidOffsetNumber, false, false) == InvalidOffsetNumber)
729  elog(ERROR, "failed to add item to index root page");
730  pfree(itup);
731 
732  itup = GinFormInteriorTuple(getRightMostTuple(rpage), rpage, rblkno);
733  if (PageAddItem(root, (Item) itup, IndexTupleSize(itup), InvalidOffsetNumber, false, false) == InvalidOffsetNumber)
734  elog(ERROR, "failed to add item to index root page");
735  pfree(itup);
736 }
Pointer Item
Definition: item.h:17
static IndexTuple getRightMostTuple(Page page)
Definition: ginentrypage.c:236
#define PageAddItem(page, item, size, offsetNumber, overwrite, is_heap)
Definition: bufpage.h:416
void pfree(void *pointer)
Definition: mcxt.c:1031
#define ERROR
Definition: elog.h:43
static IndexTuple GinFormInteriorTuple(IndexTuple itup, Page page, BlockNumber childblk)
Definition: ginentrypage.c:202
#define InvalidOffsetNumber
Definition: off.h:26
#define elog(elevel,...)
Definition: elog.h:226
#define IndexTupleSize(itup)
Definition: itup.h:71

◆ ginEntryInsert()

void ginEntryInsert ( GinState ginstate,
OffsetNumber  attnum,
Datum  key,
GinNullCategory  category,
ItemPointerData items,
uint32  nitem,
GinStatsData buildStats 
)

Definition at line 180 of file gininsert.c.

References addItemPointersToLeafTuple(), GinBtreeStack::buffer, BufferGetPage, buildFreshLeafTuple(), CheckForSerializableConflictIn(), GinBtreeEntryInsertData::entry, GinBtreeData::findItem, freeGinBtreeStack(), GIN_UNLOCK, ginFindLeafPage(), GinGetPostingTree, ginInsertItemPointers(), ginInsertValue(), GinIsPostingTree, ginPrepareEntryScan(), GinState::index, GinBtreeData::isBuild, GinBtreeEntryInsertData::isDelete, LockBuffer(), GinStatsData::nEntries, GinBtreeStack::off, PageGetItem, PageGetItemId, and pfree().

Referenced by ginbuild(), ginBuildCallback(), ginHeapTupleInsert(), and ginInsertCleanup().

184 {
185  GinBtreeData btree;
186  GinBtreeEntryInsertData insertdata;
187  GinBtreeStack *stack;
188  IndexTuple itup;
189  Page page;
190 
191  insertdata.isDelete = false;
192 
193  /* During index build, count the to-be-inserted entry */
194  if (buildStats)
195  buildStats->nEntries++;
196 
197  ginPrepareEntryScan(&btree, attnum, key, category, ginstate);
198  btree.isBuild = (buildStats != NULL);
199 
200  stack = ginFindLeafPage(&btree, false, false, NULL);
201  page = BufferGetPage(stack->buffer);
202 
203  if (btree.findItem(&btree, stack))
204  {
205  /* found pre-existing entry */
206  itup = (IndexTuple) PageGetItem(page, PageGetItemId(page, stack->off));
207 
208  if (GinIsPostingTree(itup))
209  {
210  /* add entries to existing posting tree */
211  BlockNumber rootPostingTree = GinGetPostingTree(itup);
212 
213  /* release all stack */
214  LockBuffer(stack->buffer, GIN_UNLOCK);
215  freeGinBtreeStack(stack);
216 
217  /* insert into posting tree */
218  ginInsertItemPointers(ginstate->index, rootPostingTree,
219  items, nitem,
220  buildStats);
221  return;
222  }
223 
224  CheckForSerializableConflictIn(ginstate->index, NULL, stack->buffer);
225  /* modify an existing leaf entry */
226  itup = addItemPointersToLeafTuple(ginstate, itup,
227  items, nitem, buildStats, stack->buffer);
228 
229  insertdata.isDelete = true;
230  }
231  else
232  {
233  CheckForSerializableConflictIn(ginstate->index, NULL, stack->buffer);
234  /* no match, so construct a new leaf entry */
235  itup = buildFreshLeafTuple(ginstate, attnum, key, category,
236  items, nitem, buildStats, stack->buffer);
237  }
238 
239  /* Insert the new or modified leaf tuple */
240  insertdata.entry = itup;
241  ginInsertValue(&btree, stack, &insertdata, buildStats);
242  pfree(itup);
243 }
#define GIN_UNLOCK
Definition: gin_private.h:43
void ginInsertItemPointers(Relation index, BlockNumber rootBlkno, ItemPointerData *items, uint32 nitem, GinStatsData *buildStats)
Definition: gindatapage.c:1899
Relation index
Definition: gin_private.h:53
OffsetNumber off
Definition: gin_private.h:126
GinBtreeStack * ginFindLeafPage(GinBtree btree, bool searchMode, bool rootConflictCheck, Snapshot snapshot)
Definition: ginbtree.c:80
int64 nEntries
Definition: gin.h:47
uint32 BlockNumber
Definition: block.h:31
void CheckForSerializableConflictIn(Relation relation, HeapTuple tuple, Buffer buffer)
Definition: predicate.c:4442
static IndexTuple addItemPointersToLeafTuple(GinState *ginstate, IndexTuple old, ItemPointerData *items, uint32 nitem, GinStatsData *buildStats, Buffer buffer)
Definition: gininsert.c:50
bool(* findItem)(GinBtree, GinBtreeStack *)
Definition: gin_private.h:149
void pfree(void *pointer)
Definition: mcxt.c:1031
IndexTupleData * IndexTuple
Definition: itup.h:53
static IndexTuple buildFreshLeafTuple(GinState *ginstate, OffsetNumber attnum, Datum key, GinNullCategory category, ItemPointerData *items, uint32 nitem, GinStatsData *buildStats, Buffer buffer)
Definition: gininsert.c:130
#define BufferGetPage(buffer)
Definition: bufmgr.h:159
void ginPrepareEntryScan(GinBtree btree, OffsetNumber attnum, Datum key, GinNullCategory category, GinState *ginstate)
Definition: ginentrypage.c:745
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:235
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3590
void ginInsertValue(GinBtree btree, GinBtreeStack *stack, void *insertdata, GinStatsData *buildStats)
Definition: ginbtree.c:784
int16 attnum
Definition: pg_attribute.h:79
#define GinGetPostingTree(itup)
Definition: ginblock.h:237
#define GinIsPostingTree(itup)
Definition: ginblock.h:235
void freeGinBtreeStack(GinBtreeStack *stack)
Definition: ginbtree.c:201
#define PageGetItem(page, itemId)
Definition: bufpage.h:340
Pointer Page
Definition: bufpage.h:78

◆ ginExtractEntries()

Datum* ginExtractEntries ( GinState ginstate,
OffsetNumber  attnum,
Datum  value,
bool  isNull,
int32 nentries,
GinNullCategory **  categories 
)

Definition at line 484 of file ginutil.c.

References arg, cmpEntriesArg::cmpDatumFunc, cmpEntries(), cmpEntriesArg::collation, GinState::compareFn, keyEntryData::datum, DatumGetPointer, GinState::extractValueFn, FunctionCall3Coll(), GIN_CAT_EMPTY_ITEM, GIN_CAT_NORM_KEY, GIN_CAT_NULL_ITEM, GIN_CAT_NULL_KEY, cmpEntriesArg::haveDups, i, keyEntryData::isnull, palloc(), palloc0(), pfree(), PointerGetDatum, qsort_arg(), and GinState::supportCollation.

Referenced by ginHeapTupleBulkInsert(), ginHeapTupleFastCollect(), and ginHeapTupleInsert().

487 {
488  Datum *entries;
489  bool *nullFlags;
490  int32 i;
491 
492  /*
493  * We don't call the extractValueFn on a null item. Instead generate a
494  * placeholder.
495  */
496  if (isNull)
497  {
498  *nentries = 1;
499  entries = (Datum *) palloc(sizeof(Datum));
500  entries[0] = (Datum) 0;
501  *categories = (GinNullCategory *) palloc(sizeof(GinNullCategory));
502  (*categories)[0] = GIN_CAT_NULL_ITEM;
503  return entries;
504  }
505 
506  /* OK, call the opclass's extractValueFn */
507  nullFlags = NULL; /* in case extractValue doesn't set it */
508  entries = (Datum *)
510  ginstate->supportCollation[attnum - 1],
511  value,
512  PointerGetDatum(nentries),
513  PointerGetDatum(&nullFlags)));
514 
515  /*
516  * Generate a placeholder if the item contained no keys.
517  */
518  if (entries == NULL || *nentries <= 0)
519  {
520  *nentries = 1;
521  entries = (Datum *) palloc(sizeof(Datum));
522  entries[0] = (Datum) 0;
523  *categories = (GinNullCategory *) palloc(sizeof(GinNullCategory));
524  (*categories)[0] = GIN_CAT_EMPTY_ITEM;
525  return entries;
526  }
527 
528  /*
529  * If the extractValueFn didn't create a nullFlags array, create one,
530  * assuming that everything's non-null.
531  */
532  if (nullFlags == NULL)
533  nullFlags = (bool *) palloc0(*nentries * sizeof(bool));
534 
535  /*
536  * If there's more than one key, sort and unique-ify.
537  *
538  * XXX Using qsort here is notationally painful, and the overhead is
539  * pretty bad too. For small numbers of keys it'd likely be better to use
540  * a simple insertion sort.
541  */
542  if (*nentries > 1)
543  {
544  keyEntryData *keydata;
546 
547  keydata = (keyEntryData *) palloc(*nentries * sizeof(keyEntryData));
548  for (i = 0; i < *nentries; i++)
549  {
550  keydata[i].datum = entries[i];
551  keydata[i].isnull = nullFlags[i];
552  }
553 
554  arg.cmpDatumFunc = &ginstate->compareFn[attnum - 1];
555  arg.collation = ginstate->supportCollation[attnum - 1];
556  arg.haveDups = false;
557  qsort_arg(keydata, *nentries, sizeof(keyEntryData),
558  cmpEntries, (void *) &arg);
559 
560  if (arg.haveDups)
561  {
562  /* there are duplicates, must get rid of 'em */
563  int32 j;
564 
565  entries[0] = keydata[0].datum;
566  nullFlags[0] = keydata[0].isnull;
567  j = 1;
568  for (i = 1; i < *nentries; i++)
569  {
570  if (cmpEntries(&keydata[i - 1], &keydata[i], &arg) != 0)
571  {
572  entries[j] = keydata[i].datum;
573  nullFlags[j] = keydata[i].isnull;
574  j++;
575  }
576  }
577  *nentries = j;
578  }
579  else
580  {
581  /* easy, no duplicates */
582  for (i = 0; i < *nentries; i++)
583  {
584  entries[i] = keydata[i].datum;
585  nullFlags[i] = keydata[i].isnull;
586  }
587  }
588 
589  pfree(keydata);
590  }
591 
592  /*
593  * Create GinNullCategory representation from nullFlags.
594  */
595  *categories = (GinNullCategory *) palloc0(*nentries * sizeof(GinNullCategory));
596  for (i = 0; i < *nentries; i++)
597  (*categories)[i] = (nullFlags[i] ? GIN_CAT_NULL_KEY : GIN_CAT_NORM_KEY);
598 
599  return entries;
600 }
Oid supportCollation[INDEX_MAX_KEYS]
Definition: gin_private.h:82
FmgrInfo * cmpDatumFunc
Definition: ginutil.c:438
bool isnull
Definition: ginutil.c:433
#define PointerGetDatum(X)
Definition: postgres.h:556
static struct @144 value
FmgrInfo extractValueFn[INDEX_MAX_KEYS]
Definition: gin_private.h:74
Datum datum
Definition: ginutil.c:432
signed int int32
Definition: c.h:346
void pfree(void *pointer)
Definition: mcxt.c:1031
signed char GinNullCategory
Definition: ginblock.h:210
bool haveDups
Definition: ginutil.c:440
#define GIN_CAT_NORM_KEY
Definition: ginblock.h:212
void qsort_arg(void *base, size_t nel, size_t elsize, qsort_arg_comparator cmp, void *arg)
Definition: qsort_arg.c:113
#define GIN_CAT_NULL_KEY
Definition: ginblock.h:213
void * palloc0(Size size)
Definition: mcxt.c:955
uintptr_t Datum
Definition: postgres.h:367
#define GIN_CAT_NULL_ITEM
Definition: ginblock.h:215
int16 attnum
Definition: pg_attribute.h:79
Datum FunctionCall3Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2, Datum arg3)
Definition: fmgr.c:1172
Oid collation
Definition: ginutil.c:439
#define DatumGetPointer(X)
Definition: postgres.h:549
void * palloc(Size size)
Definition: mcxt.c:924
int i
void * arg
#define GIN_CAT_EMPTY_ITEM
Definition: ginblock.h:214
static int cmpEntries(const void *a, const void *b, void *arg)
Definition: ginutil.c:444
FmgrInfo compareFn[INDEX_MAX_KEYS]
Definition: gin_private.h:73

◆ ginFindLeafPage()

GinBtreeStack* ginFindLeafPage ( GinBtree  btree,
bool  searchMode,
bool  rootConflictCheck,
Snapshot  snapshot 
)

Definition at line 80 of file ginbtree.c.

References Assert, GinBtreeStack::blkno, GinBtreeStack::buffer, BufferGetPage, CheckForSerializableConflictIn(), GinBtreeData::findChildPage, GinBtreeData::fullScan, GIN_UNLOCK, ginFinishSplit(), GinPageGetOpaque, GinPageIsIncompleteSplit, GinPageIsLeaf, ginStepRight(), ginTraverseLock(), GinBtreeData::index, InvalidBlockNumber, InvalidOffsetNumber, GinBtreeData::isMoveRight, LockBuffer(), GinBtreeStack::off, palloc(), GinBtreeStack::parent, GinBtreeStack::predictNumber, ReadBuffer(), ReleaseAndReadBuffer(), GinBtreeData::rootBlkno, and TestForOldSnapshot().

Referenced by entryLoadMoreItems(), ginEntryInsert(), ginInsertItemPointers(), ginScanBeginPostingTree(), and startScanEntry().

82 {
83  GinBtreeStack *stack;
84 
85  stack = (GinBtreeStack *) palloc(sizeof(GinBtreeStack));
86  stack->blkno = btree->rootBlkno;
87  stack->buffer = ReadBuffer(btree->index, btree->rootBlkno);
88  stack->parent = NULL;
89  stack->predictNumber = 1;
90 
91  if (rootConflictCheck)
92  CheckForSerializableConflictIn(btree->index, NULL, stack->buffer);
93 
94  for (;;)
95  {
96  Page page;
97  BlockNumber child;
98  int access;
99 
100  stack->off = InvalidOffsetNumber;
101 
102  page = BufferGetPage(stack->buffer);
103  TestForOldSnapshot(snapshot, btree->index, page);
104 
105  access = ginTraverseLock(stack->buffer, searchMode);
106 
107  /*
108  * If we're going to modify the tree, finish any incomplete splits we
109  * encounter on the way.
110  */
111  if (!searchMode && GinPageIsIncompleteSplit(page))
112  ginFinishSplit(btree, stack, false, NULL);
113 
114  /*
115  * ok, page is correctly locked, we should check to move right ..,
116  * root never has a right link, so small optimization
117  */
118  while (btree->fullScan == false && stack->blkno != btree->rootBlkno &&
119  btree->isMoveRight(btree, page))
120  {
121  BlockNumber rightlink = GinPageGetOpaque(page)->rightlink;
122 
123  if (rightlink == InvalidBlockNumber)
124  /* rightmost page */
125  break;
126 
127  stack->buffer = ginStepRight(stack->buffer, btree->index, access);
128  stack->blkno = rightlink;
129  page = BufferGetPage(stack->buffer);
130  TestForOldSnapshot(snapshot, btree->index, page);
131 
132  if (!searchMode && GinPageIsIncompleteSplit(page))
133  ginFinishSplit(btree, stack, false, NULL);
134  }
135 
136  if (GinPageIsLeaf(page)) /* we found, return locked page */
137  return stack;
138 
139  /* now we have correct buffer, try to find child */
140  child = btree->findChildPage(btree, stack);
141 
142  LockBuffer(stack->buffer, GIN_UNLOCK);
143  Assert(child != InvalidBlockNumber);
144  Assert(stack->blkno != child);
145 
146  if (searchMode)
147  {
148  /* in search mode we may forget path to leaf */
149  stack->blkno = child;
150  stack->buffer = ReleaseAndReadBuffer(stack->buffer, btree->index, stack->blkno);
151  }
152  else
153  {
154  GinBtreeStack *ptr = (GinBtreeStack *) palloc(sizeof(GinBtreeStack));
155 
156  ptr->parent = stack;
157  stack = ptr;
158  stack->blkno = child;
159  stack->buffer = ReadBuffer(btree->index, stack->blkno);
160  stack->predictNumber = 1;
161  }
162  }
163 }
#define GIN_UNLOCK
Definition: gin_private.h:43
static void TestForOldSnapshot(Snapshot snapshot, Relation relation, Page page)
Definition: bufmgr.h:264
OffsetNumber off
Definition: gin_private.h:126
#define GinPageIsIncompleteSplit(page)
Definition: ginblock.h:127
bool(* isMoveRight)(GinBtree, Page)
Definition: gin_private.h:148
static void ginFinishSplit(GinBtree btree, GinBtreeStack *stack, bool freestack, GinStatsData *buildStats)
Definition: ginbtree.c:675
BlockNumber rootBlkno
Definition: gin_private.h:161
uint32 BlockNumber
Definition: block.h:31
#define GinPageGetOpaque(page)
Definition: ginblock.h:110
void CheckForSerializableConflictIn(Relation relation, HeapTuple tuple, Buffer buffer)
Definition: predicate.c:4442
BlockNumber(* findChildPage)(GinBtree, GinBtreeStack *)
Definition: gin_private.h:146
Buffer ginStepRight(Buffer buffer, Relation index, int lockmode)
Definition: ginbtree.c:173
#define GinPageIsLeaf(page)
Definition: ginblock.h:112
#define BufferGetPage(buffer)
Definition: bufmgr.h:159
struct GinBtreeStack * parent
Definition: gin_private.h:130
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3590
Relation index
Definition: gin_private.h:160
#define InvalidOffsetNumber
Definition: off.h:26
#define Assert(condition)
Definition: c.h:732
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:596
#define InvalidBlockNumber
Definition: block.h:33
Buffer ReleaseAndReadBuffer(Buffer buffer, Relation relation, BlockNumber blockNum)
Definition: bufmgr.c:1521
BlockNumber blkno
Definition: gin_private.h:124
uint32 predictNumber
Definition: gin_private.h:129
void * palloc(Size size)
Definition: mcxt.c:924
Pointer Page
Definition: bufpage.h:78
int ginTraverseLock(Buffer buffer, bool searchMode)
Definition: ginbtree.c:36

◆ GinFormTuple()

IndexTuple GinFormTuple ( GinState ginstate,
OffsetNumber  attnum,
Datum  key,
GinNullCategory  category,
Pointer  data,
Size  dataSize,
int  nipd,
bool  errorTooBig 
)

Definition at line 45 of file ginentrypage.c.

References Assert, ereport, errcode(), errmsg(), ERROR, GIN_CAT_NORM_KEY, GinCategoryOffset, GinGetPosting, GinMaxItemSize, GinSetNPosting, GinSetNullCategory, GinSetPostingOffset, GinState::index, index_form_tuple(), INDEX_SIZE_MASK, IndexTupleHasNulls, IndexTupleSize, sort-test::key, Max, MAXALIGN, GinState::oneCol, pfree(), RelationGetRelationName, repalloc(), SHORTALIGN, IndexTupleData::t_info, GinState::tupdesc, and UInt16GetDatum.

Referenced by addItemPointersToLeafTuple(), buildFreshLeafTuple(), ginHeapTupleFastCollect(), and ginVacuumEntryPage().

49 {
50  Datum datums[2];
51  bool isnull[2];
52  IndexTuple itup;
53  uint32 newsize;
54 
55  /* Build the basic tuple: optional column number, plus key datum */
56  if (ginstate->oneCol)
57  {
58  datums[0] = key;
59  isnull[0] = (category != GIN_CAT_NORM_KEY);
60  }
61  else
62  {
63  datums[0] = UInt16GetDatum(attnum);
64  isnull[0] = false;
65  datums[1] = key;
66  isnull[1] = (category != GIN_CAT_NORM_KEY);
67  }
68 
69  itup = index_form_tuple(ginstate->tupdesc[attnum - 1], datums, isnull);
70 
71  /*
72  * Determine and store offset to the posting list, making sure there is
73  * room for the category byte if needed.
74  *
75  * Note: because index_form_tuple MAXALIGNs the tuple size, there may well
76  * be some wasted pad space. Is it worth recomputing the data length to
77  * prevent that? That would also allow us to Assert that the real data
78  * doesn't overlap the GinNullCategory byte, which this code currently
79  * takes on faith.
80  */
81  newsize = IndexTupleSize(itup);
82 
83  if (IndexTupleHasNulls(itup))
84  {
85  uint32 minsize;
86 
87  Assert(category != GIN_CAT_NORM_KEY);
88  minsize = GinCategoryOffset(itup, ginstate) + sizeof(GinNullCategory);
89  newsize = Max(newsize, minsize);
90  }
91 
92  newsize = SHORTALIGN(newsize);
93 
94  GinSetPostingOffset(itup, newsize);
95  GinSetNPosting(itup, nipd);
96 
97  /*
98  * Add space needed for posting list, if any. Then check that the tuple
99  * won't be too big to store.
100  */
101  newsize += dataSize;
102 
103  newsize = MAXALIGN(newsize);
104 
105  if (newsize > GinMaxItemSize)
106  {
107  if (errorTooBig)
108  ereport(ERROR,
109  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
110  errmsg("index row size %zu exceeds maximum %zu for index \"%s\"",
111  (Size) newsize, (Size) GinMaxItemSize,
112  RelationGetRelationName(ginstate->index))));
113  pfree(itup);
114  return NULL;
115  }
116 
117  /*
118  * Resize tuple if needed
119  */
120  if (newsize != IndexTupleSize(itup))
121  {
122  itup = repalloc(itup, newsize);
123 
124  /*
125  * PostgreSQL 9.3 and earlier did not clear this new space, so we
126  * might find uninitialized padding when reading tuples from disk.
127  */
128  memset((char *) itup + IndexTupleSize(itup),
129  0, newsize - IndexTupleSize(itup));
130  /* set new size in tuple header */
131  itup->t_info &= ~INDEX_SIZE_MASK;
132  itup->t_info |= newsize;
133  }
134 
135  /*
136  * Copy in the posting list, if provided
137  */
138  if (data)
139  {
140  char *ptr = GinGetPosting(itup);
141 
142  memcpy(ptr, data, dataSize);
143  }
144 
145  /*
146  * Insert category byte, if needed
147  */
148  if (category != GIN_CAT_NORM_KEY)
149  {
150  Assert(IndexTupleHasNulls(itup));
151  GinSetNullCategory(itup, ginstate, category);
152  }
153  return itup;
154 }
#define GinSetNPosting(itup, n)
Definition: ginblock.h:233
Relation index
Definition: gin_private.h:53
#define INDEX_SIZE_MASK
Definition: itup.h:65
int errcode(int sqlerrcode)
Definition: elog.c:570
#define IndexTupleHasNulls(itup)
Definition: itup.h:72
#define GinGetPosting(itup)
Definition: ginblock.h:242
IndexTuple index_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: indextuple.c:40
void pfree(void *pointer)
Definition: mcxt.c:1031
#define ERROR
Definition: elog.h:43
signed char GinNullCategory
Definition: ginblock.h:210
#define GinSetPostingOffset(itup, n)
Definition: ginblock.h:241
#define GIN_CAT_NORM_KEY
Definition: ginblock.h:212
#define RelationGetRelationName(relation)
Definition: rel.h:448
unsigned int uint32
Definition: c.h:358
#define ereport(elevel, rest)
Definition: elog.h:141
uintptr_t Datum
Definition: postgres.h:367
TupleDesc tupdesc[INDEX_MAX_KEYS]
Definition: gin_private.h:68
int16 attnum
Definition: pg_attribute.h:79
#define Max(x, y)
Definition: c.h:884
#define Assert(condition)
Definition: c.h:732
#define GinSetNullCategory(itup, ginstate, c)
Definition: ginblock.h:226
size_t Size
Definition: c.h:466
#define MAXALIGN(LEN)
Definition: c.h:685
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1044
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define GinMaxItemSize
Definition: ginblock.h:252
unsigned short t_info
Definition: itup.h:49
#define SHORTALIGN(LEN)
Definition: c.h:681
bool oneCol
Definition: gin_private.h:54
#define GinCategoryOffset(itup, ginstate)
Definition: ginblock.h:221
#define UInt16GetDatum(X)
Definition: postgres.h:465
#define IndexTupleSize(itup)
Definition: itup.h:71

◆ ginFreeScanKeys()

void ginFreeScanKeys ( GinScanOpaque  so)

Definition at line 232 of file ginscan.c.

References GinScanEntryData::buffer, GinScanOpaqueData::entries, i, InvalidBuffer, GinScanOpaqueData::keyCtx, GinScanOpaqueData::keys, GinScanEntryData::list, GinScanEntryData::matchBitmap, GinScanEntryData::matchIterator, MemoryContextResetAndDeleteChildren, GinScanOpaqueData::nkeys, pfree(), ReleaseBuffer(), tbm_end_iterate(), tbm_free(), and GinScanOpaqueData::totalentries.

Referenced by ginendscan(), gingetbitmap(), and ginrescan().

233 {
234  uint32 i;
235 
236  if (so->keys == NULL)
237  return;
238 
239  for (i = 0; i < so->totalentries; i++)
240  {
241  GinScanEntry entry = so->entries[i];
242 
243  if (entry->buffer != InvalidBuffer)
244  ReleaseBuffer(entry->buffer);
245  if (entry->list)
246  pfree(entry->list);
247  if (entry->matchIterator)
249  if (entry->matchBitmap)
250  tbm_free(entry->matchBitmap);
251  }
252 
254 
255  so->keys = NULL;
256  so->nkeys = 0;
257  so->entries = NULL;
258  so->totalentries = 0;
259 }
void tbm_end_iterate(TBMIterator *iterator)
Definition: tidbitmap.c:1145
TBMIterator * matchIterator
Definition: gin_private.h:333
#define InvalidBuffer
Definition: buf.h:25
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3353
ItemPointerData * list
Definition: gin_private.h:337
void pfree(void *pointer)
Definition: mcxt.c:1031
void tbm_free(TIDBitmap *tbm)
Definition: tidbitmap.c:321
MemoryContext keyCtx
Definition: gin_private.h:359
unsigned int uint32
Definition: c.h:358
TIDBitmap * matchBitmap
Definition: gin_private.h:332
GinScanKey keys
Definition: gin_private.h:352
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
GinScanEntry * entries
Definition: gin_private.h:355
int i

◆ ginGetBAEntry()

ItemPointerData* ginGetBAEntry ( BuildAccumulator accum,
OffsetNumber attnum,
Datum key,
GinNullCategory category,
uint32 n 
)

Definition at line 268 of file ginbulk.c.

References Assert, GinEntryAccumulator::attnum, GinEntryAccumulator::category, GinEntryAccumulator::count, GinEntryAccumulator::key, sort-test::list, GinEntryAccumulator::list, qsort, qsortCompareItemPointers(), rbt_iterate(), GinEntryAccumulator::shouldSort, and BuildAccumulator::tree_walk.

Referenced by ginbuild(), ginBuildCallback(), and ginInsertCleanup().

271 {
272  GinEntryAccumulator *entry;
274 
275  entry = (GinEntryAccumulator *) rbt_iterate(&accum->tree_walk);
276 
277  if (entry == NULL)
278  return NULL; /* no more entries */
279 
280  *attnum = entry->attnum;
281  *key = entry->key;
282  *category = entry->category;
283  list = entry->list;
284  *n = entry->count;
285 
286  Assert(list != NULL && entry->count > 0);
287 
288  if (entry->shouldSort && entry->count > 1)
289  qsort(list, entry->count, sizeof(ItemPointerData),
291 
292  return list;
293 }
RBTNode * rbt_iterate(RBTreeIterator *iter)
Definition: rbtree.c:764
OffsetNumber attnum
Definition: gin_private.h:398
GinNullCategory category
Definition: gin_private.h:397
int16 attnum
Definition: pg_attribute.h:79
#define Assert(condition)
Definition: c.h:732
static int qsortCompareItemPointers(const void *a, const void *b)
Definition: ginbulk.c:246
RBTreeIterator tree_walk
Definition: gin_private.h:412
#define qsort(a, b, c, d)
Definition: port.h:491
ItemPointerData * list
Definition: gin_private.h:400

◆ gingetbitmap()

int64 gingetbitmap ( IndexScanDesc  scan,
TIDBitmap tbm 
)

Definition at line 1849 of file ginget.c.

References CHECK_FOR_INTERRUPTS, ginFreeScanKeys(), GinIsVoidRes, ginNewScanKey(), ItemPointerGetBlockNumber, ItemPointerIsLossyPage, ItemPointerSetMin, IndexScanDescData::opaque, scanGetItem(), scanPendingInsert(), startScan(), tbm_add_page(), and tbm_add_tuples().

Referenced by ginhandler().

1850 {
1851  GinScanOpaque so = (GinScanOpaque) scan->opaque;
1852  int64 ntids;
1853  ItemPointerData iptr;
1854  bool recheck;
1855 
1856  /*
1857  * Set up the scan keys, and check for unsatisfiable query.
1858  */
1859  ginFreeScanKeys(so); /* there should be no keys yet, but just to be
1860  * sure */
1861  ginNewScanKey(scan);
1862 
1863  if (GinIsVoidRes(scan))
1864  return 0;
1865 
1866  ntids = 0;
1867 
1868  /*
1869  * First, scan the pending list and collect any matching entries into the
1870  * bitmap. After we scan a pending item, some other backend could post it
1871  * into the main index, and so we might visit it a second time during the
1872  * main scan. This is okay because we'll just re-set the same bit in the
1873  * bitmap. (The possibility of duplicate visits is a major reason why GIN
1874  * can't support the amgettuple API, however.) Note that it would not do
1875  * to scan the main index before the pending list, since concurrent
1876  * cleanup could then make us miss entries entirely.
1877  */
1878  scanPendingInsert(scan, tbm, &ntids);
1879 
1880  /*
1881  * Now scan the main index.
1882  */
1883  startScan(scan);
1884 
1885  ItemPointerSetMin(&iptr);
1886 
1887  for (;;)
1888  {
1890 
1891  if (!scanGetItem(scan, iptr, &iptr, &recheck))
1892  break;
1893 
1894  if (ItemPointerIsLossyPage(&iptr))
1896  else
1897  tbm_add_tuples(tbm, &iptr, 1, recheck);
1898  ntids++;
1899  }
1900 
1901  return ntids;
1902 }
static void scanPendingInsert(IndexScanDesc scan, TIDBitmap *tbm, int64 *ntids)
Definition: ginget.c:1754
void tbm_add_tuples(TIDBitmap *tbm, const ItemPointer tids, int ntids, bool recheck)
Definition: tidbitmap.c:376
#define ItemPointerIsLossyPage(p)
Definition: ginblock.h:179
static void startScan(IndexScanDesc scan)
Definition: ginget.c:584
GinScanOpaqueData * GinScanOpaque
Definition: gin_private.h:364
#define ItemPointerSetMin(p)
Definition: ginblock.h:167
static bool scanGetItem(IndexScanDesc scan, ItemPointerData advancePast, ItemPointerData *item, bool *recheck)
Definition: ginget.c:1233
void ginNewScanKey(IndexScanDesc scan)
Definition: ginscan.c:262
#define GinIsVoidRes(s)
Definition: ginget.c:1846
void tbm_add_page(TIDBitmap *tbm, BlockNumber pageno)
Definition: tidbitmap.c:442
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98
void ginFreeScanKeys(GinScanOpaque so)
Definition: ginscan.c:232

◆ ginHeapTupleFastCollect()

void ginHeapTupleFastCollect ( GinState ginstate,
GinTupleCollector collector,
OffsetNumber  attnum,
Datum  value,
bool  isNull,
ItemPointer  ht_ctid 
)

Definition at line 473 of file ginfast.c.

References KeyArray::categories, elog, ERROR, ginExtractEntries(), GinFormTuple(), i, IndexTupleSize, GinTupleCollector::lentuples, MaxAllocSize, GinTupleCollector::ntuples, palloc(), repalloc(), GinTupleCollector::sumsize, IndexTupleData::t_tid, and GinTupleCollector::tuples.

Referenced by gininsert().

477 {
478  Datum *entries;
479  GinNullCategory *categories;
480  int32 i,
481  nentries;
482 
483  /*
484  * Extract the key values that need to be inserted in the index
485  */
486  entries = ginExtractEntries(ginstate, attnum, value, isNull,
487  &nentries, &categories);
488 
489  /*
490  * Protect against integer overflow in allocation calculations
491  */
492  if (nentries < 0 ||
493  collector->ntuples + nentries > MaxAllocSize / sizeof(IndexTuple))
494  elog(ERROR, "too many entries for GIN index");
495 
496  /*
497  * Allocate/reallocate memory for storing collected tuples
498  */
499  if (collector->tuples == NULL)
500  {
501  /*
502  * Determine the number of elements to allocate in the tuples array
503  * initially. Make it a power of 2 to avoid wasting memory when
504  * resizing (since palloc likes powers of 2).
505  */
506  collector->lentuples = 16;
507  while (collector->lentuples < nentries)
508  collector->lentuples *= 2;
509 
510  collector->tuples = (IndexTuple *) palloc(sizeof(IndexTuple) * collector->lentuples);
511  }
512  else if (collector->lentuples < collector->ntuples + nentries)
513  {
514  /*
515  * Advance lentuples to the next suitable power of 2. This won't
516  * overflow, though we could get to a value that exceeds
517  * MaxAllocSize/sizeof(IndexTuple), causing an error in repalloc.
518  */
519  do
520  {
521  collector->lentuples *= 2;
522  } while (collector->lentuples < collector->ntuples + nentries);
523 
524  collector->tuples = (IndexTuple *) repalloc(collector->tuples,
525  sizeof(IndexTuple) * collector->lentuples);
526  }
527 
528  /*
529  * Build an index tuple for each key value, and add to array. In pending
530  * tuples we just stick the heap TID into t_tid.
531  */
532  for (i = 0; i < nentries; i++)
533  {
534  IndexTuple itup;
535 
536  itup = GinFormTuple(ginstate, attnum, entries[i], categories[i],
537  NULL, 0, 0, true);
538  itup->t_tid = *ht_ctid;
539  collector->tuples[collector->ntuples++] = itup;
540  collector->sumsize += IndexTupleSize(itup);
541  }
542 }
ItemPointerData t_tid
Definition: itup.h:37
static struct @144 value
signed int int32
Definition: c.h:346
#define ERROR
Definition: elog.h:43
signed char GinNullCategory
Definition: ginblock.h:210
#define MaxAllocSize
Definition: memutils.h:40
IndexTuple * tuples
Definition: gin_private.h:429
uintptr_t Datum
Definition: postgres.h:367
int16 attnum
Definition: pg_attribute.h:79
IndexTuple GinFormTuple(GinState *ginstate, OffsetNumber attnum, Datum key, GinNullCategory category, Pointer data, Size dataSize, int nipd, bool errorTooBig)
Definition: ginentrypage.c:45
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1044
void * palloc(Size size)
Definition: mcxt.c:924
#define elog(elevel,...)
Definition: elog.h:226
int i
Datum * ginExtractEntries(GinState *ginstate, OffsetNumber attnum, Datum value, bool isNull, int32 *nentries, GinNullCategory **categories)
Definition: ginutil.c:484
#define IndexTupleSize(itup)
Definition: itup.h:71

◆ ginHeapTupleFastInsert()

void ginHeapTupleFastInsert ( GinState ginstate,
GinTupleCollector collector 
)

Definition at line 218 of file ginfast.c.

References Assert, BufferGetPage, CheckForSerializableConflictIn(), elog, END_CRIT_SECTION, ERROR, FirstOffsetNumber, GIN_EXCLUSIVE, GIN_METAPAGE_BLKNO, GIN_PAGE_FREESIZE, GIN_UNLOCK, GinGetPendingListCleanupSize, ginInsertCleanup(), GinListPageSize, GinPageGetMeta, GinPageGetOpaque, GinMetaPageData::head, i, GinState::index, IndexTupleSize, InvalidBlockNumber, InvalidBuffer, InvalidOffsetNumber, LockBuffer(), makeSublist(), MarkBufferDirty(), ginxlogUpdateMeta::metadata, ginxlogUpdateMeta::newRightlink, ginxlogUpdateMeta::node, GinMetaPageData::nPendingHeapTuples, GinMetaPageData::nPendingPages, ginxlogUpdateMeta::ntuples, GinTupleCollector::ntuples, OffsetNumberNext, PageAddItem, PageGetExactFreeSpace(), PageGetMaxOffsetNumber, PageIsEmpty, PageSetLSN, palloc(), ginxlogUpdateMeta::prevTail, RelationData::rd_node, ReadBuffer(), REGBUF_STANDARD, REGBUF_WILL_INIT, RelationGetRelationName, RelationNeedsWAL, START_CRIT_SECTION, GinTupleCollector::sumsize, GinMetaPageData::tail, GinMetaPageData::tailFreeSize, GinTupleCollector::tuples, UnlockReleaseBuffer(), XLOG_GIN_UPDATE_META_PAGE, XLogBeginInsert(), XLogInsert(), XLogRegisterBufData(), XLogRegisterBuffer(), and XLogRegisterData().

Referenced by gininsert().

219 {
220  Relation index = ginstate->index;
221  Buffer metabuffer;
222  Page metapage;
223  GinMetaPageData *metadata = NULL;
224  Buffer buffer = InvalidBuffer;
225  Page page = NULL;
226  ginxlogUpdateMeta data;
227  bool separateList = false;
228  bool needCleanup = false;
229  int cleanupSize;
230  bool needWal;
231 
232  if (collector->ntuples == 0)
233  return;
234 
235  needWal = RelationNeedsWAL(index);
236 
237  data.node = index->rd_node;
238  data.ntuples = 0;
240 
241  metabuffer = ReadBuffer(index, GIN_METAPAGE_BLKNO);
242  metapage = BufferGetPage(metabuffer);
243 
244  /*
245  * An insertion to the pending list could logically belong anywhere in the
246  * tree, so it conflicts with all serializable scans. All scans acquire a
247  * predicate lock on the metabuffer to represent that.
248  */
249  CheckForSerializableConflictIn(index, NULL, metabuffer);
250 
251  if (collector->sumsize + collector->ntuples * sizeof(ItemIdData) > GinListPageSize)
252  {
253  /*
254  * Total size is greater than one page => make sublist
255  */
256  separateList = true;
257  }
258  else
259  {
260  LockBuffer(metabuffer, GIN_EXCLUSIVE);
261  metadata = GinPageGetMeta(metapage);
262 
263  if (metadata->head == InvalidBlockNumber ||
264  collector->sumsize + collector->ntuples * sizeof(ItemIdData) > metadata->tailFreeSize)
265  {
266  /*
267  * Pending list is empty or total size is greater than freespace
268  * on tail page => make sublist
269  *
270  * We unlock metabuffer to keep high concurrency
271  */
272  separateList = true;
273  LockBuffer(metabuffer, GIN_UNLOCK);
274  }
275  }
276 
277  if (separateList)
278  {
279  /*
280  * We should make sublist separately and append it to the tail
281  */
282  GinMetaPageData sublist;
283 
284  memset(&sublist, 0, sizeof(GinMetaPageData));
285  makeSublist(index, collector->tuples, collector->ntuples, &sublist);
286 
287  if (needWal)
288  XLogBeginInsert();
289 
290  /*
291  * metapage was unlocked, see above
292  */
293  LockBuffer(metabuffer, GIN_EXCLUSIVE);
294  metadata = GinPageGetMeta(metapage);
295 
296  if (metadata->head == InvalidBlockNumber)
297  {
298  /*
299  * Main list is empty, so just insert sublist as main list
300  */
302 
303  metadata->head = sublist.head;
304  metadata->tail = sublist.tail;
305  metadata->tailFreeSize = sublist.tailFreeSize;
306 
307  metadata->nPendingPages = sublist.nPendingPages;
308  metadata->nPendingHeapTuples = sublist.nPendingHeapTuples;
309  }
310  else
311  {
312  /*
313  * Merge lists
314  */
315  data.prevTail = metadata->tail;
316  data.newRightlink = sublist.head;
317 
318  buffer = ReadBuffer(index, metadata->tail);
319  LockBuffer(buffer, GIN_EXCLUSIVE);
320  page = BufferGetPage(buffer);
321 
322  Assert(GinPageGetOpaque(page)->rightlink == InvalidBlockNumber);
323 
325 
326  GinPageGetOpaque(page)->rightlink = sublist.head;
327 
328  MarkBufferDirty(buffer);
329 
330  metadata->tail = sublist.tail;
331  metadata->tailFreeSize = sublist.tailFreeSize;
332 
333  metadata->nPendingPages += sublist.nPendingPages;
334  metadata->nPendingHeapTuples += sublist.nPendingHeapTuples;
335 
336  if (needWal)
338  }
339  }
340  else
341  {
342  /*
343  * Insert into tail page. Metapage is already locked
344  */
345  OffsetNumber l,
346  off;
347  int i,
348  tupsize;
349  char *ptr;
350  char *collectordata;
351 
352  buffer = ReadBuffer(index, metadata->tail);
353  LockBuffer(buffer, GIN_EXCLUSIVE);
354  page = BufferGetPage(buffer);
355 
356  off = (PageIsEmpty(page)) ? FirstOffsetNumber :
358 
359  collectordata = ptr = (char *) palloc(collector->sumsize);
360 
361  data.ntuples = collector->ntuples;
362 
363  if (needWal)
364  XLogBeginInsert();
365 
367 
368  /*
369  * Increase counter of heap tuples
370  */
371  Assert(GinPageGetOpaque(page)->maxoff <= metadata->nPendingHeapTuples);
372  GinPageGetOpaque(page)->maxoff++;
373  metadata->nPendingHeapTuples++;
374 
375  for (i = 0; i < collector->ntuples; i++)
376  {
377  tupsize = IndexTupleSize(collector->tuples[i]);
378  l = PageAddItem(page, (Item) collector->tuples[i], tupsize, off, false, false);
379 
380  if (l == InvalidOffsetNumber)
381  elog(ERROR, "failed to add item to index page in \"%s\"",
382  RelationGetRelationName(index));
383 
384  memcpy(ptr, collector->tuples[i], tupsize);
385  ptr += tupsize;
386 
387  off++;
388  }
389 
390  Assert((ptr - collectordata) <= collector->sumsize);
391  if (needWal)
392  {
394  XLogRegisterBufData(1, collectordata, collector->sumsize);
395  }
396 
397  metadata->tailFreeSize = PageGetExactFreeSpace(page);
398 
399  MarkBufferDirty(buffer);
400  }
401 
402  /*
403  * Set pd_lower just past the end of the metadata. This is essential,
404  * because without doing so, metadata will be lost if xlog.c compresses
405  * the page. (We must do this here because pre-v11 versions of PG did not
406  * set the metapage's pd_lower correctly, so a pg_upgraded index might
407  * contain the wrong value.)
408  */
409  ((PageHeader) metapage)->pd_lower =
410  ((char *) metadata + sizeof(GinMetaPageData)) - (char *) metapage;
411 
412  /*
413  * Write metabuffer, make xlog entry
414  */
415  MarkBufferDirty(metabuffer);
416 
417  if (needWal)
418  {
419  XLogRecPtr recptr;
420 
421  memcpy(&data.metadata, metadata, sizeof(GinMetaPageData));
422 
424  XLogRegisterData((char *) &data, sizeof(ginxlogUpdateMeta));
425 
426  recptr = XLogInsert(RM_GIN_ID, XLOG_GIN_UPDATE_META_PAGE);
427  PageSetLSN(metapage, recptr);
428 
429  if (buffer != InvalidBuffer)
430  {
431  PageSetLSN(page, recptr);
432  }
433  }
434 
435  if (buffer != InvalidBuffer)
436  UnlockReleaseBuffer(buffer);
437 
438  /*
439  * Force pending list cleanup when it becomes too long. And,
440  * ginInsertCleanup could take significant amount of time, so we prefer to
441  * call it when it can do all the work in a single collection cycle. In
442  * non-vacuum mode, it shouldn't require maintenance_work_mem, so fire it
443  * while pending list is still small enough to fit into
444  * gin_pending_list_limit.
445  *
446  * ginInsertCleanup() should not be called inside our CRIT_SECTION.
447  */
448  cleanupSize = GinGetPendingListCleanupSize(index);
449  if (metadata->nPendingPages * GIN_PAGE_FREESIZE > cleanupSize * 1024L)
450  needCleanup = true;
451 
452  UnlockReleaseBuffer(metabuffer);
453 
455 
456  /*
457  * Since it could contend with concurrent cleanup process we cleanup
458  * pending list not forcibly.
459  */
460  if (needCleanup)
461  ginInsertCleanup(ginstate, false, true, false, NULL);
462 }
BlockNumber prevTail
Definition: ginxlog.h:172
#define GIN_UNLOCK
Definition: gin_private.h:43
void XLogRegisterBufData(uint8 block_id, char *data, int len)
Definition: xloginsert.c:361
#define PageIsEmpty(page)
Definition: bufpage.h:222
RelFileNode node
Definition: ginxlog.h:170
Relation index
Definition: gin_private.h:53
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1458
void XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Definition: xloginsert.c:213
#define END_CRIT_SECTION()
Definition: miscadmin.h:134
#define GinListPageSize
Definition: ginblock.h:331
Pointer Item
Definition: item.h:17
#define InvalidBuffer
Definition: buf.h:25
#define REGBUF_WILL_INIT
Definition: xloginsert.h:33
#define START_CRIT_SECTION()
Definition: miscadmin.h:132
#define PageAddItem(page, item, size, offsetNumber, overwrite, is_heap)
Definition: bufpage.h:416
#define GinPageGetOpaque(page)
Definition: ginblock.h:110
#define GIN_METAPAGE_BLKNO
Definition: ginblock.h:51
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:357
void CheckForSerializableConflictIn(Relation relation, HeapTuple tuple, Buffer buffer)
Definition: predicate.c:4442
static void makeSublist(Relation index, IndexTuple *tuples, int32 ntuples, GinMetaPageData *res)
Definition: ginfast.c:144
uint16 OffsetNumber
Definition: off.h:24
Definition: type.h:89
int64 nPendingHeapTuples
Definition: ginblock.h:74
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3376
#define ERROR
Definition: elog.h:43
#define XLOG_GIN_UPDATE_META_PAGE
Definition: ginxlog.h:162
BlockNumber head
Definition: ginblock.h:61
BlockNumber tail
Definition: ginblock.h:62
#define FirstOffsetNumber
Definition: off.h:27
#define REGBUF_STANDARD
Definition: xloginsert.h:35
#define GinGetPendingListCleanupSize(relation)
Definition: gin_private.h:35
#define RelationGetRelationName(relation)
Definition: rel.h:448
#define BufferGetPage(buffer)
Definition: bufmgr.h:159
BlockNumber newRightlink
Definition: ginxlog.h:173
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:323
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:415
IndexTuple * tuples
Definition: gin_private.h:429
#define GIN_EXCLUSIVE
Definition: gin_private.h:45
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3590
#define InvalidOffsetNumber
Definition: off.h:26
void ginInsertCleanup(GinState *ginstate, bool full_clean, bool fill_fsm, bool forceCleanup, IndexBulkDeleteResult *stats)
Definition: ginfast.c:780
GinMetaPageData metadata
Definition: ginxlog.h:171
RelFileNode rd_node
Definition: rel.h:55
PageHeaderData * PageHeader
Definition: bufpage.h:166
uint32 tailFreeSize
Definition: ginblock.h:67
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:732
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:596
#define OffsetNumberNext(offsetNumber)
Definition: off.h:53
#define InvalidBlockNumber
Definition: block.h:33
#define RelationNeedsWAL(relation)
Definition: rel.h:516
Size PageGetExactFreeSpace(Page page)
Definition: bufpage.c:632
void * palloc(Size size)
Definition: mcxt.c:924
#define elog(elevel,...)
Definition: elog.h:226
int i
#define GIN_PAGE_FREESIZE
Definition: ginfast.c:40
#define GinPageGetMeta(p)
Definition: ginblock.h:104
void XLogBeginInsert(void)
Definition: xloginsert.c:120
#define PageSetLSN(page, lsn)
Definition: bufpage.h:368
int Buffer
Definition: buf.h:23
Pointer Page
Definition: bufpage.h:78
#define IndexTupleSize(itup)
Definition: itup.h:71
BlockNumber nPendingPages
Definition: ginblock.h:73

◆ ginInitBA()

void ginInitBA ( BuildAccumulator accum)

Definition at line 109 of file ginbulk.c.

References BuildAccumulator::allocatedMemory, cmpEntryAccumulator(), BuildAccumulator::eas_used, BuildAccumulator::entryallocator, ginAllocEntryAccumulator(), ginCombineData(), rbt_create(), and BuildAccumulator::tree.

Referenced by ginbuild(), ginBuildCallback(), and ginInsertCleanup().

110 {
111  /* accum->ginstate is intentionally not set here */
112  accum->allocatedMemory = 0;
113  accum->entryallocator = NULL;
114  accum->eas_used = 0;
115  accum->tree = rbt_create(sizeof(GinEntryAccumulator),
119  NULL, /* no freefunc needed */
120  (void *) accum);
121 }
GinEntryAccumulator * entryallocator
Definition: gin_private.h:409
RBTree * rbt_create(Size node_size, rbt_comparator comparator, rbt_combiner combiner, rbt_allocfunc allocfunc, rbt_freefunc freefunc, void *arg)
Definition: rbtree.c:102
static void ginCombineData(RBTNode *existing, const RBTNode *newdata, void *arg)
Definition: ginbulk.c:30
static RBTNode * ginAllocEntryAccumulator(void *arg)
Definition: ginbulk.c:85
static int cmpEntryAccumulator(const RBTNode *a, const RBTNode *b, void *arg)
Definition: ginbulk.c:72

◆ GinInitBuffer()

void GinInitBuffer ( Buffer  b,
uint32  f 
)

Definition at line 351 of file ginutil.c.

References BufferGetPage, BufferGetPageSize, and GinInitPage().

Referenced by ginbuild(), ginbuildempty(), ginRedoCreatePTree(), ginRedoDeleteListPages(), ginRedoInsertListPage(), and writeListPage().

352 {
354 }
void GinInitPage(Page page, uint32 f, Size pageSize)
Definition: ginutil.c:338
#define BufferGetPage(buffer)
Definition: bufmgr.h:159
#define BufferGetPageSize(buffer)
Definition: bufmgr.h:146

◆ ginInitConsistentFunction()

void ginInitConsistentFunction ( GinState ginstate,
GinScanKey  key 
)

Definition at line 225 of file ginlogic.c.

References GinScanKeyData::attnum, GinScanKeyData::boolConsistentFn, GinScanKeyData::collation, GinScanKeyData::consistentFmgrInfo, GinState::consistentFn, directBoolConsistentFn(), directTriConsistentFn(), FmgrInfo::fn_oid, GIN_SEARCH_MODE_EVERYTHING, OidIsValid, GinScanKeyData::searchMode, shimBoolConsistentFn(), shimTriConsistentFn(), GinState::supportCollation, GinScanKeyData::triConsistentFmgrInfo, GinState::triConsistentFn, GinScanKeyData::triConsistentFn, trueConsistentFn(), and trueTriConsistentFn().

Referenced by ginFillScanKey().

226 {
228  {
231  }
232  else
233  {
234  key->consistentFmgrInfo = &ginstate->consistentFn[key->attnum - 1];
235  key->triConsistentFmgrInfo = &ginstate->triConsistentFn[key->attnum - 1];
236  key->collation = ginstate->supportCollation[key->attnum - 1];
237 
238  if (OidIsValid(ginstate->consistentFn[key->attnum - 1].fn_oid))
240  else
242 
243  if (OidIsValid(ginstate->triConsistentFn[key->attnum - 1].fn_oid))
245  else
247  }
248 }
FmgrInfo * triConsistentFmgrInfo
Definition: gin_private.h:288
Oid supportCollation[INDEX_MAX_KEYS]
Definition: gin_private.h:82
static GinTernaryValue directTriConsistentFn(GinScanKey key)
Definition: ginlogic.c:95
static GinTernaryValue shimTriConsistentFn(GinScanKey key)
Definition: ginlogic.c:154
#define GIN_SEARCH_MODE_EVERYTHING
Definition: gin.h:36
FmgrInfo consistentFn[INDEX_MAX_KEYS]
Definition: gin_private.h:76
FmgrInfo * consistentFmgrInfo
Definition: gin_private.h:287
#define OidIsValid(objectId)
Definition: c.h:638
OffsetNumber attnum
Definition: gin_private.h:299
static GinTernaryValue trueTriConsistentFn(GinScanKey key)
Definition: ginlogic.c:62
bool(* boolConsistentFn)(GinScanKey key)
Definition: gin_private.h:285
Oid fn_oid
Definition: fmgr.h:59
GinTernaryValue(* triConsistentFn)(GinScanKey key)
Definition: gin_private.h:286
static bool directBoolConsistentFn(GinScanKey key)
Definition: ginlogic.c:71
static bool trueConsistentFn(GinScanKey key)
Definition: ginlogic.c:56
static bool shimBoolConsistentFn(GinScanKey key)
Definition: ginlogic.c:115
FmgrInfo triConsistentFn[INDEX_MAX_KEYS]
Definition: gin_private.h:77

◆ GinInitMetabuffer()

void GinInitMetabuffer ( Buffer  b)

Definition at line 357 of file ginutil.c.

References BufferGetPage, BufferGetPageSize, GIN_CURRENT_VERSION, GIN_META, GinInitPage(), GinPageGetMeta, GinMetaPageData::ginVersion, GinMetaPageData::head, InvalidBlockNumber, GinMetaPageData::nDataPages, GinMetaPageData::nEntries, GinMetaPageData::nEntryPages, GinMetaPageData::nPendingHeapTuples, GinMetaPageData::nPendingPages, GinMetaPageData::nTotalPages, GinMetaPageData::tail, and GinMetaPageData::tailFreeSize.

Referenced by ginbuild(), ginbuildempty(), ginRedoDeleteListPages(), and ginRedoUpdateMetapage().

358 {
359  GinMetaPageData *metadata;
360  Page page = BufferGetPage(b);
361 
363 
364  metadata = GinPageGetMeta(page);
365 
366  metadata->head = metadata->tail = InvalidBlockNumber;
367  metadata->tailFreeSize = 0;
368  metadata->nPendingPages = 0;
369  metadata->nPendingHeapTuples = 0;
370  metadata->nTotalPages = 0;
371  metadata->nEntryPages = 0;
372  metadata->nDataPages = 0;
373  metadata->nEntries = 0;
374  metadata->ginVersion = GIN_CURRENT_VERSION;
375 
376  /*
377  * Set pd_lower just past the end of the metadata. This is essential,
378  * because without doing so, metadata will be lost if xlog.c compresses
379  * the page.
380  */
381  ((PageHeader) page)->pd_lower =
382  ((char *) metadata + sizeof(GinMetaPageData)) - (char *) page;
383 }
BlockNumber nEntryPages
Definition: ginblock.h:80
void GinInitPage(Page page, uint32 f, Size pageSize)
Definition: ginutil.c:338
BlockNumber nTotalPages
Definition: ginblock.h:79
int64 nEntries
Definition: ginblock.h:82
int64 nPendingHeapTuples
Definition: ginblock.h:74
#define GIN_META
Definition: ginblock.h:43
BlockNumber head
Definition: ginblock.h:61
BlockNumber tail
Definition: ginblock.h:62
#define BufferGetPage(buffer)
Definition: bufmgr.h:159
#define BufferGetPageSize(buffer)
Definition: bufmgr.h:146
PageHeaderData * PageHeader
Definition: bufpage.h:166
uint32 tailFreeSize
Definition: ginblock.h:67
#define GIN_CURRENT_VERSION
Definition: ginblock.h:102
#define InvalidBlockNumber
Definition: block.h:33
int32 ginVersion
Definition: ginblock.h:99
BlockNumber nDataPages
Definition: ginblock.h:81
#define GinPageGetMeta(p)
Definition: ginblock.h:104
Pointer Page
Definition: bufpage.h:78
BlockNumber nPendingPages
Definition: ginblock.h:73

◆ GinInitPage()

void GinInitPage ( Page  page,
uint32  f,
Size  pageSize 
)

Definition at line 338 of file ginutil.c.

References GinPageOpaqueData::flags, GinPageGetOpaque, InvalidBlockNumber, PageInit(), and GinPageOpaqueData::rightlink.

Referenced by createPostingTree(), dataPlaceToPageLeafSplit(), dataSplitPageInternal(), entrySplitPage(), GinInitBuffer(), GinInitMetabuffer(), and ginPlaceToPage().

339 {
340  GinPageOpaque opaque;
341 
342  PageInit(page, pageSize, sizeof(GinPageOpaqueData));
343 
344  opaque = GinPageGetOpaque(page);
345  memset(opaque, 0, sizeof(GinPageOpaqueData));
346  opaque->flags = f;
347  opaque->rightlink = InvalidBlockNumber;
348 }
BlockNumber rightlink
Definition: ginblock.h:31
#define GinPageGetOpaque(page)
Definition: ginblock.h:110
#define InvalidBlockNumber
Definition: block.h:33
void PageInit(Page page, Size pageSize, Size specialSize)
Definition: bufpage.c:42

◆ gininsert()

bool gininsert ( Relation  index,
Datum values,
bool isnull,
ItemPointer  ht_ctid,
Relation  heapRel,
IndexUniqueCheck  checkUnique,
struct IndexInfo indexInfo 
)

Definition at line 485 of file gininsert.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, CurrentMemoryContext, GinGetUseFastUpdate, ginHeapTupleFastCollect(), ginHeapTupleFastInsert(), ginHeapTupleInsert(), i, IndexInfo::ii_AmCache, IndexInfo::ii_Context, initGinState(), MemoryContextDelete(), MemoryContextSwitchTo(), TupleDescData::natts, GinState::origTupdesc, and palloc().

Referenced by ginhandler().

489 {
490  GinState *ginstate = (GinState *) indexInfo->ii_AmCache;
491  MemoryContext oldCtx;
492  MemoryContext insertCtx;
493  int i;
494 
495  /* Initialize GinState cache if first call in this statement */
496  if (ginstate == NULL)
497  {
498  oldCtx = MemoryContextSwitchTo(indexInfo->ii_Context);
499  ginstate = (GinState *) palloc(sizeof(GinState));
500  initGinState(ginstate, index);
501  indexInfo->ii_AmCache = (void *) ginstate;
502  MemoryContextSwitchTo(oldCtx);
503  }
504 
506  "Gin insert temporary context",
508 
509  oldCtx = MemoryContextSwitchTo(insertCtx);
510 
511  if (GinGetUseFastUpdate(index))
512  {
513  GinTupleCollector collector;
514 
515  memset(&collector, 0, sizeof(GinTupleCollector));
516 
517  for (i = 0; i < ginstate->origTupdesc->natts; i++)
518  ginHeapTupleFastCollect(ginstate, &collector,
519  (OffsetNumber) (i + 1),
520  values[i], isnull[i],
521  ht_ctid);
522 
523  ginHeapTupleFastInsert(ginstate, &collector);
524  }
525  else
526  {
527  for (i = 0; i < ginstate->origTupdesc->natts; i++)
528  ginHeapTupleInsert(ginstate, (OffsetNumber) (i + 1),
529  values[i], isnull[i],
530  ht_ctid);
531  }
532 
533  MemoryContextSwitchTo(oldCtx);
534  MemoryContextDelete(insertCtx);
535 
536  return false;
537 }
MemoryContext ii_Context
Definition: execnodes.h:176
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:169
void ginHeapTupleFastInsert(GinState *ginstate, GinTupleCollector *collector)
Definition: ginfast.c:218
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static void ginHeapTupleInsert(GinState *ginstate, OffsetNumber attnum, Datum value, bool isNull, ItemPointer item)
Definition: gininsert.c:467
uint16 OffsetNumber
Definition: off.h:24
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:191
void initGinState(GinState *state, Relation index)
Definition: ginutil.c:89
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
void * ii_AmCache
Definition: execnodes.h:175
#define GinGetUseFastUpdate(relation)
Definition: gin_private.h:32
static Datum values[MAXATTR]
Definition: bootstrap.c:167
void * palloc(Size size)
Definition: mcxt.c:924
int i
void ginHeapTupleFastCollect(GinState *ginstate, GinTupleCollector *collector, OffsetNumber attnum, Datum value, bool isNull, ItemPointer ht_ctid)
Definition: ginfast.c:473
TupleDesc origTupdesc
Definition: gin_private.h:67

◆ ginInsertBAEntries()

void ginInsertBAEntries ( BuildAccumulator accum,
ItemPointer  heapptr,
OffsetNumber  attnum,
Datum entries,
GinNullCategory categories,
int32  nentries 
)

Definition at line 210 of file ginbulk.c.

References Assert, FirstOffsetNumber, ginInsertBAEntry(), i, and ItemPointerIsValid.

Referenced by ginHeapTupleBulkInsert(), and processPendingPage().

214 {
215  uint32 step = nentries;
216 
217  if (nentries <= 0)
218  return;
219 
221 
222  /*
223  * step will contain largest power of 2 and <= nentries
224  */
225  step |= (step >> 1);
226  step |= (step >> 2);
227  step |= (step >> 4);
228  step |= (step >> 8);
229  step |= (step >> 16);
230  step >>= 1;
231  step++;
232 
233  while (step > 0)
234  {
235  int i;
236 
237  for (i = step - 1; i < nentries && i >= 0; i += step << 1 /* *2 */ )
238  ginInsertBAEntry(accum, heapptr, attnum,
239  entries[i], categories[i]);
240 
241  step >>= 1; /* /2 */
242  }
243 }
#define ItemPointerIsValid(pointer)
Definition: itemptr.h:82
static void ginInsertBAEntry(BuildAccumulator *accum, ItemPointer heapptr, OffsetNumber attnum, Datum key, GinNullCategory category)
Definition: ginbulk.c:148
#define FirstOffsetNumber
Definition: off.h:27
unsigned int uint32
Definition: c.h:358
int16 attnum
Definition: pg_attribute.h:79
#define Assert(condition)
Definition: c.h:732
int i

◆ ginInsertCleanup()

void ginInsertCleanup ( GinState ginstate,
bool  full_clean,
bool  fill_fsm,
bool  forceCleanup,
IndexBulkDeleteResult stats 
)

Definition at line 780 of file ginfast.c.

References BuildAccumulator::allocatedMemory, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, attnum, autovacuum_work_mem, BufferGetPage, ConditionalLockPage(), CurrentMemoryContext, ExclusiveLock, FirstOffsetNumber, GIN_EXCLUSIVE, GIN_METAPAGE_BLKNO, GIN_SHARE, GIN_UNLOCK, ginBeginBAScan(), ginEntryInsert(), ginGetBAEntry(), ginInitBA(), GinPageGetMeta, GinPageGetOpaque, GinPageHasFullRow, GinPageIsDeleted, BuildAccumulator::ginstate, GinMetaPageData::head, GinState::index, IndexFreeSpaceMapVacuum(), initKeyArray(), InvalidBlockNumber, IsAutoVacuumWorkerProcess(), sort-test::key, sort-test::list, LockBuffer(), LockPage(), maintenance_work_mem, KeyArray::maxvalues, MemoryContextDelete(), MemoryContextReset(), MemoryContextSwitchTo(), opCtx, PageGetMaxOffsetNumber, processPendingPage(), ReadBuffer(), ReleaseBuffer(), shiftList(), GinMetaPageData::tail, UnlockPage(), UnlockReleaseBuffer(), vacuum_delay_point(), and work_mem.

Referenced by gin_clean_pending_list(), ginbulkdelete(), ginHeapTupleFastInsert(), and ginvacuumcleanup().

783 {
784  Relation index = ginstate->index;
785  Buffer metabuffer,
786  buffer;
787  Page metapage,
788  page;
789  GinMetaPageData *metadata;
791  oldCtx;
792  BuildAccumulator accum;
793  KeyArray datums;
794  BlockNumber blkno,
795  blknoFinish;
796  bool cleanupFinish = false;
797  bool fsm_vac = false;
798  Size workMemory;
799 
800  /*
801  * We would like to prevent concurrent cleanup process. For that we will
802  * lock metapage in exclusive mode using LockPage() call. Nobody other
803  * will use that lock for metapage, so we keep possibility of concurrent
804  * insertion into pending list
805  */
806 
807  if (forceCleanup)
808  {
809  /*
810  * We are called from [auto]vacuum/analyze or gin_clean_pending_list()
811  * and we would like to wait concurrent cleanup to finish.
812  */
814  workMemory =
817  }
818  else
819  {
820  /*
821  * We are called from regular insert and if we see concurrent cleanup
822  * just exit in hope that concurrent process will clean up pending
823  * list.
824  */
826  return;
827  workMemory = work_mem;
828  }
829 
830  metabuffer = ReadBuffer(index, GIN_METAPAGE_BLKNO);
831  LockBuffer(metabuffer, GIN_SHARE);
832  metapage = BufferGetPage(metabuffer);
833  metadata = GinPageGetMeta(metapage);
834 
835  if (metadata->head == InvalidBlockNumber)
836  {
837  /* Nothing to do */
838  UnlockReleaseBuffer(metabuffer);
840  return;
841  }
842 
843  /*
844  * Remember a tail page to prevent infinite cleanup if other backends add
845  * new tuples faster than we can cleanup.
846  */
847  blknoFinish = metadata->tail;
848 
849  /*
850  * Read and lock head of pending list
851  */
852  blkno = metadata->head;
853  buffer = ReadBuffer(index, blkno);
854  LockBuffer(buffer, GIN_SHARE);
855  page = BufferGetPage(buffer);
856 
857  LockBuffer(metabuffer, GIN_UNLOCK);
858 
859  /*
860  * Initialize. All temporary space will be in opCtx
861  */
863  "GIN insert cleanup temporary context",
865 
866  oldCtx = MemoryContextSwitchTo(opCtx);
867 
868  initKeyArray(&datums, 128);
869  ginInitBA(&accum);
870  accum.ginstate = ginstate;
871 
872  /*
873  * At the top of this loop, we have pin and lock on the current page of
874  * the pending list. However, we'll release that before exiting the loop.
875  * Note we also have pin but not lock on the metapage.
876  */
877  for (;;)
878  {
879  Assert(!GinPageIsDeleted(page));
880 
881  /*
882  * Are we walk through the page which as we remember was a tail when
883  * we start our cleanup? But if caller asks us to clean up whole
884  * pending list then ignore old tail, we will work until list becomes
885  * empty.
886  */
887  if (blkno == blknoFinish && full_clean == false)
888  cleanupFinish = true;
889 
890  /*
891  * read page's datums into accum
892  */
893  processPendingPage(&accum, &datums, page, FirstOffsetNumber);
894 
896 
897  /*
898  * Is it time to flush memory to disk? Flush if we are at the end of
899  * the pending list, or if we have a full row and memory is getting
900  * full.
901  */
902  if (GinPageGetOpaque(page)->rightlink == InvalidBlockNumber ||
903  (GinPageHasFullRow(page) &&
904  (accum.allocatedMemory >= workMemory * 1024L)))
905  {
907  uint32 nlist;
908  Datum key;
909  GinNullCategory category;
910  OffsetNumber maxoff,
911  attnum;
912 
913  /*
914  * Unlock current page to increase performance. Changes of page
915  * will be checked later by comparing maxoff after completion of
916  * memory flush.
917  */
918  maxoff = PageGetMaxOffsetNumber(page);
919  LockBuffer(buffer, GIN_UNLOCK);
920 
921  /*
922  * Moving collected data into regular structure can take
923  * significant amount of time - so, run it without locking pending
924  * list.
925  */
926  ginBeginBAScan(&accum);
927  while ((list = ginGetBAEntry(&accum,
928  &attnum, &key, &category, &nlist)) != NULL)
929  {
930  ginEntryInsert(ginstate, attnum, key, category,
931  list, nlist, NULL);
933  }
934 
935  /*
936  * Lock the whole list to remove pages
937  */
938  LockBuffer(metabuffer, GIN_EXCLUSIVE);
939  LockBuffer(buffer, GIN_SHARE);
940 
941  Assert(!GinPageIsDeleted(page));
942 
943  /*
944  * While we left the page unlocked, more stuff might have gotten
945  * added to it. If so, process those entries immediately. There
946  * shouldn't be very many, so we don't worry about the fact that
947  * we're doing this with exclusive lock. Insertion algorithm
948  * guarantees that inserted row(s) will not continue on next page.
949  * NOTE: intentionally no vacuum_delay_point in this loop.
950  */
951  if (PageGetMaxOffsetNumber(page) != maxoff)
952  {
953  ginInitBA(&accum);
954  processPendingPage(&accum, &datums, page, maxoff + 1);
955 
956  ginBeginBAScan(&accum);
957  while ((list = ginGetBAEntry(&accum,
958  &attnum, &key, &category, &nlist)) != NULL)
959  ginEntryInsert(ginstate, attnum, key, category,
960  list, nlist, NULL);
961  }
962 
963  /*
964  * Remember next page - it will become the new list head
965  */
966  blkno = GinPageGetOpaque(page)->rightlink;
967  UnlockReleaseBuffer(buffer); /* shiftList will do exclusive
968  * locking */
969 
970  /*
971  * remove read pages from pending list, at this point all content
972  * of read pages is in regular structure
973  */
974  shiftList(index, metabuffer, blkno, fill_fsm, stats);
975 
976  /* At this point, some pending pages have been freed up */
977  fsm_vac = true;
978 
979  Assert(blkno == metadata->head);
980  LockBuffer(metabuffer, GIN_UNLOCK);
981 
982  /*
983  * if we removed the whole pending list or we cleanup tail (which
984  * we remembered on start our cleanup process) then just exit
985  */
986  if (blkno == InvalidBlockNumber || cleanupFinish)
987  break;
988 
989  /*
990  * release memory used so far and reinit state
991  */
992  MemoryContextReset(opCtx);
993  initKeyArray(&datums, datums.maxvalues);
994  ginInitBA(&accum);
995  }
996  else
997  {
998  blkno = GinPageGetOpaque(page)->rightlink;
999  UnlockReleaseBuffer(buffer);
1000  }
1001 
1002  /*
1003  * Read next page in pending list
1004  */
1006  buffer = ReadBuffer(index, blkno);
1007  LockBuffer(buffer, GIN_SHARE);
1008  page = BufferGetPage(buffer);
1009  }
1010 
1012  ReleaseBuffer(metabuffer);
1013 
1014  /*
1015  * As pending list pages can have a high churn rate, it is desirable to
1016  * recycle them immediately to the FreeSpaceMap when ordinary backends
1017  * clean the list.
1018  */
1019  if (fsm_vac && fill_fsm)
1020  IndexFreeSpaceMapVacuum(index);
1021 
1022  /* Clean up temporary space */
1023  MemoryContextSwitchTo(oldCtx);
1024  MemoryContextDelete(opCtx);
1025 }
#define GinPageHasFullRow(page)
Definition: ginblock.h:119
int autovacuum_work_mem
Definition: autovacuum.c:115
#define GIN_UNLOCK
Definition: gin_private.h:43
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:169
Relation index
Definition: gin_private.h:53
#define ExclusiveLock
Definition: lockdefs.h:44
static MemoryContext opCtx
Definition: ginxlog.c:22
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:136
uint32 BlockNumber
Definition: block.h:31
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3353
#define GinPageGetOpaque(page)
Definition: ginblock.h:110
#define GIN_METAPAGE_BLKNO
Definition: ginblock.h:51
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:357
uint16 OffsetNumber
Definition: off.h:24
static void initKeyArray(KeyArray *keys, int32 maxvalues)
Definition: ginfast.c:672
Definition: type.h:89
void ginEntryInsert(GinState *ginstate, OffsetNumber attnum, Datum key, GinNullCategory category, ItemPointerData *items, uint32 nitem, GinStatsData *buildStats)
Definition: gininsert.c:180
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3376
signed char GinNullCategory
Definition: ginblock.h:210
BlockNumber head
Definition: ginblock.h:61
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:191
void LockPage(Relation relation, BlockNumber blkno, LOCKMODE lockmode)
Definition: lmgr.c:470
BlockNumber tail
Definition: ginblock.h:62
#define FirstOffsetNumber
Definition: off.h:27
unsigned int uint32
Definition: c.h:358
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
GinState * ginstate
Definition: gin_private.h:407
#define BufferGetPage(buffer)
Definition: bufmgr.h:159
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3278
#define GIN_SHARE
Definition: gin_private.h:44
int32 maxvalues
Definition: ginfast.c:48
static void processPendingPage(BuildAccumulator *accum, KeyArray *ka, Page page, OffsetNumber startoff)
Definition: ginfast.c:709
#define GinPageIsDeleted(page)
Definition: ginblock.h:124
uintptr_t Datum
Definition: postgres.h:367
#define GIN_EXCLUSIVE
Definition: gin_private.h:45
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3590
int work_mem
Definition: globals.c:121
int16 attnum
Definition: pg_attribute.h:79
int maintenance_work_mem
Definition: globals.c:122
#define Assert(condition)
Definition: c.h:732
static void shiftList(Relation index, Buffer metabuffer, BlockNumber newHead, bool fill_fsm, IndexBulkDeleteResult *stats)
Definition: ginfast.c:551
void IndexFreeSpaceMapVacuum(Relation rel)
Definition: indexfsm.c:71
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:596
size_t Size
Definition: c.h:466
#define InvalidBlockNumber
Definition: block.h:33
ItemPointerData * ginGetBAEntry(BuildAccumulator *accum, OffsetNumber *attnum, Datum *key, GinNullCategory *category, uint32 *n)
Definition: ginbulk.c:268
void UnlockPage(Relation relation, BlockNumber blkno, LOCKMODE lockmode)
Definition: lmgr.c:505
bool ConditionalLockPage(Relation relation, BlockNumber blkno, LOCKMODE lockmode)
Definition: lmgr.c:489
void ginBeginBAScan(BuildAccumulator *accum)
Definition: ginbulk.c:257
#define GinPageGetMeta(p)
Definition: ginblock.h:104
void vacuum_delay_point(void)
Definition: vacuum.c:1931
int Buffer
Definition: buf.h:23
Pointer Page
Definition: bufpage.h:78
void ginInitBA(BuildAccumulator *accum)
Definition: ginbulk.c:109

◆ ginInsertItemPointers()

void ginInsertItemPointers ( Relation  index,
BlockNumber  rootBlkno,
ItemPointerData items,
uint32  nitem,
GinStatsData buildStats 
)

Definition at line 1899 of file gindatapage.c.

References GinBtreeDataLeafInsertData::curitem, ginFindLeafPage(), ginInsertValue(), ginPrepareDataScan(), GinBtreeData::isBuild, GinBtreeData::itemptr, GinBtreeDataLeafInsertData::items, and GinBtreeDataLeafInsertData::nitem.

Referenced by addItemPointersToLeafTuple(), createPostingTree(), and ginEntryInsert().

1902 {
1903  GinBtreeData btree;
1904  GinBtreeDataLeafInsertData insertdata;
1905  GinBtreeStack *stack;
1906 
1907  ginPrepareDataScan(&btree, index, rootBlkno);
1908  btree.isBuild = (buildStats != NULL);
1909  insertdata.items = items;
1910  insertdata.nitem = nitem;
1911  insertdata.curitem = 0;
1912 
1913  while (insertdata.curitem < insertdata.nitem)
1914  {
1915  /* search for the leaf page where the first item should go to */
1916  btree.itemptr = insertdata.items[insertdata.curitem];
1917  stack = ginFindLeafPage(&btree, false, true, NULL);
1918 
1919  ginInsertValue(&btree, stack, &insertdata, buildStats);
1920  }
1921 }
GinBtreeStack * ginFindLeafPage(GinBtree btree, bool searchMode, bool rootConflictCheck, Snapshot snapshot)
Definition: ginbtree.c:80
static void ginPrepareDataScan(GinBtree btree, Relation index, BlockNumber rootBlkno)
Definition: gindatapage.c:1873
ItemPointerData * items
Definition: gin_private.h:188
void ginInsertValue(GinBtree btree, GinBtreeStack *stack, void *insertdata, GinStatsData *buildStats)
Definition: ginbtree.c:784
ItemPointerData itemptr
Definition: gin_private.h:172

◆ ginInsertValue()

void ginInsertValue ( GinBtree  btree,
GinBtreeStack stack,
void *  insertdata,
GinStatsData buildStats 
)

Definition at line 784 of file ginbtree.c.

References GinBtreeStack::buffer, BufferGetPage, freeGinBtreeStack(), GIN_UNLOCK, ginFinishSplit(), GinPageIsIncompleteSplit, ginPlaceToPage(), InvalidBlockNumber, InvalidBuffer, and LockBuffer().

Referenced by ginEntryInsert(), and ginInsertItemPointers().

786 {
787  bool done;
788 
789  /* If the leaf page was incompletely split, finish the split first */
791  ginFinishSplit(btree, stack, false, buildStats);
792 
793  done = ginPlaceToPage(btree, stack,
794  insertdata, InvalidBlockNumber,
795  InvalidBuffer, buildStats);
796  if (done)
797  {
798  LockBuffer(stack->buffer, GIN_UNLOCK);
799  freeGinBtreeStack(stack);
800  }
801  else
802  ginFinishSplit(btree, stack, true, buildStats);
803 }
#define GIN_UNLOCK
Definition: gin_private.h:43
#define GinPageIsIncompleteSplit(page)
Definition: ginblock.h:127
static void ginFinishSplit(GinBtree btree, GinBtreeStack *stack, bool freestack, GinStatsData *buildStats)
Definition: ginbtree.c:675
#define InvalidBuffer
Definition: buf.h:25
#define BufferGetPage(buffer)
Definition: bufmgr.h:159
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3590
#define InvalidBlockNumber
Definition: block.h:33
void freeGinBtreeStack(GinBtreeStack *stack)
Definition: ginbtree.c:201
static bool ginPlaceToPage(GinBtree btree, GinBtreeStack *stack, void *insertdata, BlockNumber updateblkno, Buffer childbuf, GinStatsData *buildStats)
Definition: ginbtree.c:337

◆ ginMergeItemPointers()

ItemPointer ginMergeItemPointers ( ItemPointerData a,
uint32  na,
ItemPointerData b,
uint32  nb,
int *  nmerged 
)

Definition at line 363 of file ginpostinglist.c.

References cmp(), ginCompareItemPointers(), and palloc().

Referenced by addItemPointersToLeafTuple(), addItemsToLeaf(), ginRedoRecompress(), and leafRepackItems().

366 {
367  ItemPointerData *dst;
368 
369  dst = (ItemPointer) palloc((na + nb) * sizeof(ItemPointerData));
370 
371  /*
372  * If the argument arrays don't overlap, we can just append them to each
373  * other.
374  */
375  if (na == 0 || nb == 0 || ginCompareItemPointers(&a[na - 1], &b[0]) < 0)
376  {
377  memcpy(dst, a, na * sizeof(ItemPointerData));
378  memcpy(&dst[na], b, nb * sizeof(ItemPointerData));
379  *nmerged = na + nb;
380  }
381  else if (ginCompareItemPointers(&b[nb - 1], &a[0]) < 0)
382  {
383  memcpy(dst, b, nb * sizeof(ItemPointerData));
384  memcpy(&dst[nb], a, na * sizeof(ItemPointerData));
385  *nmerged = na + nb;
386  }
387  else
388  {
389  ItemPointerData *dptr = dst;
390  ItemPointerData *aptr = a;
391  ItemPointerData *bptr = b;
392 
393  while (aptr - a < na && bptr - b < nb)
394  {
395  int cmp = ginCompareItemPointers(aptr, bptr);
396 
397  if (cmp > 0)
398  *dptr++ = *bptr++;
399  else if (cmp == 0)
400  {
401  /* only keep one copy of the identical items */
402  *dptr++ = *bptr++;
403  aptr++;
404  }
405  else
406  *dptr++ = *aptr++;
407  }
408 
409  while (aptr - a < na)
410  *dptr++ = *aptr++;
411 
412  while (bptr - b < nb)
413  *dptr++ = *bptr++;
414 
415  *nmerged = dptr - dst;
416  }
417 
418  return dst;
419 }
ItemPointerData * ItemPointer
Definition: itemptr.h:49
struct ItemPointerData ItemPointerData
static int ginCompareItemPointers(ItemPointer a, ItemPointer b)
Definition: gin_private.h:461
void * palloc(Size size)
Definition: mcxt.c:924
static int cmp(const chr *x, const chr *y, size_t len)
Definition: regc_locale.c:742

◆ GinNewBuffer()

Buffer GinNewBuffer ( Relation  index)

Definition at line 292 of file ginutil.c.

References BufferGetPage, ConditionalLockBuffer(), ExclusiveLock, GetFreeIndexPage(), GIN_EXCLUSIVE, GIN_UNLOCK, GinPageIsRecyclable, InvalidBlockNumber, LockBuffer(), LockRelationForExtension(), P_NEW, ReadBuffer(), RELATION_IS_LOCAL, ReleaseBuffer(), and UnlockRelationForExtension().

Referenced by createPostingTree(), ginbuild(), ginPlaceToPage(), and makeSublist().

293 {
294  Buffer buffer;
295  bool needLock;
296 
297  /* First, try to get a page from FSM */
298  for (;;)
299  {
300  BlockNumber blkno = GetFreeIndexPage(index);
301 
302  if (blkno == InvalidBlockNumber)
303  break;
304 
305  buffer = ReadBuffer(index, blkno);
306 
307  /*
308  * We have to guard against the possibility that someone else already
309  * recycled this page; the buffer may be locked if so.
310  */
311  if (ConditionalLockBuffer(buffer))
312  {
313  if (GinPageIsRecyclable(BufferGetPage(buffer)))
314  return buffer; /* OK to use */
315 
316  LockBuffer(buffer, GIN_UNLOCK);
317  }
318 
319  /* Can't use it, so release buffer and try again */
320  ReleaseBuffer(buffer);
321  }
322 
323  /* Must extend the file */
324  needLock = !RELATION_IS_LOCAL(index);
325  if (needLock)
327 
328  buffer = ReadBuffer(index, P_NEW);
329  LockBuffer(buffer, GIN_EXCLUSIVE);
330 
331  if (needLock)
333 
334  return buffer;
335 }
#define GIN_UNLOCK
Definition: gin_private.h:43
#define GinPageIsRecyclable(page)
Definition: ginblock.h:137
#define ExclusiveLock
Definition: lockdefs.h:44
#define RELATION_IS_LOCAL(relation)
Definition: rel.h:534
uint32 BlockNumber
Definition: block.h:31
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3353
#define P_NEW
Definition: bufmgr.h:81
#define BufferGetPage(buffer)
Definition: bufmgr.h:159
bool ConditionalLockBuffer(Buffer buffer)
Definition: bufmgr.c:3616
void LockRelationForExtension(Relation relation, LOCKMODE lockmode)
Definition: lmgr.c:402
void UnlockRelationForExtension(Relation relation, LOCKMODE lockmode)
Definition: lmgr.c:452
#define GIN_EXCLUSIVE
Definition: gin_private.h:45
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3590
BlockNumber GetFreeIndexPage(Relation rel)
Definition: indexfsm.c:38
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:596
#define InvalidBlockNumber
Definition: block.h:33
int Buffer
Definition: buf.h:23

◆ ginNewScanKey()

void ginNewScanKey ( IndexScanDesc  scan)

Definition at line 262 of file ginscan.c.

References GinScanOpaqueData::allocentries, DatumGetPointer, GinScanOpaqueData::entries, ereport, errcode(), errhint(), errmsg(), ERROR, GinState::extractQueryFn, FirstOffsetNumber, FunctionCall7Coll(), GIN_CAT_NULL_KEY, GIN_SEARCH_MODE_ALL, GIN_SEARCH_MODE_DEFAULT, GIN_SEARCH_MODE_EVERYTHING, ginFillScanKey(), ginGetStats(), GinScanOpaqueData::ginstate, GinStatsData::ginVersion, i, IndexScanDescData::indexRelation, InvalidStrategy, GinScanOpaqueData::isVoidRes, GinScanOpaqueData::keyCtx, IndexScanDescData::keyData, GinScanOpaqueData::keys, Max, MemoryContextSwitchTo(), GinScanOpaqueData::nkeys, IndexScanDescData::numberOfKeys, IndexScanDescData::opaque, palloc(), palloc0(), pgstat_count_index_scan, PointerGetDatum, RelationGetRelationName, ScanKeyData::sk_argument, ScanKeyData::sk_attno, ScanKeyData::sk_flags, SK_ISNULL, ScanKeyData::sk_strategy, GinState::supportCollation, GinScanOpaqueData::totalentries, and UInt16GetDatum.

Referenced by gingetbitmap().

263 {
264  ScanKey scankey = scan->keyData;
265  GinScanOpaque so = (GinScanOpaque) scan->opaque;
266  int i;
267  bool hasNullQuery = false;
268  MemoryContext oldCtx;
269 
270  /*
271  * Allocate all the scan key information in the key context. (If
272  * extractQuery leaks anything there, it won't be reset until the end of
273  * scan or rescan, but that's OK.)
274  */
275  oldCtx = MemoryContextSwitchTo(so->keyCtx);
276 
277  /* if no scan keys provided, allocate extra EVERYTHING GinScanKey */
278  so->keys = (GinScanKey)
279  palloc(Max(scan->numberOfKeys, 1) * sizeof(GinScanKeyData));
280  so->nkeys = 0;
281 
282  /* initialize expansible array of GinScanEntry pointers */
283  so->totalentries = 0;
284  so->allocentries = 32;
285  so->entries = (GinScanEntry *)
286  palloc(so->allocentries * sizeof(GinScanEntry));
287 
288  so->isVoidRes = false;
289 
290  for (i = 0; i < scan->numberOfKeys; i++)
291  {
292  ScanKey skey = &scankey[i];
293  Datum *queryValues;
294  int32 nQueryValues = 0;
295  bool *partial_matches = NULL;
296  Pointer *extra_data = NULL;
297  bool *nullFlags = NULL;
298  GinNullCategory *categories;
299  int32 searchMode = GIN_SEARCH_MODE_DEFAULT;
300 
301  /*
302  * We assume that GIN-indexable operators are strict, so a null query
303  * argument means an unsatisfiable query.
304  */
305  if (skey->sk_flags & SK_ISNULL)
306  {
307  so->isVoidRes = true;
308  break;
309  }
310 
311  /* OK to call the extractQueryFn */
312  queryValues = (Datum *)
314  so->ginstate.supportCollation[skey->sk_attno - 1],
315  skey->sk_argument,
316  PointerGetDatum(&nQueryValues),
318  PointerGetDatum(&partial_matches),
319  PointerGetDatum(&extra_data),
320  PointerGetDatum(&nullFlags),
321  PointerGetDatum(&searchMode)));
322 
323  /*
324  * If bogus searchMode is returned, treat as GIN_SEARCH_MODE_ALL; note
325  * in particular we don't allow extractQueryFn to select
326  * GIN_SEARCH_MODE_EVERYTHING.
327  */
328  if (searchMode < GIN_SEARCH_MODE_DEFAULT ||
329  searchMode > GIN_SEARCH_MODE_ALL)
330  searchMode = GIN_SEARCH_MODE_ALL;
331 
332  /* Non-default modes require the index to have placeholders */
333  if (searchMode != GIN_SEARCH_MODE_DEFAULT)
334  hasNullQuery = true;
335 
336  /*
337  * In default mode, no keys means an unsatisfiable query.
338  */
339  if (queryValues == NULL || nQueryValues <= 0)
340  {
341  if (searchMode == GIN_SEARCH_MODE_DEFAULT)
342  {
343  so->isVoidRes = true;
344  break;
345  }
346  nQueryValues = 0; /* ensure sane value */
347  }
348 
349  /*
350  * Create GinNullCategory representation. If the extractQueryFn
351  * didn't create a nullFlags array, we assume everything is non-null.
352  * While at it, detect whether any null keys are present.
353  */
354  categories = (GinNullCategory *) palloc0(nQueryValues * sizeof(GinNullCategory));
355  if (nullFlags)
356  {
357  int32 j;
358 
359  for (j = 0; j < nQueryValues; j++)
360  {
361  if (nullFlags[j])
362  {
363  categories[j] = GIN_CAT_NULL_KEY;
364  hasNullQuery = true;
365  }
366  }
367  }
368 
369  ginFillScanKey(so, skey->sk_attno,
370  skey->sk_strategy, searchMode,
371  skey->sk_argument, nQueryValues,
372  queryValues, categories,
373  partial_matches, extra_data);
374  }
375 
376  /*
377  * If there are no regular scan keys, generate an EVERYTHING scankey to
378  * drive a full-index scan.
379  */
380  if (so->nkeys == 0 && !so->isVoidRes)
381  {
382  hasNullQuery = true;
385  (Datum) 0, 0,
386  NULL, NULL, NULL, NULL);
387  }
388 
389  /*
390  * If the index is version 0, it may be missing null and placeholder
391  * entries, which would render searches for nulls and full-index scans
392  * unreliable. Throw an error if so.
393  */
394  if (hasNullQuery && !so->isVoidRes)
395  {
396  GinStatsData ginStats;
397 
398  ginGetStats(scan->indexRelation, &ginStats);
399  if (ginStats.ginVersion < 1)
400  ereport(ERROR,
401  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
402  errmsg("old GIN indexes do not support whole-index scans nor searches for nulls"),
403  errhint("To fix this, do REINDEX INDEX \"%s\".",
405  }
406 
407  MemoryContextSwitchTo(oldCtx);
408 
410 }
#define InvalidStrategy
Definition: stratnum.h:24
Oid supportCollation[INDEX_MAX_KEYS]
Definition: gin_private.h:82
int errhint(const char *fmt,...)
Definition: elog.c:974
#define PointerGetDatum(X)
Definition: postgres.h:556
#define GIN_SEARCH_MODE_EVERYTHING
Definition: gin.h:36
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:570
signed int int32
Definition: c.h:346
Relation indexRelation
Definition: relscan.h:103
#define GIN_SEARCH_MODE_ALL
Definition: gin.h:35
char * Pointer
Definition: c.h:335
#define ERROR
Definition: elog.h:43
signed char GinNullCategory
Definition: ginblock.h:210
Datum FunctionCall7Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4, Datum arg5, Datum arg6, Datum arg7)
Definition: fmgr.c:1285
struct GinScanKeyData * GinScanKey
Definition: gin_private.h:256
StrategyNumber sk_strategy
Definition: skey.h:68
GinScanOpaqueData * GinScanOpaque
Definition: gin_private.h:364
static void ginFillScanKey(GinScanOpaque so, OffsetNumber attnum, StrategyNumber strategy, int32 searchMode, Datum query, uint32 nQueryValues, Datum *queryValues, GinNullCategory *queryCategories, bool *partial_matches, Pointer *extra_data)
Definition: ginscan.c:132
#define FirstOffsetNumber
Definition: off.h:27
MemoryContext keyCtx
Definition: gin_private.h:359
#define RelationGetRelationName(relation)
Definition: rel.h:448
#define pgstat_count_index_scan(rel)
Definition: pgstat.h:1374
FmgrInfo extractQueryFn[INDEX_MAX_KEYS]
Definition: gin_private.h:75
#define SK_ISNULL
Definition: skey.h:115
#define ereport(elevel, rest)
Definition: elog.h:141
GinScanKey keys
Definition: gin_private.h:352
#define GIN_CAT_NULL_KEY
Definition: ginblock.h:213
void * palloc0(Size size)
Definition: mcxt.c:955
struct GinScanKeyData GinScanKeyData
uintptr_t Datum
Definition: postgres.h:367
void ginGetStats(Relation index, GinStatsData *stats)
Definition: ginutil.c:638
#define GIN_SEARCH_MODE_DEFAULT
Definition: gin.h:33
#define Max(x, y)
Definition: c.h:884
int sk_flags
Definition: skey.h:66
int32 ginVersion
Definition: gin.h:48
#define DatumGetPointer(X)
Definition: postgres.h:549
struct ScanKeyData * keyData
Definition: relscan.h:107
GinScanEntry * entries
Definition: gin_private.h:355
void * palloc(Size size)
Definition: mcxt.c:924
int errmsg(const char *fmt,...)
Definition: elog.c:784
int i
Datum sk_argument
Definition: skey.h:72
#define UInt16GetDatum(X)
Definition: postgres.h:465
AttrNumber sk_attno
Definition: skey.h:67

◆ ginoptions()

bytea* ginoptions ( Datum  reloptions,
bool  validate 
)

Definition at line 603 of file ginutil.c.

References allocateReloptStruct(), fillRelOptions(), lengthof, offsetof, options, parseRelOptions(), pfree(), RELOPT_KIND_GIN, RELOPT_TYPE_BOOL, and RELOPT_TYPE_INT.

Referenced by ginhandler().

604 {
606  GinOptions *rdopts;
607  int numoptions;
608  static const relopt_parse_elt tab[] = {
609  {"fastupdate", RELOPT_TYPE_BOOL, offsetof(GinOptions, useFastUpdate)},
610  {"gin_pending_list_limit", RELOPT_TYPE_INT, offsetof(GinOptions,
611  pendingListCleanupSize)}
612  };
613 
614  options = parseRelOptions(reloptions, validate, RELOPT_KIND_GIN,
615  &numoptions);
616 
617  /* if none set, we're done */
618  if (numoptions == 0)
619  return NULL;
620 
621  rdopts = allocateReloptStruct(sizeof(GinOptions), options, numoptions);
622 
623  fillRelOptions((void *) rdopts, sizeof(GinOptions), options, numoptions,
624  validate, tab, lengthof(tab));
625 
626  pfree(options);
627 
628  return (bytea *) rdopts;
629 }
#define lengthof(array)
Definition: c.h:662
void pfree(void *pointer)
Definition: mcxt.c:1031
void * allocateReloptStruct(Size base, relopt_value *options, int numoptions)
Definition: reloptions.c:1268
static char ** options
void fillRelOptions(void *rdopts, Size basesize, relopt_value *options, int numoptions, bool validate, const relopt_parse_elt *elems, int numelems)
Definition: reloptions.c:1292
Definition: c.h:549
relopt_value * parseRelOptions(Datum options, bool validate, relopt_kind kind, int *numrelopts)
Definition: reloptions.c:1074
#define offsetof(type, field)
Definition: c.h:655

◆ GinPageDeletePostingItem()

void GinPageDeletePostingItem ( Page  page,
OffsetNumber  offset 
)

Definition at line 414 of file gindatapage.c.

References Assert, FirstOffsetNumber, GinDataPageGetPostingItem, GinDataPageSetDataSize, GinPageGetOpaque, GinPageIsLeaf, and memmove.

Referenced by ginDeletePage(), and ginRedoDeletePage().

415 {
416  OffsetNumber maxoff = GinPageGetOpaque(page)->maxoff;
417 
418  Assert(!GinPageIsLeaf(page));
419  Assert(offset >= FirstOffsetNumber && offset <= maxoff);
420 
421  if (offset != maxoff)
422  memmove(GinDataPageGetPostingItem(page, offset),
423  GinDataPageGetPostingItem(page, offset + 1),
424  sizeof(PostingItem) * (maxoff - offset));
425 
426  maxoff--;
427  GinPageGetOpaque(page)->maxoff = maxoff;
428 
429  GinDataPageSetDataSize(page, maxoff * sizeof(PostingItem));
430 }
#define GinPageGetOpaque(page)
Definition: ginblock.h:110
uint16 OffsetNumber
Definition: off.h:24
#define GinDataPageSetDataSize(page, size)
Definition: ginblock.h:313
#define GinDataPageGetPostingItem(page, i)
Definition: ginblock.h:302
#define memmove(d, s, c)
Definition: c.h:1224
#define FirstOffsetNumber
Definition: off.h:27
#define GinPageIsLeaf(page)
Definition: ginblock.h:112
#define Assert(condition)
Definition: c.h:732

◆ ginPostingListDecode()

ItemPointer ginPostingListDecode ( GinPostingList ptr,
int *  ndecoded 
)

Definition at line 269 of file ginpostinglist.c.

References ginPostingListDecodeAllSegments(), and SizeOfGinPostingList.

Referenced by addItemsToLeaf(), dataBeginPlaceToPageLeaf(), gin_leafpage_items(), ginCompressPostingList(), ginReadTuple(), ginRedoRecompress(), ginVacuumEntryPage(), ginVacuumPostingTreeLeaf(), and leafRepackItems().

270 {
271  return ginPostingListDecodeAllSegments(plist,
272  SizeOfGinPostingList(plist),
273  ndecoded);
274 }
#define SizeOfGinPostingList(plist)
Definition: ginblock.h:346
ItemPointer ginPostingListDecodeAllSegments(GinPostingList *segment, int len, int *ndecoded_out)

◆ ginPostingListDecodeAllSegments()

ItemPointer ginPostingListDecodeAllSegments ( GinPostingList ptr,
int  len,
int *  ndecoded 
)

Definition at line 282 of file ginpostinglist.c.

References Assert, GinPostingList::bytes, decode_varbyte(), GinPostingList::first, ginCompareItemPointers(), GinNextPostingListSegment, ItemPointerGetOffsetNumber, itemptr_to_uint64(), GinPostingList::nbytes, OffsetNumberIsValid, palloc(), repalloc(), uint64_to_itemptr(), and val.

Referenced by GinDataLeafPageGetItems(), ginPostingListDecode(), and ginPostingListDecodeAllSegmentsToTbm().

283 {
284  ItemPointer result;
285  int nallocated;
286  uint64 val;
287  char *endseg = ((char *) segment) + len;
288  int ndecoded;
289  unsigned char *ptr;
290  unsigned char *endptr;
291 
292  /*
293  * Guess an initial size of the array.
294  */
295  nallocated = segment->nbytes * 2 + 1;
296  result = palloc(nallocated * sizeof(ItemPointerData));
297 
298  ndecoded = 0;
299  while ((char *) segment < endseg)
300  {
301  /* enlarge output array if needed */
302  if (ndecoded >= nallocated)
303  {
304  nallocated *= 2;
305  result = repalloc(result, nallocated * sizeof(ItemPointerData));
306  }
307 
308  /* copy the first item */
310  Assert(ndecoded == 0 || ginCompareItemPointers(&segment->first, &result[ndecoded - 1]) > 0);
311  result[ndecoded] = segment->first;
312  ndecoded++;
313 
314  val = itemptr_to_uint64(&segment->first);
315  ptr = segment->bytes;
316  endptr = segment->bytes + segment->nbytes;
317  while (ptr < endptr)
318  {
319  /* enlarge output array if needed */
320  if (ndecoded >= nallocated)
321  {
322  nallocated *= 2;
323  result = repalloc(result, nallocated * sizeof(ItemPointerData));
324  }
325 
326  val += decode_varbyte(&ptr);
327 
328  uint64_to_itemptr(val, &result[ndecoded]);
329  ndecoded++;
330  }
331  segment = GinNextPostingListSegment(segment);
332  }
333 
334  if (ndecoded_out)
335  *ndecoded_out = ndecoded;
336  return result;
337 }
static uint64 decode_varbyte(unsigned char **ptr)
#define GinNextPostingListSegment(cur)
Definition: ginblock.h:347
static void uint64_to_itemptr(uint64 val, ItemPointer iptr)
uint16 nbytes
Definition: ginblock.h:342
#define Assert(condition)
Definition: c.h:732
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:117
static uint64 itemptr_to_uint64(const ItemPointer iptr)
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1044
static int ginCompareItemPointers(ItemPointer a, ItemPointer b)
Definition: gin_private.h:461
void * palloc(Size size)
Definition: mcxt.c:924
#define OffsetNumberIsValid(offsetNumber)
Definition: off.h:40
long val
Definition: informix.c:689

◆ ginPostingListDecodeAllSegmentsToTbm()

int ginPostingListDecodeAllSegmentsToTbm ( GinPostingList ptr,
int  totalsize,
TIDBitmap tbm 
)

Definition at line 343 of file ginpostinglist.c.

References ginPostingListDecodeAllSegments(), pfree(), and tbm_add_tuples().

Referenced by GinDataLeafPageGetItemsToTbm().

345 {
346  int ndecoded;
347  ItemPointer items;
348 
349  items = ginPostingListDecodeAllSegments(ptr, len, &ndecoded);
350  tbm_add_tuples(tbm, items, ndecoded, false);
351  pfree(items);
352 
353  return ndecoded;
354 }
void tbm_add_tuples(TIDBitmap *tbm, const ItemPointer tids, int ntids, bool recheck)
Definition: tidbitmap.c:376
void pfree(void *pointer)
Definition: mcxt.c:1031
ItemPointer ginPostingListDecodeAllSegments(GinPostingList *segment, int len, int *ndecoded_out)

◆ ginPrepareEntryScan()

void ginPrepareEntryScan ( GinBtree  btree,
OffsetNumber  attnum,
Datum  key,
GinNullCategory  category,
GinState ginstate 
)

Definition at line 745 of file ginentrypage.c.

References attnum, GinBtreeData::beginPlaceToPage, GinBtreeData::entryAttnum, entryBeginPlaceToPage(), GinBtreeData::entryCategory, entryExecPlaceToPage(), entryFindChildPtr(), entryGetLeftMostPage(), entryIsMoveRight(), GinBtreeData::entryKey, entryLocateEntry(), entryLocateLeafEntry(), entryPrepareDownlink(), GinBtreeData::execPlaceToPage, GinBtreeData::fillRoot, GinBtreeData::findChildPage, GinBtreeData::findChildPtr, GinBtreeData::findItem, GinBtreeData::fullScan, GinBtreeData::getLeftMostChild, GIN_ROOT_BLKNO, ginEntryFillRoot(), GinBtreeData::ginstate, GinState::index, GinBtreeData::index, GinBtreeData::isBuild, GinBtreeData::isData, GinBtreeData::isMoveRight, sort-test::key, GinBtreeData::prepareDownlink, and GinBtreeData::rootBlkno.

Referenced by ginEntryInsert(), and startScanEntry().

748 {
749  memset(btree, 0, sizeof(GinBtreeData));
750 
751  btree->index = ginstate->index;
752  btree->rootBlkno = GIN_ROOT_BLKNO;
753  btree->ginstate = ginstate;
754 
757  btree->isMoveRight = entryIsMoveRight;
762  btree->fillRoot = ginEntryFillRoot;
764 
765  btree->isData = false;
766  btree->fullScan = false;
767  btree->isBuild = false;
768 
769  btree->entryAttnum = attnum;
770  btree->entryKey = key;
771  btree->entryCategory = category;
772 }
static bool entryIsMoveRight(GinBtree btree, Page page)
Definition: ginentrypage.c:244
GinState * ginstate
Definition: gin_private.h:162
void(* fillRoot)(GinBtree, Page, BlockNumber, Page, BlockNumber, Page)
Definition: gin_private.h:156
Relation index
Definition: gin_private.h:53
static BlockNumber entryLocateEntry(GinBtree btree, GinBtreeStack *stack)
Definition: ginentrypage.c:271
static OffsetNumber entryFindChildPtr(GinBtree btree, Page page, BlockNumber blkno, OffsetNumber storedOff)
Definition: ginentrypage.c:406
bool(* isMoveRight)(GinBtree, Page)
Definition: gin_private.h:148
BlockNumber rootBlkno
Definition: gin_private.h:161
bool(* findItem)(GinBtree, GinBtreeStack *)
Definition: gin_private.h:149
OffsetNumber entryAttnum
Definition: gin_private.h:167
GinPlaceToPageRC(* beginPlaceToPage)(GinBtree, Buffer, GinBtreeStack *, void *, BlockNumber, void **, Page *, Page *)
Definition: gin_private.h:153
void(* execPlaceToPage)(GinBtree, Buffer, GinBtreeStack *, void *, BlockNumber, void *)
Definition: gin_private.h:154
Datum entryKey
Definition: gin_private.h:168
BlockNumber(* findChildPage)(GinBtree, GinBtreeStack *)
Definition: gin_private.h:146
void ginEntryFillRoot(GinBtree btree, Page root, BlockNumber lblkno, Page lpage, BlockNumber rblkno, Page rpage)
Definition: ginentrypage.c:721
GinNullCategory entryCategory
Definition: gin_private.h:169
BlockNumber(* getLeftMostChild)(GinBtree, Page)
Definition: gin_private.h:147
static bool entryLocateLeafEntry(GinBtree btree, GinBtreeStack *stack)
Definition: ginentrypage.c:347
static BlockNumber entryGetLeftMostPage(GinBtree btree, Page page)
Definition: ginentrypage.c:447
static GinPlaceToPageRC entryBeginPlaceToPage(GinBtree btree, Buffer buf, GinBtreeStack *stack, void *insertPayload, BlockNumber updateblkno, void **ptp_workspace, Page *newlpage, Page *newrpage)
Definition: ginentrypage.c:528
static void entryExecPlaceToPage(GinBtree btree, Buffer buf, GinBtreeStack *stack, void *insertPayload, BlockNumber updateblkno, void *ptp_workspace)
Definition: ginentrypage.c:555
Relation index
Definition: gin_private.h:160
static void * entryPrepareDownlink(GinBtree btree, Buffer lbuf)
Definition: ginentrypage.c:700
int16 attnum
Definition: pg_attribute.h:79
void *(* prepareDownlink)(GinBtree, Buffer)
Definition: gin_private.h:155
OffsetNumber(* findChildPtr)(GinBtree, Page, BlockNumber, OffsetNumber)
Definition: gin_private.h:152
#define GIN_ROOT_BLKNO
Definition: ginblock.h:52

◆ ginReadTuple()

ItemPointer ginReadTuple ( GinState ginstate,
OffsetNumber  attnum,
IndexTuple  itup,
int *  nitems 
)

Definition at line 163 of file ginentrypage.c.

References elog, ERROR, GinGetNPosting, GinGetPosting, GinItupIsCompressed, ginPostingListDecode(), and palloc().

Referenced by addItemPointersToLeafTuple(), collectMatchBitmap(), and startScanEntry().

165 {
166  Pointer ptr = GinGetPosting(itup);
167  int nipd = GinGetNPosting(itup);
168  ItemPointer ipd;
169  int ndecoded;
170 
171  if (GinItupIsCompressed(itup))
172  {
173  if (nipd > 0)
174  {
175  ipd = ginPostingListDecode((GinPostingList *) ptr, &ndecoded);
176  if (nipd != ndecoded)
177  elog(ERROR, "number of items mismatch in GIN entry tuple, %d in tuple header, %d decoded",
178  nipd, ndecoded);
179  }
180  else
181  {
182  ipd = palloc(0);
183  }
184  }
185  else
186  {
187  ipd = (ItemPointer) palloc(sizeof(ItemPointerData) * nipd);
188  memcpy(ipd, ptr, sizeof(ItemPointerData) * nipd);
189  }
190  *nitems = nipd;
191  return ipd;
192 }
ItemPointer ginPostingListDecode(GinPostingList *plist, int *ndecoded)
#define GinGetNPosting(itup)
Definition: ginblock.h:232
#define GinGetPosting(itup)
Definition: ginblock.h:242
#define GinItupIsCompressed(itup)
Definition: ginblock.h:243
ItemPointerData * ItemPointer
Definition: itemptr.h:49
char * Pointer
Definition: c.h:335
#define ERROR
Definition: elog.h:43
void * palloc(Size size)
Definition: mcxt.c:924
#define elog(elevel,...)
Definition: elog.h:226

◆ ginrescan()

void ginrescan ( IndexScanDesc  scan,
ScanKey  key,
int  nscankeys,
ScanKey  orderbys,
int  norderbys 
)

Definition at line 413 of file ginscan.c.

References ginFreeScanKeys(), IndexScanDescData::keyData, memmove, IndexScanDescData::numberOfKeys, and IndexScanDescData::opaque.

Referenced by ginhandler().

415 {
416  GinScanOpaque so = (GinScanOpaque) scan->opaque;
417 
418  ginFreeScanKeys(so);
419 
420  if (scankey && scan->numberOfKeys > 0)
421  {
422  memmove(scan->keyData, scankey,
423  scan->numberOfKeys * sizeof(ScanKeyData));
424  }
425 }
GinScanOpaqueData * GinScanOpaque
Definition: gin_private.h:364
#define memmove(d, s, c)
Definition: c.h:1224
struct ScanKeyData * keyData
Definition: relscan.h:107
void ginFreeScanKeys(GinScanOpaque so)
Definition: ginscan.c:232

◆ ginScanBeginPostingTree()

GinBtreeStack* ginScanBeginPostingTree ( GinBtree  btree,
Relation  index,
BlockNumber  rootBlkno,
Snapshot  snapshot 
)

Definition at line 1927 of file gindatapage.c.

References GinBtreeData::fullScan, ginFindLeafPage(), and ginPrepareDataScan().

Referenced by scanPostingTree(), and startScanEntry().

1929 {
1930  GinBtreeStack *stack;
1931 
1932  ginPrepareDataScan(btree, index, rootBlkno);
1933 
1934  btree->fullScan = true;
1935 
1936  stack = ginFindLeafPage(btree, true, false, snapshot);
1937 
1938  return stack;
1939 }
GinBtreeStack * ginFindLeafPage(GinBtree btree, bool searchMode, bool rootConflictCheck, Snapshot snapshot)
Definition: ginbtree.c:80
static void ginPrepareDataScan(GinBtree btree, Relation index, BlockNumber rootBlkno)
Definition: gindatapage.c:1873

◆ ginStepRight()

Buffer ginStepRight ( Buffer  buffer,
Relation  index,
int  lockmode 
)

Definition at line 173 of file ginbtree.c.

References BufferGetPage, elog, ERROR, GinPageGetOpaque, GinPageIsData, GinPageIsDeleted, GinPageIsLeaf, LockBuffer(), ReadBuffer(), and UnlockReleaseBuffer().

Referenced by entryLoadMoreItems(), ginFindLeafPage(), ginFindParents(), ginFinishSplit(), moveRightIfItNeeded(), and scanPostingTree().

174 {
175  Buffer nextbuffer;
176  Page page = BufferGetPage(buffer);
177  bool isLeaf = GinPageIsLeaf(page);
178  bool isData = GinPageIsData(page);
179  BlockNumber blkno = GinPageGetOpaque(page)->rightlink;
180 
181  nextbuffer = ReadBuffer(index, blkno);
182  LockBuffer(nextbuffer, lockmode);
183  UnlockReleaseBuffer(buffer);
184 
185  /* Sanity check that the page we stepped to is of similar kind. */
186  page = BufferGetPage(nextbuffer);
187  if (isLeaf != GinPageIsLeaf(page) || isData != GinPageIsData(page))
188  elog(ERROR, "right sibling of GIN page is of different type");
189 
190  /*
191  * Given the proper lock sequence above, we should never land on a deleted
192  * page.
193  */
194  if (GinPageIsDeleted(page))
195  elog(ERROR, "right sibling of GIN page was deleted");
196 
197  return nextbuffer;
198 }
uint32 BlockNumber
Definition: block.h:31
#define GinPageGetOpaque(page)
Definition: ginblock.h:110
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3376
#define ERROR
Definition: elog.h:43
#define GinPageIsLeaf(page)
Definition: ginblock.h:112
#define BufferGetPage(buffer)
Definition: bufmgr.h:159
#define GinPageIsDeleted(page)
Definition: ginblock.h:124
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3590
#define GinPageIsData(page)
Definition: ginblock.h:115
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:596
#define elog(elevel,...)
Definition: elog.h:226
int Buffer
Definition: buf.h:23
Pointer Page
Definition: bufpage.h:78

◆ ginTraverseLock()

int ginTraverseLock ( Buffer  buffer,
bool  searchMode 
)

Definition at line 36 of file ginbtree.c.

References BufferGetPage, GIN_EXCLUSIVE, GIN_SHARE, GIN_UNLOCK, GinPageIsLeaf, and LockBuffer().

Referenced by ginCompareItemPointers(), and ginFindLeafPage().

37 {
38  Page page;
39  int access = GIN_SHARE;
40 
41  LockBuffer(buffer, GIN_SHARE);
42  page = BufferGetPage(buffer);
43  if (GinPageIsLeaf(page))
44  {
45  if (searchMode == false)
46  {
47  /* we should relock our page */
48  LockBuffer(buffer, GIN_UNLOCK);
49  LockBuffer(buffer, GIN_EXCLUSIVE);
50 
51  /* But root can become non-leaf during relock */
52  if (!GinPageIsLeaf(page))
53  {
54  /* restore old lock type (very rare) */
55  LockBuffer(buffer, GIN_UNLOCK);
56  LockBuffer(buffer, GIN_SHARE);
57  }
58  else
59  access = GIN_EXCLUSIVE;
60  }
61  }
62 
63  return access;
64 }
#define GIN_UNLOCK
Definition: gin_private.h:43
#define GinPageIsLeaf(page)
Definition: ginblock.h:112
#define BufferGetPage(buffer)
Definition: bufmgr.h:159
#define GIN_SHARE
Definition: gin_private.h:44
#define GIN_EXCLUSIVE
Definition: gin_private.h:45
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3590
Pointer Page
Definition: bufpage.h:78

◆ gintuple_get_attrnum()

OffsetNumber gintuple_get_attrnum ( GinState ginstate,
IndexTuple  tuple 
)

Definition at line 218 of file ginutil.c.

References Assert, DatumGetUInt16, FirstOffsetNumber, index_getattr, GinState::oneCol, and GinState::tupdesc.

Referenced by addItemPointersToLeafTuple(), collectMatchBitmap(), collectMatchesForHeapRow(), entryIsMoveRight(), entryLocateEntry(), entryLocateLeafEntry(), gintuple_get_key(), ginVacuumEntryPage(), matchPartialInPendingList(), and processPendingPage().

219 {
220  OffsetNumber colN;
221 
222  if (ginstate->oneCol)
223  {
224  /* column number is not stored explicitly */
225  colN = FirstOffsetNumber;
226  }
227  else
228  {
229  Datum res;
230  bool isnull;
231 
232  /*
233  * First attribute is always int16, so we can safely use any tuple
234  * descriptor to obtain first attribute of tuple
235  */
236  res = index_getattr(tuple, FirstOffsetNumber, ginstate->tupdesc[0],
237  &isnull);
238  Assert(!isnull);
239 
240  colN = DatumGetUInt16(res);
241  Assert(colN >= FirstOffsetNumber && colN <= ginstate->origTupdesc->natts);
242  }
243 
244  return colN;
245 }
#define DatumGetUInt16(X)
Definition: postgres.h:458
uint16 OffsetNumber
Definition: off.h:24
#define FirstOffsetNumber
Definition: off.h:27
uintptr_t Datum
Definition: postgres.h:367
TupleDesc tupdesc[INDEX_MAX_KEYS]
Definition: gin_private.h:68
#define Assert(condition)
Definition: c.h:732
#define index_getattr(tup, attnum, tupleDesc, isnull)
Definition: itup.h:100
bool oneCol
Definition: gin_private.h:54

◆ gintuple_get_key()

Datum gintuple_get_key ( GinState ginstate,
IndexTuple  tuple,
GinNullCategory category 
)

Definition at line 251 of file ginutil.c.

References FirstOffsetNumber, GIN_CAT_NORM_KEY, GinGetNullCategory, gintuple_get_attrnum(), index_getattr, OffsetNumberNext, GinState::oneCol, GinState::origTupdesc, and GinState::tupdesc.

Referenced by addItemPointersToLeafTuple(), collectMatchBitmap(), collectMatchesForHeapRow(), entryIsMoveRight(), entryLocateEntry(), entryLocateLeafEntry(), ginVacuumEntryPage(), matchPartialInPendingList(), and processPendingPage().

253 {
254  Datum res;
255  bool isnull;
256 
257  if (ginstate->oneCol)
258  {
259  /*
260  * Single column index doesn't store attribute numbers in tuples
261  */
262  res = index_getattr(tuple, FirstOffsetNumber, ginstate->origTupdesc,
263  &isnull);
264  }
265  else
266  {
267  /*
268  * Since the datum type depends on which index column it's from, we
269  * must be careful to use the right tuple descriptor here.
270  */
271  OffsetNumber colN = gintuple_get_attrnum(ginstate, tuple);
272 
274  ginstate->tupdesc[colN - 1],
275  &isnull);
276  }
277 
278  if (isnull)
279  *category = GinGetNullCategory(tuple, ginstate);
280  else
281  *category = GIN_CAT_NORM_KEY;
282 
283  return res;
284 }
#define GinGetNullCategory(itup, ginstate)
Definition: ginblock.h:224
uint16 OffsetNumber
Definition: off.h:24
OffsetNumber gintuple_get_attrnum(GinState *ginstate, IndexTuple tuple)
Definition: ginutil.c:218
#define GIN_CAT_NORM_KEY
Definition: ginblock.h:212
#define FirstOffsetNumber
Definition: off.h:27
uintptr_t Datum
Definition: postgres.h:367
TupleDesc tupdesc[INDEX_MAX_KEYS]
Definition: gin_private.h:68
#define OffsetNumberNext(offsetNumber)
Definition: off.h:53
#define index_getattr(tup, attnum, tupleDesc, isnull)
Definition: itup.h:100
TupleDesc origTupdesc
Definition: gin_private.h:67
bool oneCol
Definition: gin_private.h:54

◆ ginvacuumcleanup()

IndexBulkDeleteResult* ginvacuumcleanup ( IndexVacuumInfo info,
IndexBulkDeleteResult stats 
)

Definition at line 668 of file ginvacuum.c.

References IndexVacuumInfo::analyze_only, Assert, DataPageDeleteStack::blkno, BufferGetPage, IndexVacuumInfo::estimated_count, IndexBulkDeleteResult::estimated_count, ExclusiveLock, GIN_ROOT_BLKNO, GIN_SHARE, ginInsertCleanup(), GinPageIsData, GinPageIsLeaf, GinPageIsList, GinPageIsRecyclable, GinVacuumState::ginstate, ginUpdateStats(), IndexVacuumInfo::index, IndexFreeSpaceMapVacuum(), initGinState(), IsAutoVacuumWorkerProcess(), LockBuffer(), LockRelationForExtension(), MAIN_FORKNUM, GinStatsData::nDataPages, GinStatsData::nEntries, GinStatsData::nEntryPages, GinStatsData::nTotalPages, IndexVacuumInfo::num_heap_tuples, IndexBulkDeleteResult::num_index_tuples, IndexBulkDeleteResult::num_pages, PageGetMaxOffsetNumber, IndexBulkDeleteResult::pages_free, palloc0(), RBM_NORMAL, ReadBufferExtended(), RecordFreeIndexPage(), RELATION_IS_LOCAL, RelationGetNumberOfBlocks, IndexVacuumInfo::strategy, UnlockRelationForExtension(), UnlockReleaseBuffer(), and vacuum_delay_point().

Referenced by ginhandler().

669 {
670  Relation index = info->index;
671  bool needLock;
672  BlockNumber npages,
673  blkno;
674  BlockNumber totFreePages;
675  GinState ginstate;
676  GinStatsData idxStat;
677 
678  /*
679  * In an autovacuum analyze, we want to clean up pending insertions.
680  * Otherwise, an ANALYZE-only call is a no-op.
681  */
682  if (info->analyze_only)
683  {
685  {
686  initGinState(&ginstate, index);
687  ginInsertCleanup(&ginstate, false, true, true, stats);
688  }
689  return stats;
690  }
691 
692  /*
693  * Set up all-zero stats and cleanup pending inserts if ginbulkdelete
694  * wasn't called
695  */
696  if (stats == NULL)
697  {
699  initGinState(&ginstate, index);
701  false, true, stats);
702  }
703 
704  memset(&idxStat, 0, sizeof(idxStat));
705 
706  /*
707  * XXX we always report the heap tuple count as the number of index
708  * entries. This is bogus if the index is partial, but it's real hard to
709  * tell how many distinct heap entries are referenced by a GIN index.
710  */
711  stats->num_index_tuples = info->num_heap_tuples;
712  stats->estimated_count = info->estimated_count;
713 
714  /*
715  * Need lock unless it's local to this backend.
716  */
717  needLock = !RELATION_IS_LOCAL(index);
718 
719  if (needLock)
721  npages = RelationGetNumberOfBlocks(index);
722  if (needLock)
724 
725  totFreePages = 0;
726 
727  for (blkno = GIN_ROOT_BLKNO; blkno < npages; blkno++)
728  {
729  Buffer buffer;
730  Page page;
731 
733 
734  buffer = ReadBufferExtended(index, MAIN_FORKNUM, blkno,
735  RBM_NORMAL, info->strategy);
736  LockBuffer(buffer, GIN_SHARE);
737  page = (Page) BufferGetPage(buffer);
738 
739  if (GinPageIsRecyclable(page))
740  {
741  Assert(blkno != GIN_ROOT_BLKNO);
742  RecordFreeIndexPage(index, blkno);
743  totFreePages++;
744  }
745  else if (GinPageIsData(page))
746  {
747  idxStat.nDataPages++;
748  }
749  else if (!GinPageIsList(page))
750  {
751  idxStat.nEntryPages++;
752 
753  if (GinPageIsLeaf(page))
754  idxStat.nEntries += PageGetMaxOffsetNumber(page);
755  }
756 
757  UnlockReleaseBuffer(buffer);
758  }
759 
760  /* Update the metapage with accurate page and entry counts */
761  idxStat.nTotalPages = npages;
762  ginUpdateStats(info->index, &idxStat, false);
763 
764  /* Finally, vacuum the FSM */
766 
767  stats->pages_free = totFreePages;
768 
769  if (needLock)
771  stats->num_pages = RelationGetNumberOfBlocks(index);
772  if (needLock)
774 
775  return stats;
776 }
BlockNumber nEntryPages
Definition: gin.h:45
#define GinPageIsRecyclable(page)
Definition: ginblock.h:137
#define ExclusiveLock
Definition: lockdefs.h:44
#define RELATION_IS_LOCAL(relation)
Definition: rel.h:534
bool analyze_only
Definition: genam.h:47
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:642
BufferAccessStrategy strategy
Definition: genam.h:52
Relation index
Definition: genam.h:46
int64 nEntries
Definition: gin.h:47
uint32 BlockNumber
Definition: block.h:31
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:357
Definition: type.h:89
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3376
BlockNumber num_pages
Definition: genam.h:74
BlockNumber pages_free
Definition: genam.h:80
void initGinState(GinState *state, Relation index)
Definition: ginutil.c:89
#define GinPageIsLeaf(page)
Definition: ginblock.h:112
#define BufferGetPage(buffer)
Definition: bufmgr.h:159
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3278
#define GIN_SHARE
Definition: gin_private.h:44
void LockRelationForExtension(Relation relation, LOCKMODE lockmode)
Definition: lmgr.c:402
void * palloc0(Size size)
Definition: mcxt.c:955
void UnlockRelationForExtension(Relation relation, LOCKMODE lockmode)
Definition: lmgr.c:452
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3590
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:198
BlockNumber nDataPages
Definition: gin.h:46
void ginInsertCleanup(GinState *ginstate, bool full_clean, bool fill_fsm, bool forceCleanup, IndexBulkDeleteResult *stats)
Definition: ginfast.c:780
#define GinPageIsData(page)
Definition: ginblock.h:115
double num_heap_tuples
Definition: genam.h:51
#define Assert(condition)
Definition: c.h:732
void IndexFreeSpaceMapVacuum(Relation rel)
Definition: indexfsm.c:71
#define GinPageIsList(page)
Definition: ginblock.h:117
BlockNumber nTotalPages
Definition: gin.h:44
void ginUpdateStats(Relation index, const GinStatsData *stats, bool is_build)
Definition: ginutil.c:665
void vacuum_delay_point(void)
Definition: vacuum.c:1931
void RecordFreeIndexPage(Relation rel, BlockNumber freeBlock)
Definition: indexfsm.c:52
double num_index_tuples
Definition: genam.h:77
int Buffer
Definition: buf.h:23
bool estimated_count
Definition: genam.h:76
#define GIN_ROOT_BLKNO
Definition: ginblock.h:52
Pointer Page
Definition: bufpage.h:78
bool estimated_count
Definition: genam.h:49

◆ ginVacuumItemPointers()

ItemPointer ginVacuumItemPointers ( GinVacuumState gvs,
ItemPointerData items,
int  nitem,
int *  nremaining 
)

Definition at line 48 of file ginvacuum.c.

References GinVacuumState::callback, GinVacuumState::callback_state, i, IndexBulkDeleteResult::num_index_tuples, palloc(), remaining, GinVacuumState::result, and IndexBulkDeleteResult::tuples_removed.

Referenced by ginVacuumEntryPage(), and ginVacuumPostingTreeLeaf().

50 {
51  int i,
52  remaining = 0;
53  ItemPointer tmpitems = NULL;
54 
55  /*
56  * Iterate over TIDs array
57  */
58  for (i = 0; i < nitem; i++)
59  {
60  if (gvs->callback(items + i, gvs->callback_state))
61  {
62  gvs->result->tuples_removed += 1;
63  if (!tmpitems)
64  {
65  /*
66  * First TID to be deleted: allocate memory to hold the
67  * remaining items.
68  */
69  tmpitems = palloc(sizeof(ItemPointerData) * nitem);
70  memcpy(tmpitems, items, sizeof(ItemPointerData) * i);
71  }
72  }
73  else
74  {
75  gvs->result->num_index_tuples += 1;
76  if (tmpitems)
77  tmpitems[remaining] = items[i];
78  remaining++;
79  }
80  }
81 
82  *nremaining = remaining;
83  return tmpitems;
84 }
int remaining
Definition: informix.c:692
double tuples_removed
Definition: genam.h:78
IndexBulkDeleteResult * result
Definition: ginvacuum.c:31
IndexBulkDeleteCallback callback
Definition: ginvacuum.c:32
void * callback_state
Definition: ginvacuum.c:33
void * palloc(Size size)
Definition: mcxt.c:924
int i
double num_index_tuples
Definition: genam.h:77

◆ ginVacuumPostingTreeLeaf()

void ginVacuumPostingTreeLeaf ( Relation  rel,
Buffer  buf,
GinVacuumState gvs 
)

Definition at line 732 of file gindatapage.c.

References leafSegmentInfo::action, BufferGetPage, computeLeafRecompressWALData(), dlist_iter::cur, dataPlaceToPageLeafRecompress(), disassembleLeaf(), dlist_container, dlist_foreach, elog, END_CRIT_SECTION, ERROR, GIN_SEGMENT_DELETE, GIN_SEGMENT_REPLACE, GIN_SEGMENT_UNMODIFIED, ginCompressPostingList(), GinDataPageMaxDataSize, ginPostingListDecode(), ginVacuumItemPointers(), leafSegmentInfo::items, MarkBufferDirty(), leafSegmentInfo::nitems, PageSetLSN, palloc(), pfree(), REGBUF_STANDARD, RelationNeedsWAL, leafSegmentInfo::seg, disassembledLeaf::segments, SizeOfGinPostingList, START_CRIT_SECTION, disassembledLeaf::walinfo, disassembledLeaf::walinfolen, XLOG_GIN_VACUUM_DATA_LEAF_PAGE, XLogBeginInsert(), XLogInsert(), XLogRegisterBufData(), and XLogRegisterBuffer().

Referenced by ginVacuumPostingTreeLeaves().

733 {
734  Page page = BufferGetPage(buffer);
735  disassembledLeaf *leaf;
736  bool removedsomething = false;
737  dlist_iter iter;
738 
739  leaf = disassembleLeaf(page);
740 
741  /* Vacuum each segment. */
742  dlist_foreach(iter, &leaf->segments)
743  {
744  leafSegmentInfo *seginfo = dlist_container(leafSegmentInfo, node, iter.cur);
745  int oldsegsize;
746  ItemPointer cleaned;
747  int ncleaned;
748 
749  if (!seginfo->items)
750  seginfo->items = ginPostingListDecode(seginfo->seg,
751  &seginfo->nitems);
752  if (seginfo->seg)
753  oldsegsize = SizeOfGinPostingList(seginfo->seg);
754  else
755  oldsegsize = GinDataPageMaxDataSize;
756 
757  cleaned = ginVacuumItemPointers(gvs,
758  seginfo->items,
759  seginfo->nitems,
760  &ncleaned);
761  pfree(seginfo->items);
762  seginfo->items = NULL;
763  seginfo->nitems = 0;
764  if (cleaned)
765  {
766  if (ncleaned > 0)
767  {
768  int npacked;
769 
770  seginfo->seg = ginCompressPostingList(cleaned,
771  ncleaned,
772  oldsegsize,
773  &npacked);
774  /* Removing an item never increases the size of the segment */
775  if (npacked != ncleaned)
776  elog(ERROR, "could not fit vacuumed posting list");
777  seginfo->action = GIN_SEGMENT_REPLACE;