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, bool indexUnchanged, struct IndexInfo *indexInfo)
 
void brininsertcleanup (Relation index, 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)

Definition at line 85 of file brin_internal.h.

◆ BRIN_FIRST_OPTIONAL_PROCNUM

#define BRIN_FIRST_OPTIONAL_PROCNUM   11

Definition at line 77 of file brin_internal.h.

◆ BRIN_LAST_OPTIONAL_PROCNUM

#define BRIN_LAST_OPTIONAL_PROCNUM   15

Definition at line 78 of file brin_internal.h.

◆ BRIN_MANDATORY_NPROCS

#define BRIN_MANDATORY_NPROCS   4

Definition at line 74 of file brin_internal.h.

◆ BRIN_PROCNUM_ADDVALUE

#define BRIN_PROCNUM_ADDVALUE   2

Definition at line 71 of file brin_internal.h.

◆ BRIN_PROCNUM_CONSISTENT

#define BRIN_PROCNUM_CONSISTENT   3

Definition at line 72 of file brin_internal.h.

◆ BRIN_PROCNUM_OPCINFO

#define BRIN_PROCNUM_OPCINFO   1

Definition at line 70 of file brin_internal.h.

◆ BRIN_PROCNUM_OPTIONS

#define BRIN_PROCNUM_OPTIONS   5 /* optional */

Definition at line 75 of file brin_internal.h.

◆ BRIN_PROCNUM_UNION

#define BRIN_PROCNUM_UNION   4

Definition at line 73 of file brin_internal.h.

◆ SizeofBrinOpcInfo

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

Definition at line 41 of file brin_internal.h.

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 1573 of file brin.c.

1574 {
1575  BrinOpcInfo **opcinfo;
1576  BrinDesc *bdesc;
1577  TupleDesc tupdesc;
1578  int totalstored = 0;
1579  int keyno;
1580  long totalsize;
1581  MemoryContext cxt;
1582  MemoryContext oldcxt;
1583 
1585  "brin desc cxt",
1587  oldcxt = MemoryContextSwitchTo(cxt);
1588  tupdesc = RelationGetDescr(rel);
1589 
1590  /*
1591  * Obtain BrinOpcInfo for each indexed column. While at it, accumulate
1592  * the number of columns stored, since the number is opclass-defined.
1593  */
1594  opcinfo = palloc_array(BrinOpcInfo *, tupdesc->natts);
1595  for (keyno = 0; keyno < tupdesc->natts; keyno++)
1596  {
1597  FmgrInfo *opcInfoFn;
1598  Form_pg_attribute attr = TupleDescAttr(tupdesc, keyno);
1599 
1600  opcInfoFn = index_getprocinfo(rel, keyno + 1, BRIN_PROCNUM_OPCINFO);
1601 
1602  opcinfo[keyno] = (BrinOpcInfo *)
1603  DatumGetPointer(FunctionCall1(opcInfoFn, attr->atttypid));
1604  totalstored += opcinfo[keyno]->oi_nstored;
1605  }
1606 
1607  /* Allocate our result struct and fill it in */
1608  totalsize = offsetof(BrinDesc, bd_info) +
1609  sizeof(BrinOpcInfo *) * tupdesc->natts;
1610 
1611  bdesc = palloc(totalsize);
1612  bdesc->bd_context = cxt;
1613  bdesc->bd_index = rel;
1614  bdesc->bd_tupdesc = tupdesc;
1615  bdesc->bd_disktdesc = NULL; /* generated lazily */
1616  bdesc->bd_totalstored = totalstored;
1617 
1618  for (keyno = 0; keyno < tupdesc->natts; keyno++)
1619  bdesc->bd_info[keyno] = opcinfo[keyno];
1620  pfree(opcinfo);
1621 
1622  MemoryContextSwitchTo(oldcxt);
1623 
1624  return bdesc;
1625 }
#define BRIN_PROCNUM_OPCINFO
Definition: brin_internal.h:70
#define palloc_array(type, count)
Definition: fe_memutils.h:76
#define FunctionCall1(flinfo, arg1)
Definition: fmgr.h:659
FmgrInfo * index_getprocinfo(Relation irel, AttrNumber attnum, uint16 procnum)
Definition: indexam.c:862
void pfree(void *pointer)
Definition: mcxt.c:1521
MemoryContext CurrentMemoryContext
Definition: mcxt.c:143
void * palloc(Size size)
Definition: mcxt.c:1317
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:170
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:312
MemoryContextSwitchTo(old_ctx)
#define RelationGetDescr(relation)
Definition: rel.h:531
int bd_totalstored
Definition: brin_internal.h:59
TupleDesc bd_tupdesc
Definition: brin_internal.h:53
BrinOpcInfo * bd_info[FLEXIBLE_ARRAY_MEMBER]
Definition: brin_internal.h:62
Relation bd_index
Definition: brin_internal.h:50
MemoryContext bd_context
Definition: brin_internal.h:47
TupleDesc bd_disktdesc
Definition: brin_internal.h:56
uint16 oi_nstored
Definition: brin_internal.h:28
Definition: fmgr.h:57
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

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, BrinOpcInfo::oi_nstored, palloc(), palloc_array, pfree(), RelationGetDescr, and TupleDescAttr.

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

◆ brin_free_desc()

void brin_free_desc ( BrinDesc bdesc)

Definition at line 1628 of file brin.c.

1629 {
1630  /* make sure the tupdesc is still valid */
1631  Assert(bdesc->bd_tupdesc->tdrefcount >= 1);
1632  /* no need for retail pfree */
1634 }
#define Assert(condition)
Definition: c.h:812
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:454
int tdrefcount
Definition: tupdesc.h:84

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

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

◆ brinbeginscan()

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

Definition at line 532 of file brin.c.

533 {
534  IndexScanDesc scan;
535  BrinOpaque *opaque;
536 
537  scan = RelationGetIndexScan(r, nkeys, norderbys);
538 
539  opaque = palloc_object(BrinOpaque);
540  opaque->bo_rmAccess = brinRevmapInitialize(r, &opaque->bo_pagesPerRange);
541  opaque->bo_bdesc = brin_build_desc(r);
542  scan->opaque = opaque;
543 
544  return scan;
545 }
BrinDesc * brin_build_desc(Relation rel)
Definition: brin.c:1573
BrinRevmap * brinRevmapInitialize(Relation idxrel, BlockNumber *pagesPerRange)
Definition: brin_revmap.c:70
#define palloc_object(type)
Definition: fe_memutils.h:74
IndexScanDesc RelationGetIndexScan(Relation indexRelation, int nkeys, int norderbys)
Definition: genam.c:80
BlockNumber bo_pagesPerRange
Definition: brin.c:204
BrinDesc * bo_bdesc
Definition: brin.c:206
BrinRevmap * bo_rmAccess
Definition: brin.c:205

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

