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