PostgreSQL Source Code  git master
brin_internal.h File Reference
#include "access/amapi.h"
#include "storage/bufpage.h"
#include "utils/typcache.h"
Include dependency graph for brin_internal.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  BrinOpcInfo
 
struct  BrinDesc
 

Macros

#define SizeofBrinOpcInfo(ncols)   (offsetof(BrinOpcInfo, oi_typcache) + sizeof(TypeCacheEntry *) * ncols)
 
#define BRIN_PROCNUM_OPCINFO   1
 
#define BRIN_PROCNUM_ADDVALUE   2
 
#define BRIN_PROCNUM_CONSISTENT   3
 
#define BRIN_PROCNUM_UNION   4
 
#define BRIN_MANDATORY_NPROCS   4
 
#define BRIN_PROCNUM_OPTIONS   5 /* optional */
 
#define BRIN_FIRST_OPTIONAL_PROCNUM   11
 
#define BRIN_LAST_OPTIONAL_PROCNUM   15
 
#define BRIN_elog(args)   ((void) 0)
 

Typedefs

typedef struct BrinOpcInfo BrinOpcInfo
 
typedef struct BrinDesc BrinDesc
 

Functions

BrinDescbrin_build_desc (Relation rel)
 
void brin_free_desc (BrinDesc *bdesc)
 
IndexBuildResultbrinbuild (Relation heap, Relation index, struct IndexInfo *indexInfo)
 
void brinbuildempty (Relation index)
 
bool brininsert (Relation idxRel, Datum *values, bool *nulls, ItemPointer heaptid, Relation heapRel, IndexUniqueCheck checkUnique, struct IndexInfo *indexInfo)
 
IndexScanDesc brinbeginscan (Relation r, int nkeys, int norderbys)
 
int64 bringetbitmap (IndexScanDesc scan, TIDBitmap *tbm)
 
void brinrescan (IndexScanDesc scan, ScanKey scankey, int nscankeys, ScanKey orderbys, int norderbys)
 
void brinendscan (IndexScanDesc scan)
 
IndexBulkDeleteResultbrinbulkdelete (IndexVacuumInfo *info, IndexBulkDeleteResult *stats, IndexBulkDeleteCallback callback, void *callback_state)
 
IndexBulkDeleteResultbrinvacuumcleanup (IndexVacuumInfo *info, IndexBulkDeleteResult *stats)
 
byteabrinoptions (Datum reloptions, bool validate)
 
bool brinvalidate (Oid opclassoid)
 

Macro Definition Documentation

◆ BRIN_elog

#define BRIN_elog (   args)    ((void) 0)

◆ BRIN_FIRST_OPTIONAL_PROCNUM

#define BRIN_FIRST_OPTIONAL_PROCNUM   11

Definition at line 74 of file brin_internal.h.

Referenced by brinvalidate().

◆ BRIN_LAST_OPTIONAL_PROCNUM

#define BRIN_LAST_OPTIONAL_PROCNUM   15

Definition at line 75 of file brin_internal.h.

Referenced by brinhandler(), and brinvalidate().

◆ BRIN_MANDATORY_NPROCS

#define BRIN_MANDATORY_NPROCS   4

Definition at line 71 of file brin_internal.h.

Referenced by brinvalidate().

◆ BRIN_PROCNUM_ADDVALUE

#define BRIN_PROCNUM_ADDVALUE   2

Definition at line 68 of file brin_internal.h.

Referenced by brinbuildCallback(), brininsert(), and brinvalidate().

◆ BRIN_PROCNUM_CONSISTENT

#define BRIN_PROCNUM_CONSISTENT   3

Definition at line 69 of file brin_internal.h.

Referenced by bringetbitmap(), and brinvalidate().

◆ BRIN_PROCNUM_OPCINFO

#define BRIN_PROCNUM_OPCINFO   1

Definition at line 67 of file brin_internal.h.

Referenced by brin_build_desc(), and brinvalidate().

◆ BRIN_PROCNUM_OPTIONS

#define BRIN_PROCNUM_OPTIONS   5 /* optional */

Definition at line 72 of file brin_internal.h.

Referenced by brinhandler(), and brinvalidate().

◆ BRIN_PROCNUM_UNION

#define BRIN_PROCNUM_UNION   4

Definition at line 70 of file brin_internal.h.

Referenced by brinvalidate(), and union_tuples().

◆ SizeofBrinOpcInfo

#define SizeofBrinOpcInfo (   ncols)    (offsetof(BrinOpcInfo, oi_typcache) + sizeof(TypeCacheEntry *) * ncols)

Definition at line 38 of file brin_internal.h.

Referenced by brin_inclusion_opcinfo(), and brin_minmax_opcinfo().

Typedef Documentation

◆ BrinDesc

typedef struct BrinDesc BrinDesc

◆ BrinOpcInfo

typedef struct BrinOpcInfo BrinOpcInfo

Function Documentation

◆ brin_build_desc()

BrinDesc* brin_build_desc ( Relation  rel)

Definition at line 1018 of file brin.c.

References ALLOCSET_SMALL_SIZES, AllocSetContextCreate, BrinDesc::bd_context, BrinDesc::bd_disktdesc, BrinDesc::bd_index, BrinDesc::bd_info, BrinDesc::bd_totalstored, BrinDesc::bd_tupdesc, BRIN_PROCNUM_OPCINFO, CurrentMemoryContext, DatumGetPointer, FunctionCall1, index_getprocinfo(), MemoryContextSwitchTo(), TupleDescData::natts, offsetof, BrinOpcInfo::oi_nstored, palloc(), pfree(), RelationGetDescr, and TupleDescAttr.

Referenced by brin_page_items(), brinbeginscan(), brininsert(), and initialize_brin_buildstate().

1019 {
1020  BrinOpcInfo **opcinfo;
1021  BrinDesc *bdesc;
1022  TupleDesc tupdesc;
1023  int totalstored = 0;
1024  int keyno;
1025  long totalsize;
1026  MemoryContext cxt;
1027  MemoryContext oldcxt;
1028 
1030  "brin desc cxt",
1032  oldcxt = MemoryContextSwitchTo(cxt);
1033  tupdesc = RelationGetDescr(rel);
1034 
1035  /*
1036  * Obtain BrinOpcInfo for each indexed column. While at it, accumulate
1037  * the number of columns stored, since the number is opclass-defined.
1038  */
1039  opcinfo = (BrinOpcInfo **) palloc(sizeof(BrinOpcInfo *) * tupdesc->natts);
1040  for (keyno = 0; keyno < tupdesc->natts; keyno++)
1041  {
1042  FmgrInfo *opcInfoFn;
1043  Form_pg_attribute attr = TupleDescAttr(tupdesc, keyno);
1044 
1045  opcInfoFn = index_getprocinfo(rel, keyno + 1, BRIN_PROCNUM_OPCINFO);
1046 
1047  opcinfo[keyno] = (BrinOpcInfo *)
1048  DatumGetPointer(FunctionCall1(opcInfoFn, attr->atttypid));
1049  totalstored += opcinfo[keyno]->oi_nstored;
1050  }
1051 
1052  /* Allocate our result struct and fill it in */
1053  totalsize = offsetof(BrinDesc, bd_info) +
1054  sizeof(BrinOpcInfo *) * tupdesc->natts;
1055 
1056  bdesc = palloc(totalsize);
1057  bdesc->bd_context = cxt;
1058  bdesc->bd_index = rel;
1059  bdesc->bd_tupdesc = tupdesc;
1060  bdesc->bd_disktdesc = NULL; /* generated lazily */
1061  bdesc->bd_totalstored = totalstored;
1062 
1063  for (keyno = 0; keyno < tupdesc->natts; keyno++)
1064  bdesc->bd_info[keyno] = opcinfo[keyno];
1065  pfree(opcinfo);
1066 
1067  MemoryContextSwitchTo(oldcxt);
1068 
1069  return bdesc;
1070 }
Definition: fmgr.h:56
#define AllocSetContextCreate
Definition: memutils.h:170
FmgrInfo * index_getprocinfo(Relation irel, AttrNumber attnum, uint16 procnum)
Definition: indexam.c:800
#define RelationGetDescr(relation)
Definition: rel.h:482
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:202
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define BRIN_PROCNUM_OPCINFO
Definition: brin_internal.h:67
void pfree(void *pointer)
Definition: mcxt.c:1056
Relation bd_index
Definition: brin_internal.h:47
uint16 oi_nstored
Definition: brin_internal.h:28
int bd_totalstored
Definition: brin_internal.h:56
TupleDesc bd_tupdesc
Definition: brin_internal.h:50
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
BrinOpcInfo * bd_info[FLEXIBLE_ARRAY_MEMBER]
Definition: brin_internal.h:59
#define DatumGetPointer(X)
Definition: postgres.h:549
MemoryContext bd_context
Definition: brin_internal.h:44
void * palloc(Size size)
Definition: mcxt.c:949
TupleDesc bd_disktdesc
Definition: brin_internal.h:53
#define FunctionCall1(flinfo, arg1)
Definition: fmgr.h:642
#define offsetof(type, field)
Definition: c.h:661