Referenced by brinhandler().

◆ brinbuild()

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

Definition at line 1096 of file brin.c.

1097 {
1098  IndexBuildResult *result;
1099  double reltuples;
1100  double idxtuples;
1101  BrinRevmap *revmap;
1103  Buffer meta;
1104  BlockNumber pagesPerRange;
1105 
1106  /*
1107  * We expect to be called exactly once for any index relation.
1108  */
1109  if (RelationGetNumberOfBlocks(index) != 0)
1110  elog(ERROR, "index \"%s\" already contains data",
1112 
1113  /*
1114  * Critical section not required, because on error the creation of the
1115  * whole relation will be rolled back.
1116  */
1117 
1121 
1124  MarkBufferDirty(meta);
1125 
1126  if (RelationNeedsWAL(index))
1127  {
1128  xl_brin_createidx xlrec;
1129  XLogRecPtr recptr;
1130  Page page;
1131 
1132  xlrec.version = BRIN_CURRENT_VERSION;
1134 
1135  XLogBeginInsert();
1136  XLogRegisterData((char *) &xlrec, SizeOfBrinCreateIdx);
1138 
1139  recptr = XLogInsert(RM_BRIN_ID, XLOG_BRIN_CREATE_INDEX);
1140 
1141  page = BufferGetPage(meta);
1142  PageSetLSN(page, recptr);
1143  }
1144 
1145  UnlockReleaseBuffer(meta);
1146 
1147  /*
1148  * Initialize our state, including the deformed tuple state.
1149  */
1150  revmap = brinRevmapInitialize(index, &pagesPerRange);
1151  state = initialize_brin_buildstate(index, revmap, pagesPerRange,
1153 
1154  /*
1155  * Attempt to launch parallel worker scan when required
1156  *
1157  * XXX plan_create_index_workers makes the number of workers dependent on
1158  * maintenance_work_mem, requiring 32MB for each worker. That makes sense
1159  * for btree, but not for BRIN, which can do with much less memory. So
1160  * maybe make that somehow less strict, optionally?
1161  */
1162  if (indexInfo->ii_ParallelWorkers > 0)
1163  _brin_begin_parallel(state, heap, index, indexInfo->ii_Concurrent,
1164  indexInfo->ii_ParallelWorkers);
1165 
1166  /*
1167  * If parallel build requested and at least one worker process was
1168  * successfully launched, set up coordination state, wait for workers to
1169  * complete. Then read all tuples from the shared tuplesort and insert
1170  * them into the index.
1171  *
1172  * In serial mode, simply scan the table and build the index one index
1173  * tuple at a time.
1174  */
1175  if (state->bs_leader)
1176  {
1177  SortCoordinate coordinate;
1178 
1179  coordinate = (SortCoordinate) palloc0(sizeof(SortCoordinateData));
1180  coordinate->isWorker = false;
1181  coordinate->nParticipants =
1182  state->bs_leader->nparticipanttuplesorts;
1183  coordinate->sharedsort = state->bs_leader->sharedsort;
1184 
1185  /*
1186  * Begin leader tuplesort.
1187  *
1188  * In cases where parallelism is involved, the leader receives the
1189  * same share of maintenance_work_mem as a serial sort (it is
1190  * generally treated in the same way as a serial sort once we return).
1191  * Parallel worker Tuplesortstates will have received only a fraction
1192  * of maintenance_work_mem, though.
1193  *
1194  * We rely on the lifetime of the Leader Tuplesortstate almost not
1195  * overlapping with any worker Tuplesortstate's lifetime. There may
1196  * be some small overlap, but that's okay because we rely on leader
1197  * Tuplesortstate only allocating a small, fixed amount of memory
1198  * here. When its tuplesort_performsort() is called (by our caller),
1199  * and significant amounts of memory are likely to be used, all
1200  * workers must have already freed almost all memory held by their
1201  * Tuplesortstates (they are about to go away completely, too). The
1202  * overall effect is that maintenance_work_mem always represents an
1203  * absolute high watermark on the amount of memory used by a CREATE
1204  * INDEX operation, regardless of the use of parallelism or any other
1205  * factor.
1206  */
1207  state->bs_sortstate =
1209  TUPLESORT_NONE);
1210 
1211  /* scan the relation and merge per-worker results */
1212  reltuples = _brin_parallel_merge(state);
1213 
1214  _brin_end_parallel(state->bs_leader, state);
1215  }
1216  else /* no parallel index build */
1217  {
1218  /*
1219  * Now scan the relation. No syncscan allowed here because we want
1220  * the heap blocks in physical order (we want to produce the ranges
1221  * starting from block 0, and the callback also relies on this to not
1222  * generate summary for the same range twice).
1223  */
1224  reltuples = table_index_build_scan(heap, index, indexInfo, false, true,
1225  brinbuildCallback, state, NULL);
1226 
1227  /*
1228  * process the final batch
1229  *
1230  * XXX Note this does not update state->bs_currRangeStart, i.e. it
1231  * stays set to the last range added to the index. This is OK, because
1232  * that's what brin_fill_empty_ranges expects.
1233  */
1235 
1236  /*
1237  * Backfill the final ranges with empty data.
1238  *
1239  * This saves us from doing what amounts to full table scans when the
1240  * index with a predicate like WHERE (nonnull_column IS NULL), or
1241  * other very selective predicates.
1242  */
1244  state->bs_currRangeStart,
1245  state->bs_maxRangeStart);
1246  }
1247 
1248  /* release resources */
1249  idxtuples = state->bs_numtuples;
1250  brinRevmapTerminate(state->bs_rmAccess);
1252 
1253  /*
1254  * Return statistics
1255  */
1256  result = palloc_object(IndexBuildResult);
1257 
1258  result->heap_tuples = reltuples;
1259  result->index_tuples = idxtuples;
1260 
1261  return result;
1262 }
uint32 BlockNumber
Definition: block.h:31
static double _brin_parallel_merge(BrinBuildState *state)
Definition: brin.c:2612
static void terminate_brin_buildstate(BrinBuildState *state)
Definition: brin.c:1708
static void form_and_insert_tuple(BrinBuildState *state)
Definition: brin.c:1977
static BrinBuildState * initialize_brin_buildstate(Relation idxRel, BrinRevmap *revmap, BlockNumber pagesPerRange, BlockNumber tablePages)
Definition: brin.c:1661
static void _brin_begin_parallel(BrinBuildState *buildstate, Relation heap, Relation index, bool isconcurrent, int request)
Definition: brin.c:2355
static void _brin_end_parallel(BrinLeader *brinleader, BrinBuildState *state)
Definition: brin.c:2540
static void brin_fill_empty_ranges(BrinBuildState *state, BlockNumber prevRange, BlockNumber nextRange)
Definition: brin.c:2985
static void brinbuildCallback(Relation index, ItemPointer tid, Datum *values, bool *isnull, bool tupleIsAlive, void *brstate)
Definition: brin.c:986
#define BrinGetPagesPerRange(relation)
Definition: brin.h:40
#define BRIN_CURRENT_VERSION
Definition: brin_page.h:72
#define BRIN_METAPAGE_BLKNO
Definition: brin_page.h:75
void brin_metapage_init(Page page, BlockNumber pagesPerRange, uint16 version)
Definition: brin_pageops.c:486
void brinRevmapTerminate(BrinRevmap *revmap)
Definition: brin_revmap.c:100
#define SizeOfBrinCreateIdx
Definition: brin_xlog.h:55
#define XLOG_BRIN_CREATE_INDEX
Definition: brin_xlog.h:31
int Buffer
Definition: buf.h:23
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition: bufmgr.c:3724
Buffer ExtendBufferedRel(BufferManagerRelation bmr, ForkNumber forkNum, BufferAccessStrategy strategy, uint32 flags)
Definition: bufmgr.c:846
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:4941
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:2532
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:273
static Page BufferGetPage(Buffer buffer)
Definition: bufmgr.h:400
@ EB_SKIP_EXTENSION_LOCK
Definition: bufmgr.h:74
@ EB_LOCK_FIRST
Definition: bufmgr.h:86
#define BMR_REL(p_rel)
Definition: bufmgr.h:107
Pointer Page
Definition: bufpage.h:81
static void PageSetLSN(Page page, XLogRecPtr lsn)
Definition: bufpage.h:391
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
int maintenance_work_mem
Definition: globals.c:132
void * palloc0(Size size)
Definition: mcxt.c:1347
#define RelationGetRelationName(relation)
Definition: rel.h:539
#define RelationNeedsWAL(relation)
Definition: rel.h:628
@ MAIN_FORKNUM
Definition: relpath.h:58
double heap_tuples
Definition: genam.h:34
double index_tuples
Definition: genam.h:35
int ii_ParallelWorkers
Definition: execnodes.h:208
bool ii_Concurrent
Definition: execnodes.h:204
Sharedsort * sharedsort
Definition: tuplesort.h:58
Definition: type.h:96
Definition: regguts.h:323
BlockNumber pagesPerRange
Definition: brin_xlog.h:52
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:1784
struct SortCoordinateData * SortCoordinate
Definition: tuplesort.h:61
#define TUPLESORT_NONE
Definition: tuplesort.h:93
Tuplesortstate * tuplesort_begin_index_brin(int workMem, SortCoordinate coordinate, int sortopt)
uint64 XLogRecPtr
Definition: xlogdefs.h:21
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:474
void XLogRegisterData(const char *data, uint32 len)
Definition: xloginsert.c:364
void XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Definition: xloginsert.c:242
void XLogBeginInsert(void)
Definition: xloginsert.c:149
#define REGBUF_STANDARD
Definition: xloginsert.h:34
#define REGBUF_WILL_INIT
Definition: xloginsert.h:33

