PostgreSQL Source Code  git master
brin.c
Go to the documentation of this file.
1 /*
2  * brin.c
3  * Implementation of BRIN indexes for Postgres
4  *
5  * See src/backend/access/brin/README for details.
6  *
7  * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  * IDENTIFICATION
11  * src/backend/access/brin/brin.c
12  *
13  * TODO
14  * * ScalarArrayOpExpr (amsearcharray -> SK_SEARCHARRAY)
15  */
16 #include "postgres.h"
17 
18 #include "access/brin.h"
19 #include "access/brin_page.h"
20 #include "access/brin_pageops.h"
21 #include "access/brin_xlog.h"
22 #include "access/relation.h"
23 #include "access/reloptions.h"
24 #include "access/relscan.h"
25 #include "access/table.h"
26 #include "access/tableam.h"
27 #include "access/xloginsert.h"
28 #include "catalog/index.h"
29 #include "catalog/pg_am.h"
30 #include "commands/vacuum.h"
31 #include "miscadmin.h"
32 #include "pgstat.h"
33 #include "postmaster/autovacuum.h"
34 #include "storage/bufmgr.h"
35 #include "storage/freespace.h"
36 #include "utils/acl.h"
37 #include "utils/builtins.h"
38 #include "utils/index_selfuncs.h"
39 #include "utils/memutils.h"
40 #include "utils/rel.h"
41 
42 
43 /*
44  * We use a BrinBuildState during initial construction of a BRIN index.
45  * The running state is kept in a BrinMemTuple.
46  */
47 typedef struct BrinBuildState
48 {
58 
59 /*
60  * Struct used as "opaque" during index scans
61  */
62 typedef struct BrinOpaque
63 {
67 } BrinOpaque;
68 
69 #define BRIN_ALL_BLOCKRANGES InvalidBlockNumber
70 
72  BrinRevmap *revmap, BlockNumber pagesPerRange);
74 static void brinsummarize(Relation index, Relation heapRel, BlockNumber pageRange,
75  bool include_partial, double *numSummarized, double *numExisting);
77 static void union_tuples(BrinDesc *bdesc, BrinMemTuple *a,
78  BrinTuple *b);
79 static void brin_vacuum_scan(Relation idxrel, BufferAccessStrategy strategy);
80 
81 
82 /*
83  * BRIN handler function: return IndexAmRoutine with access method parameters
84  * and callbacks.
85  */
86 Datum
88 {
90 
91  amroutine->amstrategies = 0;
94  amroutine->amcanorder = false;
95  amroutine->amcanorderbyop = false;
96  amroutine->amcanbackward = false;
97  amroutine->amcanunique = false;
98  amroutine->amcanmulticol = true;
99  amroutine->amoptionalkey = true;
100  amroutine->amsearcharray = false;
101  amroutine->amsearchnulls = true;
102  amroutine->amstorage = true;
103  amroutine->amclusterable = false;
104  amroutine->ampredlocks = false;
105  amroutine->amcanparallel = false;
106  amroutine->amcaninclude = false;
107  amroutine->amusemaintenanceworkmem = false;
108  amroutine->amparallelvacuumoptions =
110  amroutine->amkeytype = InvalidOid;
111 
112  amroutine->ambuild = brinbuild;
113  amroutine->ambuildempty = brinbuildempty;
114  amroutine->aminsert = brininsert;
115  amroutine->ambulkdelete = brinbulkdelete;
116  amroutine->amvacuumcleanup = brinvacuumcleanup;
117  amroutine->amcanreturn = NULL;
118  amroutine->amcostestimate = brincostestimate;
119  amroutine->amoptions = brinoptions;
120  amroutine->amproperty = NULL;
121  amroutine->ambuildphasename = NULL;
122  amroutine->amvalidate = brinvalidate;
123  amroutine->amadjustmembers = NULL;
124  amroutine->ambeginscan = brinbeginscan;
125  amroutine->amrescan = brinrescan;
126  amroutine->amgettuple = NULL;
127  amroutine->amgetbitmap = bringetbitmap;
128  amroutine->amendscan = brinendscan;
129  amroutine->ammarkpos = NULL;
130  amroutine->amrestrpos = NULL;
131  amroutine->amestimateparallelscan = NULL;
132  amroutine->aminitparallelscan = NULL;
133  amroutine->amparallelrescan = NULL;
134 
135  PG_RETURN_POINTER(amroutine);
136 }
137 
138 /*
139  * A tuple in the heap is being inserted. To keep a brin index up to date,
140  * we need to obtain the relevant index tuple and compare its stored values
141  * with those of the new tuple. If the tuple values are not consistent with
142  * the summary tuple, we need to update the index tuple.
143  *
144  * If autosummarization is enabled, check if we need to summarize the previous
145  * page range.
146  *
147  * If the range is not currently summarized (i.e. the revmap returns NULL for
148  * it), there's nothing to do for this tuple.
149  */
150 bool
151 brininsert(Relation idxRel, Datum *values, bool *nulls,
152  ItemPointer heaptid, Relation heapRel,
153  IndexUniqueCheck checkUnique,
154  IndexInfo *indexInfo)
155 {
156  BlockNumber pagesPerRange;
157  BlockNumber origHeapBlk;
158  BlockNumber heapBlk;
159  BrinDesc *bdesc = (BrinDesc *) indexInfo->ii_AmCache;
160  BrinRevmap *revmap;
162  MemoryContext tupcxt = NULL;
164  bool autosummarize = BrinGetAutoSummarize(idxRel);
165 
166  revmap = brinRevmapInitialize(idxRel, &pagesPerRange, NULL);
167 
168  /*
169  * origHeapBlk is the block number where the insertion occurred. heapBlk
170  * is the first block in the corresponding page range.
171  */
172  origHeapBlk = ItemPointerGetBlockNumber(heaptid);
173  heapBlk = (origHeapBlk / pagesPerRange) * pagesPerRange;
174 
175  for (;;)
176  {
177  bool need_insert = false;
178  OffsetNumber off;
179  BrinTuple *brtup;
180  BrinMemTuple *dtup;
181  int keyno;
182 
184 
185  /*
186  * If auto-summarization is enabled and we just inserted the first
187  * tuple into the first block of a new non-first page range, request a
188  * summarization run of the previous range.
189  */
190  if (autosummarize &&
191  heapBlk > 0 &&
192  heapBlk == origHeapBlk &&
194  {
195  BlockNumber lastPageRange = heapBlk - 1;
196  BrinTuple *lastPageTuple;
197 
198  lastPageTuple =
199  brinGetTupleForHeapBlock(revmap, lastPageRange, &buf, &off,
200  NULL, BUFFER_LOCK_SHARE, NULL);
201  if (!lastPageTuple)
202  {
203  bool recorded;
204 
206  RelationGetRelid(idxRel),
207  lastPageRange);
208  if (!recorded)
209  ereport(LOG,
210  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
211  errmsg("request for BRIN range summarization for index \"%s\" page %u was not recorded",
212  RelationGetRelationName(idxRel),
213  lastPageRange)));
214  }
215  else
217  }
218 
219  brtup = brinGetTupleForHeapBlock(revmap, heapBlk, &buf, &off,
220  NULL, BUFFER_LOCK_SHARE, NULL);
221 
222  /* if range is unsummarized, there's nothing to do */
223  if (!brtup)
224  break;
225 
226  /* First time through in this statement? */
227  if (bdesc == NULL)
228  {
229  MemoryContextSwitchTo(indexInfo->ii_Context);
230  bdesc = brin_build_desc(idxRel);
231  indexInfo->ii_AmCache = (void *) bdesc;
232  MemoryContextSwitchTo(oldcxt);
233  }
234  /* First time through in this brininsert call? */
235  if (tupcxt == NULL)
236  {
238  "brininsert cxt",
240  MemoryContextSwitchTo(tupcxt);
241  }
242 
243  dtup = brin_deform_tuple(bdesc, brtup, NULL);
244 
245  /*
246  * Compare the key values of the new tuple to the stored index values;
247  * our deformed tuple will get updated if the new tuple doesn't fit
248  * the original range (note this means we can't break out of the loop
249  * early). Make a note of whether this happens, so that we know to
250  * insert the modified tuple later.
251  */
252  for (keyno = 0; keyno < bdesc->bd_tupdesc->natts; keyno++)
253  {
254  Datum result;
255  BrinValues *bval;
256  FmgrInfo *addValue;
257 
258  bval = &dtup->bt_columns[keyno];
259  addValue = index_getprocinfo(idxRel, keyno + 1,
261  result = FunctionCall4Coll(addValue,
262  idxRel->rd_indcollation[keyno],
263  PointerGetDatum(bdesc),
264  PointerGetDatum(bval),
265  values[keyno],
266  nulls[keyno]);
267  /* if that returned true, we need to insert the updated tuple */
268  need_insert |= DatumGetBool(result);
269  }
270 
271  if (!need_insert)
272  {
273  /*
274  * The tuple is consistent with the new values, so there's nothing
275  * to do.
276  */
278  }
279  else
280  {
281  Page page = BufferGetPage(buf);
282  ItemId lp = PageGetItemId(page, off);
283  Size origsz;
284  BrinTuple *origtup;
285  Size newsz;
286  BrinTuple *newtup;
287  bool samepage;
288 
289  /*
290  * Make a copy of the old tuple, so that we can compare it after
291  * re-acquiring the lock.
292  */
293  origsz = ItemIdGetLength(lp);
294  origtup = brin_copy_tuple(brtup, origsz, NULL, NULL);
295 
296  /*
297  * Before releasing the lock, check if we can attempt a same-page
298  * update. Another process could insert a tuple concurrently in
299  * the same page though, so downstream we must be prepared to cope
300  * if this turns out to not be possible after all.
301  */
302  newtup = brin_form_tuple(bdesc, heapBlk, dtup, &newsz);
303  samepage = brin_can_do_samepage_update(buf, origsz, newsz);
305 
306  /*
307  * Try to update the tuple. If this doesn't work for whatever
308  * reason, we need to restart from the top; the revmap might be
309  * pointing at a different tuple for this block now, so we need to
310  * recompute to ensure both our new heap tuple and the other
311  * inserter's are covered by the combined tuple. It might be that
312  * we don't need to update at all.
313  */
314  if (!brin_doupdate(idxRel, pagesPerRange, revmap, heapBlk,
315  buf, off, origtup, origsz, newtup, newsz,
316  samepage))
317  {
318  /* no luck; start over */
320  continue;
321  }
322  }
323 
324  /* success! */
325  break;
326  }
327 
328  brinRevmapTerminate(revmap);
329  if (BufferIsValid(buf))
331  MemoryContextSwitchTo(oldcxt);
332  if (tupcxt != NULL)
333  MemoryContextDelete(tupcxt);
334 
335  return false;
336 }
337 
338 /*
339  * Initialize state for a BRIN index scan.
340  *
341  * We read the metapage here to determine the pages-per-range number that this
342  * index was built with. Note that since this cannot be changed while we're
343  * holding lock on index, it's not necessary to recompute it during brinrescan.
344  */
346 brinbeginscan(Relation r, int nkeys, int norderbys)
347 {
348  IndexScanDesc scan;
349  BrinOpaque *opaque;
350 
351  scan = RelationGetIndexScan(r, nkeys, norderbys);
352 
353  opaque = (BrinOpaque *) palloc(sizeof(BrinOpaque));
354  opaque->bo_rmAccess = brinRevmapInitialize(r, &opaque->bo_pagesPerRange,
355  scan->xs_snapshot);
356  opaque->bo_bdesc = brin_build_desc(r);
357  scan->opaque = opaque;
358 
359  return scan;
360 }
361 
362 /*
363  * Execute the index scan.
364  *
365  * This works by reading index TIDs from the revmap, and obtaining the index
366  * tuples pointed to by them; the summary values in the index tuples are
367  * compared to the scan keys. We return into the TID bitmap all the pages in
368  * ranges corresponding to index tuples that match the scan keys.
369  *
370  * If a TID from the revmap is read as InvalidTID, we know that range is
371  * unsummarized. Pages in those ranges need to be returned regardless of scan
372  * keys.
373  */
374 int64
376 {
377  Relation idxRel = scan->indexRelation;
379  BrinDesc *bdesc;
380  Oid heapOid;
381  Relation heapRel;
382  BrinOpaque *opaque;
383  BlockNumber nblocks;
384  BlockNumber heapBlk;
385  int totalpages = 0;
386  FmgrInfo *consistentFn;
387  MemoryContext oldcxt;
388  MemoryContext perRangeCxt;
389  BrinMemTuple *dtup;
390  BrinTuple *btup = NULL;
391  Size btupsz = 0;
392 
393  opaque = (BrinOpaque *) scan->opaque;
394  bdesc = opaque->bo_bdesc;
395  pgstat_count_index_scan(idxRel);
396 
397  /*
398  * We need to know the size of the table so that we know how long to
399  * iterate on the revmap.
400  */
401  heapOid = IndexGetRelation(RelationGetRelid(idxRel), false);
402  heapRel = table_open(heapOid, AccessShareLock);
403  nblocks = RelationGetNumberOfBlocks(heapRel);
404  table_close(heapRel, AccessShareLock);
405 
406  /*
407  * Make room for the consistent support procedures of indexed columns. We
408  * don't look them up here; we do that lazily the first time we see a scan
409  * key reference each of them. We rely on zeroing fn_oid to InvalidOid.
410  */
411  consistentFn = palloc0(sizeof(FmgrInfo) * bdesc->bd_tupdesc->natts);
412 
413  /* allocate an initial in-memory tuple, out of the per-range memcxt */
414  dtup = brin_new_memtuple(bdesc);
415 
416  /*
417  * Setup and use a per-range memory context, which is reset every time we
418  * loop below. This avoids having to free the tuples within the loop.
419  */
421  "bringetbitmap cxt",
423  oldcxt = MemoryContextSwitchTo(perRangeCxt);
424 
425  /*
426  * Now scan the revmap. We start by querying for heap page 0,
427  * incrementing by the number of pages per range; this gives us a full
428  * view of the table.
429  */
430  for (heapBlk = 0; heapBlk < nblocks; heapBlk += opaque->bo_pagesPerRange)
431  {
432  bool addrange;
433  bool gottuple = false;
434  BrinTuple *tup;
435  OffsetNumber off;
436  Size size;
437 
439 
441 
442  tup = brinGetTupleForHeapBlock(opaque->bo_rmAccess, heapBlk, &buf,
443  &off, &size, BUFFER_LOCK_SHARE,
444  scan->xs_snapshot);
445  if (tup)
446  {
447  gottuple = true;
448  btup = brin_copy_tuple(tup, size, btup, &btupsz);
450  }
451 
452  /*
453  * For page ranges with no indexed tuple, we must return the whole
454  * range; otherwise, compare it to the scan keys.
455  */
456  if (!gottuple)
457  {
458  addrange = true;
459  }
460  else
461  {
462  dtup = brin_deform_tuple(bdesc, btup, dtup);
463  if (dtup->bt_placeholder)
464  {
465  /*
466  * Placeholder tuples are always returned, regardless of the
467  * values stored in them.
468  */
469  addrange = true;
470  }
471  else
472  {
473  int keyno;
474 
475  /*
476  * Compare scan keys with summary values stored for the range.
477  * If scan keys are matched, the page range must be added to
478  * the bitmap. We initially assume the range needs to be
479  * added; in particular this serves the case where there are
480  * no keys.
481  */
482  addrange = true;
483  for (keyno = 0; keyno < scan->numberOfKeys; keyno++)
484  {
485  ScanKey key = &scan->keyData[keyno];
486  AttrNumber keyattno = key->sk_attno;
487  BrinValues *bval = &dtup->bt_columns[keyattno - 1];
488  Datum add;
489 
490  /*
491  * The collation of the scan key must match the collation
492  * used in the index column (but only if the search is not
493  * IS NULL/ IS NOT NULL). Otherwise we shouldn't be using
494  * this index ...
495  */
496  Assert((key->sk_flags & SK_ISNULL) ||
497  (key->sk_collation ==
498  TupleDescAttr(bdesc->bd_tupdesc,
499  keyattno - 1)->attcollation));
500 
501  /* First time this column? look up consistent function */
502  if (consistentFn[keyattno - 1].fn_oid == InvalidOid)
503  {
504  FmgrInfo *tmp;
505 
506  tmp = index_getprocinfo(idxRel, keyattno,
508  fmgr_info_copy(&consistentFn[keyattno - 1], tmp,
510  }
511 
512  /*
513  * Check whether the scan key is consistent with the page
514  * range values; if so, have the pages in the range added
515  * to the output bitmap.
516  *
517  * When there are multiple scan keys, failure to meet the
518  * criteria for a single one of them is enough to discard
519  * the range as a whole, so break out of the loop as soon
520  * as a false return value is obtained.
521  */
522  add = FunctionCall3Coll(&consistentFn[keyattno - 1],
523  key->sk_collation,
524  PointerGetDatum(bdesc),
525  PointerGetDatum(bval),
526  PointerGetDatum(key));
527  addrange = DatumGetBool(add);
528  if (!addrange)
529  break;
530  }
531  }
532  }
533 
534  /* add the pages in the range to the output bitmap, if needed */
535  if (addrange)
536  {
537  BlockNumber pageno;
538 
539  for (pageno = heapBlk;
540  pageno <= heapBlk + opaque->bo_pagesPerRange - 1;
541  pageno++)
542  {
543  MemoryContextSwitchTo(oldcxt);
544  tbm_add_page(tbm, pageno);
545  totalpages++;
546  MemoryContextSwitchTo(perRangeCxt);
547  }
548  }
549  }
550 
551  MemoryContextSwitchTo(oldcxt);
552  MemoryContextDelete(perRangeCxt);
553 
554  if (buf != InvalidBuffer)
555  ReleaseBuffer(buf);
556 
557  /*
558  * XXX We have an approximation of the number of *pages* that our scan
559  * returns, but we don't have a precise idea of the number of heap tuples
560  * involved.
561  */
562  return totalpages * 10;
563 }
564 
565 /*
566  * Re-initialize state for a BRIN index scan
567  */
568 void
569 brinrescan(IndexScanDesc scan, ScanKey scankey, int nscankeys,
570  ScanKey orderbys, int norderbys)
571 {
572  /*
573  * Other index AMs preprocess the scan keys at this point, or sometime
574  * early during the scan; this lets them optimize by removing redundant
575  * keys, or doing early returns when they are impossible to satisfy; see
576  * _bt_preprocess_keys for an example. Something like that could be added
577  * here someday, too.
578  */
579 
580  if (scankey && scan->numberOfKeys > 0)
581  memmove(scan->keyData, scankey,
582  scan->numberOfKeys * sizeof(ScanKeyData));
583 }
584 
585 /*
586  * Close down a BRIN index scan
587  */
588 void
590 {
591  BrinOpaque *opaque = (BrinOpaque *) scan->opaque;
592 
594  brin_free_desc(opaque->bo_bdesc);
595  pfree(opaque);
596 }
597 
598 /*
599  * Per-heap-tuple callback for table_index_build_scan.
600  *
601  * Note we don't worry about the page range at the end of the table here; it is
602  * present in the build state struct after we're called the last time, but not
603  * inserted into the index. Caller must ensure to do so, if appropriate.
604  */
605 static void
607  ItemPointer tid,
608  Datum *values,
609  bool *isnull,
610  bool tupleIsAlive,
611  void *brstate)
612 {
613  BrinBuildState *state = (BrinBuildState *) brstate;
614  BlockNumber thisblock;
615  int i;
616 
617  thisblock = ItemPointerGetBlockNumber(tid);
618 
619  /*
620  * If we're in a block that belongs to a future range, summarize what
621  * we've got and start afresh. Note the scan might have skipped many
622  * pages, if they were devoid of live tuples; make sure to insert index
623  * tuples for those too.
624  */
625  while (thisblock > state->bs_currRangeStart + state->bs_pagesPerRange - 1)
626  {
627 
628  BRIN_elog((DEBUG2,
629  "brinbuildCallback: completed a range: %u--%u",
630  state->bs_currRangeStart,
631  state->bs_currRangeStart + state->bs_pagesPerRange));
632 
633  /* create the index tuple and insert it */
634  form_and_insert_tuple(state);
635 
636  /* set state to correspond to the next range */
637  state->bs_currRangeStart += state->bs_pagesPerRange;
638 
639  /* re-initialize state for it */
641  }
642 
643  /* Accumulate the current tuple into the running state */
644  for (i = 0; i < state->bs_bdesc->bd_tupdesc->natts; i++)
645  {
646  FmgrInfo *addValue;
647  BrinValues *col;
649 
650  col = &state->bs_dtuple->bt_columns[i];
651  addValue = index_getprocinfo(index, i + 1,
653 
654  /*
655  * Update dtuple state, if and as necessary.
656  */
657  FunctionCall4Coll(addValue,
658  attr->attcollation,
659  PointerGetDatum(state->bs_bdesc),
660  PointerGetDatum(col),
661  values[i], isnull[i]);
662  }
663 }
664 
665 /*
666  * brinbuild() -- build a new BRIN index.
667  */
670 {
671  IndexBuildResult *result;
672  double reltuples;
673  double idxtuples;
674  BrinRevmap *revmap;
676  Buffer meta;
677  BlockNumber pagesPerRange;
678 
679  /*
680  * We expect to be called exactly once for any index relation.
681  */
682  if (RelationGetNumberOfBlocks(index) != 0)
683  elog(ERROR, "index \"%s\" already contains data",
684  RelationGetRelationName(index));
685 
686  /*
687  * Critical section not required, because on error the creation of the
688  * whole relation will be rolled back.
689  */
690 
691  meta = ReadBuffer(index, P_NEW);
694 
697  MarkBufferDirty(meta);
698 
699  if (RelationNeedsWAL(index))
700  {
701  xl_brin_createidx xlrec;
702  XLogRecPtr recptr;
703  Page page;
704 
706  xlrec.pagesPerRange = BrinGetPagesPerRange(index);
707 
708  XLogBeginInsert();
709  XLogRegisterData((char *) &xlrec, SizeOfBrinCreateIdx);
711 
712  recptr = XLogInsert(RM_BRIN_ID, XLOG_BRIN_CREATE_INDEX);
713 
714  page = BufferGetPage(meta);
715  PageSetLSN(page, recptr);
716  }
717 
718  UnlockReleaseBuffer(meta);
719 
720  /*
721  * Initialize our state, including the deformed tuple state.
722  */
723  revmap = brinRevmapInitialize(index, &pagesPerRange, NULL);
724  state = initialize_brin_buildstate(index, revmap, pagesPerRange);
725 
726  /*
727  * Now scan the relation. No syncscan allowed here because we want the
728  * heap blocks in physical order.
729  */
730  reltuples = table_index_build_scan(heap, index, indexInfo, false, true,
731  brinbuildCallback, (void *) state, NULL);
732 
733  /* process the final batch */
734  form_and_insert_tuple(state);
735 
736  /* release resources */
737  idxtuples = state->bs_numtuples;
738  brinRevmapTerminate(state->bs_rmAccess);
740 
741  /*
742  * Return statistics
743  */
744  result = (IndexBuildResult *) palloc(sizeof(IndexBuildResult));
745 
746  result->heap_tuples = reltuples;
747  result->index_tuples = idxtuples;
748 
749  return result;
750 }
751 
752 void
754 {
755  Buffer metabuf;
756 
757  /* An empty BRIN index has a metapage only. */
758  metabuf =
761 
762  /* Initialize and xlog metabuffer. */
766  MarkBufferDirty(metabuf);
767  log_newpage_buffer(metabuf, true);
769 
770  UnlockReleaseBuffer(metabuf);
771 }
772 
773 /*
774  * brinbulkdelete
775  * Since there are no per-heap-tuple index tuples in BRIN indexes,
776  * there's not a lot we can do here.
777  *
778  * XXX we could mark item tuples as "dirty" (when a minimum or maximum heap
779  * tuple is deleted), meaning the need to re-run summarization on the affected
780  * range. Would need to add an extra flag in brintuples for that.
781  */
784  IndexBulkDeleteCallback callback, void *callback_state)
785 {
786  /* allocate stats if first time through, else re-use existing struct */
787  if (stats == NULL)
789 
790  return stats;
791 }
792 
793 /*
794  * This routine is in charge of "vacuuming" a BRIN index: we just summarize
795  * ranges that are currently unsummarized.
796  */
799 {
800  Relation heapRel;
801 
802  /* No-op in ANALYZE ONLY mode */
803  if (info->analyze_only)
804  return stats;
805 
806  if (!stats)
808  stats->num_pages = RelationGetNumberOfBlocks(info->index);
809  /* rest of stats is initialized by zeroing */
810 
811  heapRel = table_open(IndexGetRelation(RelationGetRelid(info->index), false),
813 
814  brin_vacuum_scan(info->index, info->strategy);
815 
816  brinsummarize(info->index, heapRel, BRIN_ALL_BLOCKRANGES, false,
817  &stats->num_index_tuples, &stats->num_index_tuples);
818 
819  table_close(heapRel, AccessShareLock);
820 
821  return stats;
822 }
823 
824 /*
825  * reloptions processor for BRIN indexes
826  */
827 bytea *
828 brinoptions(Datum reloptions, bool validate)
829 {
830  static const relopt_parse_elt tab[] = {
831  {"pages_per_range", RELOPT_TYPE_INT, offsetof(BrinOptions, pagesPerRange)},
832  {"autosummarize", RELOPT_TYPE_BOOL, offsetof(BrinOptions, autosummarize)}
833  };
834 
835  return (bytea *) build_reloptions(reloptions, validate,
837  sizeof(BrinOptions),
838  tab, lengthof(tab));
839 }
840 
841 /*
842  * SQL-callable function to scan through an index and summarize all ranges
843  * that are not currently summarized.
844  */
845 Datum
847 {
848  Datum relation = PG_GETARG_DATUM(0);
849 
851  relation,
853 }
854 
855 /*
856  * SQL-callable function to summarize the indicated page range, if not already
857  * summarized. If the second argument is BRIN_ALL_BLOCKRANGES, all
858  * unsummarized ranges are summarized.
859  */
860 Datum
862 {
863  Oid indexoid = PG_GETARG_OID(0);
864  int64 heapBlk64 = PG_GETARG_INT64(1);
865  BlockNumber heapBlk;
866  Oid heapoid;
867  Relation indexRel;
868  Relation heapRel;
869  double numSummarized = 0;
870 
871  if (RecoveryInProgress())
872  ereport(ERROR,
873  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
874  errmsg("recovery is in progress"),
875  errhint("BRIN control functions cannot be executed during recovery.")));
876 
877  if (heapBlk64 > BRIN_ALL_BLOCKRANGES || heapBlk64 < 0)
878  {
879  char *blk = psprintf(INT64_FORMAT, heapBlk64);
880 
881  ereport(ERROR,
882  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
883  errmsg("block number out of range: %s", blk)));
884  }
885  heapBlk = (BlockNumber) heapBlk64;
886 
887  /*
888  * We must lock table before index to avoid deadlocks. However, if the
889  * passed indexoid isn't an index then IndexGetRelation() will fail.
890  * Rather than emitting a not-very-helpful error message, postpone
891  * complaining, expecting that the is-it-an-index test below will fail.
892  */
893  heapoid = IndexGetRelation(indexoid, true);
894  if (OidIsValid(heapoid))
895  heapRel = table_open(heapoid, ShareUpdateExclusiveLock);
896  else
897  heapRel = NULL;
898 
899  indexRel = index_open(indexoid, ShareUpdateExclusiveLock);
900 
901  /* Must be a BRIN index */
902  if (indexRel->rd_rel->relkind != RELKIND_INDEX ||
903  indexRel->rd_rel->relam != BRIN_AM_OID)
904  ereport(ERROR,
905  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
906  errmsg("\"%s\" is not a BRIN index",
907  RelationGetRelationName(indexRel))));
908 
909  /* User must own the index (comparable to privileges needed for VACUUM) */
910  if (!pg_class_ownercheck(indexoid, GetUserId()))
912  RelationGetRelationName(indexRel));
913 
914  /*
915  * Since we did the IndexGetRelation call above without any lock, it's
916  * barely possible that a race against an index drop/recreation could have
917  * netted us the wrong table. Recheck.
918  */
919  if (heapRel == NULL || heapoid != IndexGetRelation(indexoid, false))
920  ereport(ERROR,
922  errmsg("could not open parent table of index %s",
923  RelationGetRelationName(indexRel))));
924 
925  /* OK, do it */
926  brinsummarize(indexRel, heapRel, heapBlk, true, &numSummarized, NULL);
927 
930 
931  PG_RETURN_INT32((int32) numSummarized);
932 }
933 
934 /*
935  * SQL-callable interface to mark a range as no longer summarized
936  */
937 Datum
939 {
940  Oid indexoid = PG_GETARG_OID(0);
941  int64 heapBlk64 = PG_GETARG_INT64(1);
942  BlockNumber heapBlk;
943  Oid heapoid;
944  Relation heapRel;
945  Relation indexRel;
946  bool done;
947 
948  if (RecoveryInProgress())
949  ereport(ERROR,
950  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
951  errmsg("recovery is in progress"),
952  errhint("BRIN control functions cannot be executed during recovery.")));
953 
954  if (heapBlk64 > MaxBlockNumber || heapBlk64 < 0)
955  {
956  char *blk = psprintf(INT64_FORMAT, heapBlk64);
957 
958  ereport(ERROR,
959  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
960  errmsg("block number out of range: %s", blk)));
961  }
962  heapBlk = (BlockNumber) heapBlk64;
963 
964  /*
965  * We must lock table before index to avoid deadlocks. However, if the
966  * passed indexoid isn't an index then IndexGetRelation() will fail.
967  * Rather than emitting a not-very-helpful error message, postpone
968  * complaining, expecting that the is-it-an-index test below will fail.
969  */
970  heapoid = IndexGetRelation(indexoid, true);
971  if (OidIsValid(heapoid))
972  heapRel = table_open(heapoid, ShareUpdateExclusiveLock);
973  else
974  heapRel = NULL;
975 
976  indexRel = index_open(indexoid, ShareUpdateExclusiveLock);
977 
978  /* Must be a BRIN index */
979  if (indexRel->rd_rel->relkind != RELKIND_INDEX ||
980  indexRel->rd_rel->relam != BRIN_AM_OID)
981  ereport(ERROR,
982  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
983  errmsg("\"%s\" is not a BRIN index",
984  RelationGetRelationName(indexRel))));
985 
986  /* User must own the index (comparable to privileges needed for VACUUM) */
987  if (!pg_class_ownercheck(indexoid, GetUserId()))
989  RelationGetRelationName(indexRel));
990 
991  /*
992  * Since we did the IndexGetRelation call above without any lock, it's
993  * barely possible that a race against an index drop/recreation could have
994  * netted us the wrong table. Recheck.
995  */
996  if (heapRel == NULL || heapoid != IndexGetRelation(indexoid, false))
997  ereport(ERROR,
999  errmsg("could not open parent table of index %s",
1000  RelationGetRelationName(indexRel))));
1001 
1002  /* the revmap does the hard work */
1003  do
1004  {
1005  done = brinRevmapDesummarizeRange(indexRel, heapBlk);
1006  }
1007  while (!done);
1008 
1011 
1012  PG_RETURN_VOID();
1013 }
1014 
1015 /*
1016  * Build a BrinDesc used to create or scan a BRIN index
1017  */
1018 BrinDesc *
1020 {
1021  BrinOpcInfo **opcinfo;
1022  BrinDesc *bdesc;
1023  TupleDesc tupdesc;
1024  int totalstored = 0;
1025  int keyno;
1026  long totalsize;
1027  MemoryContext cxt;
1028  MemoryContext oldcxt;
1029 
1031  "brin desc cxt",
1033  oldcxt = MemoryContextSwitchTo(cxt);
1034  tupdesc = RelationGetDescr(rel);
1035 
1036  /*
1037  * Obtain BrinOpcInfo for each indexed column. While at it, accumulate
1038  * the number of columns stored, since the number is opclass-defined.
1039  */
1040  opcinfo = (BrinOpcInfo **) palloc(sizeof(BrinOpcInfo *) * tupdesc->natts);
1041  for (keyno = 0; keyno < tupdesc->natts; keyno++)
1042  {
1043  FmgrInfo *opcInfoFn;
1044  Form_pg_attribute attr = TupleDescAttr(tupdesc, keyno);
1045 
1046  opcInfoFn = index_getprocinfo(rel, keyno + 1, BRIN_PROCNUM_OPCINFO);
1047 
1048  opcinfo[keyno] = (BrinOpcInfo *)
1049  DatumGetPointer(FunctionCall1(opcInfoFn, attr->atttypid));
1050  totalstored += opcinfo[keyno]->oi_nstored;
1051  }
1052 
1053  /* Allocate our result struct and fill it in */
1054  totalsize = offsetof(BrinDesc, bd_info) +
1055  sizeof(BrinOpcInfo *) * tupdesc->natts;
1056 
1057  bdesc = palloc(totalsize);
1058  bdesc->bd_context = cxt;
1059  bdesc->bd_index = rel;
1060  bdesc->bd_tupdesc = tupdesc;
1061  bdesc->bd_disktdesc = NULL; /* generated lazily */
1062  bdesc->bd_totalstored = totalstored;
1063 
1064  for (keyno = 0; keyno < tupdesc->natts; keyno++)
1065  bdesc->bd_info[keyno] = opcinfo[keyno];
1066  pfree(opcinfo);
1067 
1068  MemoryContextSwitchTo(oldcxt);
1069 
1070  return bdesc;
1071 }
1072 
1073 void
1075 {
1076  /* make sure the tupdesc is still valid */
1077  Assert(bdesc->bd_tupdesc->tdrefcount >= 1);
1078  /* no need for retail pfree */
1080 }
1081 
1082 /*
1083  * Fetch index's statistical data into *stats
1084  */
1085 void
1087 {
1088  Buffer metabuffer;
1089  Page metapage;
1090  BrinMetaPageData *metadata;
1091 
1092  metabuffer = ReadBuffer(index, BRIN_METAPAGE_BLKNO);
1093  LockBuffer(metabuffer, BUFFER_LOCK_SHARE);
1094  metapage = BufferGetPage(metabuffer);
1095  metadata = (BrinMetaPageData *) PageGetContents(metapage);
1096 
1097  stats->pagesPerRange = metadata->pagesPerRange;
1098  stats->revmapNumPages = metadata->lastRevmapPage - 1;
1099 
1100  UnlockReleaseBuffer(metabuffer);
1101 }
1102 
1103 /*
1104  * Initialize a BrinBuildState appropriate to create tuples on the given index.
1105  */
1106 static BrinBuildState *
1108  BlockNumber pagesPerRange)
1109 {
1111 
1112  state = palloc(sizeof(BrinBuildState));
1113 
1114  state->bs_irel = idxRel;
1115  state->bs_numtuples = 0;
1117  state->bs_pagesPerRange = pagesPerRange;
1118  state->bs_currRangeStart = 0;
1119  state->bs_rmAccess = revmap;
1120  state->bs_bdesc = brin_build_desc(idxRel);
1121  state->bs_dtuple = brin_new_memtuple(state->bs_bdesc);
1122 
1124 
1125  return state;
1126 }
1127 
1128 /*
1129  * Release resources associated with a BrinBuildState.
1130  */
1131 static void
1133 {
1134  /*
1135  * Release the last index buffer used. We might as well ensure that
1136  * whatever free space remains in that page is available in FSM, too.
1137  */
1138  if (!BufferIsInvalid(state->bs_currentInsertBuf))
1139  {
1140  Page page;
1141  Size freespace;
1142  BlockNumber blk;
1143 
1144  page = BufferGetPage(state->bs_currentInsertBuf);
1145  freespace = PageGetFreeSpace(page);
1148  RecordPageWithFreeSpace(state->bs_irel, blk, freespace);
1149  FreeSpaceMapVacuumRange(state->bs_irel, blk, blk + 1);
1150  }
1151 
1152  brin_free_desc(state->bs_bdesc);
1153  pfree(state->bs_dtuple);
1154  pfree(state);
1155 }
1156 
1157 /*
1158  * On the given BRIN index, summarize the heap page range that corresponds
1159  * to the heap block number given.
1160  *
1161  * This routine can run in parallel with insertions into the heap. To avoid
1162  * missing those values from the summary tuple, we first insert a placeholder
1163  * index tuple into the index, then execute the heap scan; transactions
1164  * concurrent with the scan update the placeholder tuple. After the scan, we
1165  * union the placeholder tuple with the one computed by this routine. The
1166  * update of the index value happens in a loop, so that if somebody updates
1167  * the placeholder tuple after we read it, we detect the case and try again.
1168  * This ensures that the concurrently inserted tuples are not lost.
1169  *
1170  * A further corner case is this routine being asked to summarize the partial
1171  * range at the end of the table. heapNumBlocks is the (possibly outdated)
1172  * table size; if we notice that the requested range lies beyond that size,
1173  * we re-compute the table size after inserting the placeholder tuple, to
1174  * avoid missing pages that were appended recently.
1175  */
1176 static void
1178  BlockNumber heapBlk, BlockNumber heapNumBlks)
1179 {
1180  Buffer phbuf;
1181  BrinTuple *phtup;
1182  Size phsz;
1183  OffsetNumber offset;
1184  BlockNumber scanNumBlks;
1185 
1186  /*
1187  * Insert the placeholder tuple
1188  */
1189  phbuf = InvalidBuffer;
1190  phtup = brin_form_placeholder_tuple(state->bs_bdesc, heapBlk, &phsz);
1191  offset = brin_doinsert(state->bs_irel, state->bs_pagesPerRange,
1192  state->bs_rmAccess, &phbuf,
1193  heapBlk, phtup, phsz);
1194 
1195  /*
1196  * Compute range end. We hold ShareUpdateExclusive lock on table, so it
1197  * cannot shrink concurrently (but it can grow).
1198  */
1199  Assert(heapBlk % state->bs_pagesPerRange == 0);
1200  if (heapBlk + state->bs_pagesPerRange > heapNumBlks)
1201  {
1202  /*
1203  * If we're asked to scan what we believe to be the final range on the
1204  * table (i.e. a range that might be partial) we need to recompute our
1205  * idea of what the latest page is after inserting the placeholder
1206  * tuple. Anyone that grows the table later will update the
1207  * placeholder tuple, so it doesn't matter that we won't scan these
1208  * pages ourselves. Careful: the table might have been extended
1209  * beyond the current range, so clamp our result.
1210  *
1211  * Fortunately, this should occur infrequently.
1212  */
1213  scanNumBlks = Min(RelationGetNumberOfBlocks(heapRel) - heapBlk,
1214  state->bs_pagesPerRange);
1215  }
1216  else
1217  {
1218  /* Easy case: range is known to be complete */
1219  scanNumBlks = state->bs_pagesPerRange;
1220  }
1221 
1222  /*
1223  * Execute the partial heap scan covering the heap blocks in the specified
1224  * page range, summarizing the heap tuples in it. This scan stops just
1225  * short of brinbuildCallback creating the new index entry.
1226  *
1227  * Note that it is critical we use the "any visible" mode of
1228  * table_index_build_range_scan here: otherwise, we would miss tuples
1229  * inserted by transactions that are still in progress, among other corner
1230  * cases.
1231  */
1232  state->bs_currRangeStart = heapBlk;
1233  table_index_build_range_scan(heapRel, state->bs_irel, indexInfo, false, true, false,
1234  heapBlk, scanNumBlks,
1235  brinbuildCallback, (void *) state, NULL);
1236 
1237  /*
1238  * Now we update the values obtained by the scan with the placeholder
1239  * tuple. We do this in a loop which only terminates if we're able to
1240  * update the placeholder tuple successfully; if we are not, this means
1241  * somebody else modified the placeholder tuple after we read it.
1242  */
1243  for (;;)
1244  {
1245  BrinTuple *newtup;
1246  Size newsize;
1247  bool didupdate;
1248  bool samepage;
1249 
1251 
1252  /*
1253  * Update the summary tuple and try to update.
1254  */
1255  newtup = brin_form_tuple(state->bs_bdesc,
1256  heapBlk, state->bs_dtuple, &newsize);
1257  samepage = brin_can_do_samepage_update(phbuf, phsz, newsize);
1258  didupdate =
1259  brin_doupdate(state->bs_irel, state->bs_pagesPerRange,
1260  state->bs_rmAccess, heapBlk, phbuf, offset,
1261  phtup, phsz, newtup, newsize, samepage);
1262  brin_free_tuple(phtup);
1263  brin_free_tuple(newtup);
1264 
1265  /* If the update succeeded, we're done. */
1266  if (didupdate)
1267  break;
1268 
1269  /*
1270  * If the update didn't work, it might be because somebody updated the
1271  * placeholder tuple concurrently. Extract the new version, union it
1272  * with the values we have from the scan, and start over. (There are
1273  * other reasons for the update to fail, but it's simple to treat them
1274  * the same.)
1275  */
1276  phtup = brinGetTupleForHeapBlock(state->bs_rmAccess, heapBlk, &phbuf,
1277  &offset, &phsz, BUFFER_LOCK_SHARE,
1278  NULL);
1279  /* the placeholder tuple must exist */
1280  if (phtup == NULL)
1281  elog(ERROR, "missing placeholder tuple");
1282  phtup = brin_copy_tuple(phtup, phsz, NULL, NULL);
1284 
1285  /* merge it into the tuple from the heap scan */
1286  union_tuples(state->bs_bdesc, state->bs_dtuple, phtup);
1287  }
1288 
1289  ReleaseBuffer(phbuf);
1290 }
1291 
1292 /*
1293  * Summarize page ranges that are not already summarized. If pageRange is
1294  * BRIN_ALL_BLOCKRANGES then the whole table is scanned; otherwise, only the
1295  * page range containing the given heap page number is scanned.
1296  * If include_partial is true, then the partial range at the end of the table
1297  * is summarized, otherwise not.
1298  *
1299  * For each new index tuple inserted, *numSummarized (if not NULL) is
1300  * incremented; for each existing tuple, *numExisting (if not NULL) is
1301  * incremented.
1302  */
1303 static void
1305  bool include_partial, double *numSummarized, double *numExisting)
1306 {
1307  BrinRevmap *revmap;
1308  BrinBuildState *state = NULL;
1309  IndexInfo *indexInfo = NULL;
1310  BlockNumber heapNumBlocks;
1311  BlockNumber pagesPerRange;
1312  Buffer buf;
1313  BlockNumber startBlk;
1314 
1315  revmap = brinRevmapInitialize(index, &pagesPerRange, NULL);
1316 
1317  /* determine range of pages to process */
1318  heapNumBlocks = RelationGetNumberOfBlocks(heapRel);
1319  if (pageRange == BRIN_ALL_BLOCKRANGES)
1320  startBlk = 0;
1321  else
1322  {
1323  startBlk = (pageRange / pagesPerRange) * pagesPerRange;
1324  heapNumBlocks = Min(heapNumBlocks, startBlk + pagesPerRange);
1325  }
1326  if (startBlk > heapNumBlocks)
1327  {
1328  /* Nothing to do if start point is beyond end of table */
1329  brinRevmapTerminate(revmap);
1330  return;
1331  }
1332 
1333  /*
1334  * Scan the revmap to find unsummarized items.
1335  */
1336  buf = InvalidBuffer;
1337  for (; startBlk < heapNumBlocks; startBlk += pagesPerRange)
1338  {
1339  BrinTuple *tup;
1340  OffsetNumber off;
1341 
1342  /*
1343  * Unless requested to summarize even a partial range, go away now if
1344  * we think the next range is partial. Caller would pass true when it
1345  * is typically run once bulk data loading is done
1346  * (brin_summarize_new_values), and false when it is typically the
1347  * result of arbitrarily-scheduled maintenance command (vacuuming).
1348  */
1349  if (!include_partial &&
1350  (startBlk + pagesPerRange > heapNumBlocks))
1351  break;
1352 
1354 
1355  tup = brinGetTupleForHeapBlock(revmap, startBlk, &buf, &off, NULL,
1356  BUFFER_LOCK_SHARE, NULL);
1357  if (tup == NULL)
1358  {
1359  /* no revmap entry for this heap range. Summarize it. */
1360  if (state == NULL)
1361  {
1362  /* first time through */
1363  Assert(!indexInfo);
1364  state = initialize_brin_buildstate(index, revmap,
1365  pagesPerRange);
1366  indexInfo = BuildIndexInfo(index);
1367  }
1368  summarize_range(indexInfo, state, heapRel, startBlk, heapNumBlocks);
1369 
1370  /* and re-initialize state for the next range */
1372 
1373  if (numSummarized)
1374  *numSummarized += 1.0;
1375  }
1376  else
1377  {
1378  if (numExisting)
1379  *numExisting += 1.0;
1381  }
1382  }
1383 
1384  if (BufferIsValid(buf))
1385  ReleaseBuffer(buf);
1386 
1387  /* free resources */
1388  brinRevmapTerminate(revmap);
1389  if (state)
1390  {
1392  pfree(indexInfo);
1393  }
1394 }
1395 
1396 /*
1397  * Given a deformed tuple in the build state, convert it into the on-disk
1398  * format and insert it into the index, making the revmap point to it.
1399  */
1400 static void
1402 {
1403  BrinTuple *tup;
1404  Size size;
1405 
1406  tup = brin_form_tuple(state->bs_bdesc, state->bs_currRangeStart,
1407  state->bs_dtuple, &size);
1408  brin_doinsert(state->bs_irel, state->bs_pagesPerRange, state->bs_rmAccess,
1409  &state->bs_currentInsertBuf, state->bs_currRangeStart,
1410  tup, size);
1411  state->bs_numtuples++;
1412 
1413  pfree(tup);
1414 }
1415 
1416 /*
1417  * Given two deformed tuples, adjust the first one so that it's consistent
1418  * with the summary values in both.
1419  */
1420 static void
1422 {
1423  int keyno;
1424  BrinMemTuple *db;
1425  MemoryContext cxt;
1426  MemoryContext oldcxt;
1427 
1428  /* Use our own memory context to avoid retail pfree */
1430  "brin union",
1432  oldcxt = MemoryContextSwitchTo(cxt);
1433  db = brin_deform_tuple(bdesc, b, NULL);
1434  MemoryContextSwitchTo(oldcxt);
1435 
1436  for (keyno = 0; keyno < bdesc->bd_tupdesc->natts; keyno++)
1437  {
1438  FmgrInfo *unionFn;
1439  BrinValues *col_a = &a->bt_columns[keyno];
1440  BrinValues *col_b = &db->bt_columns[keyno];
1441 
1442  unionFn = index_getprocinfo(bdesc->bd_index, keyno + 1,
1444  FunctionCall3Coll(unionFn,
1445  bdesc->bd_index->rd_indcollation[keyno],
1446  PointerGetDatum(bdesc),
1447  PointerGetDatum(col_a),
1448  PointerGetDatum(col_b));
1449  }
1450 
1451  MemoryContextDelete(cxt);
1452 }
1453 
1454 /*
1455  * brin_vacuum_scan
1456  * Do a complete scan of the index during VACUUM.
1457  *
1458  * This routine scans the complete index looking for uncatalogued index pages,
1459  * i.e. those that might have been lost due to a crash after index extension
1460  * and such.
1461  */
1462 static void
1464 {
1465  BlockNumber nblocks;
1466  BlockNumber blkno;
1467 
1468  /*
1469  * Scan the index in physical order, and clean up any possible mess in
1470  * each page.
1471  */
1472  nblocks = RelationGetNumberOfBlocks(idxrel);
1473  for (blkno = 0; blkno < nblocks; blkno++)
1474  {
1475  Buffer buf;
1476 
1478 
1479  buf = ReadBufferExtended(idxrel, MAIN_FORKNUM, blkno,
1480  RBM_NORMAL, strategy);
1481 
1482  brin_page_cleanup(idxrel, buf);
1483 
1484  ReleaseBuffer(buf);
1485  }
1486 
1487  /*
1488  * Update all upper pages in the index's FSM, as well. This ensures not
1489  * only that we propagate leaf-page FSM updates made by brin_page_cleanup,
1490  * but also that any pre-existing damage or out-of-dateness is repaired.
1491  */
1492  FreeSpaceMapVacuum(idxrel);
1493 }
void brin_free_desc(BrinDesc *bdesc)
Definition: brin.c:1074
IndexBulkDeleteResult * brinbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats, IndexBulkDeleteCallback callback, void *callback_state)
Definition: brin.c:783
ambeginscan_function ambeginscan
Definition: amapi.h:270
uint8 amparallelvacuumoptions
Definition: amapi.h:247
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:360
bool AutoVacuumRequestWork(AutoVacuumWorkItemType type, Oid relationId, BlockNumber blkno)
Definition: autovacuum.c:3263
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:96
MemoryContext ii_Context
Definition: execnodes.h:179
Definition: fmgr.h:56
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3401
ambulkdelete_function ambulkdelete
Definition: amapi.h:261
#define BRIN_CURRENT_VERSION
Definition: brin_page.h:72
bool amcanmulticol
Definition: amapi.h:227
uint16 amsupport
Definition: amapi.h:215
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:212
#define BRIN_elog(args)
Definition: brin_internal.h:82
#define AllocSetContextCreate
Definition: memutils.h:170
#define BRIN_METAPAGE_BLKNO
Definition: brin_page.h:75
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
IndexBuildResult * brinbuild(Relation heap, Relation index, IndexInfo *indexInfo)
Definition: brin.c:669
int errhint(const char *fmt,...)
Definition: elog.c:1071
XLogRecPtr log_newpage_buffer(Buffer buffer, bool page_std)
Definition: xloginsert.c:1090
bool brininsert(Relation idxRel, Datum *values, bool *nulls, ItemPointer heaptid, Relation heapRel, IndexUniqueCheck checkUnique, IndexInfo *indexInfo)
Definition: brin.c:151
#define ERRCODE_UNDEFINED_TABLE
Definition: pgbench.c:74
FmgrInfo * index_getprocinfo(Relation irel, AttrNumber attnum, uint16 procnum)
Definition: indexam.c:801
BrinTuple * brin_copy_tuple(BrinTuple *tuple, Size len, BrinTuple *dest, Size *destsz)
Definition: brin_tuple.c:319
#define SizeOfBrinCreateIdx
Definition: brin_xlog.h:55
amgettuple_function amgettuple
Definition: amapi.h:272
void RecordPageWithFreeSpace(Relation rel, BlockNumber heapBlk, Size spaceAvail)
Definition: freespace.c:181
#define RelationGetDescr(relation)
Definition: rel.h:482
void brinRevmapTerminate(BrinRevmap *revmap)
Definition: brin_revmap.c:103
Oid GetUserId(void)
Definition: miscinit.c:476
bool amcanorderbyop
Definition: amapi.h:221
static void union_tuples(BrinDesc *bdesc, BrinMemTuple *a, BrinTuple *b)
Definition: brin.c:1421
amproperty_function amproperty
Definition: amapi.h:266
BrinTuple * brinGetTupleForHeapBlock(BrinRevmap *revmap, BlockNumber heapBlk, Buffer *buf, OffsetNumber *off, Size *size, int mode, Snapshot snapshot)
Definition: brin_revmap.c:197
bool brinvalidate(Oid opclassoid)
Definition: brin_validate.c:37
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1469
void XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Definition: xloginsert.c:220
#define PointerGetDatum(X)
Definition: postgres.h:556
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:268
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
static void addrange(struct cvec *cv, chr from, chr to)
Definition: regc_cvec.c:90
Buffer bs_currentInsertBuf
Definition: brin.c:51
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:202
static void summarize_range(IndexInfo *indexInfo, BrinBuildState *state, Relation heapRel, BlockNumber heapBlk, BlockNumber heapNumBlks)
Definition: brin.c:1177
bool analyze_only
Definition: genam.h:47
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:653
amparallelrescan_function amparallelrescan
Definition: amapi.h:281
#define Min(x, y)
Definition: c.h:927
#define END_CRIT_SECTION()
Definition: miscadmin.h:134
BufferAccessStrategy strategy
Definition: genam.h:52
bool amstorage
Definition: amapi.h:235
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define XLOG_BRIN_CREATE_INDEX
Definition: brin_xlog.h:31
#define PG_RETURN_INT32(x)
Definition: fmgr.h:353
#define AccessShareLock
Definition: lockdefs.h:36
#define InvalidBuffer
Definition: buf.h:25
#define REGBUF_WILL_INIT
Definition: xloginsert.h:33
#define BRIN_PROCNUM_OPCINFO
Definition: brin_internal.h:67
int64 bringetbitmap(IndexScanDesc scan, TIDBitmap *tbm)
Definition: brin.c:375
#define START_CRIT_SECTION()
Definition: miscadmin.h:132
int errcode(int sqlerrcode)
Definition: elog.c:610
Relation index
Definition: genam.h:46
bool ampredlocks
Definition: amapi.h:239
struct SnapshotData * xs_snapshot
Definition: relscan.h:116
Datum FunctionCall4Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition: fmgr.c:1199
uint32 BlockNumber
Definition: block.h:31
static void form_and_insert_tuple(BrinBuildState *state)
Definition: brin.c:1401
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3511
#define P_NEW
Definition: bufmgr.h:91
aminsert_function aminsert
Definition: amapi.h:260
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2301
#define lengthof(array)
Definition: c.h:675
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:98
#define LOG
Definition: elog.h:26
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
bool brin_doupdate(Relation idxrel, BlockNumber pagesPerRange, BrinRevmap *revmap, BlockNumber heapBlk, Buffer oldbuf, OffsetNumber oldoff, const BrinTuple *origtup, Size origsz, const BrinTuple *newtup, Size newsz, bool samepage)
Definition: brin_pageops.c:54
bool RecoveryInProgress(void)
Definition: xlog.c:8074
BrinMemTuple * brin_new_memtuple(BrinDesc *brdesc)
Definition: brin_tuple.c:355
Oid amkeytype
Definition: amapi.h:249
#define BrinGetPagesPerRange(relation)
Definition: brin.h:39
#define OidIsValid(objectId)
Definition: c.h:651
Relation bs_irel
Definition: brin.c:49
bool amoptionalkey
Definition: amapi.h:229
BlockNumber bs_currRangeStart
Definition: brin.c:53
void brinendscan(IndexScanDesc scan)
Definition: brin.c:589
amvalidate_function amvalidate
Definition: amapi.h:268
BlockNumber bo_pagesPerRange
Definition: brin.c:64
Size PageGetFreeSpace(Page page)
Definition: bufpage.c:782
signed int int32
Definition: c.h:362
void * build_reloptions(Datum reloptions, bool validate, relopt_kind kind, Size relopt_struct_size, const relopt_parse_elt *relopt_elems, int num_relopt_elems)
Definition: reloptions.c:1887
Relation indexRelation
Definition: relscan.h:115
bytea * brinoptions(Datum reloptions, bool validate)
Definition: brin.c:828
uint16 OffsetNumber
Definition: off.h:24
void brin_page_cleanup(Relation idxrel, Buffer buf)
Definition: brin_pageops.c:620
Definition: type.h:89
OffsetNumber brin_doinsert(Relation idxrel, BlockNumber pagesPerRange, BrinRevmap *revmap, Buffer *buffer, BlockNumber heapBlk, BrinTuple *tup, Size itemsz)
Definition: brin_pageops.c:343
Datum brin_summarize_range(PG_FUNCTION_ARGS)
Definition: brin.c:861
BrinMemTuple * brin_deform_tuple(BrinDesc *brdesc, BrinTuple *tuple, BrinMemTuple *dMemtuple)
Definition: brin_tuple.c:420
IndexUniqueCheck
Definition: genam.h:112
struct BrinOpaque BrinOpaque
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3294
#define BRIN_PROCNUM_ADDVALUE
Definition: brin_internal.h:68
BlockNumber bs_pagesPerRange
Definition: brin.c:52
void pfree(void *pointer)
Definition: mcxt.c:1057
#define ItemIdGetLength(itemId)
Definition: itemid.h:59
amgetbitmap_function amgetbitmap
Definition: amapi.h:273
void brin_metapage_init(Page page, BlockNumber pagesPerRange, uint16 version)
Definition: brin_pageops.c:487
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3534
bool bt_placeholder
Definition: brin_tuple.h:38
Oid * rd_indcollation
Definition: rel.h:199
#define ERROR
Definition: elog.h:43
#define MaxBlockNumber
Definition: block.h:35
Relation bd_index
Definition: brin_internal.h:47
ambuild_function ambuild
Definition: amapi.h:258
amoptions_function amoptions
Definition: amapi.h:265
static double table_index_build_scan(Relation table_rel, Relation index_rel, struct IndexInfo *index_info, bool allow_sync, bool progress, IndexBuildCallback callback, void *callback_state, TableScanDesc scan)
Definition: tableam.h:1552
BlockNumber num_pages
Definition: genam.h:74
static void callback(struct sockaddr *addr, struct sockaddr *mask, void *unused)
Definition: test_ifaddrs.c:48
bool amcaninclude
Definition: amapi.h:243
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
void fmgr_info_copy(FmgrInfo *dstinfo, FmgrInfo *srcinfo, MemoryContext destcxt)
Definition: fmgr.c:612
Datum brin_desummarize_range(PG_FUNCTION_ARGS)
Definition: brin.c:938
#define DEBUG2
Definition: elog.h:24
amcostestimate_function amcostestimate
Definition: amapi.h:264
uint16 oi_nstored
Definition: brin_internal.h:28
bool amcanunique
Definition: amapi.h:225
int bd_totalstored
Definition: brin_internal.h:56
struct BrinBuildState BrinBuildState
BrinValues bt_columns[FLEXIBLE_ARRAY_MEMBER]
Definition: brin_tuple.h:46
#define BufferIsInvalid(buffer)
Definition: buf.h:31
#define BRIN_PROCNUM_OPTIONS
Definition: brin_internal.h:72
static char * buf
Definition: pg_test_fsync.c:68
amvacuumcleanup_function amvacuumcleanup
Definition: amapi.h:262
BrinRevmap * bo_rmAccess
Definition: brin.c:65
amendscan_function amendscan
Definition: amapi.h:274
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
static double table_index_build_range_scan(Relation table_rel, Relation index_rel, struct IndexInfo *index_info, bool allow_sync, bool anyvisible, bool progress, BlockNumber start_blockno, BlockNumber numblocks, IndexBuildCallback callback, void *callback_state, TableScanDesc scan)
Definition: tableam.h:1585
bool amcanbackward
Definition: amapi.h:223
#define FirstOffsetNumber
Definition: off.h:27
#define REGBUF_STANDARD
Definition: xloginsert.h:35
static void brin_vacuum_scan(Relation idxrel, BufferAccessStrategy strategy)
Definition: brin.c:1463
BrinRevmap * bs_rmAccess
Definition: brin.c:54
#define DatumGetBool(X)
Definition: postgres.h:393
#define RelationGetRelationName(relation)
Definition: rel.h:490
static void brinbuildCallback(Relation index, ItemPointer tid, Datum *values, bool *isnull, bool tupleIsAlive, void *brstate)
Definition: brin.c:606
#define pgstat_count_index_scan(rel)
Definition: pgstat.h:1417
TupleDesc bd_tupdesc
Definition: brin_internal.h:50
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
void brinrescan(IndexScanDesc scan, ScanKey scankey, int nscankeys, ScanKey orderbys, int norderbys)
Definition: brin.c:569
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
Datum Int64GetDatum(int64 X)
Definition: fmgr.c:1701
#define SK_ISNULL
Definition: skey.h:115
#define BufferGetPage(buffer)
Definition: bufmgr.h:169
static void brinsummarize(Relation index, Relation heapRel, BlockNumber pageRange, bool include_partial, double *numSummarized, double *numExisting)
Definition: brin.c:1304
bool brin_can_do_samepage_update(Buffer buffer, Size origsz, Size newsz)
Definition: brin_pageops.c:324
amrescan_function amrescan
Definition: amapi.h:271
bool amcanparallel
Definition: amapi.h:241
IndexScanDesc brinbeginscan(Relation r, int nkeys, int norderbys)
Definition: brin.c:346
void * ii_AmCache
Definition: execnodes.h:178
void FreeSpaceMapVacuum(Relation rel)
Definition: freespace.c:335
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:235
BlockNumber lastRevmapPage
Definition: brin_page.h:69
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:330
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
bool amsearchnulls
Definition: amapi.h:233
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:422
BrinDesc * bo_bdesc
Definition: brin.c:66
void * palloc0(Size size)
Definition: mcxt.c:981
#define PageGetContents(page)
Definition: bufpage.h:246
uintptr_t Datum
Definition: postgres.h:367
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3750
bool amclusterable
Definition: amapi.h:237
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:211
BrinOpcInfo * bd_info[FLEXIBLE_ARRAY_MEMBER]
Definition: brin_internal.h:59
bool amsearcharray
Definition: amapi.h:231
#define InvalidOid
Definition: postgres_ext.h:36
BlockNumber pagesPerRange
Definition: brin.h:33
#define ereport(elevel,...)
Definition: elog.h:144
Datum FunctionCall3Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2, Datum arg3)
Definition: fmgr.c:1174
bool amusemaintenanceworkmem
Definition: amapi.h:245
BlockNumber pagesPerRange
Definition: brin_page.h:68
void brin_free_tuple(BrinTuple *tuple)
Definition: brin_tuple.c:306
#define PG_RETURN_VOID()
Definition: fmgr.h:348
#define makeNode(_type_)
Definition: nodes.h:576
BrinDesc * brin_build_desc(Relation rel)
Definition: brin.c:1019
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
int sk_flags
Definition: skey.h:66
amadjustmembers_function amadjustmembers
Definition: amapi.h:269
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:745
Definition: regguts.h:298
#define BRIN_PROCNUM_CONSISTENT
Definition: brin_internal.h:69
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4687
bool brinRevmapDesummarizeRange(Relation idxrel, BlockNumber heapBlk)
Definition: brin_revmap.c:328
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:607
size_t Size
Definition: c.h:473
void brincostestimate(PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
Definition: selfuncs.c:7334
BrinRevmap * brinRevmapInitialize(Relation idxrel, BlockNumber *pagesPerRange, Snapshot snapshot)
Definition: brin_revmap.c:71
#define BufferIsValid(bufnum)
Definition: bufmgr.h:123
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:117
ammarkpos_function ammarkpos
Definition: amapi.h:275
bool amcanorder
Definition: amapi.h:219
ambuildphasename_function ambuildphasename
Definition: amapi.h:267
#define RelationNeedsWAL(relation)
Definition: rel.h:562
amestimateparallelscan_function amestimateparallelscan
Definition: amapi.h:279
#define INT64_FORMAT
Definition: c.h:416
#define DatumGetPointer(X)
Definition: postgres.h:549
struct ScanKeyData * keyData
Definition: relscan.h:119
#define BRIN_ALL_BLOCKRANGES
Definition: brin.c:69
int bs_numtuples
Definition: brin.c:50
MemoryContext bd_context
Definition: brin_internal.h:44
#define BRIN_LAST_OPTIONAL_PROCNUM
Definition: brin_internal.h:75
static Datum values[MAXATTR]
Definition: bootstrap.c:165
uint16 amstrategies
Definition: amapi.h:213
#define BRIN_PROCNUM_UNION
Definition: brin_internal.h:70
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition: bufmgr.c:2661
void tbm_add_page(TIDBitmap *tbm, BlockNumber pageno)
Definition: tidbitmap.c:442
#define BrinGetAutoSummarize(relation)
Definition: brin.h:45
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:824
uint16 amoptsprocnum
Definition: amapi.h:217
TupleDesc bd_disktdesc
Definition: brin_internal.h:53
BrinTuple * brin_form_tuple(BrinDesc *brdesc, BlockNumber blkno, BrinMemTuple *tuple, Size *size)
Definition: brin_tuple.c:88
Oid sk_collation
Definition: skey.h:70
#define elog(elevel,...)
Definition: elog.h:214
ambuildempty_function ambuildempty
Definition: amapi.h:259
int i
#define FunctionCall1(flinfo, arg1)
Definition: fmgr.h:642
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:97
IndexBulkDeleteResult * brinvacuumcleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats)
Definition: brin.c:798
BlockNumber pagesPerRange
Definition: brin_xlog.h:52
IndexScanDesc RelationGetIndexScan(Relation indexRelation, int nkeys, int norderbys)
Definition: genam.c:81
int tdrefcount
Definition: tupdesc.h:84
Definition: c.h:562
#define PG_FUNCTION_ARGS
Definition: fmgr.h:193
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
Datum brin_summarize_new_values(PG_FUNCTION_ARGS)
Definition: brin.c:846
BrinMemTuple * bs_dtuple
Definition: brin.c:56
static BrinBuildState * initialize_brin_buildstate(Relation idxRel, BrinRevmap *revmap, BlockNumber pagesPerRange)
Definition: brin.c:1107
void brinbuildempty(Relation index)
Definition: brin.c:753
BrinDesc * bs_bdesc
Definition: brin.c:55
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void XLogBeginInsert(void)
Definition: xloginsert.c:123
#define PG_GETARG_INT64(n)
Definition: fmgr.h:282
#define VACUUM_OPTION_PARALLEL_CLEANUP
Definition: vacuum.h:60
#define PageSetLSN(page, lsn)
Definition: bufpage.h:368
double num_index_tuples
Definition: genam.h:77
int Buffer
Definition: buf.h:23
BrinTuple * brin_form_placeholder_tuple(BrinDesc *brdesc, BlockNumber blkno, Size *size)
Definition: brin_tuple.c:261
amcanreturn_function amcanreturn
Definition: amapi.h:263
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:456
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
void FreeSpaceMapVacuumRange(Relation rel, BlockNumber start, BlockNumber end)
Definition: freespace.c:354
#define DirectFunctionCall2(func, arg1, arg2)
Definition: fmgr.h:626
Datum brinhandler(PG_FUNCTION_ARGS)
Definition: brin.c:87
#define offsetof(type, field)
Definition: c.h:668
AttrNumber sk_attno
Definition: skey.h:67
Pointer Page
Definition: bufpage.h:78
double index_tuples
Definition: genam.h:33
bool(* IndexBulkDeleteCallback)(ItemPointer itemptr, void *state)
Definition: genam.h:84
aminitparallelscan_function aminitparallelscan
Definition: amapi.h:280
double heap_tuples
Definition: genam.h:32
BrinMemTuple * brin_memtuple_initialize(BrinMemTuple *dtuple, BrinDesc *brdesc)
Definition: brin_tuple.c:382
void brinGetStats(Relation index, BrinStatsData *stats)
Definition: brin.c:1086
static void terminate_brin_buildstate(BrinBuildState *state)
Definition: brin.c:1132
BlockNumber revmapNumPages
Definition: brin.h:34
amrestrpos_function amrestrpos
Definition: amapi.h:276