PostgreSQL Source Code  git master
brin.c File Reference
#include "postgres.h"
#include "access/brin.h"
#include "access/brin_page.h"
#include "access/brin_pageops.h"
#include "access/brin_xlog.h"
#include "access/relation.h"
#include "access/reloptions.h"
#include "access/relscan.h"
#include "access/table.h"
#include "access/tableam.h"
#include "access/xloginsert.h"
#include "catalog/index.h"
#include "catalog/pg_am.h"
#include "commands/vacuum.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "postmaster/autovacuum.h"
#include "storage/bufmgr.h"
#include "storage/freespace.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/index_selfuncs.h"
#include "utils/memutils.h"
#include "utils/rel.h"
Include dependency graph for brin.c:

Go to the source code of this file.

Data Structures

struct  BrinBuildState
 
struct  BrinOpaque
 

Macros

#define BRIN_ALL_BLOCKRANGES   InvalidBlockNumber
 

Typedefs

typedef struct BrinBuildState BrinBuildState
 
typedef struct BrinOpaque BrinOpaque
 

Functions

static BrinBuildStateinitialize_brin_buildstate (Relation idxRel, BrinRevmap *revmap, BlockNumber pagesPerRange)
 
static void terminate_brin_buildstate (BrinBuildState *state)
 
static void brinsummarize (Relation index, Relation heapRel, BlockNumber pageRange, bool include_partial, double *numSummarized, double *numExisting)
 
static void form_and_insert_tuple (BrinBuildState *state)
 
static void union_tuples (BrinDesc *bdesc, BrinMemTuple *a, BrinTuple *b)
 
static void brin_vacuum_scan (Relation idxrel, BufferAccessStrategy strategy)
 
Datum brinhandler (PG_FUNCTION_ARGS)
 
bool brininsert (Relation idxRel, Datum *values, bool *nulls, ItemPointer heaptid, Relation heapRel, IndexUniqueCheck checkUnique, 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)
 
static void brinbuildCallback (Relation index, ItemPointer tid, Datum *values, bool *isnull, bool tupleIsAlive, void *brstate)
 
IndexBuildResultbrinbuild (Relation heap, Relation index, IndexInfo *indexInfo)
 
void brinbuildempty (Relation index)
 
IndexBulkDeleteResultbrinbulkdelete (IndexVacuumInfo *info, IndexBulkDeleteResult *stats, IndexBulkDeleteCallback callback, void *callback_state)
 
IndexBulkDeleteResultbrinvacuumcleanup (IndexVacuumInfo *info, IndexBulkDeleteResult *stats)
 
byteabrinoptions (Datum reloptions, bool validate)
 
Datum brin_summarize_new_values (PG_FUNCTION_ARGS)
 
Datum brin_summarize_range (PG_FUNCTION_ARGS)
 
Datum brin_desummarize_range (PG_FUNCTION_ARGS)
 
BrinDescbrin_build_desc (Relation rel)
 
void brin_free_desc (BrinDesc *bdesc)
 
void brinGetStats (Relation index, BrinStatsData *stats)
 
static void summarize_range (IndexInfo *indexInfo, BrinBuildState *state, Relation heapRel, BlockNumber heapBlk, BlockNumber heapNumBlks)
 

Macro Definition Documentation

◆ BRIN_ALL_BLOCKRANGES

#define BRIN_ALL_BLOCKRANGES   InvalidBlockNumber

Typedef Documentation

◆ BrinBuildState

◆ BrinOpaque

typedef struct BrinOpaque BrinOpaque

Function Documentation

◆ brin_build_desc()

BrinDesc* brin_build_desc ( Relation  rel)

Definition at line 1019 of file brin.c.

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

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

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

◆ brin_desummarize_range()

Datum brin_desummarize_range ( PG_FUNCTION_ARGS  )

Definition at line 938 of file brin.c.

References aclcheck_error(), ACLCHECK_NOT_OWNER, brinRevmapDesummarizeRange(), ereport, errcode(), ERRCODE_UNDEFINED_TABLE, ERRCODE_WRONG_OBJECT_TYPE, errhint(), errmsg(), ERROR, GetUserId(), index_open(), IndexGetRelation(), INT64_FORMAT, MaxBlockNumber, OBJECT_INDEX, OidIsValid, pg_class_ownercheck(), PG_GETARG_INT64, PG_GETARG_OID, PG_RETURN_VOID, psprintf(), RelationData::rd_rel, RecoveryInProgress(), relation_close(), RelationGetRelationName, ShareUpdateExclusiveLock, and table_open().

939 {
940  Oid indexoid = PG_GETARG_OID(0);
941  int64 heapBlk64 = PG_GETARG_INT64(1);
942  BlockNumber heapBlk;
943  Oid heapoid;
944  Relation heapRel;
945  Relation indexRel;
946  bool done;
947 
948  if (RecoveryInProgress())
949  ereport(ERROR,
950  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
951  errmsg("recovery is in progress"),
952  errhint("BRIN control functions cannot be executed during recovery.")));
953 
954  if (heapBlk64 > MaxBlockNumber || heapBlk64 < 0)
955  {
956  char *blk = psprintf(INT64_FORMAT, heapBlk64);
957 
958  ereport(ERROR,
959  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
960  errmsg("block number out of range: %s", blk)));
961  }
962  heapBlk = (BlockNumber) heapBlk64;
963 
964  /*
965  * We must lock table before index to avoid deadlocks. However, if the
966  * passed indexoid isn't an index then IndexGetRelation() will fail.
967  * Rather than emitting a not-very-helpful error message, postpone
968  * complaining, expecting that the is-it-an-index test below will fail.
969  */
970  heapoid = IndexGetRelation(indexoid, true);
971  if (OidIsValid(heapoid))
972  heapRel = table_open(heapoid, ShareUpdateExclusiveLock);
973  else
974  heapRel = NULL;
975 
976  indexRel = index_open(indexoid, ShareUpdateExclusiveLock);
977 
978  /* Must be a BRIN index */
979  if (indexRel->rd_rel->relkind != RELKIND_INDEX ||
980  indexRel->rd_rel->relam != BRIN_AM_OID)
981  ereport(ERROR,
983  errmsg("\"%s\" is not a BRIN index",
984  RelationGetRelationName(indexRel))));
985 
986  /* User must own the index (comparable to privileges needed for VACUUM) */
987  if (!pg_class_ownercheck(indexoid, GetUserId()))
989  RelationGetRelationName(indexRel));
990 
991  /*
992  * Since we did the IndexGetRelation call above without any lock, it's
993  * barely possible that a race against an index drop/recreation could have
994  * netted us the wrong table. Recheck.
995  */
996  if (heapRel == NULL || heapoid != IndexGetRelation(indexoid, false))
997  ereport(ERROR,
999  errmsg("could not open parent table of index %s",
1000  RelationGetRelationName(indexRel))));
1001 
1002  /* the revmap does the hard work */
1003  do
1004  {
1005  done = brinRevmapDesummarizeRange(indexRel, heapBlk);
1006  }
1007  while (!done);
1008 
1011 
1012  PG_RETURN_VOID();
1013 }
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3401
int errhint(const char *fmt,...)
Definition: elog.c:1068
#define ERRCODE_UNDEFINED_TABLE
Definition: pgbench.c:74
Oid GetUserId(void)
Definition: miscinit.c:476
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
int errcode(int sqlerrcode)
Definition: elog.c:610
uint32 BlockNumber
Definition: block.h:31
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
bool RecoveryInProgress(void)
Definition: xlog.c:8076
#define OidIsValid(objectId)
Definition: c.h:652
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3294
#define ERRCODE_WRONG_OBJECT_TYPE
#define ERROR
Definition: elog.h:43
#define MaxBlockNumber
Definition: block.h:35
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
#define RelationGetRelationName(relation)
Definition: rel.h:490
#define ereport(elevel,...)
Definition: elog.h:144
#define PG_RETURN_VOID()
Definition: fmgr.h:348
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4687
bool brinRevmapDesummarizeRange(Relation idxrel, BlockNumber heapBlk)
Definition: brin_revmap.c:328
#define INT64_FORMAT
Definition: c.h:417
int errmsg(const char *fmt,...)
Definition: elog.c:821
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define PG_GETARG_INT64(n)
Definition: fmgr.h:282
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132

