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/datum.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)
 
static bool add_values_to_range (Relation idxRel, BrinDesc *bdesc, BrinMemTuple *dtup, Datum *values, bool *nulls)
 
static bool check_null_keys (BrinValues *bval, ScanKey *nullkeys, int nnullkeys)
 
Datum brinhandler (PG_FUNCTION_ARGS)
 
bool brininsert (Relation idxRel, Datum *values, bool *nulls, ItemPointer heaptid, Relation heapRel, IndexUniqueCheck checkUnique, bool indexUnchanged, 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

Definition at line 70 of file brin.c.

Typedef Documentation

◆ BrinBuildState

◆ BrinOpaque

typedef struct BrinOpaque BrinOpaque

Function Documentation

◆ add_values_to_range()

static bool add_values_to_range ( Relation  idxRel,
BrinDesc bdesc,
BrinMemTuple dtup,
Datum values,
bool nulls 
)
static

Definition at line 1669 of file brin.c.

1671 {
1672  int keyno;
1673  bool modified = false;
1674 
1675  /*
1676  * Compare the key values of the new tuple to the stored index values; our
1677  * deformed tuple will get updated if the new tuple doesn't fit the
1678  * original range (note this means we can't break out of the loop early).
1679  * Make a note of whether this happens, so that we know to insert the
1680  * modified tuple later.
1681  */
1682  for (keyno = 0; keyno < bdesc->bd_tupdesc->natts; keyno++)
1683  {
1684  Datum result;
1685  BrinValues *bval;
1686  FmgrInfo *addValue;
1687 
1688  bval = &dtup->bt_columns[keyno];
1689 
1690  if (bdesc->bd_info[keyno]->oi_regular_nulls && nulls[keyno])
1691  {
1692  /*
1693  * If the new value is null, we record that we saw it if it's the
1694  * first one; otherwise, there's nothing to do.
1695  */
1696  if (!bval->bv_hasnulls)
1697  {
1698  bval->bv_hasnulls = true;
1699  modified = true;
1700  }
1701 
1702  continue;
1703  }
1704 
1705  addValue = index_getprocinfo(idxRel, keyno + 1,
1707  result = FunctionCall4Coll(addValue,
1708  idxRel->rd_indcollation[keyno],
1709  PointerGetDatum(bdesc),
1710  PointerGetDatum(bval),
1711  values[keyno],
1712  nulls[keyno]);
1713  /* if that returned true, we need to insert the updated tuple */
1714  modified |= DatumGetBool(result);
1715  }
1716 
1717  return modified;
1718 }
static Datum values[MAXATTR]
Definition: bootstrap.c:156
#define BRIN_PROCNUM_ADDVALUE
Definition: brin_internal.h:71
Datum FunctionCall4Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition: fmgr.c:1195
FmgrInfo * index_getprocinfo(Relation irel, AttrNumber attnum, uint16 procnum)
Definition: indexam.c:803
uintptr_t Datum
Definition: postgres.h:411
#define DatumGetBool(X)
Definition: postgres.h:437
#define PointerGetDatum(X)
Definition: postgres.h:600
TupleDesc bd_tupdesc
Definition: brin_internal.h:53
BrinOpcInfo * bd_info[FLEXIBLE_ARRAY_MEMBER]
Definition: brin_internal.h:62
BrinValues bt_columns[FLEXIBLE_ARRAY_MEMBER]
Definition: brin_tuple.h:54
bool oi_regular_nulls
Definition: brin_internal.h:31
bool bv_hasnulls
Definition: brin_tuple.h:32
Definition: fmgr.h:57
Oid * rd_indcollation
Definition: rel.h:213

References BrinDesc::bd_info, BrinDesc::bd_tupdesc, BRIN_PROCNUM_ADDVALUE, BrinMemTuple::bt_columns, BrinValues::bv_hasnulls, DatumGetBool, FunctionCall4Coll(), index_getprocinfo(), TupleDescData::natts, BrinOpcInfo::oi_regular_nulls, PointerGetDatum, RelationData::rd_indcollation, and values.

Referenced by brinbuildCallback(), and brininsert().

◆ brin_build_desc()

BrinDesc* brin_build_desc ( Relation  rel)

Definition at line 1161 of file brin.c.

1162 {
1163  BrinOpcInfo **opcinfo;
1164  BrinDesc *bdesc;
1165  TupleDesc tupdesc;
1166  int totalstored = 0;
1167  int keyno;
1168  long totalsize;
1169  MemoryContext cxt;
1170  MemoryContext oldcxt;
1171 
1173  "brin desc cxt",
1175  oldcxt = MemoryContextSwitchTo(cxt);
1176  tupdesc = RelationGetDescr(rel);
1177 
1178  /*
1179  * Obtain BrinOpcInfo for each indexed column. While at it, accumulate
1180  * the number of columns stored, since the number is opclass-defined.
1181  */
1182  opcinfo = (BrinOpcInfo **) palloc(sizeof(BrinOpcInfo *) * tupdesc->natts);
1183  for (keyno = 0; keyno < tupdesc->natts; keyno++)
1184  {
1185  FmgrInfo *opcInfoFn;
1186  Form_pg_attribute attr = TupleDescAttr(tupdesc, keyno);
1187 
1188  opcInfoFn = index_getprocinfo(rel, keyno + 1, BRIN_PROCNUM_OPCINFO);
1189 
1190  opcinfo[keyno] = (BrinOpcInfo *)
1191  DatumGetPointer(FunctionCall1(opcInfoFn, attr->atttypid));
1192  totalstored += opcinfo[keyno]->oi_nstored;
1193  }
1194 
1195  /* Allocate our result struct and fill it in */
1196  totalsize = offsetof(BrinDesc, bd_info) +
1197  sizeof(BrinOpcInfo *) * tupdesc->natts;
1198 
1199  bdesc = palloc(totalsize);
1200  bdesc->bd_context = cxt;
1201  bdesc->bd_index = rel;
1202  bdesc->bd_tupdesc = tupdesc;
1203  bdesc->bd_disktdesc = NULL; /* generated lazily */
1204  bdesc->bd_totalstored = totalstored;
1205 
1206  for (keyno = 0; keyno < tupdesc->natts; keyno++)
1207  bdesc->bd_info[keyno] = opcinfo[keyno];
1208  pfree(opcinfo);
1209 
1210  MemoryContextSwitchTo(oldcxt);
1211 
1212  return bdesc;
1213 }
#define BRIN_PROCNUM_OPCINFO
Definition: brin_internal.h:70
#define offsetof(type, field)
Definition: c.h:727
#define FunctionCall1(flinfo, arg1)
Definition: fmgr.h:649
void pfree(void *pointer)
Definition: mcxt.c:1169
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
void * palloc(Size size)
Definition: mcxt.c:1062
#define AllocSetContextCreate
Definition: memutils.h:173
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:205
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
#define DatumGetPointer(X)
Definition: postgres.h:593
#define RelationGetDescr(relation)
Definition: rel.h:504
int bd_totalstored
Definition: brin_internal.h:59
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
#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, offsetof, BrinOpcInfo::oi_nstored, palloc(), pfree(), RelationGetDescr, and TupleDescAttr.

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

◆ brin_desummarize_range()

Datum brin_desummarize_range ( PG_FUNCTION_ARGS  )

Definition at line 1080 of file brin.c.

1081 {
1082  Oid indexoid = PG_GETARG_OID(0);
1083  int64 heapBlk64 = PG_GETARG_INT64(1);
1084  BlockNumber heapBlk;
1085  Oid heapoid;
1086  Relation heapRel;
1087  Relation indexRel;
1088  bool done;
1089 
1090  if (RecoveryInProgress())
1091  ereport(ERROR,
1092  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1093  errmsg("recovery is in progress"),
1094  errhint("BRIN control functions cannot be executed during recovery.")));
1095 
1096  if (heapBlk64 > MaxBlockNumber || heapBlk64 < 0)
1097  {
1098  char *blk = psprintf(INT64_FORMAT, heapBlk64);
1099 
1100  ereport(ERROR,
1101  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
1102  errmsg("block number out of range: %s", blk)));
1103  }
1104  heapBlk = (BlockNumber) heapBlk64;
1105 
1106  /*
1107  * We must lock table before index to avoid deadlocks. However, if the
1108  * passed indexoid isn't an index then IndexGetRelation() will fail.
1109  * Rather than emitting a not-very-helpful error message, postpone
1110  * complaining, expecting that the is-it-an-index test below will fail.
1111  */
1112  heapoid = IndexGetRelation(indexoid, true);
1113  if (OidIsValid(heapoid))
1114  heapRel = table_open(heapoid, ShareUpdateExclusiveLock);
1115  else
1116  heapRel = NULL;
1117 
1118  indexRel = index_open(indexoid, ShareUpdateExclusiveLock);
1119 
1120  /* Must be a BRIN index */
1121  if (indexRel->rd_rel->relkind != RELKIND_INDEX ||
1122  indexRel->rd_rel->relam != BRIN_AM_OID)
1123  ereport(ERROR,
1124  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1125  errmsg("\"%s\" is not a BRIN index",
1126  RelationGetRelationName(indexRel))));
1127 
1128  /* User must own the index (comparable to privileges needed for VACUUM) */
1129  if (!pg_class_ownercheck(indexoid, GetUserId()))
1131  RelationGetRelationName(indexRel));
1132 
1133  /*
1134  * Since we did the IndexGetRelation call above without any lock, it's
1135  * barely possible that a race against an index drop/recreation could have
1136  * netted us the wrong table. Recheck.
1137  */
1138  if (heapRel == NULL || heapoid != IndexGetRelation(indexoid, false))
1139  ereport(ERROR,
1141  errmsg("could not open parent table of index \"%s\"",
1142  RelationGetRelationName(indexRel))));
1143 
1144  /* the revmap does the hard work */
1145  do
1146  {
1147  done = brinRevmapDesummarizeRange(indexRel, heapBlk);
1148  }
1149  while (!done);
1150 
1153 
1154  PG_RETURN_VOID();
1155 }
@ ACLCHECK_NOT_OWNER
Definition: acl.h:181
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4820
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3308
uint32 BlockNumber
Definition: block.h:31
#define MaxBlockNumber
Definition: block.h:35
bool brinRevmapDesummarizeRange(Relation idxrel, BlockNumber heapBlk)
Definition: brin_revmap.c:328
#define INT64_FORMAT
Definition: c.h:483
#define OidIsValid(objectId)
Definition: c.h:710
int errhint(const char *fmt,...)
Definition: elog.c:1151
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define ERROR
Definition: elog.h:33
#define ereport(elevel,...)
Definition: elog.h:143
#define PG_RETURN_VOID()
Definition: fmgr.h:349
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
#define PG_GETARG_INT64(n)
Definition: fmgr.h:283
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3506
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
Oid GetUserId(void)
Definition: miscinit.c:495
@ OBJECT_INDEX
Definition: parsenodes.h:1809
#define ERRCODE_UNDEFINED_TABLE
Definition: pgbench.c:79
unsigned int Oid
Definition: postgres_ext.h:31
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
#define RelationGetRelationName(relation)
Definition: rel.h:512
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
Form_pg_class rd_rel
Definition: rel.h:109
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
bool RecoveryInProgress(void)
Definition: xlog.c:8404

