PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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, IndexInfo *indexInfo)
 
void brinbuildempty (Relation index)
 
bool brininsert (Relation idxRel, Datum *values, bool *nulls, ItemPointer heaptid, Relation heapRel, IndexUniqueCheck checkUnique, bool indexUnchanged, IndexInfo *indexInfo)
 
void brininsertcleanup (Relation index, 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.

44{
45 /* Containing memory context */
46 MemoryContext bd_context;
47
48 /* the index relation itself */
49 Relation bd_index;
50
51 /* tuple descriptor of the index relation */
52 TupleDesc bd_tupdesc;
53
54 /* cached copy for on-disk tuples; generated at first use */
55 TupleDesc bd_disktdesc;
56
57 /* total number of Datum entries that are stored on-disk for all columns */
58 int bd_totalstored;
59
60 /* per-column info; bd_tupdesc->natts entries long */
62} BrinDesc;
63
64/*
65 * Globally-known function support numbers for BRIN indexes. Individual
66 * opclasses can define more function support numbers, which must fall into
67 * BRIN_FIRST_OPTIONAL_PROCNUM .. BRIN_LAST_OPTIONAL_PROCNUM.
68 */
69#define BRIN_PROCNUM_OPCINFO 1
70#define BRIN_PROCNUM_ADDVALUE 2
71#define BRIN_PROCNUM_CONSISTENT 3
72#define BRIN_PROCNUM_UNION 4
73#define BRIN_MANDATORY_NPROCS 4
74#define BRIN_PROCNUM_OPTIONS 5 /* optional */
75/* procedure numbers up to 10 are reserved for BRIN future expansion */
76#define BRIN_FIRST_OPTIONAL_PROCNUM 11
77#define BRIN_LAST_OPTIONAL_PROCNUM 15
78
79#undef BRIN_DEBUG
80
81#ifdef BRIN_DEBUG
82#define BRIN_elog(args) elog args
83#else
84#define BRIN_elog(args) ((void) 0)
85#endif
86
87/* brin.c */
89extern void brin_free_desc(BrinDesc *bdesc);
91 IndexInfo *indexInfo);
92extern void brinbuildempty(Relation index);
93extern bool brininsert(Relation idxRel, Datum *values, bool *nulls,
96 bool indexUnchanged,
97 IndexInfo *indexInfo);
98extern void brininsertcleanup(Relation index, IndexInfo *indexInfo);
99extern IndexScanDesc brinbeginscan(Relation r, int nkeys, int norderbys);
100extern int64 bringetbitmap(IndexScanDesc scan, TIDBitmap *tbm);
101extern void brinrescan(IndexScanDesc scan, ScanKey scankey, int nscankeys,
102 ScanKey orderbys, int norderbys);
103extern void brinendscan(IndexScanDesc scan);
107 void *callback_state);
109 IndexBulkDeleteResult *stats);
110extern bytea *brinoptions(Datum reloptions, bool validate);
111
112/* brin_validate.c */
113extern bool brinvalidate(Oid opclassoid);
114
115#endif /* BRIN_INTERNAL_H */
static bool validate(Port *port, const char *auth)
Definition auth-oauth.c:638
static Datum values[MAXATTR]
Definition bootstrap.c:188
void brininsertcleanup(Relation index, IndexInfo *indexInfo)
Definition brin.c:517
void brinrescan(IndexScanDesc scan, ScanKey scankey, int nscankeys, ScanKey orderbys, int norderbys)
Definition brin.c:964
bool brinvalidate(Oid opclassoid)
IndexBulkDeleteResult * brinbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats, IndexBulkDeleteCallback callback, void *callback_state)
Definition brin.c:1308
IndexScanDesc brinbeginscan(Relation r, int nkeys, int norderbys)
Definition brin.c:544
bytea * brinoptions(Datum reloptions, bool validate)
Definition brin.c:1353
int64 bringetbitmap(IndexScanDesc scan, TIDBitmap *tbm)
Definition brin.c:572
void brinbuildempty(Relation index)
Definition brin.c:1279
void brin_free_desc(BrinDesc *bdesc)
Definition brin.c:1641
IndexBuildResult * brinbuild(Relation heap, Relation index, IndexInfo *indexInfo)
Definition brin.c:1110
IndexBulkDeleteResult * brinvacuumcleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats)
Definition brin.c:1323
bool brininsert(Relation idxRel, Datum *values, bool *nulls, ItemPointer heaptid, Relation heapRel, IndexUniqueCheck checkUnique, bool indexUnchanged, IndexInfo *indexInfo)
Definition brin.c:349
BrinDesc * brin_build_desc(Relation rel)
Definition brin.c:1586
void brinendscan(IndexScanDesc scan)
Definition brin.c:983
int64_t int64
Definition c.h:615
#define FLEXIBLE_ARRAY_MEMBER
Definition c.h:552
bool(* IndexBulkDeleteCallback)(ItemPointer itemptr, void *state)
Definition genam.h:95
IndexUniqueCheck
Definition genam.h:124
uint64_t Datum
Definition postgres.h:70
unsigned int Oid
static int fb(int x)
Definition type.h:96
Definition c.h:778
static void callback(struct sockaddr *addr, struct sockaddr *mask, void *unused)

