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

Go to the source code of this file.

Data Structures

struct  BrinOpcInfo
 
struct  BrinDesc
 

Macros

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

Typedefs

typedef struct BrinOpcInfo BrinOpcInfo
 
typedef struct BrinDesc BrinDesc
 

Functions

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

Macro Definition Documentation

◆ BRIN_elog

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

Definition at line 85 of file brin_internal.h.

◆ BRIN_FIRST_OPTIONAL_PROCNUM

#define BRIN_FIRST_OPTIONAL_PROCNUM   11

Definition at line 77 of file brin_internal.h.

◆ BRIN_LAST_OPTIONAL_PROCNUM

#define BRIN_LAST_OPTIONAL_PROCNUM   15

Definition at line 78 of file brin_internal.h.

◆ BRIN_MANDATORY_NPROCS

#define BRIN_MANDATORY_NPROCS   4

Definition at line 74 of file brin_internal.h.

◆ BRIN_PROCNUM_ADDVALUE

#define BRIN_PROCNUM_ADDVALUE   2

Definition at line 71 of file brin_internal.h.

◆ BRIN_PROCNUM_CONSISTENT

#define BRIN_PROCNUM_CONSISTENT   3

Definition at line 72 of file brin_internal.h.

◆ BRIN_PROCNUM_OPCINFO

#define BRIN_PROCNUM_OPCINFO   1

Definition at line 70 of file brin_internal.h.

◆ BRIN_PROCNUM_OPTIONS

#define BRIN_PROCNUM_OPTIONS   5 /* optional */

Definition at line 75 of file brin_internal.h.

◆ BRIN_PROCNUM_UNION

#define BRIN_PROCNUM_UNION   4

Definition at line 73 of file brin_internal.h.

◆ SizeofBrinOpcInfo

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

Definition at line 41 of file brin_internal.h.

Typedef Documentation

◆ BrinDesc

typedef struct BrinDesc BrinDesc

◆ BrinOpcInfo

typedef struct BrinOpcInfo BrinOpcInfo

Function Documentation

◆ brin_build_desc()

BrinDesc * brin_build_desc ( Relation  rel)

Definition at line 1575 of file brin.c.

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

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

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

◆ brin_free_desc()

void brin_free_desc ( BrinDesc bdesc)

Definition at line 1630 of file brin.c.

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

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

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

◆ brinbeginscan()

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

Definition at line 534 of file brin.c.

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

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

Referenced by brinhandler().

◆ brinbuild()

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

Definition at line 1098 of file brin.c.

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

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

Referenced by brinhandler().

◆ brinbuildempty()

void brinbuildempty ( Relation  index)

Definition at line 1267 of file brin.c.

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

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

Referenced by brinhandler().

◆ brinbulkdelete()

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

Definition at line 1296 of file brin.c.

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

References palloc0_object.

Referenced by brinhandler().

◆ brinendscan()

void brinendscan ( IndexScanDesc  scan)

Definition at line 971 of file brin.c.

972{
973 BrinOpaque *opaque = (BrinOpaque *) scan->opaque;
974
976 brin_free_desc(opaque->bo_bdesc);
977 pfree(opaque);
978}
void brin_free_desc(BrinDesc *bdesc)
Definition: brin.c:1630

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

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

References AccessShareLock, addrange(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, BrinDesc::bd_info, BrinDesc::bd_tupdesc, BrinOpaque::bo_bdesc, BrinOpaque::bo_pagesPerRange, BrinOpaque::bo_rmAccess, brin_copy_tuple(), brin_deform_tuple(), brin_new_memtuple(), BRIN_PROCNUM_CONSISTENT, brinGetTupleForHeapBlock(), BrinMemTuple::bt_columns, BrinMemTuple::bt_empty_range, BrinMemTuple::bt_placeholder, buf, BUFFER_LOCK_SHARE, BUFFER_LOCK_UNLOCK, BrinValues::bv_allnulls, CHECK_FOR_INTERRUPTS, check_null_keys(), CurrentMemoryContext, DatumGetBool(), fmgr_info_copy(), FunctionCall3Coll(), FunctionCall4Coll(), i, index_getprocinfo(), IndexGetRelation(), IndexScanDescData::indexRelation, Int32GetDatum(), InvalidBuffer, InvalidOid, sort-test::key, IndexScanDescData::keyData, len, LockBuffer(), MAXALIGN, MemoryContextDelete(), MemoryContextReset(), MemoryContextSwitchTo(), Min, TupleDescData::natts, IndexScanDescData::numberOfKeys, BrinOpcInfo::oi_regular_nulls, IndexScanDescData::opaque, palloc(), palloc0_array, PG_USED_FOR_ASSERTS_ONLY, pgstat_count_index_scan, PointerGetDatum(), RelationGetNumberOfBlocks, RelationGetRelid, ReleaseBuffer(), size, ScanKeyData::sk_collation, SK_ISNULL, table_close(), table_open(), tbm_add_page(), and TupleDescAttr().

Referenced by brinhandler().

◆ brininsert()

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

Definition at line 341 of file brin.c.

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

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

Referenced by brinhandler().

◆ brininsertcleanup()

void brininsertcleanup ( Relation  index,
struct IndexInfo indexInfo 
)

Definition at line 509 of file brin.c.

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

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

Referenced by brinhandler().

◆ brinoptions()

bytea * brinoptions ( Datum  reloptions,
bool  validate 
)

Definition at line 1341 of file brin.c.

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

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

Referenced by brinhandler().

◆ brinrescan()

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

Definition at line 952 of file brin.c.

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

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

Referenced by brinhandler().

◆ brinvacuumcleanup()

IndexBulkDeleteResult * brinvacuumcleanup ( IndexVacuumInfo info,
IndexBulkDeleteResult stats 
)

Definition at line 1311 of file brin.c.

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

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

Referenced by brinhandler().

◆ brinvalidate()

bool brinvalidate ( Oid  opclassoid)

Definition at line 37 of file brin_validate.c.

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

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

Referenced by brinhandler().