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-2023, 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/datum.h"
39 #include "utils/guc.h"
40 #include "utils/index_selfuncs.h"
41 #include "utils/memutils.h"
42 #include "utils/rel.h"
43 
44 
45 /*
46  * We use a BrinBuildState during initial construction of a BRIN index.
47  * The running state is kept in a BrinMemTuple.
48  */
49 typedef struct BrinBuildState
50 {
60 
61 /*
62  * Struct used as "opaque" during index scans
63  */
64 typedef struct BrinOpaque
65 {
70 
71 #define BRIN_ALL_BLOCKRANGES InvalidBlockNumber
72 
74  BrinRevmap *revmap, BlockNumber pagesPerRange);
76 static void brinsummarize(Relation index, Relation heapRel, BlockNumber pageRange,
77  bool include_partial, double *numSummarized, double *numExisting);
79 static void union_tuples(BrinDesc *bdesc, BrinMemTuple *a,
80  BrinTuple *b);
81 static void brin_vacuum_scan(Relation idxrel, BufferAccessStrategy strategy);
82 static bool add_values_to_range(Relation idxRel, BrinDesc *bdesc,
83  BrinMemTuple *dtup, Datum *values, bool *nulls);
84 static bool check_null_keys(BrinValues *bval, ScanKey *nullkeys, int nnullkeys);
85 
86 /*
87  * BRIN handler function: return IndexAmRoutine with access method parameters
88  * and callbacks.
89  */
90 Datum
92 {
94 
95  amroutine->amstrategies = 0;
98  amroutine->amcanorder = false;
99  amroutine->amcanorderbyop = false;
100  amroutine->amcanbackward = false;
101  amroutine->amcanunique = false;
102  amroutine->amcanmulticol = true;
103  amroutine->amoptionalkey = true;
104  amroutine->amsearcharray = false;
105  amroutine->amsearchnulls = true;
106  amroutine->amstorage = true;
107  amroutine->amclusterable = false;
108  amroutine->ampredlocks = false;
109  amroutine->amcanparallel = false;
110  amroutine->amcaninclude = false;
111  amroutine->amusemaintenanceworkmem = false;
112  amroutine->amsummarizing = true;
113  amroutine->amparallelvacuumoptions =
115  amroutine->amkeytype = InvalidOid;
116 
117  amroutine->ambuild = brinbuild;
118  amroutine->ambuildempty = brinbuildempty;
119  amroutine->aminsert = brininsert;
120  amroutine->ambulkdelete = brinbulkdelete;
121  amroutine->amvacuumcleanup = brinvacuumcleanup;
122  amroutine->amcanreturn = NULL;
123  amroutine->amcostestimate = brincostestimate;
124  amroutine->amoptions = brinoptions;
125  amroutine->amproperty = NULL;
126  amroutine->ambuildphasename = NULL;
127  amroutine->amvalidate = brinvalidate;
128  amroutine->amadjustmembers = NULL;
129  amroutine->ambeginscan = brinbeginscan;
130  amroutine->amrescan = brinrescan;
131  amroutine->amgettuple = NULL;
132  amroutine->amgetbitmap = bringetbitmap;
133  amroutine->amendscan = brinendscan;
134  amroutine->ammarkpos = NULL;
135  amroutine->amrestrpos = NULL;
136  amroutine->amestimateparallelscan = NULL;
137  amroutine->aminitparallelscan = NULL;
138  amroutine->amparallelrescan = NULL;
139 
140  PG_RETURN_POINTER(amroutine);
141 }
142 
143 /*
144  * A tuple in the heap is being inserted. To keep a brin index up to date,
145  * we need to obtain the relevant index tuple and compare its stored values
146  * with those of the new tuple. If the tuple values are not consistent with
147  * the summary tuple, we need to update the index tuple.
148  *
149  * If autosummarization is enabled, check if we need to summarize the previous
150  * page range.
151  *
152  * If the range is not currently summarized (i.e. the revmap returns NULL for
153  * it), there's nothing to do for this tuple.
154  */
155 bool
156 brininsert(Relation idxRel, Datum *values, bool *nulls,
157  ItemPointer heaptid, Relation heapRel,
158  IndexUniqueCheck checkUnique,
159  bool indexUnchanged,
160  IndexInfo *indexInfo)
161 {
162  BlockNumber pagesPerRange;
163  BlockNumber origHeapBlk;
164  BlockNumber heapBlk;
165  BrinDesc *bdesc = (BrinDesc *) indexInfo->ii_AmCache;
166  BrinRevmap *revmap;
168  MemoryContext tupcxt = NULL;
170  bool autosummarize = BrinGetAutoSummarize(idxRel);
171 
172  revmap = brinRevmapInitialize(idxRel, &pagesPerRange, NULL);
173 
174  /*
175  * origHeapBlk is the block number where the insertion occurred. heapBlk
176  * is the first block in the corresponding page range.
177  */
178  origHeapBlk = ItemPointerGetBlockNumber(heaptid);
179  heapBlk = (origHeapBlk / pagesPerRange) * pagesPerRange;
180 
181  for (;;)
182  {
183  bool need_insert = false;
184  OffsetNumber off;
185  BrinTuple *brtup;
186  BrinMemTuple *dtup;
187 
189 
190  /*
191  * If auto-summarization is enabled and we just inserted the first
192  * tuple into the first block of a new non-first page range, request a
193  * summarization run of the previous range.
194  */
195  if (autosummarize &&
196  heapBlk > 0 &&
197  heapBlk == origHeapBlk &&
199  {
200  BlockNumber lastPageRange = heapBlk - 1;
201  BrinTuple *lastPageTuple;
202 
203  lastPageTuple =
204  brinGetTupleForHeapBlock(revmap, lastPageRange, &buf, &off,
205  NULL, BUFFER_LOCK_SHARE, NULL);
206  if (!lastPageTuple)
207  {
208  bool recorded;
209 
211  RelationGetRelid(idxRel),
212  lastPageRange);
213  if (!recorded)
214  ereport(LOG,
215  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
216  errmsg("request for BRIN range summarization for index \"%s\" page %u was not recorded",
217  RelationGetRelationName(idxRel),
218  lastPageRange)));
219  }
220  else
222  }
223 
224  brtup = brinGetTupleForHeapBlock(revmap, heapBlk, &buf, &off,
225  NULL, BUFFER_LOCK_SHARE, NULL);
226 
227  /* if range is unsummarized, there's nothing to do */
228  if (!brtup)
229  break;
230 
231  /* First time through in this statement? */
232  if (bdesc == NULL)
233  {
234  MemoryContextSwitchTo(indexInfo->ii_Context);
235  bdesc = brin_build_desc(idxRel);
236  indexInfo->ii_AmCache = (void *) bdesc;
237  MemoryContextSwitchTo(oldcxt);
238  }
239  /* First time through in this brininsert call? */
240  if (tupcxt == NULL)
241  {
243  "brininsert cxt",
245  MemoryContextSwitchTo(tupcxt);
246  }
247 
248  dtup = brin_deform_tuple(bdesc, brtup, NULL);
249 
250  need_insert = add_values_to_range(idxRel, bdesc, dtup, values, nulls);
251 
252  if (!need_insert)
253  {
254  /*
255  * The tuple is consistent with the new values, so there's nothing
256  * to do.
257  */
259  }
260  else
261  {
262  Page page = BufferGetPage(buf);
263  ItemId lp = PageGetItemId(page, off);
264  Size origsz;
265  BrinTuple *origtup;
266  Size newsz;
267  BrinTuple *newtup;
268  bool samepage;
269 
270  /*
271  * Make a copy of the old tuple, so that we can compare it after
272  * re-acquiring the lock.
273  */
274  origsz = ItemIdGetLength(lp);
275  origtup = brin_copy_tuple(brtup, origsz, NULL, NULL);
276 
277  /*
278  * Before releasing the lock, check if we can attempt a same-page
279  * update. Another process could insert a tuple concurrently in
280  * the same page though, so downstream we must be prepared to cope
281  * if this turns out to not be possible after all.
282  */
283  newtup = brin_form_tuple(bdesc, heapBlk, dtup, &newsz);
284  samepage = brin_can_do_samepage_update(buf, origsz, newsz);
286 
287  /*
288  * Try to update the tuple. If this doesn't work for whatever
289  * reason, we need to restart from the top; the revmap might be
290  * pointing at a different tuple for this block now, so we need to
291  * recompute to ensure both our new heap tuple and the other
292  * inserter's are covered by the combined tuple. It might be that
293  * we don't need to update at all.
294  */
295  if (!brin_doupdate(idxRel, pagesPerRange, revmap, heapBlk,
296  buf, off, origtup, origsz, newtup, newsz,
297  samepage))
298  {
299  /* no luck; start over */
301  continue;
302  }
303  }
304 
305  /* success! */
306  break;
307  }
308 
309  brinRevmapTerminate(revmap);
310  if (BufferIsValid(buf))
312  MemoryContextSwitchTo(oldcxt);
313  if (tupcxt != NULL)
314  MemoryContextDelete(tupcxt);
315 
316  return false;
317 }
318 
319 /*
320  * Initialize state for a BRIN index scan.
321  *
322  * We read the metapage here to determine the pages-per-range number that this
323  * index was built with. Note that since this cannot be changed while we're
324  * holding lock on index, it's not necessary to recompute it during brinrescan.
325  */
327 brinbeginscan(Relation r, int nkeys, int norderbys)
328 {
329  IndexScanDesc scan;
330  BrinOpaque *opaque;
331 
332  scan = RelationGetIndexScan(r, nkeys, norderbys);
333 
334  opaque = palloc_object(BrinOpaque);
335  opaque->bo_rmAccess = brinRevmapInitialize(r, &opaque->bo_pagesPerRange,
336  scan->xs_snapshot);
337  opaque->bo_bdesc = brin_build_desc(r);
338  scan->opaque = opaque;
339 
340  return scan;
341 }
342 
343 /*
344  * Execute the index scan.
345  *
346  * This works by reading index TIDs from the revmap, and obtaining the index
347  * tuples pointed to by them; the summary values in the index tuples are
348  * compared to the scan keys. We return into the TID bitmap all the pages in
349  * ranges corresponding to index tuples that match the scan keys.
350  *
351  * If a TID from the revmap is read as InvalidTID, we know that range is
352  * unsummarized. Pages in those ranges need to be returned regardless of scan
353  * keys.
354  */
355 int64
357 {
358  Relation idxRel = scan->indexRelation;
360  BrinDesc *bdesc;
361  Oid heapOid;
362  Relation heapRel;
363  BrinOpaque *opaque;
364  BlockNumber nblocks;
365  BlockNumber heapBlk;
366  int totalpages = 0;
367  FmgrInfo *consistentFn;
368  MemoryContext oldcxt;
369  MemoryContext perRangeCxt;
370  BrinMemTuple *dtup;
371  BrinTuple *btup = NULL;
372  Size btupsz = 0;
373  ScanKey **keys,
374  **nullkeys;
375  int *nkeys,
376  *nnullkeys;
377  char *ptr;
378  Size len;
379  char *tmp PG_USED_FOR_ASSERTS_ONLY;
380 
381  opaque = (BrinOpaque *) scan->opaque;
382  bdesc = opaque->bo_bdesc;
383  pgstat_count_index_scan(idxRel);
384 
385  /*
386  * We need to know the size of the table so that we know how long to
387  * iterate on the revmap.
388  */
389  heapOid = IndexGetRelation(RelationGetRelid(idxRel), false);
390  heapRel = table_open(heapOid, AccessShareLock);
391  nblocks = RelationGetNumberOfBlocks(heapRel);
392  table_close(heapRel, AccessShareLock);
393 
394  /*
395  * Make room for the consistent support procedures of indexed columns. We
396  * don't look them up here; we do that lazily the first time we see a scan
397  * key reference each of them. We rely on zeroing fn_oid to InvalidOid.
398  */
399  consistentFn = palloc0_array(FmgrInfo, bdesc->bd_tupdesc->natts);
400 
401  /*
402  * Make room for per-attribute lists of scan keys that we'll pass to the
403  * consistent support procedure. We don't know which attributes have scan
404  * keys, so we allocate space for all attributes. That may use more memory
405  * but it's probably cheaper than determining which attributes are used.
406  *
407  * We keep null and regular keys separate, so that we can pass just the
408  * regular keys to the consistent function easily.
409  *
410  * To reduce the allocation overhead, we allocate one big chunk and then
411  * carve it into smaller arrays ourselves. All the pieces have exactly the
412  * same lifetime, so that's OK.
413  *
414  * XXX The widest index can have 32 attributes, so the amount of wasted
415  * memory is negligible. We could invent a more compact approach (with
416  * just space for used attributes) but that would make the matching more
417  * complex so it's not a good trade-off.
418  */
419  len =
420  MAXALIGN(sizeof(ScanKey *) * bdesc->bd_tupdesc->natts) + /* regular keys */
421  MAXALIGN(sizeof(ScanKey) * scan->numberOfKeys) * bdesc->bd_tupdesc->natts +
422  MAXALIGN(sizeof(int) * bdesc->bd_tupdesc->natts) +
423  MAXALIGN(sizeof(ScanKey *) * bdesc->bd_tupdesc->natts) + /* NULL keys */
424  MAXALIGN(sizeof(ScanKey) * scan->numberOfKeys) * bdesc->bd_tupdesc->natts +
425  MAXALIGN(sizeof(int) * bdesc->bd_tupdesc->natts);
426 
427  ptr = palloc(len);
428  tmp = ptr;
429 
430  keys = (ScanKey **) ptr;
431  ptr += MAXALIGN(sizeof(ScanKey *) * bdesc->bd_tupdesc->natts);
432 
433  nullkeys = (ScanKey **) ptr;
434  ptr += MAXALIGN(sizeof(ScanKey *) * bdesc->bd_tupdesc->natts);
435 
436  nkeys = (int *) ptr;
437  ptr += MAXALIGN(sizeof(int) * bdesc->bd_tupdesc->natts);
438 
439  nnullkeys = (int *) ptr;
440  ptr += MAXALIGN(sizeof(int) * bdesc->bd_tupdesc->natts);
441 
442  for (int i = 0; i < bdesc->bd_tupdesc->natts; i++)
443  {
444  keys[i] = (ScanKey *) ptr;
445  ptr += MAXALIGN(sizeof(ScanKey) * scan->numberOfKeys);
446 
447  nullkeys[i] = (ScanKey *) ptr;
448  ptr += MAXALIGN(sizeof(ScanKey) * scan->numberOfKeys);
449  }
450 
451  Assert(tmp + len == ptr);
452 
453  /* zero the number of keys */
454  memset(nkeys, 0, sizeof(int) * bdesc->bd_tupdesc->natts);
455  memset(nnullkeys, 0, sizeof(int) * bdesc->bd_tupdesc->natts);
456 
457  /* Preprocess the scan keys - split them into per-attribute arrays. */
458  for (int keyno = 0; keyno < scan->numberOfKeys; keyno++)
459  {
460  ScanKey key = &scan->keyData[keyno];
461  AttrNumber keyattno = key->sk_attno;
462 
463  /*
464  * The collation of the scan key must match the collation used in the
465  * index column (but only if the search is not IS NULL/ IS NOT NULL).
466  * Otherwise we shouldn't be using this index ...
467  */
468  Assert((key->sk_flags & SK_ISNULL) ||
469  (key->sk_collation ==
470  TupleDescAttr(bdesc->bd_tupdesc,
471  keyattno - 1)->attcollation));
472 
473  /*
474  * First time we see this index attribute, so init as needed.
475  *
476  * This is a bit of an overkill - we don't know how many scan keys are
477  * there for this attribute, so we simply allocate the largest number
478  * possible (as if all keys were for this attribute). This may waste a
479  * bit of memory, but we only expect small number of scan keys in
480  * general, so this should be negligible, and repeated repalloc calls
481  * are not free either.
482  */
483  if (consistentFn[keyattno - 1].fn_oid == InvalidOid)
484  {
485  FmgrInfo *tmp;
486 
487  /* First time we see this attribute, so no key/null keys. */
488  Assert(nkeys[keyattno - 1] == 0);
489  Assert(nnullkeys[keyattno - 1] == 0);
490 
491  tmp = index_getprocinfo(idxRel, keyattno,
493  fmgr_info_copy(&consistentFn[keyattno - 1], tmp,
495  }
496 
497  /* Add key to the proper per-attribute array. */
498  if (key->sk_flags & SK_ISNULL)
499  {
500  nullkeys[keyattno - 1][nnullkeys[keyattno - 1]] = key;
501  nnullkeys[keyattno - 1]++;
502  }
503  else
504  {
505  keys[keyattno - 1][nkeys[keyattno - 1]] = key;
506  nkeys[keyattno - 1]++;
507  }
508  }
509 
510  /* allocate an initial in-memory tuple, out of the per-range memcxt */
511  dtup = brin_new_memtuple(bdesc);
512 
513  /*
514  * Setup and use a per-range memory context, which is reset every time we
515  * loop below. This avoids having to free the tuples within the loop.
516  */
518  "bringetbitmap cxt",
520  oldcxt = MemoryContextSwitchTo(perRangeCxt);
521 
522  /*
523  * Now scan the revmap. We start by querying for heap page 0,
524  * incrementing by the number of pages per range; this gives us a full
525  * view of the table.
526  */
527  for (heapBlk = 0; heapBlk < nblocks; heapBlk += opaque->bo_pagesPerRange)
528  {
529  bool addrange;
530  bool gottuple = false;
531  BrinTuple *tup;
532  OffsetNumber off;
533  Size size;
534 
536 
538 
539  tup = brinGetTupleForHeapBlock(opaque->bo_rmAccess, heapBlk, &buf,
540  &off, &size, BUFFER_LOCK_SHARE,
541  scan->xs_snapshot);
542  if (tup)
543  {
544  gottuple = true;
545  btup = brin_copy_tuple(tup, size, btup, &btupsz);
547  }
548 
549  /*
550  * For page ranges with no indexed tuple, we must return the whole
551  * range; otherwise, compare it to the scan keys.
552  */
553  if (!gottuple)
554  {
555  addrange = true;
556  }
557  else
558  {
559  dtup = brin_deform_tuple(bdesc, btup, dtup);
560  if (dtup->bt_placeholder)
561  {
562  /*
563  * Placeholder tuples are always returned, regardless of the
564  * values stored in them.
565  */
566  addrange = true;
567  }
568  else
569  {
570  int attno;
571 
572  /*
573  * Compare scan keys with summary values stored for the range.
574  * If scan keys are matched, the page range must be added to
575  * the bitmap. We initially assume the range needs to be
576  * added; in particular this serves the case where there are
577  * no keys.
578  */
579  addrange = true;
580  for (attno = 1; attno <= bdesc->bd_tupdesc->natts; attno++)
581  {
582  BrinValues *bval;
583  Datum add;
584  Oid collation;
585 
586  /*
587  * skip attributes without any scan keys (both regular and
588  * IS [NOT] NULL)
589  */
590  if (nkeys[attno - 1] == 0 && nnullkeys[attno - 1] == 0)
591  continue;
592 
593  bval = &dtup->bt_columns[attno - 1];
594 
595  /*
596  * First check if there are any IS [NOT] NULL scan keys,
597  * and if we're violating them. In that case we can
598  * terminate early, without invoking the support function.
599  *
600  * As there may be more keys, we can only determine
601  * mismatch within this loop.
602  */
603  if (bdesc->bd_info[attno - 1]->oi_regular_nulls &&
604  !check_null_keys(bval, nullkeys[attno - 1],
605  nnullkeys[attno - 1]))
606  {
607  /*
608  * If any of the IS [NOT] NULL keys failed, the page
609  * range as a whole can't pass. So terminate the loop.
610  */
611  addrange = false;
612  break;
613  }
614 
615  /*
616  * So either there are no IS [NOT] NULL keys, or all
617  * passed. If there are no regular scan keys, we're done -
618  * the page range matches. If there are regular keys, but
619  * the page range is marked as 'all nulls' it can't
620  * possibly pass (we're assuming the operators are
621  * strict).
622  */
623 
624  /* No regular scan keys - page range as a whole passes. */
625  if (!nkeys[attno - 1])
626  continue;
627 
628  Assert((nkeys[attno - 1] > 0) &&
629  (nkeys[attno - 1] <= scan->numberOfKeys));
630 
631  /* If it is all nulls, it cannot possibly be consistent. */
632  if (bval->bv_allnulls)
633  {
634  addrange = false;
635  break;
636  }
637 
638  /*
639  * Collation from the first key (has to be the same for
640  * all keys for the same attribute).
641  */
642  collation = keys[attno - 1][0]->sk_collation;
643 
644  /*
645  * Check whether the scan key is consistent with the page
646  * range values; if so, have the pages in the range added
647  * to the output bitmap.
648  *
649  * The opclass may or may not support processing of
650  * multiple scan keys. We can determine that based on the
651  * number of arguments - functions with extra parameter
652  * (number of scan keys) do support this, otherwise we
653  * have to simply pass the scan keys one by one.
654  */
655  if (consistentFn[attno - 1].fn_nargs >= 4)
656  {
657  /* Check all keys at once */
658  add = FunctionCall4Coll(&consistentFn[attno - 1],
659  collation,
660  PointerGetDatum(bdesc),
661  PointerGetDatum(bval),
662  PointerGetDatum(keys[attno - 1]),
663  Int32GetDatum(nkeys[attno - 1]));
664  addrange = DatumGetBool(add);
665  }
666  else
667  {
668  /*
669  * Check keys one by one
670  *
671  * When there are multiple scan keys, failure to meet
672  * the criteria for a single one of them is enough to
673  * discard the range as a whole, so break out of the
674  * loop as soon as a false return value is obtained.
675  */
676  int keyno;
677 
678  for (keyno = 0; keyno < nkeys[attno - 1]; keyno++)
679  {
680  add = FunctionCall3Coll(&consistentFn[attno - 1],
681  keys[attno - 1][keyno]->sk_collation,
682  PointerGetDatum(bdesc),
683  PointerGetDatum(bval),
684  PointerGetDatum(keys[attno - 1][keyno]));
685  addrange = DatumGetBool(add);
686  if (!addrange)
687  break;
688  }
689  }
690 
691  /*
692  * If we found a scan key eliminating the range, no need to
693  * check additional ones.
694  */
695  if (!addrange)
696  break;
697  }
698  }
699  }
700 
701  /* add the pages in the range to the output bitmap, if needed */
702  if (addrange)
703  {
704  BlockNumber pageno;
705 
706  for (pageno = heapBlk;
707  pageno <= Min(nblocks, heapBlk + opaque->bo_pagesPerRange) - 1;
708  pageno++)
709  {
710  MemoryContextSwitchTo(oldcxt);
711  tbm_add_page(tbm, pageno);
712  totalpages++;
713  MemoryContextSwitchTo(perRangeCxt);
714  }
715  }
716  }
717 
718  MemoryContextSwitchTo(oldcxt);
719  MemoryContextDelete(perRangeCxt);
720 
721  if (buf != InvalidBuffer)
723 
724  /*
725  * XXX We have an approximation of the number of *pages* that our scan
726  * returns, but we don't have a precise idea of the number of heap tuples
727  * involved.
728  */
729  return totalpages * 10;
730 }
731 
732 /*
733  * Re-initialize state for a BRIN index scan
734  */
735 void
736 brinrescan(IndexScanDesc scan, ScanKey scankey, int nscankeys,
737  ScanKey orderbys, int norderbys)
738 {
739  /*
740  * Other index AMs preprocess the scan keys at this point, or sometime
741  * early during the scan; this lets them optimize by removing redundant
742  * keys, or doing early returns when they are impossible to satisfy; see
743  * _bt_preprocess_keys for an example. Something like that could be added
744  * here someday, too.
745  */
746 
747  if (scankey && scan->numberOfKeys > 0)
748  memmove(scan->keyData, scankey,
749  scan->numberOfKeys * sizeof(ScanKeyData));
750 }
751 
752 /*
753  * Close down a BRIN index scan
754  */
755 void
757 {
758  BrinOpaque *opaque = (BrinOpaque *) scan->opaque;
759 
761  brin_free_desc(opaque->bo_bdesc);
762  pfree(opaque);
763 }
764 
765 /*
766  * Per-heap-tuple callback for table_index_build_scan.
767  *
768  * Note we don't worry about the page range at the end of the table here; it is
769  * present in the build state struct after we're called the last time, but not
770  * inserted into the index. Caller must ensure to do so, if appropriate.
771  */
772 static void
774  ItemPointer tid,
775  Datum *values,
776  bool *isnull,
777  bool tupleIsAlive,
778  void *brstate)
779 {
780  BrinBuildState *state = (BrinBuildState *) brstate;
781  BlockNumber thisblock;
782 
783  thisblock = ItemPointerGetBlockNumber(tid);
784 
785  /*
786  * If we're in a block that belongs to a future range, summarize what
787  * we've got and start afresh. Note the scan might have skipped many
788  * pages, if they were devoid of live tuples; make sure to insert index
789  * tuples for those too.
790  */
791  while (thisblock > state->bs_currRangeStart + state->bs_pagesPerRange - 1)
792  {
793 
794  BRIN_elog((DEBUG2,
795  "brinbuildCallback: completed a range: %u--%u",
796  state->bs_currRangeStart,
797  state->bs_currRangeStart + state->bs_pagesPerRange));
798 
799  /* create the index tuple and insert it */
801 
802  /* set state to correspond to the next range */
803  state->bs_currRangeStart += state->bs_pagesPerRange;
804 
805  /* re-initialize state for it */
806  brin_memtuple_initialize(state->bs_dtuple, state->bs_bdesc);
807  }
808 
809  /* Accumulate the current tuple into the running state */
810  (void) add_values_to_range(index, state->bs_bdesc, state->bs_dtuple,
811  values, isnull);
812 }
813 
814 /*
815  * brinbuild() -- build a new BRIN index.
816  */
819 {
820  IndexBuildResult *result;
821  double reltuples;
822  double idxtuples;
823  BrinRevmap *revmap;
825  Buffer meta;
826  BlockNumber pagesPerRange;
827 
828  /*
829  * We expect to be called exactly once for any index relation.
830  */
832  elog(ERROR, "index \"%s\" already contains data",
834 
835  /*
836  * Critical section not required, because on error the creation of the
837  * whole relation will be rolled back.
838  */
839 
840  meta = ReadBuffer(index, P_NEW);
843 
846  MarkBufferDirty(meta);
847 
848  if (RelationNeedsWAL(index))
849  {
850  xl_brin_createidx xlrec;
851  XLogRecPtr recptr;
852  Page page;
853 
856 
857  XLogBeginInsert();
858  XLogRegisterData((char *) &xlrec, SizeOfBrinCreateIdx);
860 
861  recptr = XLogInsert(RM_BRIN_ID, XLOG_BRIN_CREATE_INDEX);
862 
863  page = BufferGetPage(meta);
864  PageSetLSN(page, recptr);
865  }
866 
867  UnlockReleaseBuffer(meta);
868 
869  /*
870  * Initialize our state, including the deformed tuple state.
871  */
872  revmap = brinRevmapInitialize(index, &pagesPerRange, NULL);
873  state = initialize_brin_buildstate(index, revmap, pagesPerRange);
874 
875  /*
876  * Now scan the relation. No syncscan allowed here because we want the
877  * heap blocks in physical order.
878  */
879  reltuples = table_index_build_scan(heap, index, indexInfo, false, true,
880  brinbuildCallback, (void *) state, NULL);
881 
882  /* process the final batch */
884 
885  /* release resources */
886  idxtuples = state->bs_numtuples;
887  brinRevmapTerminate(state->bs_rmAccess);
889 
890  /*
891  * Return statistics
892  */
894 
895  result->heap_tuples = reltuples;
896  result->index_tuples = idxtuples;
897 
898  return result;
899 }
900 
901 void
903 {
904  Buffer metabuf;
905 
906  /* An empty BRIN index has a metapage only. */
907  metabuf =
910 
911  /* Initialize and xlog metabuffer. */
915  MarkBufferDirty(metabuf);
916  log_newpage_buffer(metabuf, true);
918 
919  UnlockReleaseBuffer(metabuf);
920 }
921 
922 /*
923  * brinbulkdelete
924  * Since there are no per-heap-tuple index tuples in BRIN indexes,
925  * there's not a lot we can do here.
926  *
927  * XXX we could mark item tuples as "dirty" (when a minimum or maximum heap
928  * tuple is deleted), meaning the need to re-run summarization on the affected
929  * range. Would need to add an extra flag in brintuples for that.
930  */
933  IndexBulkDeleteCallback callback, void *callback_state)
934 {
935  /* allocate stats if first time through, else re-use existing struct */
936  if (stats == NULL)
938 
939  return stats;
940 }
941 
942 /*
943  * This routine is in charge of "vacuuming" a BRIN index: we just summarize
944  * ranges that are currently unsummarized.
945  */
948 {
949  Relation heapRel;
950 
951  /* No-op in ANALYZE ONLY mode */
952  if (info->analyze_only)
953  return stats;
954 
955  if (!stats)
957  stats->num_pages = RelationGetNumberOfBlocks(info->index);
958  /* rest of stats is initialized by zeroing */
959 
960  heapRel = table_open(IndexGetRelation(RelationGetRelid(info->index), false),
962 
963  brin_vacuum_scan(info->index, info->strategy);
964 
965  brinsummarize(info->index, heapRel, BRIN_ALL_BLOCKRANGES, false,
966  &stats->num_index_tuples, &stats->num_index_tuples);
967 
968  table_close(heapRel, AccessShareLock);
969 
970  return stats;
971 }
972 
973 /*
974  * reloptions processor for BRIN indexes
975  */
976 bytea *
977 brinoptions(Datum reloptions, bool validate)
978 {
979  static const relopt_parse_elt tab[] = {
980  {"pages_per_range", RELOPT_TYPE_INT, offsetof(BrinOptions, pagesPerRange)},
981  {"autosummarize", RELOPT_TYPE_BOOL, offsetof(BrinOptions, autosummarize)}
982  };
983 
984  return (bytea *) build_reloptions(reloptions, validate,
986  sizeof(BrinOptions),
987  tab, lengthof(tab));
988 }
989 
990 /*
991  * SQL-callable function to scan through an index and summarize all ranges
992  * that are not currently summarized.
993  */
994 Datum
996 {
997  Datum relation = PG_GETARG_DATUM(0);
998 
1000  relation,
1002 }
1003 
1004 /*
1005  * SQL-callable function to summarize the indicated page range, if not already
1006  * summarized. If the second argument is BRIN_ALL_BLOCKRANGES, all
1007  * unsummarized ranges are summarized.
1008  */
1009 Datum
1011 {
1012  Oid indexoid = PG_GETARG_OID(0);
1013  int64 heapBlk64 = PG_GETARG_INT64(1);
1014  BlockNumber heapBlk;
1015  Oid heapoid;
1016  Relation indexRel;
1017  Relation heapRel;
1018  Oid save_userid;
1019  int save_sec_context;
1020  int save_nestlevel;
1021  double numSummarized = 0;
1022 
1023  if (RecoveryInProgress())
1024  ereport(ERROR,
1025  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1026  errmsg("recovery is in progress"),
1027  errhint("BRIN control functions cannot be executed during recovery.")));
1028 
1029  if (heapBlk64 > BRIN_ALL_BLOCKRANGES || heapBlk64 < 0)
1030  ereport(ERROR,
1031  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
1032  errmsg("block number out of range: %lld",
1033  (long long) heapBlk64)));
1034  heapBlk = (BlockNumber) heapBlk64;
1035 
1036  /*
1037  * We must lock table before index to avoid deadlocks. However, if the
1038  * passed indexoid isn't an index then IndexGetRelation() will fail.
1039  * Rather than emitting a not-very-helpful error message, postpone
1040  * complaining, expecting that the is-it-an-index test below will fail.
1041  */
1042  heapoid = IndexGetRelation(indexoid, true);
1043  if (OidIsValid(heapoid))
1044  {
1045  heapRel = table_open(heapoid, ShareUpdateExclusiveLock);
1046 
1047  /*
1048  * Autovacuum calls us. For its benefit, switch to the table owner's
1049  * userid, so that any index functions are run as that user. Also
1050  * lock down security-restricted operations and arrange to make GUC
1051  * variable changes local to this command. This is harmless, albeit
1052  * unnecessary, when called from SQL, because we fail shortly if the
1053  * user does not own the index.
1054  */
1055  GetUserIdAndSecContext(&save_userid, &save_sec_context);
1056  SetUserIdAndSecContext(heapRel->rd_rel->relowner,
1057  save_sec_context | SECURITY_RESTRICTED_OPERATION);
1058  save_nestlevel = NewGUCNestLevel();
1059  }
1060  else
1061  {
1062  heapRel = NULL;
1063  /* Set these just to suppress "uninitialized variable" warnings */
1064  save_userid = InvalidOid;
1065  save_sec_context = -1;
1066  save_nestlevel = -1;
1067  }
1068 
1069  indexRel = index_open(indexoid, ShareUpdateExclusiveLock);
1070 
1071  /* Must be a BRIN index */
1072  if (indexRel->rd_rel->relkind != RELKIND_INDEX ||
1073  indexRel->rd_rel->relam != BRIN_AM_OID)
1074  ereport(ERROR,
1075  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1076  errmsg("\"%s\" is not a BRIN index",
1077  RelationGetRelationName(indexRel))));
1078 
1079  /* User must own the index (comparable to privileges needed for VACUUM) */
1080  if (heapRel != NULL && !object_ownercheck(RelationRelationId, indexoid, save_userid))
1082  RelationGetRelationName(indexRel));
1083 
1084  /*
1085  * Since we did the IndexGetRelation call above without any lock, it's
1086  * barely possible that a race against an index drop/recreation could have
1087  * netted us the wrong table. Recheck.
1088  */
1089  if (heapRel == NULL || heapoid != IndexGetRelation(indexoid, false))
1090  ereport(ERROR,
1092  errmsg("could not open parent table of index \"%s\"",
1093  RelationGetRelationName(indexRel))));
1094 
1095  /* OK, do it */
1096  brinsummarize(indexRel, heapRel, heapBlk, true, &numSummarized, NULL);
1097 
1098  /* Roll back any GUC changes executed by index functions */
1099  AtEOXact_GUC(false, save_nestlevel);
1100 
1101  /* Restore userid and security context */
1102  SetUserIdAndSecContext(save_userid, save_sec_context);
1103 
1106 
1107  PG_RETURN_INT32((int32) numSummarized);
1108 }
1109 
1110 /*
1111  * SQL-callable interface to mark a range as no longer summarized
1112  */
1113 Datum
1115 {
1116  Oid indexoid = PG_GETARG_OID(0);
1117  int64 heapBlk64 = PG_GETARG_INT64(1);
1118  BlockNumber heapBlk;
1119  Oid heapoid;
1120  Relation heapRel;
1121  Relation indexRel;
1122  bool done;
1123 
1124  if (RecoveryInProgress())
1125  ereport(ERROR,
1126  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1127  errmsg("recovery is in progress"),
1128  errhint("BRIN control functions cannot be executed during recovery.")));
1129 
1130  if (heapBlk64 > MaxBlockNumber || heapBlk64 < 0)
1131  ereport(ERROR,
1132  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
1133  errmsg("block number out of range: %lld",
1134  (long long) heapBlk64)));
1135  heapBlk = (BlockNumber) heapBlk64;
1136 
1137  /*
1138  * We must lock table before index to avoid deadlocks. However, if the
1139  * passed indexoid isn't an index then IndexGetRelation() will fail.
1140  * Rather than emitting a not-very-helpful error message, postpone
1141  * complaining, expecting that the is-it-an-index test below will fail.
1142  *
1143  * Unlike brin_summarize_range(), autovacuum never calls this. Hence, we
1144  * don't switch userid.
1145  */
1146  heapoid = IndexGetRelation(indexoid, true);
1147  if (OidIsValid(heapoid))
1148  heapRel = table_open(heapoid, ShareUpdateExclusiveLock);
1149  else
1150  heapRel = NULL;
1151 
1152  indexRel = index_open(indexoid, ShareUpdateExclusiveLock);
1153 
1154  /* Must be a BRIN index */
1155  if (indexRel->rd_rel->relkind != RELKIND_INDEX ||
1156  indexRel->rd_rel->relam != BRIN_AM_OID)
1157  ereport(ERROR,
1158  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1159  errmsg("\"%s\" is not a BRIN index",
1160  RelationGetRelationName(indexRel))));
1161 
1162  /* User must own the index (comparable to privileges needed for VACUUM) */
1163  if (!object_ownercheck(RelationRelationId, indexoid, GetUserId()))
1165  RelationGetRelationName(indexRel));
1166 
1167  /*
1168  * Since we did the IndexGetRelation call above without any lock, it's
1169  * barely possible that a race against an index drop/recreation could have
1170  * netted us the wrong table. Recheck.
1171  */
1172  if (heapRel == NULL || heapoid != IndexGetRelation(indexoid, false))
1173  ereport(ERROR,
1175  errmsg("could not open parent table of index \"%s\"",
1176  RelationGetRelationName(indexRel))));
1177 
1178  /* the revmap does the hard work */
1179  do
1180  {
1181  done = brinRevmapDesummarizeRange(indexRel, heapBlk);
1182  }
1183  while (!done);
1184 
1187 
1188  PG_RETURN_VOID();
1189 }
1190 
1191 /*
1192  * Build a BrinDesc used to create or scan a BRIN index
1193  */
1194 BrinDesc *
1196 {
1197  BrinOpcInfo **opcinfo;
1198  BrinDesc *bdesc;
1199  TupleDesc tupdesc;
1200  int totalstored = 0;
1201  int keyno;
1202  long totalsize;
1203  MemoryContext cxt;
1204  MemoryContext oldcxt;
1205 
1207  "brin desc cxt",
1209  oldcxt = MemoryContextSwitchTo(cxt);
1210  tupdesc = RelationGetDescr(rel);
1211 
1212  /*
1213  * Obtain BrinOpcInfo for each indexed column. While at it, accumulate
1214  * the number of columns stored, since the number is opclass-defined.
1215  */
1216  opcinfo = palloc_array(BrinOpcInfo*, tupdesc->natts);
1217  for (keyno = 0; keyno < tupdesc->natts; keyno++)
1218  {
1219  FmgrInfo *opcInfoFn;
1220  Form_pg_attribute attr = TupleDescAttr(tupdesc, keyno);
1221 
1222  opcInfoFn = index_getprocinfo(rel, keyno + 1, BRIN_PROCNUM_OPCINFO);
1223 
1224  opcinfo[keyno] = (BrinOpcInfo *)
1225  DatumGetPointer(FunctionCall1(opcInfoFn, attr->atttypid));
1226  totalstored += opcinfo[keyno]->oi_nstored;
1227  }
1228 
1229  /* Allocate our result struct and fill it in */
1230  totalsize = offsetof(BrinDesc, bd_info) +
1231  sizeof(BrinOpcInfo *) * tupdesc->natts;
1232 
1233  bdesc = palloc(totalsize);
1234  bdesc->bd_context = cxt;
1235  bdesc->bd_index = rel;
1236  bdesc->bd_tupdesc = tupdesc;
1237  bdesc->bd_disktdesc = NULL; /* generated lazily */
1238  bdesc->bd_totalstored = totalstored;
1239 
1240  for (keyno = 0; keyno < tupdesc->natts; keyno++)
1241  bdesc->bd_info[keyno] = opcinfo[keyno];
1242  pfree(opcinfo);
1243 
1244  MemoryContextSwitchTo(oldcxt);
1245 
1246  return bdesc;
1247 }
1248 
1249 void
1251 {
1252  /* make sure the tupdesc is still valid */
1253  Assert(bdesc->bd_tupdesc->tdrefcount >= 1);
1254  /* no need for retail pfree */
1256 }
1257 
1258 /*
1259  * Fetch index's statistical data into *stats
1260  */
1261 void
1263 {
1264  Buffer metabuffer;
1265  Page metapage;
1266  BrinMetaPageData *metadata;
1267 
1268  metabuffer = ReadBuffer(index, BRIN_METAPAGE_BLKNO);
1269  LockBuffer(metabuffer, BUFFER_LOCK_SHARE);
1270  metapage = BufferGetPage(metabuffer);
1271  metadata = (BrinMetaPageData *) PageGetContents(metapage);
1272 
1273  stats->pagesPerRange = metadata->pagesPerRange;
1274  stats->revmapNumPages = metadata->lastRevmapPage - 1;
1275 
1276  UnlockReleaseBuffer(metabuffer);
1277 }
1278 
1279 /*
1280  * Initialize a BrinBuildState appropriate to create tuples on the given index.
1281  */
1282 static BrinBuildState *
1284  BlockNumber pagesPerRange)
1285 {
1287 
1289 
1290  state->bs_irel = idxRel;
1291  state->bs_numtuples = 0;
1292  state->bs_currentInsertBuf = InvalidBuffer;
1293  state->bs_pagesPerRange = pagesPerRange;
1294  state->bs_currRangeStart = 0;
1295  state->bs_rmAccess = revmap;
1296  state->bs_bdesc = brin_build_desc(idxRel);
1297  state->bs_dtuple = brin_new_memtuple(state->bs_bdesc);
1298 
1299  return state;
1300 }
1301 
1302 /*
1303  * Release resources associated with a BrinBuildState.
1304  */
1305 static void
1307 {
1308  /*
1309  * Release the last index buffer used. We might as well ensure that
1310  * whatever free space remains in that page is available in FSM, too.
1311  */
1312  if (!BufferIsInvalid(state->bs_currentInsertBuf))
1313  {
1314  Page page;
1315  Size freespace;
1316  BlockNumber blk;
1317 
1318  page = BufferGetPage(state->bs_currentInsertBuf);
1319  freespace = PageGetFreeSpace(page);
1320  blk = BufferGetBlockNumber(state->bs_currentInsertBuf);
1321  ReleaseBuffer(state->bs_currentInsertBuf);
1322  RecordPageWithFreeSpace(state->bs_irel, blk, freespace);
1323  FreeSpaceMapVacuumRange(state->bs_irel, blk, blk + 1);
1324  }
1325 
1326  brin_free_desc(state->bs_bdesc);
1327  pfree(state->bs_dtuple);
1328  pfree(state);
1329 }
1330 
1331 /*
1332  * On the given BRIN index, summarize the heap page range that corresponds
1333  * to the heap block number given.
1334  *
1335  * This routine can run in parallel with insertions into the heap. To avoid
1336  * missing those values from the summary tuple, we first insert a placeholder
1337  * index tuple into the index, then execute the heap scan; transactions
1338  * concurrent with the scan update the placeholder tuple. After the scan, we
1339  * union the placeholder tuple with the one computed by this routine. The
1340  * update of the index value happens in a loop, so that if somebody updates
1341  * the placeholder tuple after we read it, we detect the case and try again.
1342  * This ensures that the concurrently inserted tuples are not lost.
1343  *
1344  * A further corner case is this routine being asked to summarize the partial
1345  * range at the end of the table. heapNumBlocks is the (possibly outdated)
1346  * table size; if we notice that the requested range lies beyond that size,
1347  * we re-compute the table size after inserting the placeholder tuple, to
1348  * avoid missing pages that were appended recently.
1349  */
1350 static void
1352  BlockNumber heapBlk, BlockNumber heapNumBlks)
1353 {
1354  Buffer phbuf;
1355  BrinTuple *phtup;
1356  Size phsz;
1357  OffsetNumber offset;
1358  BlockNumber scanNumBlks;
1359 
1360  /*
1361  * Insert the placeholder tuple
1362  */
1363  phbuf = InvalidBuffer;
1364  phtup = brin_form_placeholder_tuple(state->bs_bdesc, heapBlk, &phsz);
1365  offset = brin_doinsert(state->bs_irel, state->bs_pagesPerRange,
1366  state->bs_rmAccess, &phbuf,
1367  heapBlk, phtup, phsz);
1368 
1369  /*
1370  * Compute range end. We hold ShareUpdateExclusive lock on table, so it
1371  * cannot shrink concurrently (but it can grow).
1372  */
1373  Assert(heapBlk % state->bs_pagesPerRange == 0);
1374  if (heapBlk + state->bs_pagesPerRange > heapNumBlks)
1375  {
1376  /*
1377  * If we're asked to scan what we believe to be the final range on the
1378  * table (i.e. a range that might be partial) we need to recompute our
1379  * idea of what the latest page is after inserting the placeholder
1380  * tuple. Anyone that grows the table later will update the
1381  * placeholder tuple, so it doesn't matter that we won't scan these
1382  * pages ourselves. Careful: the table might have been extended
1383  * beyond the current range, so clamp our result.
1384  *
1385  * Fortunately, this should occur infrequently.
1386  */
1387  scanNumBlks = Min(RelationGetNumberOfBlocks(heapRel) - heapBlk,
1388  state->bs_pagesPerRange);
1389  }
1390  else
1391  {
1392  /* Easy case: range is known to be complete */
1393  scanNumBlks = state->bs_pagesPerRange;
1394  }
1395 
1396  /*
1397  * Execute the partial heap scan covering the heap blocks in the specified
1398  * page range, summarizing the heap tuples in it. This scan stops just
1399  * short of brinbuildCallback creating the new index entry.
1400  *
1401  * Note that it is critical we use the "any visible" mode of
1402  * table_index_build_range_scan here: otherwise, we would miss tuples
1403  * inserted by transactions that are still in progress, among other corner
1404  * cases.
1405  */
1406  state->bs_currRangeStart = heapBlk;
1407  table_index_build_range_scan(heapRel, state->bs_irel, indexInfo, false, true, false,
1408  heapBlk, scanNumBlks,
1409  brinbuildCallback, (void *) state, NULL);
1410 
1411  /*
1412  * Now we update the values obtained by the scan with the placeholder
1413  * tuple. We do this in a loop which only terminates if we're able to
1414  * update the placeholder tuple successfully; if we are not, this means
1415  * somebody else modified the placeholder tuple after we read it.
1416  */
1417  for (;;)
1418  {
1419  BrinTuple *newtup;
1420  Size newsize;
1421  bool didupdate;
1422  bool samepage;
1423 
1425 
1426  /*
1427  * Update the summary tuple and try to update.
1428  */
1429  newtup = brin_form_tuple(state->bs_bdesc,
1430  heapBlk, state->bs_dtuple, &newsize);
1431  samepage = brin_can_do_samepage_update(phbuf, phsz, newsize);
1432  didupdate =
1433  brin_doupdate(state->bs_irel, state->bs_pagesPerRange,
1434  state->bs_rmAccess, heapBlk, phbuf, offset,
1435  phtup, phsz, newtup, newsize, samepage);
1436  brin_free_tuple(phtup);
1437  brin_free_tuple(newtup);
1438 
1439  /* If the update succeeded, we're done. */
1440  if (didupdate)
1441  break;
1442 
1443  /*
1444  * If the update didn't work, it might be because somebody updated the
1445  * placeholder tuple concurrently. Extract the new version, union it
1446  * with the values we have from the scan, and start over. (There are
1447  * other reasons for the update to fail, but it's simple to treat them
1448  * the same.)
1449  */
1450  phtup = brinGetTupleForHeapBlock(state->bs_rmAccess, heapBlk, &phbuf,
1451  &offset, &phsz, BUFFER_LOCK_SHARE,
1452  NULL);
1453  /* the placeholder tuple must exist */
1454  if (phtup == NULL)
1455  elog(ERROR, "missing placeholder tuple");
1456  phtup = brin_copy_tuple(phtup, phsz, NULL, NULL);
1458 
1459  /* merge it into the tuple from the heap scan */
1460  union_tuples(state->bs_bdesc, state->bs_dtuple, phtup);
1461  }
1462 
1463  ReleaseBuffer(phbuf);
1464 }
1465 
1466 /*
1467  * Summarize page ranges that are not already summarized. If pageRange is
1468  * BRIN_ALL_BLOCKRANGES then the whole table is scanned; otherwise, only the
1469  * page range containing the given heap page number is scanned.
1470  * If include_partial is true, then the partial range at the end of the table
1471  * is summarized, otherwise not.
1472  *
1473  * For each new index tuple inserted, *numSummarized (if not NULL) is
1474  * incremented; for each existing tuple, *numExisting (if not NULL) is
1475  * incremented.
1476  */
1477 static void
1479  bool include_partial, double *numSummarized, double *numExisting)
1480 {
1481  BrinRevmap *revmap;
1482  BrinBuildState *state = NULL;
1483  IndexInfo *indexInfo = NULL;
1484  BlockNumber heapNumBlocks;
1485  BlockNumber pagesPerRange;
1486  Buffer buf;
1487  BlockNumber startBlk;
1488 
1489  revmap = brinRevmapInitialize(index, &pagesPerRange, NULL);
1490 
1491  /* determine range of pages to process */
1492  heapNumBlocks = RelationGetNumberOfBlocks(heapRel);
1493  if (pageRange == BRIN_ALL_BLOCKRANGES)
1494  startBlk = 0;
1495  else
1496  {
1497  startBlk = (pageRange / pagesPerRange) * pagesPerRange;
1498  heapNumBlocks = Min(heapNumBlocks, startBlk + pagesPerRange);
1499  }
1500  if (startBlk > heapNumBlocks)
1501  {
1502  /* Nothing to do if start point is beyond end of table */
1503  brinRevmapTerminate(revmap);
1504  return;
1505  }
1506 
1507  /*
1508  * Scan the revmap to find unsummarized items.
1509  */
1510  buf = InvalidBuffer;
1511  for (; startBlk < heapNumBlocks; startBlk += pagesPerRange)
1512  {
1513  BrinTuple *tup;
1514  OffsetNumber off;
1515 
1516  /*
1517  * Unless requested to summarize even a partial range, go away now if
1518  * we think the next range is partial. Caller would pass true when it
1519  * is typically run once bulk data loading is done
1520  * (brin_summarize_new_values), and false when it is typically the
1521  * result of arbitrarily-scheduled maintenance command (vacuuming).
1522  */
1523  if (!include_partial &&
1524  (startBlk + pagesPerRange > heapNumBlocks))
1525  break;
1526 
1528 
1529  tup = brinGetTupleForHeapBlock(revmap, startBlk, &buf, &off, NULL,
1530  BUFFER_LOCK_SHARE, NULL);
1531  if (tup == NULL)
1532  {
1533  /* no revmap entry for this heap range. Summarize it. */
1534  if (state == NULL)
1535  {
1536  /* first time through */
1537  Assert(!indexInfo);
1539  pagesPerRange);
1540  indexInfo = BuildIndexInfo(index);
1541  }
1542  summarize_range(indexInfo, state, heapRel, startBlk, heapNumBlocks);
1543 
1544  /* and re-initialize state for the next range */
1545  brin_memtuple_initialize(state->bs_dtuple, state->bs_bdesc);
1546 
1547  if (numSummarized)
1548  *numSummarized += 1.0;
1549  }
1550  else
1551  {
1552  if (numExisting)
1553  *numExisting += 1.0;
1555  }
1556  }
1557 
1558  if (BufferIsValid(buf))
1559  ReleaseBuffer(buf);
1560 
1561  /* free resources */
1562  brinRevmapTerminate(revmap);
1563  if (state)
1564  {
1566  pfree(indexInfo);
1567  }
1568 }
1569 
1570 /*
1571  * Given a deformed tuple in the build state, convert it into the on-disk
1572  * format and insert it into the index, making the revmap point to it.
1573  */
1574 static void
1576 {
1577  BrinTuple *tup;
1578  Size size;
1579 
1580  tup = brin_form_tuple(state->bs_bdesc, state->bs_currRangeStart,
1581  state->bs_dtuple, &size);
1582  brin_doinsert(state->bs_irel, state->bs_pagesPerRange, state->bs_rmAccess,
1583  &state->bs_currentInsertBuf, state->bs_currRangeStart,
1584  tup, size);
1585  state->bs_numtuples++;
1586 
1587  pfree(tup);
1588 }
1589 
1590 /*
1591  * Given two deformed tuples, adjust the first one so that it's consistent
1592  * with the summary values in both.
1593  */
1594 static void
1596 {
1597  int keyno;
1598  BrinMemTuple *db;
1599  MemoryContext cxt;
1600  MemoryContext oldcxt;
1601 
1602  /* Use our own memory context to avoid retail pfree */
1604  "brin union",
1606  oldcxt = MemoryContextSwitchTo(cxt);
1607  db = brin_deform_tuple(bdesc, b, NULL);
1608  MemoryContextSwitchTo(oldcxt);
1609 
1610  for (keyno = 0; keyno < bdesc->bd_tupdesc->natts; keyno++)
1611  {
1612  FmgrInfo *unionFn;
1613  BrinValues *col_a = &a->bt_columns[keyno];
1614  BrinValues *col_b = &db->bt_columns[keyno];
1615  BrinOpcInfo *opcinfo = bdesc->bd_info[keyno];
1616 
1617  if (opcinfo->oi_regular_nulls)
1618  {
1619  /* Adjust "hasnulls". */
1620  if (!col_a->bv_hasnulls && col_b->bv_hasnulls)
1621  col_a->bv_hasnulls = true;
1622 
1623  /* If there are no values in B, there's nothing left to do. */
1624  if (col_b->bv_allnulls)
1625  continue;
1626 
1627  /*
1628  * Adjust "allnulls". If A doesn't have values, just copy the
1629  * values from B into A, and we're done. We cannot run the
1630  * operators in this case, because values in A might contain
1631  * garbage. Note we already established that B contains values.
1632  */
1633  if (col_a->bv_allnulls)
1634  {
1635  int i;
1636 
1637  col_a->bv_allnulls = false;
1638 
1639  for (i = 0; i < opcinfo->oi_nstored; i++)
1640  col_a->bv_values[i] =
1641  datumCopy(col_b->bv_values[i],
1642  opcinfo->oi_typcache[i]->typbyval,
1643  opcinfo->oi_typcache[i]->typlen);
1644 
1645  continue;
1646  }
1647  }
1648 
1649  unionFn = index_getprocinfo(bdesc->bd_index, keyno + 1,
1651  FunctionCall3Coll(unionFn,
1652  bdesc->bd_index->rd_indcollation[keyno],
1653  PointerGetDatum(bdesc),
1654  PointerGetDatum(col_a),
1655  PointerGetDatum(col_b));
1656  }
1657 
1658  MemoryContextDelete(cxt);
1659 }
1660 
1661 /*
1662  * brin_vacuum_scan
1663  * Do a complete scan of the index during VACUUM.
1664  *
1665  * This routine scans the complete index looking for uncatalogued index pages,
1666  * i.e. those that might have been lost due to a crash after index extension
1667  * and such.
1668  */
1669 static void
1671 {
1672  BlockNumber nblocks;
1673  BlockNumber blkno;
1674 
1675  /*
1676  * Scan the index in physical order, and clean up any possible mess in
1677  * each page.
1678  */
1679  nblocks = RelationGetNumberOfBlocks(idxrel);
1680  for (blkno = 0; blkno < nblocks; blkno++)
1681  {
1682  Buffer buf;
1683 
1685 
1686  buf = ReadBufferExtended(idxrel, MAIN_FORKNUM, blkno,
1687  RBM_NORMAL, strategy);
1688 
1689  brin_page_cleanup(idxrel, buf);
1690 
1691  ReleaseBuffer(buf);
1692  }
1693 
1694  /*
1695  * Update all upper pages in the index's FSM, as well. This ensures not
1696  * only that we propagate leaf-page FSM updates made by brin_page_cleanup,
1697  * but also that any pre-existing damage or out-of-dateness is repaired.
1698  */
1699  FreeSpaceMapVacuum(idxrel);
1700 }
1701 
1702 static bool
1704  Datum *values, bool *nulls)
1705 {
1706  int keyno;
1707  bool modified = false;
1708 
1709  /*
1710  * Compare the key values of the new tuple to the stored index values; our
1711  * deformed tuple will get updated if the new tuple doesn't fit the
1712  * original range (note this means we can't break out of the loop early).
1713  * Make a note of whether this happens, so that we know to insert the
1714  * modified tuple later.
1715  */
1716  for (keyno = 0; keyno < bdesc->bd_tupdesc->natts; keyno++)
1717  {
1718  Datum result;
1719  BrinValues *bval;
1720  FmgrInfo *addValue;
1721 
1722  bval = &dtup->bt_columns[keyno];
1723 
1724  if (bdesc->bd_info[keyno]->oi_regular_nulls && nulls[keyno])
1725  {
1726  /*
1727  * If the new value is null, we record that we saw it if it's the
1728  * first one; otherwise, there's nothing to do.
1729  */
1730  if (!bval->bv_hasnulls)
1731  {
1732  bval->bv_hasnulls = true;
1733  modified = true;
1734  }
1735 
1736  continue;
1737  }
1738 
1739  addValue = index_getprocinfo(idxRel, keyno + 1,
1741  result = FunctionCall4Coll(addValue,
1742  idxRel->rd_indcollation[keyno],
1743  PointerGetDatum(bdesc),
1744  PointerGetDatum(bval),
1745  values[keyno],
1746  nulls[keyno]);
1747  /* if that returned true, we need to insert the updated tuple */
1748  modified |= DatumGetBool(result);
1749  }
1750 
1751  return modified;
1752 }
1753 
1754 static bool
1755 check_null_keys(BrinValues *bval, ScanKey *nullkeys, int nnullkeys)
1756 {
1757  int keyno;
1758 
1759  /*
1760  * First check if there are any IS [NOT] NULL scan keys, and if we're
1761  * violating them.
1762  */
1763  for (keyno = 0; keyno < nnullkeys; keyno++)
1764  {
1765  ScanKey key = nullkeys[keyno];
1766 
1767  Assert(key->sk_attno == bval->bv_attno);
1768 
1769  /* Handle only IS NULL/IS NOT NULL tests */
1770  if (!(key->sk_flags & SK_ISNULL))
1771  continue;
1772 
1773  if (key->sk_flags & SK_SEARCHNULL)
1774  {
1775  /* IS NULL scan key, but range has no NULLs */
1776  if (!bval->bv_allnulls && !bval->bv_hasnulls)
1777  return false;
1778  }
1779  else if (key->sk_flags & SK_SEARCHNOTNULL)
1780  {
1781  /*
1782  * For IS NOT NULL, we can only skip ranges that are known to have
1783  * only nulls.
1784  */
1785  if (bval->bv_allnulls)
1786  return false;
1787  }
1788  else
1789  {
1790  /*
1791  * Neither IS NULL nor IS NOT NULL was used; assume all indexable
1792  * operators are strict and thus return false with NULL value in
1793  * the scan key.
1794  */
1795  return false;
1796  }
1797  }
1798 
1799  return true;
1800 }
@ ACLCHECK_NOT_OWNER
Definition: acl.h:185
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2673
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:3976
int16 AttrNumber
Definition: attnum.h:21
bool AutoVacuumRequestWork(AutoVacuumWorkItemType type, Oid relationId, BlockNumber blkno)
Definition: autovacuum.c:3262
@ AVW_BRINSummarizeRange
Definition: autovacuum.h:25
uint32 BlockNumber
Definition: block.h:31
#define MaxBlockNumber
Definition: block.h:35
static Datum values[MAXATTR]
Definition: bootstrap.c:156
IndexBulkDeleteResult * brinvacuumcleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats)
Definition: brin.c:947
static void brin_vacuum_scan(Relation idxrel, BufferAccessStrategy strategy)
Definition: brin.c:1670
static BrinBuildState * initialize_brin_buildstate(Relation idxRel, BrinRevmap *revmap, BlockNumber pagesPerRange)
Definition: brin.c:1283
Datum brin_desummarize_range(PG_FUNCTION_ARGS)
Definition: brin.c:1114
void brinrescan(IndexScanDesc scan, ScanKey scankey, int nscankeys, ScanKey orderbys, int norderbys)
Definition: brin.c:736
static void terminate_brin_buildstate(BrinBuildState *state)
Definition: brin.c:1306
Datum brin_summarize_range(PG_FUNCTION_ARGS)
Definition: brin.c:1010
#define BRIN_ALL_BLOCKRANGES
Definition: brin.c:71
Datum brin_summarize_new_values(PG_FUNCTION_ARGS)
Definition: brin.c:995
IndexScanDesc brinbeginscan(Relation r, int nkeys, int norderbys)
Definition: brin.c:327
IndexBuildResult * brinbuild(Relation heap, Relation index, IndexInfo *indexInfo)
Definition: brin.c:818
int64 bringetbitmap(IndexScanDesc scan, TIDBitmap *tbm)
Definition: brin.c:356
static void brinsummarize(Relation index, Relation heapRel, BlockNumber pageRange, bool include_partial, double *numSummarized, double *numExisting)
Definition: brin.c:1478
static bool add_values_to_range(Relation idxRel, BrinDesc *bdesc, BrinMemTuple *dtup, Datum *values, bool *nulls)
Definition: brin.c:1703
static void form_and_insert_tuple(BrinBuildState *state)
Definition: brin.c:1575
void brinbuildempty(Relation index)
Definition: brin.c:902
void brin_free_desc(BrinDesc *bdesc)
Definition: brin.c:1250
static void union_tuples(BrinDesc *bdesc, BrinMemTuple *a, BrinTuple *b)
Definition: brin.c:1595
void brinGetStats(Relation index, BrinStatsData *stats)
Definition: brin.c:1262
BrinDesc * brin_build_desc(Relation rel)
Definition: brin.c:1195
struct BrinBuildState BrinBuildState
struct BrinOpaque BrinOpaque
static void summarize_range(IndexInfo *indexInfo, BrinBuildState *state, Relation heapRel, BlockNumber heapBlk, BlockNumber heapNumBlks)
Definition: brin.c:1351
bool brininsert(Relation idxRel, Datum *values, bool *nulls, ItemPointer heaptid, Relation heapRel, IndexUniqueCheck checkUnique, bool indexUnchanged, IndexInfo *indexInfo)
Definition: brin.c:156
Datum brinhandler(PG_FUNCTION_ARGS)
Definition: brin.c:91
bytea * brinoptions(Datum reloptions, bool validate)
Definition: brin.c:977
IndexBulkDeleteResult * brinbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats, IndexBulkDeleteCallback callback, void *callback_state)
Definition: brin.c:932
static void brinbuildCallback(Relation index, ItemPointer tid, Datum *values, bool *isnull, bool tupleIsAlive, void *brstate)
Definition: brin.c:773
void brinendscan(IndexScanDesc scan)
Definition: brin.c:756
static bool check_null_keys(BrinValues *bval, ScanKey *nullkeys, int nnullkeys)
Definition: brin.c:1755
#define BrinGetPagesPerRange(relation)
Definition: brin.h:39
#define BrinGetAutoSummarize(relation)
Definition: brin.h:45
#define BRIN_LAST_OPTIONAL_PROCNUM
Definition: brin_internal.h:78
#define BRIN_PROCNUM_UNION
Definition: brin_internal.h:73
#define BRIN_PROCNUM_OPTIONS
Definition: brin_internal.h:75
#define BRIN_PROCNUM_OPCINFO
Definition: brin_internal.h:70
#define BRIN_PROCNUM_CONSISTENT
Definition: brin_internal.h:72
#define BRIN_elog(args)
Definition: brin_internal.h:85
#define BRIN_PROCNUM_ADDVALUE
Definition: brin_internal.h:71
#define BRIN_CURRENT_VERSION
Definition: brin_page.h:72
#define BRIN_METAPAGE_BLKNO
Definition: brin_page.h:75
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
void brin_page_cleanup(Relation idxrel, Buffer buf)
Definition: brin_pageops.c:625
OffsetNumber brin_doinsert(Relation idxrel, BlockNumber pagesPerRange, BrinRevmap *revmap, Buffer *buffer, BlockNumber heapBlk, BrinTuple *tup, Size itemsz)
Definition: brin_pageops.c:343
void brin_metapage_init(Page page, BlockNumber pagesPerRange, uint16 version)
Definition: brin_pageops.c:487
bool brin_can_do_samepage_update(Buffer buffer, Size origsz, Size newsz)
Definition: brin_pageops.c:324
bool brinRevmapDesummarizeRange(Relation idxrel, BlockNumber heapBlk)
Definition: brin_revmap.c:328
BrinTuple * brinGetTupleForHeapBlock(BrinRevmap *revmap, BlockNumber heapBlk, Buffer *buf, OffsetNumber *off, Size *size, int mode, Snapshot snapshot)
Definition: brin_revmap.c:197
BrinRevmap * brinRevmapInitialize(Relation idxrel, BlockNumber *pagesPerRange, Snapshot snapshot)
Definition: brin_revmap.c:71
void brinRevmapTerminate(BrinRevmap *revmap)
Definition: brin_revmap.c:103
BrinTuple * brin_form_tuple(BrinDesc *brdesc, BlockNumber blkno, BrinMemTuple *tuple, Size *size)
Definition: brin_tuple.c:99
BrinMemTuple * brin_new_memtuple(BrinDesc *brdesc)
Definition: brin_tuple.c:479
BrinMemTuple * brin_deform_tuple(BrinDesc *brdesc, BrinTuple *tuple, BrinMemTuple *dMemtuple)
Definition: brin_tuple.c:546
BrinMemTuple * brin_memtuple_initialize(BrinMemTuple *dtuple, BrinDesc *brdesc)
Definition: brin_tuple.c:506
BrinTuple * brin_copy_tuple(BrinTuple *tuple, Size len, BrinTuple *dest, Size *destsz)
Definition: brin_tuple.c:443
void brin_free_tuple(BrinTuple *tuple)
Definition: brin_tuple.c:430
BrinTuple * brin_form_placeholder_tuple(BrinDesc *brdesc, BlockNumber blkno, Size *size)
Definition: brin_tuple.c:385
bool brinvalidate(Oid opclassoid)
Definition: brin_validate.c:37
#define SizeOfBrinCreateIdx
Definition: brin_xlog.h:55
#define XLOG_BRIN_CREATE_INDEX
Definition: brin_xlog.h:31
int Buffer
Definition: buf.h:23
#define BufferIsInvalid(buffer)
Definition: buf.h:31
#define InvalidBuffer
Definition: buf.h:25
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition: bufmgr.c:2791
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3985
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:4008
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1621
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:4226
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:751
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:704
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:110
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:111
#define P_NEW
Definition: bufmgr.h:105
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:161
static Page BufferGetPage(Buffer buffer)
Definition: bufmgr.h:284
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:112
@ RBM_NORMAL
Definition: bufmgr.h:44
static bool BufferIsValid(Buffer bufnum)
Definition: bufmgr.h:232
Size PageGetFreeSpace(Page page)
Definition: bufpage.c:907
static char * PageGetContents(Page page)
Definition: bufpage.h:254
Pointer Page
Definition: bufpage.h:78
static ItemId PageGetItemId(Page page, OffsetNumber offsetNumber)
Definition: bufpage.h:240
static void PageSetLSN(Page page, XLogRecPtr lsn)
Definition: bufpage.h:388
#define Min(x, y)
Definition: c.h:988
#define MAXALIGN(LEN)
Definition: c.h:795
signed int int32
Definition: c.h:478
#define lengthof(array)
Definition: c.h:772
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:166
#define OidIsValid(objectId)
Definition: c.h:759
size_t Size
Definition: c.h:589
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:132
int errhint(const char *fmt,...)
Definition: elog.c:1316
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define LOG
Definition: elog.h:31
#define DEBUG2
Definition: elog.h:29
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
#define palloc_object(type)
Definition: fe_memutils.h:62
#define palloc_array(type, count)
Definition: fe_memutils.h:64
#define palloc0_array(type, count)
Definition: fe_memutils.h:65
#define palloc0_object(type)
Definition: fe_memutils.h:63
Datum FunctionCall4Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition: fmgr.c:1168
Datum Int64GetDatum(int64 X)
Definition: fmgr.c:1779
Datum FunctionCall3Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2, Datum arg3)
Definition: fmgr.c:1143
void fmgr_info_copy(FmgrInfo *dstinfo, FmgrInfo *srcinfo, MemoryContext destcxt)
Definition: fmgr.c:580
#define PG_RETURN_VOID()
Definition: fmgr.h:349
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
#define DirectFunctionCall2(func, arg1, arg2)
Definition: fmgr.h:644
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:268
#define PG_GETARG_INT64(n)
Definition: fmgr.h:283
#define FunctionCall1(flinfo, arg1)
Definition: fmgr.h:660
#define PG_RETURN_INT32(x)
Definition: fmgr.h:354
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:361
#define PG_FUNCTION_ARGS
Definition: fmgr.h:193
void FreeSpaceMapVacuumRange(Relation rel, BlockNumber start, BlockNumber end)
Definition: freespace.c:354
void FreeSpaceMapVacuum(Relation rel)
Definition: freespace.c:335
void RecordPageWithFreeSpace(Relation rel, BlockNumber heapBlk, Size spaceAvail)
Definition: freespace.c:182
IndexScanDesc RelationGetIndexScan(Relation indexRelation, int nkeys, int norderbys)
Definition: genam.c:81
bool(* IndexBulkDeleteCallback)(ItemPointer itemptr, void *state)
Definition: genam.h:86
IndexUniqueCheck
Definition: genam.h:115
int NewGUCNestLevel(void)
Definition: guc.c:2201
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:2215
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3533
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2430
FmgrInfo * index_getprocinfo(Relation irel, AttrNumber attnum, uint16 procnum)
Definition: indexam.c:811
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
int b
Definition: isn.c:70
int a
Definition: isn.c:69
int i
Definition: isn.c:73
#define ItemIdGetLength(itemId)
Definition: itemid.h:59
static OffsetNumber ItemPointerGetOffsetNumber(const ItemPointerData *pointer)
Definition: itemptr.h:124
static BlockNumber ItemPointerGetBlockNumber(const ItemPointerData *pointer)
Definition: itemptr.h:103
Assert(fmt[strlen(fmt) - 1] !='\n')
#define AccessShareLock
Definition: lockdefs.h:36
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
void pfree(void *pointer)
Definition: mcxt.c:1436
MemoryContext CurrentMemoryContext
Definition: mcxt.c:135
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:387
void * palloc(Size size)
Definition: mcxt.c:1210
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:153
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:163
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:70
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:305
#define START_CRIT_SECTION()
Definition: miscadmin.h:148
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
#define END_CRIT_SECTION()
Definition: miscadmin.h:150
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:631
Oid GetUserId(void)
Definition: miscinit.c:510
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:638
#define makeNode(_type_)
Definition: nodes.h:176
uint16 OffsetNumber
Definition: off.h:24
#define FirstOffsetNumber
Definition: off.h:27
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:138
@ OBJECT_INDEX
Definition: parsenodes.h:2102
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
const void size_t len
static char * buf
Definition: pg_test_fsync.c:67
#define ERRCODE_UNDEFINED_TABLE
Definition: pgbench.c:78
#define pgstat_count_index_scan(rel)
Definition: pgstat.h:615
static bool DatumGetBool(Datum X)
Definition: postgres.h:90
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322
uintptr_t Datum
Definition: postgres.h:64
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:312
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:212
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
static void addrange(struct cvec *cv, chr from, chr to)
Definition: regc_cvec.c:90
#define RelationGetRelid(relation)
Definition: rel.h:503
#define RelationGetDescr(relation)
Definition: rel.h:529
#define RelationGetRelationName(relation)
Definition: rel.h:537
#define RelationNeedsWAL(relation)
Definition: rel.h:628
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:1910
@ RELOPT_KIND_BRIN
Definition: reloptions.h:52
@ RELOPT_TYPE_INT
Definition: reloptions.h:32
@ RELOPT_TYPE_BOOL
Definition: reloptions.h:31
@ MAIN_FORKNUM
Definition: relpath.h:50
@ INIT_FORKNUM
Definition: relpath.h:53
void brincostestimate(PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
Definition: selfuncs.c:7815
#define SK_SEARCHNOTNULL
Definition: skey.h:122
#define SK_SEARCHNULL
Definition: skey.h:121
#define SK_ISNULL
Definition: skey.h:115
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
BrinMemTuple * bs_dtuple
Definition: brin.c:58
Relation bs_irel
Definition: brin.c:51
BlockNumber bs_pagesPerRange
Definition: brin.c:54
Buffer bs_currentInsertBuf
Definition: brin.c:53
int bs_numtuples
Definition: brin.c:52
BrinRevmap * bs_rmAccess
Definition: brin.c:56
BlockNumber bs_currRangeStart
Definition: brin.c:55
BrinDesc * bs_bdesc
Definition: brin.c:57
int bd_totalstored
Definition: brin_internal.h:59
TupleDesc bd_tupdesc
Definition: brin_internal.h:53
BrinOpcInfo * bd_info[FLEXIBLE_ARRAY_MEMBER]
Definition: brin_internal.h:62
Relation bd_index
Definition: brin_internal.h:50
MemoryContext bd_context
Definition: brin_internal.h:47
TupleDesc bd_disktdesc
Definition: brin_internal.h:56
BrinValues bt_columns[FLEXIBLE_ARRAY_MEMBER]
Definition: brin_tuple.h:54
bool bt_placeholder
Definition: brin_tuple.h:46
BlockNumber lastRevmapPage
Definition: brin_page.h:69
BlockNumber pagesPerRange
Definition: brin_page.h:68
BlockNumber bo_pagesPerRange
Definition: brin.c:66
BrinDesc * bo_bdesc
Definition: brin.c:68
BrinRevmap * bo_rmAccess
Definition: brin.c:67
TypeCacheEntry * oi_typcache[FLEXIBLE_ARRAY_MEMBER]
Definition: brin_internal.h:37
uint16 oi_nstored
Definition: brin_internal.h:28
bool oi_regular_nulls
Definition: brin_internal.h:31
BlockNumber revmapNumPages
Definition: brin.h:34
BlockNumber pagesPerRange
Definition: brin.h:33
bool bv_hasnulls
Definition: brin_tuple.h:32
Datum * bv_values
Definition: brin_tuple.h:34
AttrNumber bv_attno
Definition: brin_tuple.h:31
bool bv_allnulls
Definition: brin_tuple.h:33
Definition: fmgr.h:57
ambuildphasename_function ambuildphasename
Definition: amapi.h:270
ambuildempty_function ambuildempty
Definition: amapi.h:262
amvacuumcleanup_function amvacuumcleanup
Definition: amapi.h:265
bool amclusterable
Definition: amapi.h:238
amoptions_function amoptions
Definition: amapi.h:268
amestimateparallelscan_function amestimateparallelscan
Definition: amapi.h:282
amrestrpos_function amrestrpos
Definition: amapi.h:279
aminsert_function aminsert
Definition: amapi.h:263
amendscan_function amendscan
Definition: amapi.h:277
uint16 amoptsprocnum
Definition: amapi.h:218
amparallelrescan_function amparallelrescan
Definition: amapi.h:284
Oid amkeytype
Definition: amapi.h:252
bool ampredlocks
Definition: amapi.h:240
uint16 amsupport
Definition: amapi.h:216
amcostestimate_function amcostestimate
Definition: amapi.h:267
bool amcanorderbyop
Definition: amapi.h:222
amadjustmembers_function amadjustmembers
Definition: amapi.h:272
ambuild_function ambuild
Definition: amapi.h:261
bool amstorage
Definition: amapi.h:236
uint16 amstrategies
Definition: amapi.h:214
bool amoptionalkey
Definition: amapi.h:230
amgettuple_function amgettuple
Definition: amapi.h:275
amcanreturn_function amcanreturn
Definition: amapi.h:266
bool amcanunique
Definition: amapi.h:226
amgetbitmap_function amgetbitmap
Definition: amapi.h:276
amproperty_function amproperty
Definition: amapi.h:269
ambulkdelete_function ambulkdelete
Definition: amapi.h:264
bool amsearcharray
Definition: amapi.h:232
bool amsummarizing
Definition: amapi.h:248
amvalidate_function amvalidate
Definition: amapi.h:271
ammarkpos_function ammarkpos
Definition: amapi.h:278
bool amcanmulticol
Definition: amapi.h:228
bool amusemaintenanceworkmem
Definition: amapi.h:246
ambeginscan_function ambeginscan
Definition: amapi.h:273
bool amcanparallel
Definition: amapi.h:242
amrescan_function amrescan
Definition: amapi.h:274
bool amcanorder
Definition: amapi.h:220
aminitparallelscan_function aminitparallelscan
Definition: amapi.h:283
uint8 amparallelvacuumoptions
Definition: amapi.h:250
bool amcanbackward
Definition: amapi.h:224
bool amcaninclude
Definition: amapi.h:244
bool amsearchnulls
Definition: amapi.h:234
double heap_tuples
Definition: genam.h:32
double index_tuples
Definition: genam.h:33
BlockNumber num_pages
Definition: genam.h:76
double num_index_tuples
Definition: genam.h:78
void * ii_AmCache
Definition: execnodes.h:201
MemoryContext ii_Context
Definition: execnodes.h:202
struct ScanKeyData * keyData
Definition: relscan.h:122
Relation indexRelation
Definition: relscan.h:118
struct SnapshotData * xs_snapshot
Definition: relscan.h:119
Relation index
Definition: genam.h:46
bool analyze_only
Definition: genam.h:47
BufferAccessStrategy strategy
Definition: genam.h:52
Oid * rd_indcollation
Definition: rel.h:215
Form_pg_class rd_rel
Definition: rel.h:110
Oid sk_collation
Definition: skey.h:70
int tdrefcount
Definition: tupdesc.h:84
bool typbyval
Definition: typcache.h:40
int16 typlen
Definition: typcache.h:39
Definition: type.h:95
Definition: regguts.h:318
Definition: c.h:671
BlockNumber pagesPerRange
Definition: brin_xlog.h:52
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
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:1815
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:1782
static void callback(struct sockaddr *addr, struct sockaddr *mask, void *unused)
Definition: test_ifaddrs.c:46
void tbm_add_page(TIDBitmap *tbm, BlockNumber pageno)
Definition: tidbitmap.c:442
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
#define VACUUM_OPTION_PARALLEL_CLEANUP
Definition: vacuum.h:62
bool RecoveryInProgress(void)
Definition: xlog.c:5907
uint64 XLogRecPtr
Definition: xlogdefs.h:21
void XLogRegisterData(char *data, uint32 len)
Definition: xloginsert.c:351
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:451
XLogRecPtr log_newpage_buffer(Buffer buffer, bool page_std)
Definition: xloginsert.c:1191
void XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Definition: xloginsert.c:243
void XLogBeginInsert(void)
Definition: xloginsert.c:150
#define REGBUF_STANDARD
Definition: xloginsert.h:34
#define REGBUF_WILL_INIT
Definition: xloginsert.h:33