Typedef Documentation

◆ BrinDesc

◆ BrinOpcInfo

Function Documentation

◆ brin_build_desc()

BrinDesc * brin_build_desc ( Relation  rel)
extern

Definition at line 1586 of file brin.c.

1587{
1589 BrinDesc *bdesc;
1590 TupleDesc tupdesc;
1591 int totalstored = 0;
1592 int keyno;
1593 long totalsize;
1594 MemoryContext cxt;
1596
1598 "brin desc cxt",
1601 tupdesc = RelationGetDescr(rel);
1602
1603 /*
1604 * Obtain BrinOpcInfo for each indexed column. While at it, accumulate
1605 * the number of columns stored, since the number is opclass-defined.
1606 */
1607 opcinfo = palloc_array(BrinOpcInfo *, tupdesc->natts);
1608 for (keyno = 0; keyno < tupdesc->natts; keyno++)
1609 {
1611 Form_pg_attribute attr = TupleDescAttr(tupdesc, keyno);
1612
1614
1615 opcinfo[keyno] = (BrinOpcInfo *)
1617 totalstored += opcinfo[keyno]->oi_nstored;
1618 }
1619
1620 /* Allocate our result struct and fill it in */
1621 totalsize = offsetof(BrinDesc, bd_info) +
1622 sizeof(BrinOpcInfo *) * tupdesc->natts;
1623
1624 bdesc = palloc(totalsize);
1625 bdesc->bd_context = cxt;
1626 bdesc->bd_index = rel;
1627 bdesc->bd_tupdesc = tupdesc;
1628 bdesc->bd_disktdesc = NULL; /* generated lazily */
1629 bdesc->bd_totalstored = totalstored;
1630
1631 for (keyno = 0; keyno < tupdesc->natts; keyno++)
1632 bdesc->bd_info[keyno] = opcinfo[keyno];
1633 pfree(opcinfo);
1634
1636
1637 return bdesc;
1638}
#define BRIN_PROCNUM_OPCINFO
#define palloc_array(type, count)
Definition fe_memutils.h:76
#define FunctionCall1(flinfo, arg1)
Definition fmgr.h:702
FmgrInfo * index_getprocinfo(Relation irel, AttrNumber attnum, uint16 procnum)
Definition indexam.c:917
void pfree(void *pointer)
Definition mcxt.c:1616
void * palloc(Size size)
Definition mcxt.c:1387
MemoryContext CurrentMemoryContext
Definition mcxt.c:160
#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
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
static Pointer DatumGetPointer(Datum X)
Definition postgres.h:332
#define RelationGetDescr(relation)
Definition rel.h:540
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:178

References ALLOCSET_SMALL_SIZES, AllocSetContextCreate, BRIN_PROCNUM_OPCINFO, CurrentMemoryContext, DatumGetPointer(), fb(), FunctionCall1, index_getprocinfo(), MemoryContextSwitchTo(), TupleDescData::natts, ObjectIdGetDatum(), 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)
extern

Definition at line 1641 of file brin.c.