◆ brin_free_desc()

void brin_free_desc ( BrinDesc bdesc)

Definition at line 1074 of file brin.c.

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

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

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

◆ brin_summarize_new_values()

Datum brin_summarize_new_values ( PG_FUNCTION_ARGS  )

Definition at line 846 of file brin.c.

References BRIN_ALL_BLOCKRANGES, brin_summarize_range(), DirectFunctionCall2, Int64GetDatum(), and PG_GETARG_DATUM.

847 {
848  Datum relation = PG_GETARG_DATUM(0);
849 
851  relation,
853 }
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:268
Datum brin_summarize_range(PG_FUNCTION_ARGS)
Definition: brin.c:861
Datum Int64GetDatum(int64 X)
Definition: fmgr.c:1701
uintptr_t Datum
Definition: postgres.h:367
#define BRIN_ALL_BLOCKRANGES
Definition: brin.c:69
#define DirectFunctionCall2(func, arg1, arg2)
Definition: fmgr.h:626

◆ brin_summarize_range()

Datum brin_summarize_range ( PG_FUNCTION_ARGS  )

Definition at line 861 of file brin.c.

References aclcheck_error(), ACLCHECK_NOT_OWNER, BRIN_ALL_BLOCKRANGES, brinsummarize(), ereport, errcode(), ERRCODE_UNDEFINED_TABLE, ERRCODE_WRONG_OBJECT_TYPE, errhint(), errmsg(), ERROR, GetUserId(), index_open(), IndexGetRelation(), INT64_FORMAT, OBJECT_INDEX, OidIsValid, pg_class_ownercheck(), PG_GETARG_INT64, PG_GETARG_OID, PG_RETURN_INT32, psprintf(), RelationData::rd_rel, RecoveryInProgress(), relation_close(), RelationGetRelationName, ShareUpdateExclusiveLock, and table_open().

Referenced by brin_summarize_new_values(), and perform_work_item().

862 {
863  Oid indexoid = PG_GETARG_OID(0);
864  int64 heapBlk64 = PG_GETARG_INT64(1);
865  BlockNumber heapBlk;
866  Oid heapoid;
867  Relation indexRel;
868  Relation heapRel;
869  double numSummarized = 0;
870 
871  if (RecoveryInProgress())
872  ereport(ERROR,
873  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
874  errmsg("recovery is in progress"),
875  errhint("BRIN control functions cannot be executed during recovery.")));
876 
877  if (heapBlk64 > BRIN_ALL_BLOCKRANGES || heapBlk64 < 0)
878  {
879  char *blk = psprintf(INT64_FORMAT, heapBlk64);
880 
881  ereport(ERROR,
882  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
883  errmsg("block number out of range: %s", blk)));
884  }
885  heapBlk = (BlockNumber) heapBlk64;
886 
887  /*
888  * We must lock table before index to avoid deadlocks. However, if the
889  * passed indexoid isn't an index then IndexGetRelation() will fail.
890  * Rather than emitting a not-very-helpful error message, postpone
891  * complaining, expecting that the is-it-an-index test below will fail.
892  */
893  heapoid = IndexGetRelation(indexoid, true);
894  if (OidIsValid(heapoid))
895  heapRel = table_open(heapoid, ShareUpdateExclusiveLock);
896  else
897  heapRel = NULL;
898 
899  indexRel = index_open(indexoid, ShareUpdateExclusiveLock);
900 
901  /* Must be a BRIN index */
902  if (indexRel->rd_rel->relkind != RELKIND_INDEX ||
903  indexRel->rd_rel->relam != BRIN_AM_OID)
904  ereport(ERROR,
906  errmsg("\"%s\" is not a BRIN index",
907  RelationGetRelationName(indexRel))));
908 
909  /* User must own the index (comparable to privileges needed for VACUUM) */
910  if (!pg_class_ownercheck(indexoid, GetUserId()))
912  RelationGetRelationName(indexRel));
913 
914  /*
915  * Since we did the IndexGetRelation call above without any lock, it's
916  * barely possible that a race against an index drop/recreation could have
917  * netted us the wrong table. Recheck.
918  */
919  if (heapRel == NULL || heapoid != IndexGetRelation(indexoid, false))
920  ereport(ERROR,
922  errmsg("could not open parent table of index %s",
923  RelationGetRelationName(indexRel))));
924 
925  /* OK, do it */
926  brinsummarize(indexRel, heapRel, heapBlk, true, &numSummarized, NULL);
927 
930 
931  PG_RETURN_INT32((int32) numSummarized);
932 }
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3401
int errhint(const char *fmt,...)
Definition: elog.c:1068
#define ERRCODE_UNDEFINED_TABLE
Definition: pgbench.c:74
Oid GetUserId(void)
Definition: miscinit.c:476
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
#define PG_RETURN_INT32(x)
Definition: fmgr.h:353
int errcode(int sqlerrcode)
Definition: elog.c:610
uint32 BlockNumber
Definition: block.h:31
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
bool RecoveryInProgress(void)
Definition: xlog.c:8076
#define OidIsValid(objectId)
Definition: c.h:652
signed int int32
Definition: c.h:363
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3294
#define ERRCODE_WRONG_OBJECT_TYPE
#define ERROR
Definition: elog.h:43
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
#define RelationGetRelationName(relation)
Definition: rel.h:490
static void brinsummarize(Relation index, Relation heapRel, BlockNumber pageRange, bool include_partial, double *numSummarized, double *numExisting)
Definition: brin.c:1304
#define ereport(elevel,...)
Definition: elog.h:144
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4687
#define INT64_FORMAT
Definition: c.h:417
#define BRIN_ALL_BLOCKRANGES
Definition: brin.c:69
int errmsg(const char *fmt,...)
Definition: elog.c:821
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define PG_GETARG_INT64(n)
Definition: fmgr.h:282
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132