References aclcheck_error(), ACLCHECK_NOT_OWNER, brinRevmapDesummarizeRange(), ereport, errcode(), ERRCODE_UNDEFINED_TABLE, 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().

◆ brin_free_desc()

void brin_free_desc ( BrinDesc bdesc)

Definition at line 1216 of file brin.c.

1217 {
1218  /* make sure the tupdesc is still valid */
1219  Assert(bdesc->bd_tupdesc->tdrefcount >= 1);
1220  /* no need for retail pfree */
1222 }
Assert(fmt[strlen(fmt) - 1] !='\n')
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
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().

◆ brin_summarize_new_values()

Datum brin_summarize_new_values ( PG_FUNCTION_ARGS  )

Definition at line 988 of file brin.c.

989 {
990  Datum relation = PG_GETARG_DATUM(0);
991 
993  relation,
995 }
Datum brin_summarize_range(PG_FUNCTION_ARGS)
Definition: brin.c:1003
#define BRIN_ALL_BLOCKRANGES
Definition: brin.c:70
Datum Int64GetDatum(int64 X)
Definition: fmgr.c:1697
#define DirectFunctionCall2(func, arg1, arg2)
Definition: fmgr.h:633
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:268

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

◆ brin_summarize_range()

Datum brin_summarize_range ( PG_FUNCTION_ARGS  )

Definition at line 1003 of file brin.c.

1004 {
1005  Oid indexoid = PG_GETARG_OID(0);
1006  int64 heapBlk64 = PG_GETARG_INT64(1);
1007  BlockNumber heapBlk;
1008  Oid heapoid;
1009  Relation indexRel;
1010  Relation heapRel;
1011  double numSummarized = 0;
1012 
1013  if (RecoveryInProgress())
1014  ereport(ERROR,
1015  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1016  errmsg("recovery is in progress"),
1017  errhint("BRIN control functions cannot be executed during recovery.")));
1018 
1019  if (heapBlk64 > BRIN_ALL_BLOCKRANGES || heapBlk64 < 0)
1020  {
1021  char *blk = psprintf(INT64_FORMAT, heapBlk64);
1022 
1023  ereport(ERROR,
1024  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
1025  errmsg("block number out of range: %s", blk)));
1026  }
1027  heapBlk = (BlockNumber) heapBlk64;
1028 
1029  /*
1030  * We must lock table before index to avoid deadlocks. However, if the
1031  * passed indexoid isn't an index then IndexGetRelation() will fail.
1032  * Rather than emitting a not-very-helpful error message, postpone
1033  * complaining, expecting that the is-it-an-index test below will fail.
1034  */
1035  heapoid = IndexGetRelation(indexoid, true);
1036  if (OidIsValid(heapoid))
1037  heapRel = table_open(heapoid, ShareUpdateExclusiveLock);
1038  else
1039  heapRel = NULL;
1040 
1041  indexRel = index_open(indexoid, ShareUpdateExclusiveLock);
1042 
1043  /* Must be a BRIN index */
1044  if (indexRel->rd_rel->relkind != RELKIND_INDEX ||
1045  indexRel->rd_rel->relam != BRIN_AM_OID)
1046  ereport(ERROR,
1047  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1048  errmsg("\"%s\" is not a BRIN index",
1049  RelationGetRelationName(indexRel))));
1050 
1051  /* User must own the index (comparable to privileges needed for VACUUM) */
1052  if (!pg_class_ownercheck(indexoid, GetUserId()))
1054  RelationGetRelationName(indexRel));
1055 
1056  /*
1057  * Since we did the IndexGetRelation call above without any lock, it's
1058  * barely possible that a race against an index drop/recreation could have
1059  * netted us the wrong table. Recheck.
1060  */
1061  if (heapRel == NULL || heapoid != IndexGetRelation(indexoid, false))
1062  ereport(ERROR,
1064  errmsg("could not open parent table of index \"%s\"",
1065  RelationGetRelationName(indexRel))));
1066 
1067  /* OK, do it */
1068  brinsummarize(indexRel, heapRel, heapBlk, true, &numSummarized, NULL);
1069 
1072 
1073  PG_RETURN_INT32((int32) numSummarized);
1074 }
static void brinsummarize(Relation index, Relation heapRel, BlockNumber pageRange, bool include_partial, double *numSummarized, double *numExisting)
Definition: brin.c:1444
signed int int32
Definition: c.h:429
#define PG_RETURN_INT32(x)
Definition: fmgr.h:354

References aclcheck_error(), ACLCHECK_NOT_OWNER, BRIN_ALL_BLOCKRANGES, brinsummarize(), ereport, errcode(), ERRCODE_UNDEFINED_TABLE, 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().

◆ brin_vacuum_scan()

static void brin_vacuum_scan ( Relation  idxrel,
BufferAccessStrategy  strategy 
)
static

Definition at line 1636 of file brin.c.

1637 {
1638  BlockNumber nblocks;
1639  BlockNumber blkno;
1640 
1641  /*
1642  * Scan the index in physical order, and clean up any possible mess in
1643  * each page.
1644  */
1645  nblocks = RelationGetNumberOfBlocks(idxrel);
1646  for (blkno = 0; blkno < nblocks; blkno++)
1647  {
1648  Buffer buf;
1649 
1651 
1652  buf = ReadBufferExtended(idxrel, MAIN_FORKNUM, blkno,
1653  RBM_NORMAL, strategy);
1654 
1655  brin_page_cleanup(idxrel, buf);
1656 
1657  ReleaseBuffer(buf);
1658  }
1659 
1660  /*
1661  * Update all upper pages in the index's FSM, as well. This ensures not
1662  * only that we propagate leaf-page FSM updates made by brin_page_cleanup,
1663  * but also that any pre-existing damage or out-of-dateness is repaired.
1664  */
1665  FreeSpaceMapVacuum(idxrel);
1666 }
void brin_page_cleanup(Relation idxrel, Buffer buf)
Definition: brin_pageops.c:620
int Buffer
Definition: buf.h:23
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3757
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:741
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:212
@ RBM_NORMAL
Definition: bufmgr.h:39
void FreeSpaceMapVacuum(Relation rel)
Definition: freespace.c:333
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
static char * buf
Definition: pg_test_fsync.c:70
@ MAIN_FORKNUM
Definition: relpath.h:43

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

Referenced by brinvacuumcleanup().

◆ brinbeginscan()

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

Definition at line 326 of file brin.c.

327 {
328  IndexScanDesc scan;
329  BrinOpaque *opaque;
330 
331  scan = RelationGetIndexScan(r, nkeys, norderbys);
332 
333  opaque = (BrinOpaque *) palloc(sizeof(BrinOpaque));
334  opaque->bo_rmAccess = brinRevmapInitialize(r, &opaque->bo_pagesPerRange,
335  scan->xs_snapshot);
336  opaque->bo_bdesc = brin_build_desc(r);
337  scan->opaque = opaque;
338 
339  return scan;
340 }
BrinDesc * brin_build_desc(Relation rel)
Definition: brin.c:1161
BrinRevmap * brinRevmapInitialize(Relation idxrel, BlockNumber *pagesPerRange, Snapshot snapshot)
Definition: brin_revmap.c:71
IndexScanDesc RelationGetIndexScan(Relation indexRelation, int nkeys, int norderbys)
Definition: genam.c:81
BlockNumber bo_pagesPerRange
Definition: brin.c:65
BrinDesc * bo_bdesc
Definition: brin.c:67
BrinRevmap * bo_rmAccess
Definition: brin.c:66
struct SnapshotData * xs_snapshot
Definition: relscan.h:119

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().

◆ brinbuild()

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

Definition at line 811 of file brin.c.