1642{
1643 /* make sure the tupdesc is still valid */
1644 Assert(bdesc->bd_tupdesc->tdrefcount >= 1);
1645 /* no need for retail pfree */
1646 MemoryContextDelete(bdesc->bd_context);
1647}
#define Assert(condition)
Definition c.h:945
void MemoryContextDelete(MemoryContext context)
Definition mcxt.c:472

References Assert, fb(), and MemoryContextDelete().

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

◆ brinbeginscan()

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

Definition at line 544 of file brin.c.

545{
546 IndexScanDesc scan;
547 BrinOpaque *opaque;
548
549 scan = RelationGetIndexScan(r, nkeys, norderbys);
550
551 opaque = palloc_object(BrinOpaque);
553 opaque->bo_bdesc = brin_build_desc(r);
554 scan->opaque = opaque;
555
556 return scan;
557}
BrinDesc * brin_build_desc(Relation rel)
Definition brin.c:1586
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:208
BrinDesc * bo_bdesc
Definition brin.c:210
BrinRevmap * bo_rmAccess
Definition brin.c:209

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,
IndexInfo indexInfo 
)
extern

Definition at line 1110 of file brin.c.

1111{
1112 IndexBuildResult *result;
1113 double reltuples;
1114 double idxtuples;
1117 Buffer meta;
1118 BlockNumber pagesPerRange;
1119
1120 /*
1121 * We expect to be called exactly once for any index relation.
1122 */
1124 elog(ERROR, "index \"%s\" already contains data",
1126
1127 /*
1128 * Critical section not required, because on error the creation of the
1129 * whole relation will be rolled back.
1130 */
1131
1135
1138 MarkBufferDirty(meta);
1139
1141 {
1144 Page page;
1145
1147 xlrec.pagesPerRange = BrinGetPagesPerRange(index);
1148
1152
1154
1155 page = BufferGetPage(meta);
1156 PageSetLSN(page, recptr);
1157 }
1158
1159 UnlockReleaseBuffer(meta);
1160
1161 /*
1162 * Initialize our state, including the deformed tuple state.
1163 */
1164 revmap = brinRevmapInitialize(index, &pagesPerRange);
1165 state = initialize_brin_buildstate(index, revmap, pagesPerRange,
1167
1168 /*
1169 * Attempt to launch parallel worker scan when required
1170 *
1171 * XXX plan_create_index_workers makes the number of workers dependent on
1172 * maintenance_work_mem, requiring 32MB for each worker. That makes sense
1173 * for btree, but not for BRIN, which can do with much less memory. So
1174 * maybe make that somehow less strict, optionally?
1175 */
1176 if (indexInfo->ii_ParallelWorkers > 0)
1177 _brin_begin_parallel(state, heap, index, indexInfo->ii_Concurrent,
1178 indexInfo->ii_ParallelWorkers);
1179
1180 /*
1181 * If parallel build requested and at least one worker process was
1182 * successfully launched, set up coordination state, wait for workers to
1183 * complete. Then read all tuples from the shared tuplesort and insert
1184 * them into the index.
1185 *
1186 * In serial mode, simply scan the table and build the index one index
1187 * tuple at a time.
1188 */
1189 if (state->bs_leader)
1190 {
1192
1194 coordinate->isWorker = false;
1195 coordinate->nParticipants =
1196 state->bs_leader->nparticipanttuplesorts;
1197 coordinate->sharedsort = state->bs_leader->sharedsort;
1198
1199 /*
1200 * Begin leader tuplesort.
1201 *
1202 * In cases where parallelism is involved, the leader receives the
1203 * same share of maintenance_work_mem as a serial sort (it is
1204 * generally treated in the same way as a serial sort once we return).
1205 * Parallel worker Tuplesortstates will have received only a fraction
1206 * of maintenance_work_mem, though.
1207 *
1208 * We rely on the lifetime of the Leader Tuplesortstate almost not
1209 * overlapping with any worker Tuplesortstate's lifetime. There may
1210 * be some small overlap, but that's okay because we rely on leader
1211 * Tuplesortstate only allocating a small, fixed amount of memory
1212 * here. When its tuplesort_performsort() is called (by our caller),
1213 * and significant amounts of memory are likely to be used, all
1214 * workers must have already freed almost all memory held by their
1215 * Tuplesortstates (they are about to go away completely, too). The
1216 * overall effect is that maintenance_work_mem always represents an
1217 * absolute high watermark on the amount of memory used by a CREATE
1218 * INDEX operation, regardless of the use of parallelism or any other
1219 * factor.
1220 */
1221 state->bs_sortstate =
1224
1225 /* scan the relation and merge per-worker results */
1226 reltuples = _brin_parallel_merge(state);
1227
1228 _brin_end_parallel(state->bs_leader, state);
1229 }
1230 else /* no parallel index build */
1231 {
1232 /*
1233 * Now scan the relation. No syncscan allowed here because we want
1234 * the heap blocks in physical order (we want to produce the ranges
1235 * starting from block 0, and the callback also relies on this to not
1236 * generate summary for the same range twice).
1237 */
1238 reltuples = table_index_build_scan(heap, index, indexInfo, false, true,
1240
1241 /*
1242 * process the final batch
1243 *
1244 * XXX Note this does not update state->bs_currRangeStart, i.e. it
1245 * stays set to the last range added to the index. This is OK, because
1246 * that's what brin_fill_empty_ranges expects.
1247 */
1249
1250 /*
1251 * Backfill the final ranges with empty data.
1252 *
1253 * This saves us from doing what amounts to full table scans when the
1254 * index with a predicate like WHERE (nonnull_column IS NULL), or
1255 * other very selective predicates.
1256 */
1258 state->bs_currRangeStart,
1259 state->bs_maxRangeStart);
1260 }
1261
1262 /* release resources */
1263 idxtuples = state->bs_numtuples;
1264 brinRevmapTerminate(state->bs_rmAccess);
1266
1267 /*
1268 * Return statistics
1269 */
1271
1272 result->heap_tuples = reltuples;
1273 result->index_tuples = idxtuples;
1274
1275 return result;
1276}
uint32 BlockNumber
Definition block.h:31
static double _brin_parallel_merge(BrinBuildState *state)
Definition brin.c:2636
static void terminate_brin_buildstate(BrinBuildState *state)
Definition brin.c:1718
static void form_and_insert_tuple(BrinBuildState *state)
Definition brin.c:1987
static BrinBuildState * initialize_brin_buildstate(Relation idxRel, BrinRevmap *revmap, BlockNumber pagesPerRange, BlockNumber tablePages)
Definition brin.c:1674
static void _brin_begin_parallel(BrinBuildState *buildstate, Relation heap, Relation index, bool isconcurrent, int request)
Definition brin.c:2379
static void _brin_end_parallel(BrinLeader *brinleader, BrinBuildState *state)
Definition brin.c:2564
static void brin_fill_empty_ranges(BrinBuildState *state, BlockNumber prevRange, BlockNumber nextRange)
Definition brin.c:3009
static void brinbuildCallback(Relation index, ItemPointer tid, Datum *values, bool *isnull, bool tupleIsAlive, void *brstate)
Definition brin.c:1000
#define BrinGetPagesPerRange(relation)
Definition brin.h:41
#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)
void brinRevmapTerminate(BrinRevmap *revmap)
#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:4357
Buffer ExtendBufferedRel(BufferManagerRelation bmr, ForkNumber forkNum, BufferAccessStrategy strategy, uint32 flags)
Definition bufmgr.c:974
void UnlockReleaseBuffer(Buffer buffer)
Definition bufmgr.c:5522
void MarkBufferDirty(Buffer buffer)
Definition bufmgr.c:3063
#define RelationGetNumberOfBlocks(reln)
Definition bufmgr.h:307
static Page BufferGetPage(Buffer buffer)
Definition bufmgr.h:470
@ EB_SKIP_EXTENSION_LOCK
Definition bufmgr.h:75
@ EB_LOCK_FIRST
Definition bufmgr.h:87
#define BMR_REL(p_rel)
Definition bufmgr.h:114
static void PageSetLSN(Page page, XLogRecPtr lsn)
Definition bufpage.h:417
PageData * Page
Definition bufpage.h:81
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
#define palloc0_object(type)
Definition fe_memutils.h:75
int maintenance_work_mem
Definition globals.c:133
#define RelationGetRelationName(relation)
Definition rel.h:548
#define RelationNeedsWAL(relation)
Definition rel.h:637
@ MAIN_FORKNUM
Definition relpath.h:58
double heap_tuples
Definition genam.h:40
double index_tuples
Definition genam.h:41
int ii_ParallelWorkers
Definition execnodes.h:229
bool ii_Concurrent
Definition execnodes.h:221
static double table_index_build_scan(Relation table_rel, Relation index_rel, IndexInfo *index_info, bool allow_sync, bool progress, IndexBuildCallback callback, void *callback_state, TableScanDesc scan)
Definition tableam.h:1765
#define TUPLESORT_NONE
Definition tuplesort.h:67
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:479
void XLogRegisterData(const void *data, uint32 len)
Definition xloginsert.c:369
void XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Definition xloginsert.c:246
void XLogBeginInsert(void)
Definition xloginsert.c:153
#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(), fb(), form_and_insert_tuple(), IndexBuildResult::heap_tuples, IndexInfo::ii_Concurrent, IndexInfo::ii_ParallelWorkers, IndexBuildResult::index_tuples, initialize_brin_buildstate(), MAIN_FORKNUM, maintenance_work_mem, MarkBufferDirty(), PageSetLSN(), palloc0_object, palloc_object, REGBUF_STANDARD, REGBUF_WILL_INIT, RelationGetNumberOfBlocks, RelationGetRelationName, RelationNeedsWAL, 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)
extern

Definition at line 1279 of file brin.c.

1280{
1282
1283 /* An empty BRIN index has a metapage only. */
1286
1287 /* Initialize and xlog metabuffer. */
1294
1296}
#define START_CRIT_SECTION()
Definition miscadmin.h:150
#define END_CRIT_SECTION()
Definition miscadmin.h:152
@ INIT_FORKNUM
Definition relpath.h:61
XLogRecPtr log_newpage_buffer(Buffer buffer, bool page_std)

References BMR_REL, BRIN_CURRENT_VERSION, brin_metapage_init(), BrinGetPagesPerRange, BufferGetPage(), EB_LOCK_FIRST, EB_SKIP_EXTENSION_LOCK, END_CRIT_SECTION, ExtendBufferedRel(), fb(), 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 
)
extern

Definition at line 1308 of file brin.c.

1310{
1311 /* allocate stats if first time through, else re-use existing struct */
1312 if (stats == NULL)
1314
1315 return stats;
1316}

References fb(), and palloc0_object.

Referenced by brinhandler().

◆ brinendscan()

void brinendscan ( IndexScanDesc  scan)
extern

Definition at line 983 of file brin.c.

984{
985 BrinOpaque *opaque = (BrinOpaque *) scan->opaque;
986
987 brinRevmapTerminate(opaque->bo_rmAccess);
988 brin_free_desc(opaque->bo_bdesc);
989 pfree(opaque);
990}
void brin_free_desc(BrinDesc *bdesc)
Definition brin.c:1641

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 
)
extern

