PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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_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

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

Definition at line 73 of file brin_internal.h.

Referenced by brinvalidate().

#define BRIN_LAST_OPTIONAL_PROCNUM   15

Definition at line 74 of file brin_internal.h.

Referenced by brinhandler(), and brinvalidate().

#define BRIN_MANDATORY_NPROCS   4

Definition at line 71 of file brin_internal.h.

Referenced by brinvalidate().

#define BRIN_PROCNUM_ADDVALUE   2

Definition at line 68 of file brin_internal.h.

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

#define BRIN_PROCNUM_CONSISTENT   3

Definition at line 69 of file brin_internal.h.

Referenced by bringetbitmap(), and brinvalidate().

#define BRIN_PROCNUM_OPCINFO   1

Definition at line 67 of file brin_internal.h.

Referenced by brin_build_desc(), and brinvalidate().

#define BRIN_PROCNUM_UNION   4

Definition at line 70 of file brin_internal.h.

Referenced by brinvalidate(), and union_tuples().

#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

Function Documentation

BrinDesc* brin_build_desc ( Relation  rel)

Definition at line 852 of file brin.c.

References ALLOCSET_SMALL_SIZES, AllocSetContextCreate(), tupleDesc::attrs, 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(), tupleDesc::natts, NULL, offsetof, BrinOpcInfo::oi_nstored, palloc(), pfree(), RelationGetDescr, and totalsize.

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

853 {
854  BrinOpcInfo **opcinfo;
855  BrinDesc *bdesc;
856  TupleDesc tupdesc;
857  int totalstored = 0;
858  int keyno;
859  long totalsize;
860  MemoryContext cxt;
861  MemoryContext oldcxt;
862 
864  "brin desc cxt",
866  oldcxt = MemoryContextSwitchTo(cxt);
867  tupdesc = RelationGetDescr(rel);
868 
869  /*
870  * Obtain BrinOpcInfo for each indexed column. While at it, accumulate
871  * the number of columns stored, since the number is opclass-defined.
872  */
873  opcinfo = (BrinOpcInfo **) palloc(sizeof(BrinOpcInfo *) * tupdesc->natts);
874  for (keyno = 0; keyno < tupdesc->natts; keyno++)
875  {
876  FmgrInfo *opcInfoFn;
877 
878  opcInfoFn = index_getprocinfo(rel, keyno + 1, BRIN_PROCNUM_OPCINFO);
879 
880  opcinfo[keyno] = (BrinOpcInfo *)
881  DatumGetPointer(FunctionCall1(opcInfoFn,
882  tupdesc->attrs[keyno]->atttypid));
883  totalstored += opcinfo[keyno]->oi_nstored;
884  }
885 
886  /* Allocate our result struct and fill it in */
887  totalsize = offsetof(BrinDesc, bd_info) +
888  sizeof(BrinOpcInfo *) * tupdesc->natts;
889 
890  bdesc = palloc(totalsize);
891  bdesc->bd_context = cxt;
892  bdesc->bd_index = rel;
893  bdesc->bd_tupdesc = tupdesc;
894  bdesc->bd_disktdesc = NULL; /* generated lazily */
895  bdesc->bd_totalstored = totalstored;
896 
897  for (keyno = 0; keyno < tupdesc->natts; keyno++)
898  bdesc->bd_info[keyno] = opcinfo[keyno];
899  pfree(opcinfo);
900 
901  MemoryContextSwitchTo(oldcxt);
902 
903  return bdesc;
904 }
Definition: fmgr.h:53
FmgrInfo * index_getprocinfo(Relation irel, AttrNumber attnum, uint16 procnum)
Definition: indexam.c:855
#define RelationGetDescr(relation)
Definition: rel.h:425
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:155
Form_pg_attribute * attrs
Definition: tupdesc.h:74
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define BRIN_PROCNUM_OPCINFO
Definition: brin_internal.h:67
int natts
Definition: tupdesc.h:73
void pfree(void *pointer)
Definition: mcxt.c:992
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
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
static uint64 totalsize
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:440
BrinOpcInfo * bd_info[FLEXIBLE_ARRAY_MEMBER]
Definition: brin_internal.h:59
#define NULL
Definition: c.h:226
#define DatumGetPointer(X)
Definition: postgres.h:557
MemoryContext bd_context
Definition: brin_internal.h:44
void * palloc(Size size)
Definition: mcxt.c:891
TupleDesc bd_disktdesc
Definition: brin_internal.h:53
#define FunctionCall1(flinfo, arg1)
Definition: fmgr.h:573
#define offsetof(type, field)
Definition: c.h:551
void brin_free_desc ( BrinDesc bdesc)

Definition at line 907 of file brin.c.

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

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