◆ brin_vacuum_scan()

static void brin_vacuum_scan ( Relation  idxrel,
BufferAccessStrategy  strategy 
)
static

Definition at line 1463 of file brin.c.

References brin_page_cleanup(), buf, CHECK_FOR_INTERRUPTS, FreeSpaceMapVacuum(), MAIN_FORKNUM, RBM_NORMAL, ReadBufferExtended(), RelationGetNumberOfBlocks, and ReleaseBuffer().

Referenced by brinvacuumcleanup().

1464 {
1465  BlockNumber nblocks;
1466  BlockNumber blkno;
1467 
1468  /*
1469  * Scan the index in physical order, and clean up any possible mess in
1470  * each page.
1471  */
1472  nblocks = RelationGetNumberOfBlocks(idxrel);
1473  for (blkno = 0; blkno < nblocks; blkno++)
1474  {
1475  Buffer buf;
1476 
1478 
1479  buf = ReadBufferExtended(idxrel, MAIN_FORKNUM, blkno,
1480  RBM_NORMAL, strategy);
1481 
1482  brin_page_cleanup(idxrel, buf);
1483 
1484  ReleaseBuffer(buf);
1485  }
1486 
1487  /*
1488  * Update all upper pages in the index's FSM, as well. This ensures not
1489  * only that we propagate leaf-page FSM updates made by brin_page_cleanup,
1490  * but also that any pre-existing damage or out-of-dateness is repaired.
1491  */
1492  FreeSpaceMapVacuum(idxrel);
1493 }
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:654
uint32 BlockNumber
Definition: block.h:31
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3513
void brin_page_cleanup(Relation idxrel, Buffer buf)
Definition: brin_pageops.c:620
static char * buf
Definition: pg_test_fsync.c:68
void FreeSpaceMapVacuum(Relation rel)
Definition: freespace.c:335
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:211
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
int Buffer
Definition: buf.h:23

◆ brinbeginscan()

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

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

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

◆ brinbuild()

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

Definition at line 669 of file brin.c.

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

Referenced by brinhandler().

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

◆ brinbuildCallback()

static void brinbuildCallback ( Relation  index,
ItemPointer  tid,
Datum values,
bool isnull,
bool  tupleIsAlive,
void *  brstate 
)
static

Definition at line 606 of file brin.c.

References BrinDesc::bd_tupdesc, BRIN_elog, brin_memtuple_initialize(), BRIN_PROCNUM_ADDVALUE, BrinBuildState::bs_bdesc, BrinBuildState::bs_currRangeStart, BrinBuildState::bs_dtuple, BrinBuildState::bs_pagesPerRange, BrinMemTuple::bt_columns, DEBUG2, form_and_insert_tuple(), FunctionCall4Coll(), i, index_getprocinfo(), ItemPointerGetBlockNumber, TupleDescData::natts, PointerGetDatum, and TupleDescAttr.

Referenced by brinbuild(), and summarize_range().