Definition at line 572 of file brin.c.

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

References AccessShareLock, addrange(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, BrinOpaque::bo_bdesc, BrinOpaque::bo_pagesPerRange, BrinOpaque::bo_rmAccess, brin_copy_tuple(), brin_deform_tuple(), brin_new_memtuple(), BRIN_PROCNUM_CONSISTENT, brinGetTupleForHeapBlock(), buf, BUFFER_LOCK_SHARE, BUFFER_LOCK_UNLOCK, BrinValues::bv_allnulls, CHECK_FOR_INTERRUPTS, check_null_keys(), CurrentMemoryContext, DatumGetBool(), fb(), fmgr_info_copy(), FunctionCall3Coll(), FunctionCall4Coll(), i, index_getprocinfo(), IndexGetRelation(), IndexScanDescData::indexRelation, IndexScanDescData::instrument, Int32GetDatum(), InvalidBuffer, InvalidOid, IndexScanDescData::keyData, len, LockBuffer(), MAXALIGN, MemoryContextDelete(), MemoryContextReset(), MemoryContextSwitchTo(), Min, IndexScanInstrumentation::nsearches, IndexScanDescData::numberOfKeys, IndexScanDescData::opaque, palloc(), palloc0_array, 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(), and TupleDescAttr().

Referenced by brinhandler().

◆ brininsert()

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

Definition at line 349 of file brin.c.

354{
355 BlockNumber pagesPerRange;
357 BlockNumber heapBlk;
358 BrinInsertState *bistate = (BrinInsertState *) indexInfo->ii_AmCache;
364 bool autosummarize = BrinGetAutoSummarize(idxRel);
365
366 /*
367 * If first time through in this statement, initialize the insert state
368 * that we keep for all the inserts in the command.
369 */
370 if (!bistate)
371 bistate = initialize_brin_insertstate(idxRel, indexInfo);
372
373 revmap = bistate->bis_rmAccess;
374 bdesc = bistate->bis_desc;
375 pagesPerRange = bistate->bis_pages_per_range;
376
377 /*
378 * origHeapBlk is the block number where the insertion occurred. heapBlk
379 * is the first block in the corresponding page range.
380 */
382 heapBlk = (origHeapBlk / pagesPerRange) * pagesPerRange;
383
384 for (;;)
385 {
386 bool need_insert = false;
387 OffsetNumber off;
390
392
393 /*
394 * If auto-summarization is enabled and we just inserted the first
395 * tuple into the first block of a new non-first page range, request a
396 * summarization run of the previous range.
397 */
398 if (autosummarize &&
399 heapBlk > 0 &&
400 heapBlk == origHeapBlk &&
402 {
403 BlockNumber lastPageRange = heapBlk - 1;
405
409 if (!lastPageTuple)
410 {
411 bool recorded;
412
416 if (!recorded)
417 ereport(LOG,
419 errmsg("request for BRIN range summarization for index \"%s\" page %u was not recorded",
421 lastPageRange)));
422 }
423 else
425 }
426
427 brtup = brinGetTupleForHeapBlock(revmap, heapBlk, &buf, &off,
429
430 /* if range is unsummarized, there's nothing to do */
431 if (!brtup)
432 break;
433
434 /* First time through in this brininsert call? */
435 if (tupcxt == NULL)
436 {
438 "brininsert cxt",
441 }
442
444
446
447 if (!need_insert)
448 {
449 /*
450 * The tuple is consistent with the new values, so there's nothing
451 * to do.
452 */
454 }
455 else
456 {
457 Page page = BufferGetPage(buf);
458 ItemId lp = PageGetItemId(page, off);
459 Size origsz;
461 Size newsz;
463 bool samepage;
464
465 /*
466 * Make a copy of the old tuple, so that we can compare it after
467 * re-acquiring the lock.
468 */
471
472 /*
473 * Before releasing the lock, check if we can attempt a same-page
474 * update. Another process could insert a tuple concurrently in
475 * the same page though, so downstream we must be prepared to cope
476 * if this turns out to not be possible after all.
477 */
478 newtup = brin_form_tuple(bdesc, heapBlk, dtup, &newsz);
481
482 /*
483 * Try to update the tuple. If this doesn't work for whatever
484 * reason, we need to restart from the top; the revmap might be
485 * pointing at a different tuple for this block now, so we need to
486 * recompute to ensure both our new heap tuple and the other
487 * inserter's are covered by the combined tuple. It might be that
488 * we don't need to update at all.
489 */
490 if (!brin_doupdate(idxRel, pagesPerRange, revmap, heapBlk,
491 buf, off, origtup, origsz, newtup, newsz,
492 samepage))
493 {
494 /* no luck; start over */
496 continue;
497 }
498 }
499
500 /* success! */
501 break;
502 }
503
504 if (BufferIsValid(buf))
507 if (tupcxt != NULL)
509
510 return false;
511}
bool AutoVacuumRequestWork(AutoVacuumWorkItemType type, Oid relationId, BlockNumber blkno)
@ AVW_BRINSummarizeRange
Definition autovacuum.h:25
static bool add_values_to_range(Relation idxRel, BrinDesc *bdesc, BrinMemTuple *dtup, const Datum *values, const bool *nulls)
Definition brin.c:2221
static BrinInsertState * initialize_brin_insertstate(Relation idxRel, IndexInfo *indexInfo)
Definition brin.c:320
#define BrinGetAutoSummarize(relation)
Definition brin.h:47
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)
bool brin_can_do_samepage_update(Buffer buffer, Size origsz, Size newsz)
BrinTuple * brin_form_tuple(BrinDesc *brdesc, BlockNumber blkno, BrinMemTuple *tuple, Size *size)
Definition brin_tuple.c:100
static bool BufferIsValid(Buffer bufnum)
Definition bufmgr.h:421
static ItemId PageGetItemId(Page page, OffsetNumber offsetNumber)
Definition bufpage.h:269
int errcode(int sqlerrcode)
Definition elog.c:874
#define LOG
Definition elog.h:31
#define ereport(elevel,...)
Definition elog.h:150
#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
static char * errmsg
#define FirstOffsetNumber
Definition off.h:27
void * ii_AmCache
Definition execnodes.h:234

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, fb(), 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,
IndexInfo indexInfo 
)
extern