References _brin_begin_parallel(), _brin_end_parallel(), _brin_parallel_merge(), Assert, BMR_REL, BRIN_CURRENT_VERSION, brin_fill_empty_ranges(), BRIN_METAPAGE_BLKNO, brin_metapage_init(), brinbuildCallback(), BrinGetPagesPerRange, brinRevmapInitialize(), brinRevmapTerminate(), BufferGetBlockNumber(), BufferGetPage(), EB_LOCK_FIRST, EB_SKIP_EXTENSION_LOCK, elog, ERROR, ExtendBufferedRel(), form_and_insert_tuple(), IndexBuildResult::heap_tuples, IndexInfo::ii_Concurrent, IndexInfo::ii_ParallelWorkers, IndexBuildResult::index_tuples, initialize_brin_buildstate(), SortCoordinateData::isWorker, MAIN_FORKNUM, maintenance_work_mem, MarkBufferDirty(), SortCoordinateData::nParticipants, PageSetLSN(), xl_brin_createidx::pagesPerRange, palloc0(), palloc_object, REGBUF_STANDARD, REGBUF_WILL_INIT, RelationGetNumberOfBlocks, RelationGetRelationName, RelationNeedsWAL, SortCoordinateData::sharedsort, SizeOfBrinCreateIdx, table_index_build_scan(), terminate_brin_buildstate(), tuplesort_begin_index_brin(), TUPLESORT_NONE, UnlockReleaseBuffer(), xl_brin_createidx::version, XLOG_BRIN_CREATE_INDEX, XLogBeginInsert(), XLogInsert(), XLogRegisterBuffer(), and XLogRegisterData().

Referenced by brinhandler().

◆ brinbuildempty()

void brinbuildempty ( Relation  index)

Definition at line 1265 of file brin.c.