612 {
613  BrinBuildState *state = (BrinBuildState *) brstate;
614  BlockNumber thisblock;
615  int i;
616 
617  thisblock = ItemPointerGetBlockNumber(tid);
618 
619  /*
620  * If we're in a block that belongs to a future range, summarize what
621  * we've got and start afresh. Note the scan might have skipped many
622  * pages, if they were devoid of live tuples; make sure to insert index
623  * tuples for those too.
624  */
625  while (thisblock > state->bs_currRangeStart + state->bs_pagesPerRange - 1)
626  {
627 
628  BRIN_elog((DEBUG2,
629  "brinbuildCallback: completed a range: %u--%u",
630  state->bs_currRangeStart,
631  state->bs_currRangeStart + state->bs_pagesPerRange));
632 
633  /* create the index tuple and insert it */
634  form_and_insert_tuple(state);
635 
636  /* set state to correspond to the next range */
637  state->bs_currRangeStart += state->bs_pagesPerRange;
638 
639  /* re-initialize state for it */
641  }
642 
643  /* Accumulate the current tuple into the running state */
644  for (i = 0; i < state->bs_bdesc->bd_tupdesc->natts; i++)
645  {
646  FmgrInfo *addValue;
647  BrinValues *col;
649 
650  col = &state->bs_dtuple->bt_columns[i];
651  addValue = index_getprocinfo(index, i + 1,
653 
654  /*
655  * Update dtuple state, if and as necessary.
656  */
657  FunctionCall4Coll(addValue,
658  attr->attcollation,
659  PointerGetDatum(state->bs_bdesc),
660  PointerGetDatum(col),
661  values[i], isnull[i]);
662  }
663 }
Definition: fmgr.h:56
#define BRIN_elog(args)
Definition: brin_internal.h:82
FmgrInfo * index_getprocinfo(Relation irel, AttrNumber attnum, uint16 procnum)
Definition: indexam.c:801
#define PointerGetDatum(X)
Definition: postgres.h:556
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
Datum FunctionCall4Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition: fmgr.c:1199
uint32 BlockNumber
Definition: block.h:31
static void form_and_insert_tuple(BrinBuildState *state)
Definition: brin.c:1401
BlockNumber bs_currRangeStart
Definition: brin.c:53
#define BRIN_PROCNUM_ADDVALUE
Definition: brin_internal.h:68
BlockNumber bs_pagesPerRange
Definition: brin.c:52
#define DEBUG2
Definition: elog.h:24
BrinValues bt_columns[FLEXIBLE_ARRAY_MEMBER]
Definition: brin_tuple.h:46
TupleDesc bd_tupdesc
Definition: brin_internal.h:50
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
Definition: regguts.h:298
static Datum values[MAXATTR]
Definition: bootstrap.c:165
int i
BrinMemTuple * bs_dtuple
Definition: brin.c:56
BrinDesc * bs_bdesc
Definition: brin.c:55
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98
BrinMemTuple * brin_memtuple_initialize(BrinMemTuple *dtuple, BrinDesc *brdesc)
Definition: brin_tuple.c:382

◆ brinbuildempty()

void brinbuildempty ( Relation  index)

Definition at line 753 of file brin.c.

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

Referenced by brinhandler().

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

◆ brinbulkdelete()

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

Definition at line 783 of file brin.c.

References palloc0().

Referenced by brinhandler().

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

◆ brinendscan()

void brinendscan ( IndexScanDesc  scan)

Definition at line 589 of file brin.c.

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

Referenced by brinhandler().

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

◆ bringetbitmap()

int64 bringetbitmap ( IndexScanDesc  scan,
TIDBitmap tbm 
)

Definition at line 375 of file brin.c.

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

Referenced by brinhandler().

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

◆ brinGetStats()

void brinGetStats ( Relation  index,
BrinStatsData stats 
)

Definition at line 1086 of file brin.c.

References BRIN_METAPAGE_BLKNO, BUFFER_LOCK_SHARE, BufferGetPage, BrinMetaPageData::lastRevmapPage, LockBuffer(), PageGetContents, BrinStatsData::pagesPerRange, BrinMetaPageData::pagesPerRange, ReadBuffer(), BrinStatsData::revmapNumPages, and UnlockReleaseBuffer().

Referenced by brincostestimate().

1087 {
1088  Buffer metabuffer;
1089  Page metapage;
1090  BrinMetaPageData *metadata;
1091 
1092  metabuffer = ReadBuffer(index, BRIN_METAPAGE_BLKNO);
1093  LockBuffer(metabuffer, BUFFER_LOCK_SHARE);
1094  metapage = BufferGetPage(metabuffer);
1095  metadata = (BrinMetaPageData *) PageGetContents(metapage);
1096 
1097  stats->pagesPerRange = metadata->pagesPerRange;
1098  stats->revmapNumPages = metadata->lastRevmapPage - 1;
1099 
1100  UnlockReleaseBuffer(metabuffer);
1101 }
#define BRIN_METAPAGE_BLKNO
Definition: brin_page.h:75
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3536
#define BufferGetPage(buffer)
Definition: bufmgr.h:169
BlockNumber lastRevmapPage
Definition: brin_page.h:69
#define PageGetContents(page)
Definition: bufpage.h:246
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3752
BlockNumber pagesPerRange
Definition: brin.h:33
BlockNumber pagesPerRange
Definition: brin_page.h:68
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:607
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:97
int Buffer
Definition: buf.h:23
Pointer Page
Definition: bufpage.h:78
BlockNumber revmapNumPages
Definition: brin.h:34

◆ brinhandler()

Datum brinhandler ( PG_FUNCTION_ARGS  )

Definition at line 87 of file brin.c.

References IndexAmRoutine::amadjustmembers, IndexAmRoutine::ambeginscan, IndexAmRoutine::ambuild, IndexAmRoutine::ambuildempty, IndexAmRoutine::ambuildphasename, IndexAmRoutine::ambulkdelete, IndexAmRoutine::amcanbackward, IndexAmRoutine::amcaninclude, IndexAmRoutine::amcanmulticol, IndexAmRoutine::amcanorder, IndexAmRoutine::amcanorderbyop, IndexAmRoutine::amcanparallel, IndexAmRoutine::amcanreturn, IndexAmRoutine::amcanunique, IndexAmRoutine::amclusterable, IndexAmRoutine::amcostestimate, IndexAmRoutine::amendscan, IndexAmRoutine::amestimateparallelscan, IndexAmRoutine::amgetbitmap, IndexAmRoutine::amgettuple, IndexAmRoutine::aminitparallelscan, IndexAmRoutine::aminsert, IndexAmRoutine::amkeytype, IndexAmRoutine::ammarkpos, IndexAmRoutine::amoptionalkey, IndexAmRoutine::amoptions, IndexAmRoutine::amoptsprocnum, IndexAmRoutine::amparallelrescan, IndexAmRoutine::amparallelvacuumoptions, IndexAmRoutine::ampredlocks, IndexAmRoutine::amproperty, IndexAmRoutine::amrescan, IndexAmRoutine::amrestrpos, IndexAmRoutine::amsearcharray, IndexAmRoutine::amsearchnulls, IndexAmRoutine::amstorage, IndexAmRoutine::amstrategies, IndexAmRoutine::amsupport, IndexAmRoutine::amusemaintenanceworkmem, IndexAmRoutine::amvacuumcleanup, IndexAmRoutine::amvalidate, BRIN_LAST_OPTIONAL_PROCNUM, BRIN_PROCNUM_OPTIONS, brinbeginscan(), brinbuild(), brinbuildempty(), brinbulkdelete(), brincostestimate(), brinendscan(), bringetbitmap(), brininsert(), brinoptions(), brinrescan(), brinvacuumcleanup(), brinvalidate(), InvalidOid, makeNode, PG_RETURN_POINTER, and VACUUM_OPTION_PARALLEL_CLEANUP.

88 {
90 
91  amroutine->amstrategies = 0;
94  amroutine->amcanorder = false;
95  amroutine->amcanorderbyop = false;
96  amroutine->amcanbackward = false;
97  amroutine->amcanunique = false;
98  amroutine->amcanmulticol = true;
99  amroutine->amoptionalkey = true;
100  amroutine->amsearcharray = false;
101  amroutine->amsearchnulls = true;
102  amroutine->amstorage = true;
103  amroutine->amclusterable = false;
104  amroutine->ampredlocks = false;
105  amroutine->amcanparallel = false;
106  amroutine->amcaninclude = false;
107  amroutine->amusemaintenanceworkmem = false;
108  amroutine->amparallelvacuumoptions =
110  amroutine->amkeytype = InvalidOid;
111 
112  amroutine->ambuild = brinbuild;
113  amroutine->ambuildempty = brinbuildempty;
114  amroutine->aminsert = brininsert;
115  amroutine->ambulkdelete = brinbulkdelete;
116  amroutine->amvacuumcleanup = brinvacuumcleanup;
117  amroutine->amcanreturn = NULL;
118  amroutine->amcostestimate = brincostestimate;
119  amroutine->amoptions = brinoptions;
120  amroutine->amproperty = NULL;
121  amroutine->ambuildphasename = NULL;
122  amroutine->amvalidate = brinvalidate;
123  amroutine->amadjustmembers = NULL;
124  amroutine->ambeginscan = brinbeginscan;
125  amroutine->amrescan = brinrescan;
126  amroutine->amgettuple = NULL;
127  amroutine->amgetbitmap = bringetbitmap;
128  amroutine->amendscan = brinendscan;
129  amroutine->ammarkpos = NULL;
130  amroutine->amrestrpos = NULL;
131  amroutine->amestimateparallelscan = NULL;
132  amroutine->aminitparallelscan = NULL;
133  amroutine->amparallelrescan = NULL;
134 
135  PG_RETURN_POINTER(amroutine);
136 }
IndexBulkDeleteResult * brinbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats, IndexBulkDeleteCallback callback, void *callback_state)
Definition: brin.c:783
ambeginscan_function ambeginscan
Definition: amapi.h:270
uint8 amparallelvacuumoptions
Definition: amapi.h:247
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:360
ambulkdelete_function ambulkdelete
Definition: amapi.h:261
bool amcanmulticol
Definition: amapi.h:227
uint16 amsupport
Definition: amapi.h:215
IndexBuildResult * brinbuild(Relation heap, Relation index, IndexInfo *indexInfo)
Definition: brin.c:669
bool brininsert(Relation idxRel, Datum *values, bool *nulls, ItemPointer heaptid, Relation heapRel, IndexUniqueCheck checkUnique, IndexInfo *indexInfo)
Definition: brin.c:151
amgettuple_function amgettuple
Definition: amapi.h:272
bool amcanorderbyop
Definition: amapi.h:221
amproperty_function amproperty
Definition: amapi.h:266
bool brinvalidate(Oid opclassoid)
Definition: brin_validate.c:37
amparallelrescan_function amparallelrescan
Definition: amapi.h:281
bool amstorage
Definition: amapi.h:235
int64 bringetbitmap(IndexScanDesc scan, TIDBitmap *tbm)
Definition: brin.c:375
bool ampredlocks
Definition: amapi.h:239
aminsert_function aminsert
Definition: amapi.h:260
Oid amkeytype
Definition: amapi.h:249
bool amoptionalkey
Definition: amapi.h:229
void brinendscan(IndexScanDesc scan)
Definition: brin.c:589
amvalidate_function amvalidate
Definition: amapi.h:268
bytea * brinoptions(Datum reloptions, bool validate)
Definition: brin.c:828
amgetbitmap_function amgetbitmap
Definition: amapi.h:273
ambuild_function ambuild
Definition: amapi.h:258
amoptions_function amoptions
Definition: amapi.h:265
bool amcaninclude
Definition: amapi.h:243
amcostestimate_function amcostestimate
Definition: amapi.h:264
bool amcanunique
Definition: amapi.h:225
#define BRIN_PROCNUM_OPTIONS
Definition: brin_internal.h:72
amvacuumcleanup_function amvacuumcleanup
Definition: amapi.h:262
amendscan_function amendscan
Definition: amapi.h:274
bool amcanbackward
Definition: amapi.h:223
void brinrescan(IndexScanDesc scan, ScanKey scankey, int nscankeys, ScanKey orderbys, int norderbys)
Definition: brin.c:569
amrescan_function amrescan
Definition: amapi.h:271
bool amcanparallel
Definition: amapi.h:241
IndexScanDesc brinbeginscan(Relation r, int nkeys, int norderbys)
Definition: brin.c:346
bool amsearchnulls
Definition: amapi.h:233
bool amclusterable
Definition: amapi.h:237
bool amsearcharray
Definition: amapi.h:231
#define InvalidOid
Definition: postgres_ext.h:36
bool amusemaintenanceworkmem
Definition: amapi.h:245
#define makeNode(_type_)
Definition: nodes.h:576
amadjustmembers_function amadjustmembers
Definition: amapi.h:269
void brincostestimate(PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
Definition: selfuncs.c:7334
ammarkpos_function ammarkpos
Definition: amapi.h:275
bool amcanorder
Definition: amapi.h:219
ambuildphasename_function ambuildphasename
Definition: amapi.h:267
amestimateparallelscan_function amestimateparallelscan
Definition: amapi.h:279
#define BRIN_LAST_OPTIONAL_PROCNUM
Definition: brin_internal.h:75
uint16 amstrategies
Definition: amapi.h:213
uint16 amoptsprocnum
Definition: amapi.h:217
ambuildempty_function ambuildempty
Definition: amapi.h:259
IndexBulkDeleteResult * brinvacuumcleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats)
Definition: brin.c:798
void brinbuildempty(Relation index)
Definition: brin.c:753
#define VACUUM_OPTION_PARALLEL_CLEANUP
Definition: vacuum.h:60
amcanreturn_function amcanreturn
Definition: amapi.h:263
aminitparallelscan_function aminitparallelscan
Definition: amapi.h:280
amrestrpos_function amrestrpos
Definition: amapi.h:276