812 {
813  IndexBuildResult *result;
814  double reltuples;
815  double idxtuples;
816  BrinRevmap *revmap;
818  Buffer meta;
819  BlockNumber pagesPerRange;
820 
821  /*
822  * We expect to be called exactly once for any index relation.
823  */
825  elog(ERROR, "index \"%s\" already contains data",
827 
828  /*
829  * Critical section not required, because on error the creation of the
830  * whole relation will be rolled back.
831  */
832 
833  meta = ReadBuffer(index, P_NEW);
836 
839  MarkBufferDirty(meta);
840 
841  if (RelationNeedsWAL(index))
842  {
843  xl_brin_createidx xlrec;
844  XLogRecPtr recptr;
845  Page page;
846 
849 
850  XLogBeginInsert();
851  XLogRegisterData((char *) &xlrec, SizeOfBrinCreateIdx);
853 
854  recptr = XLogInsert(RM_BRIN_ID, XLOG_BRIN_CREATE_INDEX);
855 
856  page = BufferGetPage(meta);
857  PageSetLSN(page, recptr);
858  }
859 
860  UnlockReleaseBuffer(meta);
861 
862  /*
863  * Initialize our state, including the deformed tuple state.
864  */
865  revmap = brinRevmapInitialize(index, &pagesPerRange, NULL);
866  state = initialize_brin_buildstate(index, revmap, pagesPerRange);
867 
868  /*
869  * Now scan the relation. No syncscan allowed here because we want the
870  * heap blocks in physical order.
871  */
872  reltuples = table_index_build_scan(heap, index, indexInfo, false, true,
873  brinbuildCallback, (void *) state, NULL);
874 
875  /* process the final batch */
877 
878  /* release resources */
879  idxtuples = state->bs_numtuples;
880  brinRevmapTerminate(state->bs_rmAccess);
882 
883  /*
884  * Return statistics
885  */
886  result = (IndexBuildResult *) palloc(sizeof(IndexBuildResult));
887 
888  result->heap_tuples = reltuples;
889  result->index_tuples = idxtuples;
890 
891  return result;
892 }
static BrinBuildState * initialize_brin_buildstate(Relation idxRel, BrinRevmap *revmap, BlockNumber pagesPerRange)
Definition: brin.c:1249
static void terminate_brin_buildstate(BrinBuildState *state)
Definition: brin.c:1272
static void form_and_insert_tuple(BrinBuildState *state)
Definition: brin.c:1541
static void brinbuildCallback(Relation index, ItemPointer tid, Datum *values, bool *isnull, bool tupleIsAlive, void *brstate)
Definition: brin.c:766
#define BrinGetPagesPerRange(relation)
Definition: brin.h:39
#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:487
void brinRevmapTerminate(BrinRevmap *revmap)
Definition: brin_revmap.c:103
#define SizeOfBrinCreateIdx
Definition: brin_xlog.h:55
#define XLOG_BRIN_CREATE_INDEX
Definition: brin_xlog.h:31
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition: bufmgr.c:2748
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3780
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1565
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3996
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:694
#define P_NEW
Definition: bufmgr.h:91
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:98
#define BufferGetPage(buffer)
Definition: bufmgr.h:169
Pointer Page
Definition: bufpage.h:78
#define PageSetLSN(page, lsn)
Definition: bufpage.h:367
#define elog(elevel,...)
Definition: elog.h:218
#define RelationNeedsWAL(relation)
Definition: rel.h:602
double heap_tuples
Definition: genam.h:32
double index_tuples
Definition: genam.h:33
Definition: type.h:90
Definition: regguts.h:318
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:1747
uint64 XLogRecPtr
Definition: xlogdefs.h:21
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:429
void XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Definition: xloginsert.c:229
void XLogBeginInsert(void)
Definition: xloginsert.c:136
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:337
#define REGBUF_STANDARD
Definition: xloginsert.h:34
#define REGBUF_WILL_INIT
Definition: xloginsert.h:33

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().

◆ brinbuildCallback()

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

Definition at line 766 of file brin.c.

772 {
773  BrinBuildState *state = (BrinBuildState *) brstate;
774  BlockNumber thisblock;
775 
776  thisblock = ItemPointerGetBlockNumber(tid);
777 
778  /*
779  * If we're in a block that belongs to a future range, summarize what
780  * we've got and start afresh. Note the scan might have skipped many
781  * pages, if they were devoid of live tuples; make sure to insert index
782  * tuples for those too.
783  */
784  while (thisblock > state->bs_currRangeStart + state->bs_pagesPerRange - 1)
785  {
786 
787  BRIN_elog((DEBUG2,
788  "brinbuildCallback: completed a range: %u--%u",
789  state->bs_currRangeStart,
790  state->bs_currRangeStart + state->bs_pagesPerRange));
791 
792  /* create the index tuple and insert it */
794 
795  /* set state to correspond to the next range */
796  state->bs_currRangeStart += state->bs_pagesPerRange;
797 
798  /* re-initialize state for it */
799  brin_memtuple_initialize(state->bs_dtuple, state->bs_bdesc);
800  }
801 
802  /* Accumulate the current tuple into the running state */
803  (void) add_values_to_range(index, state->bs_bdesc, state->bs_dtuple,
804  values, isnull);
805 }
static bool add_values_to_range(Relation idxRel, BrinDesc *bdesc, BrinMemTuple *dtup, Datum *values, bool *nulls)
Definition: brin.c:1669
#define BRIN_elog(args)
Definition: brin_internal.h:85
BrinMemTuple * brin_memtuple_initialize(BrinMemTuple *dtuple, BrinDesc *brdesc)
Definition: brin_tuple.c:506
#define DEBUG2
Definition: elog.h:23
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98

References add_values_to_range(), BRIN_elog, brin_memtuple_initialize(), DEBUG2, form_and_insert_tuple(), ItemPointerGetBlockNumber, and values.

Referenced by brinbuild(), and summarize_range().

◆ brinbuildempty()

void brinbuildempty ( Relation  index)

Definition at line 895 of file brin.c.

896 {
897  Buffer metabuf;
898 
899  /* An empty BRIN index has a metapage only. */
900  metabuf =
903 
904  /* Initialize and xlog metabuffer. */
908  MarkBufferDirty(metabuf);
909  log_newpage_buffer(metabuf, true);
911 
912  UnlockReleaseBuffer(metabuf);
913 }
#define START_CRIT_SECTION()
Definition: miscadmin.h:147
#define END_CRIT_SECTION()
Definition: miscadmin.h:149
@ INIT_FORKNUM
Definition: relpath.h:46
XLogRecPtr log_newpage_buffer(Buffer buffer, bool page_std)
Definition: xloginsert.c:1144

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().

◆ brinbulkdelete()

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

Definition at line 925 of file brin.c.

927 {
928  /* allocate stats if first time through, else re-use existing struct */
929  if (stats == NULL)
931 
932  return stats;
933 }
void * palloc0(Size size)
Definition: mcxt.c:1093

References palloc0().

Referenced by brinhandler().

◆ brinendscan()

void brinendscan ( IndexScanDesc  scan)

Definition at line 749 of file brin.c.

750 {
751  BrinOpaque *opaque = (BrinOpaque *) scan->opaque;
752 
754  brin_free_desc(opaque->bo_bdesc);
755  pfree(opaque);
756 }
void brin_free_desc(BrinDesc *bdesc)
Definition: brin.c:1216

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

356 {
357  Relation idxRel = scan->indexRelation;
359  BrinDesc *bdesc;
360  Oid heapOid;
361  Relation heapRel;
362  BrinOpaque *opaque;
363  BlockNumber nblocks;
364  BlockNumber heapBlk;
365  int totalpages = 0;
366  FmgrInfo *consistentFn;
367  MemoryContext oldcxt;
368  MemoryContext perRangeCxt;
369  BrinMemTuple *dtup;
370  BrinTuple *btup = NULL;
371  Size btupsz = 0;
372  ScanKey **keys,
373  **nullkeys;
374  int *nkeys,
375  *nnullkeys;
376  int keyno;
377  char *ptr;
378  Size len;
379  char *tmp PG_USED_FOR_ASSERTS_ONLY;
380 
381  opaque = (BrinOpaque *) scan->opaque;
382  bdesc = opaque->bo_bdesc;
383  pgstat_count_index_scan(idxRel);
384 
385  /*
386  * We need to know the size of the table so that we know how long to
387  * iterate on the revmap.
388  */
389  heapOid = IndexGetRelation(RelationGetRelid(idxRel), false);
390  heapRel = table_open(heapOid, AccessShareLock);
391  nblocks = RelationGetNumberOfBlocks(heapRel);
392  table_close(heapRel, AccessShareLock);
393 
394  /*
395  * Make room for the consistent support procedures of indexed columns. We
396  * don't look them up here; we do that lazily the first time we see a scan
397  * key reference each of them. We rely on zeroing fn_oid to InvalidOid.
398  */
399  consistentFn = palloc0(sizeof(FmgrInfo) * bdesc->bd_tupdesc->natts);
400 
401  /*
402  * Make room for per-attribute lists of scan keys that we'll pass to the
403  * consistent support procedure. We don't know which attributes have scan
404  * keys, so we allocate space for all attributes. That may use more memory
405  * but it's probably cheaper than determining which attributes are used.
406  *
407  * We keep null and regular keys separate, so that we can pass just the
408  * regular keys to the consistent function easily.
409  *
410  * To reduce the allocation overhead, we allocate one big chunk and then
411  * carve it into smaller arrays ourselves. All the pieces have exactly the
412  * same lifetime, so that's OK.
413  *
414  * XXX The widest index can have 32 attributes, so the amount of wasted
415  * memory is negligible. We could invent a more compact approach (with
416  * just space for used attributes) but that would make the matching more
417  * complex so it's not a good trade-off.
418  */
419  len =
420  MAXALIGN(sizeof(ScanKey *) * bdesc->bd_tupdesc->natts) + /* regular keys */
421  MAXALIGN(sizeof(ScanKey) * scan->numberOfKeys) * bdesc->bd_tupdesc->natts +
422  MAXALIGN(sizeof(int) * bdesc->bd_tupdesc->natts) +
423  MAXALIGN(sizeof(ScanKey *) * bdesc->bd_tupdesc->natts) + /* NULL keys */
424  MAXALIGN(sizeof(ScanKey) * scan->numberOfKeys) * bdesc->bd_tupdesc->natts +
425  MAXALIGN(sizeof(int) * bdesc->bd_tupdesc->natts);
426 
427  ptr = palloc(len);
428  tmp = ptr;
429 
430  keys = (ScanKey **) ptr;
431  ptr += MAXALIGN(sizeof(ScanKey *) * bdesc->bd_tupdesc->natts);
432 
433  nullkeys = (ScanKey **) ptr;
434  ptr += MAXALIGN(sizeof(ScanKey *) * bdesc->bd_tupdesc->natts);
435 
436  nkeys = (int *) ptr;
437  ptr += MAXALIGN(sizeof(int) * bdesc->bd_tupdesc->natts);
438 
439  nnullkeys = (int *) ptr;
440  ptr += MAXALIGN(sizeof(int) * bdesc->bd_tupdesc->natts);
441 
442  for (int i = 0; i < bdesc->bd_tupdesc->natts; i++)
443  {
444  keys[i] = (ScanKey *) ptr;
445  ptr += MAXALIGN(sizeof(ScanKey) * scan->numberOfKeys);
446 
447  nullkeys[i] = (ScanKey *) ptr;
448  ptr += MAXALIGN(sizeof(ScanKey) * scan->numberOfKeys);
449  }
450 
451  Assert(tmp + len == ptr);
452 
453  /* zero the number of keys */
454  memset(nkeys, 0, sizeof(int) * bdesc->bd_tupdesc->natts);
455  memset(nnullkeys, 0, sizeof(int) * bdesc->bd_tupdesc->natts);
456 
457  /* Preprocess the scan keys - split them into per-attribute arrays. */
458  for (keyno = 0; keyno < scan->numberOfKeys; keyno++)
459  {
460  ScanKey key = &scan->keyData[keyno];
461  AttrNumber keyattno = key->sk_attno;
462 
463  /*
464  * The collation of the scan key must match the collation used in the
465  * index column (but only if the search is not IS NULL/ IS NOT NULL).
466  * Otherwise we shouldn't be using this index ...
467  */
468  Assert((key->sk_flags & SK_ISNULL) ||
469  (key->sk_collation ==
470  TupleDescAttr(bdesc->bd_tupdesc,
471  keyattno - 1)->attcollation));
472 
473  /*
474  * First time we see this index attribute, so init as needed.
475  *
476  * This is a bit of an overkill - we don't know how many scan keys are
477  * there for this attribute, so we simply allocate the largest number
478  * possible (as if all keys were for this attribute). This may waste a
479  * bit of memory, but we only expect small number of scan keys in
480  * general, so this should be negligible, and repeated repalloc calls
481  * are not free either.
482  */
483  if (consistentFn[keyattno - 1].fn_oid == InvalidOid)
484  {
485  FmgrInfo *tmp;
486 
487  /* First time we see this attribute, so no key/null keys. */
488  Assert(nkeys[keyattno - 1] == 0);
489  Assert(nnullkeys[keyattno - 1] == 0);
490 
491  tmp = index_getprocinfo(idxRel, keyattno,
493  fmgr_info_copy(&consistentFn[keyattno - 1], tmp,
495  }
496 
497  /* Add key to the proper per-attribute array. */
498  if (key->sk_flags & SK_ISNULL)
499  {
500  nullkeys[keyattno - 1][nnullkeys[keyattno - 1]] = key;
501  nnullkeys[keyattno - 1]++;
502  }
503  else
504  {
505  keys[keyattno - 1][nkeys[keyattno - 1]] = key;
506  nkeys[keyattno - 1]++;
507  }
508  }
509 
510  /* allocate an initial in-memory tuple, out of the per-range memcxt */
511  dtup = brin_new_memtuple(bdesc);
512 
513  /*
514  * Setup and use a per-range memory context, which is reset every time we
515  * loop below. This avoids having to free the tuples within the loop.
516  */
518  "bringetbitmap cxt",
520  oldcxt = MemoryContextSwitchTo(perRangeCxt);
521 
522  /*
523  * Now scan the revmap. We start by querying for heap page 0,
524  * incrementing by the number of pages per range; this gives us a full
525  * view of the table.
526  */
527  for (heapBlk = 0; heapBlk < nblocks; heapBlk += opaque->bo_pagesPerRange)
528  {
529  bool addrange;
530  bool gottuple = false;
531  BrinTuple *tup;
532  OffsetNumber off;
533  Size size;
534 
536 
538 
539  tup = brinGetTupleForHeapBlock(opaque->bo_rmAccess, heapBlk, &buf,
540  &off, &size, BUFFER_LOCK_SHARE,
541  scan->xs_snapshot);
542  if (tup)
543  {
544  gottuple = true;
545  btup = brin_copy_tuple(tup, size, btup, &btupsz);
547  }
548 
549  /*
550  * For page ranges with no indexed tuple, we must return the whole
551  * range; otherwise, compare it to the scan keys.
552  */
553  if (!gottuple)
554  {
555  addrange = true;
556  }
557  else
558  {
559  dtup = brin_deform_tuple(bdesc, btup, dtup);
560  if (dtup->bt_placeholder)
561  {
562  /*
563  * Placeholder tuples are always returned, regardless of the
564  * values stored in them.
565  */
566  addrange = true;
567  }
568  else
569  {
570  int attno;
571 
572  /*
573  * Compare scan keys with summary values stored for the range.
574  * If scan keys are matched, the page range must be added to
575  * the bitmap. We initially assume the range needs to be
576  * added; in particular this serves the case where there are
577  * no keys.
578  */
579  addrange = true;
580  for (attno = 1; attno <= bdesc->bd_tupdesc->natts; attno++)
581  {
582  BrinValues *bval;
583  Datum add;
584  Oid collation;
585 
586  /*
587  * skip attributes without any scan keys (both regular and
588  * IS [NOT] NULL)
589  */
590  if (nkeys[attno - 1] == 0 && nnullkeys[attno - 1] == 0)
591  continue;
592 
593  bval = &dtup->bt_columns[attno - 1];
594 
595  /*
596  * First check if there are any IS [NOT] NULL scan keys,
597  * and if we're violating them. In that case we can
598  * terminate early, without invoking the support function.
599  *
600  * As there may be more keys, we can only determine
601  * mismatch within this loop.
602  */
603  if (bdesc->bd_info[attno - 1]->oi_regular_nulls &&
604  !check_null_keys(bval, nullkeys[attno - 1],
605  nnullkeys[attno - 1]))
606  {
607  /*
608  * If any of the IS [NOT] NULL keys failed, the page
609  * range as a whole can't pass. So terminate the loop.
610  */
611  addrange = false;
612  break;
613  }
614 
615  /*
616  * So either there are no IS [NOT] NULL keys, or all
617  * passed. If there are no regular scan keys, we're done -
618  * the page range matches. If there are regular keys, but
619  * the page range is marked as 'all nulls' it can't
620  * possibly pass (we're assuming the operators are
621  * strict).
622  */
623 
624  /* No regular scan keys - page range as a whole passes. */
625  if (!nkeys[attno - 1])
626  continue;
627 
628  Assert((nkeys[attno - 1] > 0) &&
629  (nkeys[attno - 1] <= scan->numberOfKeys));
630 
631  /* If it is all nulls, it cannot possibly be consistent. */
632  if (bval->bv_allnulls)
633  {
634  addrange = false;
635  break;
636  }
637 
638  /*
639  * Collation from the first key (has to be the same for
640  * all keys for the same attribute).
641  */
642  collation = keys[attno - 1][0]->sk_collation;
643 
644  /*
645  * Check whether the scan key is consistent with the page
646  * range values; if so, have the pages in the range added
647  * to the output bitmap.
648  *
649  * The opclass may or may not support processing of
650  * multiple scan keys. We can determine that based on the
651  * number of arguments - functions with extra parameter
652  * (number of scan keys) do support this, otherwise we
653  * have to simply pass the scan keys one by one.
654  */
655  if (consistentFn[attno - 1].fn_nargs >= 4)
656  {
657  /* Check all keys at once */
658  add = FunctionCall4Coll(&consistentFn[attno - 1],
659  collation,
660  PointerGetDatum(bdesc),
661  PointerGetDatum(bval),
662  PointerGetDatum(keys[attno - 1]),
663  Int32GetDatum(nkeys[attno - 1]));
664  addrange = DatumGetBool(add);
665  }
666  else
667  {
668  /*
669  * Check keys one by one
670  *
671  * When there are multiple scan keys, failure to meet
672  * the criteria for a single one of them is enough to
673  * discard the range as a whole, so break out of the
674  * loop as soon as a false return value is obtained.
675  */
676  int keyno;
677 
678  for (keyno = 0; keyno < nkeys[attno - 1]; keyno++)
679  {
680  add = FunctionCall3Coll(&consistentFn[attno - 1],
681  keys[attno - 1][keyno]->sk_collation,
682  PointerGetDatum(bdesc),
683  PointerGetDatum(bval),
684  PointerGetDatum(keys[attno - 1][keyno]));
685  addrange = DatumGetBool(add);
686  if (!addrange)
687  break;
688  }
689  }
690  }
691  }
692  }
693 
694  /* add the pages in the range to the output bitmap, if needed */
695  if (addrange)
696  {
697  BlockNumber pageno;
698 
699  for (pageno = heapBlk;
700  pageno <= Min(nblocks, heapBlk + opaque->bo_pagesPerRange) - 1;
701  pageno++)
702  {
703  MemoryContextSwitchTo(oldcxt);
704  tbm_add_page(tbm, pageno);
705  totalpages++;
706  MemoryContextSwitchTo(perRangeCxt);
707  }
708  }
709  }
710 
711  MemoryContextSwitchTo(oldcxt);
712  MemoryContextDelete(perRangeCxt);
713 
714  if (buf != InvalidBuffer)
716 
717  /*
718  * XXX We have an approximation of the number of *pages* that our scan
719  * returns, but we don't have a precise idea of the number of heap tuples
720  * involved.
721  */
722  return totalpages * 10;
723 }
int16 AttrNumber
Definition: attnum.h:21
static bool check_null_keys(BrinValues *bval, ScanKey *nullkeys, int nnullkeys)
Definition: brin.c:1721
#define BRIN_PROCNUM_CONSISTENT
Definition: brin_internal.h:72
BrinTuple * brinGetTupleForHeapBlock(BrinRevmap *revmap, BlockNumber heapBlk, Buffer *buf, OffsetNumber *off, Size *size, int mode, Snapshot snapshot)
Definition: brin_revmap.c:197
BrinMemTuple * brin_new_memtuple(BrinDesc *brdesc)
Definition: brin_tuple.c:479
BrinMemTuple * brin_deform_tuple(BrinDesc *brdesc, BrinTuple *tuple, BrinMemTuple *dMemtuple)
Definition: brin_tuple.c:546
BrinTuple * brin_copy_tuple(BrinTuple *tuple, Size len, BrinTuple *dest, Size *destsz)
Definition: brin_tuple.c:443
#define InvalidBuffer
Definition: buf.h:25
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:96
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:97
#define Min(x, y)
Definition: c.h:986
#define MAXALIGN(LEN)
Definition: c.h:757
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:155
size_t Size
Definition: c.h:540
Datum FunctionCall3Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2, Datum arg3)
Definition: fmgr.c:1170
void fmgr_info_copy(FmgrInfo *dstinfo, FmgrInfo *srcinfo, MemoryContext destcxt)
Definition: fmgr.c:608
int i
Definition: isn.c:73
#define AccessShareLock
Definition: lockdefs.h:36
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
uint16 OffsetNumber
Definition: off.h:24
const void size_t len
#define pgstat_count_index_scan(rel)
Definition: pgstat.h:1164
#define Int32GetDatum(X)
Definition: postgres.h:523
#define InvalidOid
Definition: postgres_ext.h:36
static void addrange(struct cvec *cv, chr from, chr to)
Definition: regc_cvec.c:90
#define RelationGetRelid(relation)
Definition: rel.h:478
#define SK_ISNULL
Definition: skey.h:115
bool bt_placeholder
Definition: brin_tuple.h:46
bool bv_allnulls
Definition: brin_tuple.h:33
struct ScanKeyData * keyData
Definition: relscan.h:122
Relation indexRelation
Definition: relscan.h:118
Oid sk_collation
Definition: skey.h:70
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
void tbm_add_page(TIDBitmap *tbm, BlockNumber pageno)
Definition: tidbitmap.c:442

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_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(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), Min, TupleDescData::natts, IndexScanDescData::numberOfKeys, BrinOpcInfo::oi_regular_nulls, IndexScanDescData::opaque, palloc(), palloc0(), PG_USED_FOR_ASSERTS_ONLY, pgstat_count_index_scan, PointerGetDatum, RelationGetNumberOfBlocks, RelationGetRelid, ReleaseBuffer(), ScanKeyData::sk_collation, SK_ISNULL, table_close(), table_open(), tbm_add_page(), TupleDescAttr, and IndexScanDescData::xs_snapshot.

Referenced by brinhandler().

◆ brinGetStats()

void brinGetStats ( Relation  index,
BrinStatsData stats 
)

Definition at line 1228 of file brin.c.

1229 {
1230  Buffer metabuffer;
1231  Page metapage;
1232  BrinMetaPageData *metadata;
1233 
1234  metabuffer = ReadBuffer(index, BRIN_METAPAGE_BLKNO);
1235  LockBuffer(metabuffer, BUFFER_LOCK_SHARE);
1236  metapage = BufferGetPage(metabuffer);
1237  metadata = (BrinMetaPageData *) PageGetContents(metapage);
1238 
1239  stats->pagesPerRange = metadata->pagesPerRange;
1240  stats->revmapNumPages = metadata->lastRevmapPage - 1;
1241 
1242  UnlockReleaseBuffer(metabuffer);
1243 }
#define PageGetContents(page)
Definition: bufpage.h:245
BlockNumber lastRevmapPage
Definition: brin_page.h:69
BlockNumber pagesPerRange
Definition: brin_page.h:68
BlockNumber revmapNumPages
Definition: brin.h:34
BlockNumber pagesPerRange
Definition: brin.h:33

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

Referenced by brincostestimate().

◆ brinhandler()

Datum brinhandler ( PG_FUNCTION_ARGS  )

Definition at line 90 of file brin.c.

91 {
93 
94  amroutine->amstrategies = 0;
97  amroutine->amcanorder = false;
98  amroutine->amcanorderbyop = false;
99  amroutine->amcanbackward = false;
100  amroutine->amcanunique = false;
101  amroutine->amcanmulticol = true;
102  amroutine->amoptionalkey = true;
103  amroutine->amsearcharray = false;
104  amroutine->amsearchnulls = true;
105  amroutine->amstorage = true;
106  amroutine->amclusterable = false;
107  amroutine->ampredlocks = false;
108  amroutine->amcanparallel = false;
109  amroutine->amcaninclude = false;
110  amroutine->amusemaintenanceworkmem = false;
111  amroutine->amhotblocking = false;
112  amroutine->amparallelvacuumoptions =
114  amroutine->amkeytype = InvalidOid;
115 
116  amroutine->ambuild = brinbuild;
117  amroutine->ambuildempty = brinbuildempty;
118  amroutine->aminsert = brininsert;
119  amroutine->ambulkdelete = brinbulkdelete;
120  amroutine->amvacuumcleanup = brinvacuumcleanup;
121  amroutine->amcanreturn = NULL;
122  amroutine->amcostestimate = brincostestimate;
123  amroutine->amoptions = brinoptions;
124  amroutine->amproperty = NULL;
125  amroutine->ambuildphasename = NULL;
126  amroutine->amvalidate = brinvalidate;
127  amroutine->amadjustmembers = NULL;
128  amroutine->ambeginscan = brinbeginscan;
129  amroutine->amrescan = brinrescan;
130  amroutine->amgettuple = NULL;
131  amroutine->amgetbitmap = bringetbitmap;
132  amroutine->amendscan = brinendscan;
133  amroutine->ammarkpos = NULL;
134  amroutine->amrestrpos = NULL;
135  amroutine->amestimateparallelscan = NULL;
136  amroutine->aminitparallelscan = NULL;
137  amroutine->amparallelrescan = NULL;
138 
139  PG_RETURN_POINTER(amroutine);
140 }
IndexBulkDeleteResult * brinvacuumcleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats)
Definition: brin.c:940
void brinrescan(IndexScanDesc scan, ScanKey scankey, int nscankeys, ScanKey orderbys, int norderbys)
Definition: brin.c:729
IndexScanDesc brinbeginscan(Relation r, int nkeys, int norderbys)
Definition: brin.c:326
IndexBuildResult * brinbuild(Relation heap, Relation index, IndexInfo *indexInfo)
Definition: brin.c:811
int64 bringetbitmap(IndexScanDesc scan, TIDBitmap *tbm)
Definition: brin.c:355
void brinbuildempty(Relation index)
Definition: brin.c:895
bool brininsert(Relation idxRel, Datum *values, bool *nulls, ItemPointer heaptid, Relation heapRel, IndexUniqueCheck checkUnique, bool indexUnchanged, IndexInfo *indexInfo)
Definition: brin.c:155
bytea * brinoptions(Datum reloptions, bool validate)
Definition: brin.c:970
IndexBulkDeleteResult * brinbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats, IndexBulkDeleteCallback callback, void *callback_state)
Definition: brin.c:925
void brinendscan(IndexScanDesc scan)
Definition: brin.c:749
#define BRIN_LAST_OPTIONAL_PROCNUM
Definition: brin_internal.h:78
#define BRIN_PROCNUM_OPTIONS
Definition: brin_internal.h:75
bool brinvalidate(Oid opclassoid)
Definition: brin_validate.c:37
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:361
#define makeNode(_type_)
Definition: nodes.h:587
void brincostestimate(PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
Definition: selfuncs.c:7703
ambuildphasename_function ambuildphasename
Definition: amapi.h:270
ambuildempty_function ambuildempty
Definition: amapi.h:262
amvacuumcleanup_function amvacuumcleanup
Definition: amapi.h:265
bool amclusterable
Definition: amapi.h:238
amoptions_function amoptions
Definition: amapi.h:268
amestimateparallelscan_function amestimateparallelscan
Definition: amapi.h:282
amrestrpos_function amrestrpos
Definition: amapi.h:279
aminsert_function aminsert
Definition: amapi.h:263
amendscan_function amendscan
Definition: amapi.h:277
uint16 amoptsprocnum
Definition: amapi.h:218
amparallelrescan_function amparallelrescan
Definition: amapi.h:284
Oid amkeytype
Definition: amapi.h:252
bool ampredlocks
Definition: amapi.h:240
uint16 amsupport
Definition: amapi.h:216
amcostestimate_function amcostestimate
Definition: amapi.h:267
bool amcanorderbyop
Definition: amapi.h:222
amadjustmembers_function amadjustmembers
Definition: amapi.h:272
ambuild_function ambuild
Definition: amapi.h:261
bool amstorage
Definition: amapi.h:236
uint16 amstrategies
Definition: amapi.h:214
bool amoptionalkey
Definition: amapi.h:230
amgettuple_function amgettuple
Definition: amapi.h:275
amcanreturn_function amcanreturn
Definition: amapi.h:266
bool amcanunique
Definition: amapi.h:226
amgetbitmap_function amgetbitmap
Definition: amapi.h:276
amproperty_function amproperty
Definition: amapi.h:269
ambulkdelete_function ambulkdelete
Definition: amapi.h:264
bool amsearcharray
Definition: amapi.h:232
amvalidate_function amvalidate
Definition: amapi.h:271
ammarkpos_function ammarkpos
Definition: amapi.h:278
bool amcanmulticol
Definition: amapi.h:228
bool amusemaintenanceworkmem
Definition: amapi.h:246
ambeginscan_function ambeginscan
Definition: amapi.h:273
bool amcanparallel
Definition: amapi.h:242
amrescan_function amrescan
Definition: amapi.h:274
bool amcanorder
Definition: amapi.h:220
bool amhotblocking
Definition: amapi.h:248
aminitparallelscan_function aminitparallelscan
Definition: amapi.h:283
uint8 amparallelvacuumoptions
Definition: amapi.h:250
bool amcanbackward
Definition: amapi.h:224
bool amcaninclude
Definition: amapi.h:244
bool amsearchnulls
Definition: amapi.h:234
#define VACUUM_OPTION_PARALLEL_CLEANUP
Definition: vacuum.h:62

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::amhotblocking, 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.

◆ brininsert()

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

Definition at line 155 of file brin.c.

160 {
161  BlockNumber pagesPerRange;
162  BlockNumber origHeapBlk;
163  BlockNumber heapBlk;
164  BrinDesc *bdesc = (BrinDesc *) indexInfo->ii_AmCache;
165  BrinRevmap *revmap;
167  MemoryContext tupcxt = NULL;
169  bool autosummarize = BrinGetAutoSummarize(idxRel);
170 
171  revmap = brinRevmapInitialize(idxRel, &pagesPerRange, NULL);
172 
173  /*
174  * origHeapBlk is the block number where the insertion occurred. heapBlk
175  * is the first block in the corresponding page range.
176  */
177  origHeapBlk = ItemPointerGetBlockNumber(heaptid);
178  heapBlk = (origHeapBlk / pagesPerRange) * pagesPerRange;
179 
180  for (;;)
181  {
182  bool need_insert = false;
183  OffsetNumber off;
184  BrinTuple *brtup;
185  BrinMemTuple *dtup;
186 
188 
189  /*
190  * If auto-summarization is enabled and we just inserted the first
191  * tuple into the first block of a new non-first page range, request a
192  * summarization run of the previous range.
193  */
194  if (autosummarize &&
195  heapBlk > 0 &&
196  heapBlk == origHeapBlk &&
198  {
199  BlockNumber lastPageRange = heapBlk - 1;
200  BrinTuple *lastPageTuple;
201 
202  lastPageTuple =
203  brinGetTupleForHeapBlock(revmap, lastPageRange, &buf, &off,
204  NULL, BUFFER_LOCK_SHARE, NULL);
205  if (!lastPageTuple)
206  {
207  bool recorded;
208 
210  RelationGetRelid(idxRel),
211  lastPageRange);
212  if (!recorded)
213  ereport(LOG,
214  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
215  errmsg("request for BRIN range summarization for index \"%s\" page %u was not recorded",
216  RelationGetRelationName(idxRel),
217  lastPageRange)));
218  }
219  else
221  }
222 
223  brtup = brinGetTupleForHeapBlock(revmap, heapBlk, &buf, &off,
224  NULL, BUFFER_LOCK_SHARE, NULL);
225 
226  /* if range is unsummarized, there's nothing to do */
227  if (!brtup)
228  break;
229 
230  /* First time through in this statement? */
231  if (bdesc == NULL)
232  {
233  MemoryContextSwitchTo(indexInfo->ii_Context);
234  bdesc = brin_build_desc(idxRel);
235  indexInfo->ii_AmCache = (void *) bdesc;
236  MemoryContextSwitchTo(oldcxt);
237  }
238  /* First time through in this brininsert call? */
239  if (tupcxt == NULL)
240  {
242  "brininsert cxt",
244  MemoryContextSwitchTo(tupcxt);
245  }
246 
247  dtup = brin_deform_tuple(bdesc, brtup, NULL);
248 
249  need_insert = add_values_to_range(idxRel, bdesc, dtup, values, nulls);
250 
251  if (!need_insert)
252  {
253  /*
254  * The tuple is consistent with the new values, so there's nothing
255  * to do.
256  */
258  }
259  else
260  {
261  Page page = BufferGetPage(buf);
262  ItemId lp = PageGetItemId(page, off);
263  Size origsz;
264  BrinTuple *origtup;
265  Size newsz;
266  BrinTuple *newtup;
267  bool samepage;
268 
269  /*
270  * Make a copy of the old tuple, so that we can compare it after
271  * re-acquiring the lock.
272  */
273  origsz = ItemIdGetLength(lp);
274  origtup = brin_copy_tuple(brtup, origsz, NULL, NULL);
275 
276  /*
277  * Before releasing the lock, check if we can attempt a same-page
278  * update. Another process could insert a tuple concurrently in
279  * the same page though, so downstream we must be prepared to cope
280  * if this turns out to not be possible after all.
281  */
282  newtup = brin_form_tuple(bdesc, heapBlk, dtup, &newsz);
283  samepage = brin_can_do_samepage_update(buf, origsz, newsz);
285 
286  /*
287  * Try to update the tuple. If this doesn't work for whatever
288  * reason, we need to restart from the top; the revmap might be
289  * pointing at a different tuple for this block now, so we need to
290  * recompute to ensure both our new heap tuple and the other
291  * inserter's are covered by the combined tuple. It might be that
292  * we don't need to update at all.
293  */
294  if (!brin_doupdate(idxRel, pagesPerRange, revmap, heapBlk,
295  buf, off, origtup, origsz, newtup, newsz,
296  samepage))
297  {
298  /* no luck; start over */
300  continue;
301  }
302  }
303 
304  /* success! */
305  break;
306  }
307 
308  brinRevmapTerminate(revmap);
309  if (BufferIsValid(buf))
311  MemoryContextSwitchTo(oldcxt);
312  if (tupcxt != NULL)
313  MemoryContextDelete(tupcxt);
314 
315  return false;
316 }
bool AutoVacuumRequestWork(AutoVacuumWorkItemType type, Oid relationId, BlockNumber blkno)
Definition: autovacuum.c:3349
@ AVW_BRINSummarizeRange
Definition: autovacuum.h:25
#define BrinGetAutoSummarize(relation)
Definition: brin.h:45
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
bool brin_can_do_samepage_update(Buffer buffer, Size origsz, Size newsz)
Definition: brin_pageops.c:324
BrinTuple * brin_form_tuple(BrinDesc *brdesc, BlockNumber blkno, BrinMemTuple *tuple, Size *size)
Definition: brin_tuple.c:99
#define BufferIsValid(bufnum)
Definition: bufmgr.h:123
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:234
#define LOG
Definition: elog.h:25
#define ItemIdGetLength(itemId)
Definition: itemid.h:59
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:117
#define FirstOffsetNumber
Definition: off.h:27
void * ii_AmCache
Definition: execnodes.h:183
MemoryContext ii_Context
Definition: execnodes.h:184

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