Definition at line 517 of file brin.c.

518{
519 BrinInsertState *bistate = (BrinInsertState *) indexInfo->ii_AmCache;
520
521 /* bail out if cache not initialized */
522 if (bistate == NULL)
523 return;
524
525 /* do this first to avoid dangling pointer if we fail partway through */
526 indexInfo->ii_AmCache = NULL;
527
528 /*
529 * Clean up the revmap. Note that the brinDesc has already been cleaned up
530 * as part of its own memory context.
531 */
532 brinRevmapTerminate(bistate->bis_rmAccess);
533 pfree(bistate);
534}

References BrinInsertState::bis_rmAccess, brinRevmapTerminate(), fb(), IndexInfo::ii_AmCache, and pfree().

Referenced by brinhandler().

◆ brinoptions()

bytea * brinoptions ( Datum  reloptions,
bool  validate 
)
extern

Definition at line 1353 of file brin.c.

1354{
1355 static const relopt_parse_elt tab[] = {
1356 {"pages_per_range", RELOPT_TYPE_INT, offsetof(BrinOptions, pagesPerRange)},
1357 {"autosummarize", RELOPT_TYPE_BOOL, offsetof(BrinOptions, autosummarize)}
1358 };
1359
1360 return (bytea *) build_reloptions(reloptions, validate,
1362 sizeof(BrinOptions),
1363 tab, lengthof(tab));
1364}
#define lengthof(array)
Definition c.h:875
void * build_reloptions(Datum reloptions, bool validate, relopt_kind kind, Size relopt_struct_size, const relopt_parse_elt *relopt_elems, int num_relopt_elems)
@ RELOPT_KIND_BRIN
Definition reloptions.h:53
@ RELOPT_TYPE_INT
Definition reloptions.h:33
@ RELOPT_TYPE_BOOL
Definition reloptions.h:31

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