◆ brininsert()

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

Definition at line 151 of file brin.c.

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

Referenced by brinhandler().

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

◆ brinoptions()

bytea* brinoptions ( Datum  reloptions,
bool  validate 
)

Definition at line 828 of file brin.c.

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

Referenced by brinhandler().

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

◆ brinrescan()

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

Definition at line 569 of file brin.c.

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

Referenced by brinhandler().

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

◆ brinsummarize()

static void brinsummarize ( Relation  index,
Relation  heapRel,
BlockNumber  pageRange,
bool  include_partial,
double *  numSummarized,
double *  numExisting 
)
static

Definition at line 1304 of file brin.c.

References Assert, BRIN_ALL_BLOCKRANGES, brin_memtuple_initialize(), brinGetTupleForHeapBlock(), brinRevmapInitialize(), brinRevmapTerminate(), BrinBuildState::bs_bdesc, BrinBuildState::bs_dtuple, buf, BUFFER_LOCK_SHARE, BUFFER_LOCK_UNLOCK, BufferIsValid, BuildIndexInfo(), CHECK_FOR_INTERRUPTS, initialize_brin_buildstate(), InvalidBuffer, LockBuffer(), Min, pfree(), RelationGetNumberOfBlocks, ReleaseBuffer(), summarize_range(), and terminate_brin_buildstate().

Referenced by brin_summarize_range(), and brinvacuumcleanup().

1306 {
1307  BrinRevmap *revmap;
1308  BrinBuildState *state = NULL;
1309  IndexInfo *indexInfo = NULL;
1310  BlockNumber heapNumBlocks;
1311  BlockNumber pagesPerRange;
1312  Buffer buf;
1313  BlockNumber startBlk;
1314 
1315  revmap = brinRevmapInitialize(index, &pagesPerRange, NULL);
1316 
1317  /* determine range of pages to process */
1318  heapNumBlocks = RelationGetNumberOfBlocks(heapRel);
1319  if (pageRange == BRIN_ALL_BLOCKRANGES)
1320  startBlk = 0;
1321  else
1322  {
1323  startBlk = (pageRange / pagesPerRange) * pagesPerRange;
1324  heapNumBlocks = Min(heapNumBlocks, startBlk + pagesPerRange);
1325  }
1326  if (startBlk > heapNumBlocks)
1327  {
1328  /* Nothing to do if start point is beyond end of table */
1329  brinRevmapTerminate(revmap);
1330  return;
1331  }
1332 
1333  /*
1334  * Scan the revmap to find unsummarized items.
1335  */
1336  buf = InvalidBuffer;
1337  for (; startBlk < heapNumBlocks; startBlk += pagesPerRange)
1338  {
1339  BrinTuple *tup;
1340  OffsetNumber off;
1341 
1342  /*
1343  * Unless requested to summarize even a partial range, go away now if
1344  * we think the next range is partial. Caller would pass true when it
1345  * is typically run once bulk data loading is done
1346  * (brin_summarize_new_values), and false when it is typically the
1347  * result of arbitrarily-scheduled maintenance command (vacuuming).
1348  */
1349  if (!include_partial &&
1350  (startBlk + pagesPerRange > heapNumBlocks))
1351  break;
1352 
1354 
1355  tup = brinGetTupleForHeapBlock(revmap, startBlk, &buf, &off, NULL,
1356  BUFFER_LOCK_SHARE, NULL);
1357  if (tup == NULL)
1358  {
1359  /* no revmap entry for this heap range. Summarize it. */
1360  if (state == NULL)
1361  {
1362  /* first time through */
1363  Assert(!indexInfo);
1364  state = initialize_brin_buildstate(index, revmap,
1365  pagesPerRange);
1366  indexInfo = BuildIndexInfo(index);
1367  }
1368  summarize_range(indexInfo, state, heapRel, startBlk, heapNumBlocks);
1369 
1370  /* and re-initialize state for the next range */
1372 
1373  if (numSummarized)
1374  *numSummarized += 1.0;
1375  }
1376  else
1377  {
1378  if (numExisting)
1379  *numExisting += 1.0;
1381  }
1382  }
1383 
1384  if (BufferIsValid(buf))
1385  ReleaseBuffer(buf);
1386 
1387  /* free resources */
1388  brinRevmapTerminate(revmap);
1389  if (state)
1390  {
1392  pfree(indexInfo);
1393  }
1394 }
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:96
void brinRevmapTerminate(BrinRevmap *revmap)
Definition: brin_revmap.c:103
BrinTuple * brinGetTupleForHeapBlock(BrinRevmap *revmap, BlockNumber heapBlk, Buffer *buf, OffsetNumber *off, Size *size, int mode, Snapshot snapshot)
Definition: brin_revmap.c:197
static void summarize_range(IndexInfo *indexInfo, BrinBuildState *state, Relation heapRel, BlockNumber heapBlk, BlockNumber heapNumBlks)
Definition: brin.c:1177
#define Min(x, y)
Definition: c.h:928
#define InvalidBuffer
Definition: buf.h:25
uint32 BlockNumber
Definition: block.h:31
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3513
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2301
uint16 OffsetNumber
Definition: off.h:24
void pfree(void *pointer)
Definition: mcxt.c:1057
static char * buf
Definition: pg_test_fsync.c:68
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3752
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:211
#define Assert(condition)
Definition: c.h:746
Definition: regguts.h:298
BrinRevmap * brinRevmapInitialize(Relation idxrel, BlockNumber *pagesPerRange, Snapshot snapshot)
Definition: brin_revmap.c:71
#define BufferIsValid(bufnum)
Definition: bufmgr.h:123
#define BRIN_ALL_BLOCKRANGES
Definition: brin.c:69
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:97
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
BrinMemTuple * bs_dtuple
Definition: brin.c:56
static BrinBuildState * initialize_brin_buildstate(Relation idxRel, BrinRevmap *revmap, BlockNumber pagesPerRange)
Definition: brin.c:1107
BrinDesc * bs_bdesc
Definition: brin.c:55
int Buffer
Definition: buf.h:23
BrinMemTuple * brin_memtuple_initialize(BrinMemTuple *dtuple, BrinDesc *brdesc)
Definition: brin_tuple.c:382
static void terminate_brin_buildstate(BrinBuildState *state)
Definition: brin.c:1132