Referenced by brinhandler().

◆ brinoptions()

bytea* brinoptions ( Datum  reloptions,
bool  validate 
)

Definition at line 970 of file brin.c.

971 {
972  static const relopt_parse_elt tab[] = {
973  {"pages_per_range", RELOPT_TYPE_INT, offsetof(BrinOptions, pagesPerRange)},
974  {"autosummarize", RELOPT_TYPE_BOOL, offsetof(BrinOptions, autosummarize)}
975  };
976 
977  return (bytea *) build_reloptions(reloptions, validate,
979  sizeof(BrinOptions),
980  tab, lengthof(tab));
981 }
#define lengthof(array)
Definition: c.h:734
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:1904
@ RELOPT_KIND_BRIN
Definition: reloptions.h:52
@ RELOPT_TYPE_INT
Definition: reloptions.h:32
@ RELOPT_TYPE_BOOL
Definition: reloptions.h:31
Definition: c.h:622

References build_reloptions(), lengthof, offsetof, 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 729 of file brin.c.

731 {
732  /*
733  * Other index AMs preprocess the scan keys at this point, or sometime
734  * early during the scan; this lets them optimize by removing redundant
735  * keys, or doing early returns when they are impossible to satisfy; see
736  * _bt_preprocess_keys for an example. Something like that could be added
737  * here someday, too.
738  */
739 
740  if (scankey && scan->numberOfKeys > 0)
741  memmove(scan->keyData, scankey,
742  scan->numberOfKeys * sizeof(ScanKeyData));
743 }

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