Referenced by brinhandler().

◆ brinrescan()

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

Definition at line 964 of file brin.c.

966{
967 /*
968 * Other index AMs preprocess the scan keys at this point, or sometime
969 * early during the scan; this lets them optimize by removing redundant
970 * keys, or doing early returns when they are impossible to satisfy; see
971 * _bt_preprocess_keys for an example. Something like that could be added
972 * here someday, too.
973 */
974
975 if (scankey && scan->numberOfKeys > 0)
976 memcpy(scan->keyData, scankey, scan->numberOfKeys * sizeof(ScanKeyData));
977}

References fb(), IndexScanDescData::keyData, and IndexScanDescData::numberOfKeys.

Referenced by brinhandler().

◆ brinvacuumcleanup()

IndexBulkDeleteResult * brinvacuumcleanup ( IndexVacuumInfo info,
IndexBulkDeleteResult stats 
)
extern

Definition at line 1323 of file brin.c.

1324{
1325 Relation heapRel;
1326
1327 /* No-op in ANALYZE ONLY mode */
1328 if (info->analyze_only)
1329 return stats;
1330
1331 if (!stats)
1334 /* rest of stats is initialized by zeroing */
1335
1336 heapRel = table_open(IndexGetRelation(RelationGetRelid(info->index), false),
1338
1339 brin_vacuum_scan(info->index, info->strategy);
1340
1341 brinsummarize(info->index, heapRel, BRIN_ALL_BLOCKRANGES, false,
1342 &stats->num_index_tuples, &stats->num_index_tuples);
1343
1344 table_close(heapRel, AccessShareLock);
1345
1346 return stats;
1347}
static void brin_vacuum_scan(Relation idxrel, BufferAccessStrategy strategy)
Definition brin.c:2174
#define BRIN_ALL_BLOCKRANGES
Definition brin.c:213
static void brinsummarize(Relation index, Relation heapRel, BlockNumber pageRange, bool include_partial, double *numSummarized, double *numExisting)
Definition brin.c:1889
BlockNumber num_pages
Definition genam.h:85
double num_index_tuples
Definition genam.h:87
Relation index
Definition genam.h:54
bool analyze_only
Definition genam.h:56
BufferAccessStrategy strategy
Definition genam.h:61

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)
extern