◆ brinvacuumcleanup()

IndexBulkDeleteResult* brinvacuumcleanup ( IndexVacuumInfo info,
IndexBulkDeleteResult stats 
)

Definition at line 798 of file brin.c.

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

Referenced by brinhandler().

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

◆ form_and_insert_tuple()

static void form_and_insert_tuple ( BrinBuildState state)
static

Definition at line 1401 of file brin.c.

References brin_doinsert(), brin_form_tuple(), BrinBuildState::bs_bdesc, BrinBuildState::bs_currentInsertBuf, BrinBuildState::bs_currRangeStart, BrinBuildState::bs_dtuple, BrinBuildState::bs_irel, BrinBuildState::bs_numtuples, BrinBuildState::bs_pagesPerRange, BrinBuildState::bs_rmAccess, and pfree().

Referenced by brinbuild(), and brinbuildCallback().

1402 {
1403  BrinTuple *tup;
1404  Size size;
1405 
1406  tup = brin_form_tuple(state->bs_bdesc, state->bs_currRangeStart,
1407  state->bs_dtuple, &size);
1408  brin_doinsert(state->bs_irel, state->bs_pagesPerRange, state->bs_rmAccess,
1409  &state->bs_currentInsertBuf, state->bs_currRangeStart,
1410  tup, size);
1411  state->bs_numtuples++;
1412 
1413  pfree(tup);
1414 }
Buffer bs_currentInsertBuf
Definition: brin.c:51
Relation bs_irel
Definition: brin.c:49
BlockNumber bs_currRangeStart
Definition: brin.c:53
OffsetNumber brin_doinsert(Relation idxrel, BlockNumber pagesPerRange, BrinRevmap *revmap, Buffer *buffer, BlockNumber heapBlk, BrinTuple *tup, Size itemsz)
Definition: brin_pageops.c:343
BlockNumber bs_pagesPerRange
Definition: brin.c:52
void pfree(void *pointer)
Definition: mcxt.c:1057
BrinRevmap * bs_rmAccess
Definition: brin.c:54
size_t Size
Definition: c.h:474
int bs_numtuples
Definition: brin.c:50
BrinTuple * brin_form_tuple(BrinDesc *brdesc, BlockNumber blkno, BrinMemTuple *tuple, Size *size)
Definition: brin_tuple.c:88
BrinMemTuple * bs_dtuple
Definition: brin.c:56
BrinDesc * bs_bdesc
Definition: brin.c:55

◆ initialize_brin_buildstate()

static BrinBuildState * initialize_brin_buildstate ( Relation  idxRel,
BrinRevmap revmap,
BlockNumber  pagesPerRange 
)
static

Definition at line 1107 of file brin.c.

References brin_build_desc(), brin_memtuple_initialize(), brin_new_memtuple(), BrinBuildState::bs_bdesc, BrinBuildState::bs_currentInsertBuf, BrinBuildState::bs_currRangeStart, BrinBuildState::bs_dtuple, BrinBuildState::bs_irel, BrinBuildState::bs_numtuples, BrinBuildState::bs_pagesPerRange, BrinBuildState::bs_rmAccess, InvalidBuffer, and palloc().

Referenced by brinbuild(), and brinsummarize().

1109 {
1111 
1112  state = palloc(sizeof(BrinBuildState));
1113 
1114  state->bs_irel = idxRel;
1115  state->bs_numtuples = 0;
1117  state->bs_pagesPerRange = pagesPerRange;
1118  state->bs_currRangeStart = 0;
1119  state->bs_rmAccess = revmap;
1120  state->bs_bdesc = brin_build_desc(idxRel);
1121  state->bs_dtuple = brin_new_memtuple(state->bs_bdesc);
1122 
1124 
1125  return state;
1126 }
Buffer bs_currentInsertBuf
Definition: brin.c:51
#define InvalidBuffer
Definition: buf.h:25
BrinMemTuple * brin_new_memtuple(BrinDesc *brdesc)
Definition: brin_tuple.c:355
Relation bs_irel
Definition: brin.c:49
BlockNumber bs_currRangeStart
Definition: brin.c:53
BlockNumber bs_pagesPerRange
Definition: brin.c:52
BrinRevmap * bs_rmAccess
Definition: brin.c:54
BrinDesc * brin_build_desc(Relation rel)
Definition: brin.c:1019
Definition: regguts.h:298
int bs_numtuples
Definition: brin.c:50
void * palloc(Size size)
Definition: mcxt.c:950
BrinMemTuple * bs_dtuple
Definition: brin.c:56
BrinDesc * bs_bdesc
Definition: brin.c:55
BrinMemTuple * brin_memtuple_initialize(BrinMemTuple *dtuple, BrinDesc *brdesc)
Definition: brin_tuple.c:382