Referenced by brinhandler().

◆ brinsummarize()

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

Definition at line 1444 of file brin.c.

1446 {
1447  BrinRevmap *revmap;
1448  BrinBuildState *state = NULL;
1449  IndexInfo *indexInfo = NULL;
1450  BlockNumber heapNumBlocks;
1451  BlockNumber pagesPerRange;
1452  Buffer buf;
1453  BlockNumber startBlk;
1454 
1455  revmap = brinRevmapInitialize(index, &pagesPerRange, NULL);
1456 
1457  /* determine range of pages to process */
1458  heapNumBlocks = RelationGetNumberOfBlocks(heapRel);
1459  if (pageRange == BRIN_ALL_BLOCKRANGES)
1460  startBlk = 0;
1461  else
1462  {
1463  startBlk = (pageRange / pagesPerRange) * pagesPerRange;
1464  heapNumBlocks = Min(heapNumBlocks, startBlk + pagesPerRange);
1465  }
1466  if (startBlk > heapNumBlocks)
1467  {
1468  /* Nothing to do if start point is beyond end of table */
1469  brinRevmapTerminate(revmap);
1470  return;
1471  }
1472 
1473  /*
1474  * Scan the revmap to find unsummarized items.
1475  */
1476  buf = InvalidBuffer;
1477  for (; startBlk < heapNumBlocks; startBlk += pagesPerRange)
1478  {
1479  BrinTuple *tup;
1480  OffsetNumber off;
1481 
1482  /*
1483  * Unless requested to summarize even a partial range, go away now if
1484  * we think the next range is partial. Caller would pass true when it
1485  * is typically run once bulk data loading is done
1486  * (brin_summarize_new_values), and false when it is typically the
1487  * result of arbitrarily-scheduled maintenance command (vacuuming).
1488  */
1489  if (!include_partial &&
1490  (startBlk + pagesPerRange > heapNumBlocks))
1491  break;
1492 
1494 
1495  tup = brinGetTupleForHeapBlock(revmap, startBlk, &buf, &off, NULL,
1496  BUFFER_LOCK_SHARE, NULL);
1497  if (tup == NULL)
1498  {
1499  /* no revmap entry for this heap range. Summarize it. */
1500  if (state == NULL)
1501  {
1502  /* first time through */
1503  Assert(!indexInfo);
1505  pagesPerRange);
1506  indexInfo = BuildIndexInfo(index);
1507  }
1508  summarize_range(indexInfo, state, heapRel, startBlk, heapNumBlocks);
1509 
1510  /* and re-initialize state for the next range */
1511  brin_memtuple_initialize(state->bs_dtuple, state->bs_bdesc);
1512 
1513  if (numSummarized)
1514  *numSummarized += 1.0;
1515  }
1516  else
1517  {
1518  if (numExisting)
1519  *numExisting += 1.0;
1521  }
1522  }
1523 
1524  if (BufferIsValid(buf))
1525  ReleaseBuffer(buf);
1526 
1527  /* free resources */
1528  brinRevmapTerminate(revmap);
1529  if (state)
1530  {
1532  pfree(indexInfo);
1533  }
1534 }
static void summarize_range(IndexInfo *indexInfo, BrinBuildState *state, Relation heapRel, BlockNumber heapBlk, BlockNumber heapNumBlks)
Definition: brin.c:1317
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2409