Definition at line 37 of file brin_validate.c.

38{
39 bool result = true;
43 Oid opcintype;
44 char *opclassname;
45 char *opfamilyname;
47 *oprlist;
48 uint64 allfuncs = 0;
49 uint64 allops = 0;
52 int i;
53 ListCell *lc;
54
55 /* Fetch opclass information */
58 elog(ERROR, "cache lookup failed for operator class %u", opclassoid);
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 */
71
72 /* Check individual support functions */
73 for (i = 0; i < proclist->n_members; i++)
74 {
75 HeapTuple proctup = &proclist->members[i]->tuple;
77 bool ok;
78
79 /* Check procedure numbers and function signatures */
80 switch (procform->amprocnum)
81 {
84 1, 1, INTERNALOID);
85 break;
90 break;
95 break;
100 break;
103 break;
104 default:
105 /* Complain if it's not a valid optional proc number */
106 if (procform->amprocnum < BRIN_FIRST_OPTIONAL_PROCNUM ||
108 {
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 {
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;
143
144 /* Check that only allowed strategy numbers exist */
145 if (oprform->amopstrategy < 1 || oprform->amopstrategy > 63)
146 {
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 {
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 {
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 */
201 foreach(lc, grouplist)
202 {
204
205 /* Remember the group exactly matching the test opclass */
206 if (thisgroup->lefttype == opcintype &&
207 thisgroup->righttype == opcintype)
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 {
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 {
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 {
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 */
263 errmsg("operator class \"%s\" of access method %s is missing support function %d",
264 opclassname, "brin", i)));
265 result = false;
266 }
267
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
#define BRIN_PROCNUM_UNION
#define BRIN_MANDATORY_NPROCS
#define BRIN_PROCNUM_OPTIONS
#define BRIN_FIRST_OPTIONAL_PROCNUM
#define BRIN_PROCNUM_ADDVALUE
#define NameStr(name)
Definition c.h:837
#define OidIsValid(objectId)
Definition c.h:860
void ReleaseCatCacheList(CatCList *list)
Definition catcache.c:2114
#define INFO
Definition elog.h:34
char * format_type_be(Oid type_oid)
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
char * get_opfamily_name(Oid opfid, bool missing_ok)
Definition lsyscache.c:1473
END_CATALOG_STRUCT typedef FormData_pg_amop * Form_pg_amop
Definition pg_amop.h:92
END_CATALOG_STRUCT typedef FormData_pg_amproc * Form_pg_amproc
Definition pg_amproc.h:72
#define lfirst(lc)
Definition pg_list.h:172
END_CATALOG_STRUCT typedef FormData_pg_opclass * Form_pg_opclass
Definition pg_opclass.h:87
char * format_procedure(Oid procedure_oid)
Definition regproc.c:305
char * format_operator(Oid operator_oid)
Definition regproc.c:801
Definition pg_list.h:54
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:264
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:220
#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, fb(), Form_pg_amop, Form_pg_amproc, Form_pg_opclass, format_operator(), format_procedure(), format_type_be(), get_opfamily_name(), GETSTRUCT(), HeapTupleIsValid, i, identify_opfamily_groups(), INFO, lfirst, NameStr, ObjectIdGetDatum(), OidIsValid, ReleaseCatCacheList(), ReleaseSysCache(), SearchSysCache1(), and SearchSysCacheList1.

Referenced by brinhandler().