1266 {
1267  Buffer metabuf;
1268 
1269  /* An empty BRIN index has a metapage only. */
1270  metabuf = ExtendBufferedRel(BMR_REL(index), INIT_FORKNUM, NULL,
1272 
1273  /* Initialize and xlog metabuffer. */
1277  MarkBufferDirty(metabuf);
1278  log_newpage_buffer(metabuf, true);
1279  END_CRIT_SECTION();
1280 
1281  UnlockReleaseBuffer(metabuf);
1282 }
#define START_CRIT_SECTION()
Definition: miscadmin.h:149
#define END_CRIT_SECTION()
Definition: miscadmin.h:151
@ INIT_FORKNUM
Definition: relpath.h:61
XLogRecPtr log_newpage_buffer(Buffer buffer, bool page_std)
Definition: xloginsert.c:1237

References BMR_REL, BRIN_CURRENT_VERSION, brin_metapage_init(), BrinGetPagesPerRange, BufferGetPage(), EB_LOCK_FIRST, EB_SKIP_EXTENSION_LOCK, END_CRIT_SECTION, ExtendBufferedRel(), INIT_FORKNUM, log_newpage_buffer(), MarkBufferDirty(), START_CRIT_SECTION, and UnlockReleaseBuffer().

Referenced by brinhandler().

◆ brinbulkdelete()

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

Definition at line 1294 of file brin.c.

1296 {
1297  /* allocate stats if first time through, else re-use existing struct */
1298  if (stats == NULL)
1300 
1301  return stats;
1302 }
#define palloc0_object(type)
Definition: fe_memutils.h:75

References palloc0_object.

Referenced by brinhandler().

◆ brinendscan()

void brinendscan ( IndexScanDesc  scan)

Definition at line 969 of file brin.c.

970 {
971  BrinOpaque *opaque = (BrinOpaque *) scan->opaque;
972 
974  brin_free_desc(opaque->bo_bdesc);
975  pfree(opaque);
976 }
void brin_free_desc(BrinDesc *bdesc)
Definition: brin.c:1628

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

Referenced by brinhandler().

◆ bringetbitmap()

int64 bringetbitmap ( IndexScanDesc  scan,
TIDBitmap tbm 
)

Definition at line 560 of file brin.c.

561 {
562  Relation idxRel = scan->indexRelation;
564  BrinDesc *bdesc;
565  Oid heapOid;
566  Relation heapRel;
567  BrinOpaque *opaque;
568  BlockNumber nblocks;
569  BlockNumber heapBlk;
570  int totalpages = 0;
571  FmgrInfo *consistentFn;
572  MemoryContext oldcxt;
573  MemoryContext perRangeCxt;
574  BrinMemTuple *dtup;
575  BrinTuple *btup = NULL;
576  Size btupsz = 0;
577  ScanKey **keys,
578  **nullkeys;
579  int *nkeys,
580  *nnullkeys;
581  char *ptr;
582  Size len;
583  char *tmp PG_USED_FOR_ASSERTS_ONLY;
584 
585  opaque = (BrinOpaque *) scan->opaque;
586  bdesc = opaque->bo_bdesc;
587  pgstat_count_index_scan(idxRel);
588 
589  /*
590  * We need to know the size of the table so that we know how long to
591  * iterate on the revmap.
592  */
593  heapOid = IndexGetRelation(RelationGetRelid(idxRel), false);
594  heapRel = table_open(heapOid, AccessShareLock);
595  nblocks = RelationGetNumberOfBlocks(heapRel);
596  table_close(heapRel, AccessShareLock);
597 
598  /*
599  * Make room for the consistent support procedures of indexed columns. We
600  * don't look them up here; we do that lazily the first time we see a scan
601  * key reference each of them. We rely on zeroing fn_oid to InvalidOid.
602  */
603  consistentFn = palloc0_array(FmgrInfo, bdesc->bd_tupdesc->natts);
604 
605  /*
606  * Make room for per-attribute lists of scan keys that we'll pass to the
607  * consistent support procedure. We don't know which attributes have scan
608  * keys, so we allocate space for all attributes. That may use more memory
609  * but it's probably cheaper than determining which attributes are used.
610  *
611  * We keep null and regular keys separate, so that we can pass just the
612  * regular keys to the consistent function easily.
613  *
614  * To reduce the allocation overhead, we allocate one big chunk and then
615  * carve it into smaller arrays ourselves. All the pieces have exactly the
616  * same lifetime, so that's OK.
617  *
618  * XXX The widest index can have 32 attributes, so the amount of wasted
619  * memory is negligible. We could invent a more compact approach (with
620  * just space for used attributes) but that would make the matching more
621  * complex so it's not a good trade-off.
622  */
623  len =
624  MAXALIGN(sizeof(ScanKey *) * bdesc->bd_tupdesc->natts) + /* regular keys */
625  MAXALIGN(sizeof(ScanKey) * scan->numberOfKeys) * bdesc->bd_tupdesc->natts +
626  MAXALIGN(sizeof(int) * bdesc->bd_tupdesc->natts) +
627  MAXALIGN(sizeof(ScanKey *) * bdesc->bd_tupdesc->natts) + /* NULL keys */
628  MAXALIGN(sizeof(ScanKey) * scan->numberOfKeys) * bdesc->bd_tupdesc->natts +
629  MAXALIGN(sizeof(int) * bdesc->bd_tupdesc->natts);
630 
631  ptr = palloc(len);
632  tmp = ptr;
633 
634  keys = (ScanKey **) ptr;
635  ptr += MAXALIGN(sizeof(ScanKey *) * bdesc->bd_tupdesc->natts);
636 
637  nullkeys = (ScanKey **) ptr;
638  ptr += MAXALIGN(sizeof(ScanKey *) * bdesc->bd_tupdesc->natts);
639 
640  nkeys = (int *) ptr;
641  ptr += MAXALIGN(sizeof(int) * bdesc->bd_tupdesc->natts);
642 
643  nnullkeys = (int *) ptr;
644  ptr += MAXALIGN(sizeof(int) * bdesc->bd_tupdesc->natts);
645 
646  for (int i = 0; i < bdesc->bd_tupdesc->natts; i++)
647  {
648  keys[i] = (ScanKey *) ptr;
649  ptr += MAXALIGN(sizeof(ScanKey) * scan->numberOfKeys);
650 
651  nullkeys[i] = (ScanKey *) ptr;
652  ptr += MAXALIGN(sizeof(ScanKey) * scan->numberOfKeys);
653  }
654 
655  Assert(tmp + len == ptr);
656 
657  /* zero the number of keys */
658  memset(nkeys, 0, sizeof(int) * bdesc->bd_tupdesc->natts);
659  memset(nnullkeys, 0, sizeof(int) * bdesc->bd_tupdesc->natts);
660 
661  /* Preprocess the scan keys - split them into per-attribute arrays. */
662  for (int keyno = 0; keyno < scan->numberOfKeys; keyno++)
663  {
664  ScanKey key = &scan->keyData[keyno];
665  AttrNumber keyattno = key->sk_attno;
666 
667  /*
668  * The collation of the scan key must match the collation used in the
669  * index column (but only if the search is not IS NULL/ IS NOT NULL).
670  * Otherwise we shouldn't be using this index ...
671  */
672  Assert((key->sk_flags & SK_ISNULL) ||
673  (key->sk_collation ==
674  TupleDescAttr(bdesc->bd_tupdesc,
675  keyattno - 1)->attcollation));
676 
677  /*
678  * First time we see this index attribute, so init as needed.
679  *
680  * This is a bit of an overkill - we don't know how many scan keys are
681  * there for this attribute, so we simply allocate the largest number
682  * possible (as if all keys were for this attribute). This may waste a
683  * bit of memory, but we only expect small number of scan keys in
684  * general, so this should be negligible, and repeated repalloc calls
685  * are not free either.
686  */
687  if (consistentFn[keyattno - 1].fn_oid == InvalidOid)
688  {
689  FmgrInfo *tmp;
690 
691  /* First time we see this attribute, so no key/null keys. */
692  Assert(nkeys[keyattno - 1] == 0);
693  Assert(nnullkeys[keyattno - 1] == 0);
694 
695  tmp = index_getprocinfo(idxRel, keyattno,
697  fmgr_info_copy(&consistentFn[keyattno - 1], tmp,
699  }
700 
701  /* Add key to the proper per-attribute array. */
702  if (key->sk_flags & SK_ISNULL)
703  {
704  nullkeys[keyattno - 1][nnullkeys[keyattno - 1]] = key;
705  nnullkeys[keyattno - 1]++;
706  }
707  else
708  {
709  keys[keyattno - 1][nkeys[keyattno - 1]] = key;
710  nkeys[keyattno - 1]++;
711  }
712  }
713 
714  /* allocate an initial in-memory tuple, out of the per-range memcxt */
715  dtup = brin_new_memtuple(bdesc);
716 
717  /*
718  * Setup and use a per-range memory context, which is reset every time we
719  * loop below. This avoids having to free the tuples within the loop.
720  */
722  "bringetbitmap cxt",
724  oldcxt = MemoryContextSwitchTo(perRangeCxt);
725 
726  /*
727  * Now scan the revmap. We start by querying for heap page 0,
728  * incrementing by the number of pages per range; this gives us a full
729  * view of the table.
730  */
731  for (heapBlk = 0; heapBlk < nblocks; heapBlk += opaque->bo_pagesPerRange)
732  {
733  bool addrange;
734  bool gottuple = false;
735  BrinTuple *tup;
736  OffsetNumber off;
737  Size size;
738 
740 
741  MemoryContextReset(perRangeCxt);
742 
743  tup = brinGetTupleForHeapBlock(opaque->bo_rmAccess, heapBlk, &buf,
744  &off, &size, BUFFER_LOCK_SHARE);
745  if (tup)
746  {
747  gottuple = true;
748  btup = brin_copy_tuple(tup, size, btup, &btupsz);
750  }
751 
752  /*
753  * For page ranges with no indexed tuple, we must return the whole
754  * range; otherwise, compare it to the scan keys.
755  */
756  if (!gottuple)
757  {
758  addrange = true;
759  }
760  else
761  {
762  dtup = brin_deform_tuple(bdesc, btup, dtup);
763  if (dtup->bt_placeholder)
764  {
765  /*
766  * Placeholder tuples are always returned, regardless of the
767  * values stored in them.
768  */
769  addrange = true;
770  }
771  else
772  {
773  int attno;
774 
775  /*
776  * Compare scan keys with summary values stored for the range.
777  * If scan keys are matched, the page range must be added to
778  * the bitmap. We initially assume the range needs to be
779  * added; in particular this serves the case where there are
780  * no keys.
781  */
782  addrange = true;
783  for (attno = 1; attno <= bdesc->bd_tupdesc->natts; attno++)
784  {
785  BrinValues *bval;
786  Datum add;
787  Oid collation;
788 
789  /*
790  * skip attributes without any scan keys (both regular and
791  * IS [NOT] NULL)
792  */
793  if (nkeys[attno - 1] == 0 && nnullkeys[attno - 1] == 0)
794  continue;
795 
796  bval = &dtup->bt_columns[attno - 1];
797 
798  /*
799  * If the BRIN tuple indicates that this range is empty,
800  * we can skip it: there's nothing to match. We don't
801  * need to examine the next columns.
802  */
803  if (dtup->bt_empty_range)
804  {
805  addrange = false;
806  break;
807  }
808 
809  /*
810  * First check if there are any IS [NOT] NULL scan keys,
811  * and if we're violating them. In that case we can
812  * terminate early, without invoking the support function.
813  *
814  * As there may be more keys, we can only determine
815  * mismatch within this loop.
816  */
817  if (bdesc->bd_info[attno - 1]->oi_regular_nulls &&
818  !check_null_keys(bval, nullkeys[attno - 1],
819  nnullkeys[attno - 1]))
820  {
821  /*
822  * If any of the IS [NOT] NULL keys failed, the page
823  * range as a whole can't pass. So terminate the loop.
824  */
825  addrange = false;
826  break;
827  }
828 
829  /*
830  * So either there are no IS [NOT] NULL keys, or all
831  * passed. If there are no regular scan keys, we're done -
832  * the page range matches. If there are regular keys, but
833  * the page range is marked as 'all nulls' it can't
834  * possibly pass (we're assuming the operators are
835  * strict).
836  */
837 
838  /* No regular scan keys - page range as a whole passes. */
839  if (!nkeys[attno - 1])
840  continue;
841 
842  Assert((nkeys[attno - 1] > 0) &&
843  (nkeys[attno - 1] <= scan->numberOfKeys));
844 
845  /* If it is all nulls, it cannot possibly be consistent. */
846  if (bval->bv_allnulls)
847  {
848  addrange = false;
849  break;
850  }
851 
852  /*
853  * Collation from the first key (has to be the same for
854  * all keys for the same attribute).
855  */
856  collation = keys[attno - 1][0]->sk_collation;
857 
858  /*
859  * Check whether the scan key is consistent with the page
860  * range values; if so, have the pages in the range added
861  * to the output bitmap.
862  *
863  * The opclass may or may not support processing of
864  * multiple scan keys. We can determine that based on the
865  * number of arguments - functions with extra parameter
866  * (number of scan keys) do support this, otherwise we
867  * have to simply pass the scan keys one by one.
868  */
869  if (consistentFn[attno - 1].fn_nargs >= 4)
870  {
871  /* Check all keys at once */
872  add = FunctionCall4Coll(&consistentFn[attno - 1],
873  collation,
874  PointerGetDatum(bdesc),
875  PointerGetDatum(bval),
876  PointerGetDatum(keys[attno - 1]),
877  Int32GetDatum(nkeys[attno - 1]));
878  addrange = DatumGetBool(add);
879  }
880  else
881  {
882  /*
883  * Check keys one by one
884  *
885  * When there are multiple scan keys, failure to meet
886  * the criteria for a single one of them is enough to
887  * discard the range as a whole, so break out of the
888  * loop as soon as a false return value is obtained.
889  */
890  int keyno;
891 
892  for (keyno = 0; keyno < nkeys[attno - 1]; keyno++)
893  {
894  add = FunctionCall3Coll(&consistentFn[attno - 1],
895  keys[attno - 1][keyno]->sk_collation,
896  PointerGetDatum(bdesc),
897  PointerGetDatum(bval),
898  PointerGetDatum(keys[attno - 1][keyno]));
899  addrange = DatumGetBool(add);
900  if (!addrange)
901  break;
902  }
903  }
904 
905  /*
906  * If we found a scan key eliminating the range, no need
907  * to check additional ones.
908  */
909  if (!addrange)
910  break;
911  }
912  }
913  }
914 
915  /* add the pages in the range to the output bitmap, if needed */
916  if (addrange)
917  {
918  BlockNumber pageno;
919 
920  for (pageno = heapBlk;
921  pageno <= Min(nblocks, heapBlk + opaque->bo_pagesPerRange) - 1;
922  pageno++)
923  {
924  MemoryContextSwitchTo(oldcxt);
925  tbm_add_page(tbm, pageno);
926  totalpages++;
927  MemoryContextSwitchTo(perRangeCxt);
928  }
929  }
930  }
931 
932  MemoryContextSwitchTo(oldcxt);
933  MemoryContextDelete(perRangeCxt);
934 
935  if (buf != InvalidBuffer)
937 
938  /*
939  * XXX We have an approximation of the number of *pages* that our scan
940  * returns, but we don't have a precise idea of the number of heap tuples
941  * involved.
942  */
943  return totalpages * 10;
944 }
int16 AttrNumber
Definition: attnum.h:21
static bool check_null_keys(BrinValues *bval, ScanKey *nullkeys, int nnullkeys)
Definition: brin.c:2291
#define BRIN_PROCNUM_CONSISTENT
Definition: brin_internal.h:72
BrinTuple * brinGetTupleForHeapBlock(BrinRevmap *revmap, BlockNumber heapBlk, Buffer *buf, OffsetNumber *off, Size *size, int mode)
Definition: brin_revmap.c:194
BrinMemTuple * brin_new_memtuple(BrinDesc *brdesc)
Definition: brin_tuple.c:482
BrinMemTuple * brin_deform_tuple(BrinDesc *brdesc, BrinTuple *tuple, BrinMemTuple *dMemtuple)
Definition: brin_tuple.c:553
BrinTuple * brin_copy_tuple(BrinTuple *tuple, Size len, BrinTuple *dest, Size *destsz)
Definition: brin_tuple.c:446
#define InvalidBuffer
Definition: buf.h:25
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:4924
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:5158
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:189
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:190
#define Min(x, y)
Definition: c.h:958
#define MAXALIGN(LEN)
Definition: c.h:765
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:201
size_t Size
Definition: c.h:559
#define palloc0_array(type, count)
Definition: fe_memutils.h:77
Datum FunctionCall4Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition: fmgr.c:1196
Datum FunctionCall3Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2, Datum arg3)
Definition: fmgr.c:1171
void fmgr_info_copy(FmgrInfo *dstinfo, FmgrInfo *srcinfo, MemoryContext destcxt)
Definition: fmgr.c:580
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3552
int i
Definition: isn.c:72
#define AccessShareLock
Definition: lockdefs.h:36
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:383
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
uint16 OffsetNumber
Definition: off.h:24
const void size_t len
static char * buf
Definition: pg_test_fsync.c:72
#define pgstat_count_index_scan(rel)
Definition: pgstat.h:664
static bool DatumGetBool(Datum X)
Definition: postgres.h:90
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322
uintptr_t Datum
Definition: postgres.h:64
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:212
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
static void addrange(struct cvec *cv, chr from, chr to)
Definition: regc_cvec.c:90
#define RelationGetRelid(relation)
Definition: rel.h:505
#define SK_ISNULL
Definition: skey.h:115
static pg_noinline void Size size
Definition: slab.c:607
BrinValues bt_columns[FLEXIBLE_ARRAY_MEMBER]
Definition: brin_tuple.h:55
bool bt_placeholder
Definition: brin_tuple.h:46
bool bt_empty_range
Definition: brin_tuple.h:47
bool oi_regular_nulls
Definition: brin_internal.h:31
bool bv_allnulls
Definition: brin_tuple.h:33
struct ScanKeyData * keyData
Definition: relscan.h:145
Relation indexRelation
Definition: relscan.h:141
Oid sk_collation
Definition: skey.h:70
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
void tbm_add_page(TIDBitmap *tbm, BlockNumber pageno)
Definition: tidbitmap.c:443

References AccessShareLock, addrange(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, BrinDesc::bd_info, 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_empty_range, BrinMemTuple::bt_placeholder, buf, BUFFER_LOCK_SHARE, BUFFER_LOCK_UNLOCK, BrinValues::bv_allnulls, CHECK_FOR_INTERRUPTS, check_null_keys(), CurrentMemoryContext, DatumGetBool(), fmgr_info_copy(), FunctionCall3Coll(), FunctionCall4Coll(), i, index_getprocinfo(), IndexGetRelation(), IndexScanDescData::indexRelation, Int32GetDatum(), InvalidBuffer, InvalidOid, sort-test::key, IndexScanDescData::keyData, len, LockBuffer(), MAXALIGN, MemoryContextDelete(), MemoryContextReset(), MemoryContextSwitchTo(), Min, TupleDescData::natts, IndexScanDescData::numberOfKeys, BrinOpcInfo::oi_regular_nulls, IndexScanDescData::opaque, palloc(), palloc0_array, PG_USED_FOR_ASSERTS_ONLY, pgstat_count_index_scan, PointerGetDatum(), RelationGetNumberOfBlocks, RelationGetRelid, ReleaseBuffer(), size, ScanKeyData::sk_collation, SK_ISNULL, table_close(), table_open(), tbm_add_page(), and TupleDescAttr.

Referenced by brinhandler().

◆ brininsert()

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

Definition at line 339 of file brin.c.

344 {
345  BlockNumber pagesPerRange;
346  BlockNumber origHeapBlk;
347  BlockNumber heapBlk;
348  BrinInsertState *bistate = (BrinInsertState *) indexInfo->ii_AmCache;
349  BrinRevmap *revmap;
350  BrinDesc *bdesc;
352  MemoryContext tupcxt = NULL;
354  bool autosummarize = BrinGetAutoSummarize(idxRel);
355 
356  /*
357  * If first time through in this statement, initialize the insert state
358  * that we keep for all the inserts in the command.
359  */
360  if (!bistate)
361  bistate = initialize_brin_insertstate(idxRel, indexInfo);
362 
363  revmap = bistate->bis_rmAccess;
364  bdesc = bistate->bis_desc;
365  pagesPerRange = bistate->bis_pages_per_range;
366 
367  /*
368  * origHeapBlk is the block number where the insertion occurred. heapBlk
369  * is the first block in the corresponding page range.
370  */
371  origHeapBlk = ItemPointerGetBlockNumber(heaptid);
372  heapBlk = (origHeapBlk / pagesPerRange) * pagesPerRange;
373 
374  for (;;)
375  {
376  bool need_insert = false;
377  OffsetNumber off;
378  BrinTuple *brtup;
379  BrinMemTuple *dtup;
380 
382 
383  /*
384  * If auto-summarization is enabled and we just inserted the first
385  * tuple into the first block of a new non-first page range, request a
386  * summarization run of the previous range.
387  */
388  if (autosummarize &&
389  heapBlk > 0 &&
390  heapBlk == origHeapBlk &&
392  {
393  BlockNumber lastPageRange = heapBlk - 1;
394  BrinTuple *lastPageTuple;
395 
396  lastPageTuple =
397  brinGetTupleForHeapBlock(revmap, lastPageRange, &buf, &off,
398  NULL, BUFFER_LOCK_SHARE);
399  if (!lastPageTuple)
400  {
401  bool recorded;
402 
404  RelationGetRelid(idxRel),
405  lastPageRange);
406  if (!recorded)
407  ereport(LOG,
408  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
409  errmsg("request for BRIN range summarization for index \"%s\" page %u was not recorded",
410  RelationGetRelationName(idxRel),
411  lastPageRange)));
412  }
413  else
415  }
416 
417  brtup = brinGetTupleForHeapBlock(revmap, heapBlk, &buf, &off,
418  NULL, BUFFER_LOCK_SHARE);
419 
420  /* if range is unsummarized, there's nothing to do */
421  if (!brtup)
422  break;
423 
424  /* First time through in this brininsert call? */
425  if (tupcxt == NULL)
426  {
428  "brininsert cxt",
430  MemoryContextSwitchTo(tupcxt);
431  }
432 
433  dtup = brin_deform_tuple(bdesc, brtup, NULL);
434 
435  need_insert = add_values_to_range(idxRel, bdesc, dtup, values, nulls);
436 
437  if (!need_insert)
438  {
439  /*
440  * The tuple is consistent with the new values, so there's nothing
441  * to do.
442  */
444  }
445  else
446  {
447  Page page = BufferGetPage(buf);
448  ItemId lp = PageGetItemId(page, off);
449  Size origsz;
450  BrinTuple *origtup;
451  Size newsz;
452  BrinTuple *newtup;
453  bool samepage;
454 
455  /*
456  * Make a copy of the old tuple, so that we can compare it after
457  * re-acquiring the lock.
458  */
459  origsz = ItemIdGetLength(lp);
460  origtup = brin_copy_tuple(brtup, origsz, NULL, NULL);
461 
462  /*
463  * Before releasing the lock, check if we can attempt a same-page
464  * update. Another process could insert a tuple concurrently in
465  * the same page though, so downstream we must be prepared to cope
466  * if this turns out to not be possible after all.
467  */
468  newtup = brin_form_tuple(bdesc, heapBlk, dtup, &newsz);
469  samepage = brin_can_do_samepage_update(buf, origsz, newsz);
471 
472  /*
473  * Try to update the tuple. If this doesn't work for whatever
474  * reason, we need to restart from the top; the revmap might be
475  * pointing at a different tuple for this block now, so we need to
476  * recompute to ensure both our new heap tuple and the other
477  * inserter's are covered by the combined tuple. It might be that
478  * we don't need to update at all.
479  */
480  if (!brin_doupdate(idxRel, pagesPerRange, revmap, heapBlk,
481  buf, off, origtup, origsz, newtup, newsz,
482  samepage))
483  {
484  /* no luck; start over */
485  MemoryContextReset(tupcxt);
486  continue;
487  }
488  }
489 
490  /* success! */
491  break;
492  }
493 
494  if (BufferIsValid(buf))
496  MemoryContextSwitchTo(oldcxt);
497  if (tupcxt != NULL)
498  MemoryContextDelete(tupcxt);
499 
500  return false;
501 }
bool AutoVacuumRequestWork(AutoVacuumWorkItemType type, Oid relationId, BlockNumber blkno)
Definition: autovacuum.c:3212
@ AVW_BRINSummarizeRange
Definition: autovacuum.h:25
static Datum values[MAXATTR]
Definition: bootstrap.c:151
static bool add_values_to_range(Relation idxRel, BrinDesc *bdesc, BrinMemTuple *dtup, const Datum *values, const bool *nulls)
Definition: brin.c:2197
static BrinInsertState * initialize_brin_insertstate(Relation idxRel, IndexInfo *indexInfo)
Definition: brin.c:310
#define BrinGetAutoSummarize(relation)
Definition: brin.h:46
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:53
bool brin_can_do_samepage_update(Buffer buffer, Size origsz, Size newsz)
Definition: brin_pageops.c:323
BrinTuple * brin_form_tuple(BrinDesc *brdesc, BlockNumber blkno, BrinMemTuple *tuple, Size *size)
Definition: brin_tuple.c:99
static bool BufferIsValid(Buffer bufnum)
Definition: bufmgr.h:351
static ItemId PageGetItemId(Page page, OffsetNumber offsetNumber)
Definition: bufpage.h:243
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define LOG
Definition: elog.h:31
#define ereport(elevel,...)
Definition: elog.h:149
#define ItemIdGetLength(itemId)
Definition: itemid.h:59
static OffsetNumber ItemPointerGetOffsetNumber(const ItemPointerData *pointer)
Definition: itemptr.h:124
static BlockNumber ItemPointerGetBlockNumber(const ItemPointerData *pointer)
Definition: itemptr.h:103
#define FirstOffsetNumber
Definition: off.h:27
BrinDesc * bis_desc
Definition: brin.c:195
BrinRevmap * bis_rmAccess
Definition: brin.c:194
BlockNumber bis_pages_per_range
Definition: brin.c:196
void * ii_AmCache
Definition: execnodes.h:210

References add_values_to_range(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, AutoVacuumRequestWork(), AVW_BRINSummarizeRange, BrinInsertState::bis_desc, BrinInsertState::bis_pages_per_range, BrinInsertState::bis_rmAccess, brin_can_do_samepage_update(), brin_copy_tuple(), brin_deform_tuple(), brin_doupdate(), brin_form_tuple(), BrinGetAutoSummarize, brinGetTupleForHeapBlock(), buf, BUFFER_LOCK_SHARE, BUFFER_LOCK_UNLOCK, BufferGetPage(), BufferIsValid(), CHECK_FOR_INTERRUPTS, CurrentMemoryContext, ereport, errcode(), errmsg(), FirstOffsetNumber, IndexInfo::ii_AmCache, initialize_brin_insertstate(), InvalidBuffer, ItemIdGetLength, ItemPointerGetBlockNumber(), ItemPointerGetOffsetNumber(), LockBuffer(), LOG, MemoryContextDelete(), MemoryContextReset(), MemoryContextSwitchTo(), PageGetItemId(), RelationGetRelationName, RelationGetRelid, ReleaseBuffer(), and values.

Referenced by brinhandler().

◆ brininsertcleanup()

void brininsertcleanup ( Relation  index,
struct IndexInfo indexInfo 
)

Definition at line 507 of file brin.c.

508 {
509  BrinInsertState *bistate = (BrinInsertState *) indexInfo->ii_AmCache;
510 
511  /* bail out if cache not initialized */
512  if (indexInfo->ii_AmCache == NULL)
513  return;
514 
515  /*
516  * Clean up the revmap. Note that the brinDesc has already been cleaned up
517  * as part of its own memory context.
518  */
520  bistate->bis_rmAccess = NULL;
521  bistate->bis_desc = NULL;
522 }
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:76

References BrinInsertState::bis_desc, BrinInsertState::bis_rmAccess, brinRevmapTerminate(), if(), and IndexInfo::ii_AmCache.

Referenced by brinhandler().

◆ brinoptions()

bytea* brinoptions ( Datum  reloptions,
bool  validate 
)

Definition at line 1339 of file brin.c.

1340 {
1341  static const relopt_parse_elt tab[] = {
1342  {"pages_per_range", RELOPT_TYPE_INT, offsetof(BrinOptions, pagesPerRange)},
1343  {"autosummarize", RELOPT_TYPE_BOOL, offsetof(BrinOptions, autosummarize)}
1344  };
1345 
1346  return (bytea *) build_reloptions(reloptions, validate,
1348  sizeof(BrinOptions),
1349  tab, lengthof(tab));
1350 }
#define lengthof(array)
Definition: c.h:742
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:1908
@ RELOPT_KIND_BRIN
Definition: reloptions.h:52
@ RELOPT_TYPE_INT
Definition: reloptions.h:32
@ RELOPT_TYPE_BOOL
Definition: reloptions.h:31
Definition: c.h:641

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

Referenced by brinhandler().

◆ brinrescan()

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

Definition at line 950 of file brin.c.

952 {
953  /*
954  * Other index AMs preprocess the scan keys at this point, or sometime
955  * early during the scan; this lets them optimize by removing redundant
956  * keys, or doing early returns when they are impossible to satisfy; see
957  * _bt_preprocess_keys for an example. Something like that could be added
958  * here someday, too.
959  */
960 
961  if (scankey && scan->numberOfKeys > 0)
962  memcpy(scan->keyData, scankey, scan->numberOfKeys * sizeof(ScanKeyData));
963 }

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

Referenced by brinhandler().

◆ brinvacuumcleanup()

IndexBulkDeleteResult* brinvacuumcleanup ( IndexVacuumInfo info,
IndexBulkDeleteResult stats 
)

Definition at line 1309 of file brin.c.

1310 {
1311  Relation heapRel;
1312 
1313  /* No-op in ANALYZE ONLY mode */
1314  if (info->analyze_only)
1315  return stats;
1316 
1317  if (!stats)
1319  stats->num_pages = RelationGetNumberOfBlocks(info->index);
1320  /* rest of stats is initialized by zeroing */
1321 
1322  heapRel = table_open(IndexGetRelation(RelationGetRelid(info->index), false),
1323  AccessShareLock);
1324 
1325  brin_vacuum_scan(info->index, info->strategy);
1326 
1327  brinsummarize(info->index, heapRel, BRIN_ALL_BLOCKRANGES, false,
1328  &stats->num_index_tuples, &stats->num_index_tuples);
1329 
1330  table_close(heapRel, AccessShareLock);
1331 
1332  return stats;
1333 }
static void brin_vacuum_scan(Relation idxrel, BufferAccessStrategy strategy)
Definition: brin.c:2164
#define BRIN_ALL_BLOCKRANGES
Definition: brin.c:209
static void brinsummarize(Relation index, Relation heapRel, BlockNumber pageRange, bool include_partial, double *numSummarized, double *numExisting)
Definition: brin.c:1879
BlockNumber num_pages
Definition: genam.h:79
double num_index_tuples
Definition: genam.h:81
Relation index
Definition: genam.h:48
bool analyze_only
Definition: genam.h:50
BufferAccessStrategy strategy
Definition: genam.h:55

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

Referenced by brinhandler().

◆ brinvalidate()

bool brinvalidate ( Oid  opclassoid)

Definition at line 37 of file brin_validate.c.

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, 4, INTERNALOID, INTERNALOID,
101  INTERNALOID, INT4OID);
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 }
bool check_amproc_signature(Oid funcid, Oid restype, bool exact, int minargs, int maxargs,...)
Definition: amvalidate.c:152
bool check_amop_signature(Oid opno, Oid restype, Oid lefttype, Oid righttype)
Definition: amvalidate.c:206
List * identify_opfamily_groups(CatCList *oprlist, CatCList *proclist)
Definition: amvalidate.c:43
bool check_amoptsproc_signature(Oid funcid)
Definition: amvalidate.c:192
#define BRIN_LAST_OPTIONAL_PROCNUM
Definition: brin_internal.h:78
#define BRIN_PROCNUM_UNION
Definition: brin_internal.h:73
#define BRIN_MANDATORY_NPROCS
Definition: brin_internal.h:74
#define BRIN_PROCNUM_OPTIONS
Definition: brin_internal.h:75
#define BRIN_FIRST_OPTIONAL_PROCNUM
Definition: brin_internal.h:77
#define BRIN_PROCNUM_ADDVALUE
Definition: brin_internal.h:71
#define NameStr(name)
Definition: c.h:700
int64_t int64
Definition: c.h:482
uint64_t uint64
Definition: c.h:486
#define OidIsValid(objectId)
Definition: c.h:729
void ReleaseCatCacheList(CatCList *list)
Definition: catcache.c:1985
#define INFO
Definition: elog.h:34
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
FormData_pg_amop * Form_pg_amop
Definition: pg_amop.h:88
FormData_pg_amproc * Form_pg_amproc
Definition: pg_amproc.h:68
#define lfirst(lc)
Definition: pg_list.h:172
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:83
FormData_pg_opfamily * Form_pg_opfamily
Definition: pg_opfamily.h:51
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
char * format_operator(Oid operator_oid)
Definition: regproc.c:793
char * format_procedure(Oid procedure_oid)
Definition: regproc.c:299
Definition: pg_list.h:54
CatCTup * members[FLEXIBLE_ARRAY_MEMBER]
Definition: catcache.h:180
int n_members
Definition: catcache.h:178
HeapTupleData tuple
Definition: catcache.h:123
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:269
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:221
#define SearchSysCacheList1(cacheId, key1)
Definition: syscache.h:127

References 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(), 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, ReleaseCatCacheList(), ReleaseSysCache(), OpFamilyOpFuncGroup::righttype, SearchSysCache1(), SearchSysCacheList1, and catctup::tuple.

Referenced by brinhandler().