References Assert(), BRIN_ALL_BLOCKRANGES, brin_memtuple_initialize(), brinGetTupleForHeapBlock(), brinRevmapInitialize(), brinRevmapTerminate(), 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().

◆ brinvacuumcleanup()

IndexBulkDeleteResult* brinvacuumcleanup ( IndexVacuumInfo info,
IndexBulkDeleteResult stats 
)

Definition at line 940 of file brin.c.

941 {
942  Relation heapRel;
943 
944  /* No-op in ANALYZE ONLY mode */
945  if (info->analyze_only)
946  return stats;
947 
948  if (!stats)
950  stats->num_pages = RelationGetNumberOfBlocks(info->index);
951  /* rest of stats is initialized by zeroing */
952 
953  heapRel = table_open(IndexGetRelation(RelationGetRelid(info->index), false),
955 
956  brin_vacuum_scan(info->index, info->strategy);
957 
958  brinsummarize(info->index, heapRel, BRIN_ALL_BLOCKRANGES, false,
959  &stats->num_index_tuples, &stats->num_index_tuples);
960 
961  table_close(heapRel, AccessShareLock);
962 
963  return stats;
964 }
static void brin_vacuum_scan(Relation idxrel, BufferAccessStrategy strategy)
Definition: brin.c:1636
BlockNumber num_pages
Definition: genam.h:76
double num_index_tuples
Definition: genam.h:78
Relation index
Definition: genam.h:46
bool analyze_only
Definition: genam.h:47
BufferAccessStrategy strategy
Definition: genam.h:52

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().

◆ check_null_keys()

static bool check_null_keys ( BrinValues bval,
ScanKey nullkeys,
int  nnullkeys 
)
static

Definition at line 1721 of file brin.c.

1722 {
1723  int keyno;
1724 
1725  /*
1726  * First check if there are any IS [NOT] NULL scan keys, and if we're
1727  * violating them.
1728  */
1729  for (keyno = 0; keyno < nnullkeys; keyno++)
1730  {
1731  ScanKey key = nullkeys[keyno];
1732 
1733  Assert(key->sk_attno == bval->bv_attno);
1734 
1735  /* Handle only IS NULL/IS NOT NULL tests */
1736  if (!(key->sk_flags & SK_ISNULL))
1737  continue;
1738 
1739  if (key->sk_flags & SK_SEARCHNULL)
1740  {
1741  /* IS NULL scan key, but range has no NULLs */
1742  if (!bval->bv_allnulls && !bval->bv_hasnulls)
1743  return false;
1744  }
1745  else if (key->sk_flags & SK_SEARCHNOTNULL)
1746  {
1747  /*
1748  * For IS NOT NULL, we can only skip ranges that are known to have
1749  * only nulls.
1750  */
1751  if (bval->bv_allnulls)
1752  return false;
1753  }
1754  else
1755  {
1756  /*
1757  * Neither IS NULL nor IS NOT NULL was used; assume all indexable
1758  * operators are strict and thus return false with NULL value in
1759  * the scan key.
1760  */
1761  return false;
1762  }
1763  }
1764 
1765  return true;
1766 }
#define SK_SEARCHNOTNULL
Definition: skey.h:122
#define SK_SEARCHNULL
Definition: skey.h:121
AttrNumber bv_attno
Definition: brin_tuple.h:31

References Assert(), BrinValues::bv_allnulls, BrinValues::bv_attno, BrinValues::bv_hasnulls, sort-test::key, SK_ISNULL, SK_SEARCHNOTNULL, and SK_SEARCHNULL.

Referenced by bringetbitmap().

◆ form_and_insert_tuple()

static void form_and_insert_tuple ( BrinBuildState state)
static

Definition at line 1541 of file brin.c.

1542 {
1543  BrinTuple *tup;
1544  Size size;
1545 
1546  tup = brin_form_tuple(state->bs_bdesc, state->bs_currRangeStart,
1547  state->bs_dtuple, &size);
1548  brin_doinsert(state->bs_irel, state->bs_pagesPerRange, state->bs_rmAccess,
1549  &state->bs_currentInsertBuf, state->bs_currRangeStart,
1550  tup, size);
1551  state->bs_numtuples++;
1552 
1553  pfree(tup);
1554 }
OffsetNumber brin_doinsert(Relation idxrel, BlockNumber pagesPerRange, BrinRevmap *revmap, Buffer *buffer, BlockNumber heapBlk, BrinTuple *tup, Size itemsz)
Definition: brin_pageops.c:343

References brin_doinsert(), brin_form_tuple(), and pfree().

Referenced by brinbuild(), and brinbuildCallback().

◆ initialize_brin_buildstate()

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

Definition at line 1249 of file brin.c.

1251 {
1253 
1254  state = palloc(sizeof(BrinBuildState));
1255 
1256  state->bs_irel = idxRel;
1257  state->bs_numtuples = 0;
1258  state->bs_currentInsertBuf = InvalidBuffer;
1259  state->bs_pagesPerRange = pagesPerRange;
1260  state->bs_currRangeStart = 0;
1261  state->bs_rmAccess = revmap;
1262  state->bs_bdesc = brin_build_desc(idxRel);
1263  state->bs_dtuple = brin_new_memtuple(state->bs_bdesc);
1264 
1265  return state;
1266 }

References brin_build_desc(), brin_new_memtuple(), InvalidBuffer, and palloc().

Referenced by brinbuild(), and brinsummarize().

◆ summarize_range()

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

Definition at line 1317 of file brin.c.

1319 {
1320  Buffer phbuf;
1321  BrinTuple *phtup;
1322  Size phsz;
1323  OffsetNumber offset;
1324  BlockNumber scanNumBlks;
1325 
1326  /*
1327  * Insert the placeholder tuple
1328  */
1329  phbuf = InvalidBuffer;
1330  phtup = brin_form_placeholder_tuple(state->bs_bdesc, heapBlk, &phsz);
1331  offset = brin_doinsert(state->bs_irel, state->bs_pagesPerRange,
1332  state->bs_rmAccess, &phbuf,
1333  heapBlk, phtup, phsz);
1334 
1335  /*
1336  * Compute range end. We hold ShareUpdateExclusive lock on table, so it
1337  * cannot shrink concurrently (but it can grow).
1338  */
1339  Assert(heapBlk % state->bs_pagesPerRange == 0);
1340  if (heapBlk + state->bs_pagesPerRange > heapNumBlks)
1341  {
1342  /*
1343  * If we're asked to scan what we believe to be the final range on the
1344  * table (i.e. a range that might be partial) we need to recompute our
1345  * idea of what the latest page is after inserting the placeholder
1346  * tuple. Anyone that grows the table later will update the
1347  * placeholder tuple, so it doesn't matter that we won't scan these
1348  * pages ourselves. Careful: the table might have been extended
1349  * beyond the current range, so clamp our result.
1350  *
1351  * Fortunately, this should occur infrequently.
1352  */
1353  scanNumBlks = Min(RelationGetNumberOfBlocks(heapRel) - heapBlk,
1354  state->bs_pagesPerRange);
1355  }
1356  else
1357  {
1358  /* Easy case: range is known to be complete */
1359  scanNumBlks = state->bs_pagesPerRange;
1360  }
1361 
1362  /*
1363  * Execute the partial heap scan covering the heap blocks in the specified
1364  * page range, summarizing the heap tuples in it. This scan stops just
1365  * short of brinbuildCallback creating the new index entry.
1366  *
1367  * Note that it is critical we use the "any visible" mode of
1368  * table_index_build_range_scan here: otherwise, we would miss tuples
1369  * inserted by transactions that are still in progress, among other corner
1370  * cases.
1371  */
1372  state->bs_currRangeStart = heapBlk;
1373  table_index_build_range_scan(heapRel, state->bs_irel, indexInfo, false, true, false,
1374  heapBlk, scanNumBlks,
1375  brinbuildCallback, (void *) state, NULL);
1376 
1377  /*
1378  * Now we update the values obtained by the scan with the placeholder
1379  * tuple. We do this in a loop which only terminates if we're able to
1380  * update the placeholder tuple successfully; if we are not, this means
1381  * somebody else modified the placeholder tuple after we read it.
1382  */
1383  for (;;)
1384  {
1385  BrinTuple *newtup;
1386  Size newsize;
1387  bool didupdate;
1388  bool samepage;
1389 
1391 
1392  /*
1393  * Update the summary tuple and try to update.
1394  */
1395  newtup = brin_form_tuple(state->bs_bdesc,
1396  heapBlk, state->bs_dtuple, &newsize);
1397  samepage = brin_can_do_samepage_update(phbuf, phsz, newsize);
1398  didupdate =
1399  brin_doupdate(state->bs_irel, state->bs_pagesPerRange,
1400  state->bs_rmAccess, heapBlk, phbuf, offset,
1401  phtup, phsz, newtup, newsize, samepage);
1402  brin_free_tuple(phtup);
1403  brin_free_tuple(newtup);
1404 
1405  /* If the update succeeded, we're done. */
1406  if (didupdate)
1407  break;
1408 
1409  /*
1410  * If the update didn't work, it might be because somebody updated the
1411  * placeholder tuple concurrently. Extract the new version, union it
1412  * with the values we have from the scan, and start over. (There are
1413  * other reasons for the update to fail, but it's simple to treat them
1414  * the same.)
1415  */
1416  phtup = brinGetTupleForHeapBlock(state->bs_rmAccess, heapBlk, &phbuf,
1417  &offset, &phsz, BUFFER_LOCK_SHARE,
1418  NULL);
1419  /* the placeholder tuple must exist */
1420  if (phtup == NULL)
1421  elog(ERROR, "missing placeholder tuple");
1422  phtup = brin_copy_tuple(phtup, phsz, NULL, NULL);
1424 
1425  /* merge it into the tuple from the heap scan */
1426  union_tuples(state->bs_bdesc, state->bs_dtuple, phtup);
1427  }
1428 
1429  ReleaseBuffer(phbuf);
1430 }
static void union_tuples(BrinDesc *bdesc, BrinMemTuple *a, BrinTuple *b)
Definition: brin.c:1561
void brin_free_tuple(BrinTuple *tuple)
Definition: brin_tuple.c:430
BrinTuple * brin_form_placeholder_tuple(BrinDesc *brdesc, BlockNumber blkno, Size *size)
Definition: brin_tuple.c:385
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:1780

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(), 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().

◆ terminate_brin_buildstate()

static void terminate_brin_buildstate ( BrinBuildState state)
static

Definition at line 1272 of file brin.c.

1273 {
1274  /*
1275  * Release the last index buffer used. We might as well ensure that
1276  * whatever free space remains in that page is available in FSM, too.
1277  */
1278  if (!BufferIsInvalid(state->bs_currentInsertBuf))
1279  {
1280  Page page;
1281  Size freespace;
1282  BlockNumber blk;
1283 
1284  page = BufferGetPage(state->bs_currentInsertBuf);
1285  freespace = PageGetFreeSpace(page);
1286  blk = BufferGetBlockNumber(state->bs_currentInsertBuf);
1287  ReleaseBuffer(state->bs_currentInsertBuf);
1288  RecordPageWithFreeSpace(state->bs_irel, blk, freespace);
1289  FreeSpaceMapVacuumRange(state->bs_irel, blk, blk + 1);
1290  }
1291 
1292  brin_free_desc(state->bs_bdesc);
1293  pfree(state->bs_dtuple);
1294  pfree(state);
1295 }
#define BufferIsInvalid(buffer)
Definition: buf.h:31
Size PageGetFreeSpace(Page page)
Definition: bufpage.c:900
void FreeSpaceMapVacuumRange(Relation rel, BlockNumber start, BlockNumber end)
Definition: freespace.c:352
void RecordPageWithFreeSpace(Relation rel, BlockNumber heapBlk, Size spaceAvail)
Definition: freespace.c:181

References brin_free_desc(), BufferGetBlockNumber(), BufferGetPage, BufferIsInvalid, FreeSpaceMapVacuumRange(), PageGetFreeSpace(), pfree(), RecordPageWithFreeSpace(), and ReleaseBuffer().

Referenced by brinbuild(), and brinsummarize().

◆ union_tuples()

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

Definition at line 1561 of file brin.c.

1562 {
1563  int keyno;
1564  BrinMemTuple *db;
1565  MemoryContext cxt;
1566  MemoryContext oldcxt;
1567 
1568  /* Use our own memory context to avoid retail pfree */
1570  "brin union",
1572  oldcxt = MemoryContextSwitchTo(cxt);
1573  db = brin_deform_tuple(bdesc, b, NULL);
1574  MemoryContextSwitchTo(oldcxt);
1575 
1576  for (keyno = 0; keyno < bdesc->bd_tupdesc->natts; keyno++)
1577  {
1578  FmgrInfo *unionFn;
1579  BrinValues *col_a = &a->bt_columns[keyno];
1580  BrinValues *col_b = &db->bt_columns[keyno];
1581  BrinOpcInfo *opcinfo = bdesc->bd_info[keyno];
1582 
1583  if (opcinfo->oi_regular_nulls)
1584  {
1585  /* Adjust "hasnulls". */
1586  if (!col_a->bv_hasnulls && col_b->bv_hasnulls)
1587  col_a->bv_hasnulls = true;
1588 
1589  /* If there are no values in B, there's nothing left to do. */
1590  if (col_b->bv_allnulls)
1591  continue;
1592 
1593  /*
1594  * Adjust "allnulls". If A doesn't have values, just copy the
1595  * values from B into A, and we're done. We cannot run the
1596  * operators in this case, because values in A might contain
1597  * garbage. Note we already established that B contains values.
1598  */
1599  if (col_a->bv_allnulls)
1600  {
1601  int i;
1602 
1603  col_a->bv_allnulls = false;
1604 
1605  for (i = 0; i < opcinfo->oi_nstored; i++)
1606  col_a->bv_values[i] =
1607  datumCopy(col_b->bv_values[i],
1608  opcinfo->oi_typcache[i]->typbyval,
1609  opcinfo->oi_typcache[i]->typlen);
1610 
1611  continue;
1612  }
1613  }
1614 
1615  unionFn = index_getprocinfo(bdesc->bd_index, keyno + 1,
1617  FunctionCall3Coll(unionFn,
1618  bdesc->bd_index->rd_indcollation[keyno],
1619  PointerGetDatum(bdesc),
1620  PointerGetDatum(col_a),
1621  PointerGetDatum(col_b));
1622  }
1623 
1624  MemoryContextDelete(cxt);
1625 }
#define BRIN_PROCNUM_UNION
Definition: brin_internal.h:73
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:132
int b
Definition: isn.c:70
int a
Definition: isn.c:69
TypeCacheEntry * oi_typcache[FLEXIBLE_ARRAY_MEMBER]
Definition: brin_internal.h:37
Datum * bv_values
Definition: brin_tuple.h:34
bool typbyval
Definition: typcache.h:40
int16 typlen
Definition: typcache.h:39

References a, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, b, BrinDesc::bd_index, BrinDesc::bd_info, BrinDesc::bd_tupdesc, brin_deform_tuple(), BRIN_PROCNUM_UNION, BrinMemTuple::bt_columns, BrinValues::bv_allnulls, BrinValues::bv_hasnulls, BrinValues::bv_values, CurrentMemoryContext, datumCopy(), FunctionCall3Coll(), i, index_getprocinfo(), MemoryContextDelete(), MemoryContextSwitchTo(), TupleDescData::natts, BrinOpcInfo::oi_nstored, BrinOpcInfo::oi_regular_nulls, BrinOpcInfo::oi_typcache, PointerGetDatum, RelationData::rd_indcollation, TypeCacheEntry::typbyval, and TypeCacheEntry::typlen.

Referenced by summarize_range().