◆ summarize_range()

static void summarize_range ( IndexInfo indexInfo,
BrinBuildState state,
Relation  heapRel,
BlockNumber  heapBlk,
BlockNumber  heapNumBlks 
)
static

Definition at line 1177 of file brin.c.

References Assert, brin_can_do_samepage_update(), brin_copy_tuple(), brin_doinsert(), brin_doupdate(), brin_form_placeholder_tuple(), brin_form_tuple(), brin_free_tuple(), brinbuildCallback(), brinGetTupleForHeapBlock(), BrinBuildState::bs_bdesc, BrinBuildState::bs_currRangeStart, BrinBuildState::bs_irel, BrinBuildState::bs_pagesPerRange, BrinBuildState::bs_rmAccess, BUFFER_LOCK_SHARE, BUFFER_LOCK_UNLOCK, CHECK_FOR_INTERRUPTS, elog, ERROR, InvalidBuffer, LockBuffer(), Min, RelationGetNumberOfBlocks, ReleaseBuffer(), table_index_build_range_scan(), and union_tuples().

Referenced by brinsummarize().

1179 {
1180  Buffer phbuf;
1181  BrinTuple *phtup;
1182  Size phsz;
1183  OffsetNumber offset;
1184  BlockNumber scanNumBlks;
1185 
1186  /*
1187  * Insert the placeholder tuple
1188  */
1189  phbuf = InvalidBuffer;
1190  phtup = brin_form_placeholder_tuple(state->bs_bdesc, heapBlk, &phsz);
1191  offset = brin_doinsert(state->bs_irel, state->bs_pagesPerRange,
1192  state->bs_rmAccess, &phbuf,
1193  heapBlk, phtup, phsz);
1194 
1195  /*
1196  * Compute range end. We hold ShareUpdateExclusive lock on table, so it
1197  * cannot shrink concurrently (but it can grow).
1198  */
1199  Assert(heapBlk % state->bs_pagesPerRange == 0);
1200  if (heapBlk + state->bs_pagesPerRange > heapNumBlks)
1201  {
1202  /*
1203  * If we're asked to scan what we believe to be the final range on the
1204  * table (i.e. a range that might be partial) we need to recompute our
1205  * idea of what the latest page is after inserting the placeholder
1206  * tuple. Anyone that grows the table later will update the
1207  * placeholder tuple, so it doesn't matter that we won't scan these
1208  * pages ourselves. Careful: the table might have been extended
1209  * beyond the current range, so clamp our result.
1210  *
1211  * Fortunately, this should occur infrequently.
1212  */
1213  scanNumBlks = Min(RelationGetNumberOfBlocks(heapRel) - heapBlk,
1214  state->bs_pagesPerRange);
1215  }
1216  else
1217  {
1218  /* Easy case: range is known to be complete */
1219  scanNumBlks = state->bs_pagesPerRange;
1220  }
1221 
1222  /*
1223  * Execute the partial heap scan covering the heap blocks in the specified
1224  * page range, summarizing the heap tuples in it. This scan stops just
1225  * short of brinbuildCallback creating the new index entry.
1226  *
1227  * Note that it is critical we use the "any visible" mode of
1228  * table_index_build_range_scan here: otherwise, we would miss tuples
1229  * inserted by transactions that are still in progress, among other corner
1230  * cases.
1231  */
1232  state->bs_currRangeStart = heapBlk;
1233  table_index_build_range_scan(heapRel, state->bs_irel, indexInfo, false, true, false,
1234  heapBlk, scanNumBlks,
1235  brinbuildCallback, (void *) state, NULL);
1236 
1237  /*
1238  * Now we update the values obtained by the scan with the placeholder
1239  * tuple. We do this in a loop which only terminates if we're able to
1240  * update the placeholder tuple successfully; if we are not, this means
1241  * somebody else modified the placeholder tuple after we read it.
1242  */
1243  for (;;)
1244  {
1245  BrinTuple *newtup;
1246  Size newsize;
1247  bool didupdate;
1248  bool samepage;
1249 
1251 
1252  /*
1253  * Update the summary tuple and try to update.
1254  */
1255  newtup = brin_form_tuple(state->bs_bdesc,
1256  heapBlk, state->bs_dtuple, &newsize);
1257  samepage = brin_can_do_samepage_update(phbuf, phsz, newsize);
1258  didupdate =
1259  brin_doupdate(state->bs_irel, state->bs_pagesPerRange,
1260  state->bs_rmAccess, heapBlk, phbuf, offset,
1261  phtup, phsz, newtup, newsize, samepage);
1262  brin_free_tuple(phtup);
1263  brin_free_tuple(newtup);
1264 
1265  /* If the update succeeded, we're done. */
1266  if (didupdate)
1267  break;
1268 
1269  /*
1270  * If the update didn't work, it might be because somebody updated the
1271  * placeholder tuple concurrently. Extract the new version, union it
1272  * with the values we have from the scan, and start over. (There are
1273  * other reasons for the update to fail, but it's simple to treat them
1274  * the same.)
1275  */
1276  phtup = brinGetTupleForHeapBlock(state->bs_rmAccess, heapBlk, &phbuf,
1277  &offset, &phsz, BUFFER_LOCK_SHARE,
1278  NULL);
1279  /* the placeholder tuple must exist */
1280  if (phtup == NULL)
1281  elog(ERROR, "missing placeholder tuple");
1282  phtup = brin_copy_tuple(phtup, phsz, NULL, NULL);
1284 
1285  /* merge it into the tuple from the heap scan */
1286  union_tuples(state->bs_bdesc, state->bs_dtuple, phtup);
1287  }
1288 
1289  ReleaseBuffer(phbuf);
1290 }
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:96
BrinTuple * brin_copy_tuple(BrinTuple *tuple, Size len, BrinTuple *dest, Size *destsz)
Definition: brin_tuple.c:319
static void union_tuples(BrinDesc *bdesc, BrinMemTuple *a, BrinTuple *b)
Definition: brin.c:1421
BrinTuple * brinGetTupleForHeapBlock(BrinRevmap *revmap, BlockNumber heapBlk, Buffer *buf, OffsetNumber *off, Size *size, int mode, Snapshot snapshot)
Definition: brin_revmap.c:197
#define Min(x, y)
Definition: c.h:928
#define InvalidBuffer
Definition: buf.h:25
uint32 BlockNumber
Definition: block.h:31
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3513
bool brin_doupdate(Relation idxrel, BlockNumber pagesPerRange, BrinRevmap *revmap, BlockNumber heapBlk, Buffer oldbuf, OffsetNumber oldoff, const BrinTuple *origtup, Size origsz, const BrinTuple *newtup, Size newsz, bool samepage)
Definition: brin_pageops.c:54
Relation bs_irel
Definition: brin.c:49
BlockNumber bs_currRangeStart
Definition: brin.c:53
uint16 OffsetNumber
Definition: off.h:24
OffsetNumber brin_doinsert(Relation idxrel, BlockNumber pagesPerRange, BrinRevmap *revmap, Buffer *buffer, BlockNumber heapBlk, BrinTuple *tup, Size itemsz)
Definition: brin_pageops.c:343
BlockNumber bs_pagesPerRange
Definition: brin.c:52
#define ERROR
Definition: elog.h:43
static double table_index_build_range_scan(Relation table_rel, Relation index_rel, struct IndexInfo *index_info, bool allow_sync, bool anyvisible, bool progress, BlockNumber start_blockno, BlockNumber numblocks, IndexBuildCallback callback, void *callback_state, TableScanDesc scan)
Definition: tableam.h:1585
BrinRevmap * bs_rmAccess
Definition: brin.c:54
static void brinbuildCallback(Relation index, ItemPointer tid, Datum *values, bool *isnull, bool tupleIsAlive, void *brstate)
Definition: brin.c:606
bool brin_can_do_samepage_update(Buffer buffer, Size origsz, Size newsz)
Definition: brin_pageops.c:324
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3752
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:211
void brin_free_tuple(BrinTuple *tuple)
Definition: brin_tuple.c:306
#define Assert(condition)
Definition: c.h:746
size_t Size
Definition: c.h:474
BrinTuple * brin_form_tuple(BrinDesc *brdesc, BlockNumber blkno, BrinMemTuple *tuple, Size *size)
Definition: brin_tuple.c:88
#define elog(elevel,...)
Definition: elog.h:214
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:97
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
BrinMemTuple * bs_dtuple
Definition: brin.c:56
BrinDesc * bs_bdesc
Definition: brin.c:55
int Buffer
Definition: buf.h:23
BrinTuple * brin_form_placeholder_tuple(BrinDesc *brdesc, BlockNumber blkno, Size *size)
Definition: brin_tuple.c:261