◆ brin_free_desc()

void brin_free_desc ( BrinDesc bdesc)

Definition at line 1073 of file brin.c.

References Assert, BrinDesc::bd_context, BrinDesc::bd_tupdesc, MemoryContextDelete(), and TupleDescData::tdrefcount.

Referenced by brin_page_items(), brinendscan(), and terminate_brin_buildstate().

1074 {
1075  /* make sure the tupdesc is still valid */
1076  Assert(bdesc->bd_tupdesc->tdrefcount >= 1);
1077  /* no need for retail pfree */
1079 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
TupleDesc bd_tupdesc
Definition: brin_internal.h:50
#define Assert(condition)
Definition: c.h:738
MemoryContext bd_context
Definition: brin_internal.h:44
int tdrefcount
Definition: tupdesc.h:84

◆ brinbeginscan()

IndexScanDesc brinbeginscan ( Relation  r,
int  nkeys,
int  norderbys 
)

Definition at line 345 of file brin.c.

References BrinOpaque::bo_bdesc, BrinOpaque::bo_pagesPerRange, BrinOpaque::bo_rmAccess, brin_build_desc(), brinRevmapInitialize(), IndexScanDescData::opaque, palloc(), RelationGetIndexScan(), and IndexScanDescData::xs_snapshot.

Referenced by brinhandler().

346 {
347  IndexScanDesc scan;
348  BrinOpaque *opaque;
349 
350  scan = RelationGetIndexScan(r, nkeys, norderbys);
351 
352  opaque = (BrinOpaque *) palloc(sizeof(BrinOpaque));
353  opaque->bo_rmAccess = brinRevmapInitialize(r, &opaque->bo_pagesPerRange,
354  scan->xs_snapshot);
355  opaque->bo_bdesc = brin_build_desc(r);
356  scan->opaque = opaque;
357 
358  return scan;
359 }
struct SnapshotData * xs_snapshot
Definition: relscan.h:104
BlockNumber bo_pagesPerRange
Definition: brin.c:64
BrinRevmap * bo_rmAccess
Definition: brin.c:65
BrinDesc * bo_bdesc
Definition: brin.c:66
BrinDesc * brin_build_desc(Relation rel)
Definition: brin.c:1018
BrinRevmap * brinRevmapInitialize(Relation idxrel, BlockNumber *pagesPerRange, Snapshot snapshot)
Definition: brin_revmap.c:71
void * palloc(Size size)
Definition: mcxt.c:949
IndexScanDesc RelationGetIndexScan(Relation indexRelation, int nkeys, int norderbys)
Definition: genam.c:80

◆ brinbuild()

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

Definition at line 668 of file brin.c.

References Assert, BRIN_CURRENT_VERSION, BRIN_METAPAGE_BLKNO, brin_metapage_init(), brinbuildCallback(), BrinGetPagesPerRange, brinRevmapInitialize(), brinRevmapTerminate(), BUFFER_LOCK_EXCLUSIVE, BufferGetBlockNumber(), BufferGetPage, elog, ERROR, form_and_insert_tuple(), IndexBuildResult::heap_tuples, IndexBuildResult::index_tuples, initialize_brin_buildstate(), LockBuffer(), MarkBufferDirty(), P_NEW, PageSetLSN, xl_brin_createidx::pagesPerRange, palloc(), ReadBuffer(), REGBUF_STANDARD, REGBUF_WILL_INIT, RelationGetNumberOfBlocks, RelationGetRelationName, RelationNeedsWAL, SizeOfBrinCreateIdx, table_index_build_scan(), terminate_brin_buildstate(), UnlockReleaseBuffer(), xl_brin_createidx::version, XLOG_BRIN_CREATE_INDEX, XLogBeginInsert(), XLogInsert(), XLogRegisterBuffer(), and XLogRegisterData().

Referenced by brinhandler().

669 {
670  IndexBuildResult *result;
671  double reltuples;
672  double idxtuples;
673  BrinRevmap *revmap;
675  Buffer meta;
676  BlockNumber pagesPerRange;
677 
678  /*
679  * We expect to be called exactly once for any index relation.
680  */
681  if (RelationGetNumberOfBlocks(index) != 0)
682  elog(ERROR, "index \"%s\" already contains data",
683  RelationGetRelationName(index));
684 
685  /*
686  * Critical section not required, because on error the creation of the
687  * whole relation will be rolled back.
688  */
689 
690  meta = ReadBuffer(index, P_NEW);
693 
696  MarkBufferDirty(meta);
697 
698  if (RelationNeedsWAL(index))
699  {
700  xl_brin_createidx xlrec;
701  XLogRecPtr recptr;
702  Page page;
703 
705  xlrec.pagesPerRange = BrinGetPagesPerRange(index);
706 
707  XLogBeginInsert();
708  XLogRegisterData((char *) &xlrec, SizeOfBrinCreateIdx);
710 
711  recptr = XLogInsert(RM_BRIN_ID, XLOG_BRIN_CREATE_INDEX);
712 
713  page = BufferGetPage(meta);
714  PageSetLSN(page, recptr);
715  }
716 
717  UnlockReleaseBuffer(meta);
718 
719  /*
720  * Initialize our state, including the deformed tuple state.
721  */
722  revmap = brinRevmapInitialize(index, &pagesPerRange, NULL);
723  state = initialize_brin_buildstate(index, revmap, pagesPerRange);
724 
725  /*
726  * Now scan the relation. No syncscan allowed here because we want the
727  * heap blocks in physical order.
728  */
729  reltuples = table_index_build_scan(heap, index, indexInfo, false, true,
730  brinbuildCallback, (void *) state, NULL);
731 
732  /* process the final batch */
733  form_and_insert_tuple(state);
734 
735  /* release resources */
736  idxtuples = state->bs_numtuples;
739 
740  /*
741  * Return statistics
742  */
743  result = (IndexBuildResult *) palloc(sizeof(IndexBuildResult));
744 
745  result->heap_tuples = reltuples;
746  result->index_tuples = idxtuples;
747 
748  return result;
749 }
#define BRIN_CURRENT_VERSION
Definition: brin_page.h:72
#define BRIN_METAPAGE_BLKNO
Definition: brin_page.h:75
#define SizeOfBrinCreateIdx
Definition: brin_xlog.h:55
void brinRevmapTerminate(BrinRevmap *revmap)
Definition: brin_revmap.c:103
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1468
void XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Definition: xloginsert.c:214
#define XLOG_BRIN_CREATE_INDEX
Definition: brin_xlog.h:31
#define REGBUF_WILL_INIT
Definition: xloginsert.h:33
uint32 BlockNumber
Definition: block.h:31
static void form_and_insert_tuple(BrinBuildState *state)
Definition: brin.c:1400
#define P_NEW
Definition: bufmgr.h:91
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:98
#define BrinGetPagesPerRange(relation)
Definition: brin.h:39
void brin_metapage_init(Page page, BlockNumber pagesPerRange, uint16 version)
Definition: brin_pageops.c:487
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3506
#define ERROR
Definition: elog.h:43
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:1524
#define REGBUF_STANDARD
Definition: xloginsert.h:35
BrinRevmap * bs_rmAccess
Definition: brin.c:54
#define RelationGetRelationName(relation)
Definition: rel.h:490
static void brinbuildCallback(Relation index, ItemPointer tid, Datum *values, bool *isnull, bool tupleIsAlive, void *brstate)
Definition: brin.c:605
#define BufferGetPage(buffer)
Definition: bufmgr.h:169
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:324
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:416
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3722
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:211
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:738
Definition: regguts.h:298
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:606
BrinRevmap * brinRevmapInitialize(Relation idxrel, BlockNumber *pagesPerRange, Snapshot snapshot)
Definition: brin_revmap.c:71
#define RelationNeedsWAL(relation)
Definition: rel.h:562
int bs_numtuples
Definition: brin.c:50
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition: bufmgr.c:2633
void * palloc(Size size)
Definition: mcxt.c:949
#define elog(elevel,...)
Definition: elog.h:214
BlockNumber pagesPerRange
Definition: brin_xlog.h:52
static BrinBuildState * initialize_brin_buildstate(Relation idxRel, BrinRevmap *revmap, BlockNumber pagesPerRange)
Definition: brin.c:1106
void XLogBeginInsert(void)
Definition: xloginsert.c:121
#define PageSetLSN(page, lsn)
Definition: bufpage.h:368
int Buffer
Definition: buf.h:23
Pointer Page
Definition: bufpage.h:78
double index_tuples
Definition: genam.h:33
double heap_tuples
Definition: genam.h:32
static void terminate_brin_buildstate(BrinBuildState *state)
Definition: brin.c:1131

◆ brinbuildempty()

void brinbuildempty ( Relation  index)

Definition at line 752 of file brin.c.

References BRIN_CURRENT_VERSION, brin_metapage_init(), BrinGetPagesPerRange, BUFFER_LOCK_EXCLUSIVE, BufferGetPage, END_CRIT_SECTION, INIT_FORKNUM, LockBuffer(), log_newpage_buffer(), MarkBufferDirty(), P_NEW, RBM_NORMAL, ReadBufferExtended(), START_CRIT_SECTION, and UnlockReleaseBuffer().

Referenced by brinhandler().

753 {
754  Buffer metabuf;
755 
756  /* An empty BRIN index has a metapage only. */
757  metabuf =
760 
761  /* Initialize and xlog metabuffer. */
765  MarkBufferDirty(metabuf);
766  log_newpage_buffer(metabuf, true);
768 
769  UnlockReleaseBuffer(metabuf);
770 }
#define BRIN_CURRENT_VERSION
Definition: brin_page.h:72
XLogRecPtr log_newpage_buffer(Buffer buffer, bool page_std)
Definition: xloginsert.c:1014
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1468
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:652
#define END_CRIT_SECTION()
Definition: miscadmin.h:134
#define START_CRIT_SECTION()
Definition: miscadmin.h:132
#define P_NEW
Definition: bufmgr.h:91
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:98
#define BrinGetPagesPerRange(relation)
Definition: brin.h:39
void brin_metapage_init(Page page, BlockNumber pagesPerRange, uint16 version)
Definition: brin_pageops.c:487
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3506
#define BufferGetPage(buffer)
Definition: bufmgr.h:169
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3722
int Buffer
Definition: buf.h:23

◆ brinbulkdelete()

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

Definition at line 782 of file brin.c.

References palloc0().

Referenced by brinhandler().

784 {
785  /* allocate stats if first time through, else re-use existing struct */
786  if (stats == NULL)
788 
789  return stats;
790 }
void * palloc0(Size size)
Definition: mcxt.c:980

◆ brinendscan()

void brinendscan ( IndexScanDesc  scan)

Definition at line 588 of file brin.c.

References BrinOpaque::bo_bdesc, BrinOpaque::bo_rmAccess, brin_free_desc(), brinRevmapTerminate(), IndexScanDescData::opaque, and pfree().

Referenced by brinhandler().

589 {
590  BrinOpaque *opaque = (BrinOpaque *) scan->opaque;
591 
593  brin_free_desc(opaque->bo_bdesc);
594  pfree(opaque);
595 }
void brin_free_desc(BrinDesc *bdesc)
Definition: brin.c:1073
void brinRevmapTerminate(BrinRevmap *revmap)
Definition: brin_revmap.c:103
void pfree(void *pointer)
Definition: mcxt.c:1056
BrinRevmap * bo_rmAccess
Definition: brin.c:65
BrinDesc * bo_bdesc
Definition: brin.c:66

◆ bringetbitmap()

int64 bringetbitmap ( IndexScanDesc  scan,
TIDBitmap tbm 
)

Definition at line 374 of file brin.c.

References AccessShareLock, addrange(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, BrinDesc::bd_tupdesc, BrinOpaque::bo_bdesc, BrinOpaque::bo_pagesPerRange, BrinOpaque::bo_rmAccess, brin_copy_tuple(), brin_deform_tuple(), brin_new_memtuple(), BRIN_PROCNUM_CONSISTENT, brinGetTupleForHeapBlock(), BrinMemTuple::bt_columns, BrinMemTuple::bt_placeholder, buf, BUFFER_LOCK_SHARE, BUFFER_LOCK_UNLOCK, CHECK_FOR_INTERRUPTS, CurrentMemoryContext, DatumGetBool, fmgr_info_copy(), FunctionCall3Coll(), index_getprocinfo(), IndexGetRelation(), IndexScanDescData::indexRelation, InvalidBuffer, InvalidOid, sort-test::key, IndexScanDescData::keyData, LockBuffer(), MemoryContextDelete(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), TupleDescData::natts, IndexScanDescData::numberOfKeys, IndexScanDescData::opaque, palloc0(), pgstat_count_index_scan, PointerGetDatum, RelationGetNumberOfBlocks, RelationGetRelid, ReleaseBuffer(), ScanKeyData::sk_attno, ScanKeyData::sk_collation, ScanKeyData::sk_flags, SK_ISNULL, table_close(), table_open(), tbm_add_page(), TupleDescAttr, and IndexScanDescData::xs_snapshot.

Referenced by brinhandler().

375 {
376  Relation idxRel = scan->indexRelation;
378  BrinDesc *bdesc;
379  Oid heapOid;
380  Relation heapRel;
381  BrinOpaque *opaque;
382  BlockNumber nblocks;
383  BlockNumber heapBlk;
384  int totalpages = 0;
385  FmgrInfo *consistentFn;
386  MemoryContext oldcxt;
387  MemoryContext perRangeCxt;
388  BrinMemTuple *dtup;
389  BrinTuple *btup = NULL;
390  Size btupsz = 0;
391 
392  opaque = (BrinOpaque *) scan->opaque;
393  bdesc = opaque->bo_bdesc;
394  pgstat_count_index_scan(idxRel);
395 
396  /*
397  * We need to know the size of the table so that we know how long to
398  * iterate on the revmap.
399  */
400  heapOid = IndexGetRelation(RelationGetRelid(idxRel), false);
401  heapRel = table_open(heapOid, AccessShareLock);
402  nblocks = RelationGetNumberOfBlocks(heapRel);
403  table_close(heapRel, AccessShareLock);
404 
405  /*
406  * Make room for the consistent support procedures of indexed columns. We
407  * don't look them up here; we do that lazily the first time we see a scan
408  * key reference each of them. We rely on zeroing fn_oid to InvalidOid.
409  */
410  consistentFn = palloc0(sizeof(FmgrInfo) * bdesc->bd_tupdesc->natts);
411 
412  /* allocate an initial in-memory tuple, out of the per-range memcxt */
413  dtup = brin_new_memtuple(bdesc);
414 
415  /*
416  * Setup and use a per-range memory context, which is reset every time we
417  * loop below. This avoids having to free the tuples within the loop.
418  */
420  "bringetbitmap cxt",
422  oldcxt = MemoryContextSwitchTo(perRangeCxt);
423 
424  /*
425  * Now scan the revmap. We start by querying for heap page 0,
426  * incrementing by the number of pages per range; this gives us a full
427  * view of the table.
428  */
429  for (heapBlk = 0; heapBlk < nblocks; heapBlk += opaque->bo_pagesPerRange)
430  {
431  bool addrange;
432  bool gottuple = false;
433  BrinTuple *tup;
434  OffsetNumber off;
435  Size size;
436 
438 
440 
441  tup = brinGetTupleForHeapBlock(opaque->bo_rmAccess, heapBlk, &buf,
442  &off, &size, BUFFER_LOCK_SHARE,
443  scan->xs_snapshot);
444  if (tup)
445  {
446  gottuple = true;
447  btup = brin_copy_tuple(tup, size, btup, &btupsz);
449  }
450 
451  /*
452  * For page ranges with no indexed tuple, we must return the whole
453  * range; otherwise, compare it to the scan keys.
454  */
455  if (!gottuple)
456  {
457  addrange = true;
458  }
459  else
460  {
461  dtup = brin_deform_tuple(bdesc, btup, dtup);
462  if (dtup->bt_placeholder)
463  {
464  /*
465  * Placeholder tuples are always returned, regardless of the
466  * values stored in them.
467  */
468  addrange = true;
469  }
470  else
471  {
472  int keyno;
473 
474  /*
475  * Compare scan keys with summary values stored for the range.
476  * If scan keys are matched, the page range must be added to
477  * the bitmap. We initially assume the range needs to be
478  * added; in particular this serves the case where there are
479  * no keys.
480  */
481  addrange = true;
482  for (keyno = 0; keyno < scan->numberOfKeys; keyno++)
483  {
484  ScanKey key = &scan->keyData[keyno];
485  AttrNumber keyattno = key->sk_attno;
486  BrinValues *bval = &dtup->bt_columns[keyattno - 1];
487  Datum add;
488 
489  /*
490  * The collation of the scan key must match the collation
491  * used in the index column (but only if the search is not
492  * IS NULL/ IS NOT NULL). Otherwise we shouldn't be using
493  * this index ...
494  */
495  Assert((key->sk_flags & SK_ISNULL) ||
496  (key->sk_collation ==
497  TupleDescAttr(bdesc->bd_tupdesc,
498  keyattno - 1)->attcollation));
499 
500  /* First time this column? look up consistent function */
501  if (consistentFn[keyattno - 1].fn_oid == InvalidOid)
502  {
503  FmgrInfo *tmp;
504 
505  tmp = index_getprocinfo(idxRel, keyattno,
507  fmgr_info_copy(&consistentFn[keyattno - 1], tmp,
509  }
510 
511  /*
512  * Check whether the scan key is consistent with the page
513  * range values; if so, have the pages in the range added
514  * to the output bitmap.
515  *
516  * When there are multiple scan keys, failure to meet the
517  * criteria for a single one of them is enough to discard
518  * the range as a whole, so break out of the loop as soon
519  * as a false return value is obtained.
520  */
521  add = FunctionCall3Coll(&consistentFn[keyattno - 1],
522  key->sk_collation,
523  PointerGetDatum(bdesc),
524  PointerGetDatum(bval),
525  PointerGetDatum(key));
526  addrange = DatumGetBool(add);
527  if (!addrange)
528  break;
529  }
530  }
531  }
532 
533  /* add the pages in the range to the output bitmap, if needed */
534  if (addrange)
535  {
536  BlockNumber pageno;
537 
538  for (pageno = heapBlk;
539  pageno <= heapBlk + opaque->bo_pagesPerRange - 1;
540  pageno++)
541  {
542  MemoryContextSwitchTo(oldcxt);
543  tbm_add_page(tbm, pageno);
544  totalpages++;
545  MemoryContextSwitchTo(perRangeCxt);
546  }
547  }
548  }
549 
550  MemoryContextSwitchTo(oldcxt);
551  MemoryContextDelete(perRangeCxt);
552 
553  if (buf != InvalidBuffer)
554  ReleaseBuffer(buf);
555 
556  /*
557  * XXX We have an approximation of the number of *pages* that our scan
558  * returns, but we don't have a precise idea of the number of heap tuples
559  * involved.
560  */
561  return totalpages * 10;
562 }
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:96
Definition: fmgr.h:56
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3412
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:170
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
FmgrInfo * index_getprocinfo(Relation irel, AttrNumber attnum, uint16 procnum)
Definition: indexam.c:800
BrinTuple * brin_copy_tuple(BrinTuple *tuple, Size len, BrinTuple *dest, Size *destsz)
Definition: brin_tuple.c:320
BrinTuple * brinGetTupleForHeapBlock(BrinRevmap *revmap, BlockNumber heapBlk, Buffer *buf, OffsetNumber *off, Size *size, int mode, Snapshot snapshot)
Definition: brin_revmap.c:197
#define PointerGetDatum(X)
Definition: postgres.h:556
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
static void addrange(struct cvec *cv, chr from, chr to)
Definition: regc_cvec.c:90
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define AccessShareLock
Definition: lockdefs.h:36
#define InvalidBuffer
Definition: buf.h:25
struct SnapshotData * xs_snapshot
Definition: relscan.h:104
uint32 BlockNumber
Definition: block.h:31
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3483
unsigned int Oid
Definition: postgres_ext.h:31
BrinMemTuple * brin_new_memtuple(BrinDesc *brdesc)
Definition: brin_tuple.c:356
BlockNumber bo_pagesPerRange
Definition: brin.c:64
Relation indexRelation
Definition: relscan.h:103
uint16 OffsetNumber
Definition: off.h:24
BrinMemTuple * brin_deform_tuple(BrinDesc *brdesc, BrinTuple *tuple, BrinMemTuple *dMemtuple)
Definition: brin_tuple.c:421
bool bt_placeholder
Definition: brin_tuple.h:38
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
void fmgr_info_copy(FmgrInfo *dstinfo, FmgrInfo *srcinfo, MemoryContext destcxt)
Definition: fmgr.c:612
BrinValues bt_columns[FLEXIBLE_ARRAY_MEMBER]
Definition: brin_tuple.h:46
static char * buf
Definition: pg_test_fsync.c:67
BrinRevmap * bo_rmAccess
Definition: brin.c:65
#define DatumGetBool(X)
Definition: postgres.h:393
#define pgstat_count_index_scan(rel)
Definition: pgstat.h:1411
TupleDesc bd_tupdesc
Definition: brin_internal.h:50
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
#define SK_ISNULL
Definition: skey.h:115
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
BrinDesc * bo_bdesc
Definition: brin.c:66
void * palloc0(Size size)
Definition: mcxt.c:980
uintptr_t Datum
Definition: postgres.h:367
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3722
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:211
#define InvalidOid
Definition: postgres_ext.h:36
Datum FunctionCall3Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2, Datum arg3)
Definition: fmgr.c:1174
int sk_flags
Definition: skey.h:66
#define Assert(condition)
Definition: c.h:738
#define BRIN_PROCNUM_CONSISTENT
Definition: brin_internal.h:69
size_t Size
Definition: c.h:466
struct ScanKeyData * keyData
Definition: relscan.h:107
void tbm_add_page(TIDBitmap *tbm, BlockNumber pageno)
Definition: tidbitmap.c:442
Oid sk_collation
Definition: skey.h:70
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:97
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
int Buffer
Definition: buf.h:23
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:456
AttrNumber sk_attno
Definition: skey.h:67

◆ brininsert()

bool brininsert ( Relation  idxRel,
Datum values,
bool nulls,
ItemPointer  heaptid,
Relation  heapRel,
IndexUniqueCheck  checkUnique,
struct IndexInfo indexInfo 
)

Definition at line 150 of file brin.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, AutoVacuumRequestWork(), AVW_BRINSummarizeRange, BrinDesc::bd_tupdesc, brin_build_desc(), brin_can_do_samepage_update(), brin_copy_tuple(), brin_deform_tuple(), brin_doupdate(), brin_form_tuple(), BRIN_PROCNUM_ADDVALUE, BrinGetAutoSummarize, brinGetTupleForHeapBlock(), brinRevmapInitialize(), brinRevmapTerminate(), BrinMemTuple::bt_columns, buf, BUFFER_LOCK_SHARE, BUFFER_LOCK_UNLOCK, BufferGetPage, BufferIsValid, CHECK_FOR_INTERRUPTS, CurrentMemoryContext, DatumGetBool, ereport, errcode(), errmsg(), FirstOffsetNumber, FunctionCall4Coll(), IndexInfo::ii_AmCache, IndexInfo::ii_Context, index_getprocinfo(), InvalidBuffer, ItemIdGetLength, ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, LockBuffer(), LOG, MemoryContextDelete(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), TupleDescData::natts, PageGetItemId, PointerGetDatum, RelationData::rd_indcollation, RelationGetRelationName, RelationGetRelid, and ReleaseBuffer().

Referenced by brinhandler().

154 {
155  BlockNumber pagesPerRange;
156  BlockNumber origHeapBlk;
157  BlockNumber heapBlk;
158  BrinDesc *bdesc = (BrinDesc *) indexInfo->ii_AmCache;
159  BrinRevmap *revmap;
161  MemoryContext tupcxt = NULL;
163  bool autosummarize = BrinGetAutoSummarize(idxRel);
164 
165  revmap = brinRevmapInitialize(idxRel, &pagesPerRange, NULL);
166 
167  /*
168  * origHeapBlk is the block number where the insertion occurred. heapBlk
169  * is the first block in the corresponding page range.
170  */
171  origHeapBlk = ItemPointerGetBlockNumber(heaptid);
172  heapBlk = (origHeapBlk / pagesPerRange) * pagesPerRange;
173 
174  for (;;)
175  {
176  bool need_insert = false;
177  OffsetNumber off;
178  BrinTuple *brtup;
179  BrinMemTuple *dtup;
180  int keyno;
181 
183 
184  /*
185  * If auto-summarization is enabled and we just inserted the first
186  * tuple into the first block of a new non-first page range, request a
187  * summarization run of the previous range.
188  */
189  if (autosummarize &&
190  heapBlk > 0 &&
191  heapBlk == origHeapBlk &&
193  {
194  BlockNumber lastPageRange = heapBlk - 1;
195  BrinTuple *lastPageTuple;
196 
197  lastPageTuple =
198  brinGetTupleForHeapBlock(revmap, lastPageRange, &buf, &off,
199  NULL, BUFFER_LOCK_SHARE, NULL);
200  if (!lastPageTuple)
201  {
202  bool recorded;
203 
205  RelationGetRelid(idxRel),
206  lastPageRange);
207  if (!recorded)
208  ereport(LOG,
209  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
210  errmsg("request for BRIN range summarization for index \"%s\" page %u was not recorded",
211  RelationGetRelationName(idxRel),
212  lastPageRange)));
213  }
214  else
216  }
217 
218  brtup = brinGetTupleForHeapBlock(revmap, heapBlk, &buf, &off,
219  NULL, BUFFER_LOCK_SHARE, NULL);
220 
221  /* if range is unsummarized, there's nothing to do */
222  if (!brtup)
223  break;
224 
225  /* First time through in this statement? */
226  if (bdesc == NULL)
227  {
228  MemoryContextSwitchTo(indexInfo->ii_Context);
229  bdesc = brin_build_desc(idxRel);
230  indexInfo->ii_AmCache = (void *) bdesc;
231  MemoryContextSwitchTo(oldcxt);
232  }
233  /* First time through in this brininsert call? */
234  if (tupcxt == NULL)
235  {
237  "brininsert cxt",
239  MemoryContextSwitchTo(tupcxt);
240  }
241 
242  dtup = brin_deform_tuple(bdesc, brtup, NULL);
243 
244  /*
245  * Compare the key values of the new tuple to the stored index values;
246  * our deformed tuple will get updated if the new tuple doesn't fit
247  * the original range (note this means we can't break out of the loop
248  * early). Make a note of whether this happens, so that we know to
249  * insert the modified tuple later.
250  */
251  for (keyno = 0; keyno < bdesc->bd_tupdesc->natts; keyno++)
252  {
253  Datum result;
254  BrinValues *bval;
255  FmgrInfo *addValue;
256 
257  bval = &dtup->bt_columns[keyno];
258  addValue = index_getprocinfo(idxRel, keyno + 1,
260  result = FunctionCall4Coll(addValue,
261  idxRel->rd_indcollation[keyno],
262  PointerGetDatum(bdesc),
263  PointerGetDatum(bval),
264  values[keyno],
265  nulls[keyno]);
266  /* if that returned true, we need to insert the updated tuple */
267  need_insert |= DatumGetBool(result);
268  }
269 
270  if (!need_insert)
271  {
272  /*
273  * The tuple is consistent with the new values, so there's nothing
274  * to do.
275  */
277  }
278  else
279  {
280  Page page = BufferGetPage(buf);
281  ItemId lp = PageGetItemId(page, off);
282  Size origsz;
283  BrinTuple *origtup;
284  Size newsz;
285  BrinTuple *newtup;
286  bool samepage;
287 
288  /*
289  * Make a copy of the old tuple, so that we can compare it after
290  * re-acquiring the lock.
291  */
292  origsz = ItemIdGetLength(lp);
293  origtup = brin_copy_tuple(brtup, origsz, NULL, NULL);
294 
295  /*
296  * Before releasing the lock, check if we can attempt a same-page
297  * update. Another process could insert a tuple concurrently in
298  * the same page though, so downstream we must be prepared to cope
299  * if this turns out to not be possible after all.
300  */
301  newtup = brin_form_tuple(bdesc, heapBlk, dtup, &newsz);
302  samepage = brin_can_do_samepage_update(buf, origsz, newsz);
304 
305  /*
306  * Try to update the tuple. If this doesn't work for whatever
307  * reason, we need to restart from the top; the revmap might be
308  * pointing at a different tuple for this block now, so we need to
309  * recompute to ensure both our new heap tuple and the other
310  * inserter's are covered by the combined tuple. It might be that
311  * we don't need to update at all.
312  */
313  if (!brin_doupdate(idxRel, pagesPerRange, revmap, heapBlk,
314  buf, off, origtup, origsz, newtup, newsz,
315  samepage))
316  {
317  /* no luck; start over */
319  continue;
320  }
321  }
322 
323  /* success! */
324  break;
325  }
326 
327  brinRevmapTerminate(revmap);
328  if (BufferIsValid(buf))
330  MemoryContextSwitchTo(oldcxt);
331  if (tupcxt != NULL)
332  MemoryContextDelete(tupcxt);
333 
334  return false;
335 }
bool AutoVacuumRequestWork(AutoVacuumWorkItemType type, Oid relationId, BlockNumber blkno)
Definition: autovacuum.c:3240
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:96
MemoryContext ii_Context
Definition: execnodes.h:179
Definition: fmgr.h:56
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:170
FmgrInfo * index_getprocinfo(Relation irel, AttrNumber attnum, uint16 procnum)
Definition: indexam.c:800
BrinTuple * brin_copy_tuple(BrinTuple *tuple, Size len, BrinTuple *dest, Size *destsz)
Definition: brin_tuple.c:320
void brinRevmapTerminate(BrinRevmap *revmap)
Definition: brin_revmap.c:103
BrinTuple * brinGetTupleForHeapBlock(BrinRevmap *revmap, BlockNumber heapBlk, Buffer *buf, OffsetNumber *off, Size *size, int mode, Snapshot snapshot)
Definition: brin_revmap.c:197
#define PointerGetDatum(X)
Definition: postgres.h:556
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define InvalidBuffer
Definition: buf.h:25
int errcode(int sqlerrcode)
Definition: elog.c:610
Datum FunctionCall4Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition: fmgr.c:1199
uint32 BlockNumber
Definition: block.h:31
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3483
#define LOG
Definition: elog.h:26
bool brin_doupdate(Relation idxrel, BlockNumber pagesPerRange, BrinRevmap *revmap, BlockNumber heapBlk, Buffer oldbuf, OffsetNumber oldoff, const BrinTuple *origtup, Size origsz, const BrinTuple *newtup, Size newsz, bool samepage)
Definition: brin_pageops.c:54
uint16 OffsetNumber
Definition: off.h:24
BrinMemTuple * brin_deform_tuple(BrinDesc *brdesc, BrinTuple *tuple, BrinMemTuple *dMemtuple)
Definition: brin_tuple.c:421
#define BRIN_PROCNUM_ADDVALUE
Definition: brin_internal.h:68
#define ItemIdGetLength(itemId)
Definition: itemid.h:59
Oid * rd_indcollation
Definition: rel.h:199
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
BrinValues bt_columns[FLEXIBLE_ARRAY_MEMBER]
Definition: brin_tuple.h:46
static char * buf
Definition: pg_test_fsync.c:67
#define FirstOffsetNumber
Definition: off.h:27
#define DatumGetBool(X)
Definition: postgres.h:393
#define RelationGetRelationName(relation)
Definition: rel.h:490
TupleDesc bd_tupdesc
Definition: brin_internal.h:50
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
#define BufferGetPage(buffer)
Definition: bufmgr.h:169
bool brin_can_do_samepage_update(Buffer buffer, Size origsz, Size newsz)
Definition: brin_pageops.c:324
void * ii_AmCache
Definition: execnodes.h:178
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:235
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
uintptr_t Datum
Definition: postgres.h:367
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3722
#define ereport(elevel,...)
Definition: elog.h:144
BrinDesc * brin_build_desc(Relation rel)
Definition: brin.c:1018
size_t Size
Definition: c.h:466
BrinRevmap * brinRevmapInitialize(Relation idxrel, BlockNumber *pagesPerRange, Snapshot snapshot)
Definition: brin_revmap.c:71
#define BufferIsValid(bufnum)
Definition: bufmgr.h:123
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:117
static Datum values[MAXATTR]
Definition: bootstrap.c:167
#define BrinGetAutoSummarize(relation)
Definition: brin.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:824
BrinTuple * brin_form_tuple(BrinDesc *brdesc, BlockNumber blkno, BrinMemTuple *tuple, Size *size)
Definition: brin_tuple.c:88
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:97
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98
int Buffer
Definition: buf.h:23
#define RelationGetRelid(relation)
Definition: rel.h:456
Pointer Page
Definition: bufpage.h:78

◆ brinoptions()

bytea* brinoptions ( Datum  reloptions,
bool  validate 
)

Definition at line 827 of file brin.c.

References build_reloptions(), lengthof, offsetof, RELOPT_KIND_BRIN, RELOPT_TYPE_BOOL, and RELOPT_TYPE_INT.

Referenced by brinhandler().

828 {
829  static const relopt_parse_elt tab[] = {
830  {"pages_per_range", RELOPT_TYPE_INT, offsetof(BrinOptions, pagesPerRange)},
831  {"autosummarize", RELOPT_TYPE_BOOL, offsetof(BrinOptions, autosummarize)}
832  };
833 
834  return (bytea *) build_reloptions(reloptions, validate,
836  sizeof(BrinOptions),
837  tab, lengthof(tab));
838 }
#define lengthof(array)
Definition: c.h:668
void * build_reloptions(Datum reloptions, bool validate, relopt_kind kind, Size relopt_struct_size, const relopt_parse_elt *relopt_elems, int num_relopt_elems)
Definition: reloptions.c:1887
Definition: c.h:555
#define offsetof(type, field)
Definition: c.h:661

◆ brinrescan()

void brinrescan ( IndexScanDesc  scan,
ScanKey  scankey,
int  nscankeys,
ScanKey  orderbys,
int  norderbys 
)

Definition at line 568 of file brin.c.

References IndexScanDescData::keyData, and IndexScanDescData::numberOfKeys.

Referenced by brinhandler().

570 {
571  /*
572  * Other index AMs preprocess the scan keys at this point, or sometime
573  * early during the scan; this lets them optimize by removing redundant
574  * keys, or doing early returns when they are impossible to satisfy; see
575  * _bt_preprocess_keys for an example. Something like that could be added
576  * here someday, too.
577  */
578 
579  if (scankey && scan->numberOfKeys > 0)
580  memmove(scan->keyData, scankey,
581  scan->numberOfKeys * sizeof(ScanKeyData));
582 }
struct ScanKeyData * keyData
Definition: relscan.h:107

◆ brinvacuumcleanup()

IndexBulkDeleteResult* brinvacuumcleanup ( IndexVacuumInfo info,
IndexBulkDeleteResult stats 
)

Definition at line 797 of file brin.c.

References AccessShareLock, IndexVacuumInfo::analyze_only, BRIN_ALL_BLOCKRANGES, brin_vacuum_scan(), brinsummarize(), IndexVacuumInfo::index, IndexGetRelation(), IndexBulkDeleteResult::num_index_tuples, IndexBulkDeleteResult::num_pages, palloc0(), RelationGetNumberOfBlocks, RelationGetRelid, IndexVacuumInfo::strategy, table_close(), and table_open().

Referenced by brinhandler().

798 {
799  Relation heapRel;
800 
801  /* No-op in ANALYZE ONLY mode */
802  if (info->analyze_only)
803  return stats;
804 
805  if (!stats)
807  stats->num_pages = RelationGetNumberOfBlocks(info->index);
808  /* rest of stats is initialized by zeroing */
809 
810  heapRel = table_open(IndexGetRelation(RelationGetRelid(info->index), false),
812 
813  brin_vacuum_scan(info->index, info->strategy);
814 
815  brinsummarize(info->index, heapRel, BRIN_ALL_BLOCKRANGES, false,
816  &stats->num_index_tuples, &stats->num_index_tuples);
817 
818  table_close(heapRel, AccessShareLock);
819 
820  return stats;
821 }
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3412
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
bool analyze_only
Definition: genam.h:47
BufferAccessStrategy strategy
Definition: genam.h:52
#define AccessShareLock
Definition: lockdefs.h:36
Relation index
Definition: genam.h:46
BlockNumber num_pages
Definition: genam.h:74
static void brin_vacuum_scan(Relation idxrel, BufferAccessStrategy strategy)
Definition: brin.c:1462
static void brinsummarize(Relation index, Relation heapRel, BlockNumber pageRange, bool include_partial, double *numSummarized, double *numExisting)
Definition: brin.c:1303
void * palloc0(Size size)
Definition: mcxt.c:980
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:211
#define BRIN_ALL_BLOCKRANGES
Definition: brin.c:69
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
double num_index_tuples
Definition: genam.h:77
#define RelationGetRelid(relation)
Definition: rel.h:456

◆ brinvalidate()

bool brinvalidate ( Oid  opclassoid)

Definition at line 37 of file brin_validate.c.

References AMOPSTRATEGY, AMPROCNUM, BRIN_FIRST_OPTIONAL_PROCNUM, BRIN_LAST_OPTIONAL_PROCNUM, BRIN_MANDATORY_NPROCS, BRIN_PROCNUM_ADDVALUE, BRIN_PROCNUM_CONSISTENT, BRIN_PROCNUM_OPCINFO, BRIN_PROCNUM_OPTIONS, BRIN_PROCNUM_UNION, check_amop_signature(), check_amoptsproc_signature(), check_amproc_signature(), CLAOID, elog, ereport, errcode(), errmsg(), ERROR, format_operator(), format_procedure(), format_type_be(), OpFamilyOpFuncGroup::functionset, GETSTRUCT, HeapTupleIsValid, i, identify_opfamily_groups(), INFO, OpFamilyOpFuncGroup::lefttype, lfirst, catclist::members, catclist::n_members, NameStr, ObjectIdGetDatum, OidIsValid, OpFamilyOpFuncGroup::operatorset, OPFAMILYOID, ReleaseCatCacheList(), ReleaseSysCache(), OpFamilyOpFuncGroup::righttype, SearchSysCache1(), SearchSysCacheList1, and catctup::tuple.

Referenced by brinhandler().

38 {
39  bool result = true;
40  HeapTuple classtup;
41  Form_pg_opclass classform;
42  Oid opfamilyoid;
43  Oid opcintype;
44  char *opclassname;
45  HeapTuple familytup;
46  Form_pg_opfamily familyform;
47  char *opfamilyname;
48  CatCList *proclist,
49  *oprlist;
50  uint64 allfuncs = 0;
51  uint64 allops = 0;
52  List *grouplist;
53  OpFamilyOpFuncGroup *opclassgroup;
54  int i;
55  ListCell *lc;
56 
57  /* Fetch opclass information */
58  classtup = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclassoid));
59  if (!HeapTupleIsValid(classtup))
60  elog(ERROR, "cache lookup failed for operator class %u", opclassoid);
61  classform = (Form_pg_opclass) GETSTRUCT(classtup);
62 
63  opfamilyoid = classform->opcfamily;
64  opcintype = classform->opcintype;
65  opclassname = NameStr(classform->opcname);
66 
67  /* Fetch opfamily information */
68  familytup = SearchSysCache1(OPFAMILYOID, ObjectIdGetDatum(opfamilyoid));
69  if (!HeapTupleIsValid(familytup))
70  elog(ERROR, "cache lookup failed for operator family %u", opfamilyoid);
71  familyform = (Form_pg_opfamily) GETSTRUCT(familytup);
72 
73  opfamilyname = NameStr(familyform->opfname);
74 
75  /* Fetch all operators and support functions of the opfamily */
76  oprlist = SearchSysCacheList1(AMOPSTRATEGY, ObjectIdGetDatum(opfamilyoid));
77  proclist = SearchSysCacheList1(AMPROCNUM, ObjectIdGetDatum(opfamilyoid));
78 
79  /* Check individual support functions */
80  for (i = 0; i < proclist->n_members; i++)
81  {
82  HeapTuple proctup = &proclist->members[i]->tuple;
83  Form_pg_amproc procform = (Form_pg_amproc) GETSTRUCT(proctup);
84  bool ok;
85 
86  /* Check procedure numbers and function signatures */
87  switch (procform->amprocnum)
88  {
90  ok = check_amproc_signature(procform->amproc, INTERNALOID, true,
91  1, 1, INTERNALOID);
92  break;
94  ok = check_amproc_signature(procform->amproc, BOOLOID, true,
95  4, 4, INTERNALOID, INTERNALOID,
96  INTERNALOID, INTERNALOID);
97  break;
99  ok = check_amproc_signature(procform->amproc, BOOLOID, true,
100  3, 3, INTERNALOID, INTERNALOID,
101  INTERNALOID);
102  break;
103  case BRIN_PROCNUM_UNION:
104  ok = check_amproc_signature(procform->amproc, BOOLOID, true,
105  3, 3, INTERNALOID, INTERNALOID,
106  INTERNALOID);
107  break;
109  ok = check_amoptsproc_signature(procform->amproc);
110  break;
111  default:
112  /* Complain if it's not a valid optional proc number */
113  if (procform->amprocnum < BRIN_FIRST_OPTIONAL_PROCNUM ||
114  procform->amprocnum > BRIN_LAST_OPTIONAL_PROCNUM)
115  {
116  ereport(INFO,
117  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
118  errmsg("operator family \"%s\" of access method %s contains function %s with invalid support number %d",
119  opfamilyname, "brin",
120  format_procedure(procform->amproc),
121  procform->amprocnum)));
122  result = false;
123  continue; /* omit bad proc numbers from allfuncs */
124  }
125  /* Can't check signatures of optional procs, so assume OK */
126  ok = true;
127  break;
128  }
129 
130  if (!ok)
131  {
132  ereport(INFO,
133  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
134  errmsg("operator family \"%s\" of access method %s contains function %s with wrong signature for support number %d",
135  opfamilyname, "brin",
136  format_procedure(procform->amproc),
137  procform->amprocnum)));
138  result = false;
139  }
140 
141  /* Track all valid procedure numbers seen in opfamily */
142  allfuncs |= ((uint64) 1) << procform->amprocnum;
143  }
144 
145  /* Check individual operators */
146  for (i = 0; i < oprlist->n_members; i++)
147  {
148  HeapTuple oprtup = &oprlist->members[i]->tuple;
149  Form_pg_amop oprform = (Form_pg_amop) GETSTRUCT(oprtup);
150 
151  /* Check that only allowed strategy numbers exist */
152  if (oprform->amopstrategy < 1 || oprform->amopstrategy > 63)
153  {
154  ereport(INFO,
155  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
156  errmsg("operator family \"%s\" of access method %s contains operator %s with invalid strategy number %d",
157  opfamilyname, "brin",
158  format_operator(oprform->amopopr),
159  oprform->amopstrategy)));
160  result = false;
161  }
162  else
163  {
164  /*
165  * The set of operators supplied varies across BRIN opfamilies.
166  * Our plan is to identify all operator strategy numbers used in
167  * the opfamily and then complain about datatype combinations that
168  * are missing any operator(s). However, consider only numbers
169  * that appear in some non-cross-type case, since cross-type
170  * operators may have unique strategies. (This is not a great
171  * heuristic, in particular an erroneous number used in a
172  * cross-type operator will not get noticed; but the core BRIN
173  * opfamilies are messy enough to make it necessary.)
174  */
175  if (oprform->amoplefttype == oprform->amoprighttype)
176  allops |= ((uint64) 1) << oprform->amopstrategy;
177  }
178 
179  /* brin doesn't support ORDER BY operators */
180  if (oprform->amoppurpose != AMOP_SEARCH ||
181  OidIsValid(oprform->amopsortfamily))
182  {
183  ereport(INFO,
184  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
185  errmsg("operator family \"%s\" of access method %s contains invalid ORDER BY specification for operator %s",
186  opfamilyname, "brin",
187  format_operator(oprform->amopopr))));
188  result = false;
189  }
190 
191  /* Check operator signature --- same for all brin strategies */
192  if (!check_amop_signature(oprform->amopopr, BOOLOID,
193  oprform->amoplefttype,
194  oprform->amoprighttype))
195  {
196  ereport(INFO,
197  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
198  errmsg("operator family \"%s\" of access method %s contains operator %s with wrong signature",
199  opfamilyname, "brin",
200  format_operator(oprform->amopopr))));
201  result = false;
202  }
203  }
204 
205  /* Now check for inconsistent groups of operators/functions */
206  grouplist = identify_opfamily_groups(oprlist, proclist);
207  opclassgroup = NULL;
208  foreach(lc, grouplist)
209  {
210  OpFamilyOpFuncGroup *thisgroup = (OpFamilyOpFuncGroup *) lfirst(lc);
211 
212  /* Remember the group exactly matching the test opclass */
213  if (thisgroup->lefttype == opcintype &&
214  thisgroup->righttype == opcintype)
215  opclassgroup = thisgroup;
216 
217  /*
218  * Some BRIN opfamilies expect cross-type support functions to exist,
219  * and some don't. We don't know exactly which are which, so if we
220  * find a cross-type operator for which there are no support functions
221  * at all, let it pass. (Don't expect that all operators exist for
222  * such cross-type cases, either.)
223  */
224  if (thisgroup->functionset == 0 &&
225  thisgroup->lefttype != thisgroup->righttype)
226  continue;
227 
228  /*
229  * Else complain if there seems to be an incomplete set of either
230  * operators or support functions for this datatype pair.
231  */
232  if (thisgroup->operatorset != allops)
233  {
234  ereport(INFO,
235  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
236  errmsg("operator family \"%s\" of access method %s is missing operator(s) for types %s and %s",
237  opfamilyname, "brin",
238  format_type_be(thisgroup->lefttype),
239  format_type_be(thisgroup->righttype))));
240  result = false;
241  }
242  if (thisgroup->functionset != allfuncs)
243  {
244  ereport(INFO,
245  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
246  errmsg("operator family \"%s\" of access method %s is missing support function(s) for types %s and %s",
247  opfamilyname, "brin",
248  format_type_be(thisgroup->lefttype),
249  format_type_be(thisgroup->righttype))));
250  result = false;
251  }
252  }
253 
254  /* Check that the originally-named opclass is complete */
255  if (!opclassgroup || opclassgroup->operatorset != allops)
256  {
257  ereport(INFO,
258  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
259  errmsg("operator class \"%s\" of access method %s is missing operator(s)",
260  opclassname, "brin")));
261  result = false;
262  }
263  for (i = 1; i <= BRIN_MANDATORY_NPROCS; i++)
264  {
265  if (opclassgroup &&
266  (opclassgroup->functionset & (((int64) 1) << i)) != 0)
267  continue; /* got it */
268  ereport(INFO,
269  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
270  errmsg("operator class \"%s\" of access method %s is missing support function %d",
271  opclassname, "brin", i)));
272  result = false;
273  }
274 
275  ReleaseCatCacheList(proclist);
276  ReleaseCatCacheList(oprlist);
277  ReleaseSysCache(familytup);
278  ReleaseSysCache(classtup);
279 
280  return result;
281 }
int n_members
Definition: catcache.h:176
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
FormData_pg_amproc * Form_pg_amproc
Definition: pg_amproc.h:68
#define BRIN_PROCNUM_OPCINFO
Definition: brin_internal.h:67
int errcode(int sqlerrcode)
Definition: elog.c:610
#define INFO
Definition: elog.h:33
char * format_type_be(Oid type_oid)
Definition: format_type.c:327
char * format_operator(Oid operator_oid)
Definition: regproc.c:821
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:644
bool check_amoptsproc_signature(Oid funcid)
Definition: amvalidate.c:191
void ReleaseCatCacheList(CatCList *list)
Definition: catcache.c:1782
CatCTup * members[FLEXIBLE_ARRAY_MEMBER]
Definition: catcache.h:178
#define BRIN_PROCNUM_ADDVALUE
Definition: brin_internal.h:68
bool check_amproc_signature(Oid funcid, Oid restype, bool exact, int minargs, int maxargs,...)
Definition: amvalidate.c:151
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define BRIN_MANDATORY_NPROCS
Definition: brin_internal.h:71
List * identify_opfamily_groups(CatCList *oprlist, CatCList *proclist)
Definition: amvalidate.c:42
#define BRIN_PROCNUM_OPTIONS
Definition: brin_internal.h:72
#define SearchSysCacheList1(cacheId, key1)
Definition: syscache.h:210
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
FormData_pg_opfamily * Form_pg_opfamily
Definition: pg_opfamily.h:51
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define ereport(elevel,...)
Definition: elog.h:144
char * format_procedure(Oid procedure_oid)
Definition: regproc.c:324
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define lfirst(lc)
Definition: pg_list.h:190
#define BRIN_PROCNUM_CONSISTENT
Definition: brin_internal.h:69
bool check_amop_signature(Oid opno, Oid restype, Oid lefttype, Oid righttype)
Definition: amvalidate.c:205
#define BRIN_FIRST_OPTIONAL_PROCNUM
Definition: brin_internal.h:74
#define BRIN_LAST_OPTIONAL_PROCNUM
Definition: brin_internal.h:75
#define BRIN_PROCNUM_UNION
Definition: brin_internal.h:70
int errmsg(const char *fmt,...)
Definition: elog.c:824
FormData_pg_amop * Form_pg_amop
Definition: pg_amop.h:88
#define elog(elevel,...)
Definition: elog.h:214
int i
#define NameStr(name)
Definition: c.h:615
HeapTupleData tuple
Definition: catcache.h:121
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:83
Definition: pg_list.h:50