908 {
909  /* make sure the tupdesc is still valid */
910  Assert(bdesc->bd_tupdesc->tdrefcount >= 1);
911  /* no need for retail pfree */
913 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
TupleDesc bd_tupdesc
Definition: brin_internal.h:50
#define Assert(condition)
Definition: c.h:671
MemoryContext bd_context
Definition: brin_internal.h:44
int tdrefcount
Definition: tupdesc.h:80
IndexScanDesc brinbeginscan ( Relation  r,
int  nkeys,
int  norderbys 
)

Definition at line 288 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().

289 {
290  IndexScanDesc scan;
291  BrinOpaque *opaque;
292 
293  scan = RelationGetIndexScan(r, nkeys, norderbys);
294 
295  opaque = (BrinOpaque *) palloc(sizeof(BrinOpaque));
296  opaque->bo_rmAccess = brinRevmapInitialize(r, &opaque->bo_pagesPerRange,
297  scan->xs_snapshot);
298  opaque->bo_bdesc = brin_build_desc(r);
299  scan->opaque = opaque;
300 
301  return scan;
302 }
Snapshot xs_snapshot
Definition: relscan.h:90
BlockNumber bo_pagesPerRange
Definition: brin.c:58
BrinRevmap * bo_rmAccess
Definition: brin.c:59
BrinDesc * bo_bdesc
Definition: brin.c:60
BrinDesc * brin_build_desc(Relation rel)
Definition: brin.c:852
BrinRevmap * brinRevmapInitialize(Relation idxrel, BlockNumber *pagesPerRange, Snapshot snapshot)
Definition: brin_revmap.c:71
void * palloc(Size size)
Definition: mcxt.c:891
IndexScanDesc RelationGetIndexScan(Relation indexRelation, int nkeys, int norderbys)
Definition: genam.c:78
IndexBuildResult* brinbuild ( Relation  heap,
Relation  index,
struct IndexInfo indexInfo 
)

Definition at line 603 of file brin.c.

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

Referenced by brinhandler().

604 {
605  IndexBuildResult *result;
606  double reltuples;
607  double idxtuples;
608  BrinRevmap *revmap;
610  Buffer meta;
611  BlockNumber pagesPerRange;
612 
613  /*
614  * We expect to be called exactly once for any index relation.
615  */
616  if (RelationGetNumberOfBlocks(index) != 0)
617  elog(ERROR, "index \"%s\" already contains data",
618  RelationGetRelationName(index));
619 
620  /*
621  * Critical section not required, because on error the creation of the
622  * whole relation will be rolled back.
623  */
624 
625  meta = ReadBuffer(index, P_NEW);
628 
631  MarkBufferDirty(meta);
632 
633  if (RelationNeedsWAL(index))
634  {
635  xl_brin_createidx xlrec;
636  XLogRecPtr recptr;
637  Page page;
638 
640  xlrec.pagesPerRange = BrinGetPagesPerRange(index);
641 
642  XLogBeginInsert();
643  XLogRegisterData((char *) &xlrec, SizeOfBrinCreateIdx);
645 
646  recptr = XLogInsert(RM_BRIN_ID, XLOG_BRIN_CREATE_INDEX);
647 
648  page = BufferGetPage(meta);
649  PageSetLSN(page, recptr);
650  }
651 
652  UnlockReleaseBuffer(meta);
653 
654  /*
655  * Initialize our state, including the deformed tuple state.
656  */
657  revmap = brinRevmapInitialize(index, &pagesPerRange, NULL);
658  state = initialize_brin_buildstate(index, revmap, pagesPerRange);
659 
660  /*
661  * Now scan the relation. No syncscan allowed here because we want the
662  * heap blocks in physical order.
663  */
664  reltuples = IndexBuildHeapScan(heap, index, indexInfo, false,
665  brinbuildCallback, (void *) state);
666 
667  /* process the final batch */
668  form_and_insert_tuple(state);
669 
670  /* release resources */
671  idxtuples = state->bs_numtuples;
674 
675  /*
676  * Return statistics
677  */
678  result = (IndexBuildResult *) palloc(sizeof(IndexBuildResult));
679 
680  result->heap_tuples = reltuples;
681  result->index_tuples = idxtuples;
682 
683  return result;
684 }
#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:1445
void XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Definition: xloginsert.c:213
#define XLOG_BRIN_CREATE_INDEX
Definition: brin_xlog.h:31
#define REGBUF_WILL_INIT
Definition: xloginsert.h:32
static void brinbuildCallback(Relation index, HeapTuple htup, Datum *values, bool *isnull, bool tupleIsAlive, void *brstate)
Definition: brin.c:541
uint32 BlockNumber
Definition: block.h:31
static void form_and_insert_tuple(BrinBuildState *state)
Definition: brin.c:1146
#define P_NEW
Definition: bufmgr.h:82
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:89
#define BrinGetPagesPerRange(relation)
Definition: brin.h:28
void brin_metapage_init(Page page, BlockNumber pagesPerRange, uint16 version)
Definition: brin_pageops.c:480
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3315
#define ERROR
Definition: elog.h:43
BrinRevmap * bs_rmAccess
Definition: brin.c:48
#define RelationGetRelationName(relation)
Definition: rel.h:433
#define BufferGetPage(buffer)
Definition: bufmgr.h:160
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:323
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:415
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3529
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:199
#define NULL
Definition: c.h:226
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:671
Definition: regguts.h:298
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:594
BrinRevmap * brinRevmapInitialize(Relation idxrel, BlockNumber *pagesPerRange, Snapshot snapshot)
Definition: brin_revmap.c:71
#define RelationNeedsWAL(relation)
Definition: rel.h:502
int bs_numtuples
Definition: brin.c:44
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition: bufmgr.c:2588
double IndexBuildHeapScan(Relation heapRelation, Relation indexRelation, IndexInfo *indexInfo, bool allow_sync, IndexBuildCallback callback, void *callback_state)
Definition: index.c:2169
void * palloc(Size size)
Definition: mcxt.c:891
BlockNumber pagesPerRange
Definition: brin_xlog.h:52
static BrinBuildState * initialize_brin_buildstate(Relation idxRel, BrinRevmap *revmap, BlockNumber pagesPerRange)
Definition: brin.c:919
#define elog
Definition: elog.h:219
void XLogBeginInsert(void)
Definition: xloginsert.c:120
#define PageSetLSN(page, lsn)
Definition: bufpage.h:365
int Buffer
Definition: buf.h:23
Pointer Page
Definition: bufpage.h:74
double index_tuples
Definition: genam.h:33
double heap_tuples
Definition: genam.h:32
static void terminate_brin_buildstate(BrinBuildState *state)
Definition: brin.c:944
void brinbuildempty ( Relation  index)

Definition at line 687 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(), NULL, P_NEW, RBM_NORMAL, ReadBufferExtended(), START_CRIT_SECTION, and UnlockReleaseBuffer().

Referenced by brinhandler().

688 {
689  Buffer metabuf;
690 
691  /* An empty BRIN index has a metapage only. */
692  metabuf =
695 
696  /* Initialize and xlog metabuffer. */
700  MarkBufferDirty(metabuf);
701  log_newpage_buffer(metabuf, false);
703 
704  UnlockReleaseBuffer(metabuf);
705 }
#define BRIN_CURRENT_VERSION
Definition: brin_page.h:72
XLogRecPtr log_newpage_buffer(Buffer buffer, bool page_std)
Definition: xloginsert.c:1010
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1445
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:640
#define END_CRIT_SECTION()
Definition: miscadmin.h:132
#define START_CRIT_SECTION()
Definition: miscadmin.h:130
#define P_NEW
Definition: bufmgr.h:82
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:89
#define BrinGetPagesPerRange(relation)
Definition: brin.h:28
void brin_metapage_init(Page page, BlockNumber pagesPerRange, uint16 version)
Definition: brin_pageops.c:480
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3315
#define BufferGetPage(buffer)
Definition: bufmgr.h:160
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3529
#define NULL
Definition: c.h:226
int Buffer
Definition: buf.h:23
IndexBulkDeleteResult* brinbulkdelete ( IndexVacuumInfo info,
IndexBulkDeleteResult stats,
IndexBulkDeleteCallback  callback,
void *  callback_state 
)

Definition at line 717 of file brin.c.

References NULL, and palloc0().

Referenced by brinhandler().

719 {
720  /* allocate stats if first time through, else re-use existing struct */
721  if (stats == NULL)
723 
724  return stats;
725 }
void * palloc0(Size size)
Definition: mcxt.c:920
#define NULL
Definition: c.h:226
void brinendscan ( IndexScanDesc  scan)

Definition at line 524 of file brin.c.

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

Referenced by brinhandler().

525 {
526  BrinOpaque *opaque = (BrinOpaque *) scan->opaque;
527 
529  brin_free_desc(opaque->bo_bdesc);
530  pfree(opaque);
531 }
void brin_free_desc(BrinDesc *bdesc)
Definition: brin.c:907
void brinRevmapTerminate(BrinRevmap *revmap)
Definition: brin_revmap.c:103
void pfree(void *pointer)
Definition: mcxt.c:992
BrinRevmap * bo_rmAccess
Definition: brin.c:59
BrinDesc * bo_bdesc
Definition: brin.c:60
int64 bringetbitmap ( IndexScanDesc  scan,
TIDBitmap tbm 
)

Definition at line 317 of file brin.c.

References AccessShareLock, addrange(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate(), Assert, tupleDesc::attrs, BrinDesc::bd_tupdesc, BrinOpaque::bo_bdesc, BrinOpaque::bo_pagesPerRange, BrinOpaque::bo_rmAccess, brin_copy_tuple(), brin_deform_tuple(), 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(), heap_close, heap_open(), index_getprocinfo(), IndexGetRelation(), IndexScanDescData::indexRelation, InvalidBuffer, InvalidOid, IndexScanDescData::keyData, LockBuffer(), MemoryContextDelete(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), tupleDesc::natts, NULL, IndexScanDescData::numberOfKeys, IndexScanDescData::opaque, palloc0(), pgstat_count_index_scan, PointerGetDatum, RelationGetNumberOfBlocks, RelationGetRelid, ReleaseBuffer(), ScanKeyData::sk_attno, ScanKeyData::sk_collation, ScanKeyData::sk_flags, SK_ISNULL, tbm_add_page(), and IndexScanDescData::xs_snapshot.

Referenced by brinhandler().

318 {
319  Relation idxRel = scan->indexRelation;
321  BrinDesc *bdesc;
322  Oid heapOid;
323  Relation heapRel;
324  BrinOpaque *opaque;
325  BlockNumber nblocks;
326  BlockNumber heapBlk;
327  int totalpages = 0;
328  FmgrInfo *consistentFn;
329  MemoryContext oldcxt;
330  MemoryContext perRangeCxt;
331 
332  opaque = (BrinOpaque *) scan->opaque;
333  bdesc = opaque->bo_bdesc;
334  pgstat_count_index_scan(idxRel);
335 
336  /*
337  * We need to know the size of the table so that we know how long to
338  * iterate on the revmap.
339  */
340  heapOid = IndexGetRelation(RelationGetRelid(idxRel), false);
341  heapRel = heap_open(heapOid, AccessShareLock);
342  nblocks = RelationGetNumberOfBlocks(heapRel);
343  heap_close(heapRel, AccessShareLock);
344 
345  /*
346  * Make room for the consistent support procedures of indexed columns. We
347  * don't look them up here; we do that lazily the first time we see a scan
348  * key reference each of them. We rely on zeroing fn_oid to InvalidOid.
349  */
350  consistentFn = palloc0(sizeof(FmgrInfo) * bdesc->bd_tupdesc->natts);
351 
352  /*
353  * Setup and use a per-range memory context, which is reset every time we
354  * loop below. This avoids having to free the tuples within the loop.
355  */
357  "bringetbitmap cxt",
359  oldcxt = MemoryContextSwitchTo(perRangeCxt);
360 
361  /*
362  * Now scan the revmap. We start by querying for heap page 0,
363  * incrementing by the number of pages per range; this gives us a full
364  * view of the table.
365  */
366  for (heapBlk = 0; heapBlk < nblocks; heapBlk += opaque->bo_pagesPerRange)
367  {
368  bool addrange;
369  BrinTuple *tup;
370  OffsetNumber off;
371  Size size;
372 
374 
376 
377  tup = brinGetTupleForHeapBlock(opaque->bo_rmAccess, heapBlk, &buf,
378  &off, &size, BUFFER_LOCK_SHARE,
379  scan->xs_snapshot);
380  if (tup)
381  {
382  tup = brin_copy_tuple(tup, size);
384  }
385 
386  /*
387  * For page ranges with no indexed tuple, we must return the whole
388  * range; otherwise, compare it to the scan keys.
389  */
390  if (tup == NULL)
391  {
392  addrange = true;
393  }
394  else
395  {
396  BrinMemTuple *dtup;
397 
398  dtup = brin_deform_tuple(bdesc, tup);
399  if (dtup->bt_placeholder)
400  {
401  /*
402  * Placeholder tuples are always returned, regardless of the
403  * values stored in them.
404  */
405  addrange = true;
406  }
407  else
408  {
409  int keyno;
410 
411  /*
412  * Compare scan keys with summary values stored for the range.
413  * If scan keys are matched, the page range must be added to
414  * the bitmap. We initially assume the range needs to be
415  * added; in particular this serves the case where there are
416  * no keys.
417  */
418  addrange = true;
419  for (keyno = 0; keyno < scan->numberOfKeys; keyno++)
420  {
421  ScanKey key = &scan->keyData[keyno];
422  AttrNumber keyattno = key->sk_attno;
423  BrinValues *bval = &dtup->bt_columns[keyattno - 1];
424  Datum add;
425 
426  /*
427  * The collation of the scan key must match the collation
428  * used in the index column (but only if the search is not
429  * IS NULL/ IS NOT NULL). Otherwise we shouldn't be using
430  * this index ...
431  */
432  Assert((key->sk_flags & SK_ISNULL) ||
433  (key->sk_collation ==
434  bdesc->bd_tupdesc->attrs[keyattno - 1]->attcollation));
435 
436  /* First time this column? look up consistent function */
437  if (consistentFn[keyattno - 1].fn_oid == InvalidOid)
438  {
439  FmgrInfo *tmp;
440 
441  tmp = index_getprocinfo(idxRel, keyattno,
443  fmgr_info_copy(&consistentFn[keyattno - 1], tmp,
445  }
446 
447  /*
448  * Check whether the scan key is consistent with the page
449  * range values; if so, have the pages in the range added
450  * to the output bitmap.
451  *
452  * When there are multiple scan keys, failure to meet the
453  * criteria for a single one of them is enough to discard
454  * the range as a whole, so break out of the loop as soon
455  * as a false return value is obtained.
456  */
457  add = FunctionCall3Coll(&consistentFn[keyattno - 1],
458  key->sk_collation,
459  PointerGetDatum(bdesc),
460  PointerGetDatum(bval),
461  PointerGetDatum(key));
462  addrange = DatumGetBool(add);
463  if (!addrange)
464  break;
465  }
466  }
467  }
468 
469  /* add the pages in the range to the output bitmap, if needed */
470  if (addrange)
471  {
472  BlockNumber pageno;
473 
474  for (pageno = heapBlk;
475  pageno <= heapBlk + opaque->bo_pagesPerRange - 1;
476  pageno++)
477  {
478  MemoryContextSwitchTo(oldcxt);
479  tbm_add_page(tbm, pageno);
480  totalpages++;
481  MemoryContextSwitchTo(perRangeCxt);
482  }
483  }
484  }
485 
486  MemoryContextSwitchTo(oldcxt);
487  MemoryContextDelete(perRangeCxt);
488 
489  if (buf != InvalidBuffer)
490  ReleaseBuffer(buf);
491 
492  /*
493  * XXX We have an approximation of the number of *pages* that our scan
494  * returns, but we don't have a precise idea of the number of heap tuples
495  * involved.
496  */
497  return totalpages * 10;
498 }
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:87
Definition: fmgr.h:53
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3281
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
FmgrInfo * index_getprocinfo(Relation irel, AttrNumber attnum, uint16 procnum)
Definition: indexam.c:855
BrinTuple * brinGetTupleForHeapBlock(BrinRevmap *revmap, BlockNumber heapBlk, Buffer *buf, OffsetNumber *off, Size *size, int mode, Snapshot snapshot)
Definition: brin_revmap.c:191
#define PointerGetDatum(X)
Definition: postgres.h:564
static void addrange(struct cvec *cv, chr from, chr to)
Definition: regc_cvec.c:90
Form_pg_attribute * attrs
Definition: tupdesc.h:74
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define AccessShareLock
Definition: lockdefs.h:36
Snapshot xs_snapshot
Definition: relscan.h:90
#define InvalidBuffer
Definition: buf.h:25
BrinMemTuple * brin_deform_tuple(BrinDesc *brdesc, BrinTuple *tuple)
Definition: brin_tuple.c:398
uint32 BlockNumber
Definition: block.h:31
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3292
BrinTuple * brin_copy_tuple(BrinTuple *tuple, Size len)
Definition: brin_tuple.c:317
#define heap_close(r, l)
Definition: heapam.h:97
unsigned int Oid
Definition: postgres_ext.h:31
int natts
Definition: tupdesc.h:73
BlockNumber bo_pagesPerRange
Definition: brin.c:58
Relation indexRelation
Definition: relscan.h:89
uint16 OffsetNumber
Definition: off.h:24
bool bt_placeholder
Definition: brin_tuple.h:38
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:145
void fmgr_info_copy(FmgrInfo *dstinfo, FmgrInfo *srcinfo, MemoryContext destcxt)
Definition: fmgr.c:583
BrinValues bt_columns[FLEXIBLE_ARRAY_MEMBER]
Definition: brin_tuple.h:41
static char * buf
Definition: pg_test_fsync.c:65
BrinRevmap * bo_rmAccess
Definition: brin.c:59
#define DatumGetBool(X)
Definition: postgres.h:401
#define pgstat_count_index_scan(rel)
Definition: pgstat.h:1155
TupleDesc bd_tupdesc
Definition: brin_internal.h:50
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
#define SK_ISNULL
Definition: skey.h:115
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:88
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:440
BrinDesc * bo_bdesc
Definition: brin.c:60
void * palloc0(Size size)
Definition: mcxt.c:920
uintptr_t Datum
Definition: postgres.h:374
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3529
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:199
#define InvalidOid
Definition: postgres_ext.h:36
Datum FunctionCall3Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2, Datum arg3)
Definition: fmgr.c:1328
int sk_flags
Definition: skey.h:66
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define BRIN_PROCNUM_CONSISTENT
Definition: brin_internal.h:69
size_t Size
Definition: c.h:353
ScanKey keyData
Definition: relscan.h:93
void tbm_add_page(TIDBitmap *tbm, BlockNumber pageno)
Definition: tidbitmap.c:356
Oid sk_collation
Definition: skey.h:70
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:88
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
int Buffer
Definition: buf.h:23
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:413
AttrNumber sk_attno
Definition: skey.h:67
bool brininsert ( Relation  idxRel,
Datum values,
bool nulls,
ItemPointer  heaptid,
Relation  heapRel,
IndexUniqueCheck  checkUnique,
struct IndexInfo indexInfo 
)

Definition at line 133 of file brin.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate(), 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, brinGetTupleForHeapBlock(), brinRevmapInitialize(), brinRevmapTerminate(), BrinMemTuple::bt_columns, buf, BUFFER_LOCK_SHARE, BUFFER_LOCK_UNLOCK, BufferGetPage, BufferIsValid, CHECK_FOR_INTERRUPTS, CurrentMemoryContext, DatumGetBool, FunctionCall4Coll(), IndexInfo::ii_AmCache, IndexInfo::ii_Context, index_getprocinfo(), InvalidBuffer, ItemIdGetLength, ItemPointerGetBlockNumber, LockBuffer(), MemoryContextDelete(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), tupleDesc::natts, NULL, PageGetItemId, PointerGetDatum, RelationData::rd_indcollation, and ReleaseBuffer().

Referenced by brinhandler().

137 {
138  BlockNumber pagesPerRange;
139  BrinDesc *bdesc = (BrinDesc *) indexInfo->ii_AmCache;
140  BrinRevmap *revmap;
142  MemoryContext tupcxt = NULL;
144 
145  revmap = brinRevmapInitialize(idxRel, &pagesPerRange, NULL);
146 
147  for (;;)
148  {
149  bool need_insert = false;
150  OffsetNumber off;
151  BrinTuple *brtup;
152  BrinMemTuple *dtup;
153  BlockNumber heapBlk;
154  int keyno;
155 
157 
158  heapBlk = ItemPointerGetBlockNumber(heaptid);
159  /* normalize the block number to be the first block in the range */
160  heapBlk = (heapBlk / pagesPerRange) * pagesPerRange;
161  brtup = brinGetTupleForHeapBlock(revmap, heapBlk, &buf, &off, NULL,
163 
164  /* if range is unsummarized, there's nothing to do */
165  if (!brtup)
166  break;
167 
168  /* First time through in this statement? */
169  if (bdesc == NULL)
170  {
171  MemoryContextSwitchTo(indexInfo->ii_Context);
172  bdesc = brin_build_desc(idxRel);
173  indexInfo->ii_AmCache = (void *) bdesc;
174  MemoryContextSwitchTo(oldcxt);
175  }
176  /* First time through in this brininsert call? */
177  if (tupcxt == NULL)
178  {
180  "brininsert cxt",
182  MemoryContextSwitchTo(tupcxt);
183  }
184 
185  dtup = brin_deform_tuple(bdesc, brtup);
186 
187  /*
188  * Compare the key values of the new tuple to the stored index values;
189  * our deformed tuple will get updated if the new tuple doesn't fit
190  * the original range (note this means we can't break out of the loop
191  * early). Make a note of whether this happens, so that we know to
192  * insert the modified tuple later.
193  */
194  for (keyno = 0; keyno < bdesc->bd_tupdesc->natts; keyno++)
195  {
196  Datum result;
197  BrinValues *bval;
198  FmgrInfo *addValue;
199 
200  bval = &dtup->bt_columns[keyno];
201  addValue = index_getprocinfo(idxRel, keyno + 1,
203  result = FunctionCall4Coll(addValue,
204  idxRel->rd_indcollation[keyno],
205  PointerGetDatum(bdesc),
206  PointerGetDatum(bval),
207  values[keyno],
208  nulls[keyno]);
209  /* if that returned true, we need to insert the updated tuple */
210  need_insert |= DatumGetBool(result);
211  }
212 
213  if (!need_insert)
214  {
215  /*
216  * The tuple is consistent with the new values, so there's nothing
217  * to do.
218  */
220  }
221  else
222  {
223  Page page = BufferGetPage(buf);
224  ItemId lp = PageGetItemId(page, off);
225  Size origsz;
226  BrinTuple *origtup;
227  Size newsz;
228  BrinTuple *newtup;
229  bool samepage;
230 
231  /*
232  * Make a copy of the old tuple, so that we can compare it after
233  * re-acquiring the lock.
234  */
235  origsz = ItemIdGetLength(lp);
236  origtup = brin_copy_tuple(brtup, origsz);
237 
238  /*
239  * Before releasing the lock, check if we can attempt a same-page
240  * update. Another process could insert a tuple concurrently in
241  * the same page though, so downstream we must be prepared to cope
242  * if this turns out to not be possible after all.
243  */
244  newtup = brin_form_tuple(bdesc, heapBlk, dtup, &newsz);
245  samepage = brin_can_do_samepage_update(buf, origsz, newsz);
247 
248  /*
249  * Try to update the tuple. If this doesn't work for whatever
250  * reason, we need to restart from the top; the revmap might be
251  * pointing at a different tuple for this block now, so we need to
252  * recompute to ensure both our new heap tuple and the other
253  * inserter's are covered by the combined tuple. It might be that
254  * we don't need to update at all.
255  */
256  if (!brin_doupdate(idxRel, pagesPerRange, revmap, heapBlk,
257  buf, off, origtup, origsz, newtup, newsz,
258  samepage))
259  {
260  /* no luck; start over */
262  continue;
263  }
264  }
265 
266  /* success! */
267  break;
268  }
269 
270  brinRevmapTerminate(revmap);
271  if (BufferIsValid(buf))
273  MemoryContextSwitchTo(oldcxt);
274  if (tupcxt != NULL)
275  MemoryContextDelete(tupcxt);
276 
277  return false;
278 }
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:87
MemoryContext ii_Context
Definition: execnodes.h:82
Definition: fmgr.h:53
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
FmgrInfo * index_getprocinfo(Relation irel, AttrNumber attnum, uint16 procnum)
Definition: indexam.c:855
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:191
#define PointerGetDatum(X)
Definition: postgres.h:564
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define InvalidBuffer
Definition: buf.h:25
BrinMemTuple * brin_deform_tuple(BrinDesc *brdesc, BrinTuple *tuple)
Definition: brin_tuple.c:398
Datum FunctionCall4Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition: fmgr.c:1353
uint32 BlockNumber
Definition: block.h:31
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3292
BrinTuple * brin_copy_tuple(BrinTuple *tuple, Size len)
Definition: brin_tuple.c:317
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:55
int natts
Definition: tupdesc.h:73
uint16 OffsetNumber
Definition: off.h:24
#define BRIN_PROCNUM_ADDVALUE
Definition: brin_internal.h:68
#define ItemIdGetLength(itemId)
Definition: itemid.h:58
Oid * rd_indcollation
Definition: rel.h:189
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:145
BrinValues bt_columns[FLEXIBLE_ARRAY_MEMBER]
Definition: brin_tuple.h:41
static char * buf
Definition: pg_test_fsync.c:65
#define DatumGetBool(X)
Definition: postgres.h:401
TupleDesc bd_tupdesc
Definition: brin_internal.h:50
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
#define BufferGetPage(buffer)
Definition: bufmgr.h:160
bool brin_can_do_samepage_update(Buffer buffer, Size origsz, Size newsz)
Definition: brin_pageops.c:323
void * ii_AmCache
Definition: execnodes.h:81
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:232
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:88
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:440
uintptr_t Datum
Definition: postgres.h:374
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3529
BrinDesc * brin_build_desc(Relation rel)
Definition: brin.c:852
#define NULL
Definition: c.h:226
size_t Size
Definition: c.h:353
BrinRevmap * brinRevmapInitialize(Relation idxrel, BlockNumber *pagesPerRange, Snapshot snapshot)
Definition: brin_revmap.c:71
#define BufferIsValid(bufnum)
Definition: bufmgr.h:114
static Datum values[MAXATTR]
Definition: bootstrap.c:162
BrinTuple * brin_form_tuple(BrinDesc *brdesc, BlockNumber blkno, BrinMemTuple *tuple, Size *size)
Definition: brin_tuple.c:89
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:88
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:66
int Buffer
Definition: buf.h:23
Pointer Page
Definition: bufpage.h:74
bytea* brinoptions ( Datum  reloptions,
bool  validate 
)

Definition at line 762 of file brin.c.

References allocateReloptStruct(), fillRelOptions(), lengthof, NULL, offsetof, options, parseRelOptions(), pfree(), RELOPT_KIND_BRIN, and RELOPT_TYPE_INT.

Referenced by brinhandler().

763 {
765  BrinOptions *rdopts;
766  int numoptions;
767  static const relopt_parse_elt tab[] = {
768  {"pages_per_range", RELOPT_TYPE_INT, offsetof(BrinOptions, pagesPerRange)}
769  };
770 
771  options = parseRelOptions(reloptions, validate, RELOPT_KIND_BRIN,
772  &numoptions);
773 
774  /* if none set, we're done */
775  if (numoptions == 0)
776  return NULL;
777 
778  rdopts = allocateReloptStruct(sizeof(BrinOptions), options, numoptions);
779 
780  fillRelOptions((void *) rdopts, sizeof(BrinOptions), options, numoptions,
781  validate, tab, lengthof(tab));
782 
783  pfree(options);
784 
785  return (bytea *) rdopts;
786 }
#define lengthof(array)
Definition: c.h:558
void pfree(void *pointer)
Definition: mcxt.c:992
void * allocateReloptStruct(Size base, relopt_value *options, int numoptions)
Definition: reloptions.c:1174
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:1198
#define NULL
Definition: c.h:226
Definition: c.h:435
relopt_value * parseRelOptions(Datum options, bool validate, relopt_kind kind, int *numrelopts)
Definition: reloptions.c:975
#define offsetof(type, field)
Definition: c.h:551
void brinrescan ( IndexScanDesc  scan,
ScanKey  scankey,
int  nscankeys,
ScanKey  orderbys,
int  norderbys 
)

Definition at line 504 of file brin.c.

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

Referenced by brinhandler().

506 {
507  /*
508  * Other index AMs preprocess the scan keys at this point, or sometime
509  * early during the scan; this lets them optimize by removing redundant
510  * keys, or doing early returns when they are impossible to satisfy; see
511  * _bt_preprocess_keys for an example. Something like that could be added
512  * here someday, too.
513  */
514 
515  if (scankey && scan->numberOfKeys > 0)
516  memmove(scan->keyData, scankey,
517  scan->numberOfKeys * sizeof(ScanKeyData));
518 }
#define memmove(d, s, c)
Definition: c.h:1058
ScanKey keyData
Definition: relscan.h:93
IndexBulkDeleteResult* brinvacuumcleanup ( IndexVacuumInfo info,
IndexBulkDeleteResult stats 
)

Definition at line 732 of file brin.c.

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

Referenced by brinhandler().

733 {
734  Relation heapRel;
735 
736  /* No-op in ANALYZE ONLY mode */
737  if (info->analyze_only)
738  return stats;
739 
740  if (!stats)
742  stats->num_pages = RelationGetNumberOfBlocks(info->index);
743  /* rest of stats is initialized by zeroing */
744 
745  heapRel = heap_open(IndexGetRelation(RelationGetRelid(info->index), false),
747 
748  brin_vacuum_scan(info->index, info->strategy);
749 
750  brinsummarize(info->index, heapRel,
751  &stats->num_index_tuples, &stats->num_index_tuples);
752 
753  heap_close(heapRel, AccessShareLock);
754 
755  return stats;
756 }
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3281
bool analyze_only
Definition: genam.h:47
BufferAccessStrategy strategy
Definition: genam.h:51
#define AccessShareLock
Definition: lockdefs.h:36
Relation index
Definition: genam.h:46
#define heap_close(r, l)
Definition: heapam.h:97
static void brinsummarize(Relation index, Relation heapRel, double *numSummarized, double *numExisting)
Definition: brin.c:1075
BlockNumber num_pages
Definition: genam.h:73
static void brin_vacuum_scan(Relation idxrel, BufferAccessStrategy strategy)
Definition: brin.c:1208
void * palloc0(Size size)
Definition: mcxt.c:920
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:199
double num_index_tuples
Definition: genam.h:76
#define RelationGetRelid(relation)
Definition: rel.h:413
bool brinvalidate ( Oid  opclassoid)

Definition at line 38 of file brin_validate.c.

References AMOP_SEARCH, AMOPSTRATEGY, AMPROCNUM, BOOLOID, BRIN_FIRST_OPTIONAL_PROCNUM, BRIN_LAST_OPTIONAL_PROCNUM, BRIN_MANDATORY_NPROCS, BRIN_PROCNUM_ADDVALUE, BRIN_PROCNUM_CONSISTENT, BRIN_PROCNUM_OPCINFO, BRIN_PROCNUM_UNION, check_amop_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, INTERNALOID, OpFamilyOpFuncGroup::lefttype, lfirst, catclist::members, catclist::n_members, NameStr, NULL, ObjectIdGetDatum, OidIsValid, OpFamilyOpFuncGroup::operatorset, OPFAMILYOID, ReleaseCatCacheList(), ReleaseSysCache(), OpFamilyOpFuncGroup::righttype, SearchSysCache1, SearchSysCacheList1, and catctup::tuple.

Referenced by brinhandler().

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