◆ terminate_brin_buildstate()

static void terminate_brin_buildstate ( BrinBuildState state)
static

Definition at line 1132 of file brin.c.

References brin_free_desc(), BrinBuildState::bs_bdesc, BrinBuildState::bs_currentInsertBuf, BrinBuildState::bs_dtuple, BrinBuildState::bs_irel, BufferGetBlockNumber(), BufferGetPage, BufferIsInvalid, FreeSpaceMapVacuumRange(), PageGetFreeSpace(), pfree(), RecordPageWithFreeSpace(), and ReleaseBuffer().

Referenced by brinbuild(), and brinsummarize().

1133 {
1134  /*
1135  * Release the last index buffer used. We might as well ensure that
1136  * whatever free space remains in that page is available in FSM, too.
1137  */
1138  if (!BufferIsInvalid(state->bs_currentInsertBuf))
1139  {
1140  Page page;
1141  Size freespace;
1142  BlockNumber blk;
1143 
1144  page = BufferGetPage(state->bs_currentInsertBuf);
1145  freespace = PageGetFreeSpace(page);
1148  RecordPageWithFreeSpace(state->bs_irel, blk, freespace);
1149  FreeSpaceMapVacuumRange(state->bs_irel, blk, blk + 1);
1150  }
1151 
1152  brin_free_desc(state->bs_bdesc);
1153  pfree(state->bs_dtuple);
1154  pfree(state);
1155 }
void brin_free_desc(BrinDesc *bdesc)
Definition: brin.c:1074
void RecordPageWithFreeSpace(Relation rel, BlockNumber heapBlk, Size spaceAvail)
Definition: freespace.c:181
Buffer bs_currentInsertBuf
Definition: brin.c:51
uint32 BlockNumber
Definition: block.h:31
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3513
Relation bs_irel
Definition: brin.c:49
Size PageGetFreeSpace(Page page)
Definition: bufpage.c:790
void pfree(void *pointer)
Definition: mcxt.c:1057
#define BufferIsInvalid(buffer)
Definition: buf.h:31
#define BufferGetPage(buffer)
Definition: bufmgr.h:169
size_t Size
Definition: c.h:474
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition: bufmgr.c:2663
BrinMemTuple * bs_dtuple
Definition: brin.c:56
BrinDesc * bs_bdesc
Definition: brin.c:55
void FreeSpaceMapVacuumRange(Relation rel, BlockNumber start, BlockNumber end)
Definition: freespace.c:354
Pointer Page
Definition: bufpage.h:78

◆ union_tuples()

static void union_tuples ( BrinDesc bdesc,
BrinMemTuple a,
BrinTuple b 
)
static

Definition at line 1421 of file brin.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, BrinDesc::bd_index, BrinDesc::bd_tupdesc, brin_deform_tuple(), BRIN_PROCNUM_UNION, BrinMemTuple::bt_columns, CurrentMemoryContext, FunctionCall3Coll(), index_getprocinfo(), MemoryContextDelete(), MemoryContextSwitchTo(), TupleDescData::natts, PointerGetDatum, and RelationData::rd_indcollation.

Referenced by summarize_range().

1422 {
1423  int keyno;
1424  BrinMemTuple *db;
1425  MemoryContext cxt;
1426  MemoryContext oldcxt;
1427 
1428  /* Use our own memory context to avoid retail pfree */
1430  "brin union",
1432  oldcxt = MemoryContextSwitchTo(cxt);
1433  db = brin_deform_tuple(bdesc, b, NULL);
1434  MemoryContextSwitchTo(oldcxt);
1435 
1436  for (keyno = 0; keyno < bdesc->bd_tupdesc->natts; keyno++)
1437  {
1438  FmgrInfo *unionFn;
1439  BrinValues *col_a = &a->bt_columns[keyno];
1440  BrinValues *col_b = &db->bt_columns[keyno];
1441 
1442  unionFn = index_getprocinfo(bdesc->bd_index, keyno + 1,
1444  FunctionCall3Coll(unionFn,
1445  bdesc->bd_index->rd_indcollation[keyno],
1446  PointerGetDatum(bdesc),
1447  PointerGetDatum(col_a),
1448  PointerGetDatum(col_b));
1449  }
1450 
1451  MemoryContextDelete(cxt);
1452 }
Definition: fmgr.h:56
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:212
#define AllocSetContextCreate
Definition: memutils.h:170
FmgrInfo * index_getprocinfo(Relation irel, AttrNumber attnum, uint16 procnum)
Definition: indexam.c:801
#define PointerGetDatum(X)
Definition: postgres.h:556
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
BrinMemTuple * brin_deform_tuple(BrinDesc *brdesc, BrinTuple *tuple, BrinMemTuple *dMemtuple)
Definition: brin_tuple.c:420
Oid * rd_indcollation
Definition: rel.h:199
Relation bd_index
Definition: brin_internal.h:47
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
BrinValues bt_columns[FLEXIBLE_ARRAY_MEMBER]
Definition: brin_tuple.h:46
TupleDesc bd_tupdesc
Definition: brin_internal.h:50
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
Datum FunctionCall3Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2, Datum arg3)
Definition: fmgr.c:1174
#define BRIN_PROCNUM_UNION
Definition: brin_internal.h:70