PostgreSQL Source Code  git master
nbtutils.c File Reference
#include "postgres.h"
#include <time.h>
#include "access/nbtree.h"
#include "access/reloptions.h"
#include "access/relscan.h"
#include "catalog/catalog.h"
#include "commands/progress.h"
#include "lib/qunique.h"
#include "miscadmin.h"
#include "utils/array.h"
#include "utils/datum.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
Include dependency graph for nbtutils.c:

Go to the source code of this file.

Data Structures

struct  BTSortArrayContext
 
struct  BTOneVacInfo
 
struct  BTVacInfo
 

Typedefs

typedef struct BTSortArrayContext BTSortArrayContext
 
typedef struct BTOneVacInfo BTOneVacInfo
 
typedef struct BTVacInfo BTVacInfo
 

Functions

static Datum _bt_find_extreme_element (IndexScanDesc scan, ScanKey skey, StrategyNumber strat, Datum *elems, int nelems)
 
static int _bt_sort_array_elements (IndexScanDesc scan, ScanKey skey, bool reverse, Datum *elems, int nelems)
 
static int _bt_compare_array_elements (const void *a, const void *b, void *arg)
 
static bool _bt_compare_scankey_args (IndexScanDesc scan, ScanKey op, ScanKey leftarg, ScanKey rightarg, bool *result)
 
static bool _bt_fix_scankey_strategy (ScanKey skey, int16 *indoption)
 
static void _bt_mark_scankey_required (ScanKey skey)
 
static bool _bt_check_rowcompare (ScanKey skey, IndexTuple tuple, int tupnatts, TupleDesc tupdesc, ScanDirection dir, bool *continuescan)
 
static int _bt_keep_natts (Relation rel, IndexTuple lastleft, IndexTuple firstright, BTScanInsert itup_key)
 
BTScanInsert _bt_mkscankey (Relation rel, Relation heaprel, IndexTuple itup)
 
void _bt_freestack (BTStack stack)
 
void _bt_preprocess_array_keys (IndexScanDesc scan)
 
void _bt_start_array_keys (IndexScanDesc scan, ScanDirection dir)
 
bool _bt_advance_array_keys (IndexScanDesc scan, ScanDirection dir)
 
void _bt_mark_array_keys (IndexScanDesc scan)
 
void _bt_restore_array_keys (IndexScanDesc scan)
 
void _bt_preprocess_keys (IndexScanDesc scan)
 
bool _bt_checkkeys (IndexScanDesc scan, IndexTuple tuple, int tupnatts, ScanDirection dir, bool *continuescan)
 
void _bt_killitems (IndexScanDesc scan)
 
BTCycleId _bt_vacuum_cycleid (Relation rel)
 
BTCycleId _bt_start_vacuum (Relation rel)
 
void _bt_end_vacuum (Relation rel)
 
void _bt_end_vacuum_callback (int code, Datum arg)
 
Size BTreeShmemSize (void)
 
void BTreeShmemInit (void)
 
byteabtoptions (Datum reloptions, bool validate)
 
bool btproperty (Oid index_oid, int attno, IndexAMProperty prop, const char *propname, bool *res, bool *isnull)
 
char * btbuildphasename (int64 phasenum)
 
IndexTuple _bt_truncate (Relation rel, IndexTuple lastleft, IndexTuple firstright, BTScanInsert itup_key)
 
int _bt_keep_natts_fast (Relation rel, IndexTuple lastleft, IndexTuple firstright)
 
bool _bt_check_natts (Relation rel, bool heapkeyspace, Page page, OffsetNumber offnum)
 
void _bt_check_third_page (Relation rel, Relation heap, bool needheaptidspace, Page page, IndexTuple newtup)
 
bool _bt_allequalimage (Relation rel, bool debugmessage)
 

Variables

static BTVacInfobtvacinfo
 

Typedef Documentation

◆ BTOneVacInfo

typedef struct BTOneVacInfo BTOneVacInfo

◆ BTSortArrayContext

◆ BTVacInfo

typedef struct BTVacInfo BTVacInfo

Function Documentation

◆ _bt_advance_array_keys()

bool _bt_advance_array_keys ( IndexScanDesc  scan,
ScanDirection  dir 
)

Definition at line 551 of file nbtutils.c.

552 {
553  BTScanOpaque so = (BTScanOpaque) scan->opaque;
554  bool found = false;
555  int i;
556 
557  /*
558  * We must advance the last array key most quickly, since it will
559  * correspond to the lowest-order index column among the available
560  * qualifications. This is necessary to ensure correct ordering of output
561  * when there are multiple array keys.
562  */
563  for (i = so->numArrayKeys - 1; i >= 0; i--)
564  {
565  BTArrayKeyInfo *curArrayKey = &so->arrayKeys[i];
566  ScanKey skey = &so->arrayKeyData[curArrayKey->scan_key];
567  int cur_elem = curArrayKey->cur_elem;
568  int num_elems = curArrayKey->num_elems;
569 
570  if (ScanDirectionIsBackward(dir))
571  {
572  if (--cur_elem < 0)
573  {
574  cur_elem = num_elems - 1;
575  found = false; /* need to advance next array key */
576  }
577  else
578  found = true;
579  }
580  else
581  {
582  if (++cur_elem >= num_elems)
583  {
584  cur_elem = 0;
585  found = false; /* need to advance next array key */
586  }
587  else
588  found = true;
589  }
590 
591  curArrayKey->cur_elem = cur_elem;
592  skey->sk_argument = curArrayKey->elem_values[cur_elem];
593  if (found)
594  break;
595  }
596 
597  /* advance parallel scan */
598  if (scan->parallel_scan != NULL)
600 
601  return found;
602 }
int i
Definition: isn.c:73
void _bt_parallel_advance_array_keys(IndexScanDesc scan)
Definition: nbtree.c:758
BTScanOpaqueData * BTScanOpaque
Definition: nbtree.h:1076
#define ScanDirectionIsBackward(direction)
Definition: sdir.h:50
Datum * elem_values
Definition: nbtree.h:1031
BTArrayKeyInfo * arrayKeys
Definition: nbtree.h:1047
ScanKey arrayKeyData
Definition: nbtree.h:1042
struct ParallelIndexScanDescData * parallel_scan
Definition: relscan.h:166
Datum sk_argument
Definition: skey.h:72

References _bt_parallel_advance_array_keys(), BTScanOpaqueData::arrayKeyData, BTScanOpaqueData::arrayKeys, BTArrayKeyInfo::cur_elem, BTArrayKeyInfo::elem_values, i, BTArrayKeyInfo::num_elems, BTScanOpaqueData::numArrayKeys, IndexScanDescData::opaque, IndexScanDescData::parallel_scan, BTArrayKeyInfo::scan_key, ScanDirectionIsBackward, and ScanKeyData::sk_argument.

Referenced by btgetbitmap(), and btgettuple().

◆ _bt_allequalimage()

bool _bt_allequalimage ( Relation  rel,
bool  debugmessage 
)

Definition at line 2690 of file nbtutils.c.

2691 {
2692  bool allequalimage = true;
2693 
2694  /* INCLUDE indexes can never support deduplication */
2697  return false;
2698 
2699  for (int i = 0; i < IndexRelationGetNumberOfKeyAttributes(rel); i++)
2700  {
2701  Oid opfamily = rel->rd_opfamily[i];
2702  Oid opcintype = rel->rd_opcintype[i];
2703  Oid collation = rel->rd_indcollation[i];
2704  Oid equalimageproc;
2705 
2706  equalimageproc = get_opfamily_proc(opfamily, opcintype, opcintype,
2708 
2709  /*
2710  * If there is no BTEQUALIMAGE_PROC then deduplication is assumed to
2711  * be unsafe. Otherwise, actually call proc and see what it says.
2712  */
2713  if (!OidIsValid(equalimageproc) ||
2714  !DatumGetBool(OidFunctionCall1Coll(equalimageproc, collation,
2715  ObjectIdGetDatum(opcintype))))
2716  {
2717  allequalimage = false;
2718  break;
2719  }
2720  }
2721 
2722  if (debugmessage)
2723  {
2724  if (allequalimage)
2725  elog(DEBUG1, "index \"%s\" can safely use deduplication",
2727  else
2728  elog(DEBUG1, "index \"%s\" cannot use deduplication",
2730  }
2731 
2732  return allequalimage;
2733 }
#define OidIsValid(objectId)
Definition: c.h:759
#define DEBUG1
Definition: elog.h:30
Datum OidFunctionCall1Coll(Oid functionId, Oid collation, Datum arg1)
Definition: fmgr.c:1382
Oid get_opfamily_proc(Oid opfamily, Oid lefttype, Oid righttype, int16 procnum)
Definition: lsyscache.c:795
#define BTEQUALIMAGE_PROC
Definition: nbtree.h:707
static bool DatumGetBool(Datum X)
Definition: postgres.h:90
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
unsigned int Oid
Definition: postgres_ext.h:31
#define RelationGetRelationName(relation)
Definition: rel.h:538
#define IndexRelationGetNumberOfAttributes(relation)
Definition: rel.h:516
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:523
Oid * rd_opcintype
Definition: rel.h:207
Oid * rd_opfamily
Definition: rel.h:206
Oid * rd_indcollation
Definition: rel.h:216

References BTEQUALIMAGE_PROC, DatumGetBool(), DEBUG1, elog(), get_opfamily_proc(), i, IndexRelationGetNumberOfAttributes, IndexRelationGetNumberOfKeyAttributes, ObjectIdGetDatum(), OidFunctionCall1Coll(), OidIsValid, RelationData::rd_indcollation, RelationData::rd_opcintype, RelationData::rd_opfamily, and RelationGetRelationName.

Referenced by _bt_leafbuild(), bt_index_check_internal(), and btbuildempty().

◆ _bt_check_natts()

bool _bt_check_natts ( Relation  rel,
bool  heapkeyspace,
Page  page,
OffsetNumber  offnum 
)

Definition at line 2472 of file nbtutils.c.

2473 {
2476  BTPageOpaque opaque = BTPageGetOpaque(page);
2477  IndexTuple itup;
2478  int tupnatts;
2479 
2480  /*
2481  * We cannot reliably test a deleted or half-dead page, since they have
2482  * dummy high keys
2483  */
2484  if (P_IGNORE(opaque))
2485  return true;
2486 
2487  Assert(offnum >= FirstOffsetNumber &&
2488  offnum <= PageGetMaxOffsetNumber(page));
2489 
2490  itup = (IndexTuple) PageGetItem(page, PageGetItemId(page, offnum));
2491  tupnatts = BTreeTupleGetNAtts(itup, rel);
2492 
2493  /* !heapkeyspace indexes do not support deduplication */
2494  if (!heapkeyspace && BTreeTupleIsPosting(itup))
2495  return false;
2496 
2497  /* Posting list tuples should never have "pivot heap TID" bit set */
2498  if (BTreeTupleIsPosting(itup) &&
2500  BT_PIVOT_HEAP_TID_ATTR) != 0)
2501  return false;
2502 
2503  /* INCLUDE indexes do not support deduplication */
2504  if (natts != nkeyatts && BTreeTupleIsPosting(itup))
2505  return false;
2506 
2507  if (P_ISLEAF(opaque))
2508  {
2509  if (offnum >= P_FIRSTDATAKEY(opaque))
2510  {
2511  /*
2512  * Non-pivot tuple should never be explicitly marked as a pivot
2513  * tuple
2514  */
2515  if (BTreeTupleIsPivot(itup))
2516  return false;
2517 
2518  /*
2519  * Leaf tuples that are not the page high key (non-pivot tuples)
2520  * should never be truncated. (Note that tupnatts must have been
2521  * inferred, even with a posting list tuple, because only pivot
2522  * tuples store tupnatts directly.)
2523  */
2524  return tupnatts == natts;
2525  }
2526  else
2527  {
2528  /*
2529  * Rightmost page doesn't contain a page high key, so tuple was
2530  * checked above as ordinary leaf tuple
2531  */
2532  Assert(!P_RIGHTMOST(opaque));
2533 
2534  /*
2535  * !heapkeyspace high key tuple contains only key attributes. Note
2536  * that tupnatts will only have been explicitly represented in
2537  * !heapkeyspace indexes that happen to have non-key attributes.
2538  */
2539  if (!heapkeyspace)
2540  return tupnatts == nkeyatts;
2541 
2542  /* Use generic heapkeyspace pivot tuple handling */
2543  }
2544  }
2545  else /* !P_ISLEAF(opaque) */
2546  {
2547  if (offnum == P_FIRSTDATAKEY(opaque))
2548  {
2549  /*
2550  * The first tuple on any internal page (possibly the first after
2551  * its high key) is its negative infinity tuple. Negative
2552  * infinity tuples are always truncated to zero attributes. They
2553  * are a particular kind of pivot tuple.
2554  */
2555  if (heapkeyspace)
2556  return tupnatts == 0;
2557 
2558  /*
2559  * The number of attributes won't be explicitly represented if the
2560  * negative infinity tuple was generated during a page split that
2561  * occurred with a version of Postgres before v11. There must be
2562  * a problem when there is an explicit representation that is
2563  * non-zero, or when there is no explicit representation and the
2564  * tuple is evidently not a pre-pg_upgrade tuple.
2565  *
2566  * Prior to v11, downlinks always had P_HIKEY as their offset.
2567  * Accept that as an alternative indication of a valid
2568  * !heapkeyspace negative infinity tuple.
2569  */
2570  return tupnatts == 0 ||
2572  }
2573  else
2574  {
2575  /*
2576  * !heapkeyspace downlink tuple with separator key contains only
2577  * key attributes. Note that tupnatts will only have been
2578  * explicitly represented in !heapkeyspace indexes that happen to
2579  * have non-key attributes.
2580  */
2581  if (!heapkeyspace)
2582  return tupnatts == nkeyatts;
2583 
2584  /* Use generic heapkeyspace pivot tuple handling */
2585  }
2586  }
2587 
2588  /* Handle heapkeyspace pivot tuples (excluding minus infinity items) */
2589  Assert(heapkeyspace);
2590 
2591  /*
2592  * Explicit representation of the number of attributes is mandatory with
2593  * heapkeyspace index pivot tuples, regardless of whether or not there are
2594  * non-key attributes.
2595  */
2596  if (!BTreeTupleIsPivot(itup))
2597  return false;
2598 
2599  /* Pivot tuple should not use posting list representation (redundant) */
2600  if (BTreeTupleIsPosting(itup))
2601  return false;
2602 
2603  /*
2604  * Heap TID is a tiebreaker key attribute, so it cannot be untruncated
2605  * when any other key attribute is truncated
2606  */
2607  if (BTreeTupleGetHeapTID(itup) != NULL && tupnatts != nkeyatts)
2608  return false;
2609 
2610  /*
2611  * Pivot tuple must have at least one untruncated key attribute (minus
2612  * infinity pivot tuples are the only exception). Pivot tuples can never
2613  * represent that there is a value present for a key attribute that
2614  * exceeds pg_index.indnkeyatts for the index.
2615  */
2616  return tupnatts > 0 && tupnatts <= nkeyatts;
2617 }
static Item PageGetItem(Page page, ItemId itemId)
Definition: bufpage.h:351
static ItemId PageGetItemId(Page page, OffsetNumber offsetNumber)
Definition: bufpage.h:240
static OffsetNumber PageGetMaxOffsetNumber(Page page)
Definition: bufpage.h:369
signed short int16
Definition: c.h:477
static OffsetNumber ItemPointerGetOffsetNumber(const ItemPointerData *pointer)
Definition: itemptr.h:124
static OffsetNumber ItemPointerGetOffsetNumberNoCheck(const ItemPointerData *pointer)
Definition: itemptr.h:114
IndexTupleData * IndexTuple
Definition: itup.h:53
Assert(fmt[strlen(fmt) - 1] !='\n')
#define BT_PIVOT_HEAP_TID_ATTR
Definition: nbtree.h:462
static bool BTreeTupleIsPivot(IndexTuple itup)
Definition: nbtree.h:477
#define P_ISLEAF(opaque)
Definition: nbtree.h:220
#define P_HIKEY
Definition: nbtree.h:364
#define BTPageGetOpaque(page)
Definition: nbtree.h:73
#define P_FIRSTDATAKEY(opaque)
Definition: nbtree.h:366
#define P_RIGHTMOST(opaque)
Definition: nbtree.h:219
#define P_IGNORE(opaque)
Definition: nbtree.h:225
static bool BTreeTupleIsPosting(IndexTuple itup)
Definition: nbtree.h:489
static ItemPointer BTreeTupleGetHeapTID(IndexTuple itup)
Definition: nbtree.h:635
#define BTreeTupleGetNAtts(itup, rel)
Definition: nbtree.h:574
#define FirstOffsetNumber
Definition: off.h:27
ItemPointerData t_tid
Definition: itup.h:37

References Assert(), BT_PIVOT_HEAP_TID_ATTR, BTPageGetOpaque, BTreeTupleGetHeapTID(), BTreeTupleGetNAtts, BTreeTupleIsPivot(), BTreeTupleIsPosting(), FirstOffsetNumber, IndexRelationGetNumberOfAttributes, IndexRelationGetNumberOfKeyAttributes, ItemPointerGetOffsetNumber(), ItemPointerGetOffsetNumberNoCheck(), P_FIRSTDATAKEY, P_HIKEY, P_IGNORE, P_ISLEAF, P_RIGHTMOST, PageGetItem(), PageGetItemId(), PageGetMaxOffsetNumber(), and IndexTupleData::t_tid.

Referenced by _bt_compare(), and bt_target_page_check().

◆ _bt_check_rowcompare()

static bool _bt_check_rowcompare ( ScanKey  skey,
IndexTuple  tuple,
int  tupnatts,
TupleDesc  tupdesc,
ScanDirection  dir,
bool continuescan 
)
static

Definition at line 1529 of file nbtutils.c.

1531 {
1532  ScanKey subkey = (ScanKey) DatumGetPointer(skey->sk_argument);
1533  int32 cmpresult = 0;
1534  bool result;
1535 
1536  /* First subkey should be same as the header says */
1537  Assert(subkey->sk_attno == skey->sk_attno);
1538 
1539  /* Loop over columns of the row condition */
1540  for (;;)
1541  {
1542  Datum datum;
1543  bool isNull;
1544 
1545  Assert(subkey->sk_flags & SK_ROW_MEMBER);
1546 
1547  if (subkey->sk_attno > tupnatts)
1548  {
1549  /*
1550  * This attribute is truncated (must be high key). The value for
1551  * this attribute in the first non-pivot tuple on the page to the
1552  * right could be any possible value. Assume that truncated
1553  * attribute passes the qual.
1554  */
1556  Assert(BTreeTupleIsPivot(tuple));
1557  cmpresult = 0;
1558  if (subkey->sk_flags & SK_ROW_END)
1559  break;
1560  subkey++;
1561  continue;
1562  }
1563 
1564  datum = index_getattr(tuple,
1565  subkey->sk_attno,
1566  tupdesc,
1567  &isNull);
1568 
1569  if (isNull)
1570  {
1571  if (subkey->sk_flags & SK_BT_NULLS_FIRST)
1572  {
1573  /*
1574  * Since NULLs are sorted before non-NULLs, we know we have
1575  * reached the lower limit of the range of values for this
1576  * index attr. On a backward scan, we can stop if this qual
1577  * is one of the "must match" subset. We can stop regardless
1578  * of whether the qual is > or <, so long as it's required,
1579  * because it's not possible for any future tuples to pass. On
1580  * a forward scan, however, we must keep going, because we may
1581  * have initially positioned to the start of the index.
1582  */
1583  if ((subkey->sk_flags & (SK_BT_REQFWD | SK_BT_REQBKWD)) &&
1585  *continuescan = false;
1586  }
1587  else
1588  {
1589  /*
1590  * Since NULLs are sorted after non-NULLs, we know we have
1591  * reached the upper limit of the range of values for this
1592  * index attr. On a forward scan, we can stop if this qual is
1593  * one of the "must match" subset. We can stop regardless of
1594  * whether the qual is > or <, so long as it's required,
1595  * because it's not possible for any future tuples to pass. On
1596  * a backward scan, however, we must keep going, because we
1597  * may have initially positioned to the end of the index.
1598  */
1599  if ((subkey->sk_flags & (SK_BT_REQFWD | SK_BT_REQBKWD)) &&
1601  *continuescan = false;
1602  }
1603 
1604  /*
1605  * In any case, this indextuple doesn't match the qual.
1606  */
1607  return false;
1608  }
1609 
1610  if (subkey->sk_flags & SK_ISNULL)
1611  {
1612  /*
1613  * Unlike the simple-scankey case, this isn't a disallowed case.
1614  * But it can never match. If all the earlier row comparison
1615  * columns are required for the scan direction, we can stop the
1616  * scan, because there can't be another tuple that will succeed.
1617  */
1618  if (subkey != (ScanKey) DatumGetPointer(skey->sk_argument))
1619  subkey--;
1620  if ((subkey->sk_flags & SK_BT_REQFWD) &&
1622  *continuescan = false;
1623  else if ((subkey->sk_flags & SK_BT_REQBKWD) &&
1625  *continuescan = false;
1626  return false;
1627  }
1628 
1629  /* Perform the test --- three-way comparison not bool operator */
1630  cmpresult = DatumGetInt32(FunctionCall2Coll(&subkey->sk_func,
1631  subkey->sk_collation,
1632  datum,
1633  subkey->sk_argument));
1634 
1635  if (subkey->sk_flags & SK_BT_DESC)
1636  INVERT_COMPARE_RESULT(cmpresult);
1637 
1638  /* Done comparing if unequal, else advance to next column */
1639  if (cmpresult != 0)
1640  break;
1641 
1642  if (subkey->sk_flags & SK_ROW_END)
1643  break;
1644  subkey++;
1645  }
1646 
1647  /*
1648  * At this point cmpresult indicates the overall result of the row
1649  * comparison, and subkey points to the deciding column (or the last
1650  * column if the result is "=").
1651  */
1652  switch (subkey->sk_strategy)
1653  {
1654  /* EQ and NE cases aren't allowed here */
1655  case BTLessStrategyNumber:
1656  result = (cmpresult < 0);
1657  break;
1659  result = (cmpresult <= 0);
1660  break;
1662  result = (cmpresult >= 0);
1663  break;
1665  result = (cmpresult > 0);
1666  break;
1667  default:
1668  elog(ERROR, "unrecognized RowCompareType: %d",
1669  (int) subkey->sk_strategy);
1670  result = 0; /* keep compiler quiet */
1671  break;
1672  }
1673 
1674  if (!result)
1675  {
1676  /*
1677  * Tuple fails this qual. If it's a required qual for the current
1678  * scan direction, then we can conclude no further tuples will pass,
1679  * either. Note we have to look at the deciding column, not
1680  * necessarily the first or last column of the row condition.
1681  */
1682  if ((subkey->sk_flags & SK_BT_REQFWD) &&
1684  *continuescan = false;
1685  else if ((subkey->sk_flags & SK_BT_REQBKWD) &&
1687  *continuescan = false;
1688  }
1689 
1690  return result;
1691 }
#define INVERT_COMPARE_RESULT(var)
Definition: c.h:1114
signed int int32
Definition: c.h:478
#define ERROR
Definition: elog.h:39
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1120
static Datum index_getattr(IndexTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Definition: itup.h:117
#define SK_BT_REQBKWD
Definition: nbtree.h:1084
#define SK_BT_NULLS_FIRST
Definition: nbtree.h:1087
#define SK_BT_REQFWD
Definition: nbtree.h:1083
#define SK_BT_DESC
Definition: nbtree.h:1086
uintptr_t Datum
Definition: postgres.h:64
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:312
static int32 DatumGetInt32(Datum X)
Definition: postgres.h:202
#define ScanDirectionIsForward(direction)
Definition: sdir.h:64
#define SK_ROW_MEMBER
Definition: skey.h:118
#define SK_ROW_END
Definition: skey.h:119
ScanKeyData * ScanKey
Definition: skey.h:75
#define SK_ISNULL
Definition: skey.h:115
#define BTGreaterStrategyNumber
Definition: stratnum.h:33
#define BTLessStrategyNumber
Definition: stratnum.h:29
#define BTLessEqualStrategyNumber
Definition: stratnum.h:30
#define BTGreaterEqualStrategyNumber
Definition: stratnum.h:32
int sk_flags
Definition: skey.h:66
FmgrInfo sk_func
Definition: skey.h:71
Oid sk_collation
Definition: skey.h:70
StrategyNumber sk_strategy
Definition: skey.h:68
AttrNumber sk_attno
Definition: skey.h:67

References Assert(), BTGreaterEqualStrategyNumber, BTGreaterStrategyNumber, BTLessEqualStrategyNumber, BTLessStrategyNumber, BTreeTupleIsPivot(), DatumGetInt32(), DatumGetPointer(), elog(), ERROR, FunctionCall2Coll(), index_getattr(), INVERT_COMPARE_RESULT, ScanDirectionIsBackward, ScanDirectionIsForward, ScanKeyData::sk_argument, ScanKeyData::sk_attno, SK_BT_DESC, SK_BT_NULLS_FIRST, SK_BT_REQBKWD, SK_BT_REQFWD, ScanKeyData::sk_collation, ScanKeyData::sk_flags, ScanKeyData::sk_func, SK_ISNULL, SK_ROW_END, SK_ROW_MEMBER, and ScanKeyData::sk_strategy.

Referenced by _bt_checkkeys().

◆ _bt_check_third_page()

void _bt_check_third_page ( Relation  rel,
Relation  heap,
bool  needheaptidspace,
Page  page,
IndexTuple  newtup 
)

Definition at line 2632 of file nbtutils.c.

2634 {
2635  Size itemsz;
2636  BTPageOpaque opaque;
2637 
2638  itemsz = MAXALIGN(IndexTupleSize(newtup));
2639 
2640  /* Double check item size against limit */
2641  if (itemsz <= BTMaxItemSize(page))
2642  return;
2643 
2644  /*
2645  * Tuple is probably too large to fit on page, but it's possible that the
2646  * index uses version 2 or version 3, or that page is an internal page, in
2647  * which case a slightly higher limit applies.
2648  */
2649  if (!needheaptidspace && itemsz <= BTMaxItemSizeNoHeapTid(page))
2650  return;
2651 
2652  /*
2653  * Internal page insertions cannot fail here, because that would mean that
2654  * an earlier leaf level insertion that should have failed didn't
2655  */
2656  opaque = BTPageGetOpaque(page);
2657  if (!P_ISLEAF(opaque))
2658  elog(ERROR, "cannot insert oversized tuple of size %zu on internal page of index \"%s\"",
2659  itemsz, RelationGetRelationName(rel));
2660 
2661  ereport(ERROR,
2662  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
2663  errmsg("index row size %zu exceeds btree version %u maximum %zu for index \"%s\"",
2664  itemsz,
2665  needheaptidspace ? BTREE_VERSION : BTREE_NOVAC_VERSION,
2666  needheaptidspace ? BTMaxItemSize(page) :
2667  BTMaxItemSizeNoHeapTid(page),
2669  errdetail("Index row references tuple (%u,%u) in relation \"%s\".",
2672  RelationGetRelationName(heap)),
2673  errhint("Values larger than 1/3 of a buffer page cannot be indexed.\n"
2674  "Consider a function index of an MD5 hash of the value, "
2675  "or use full text indexing."),
2677 }
#define MAXALIGN(LEN)
Definition: c.h:795
size_t Size
Definition: c.h:589
int errdetail(const char *fmt,...)
Definition: elog.c:1202
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 ereport(elevel,...)
Definition: elog.h:149
static BlockNumber ItemPointerGetBlockNumber(const ItemPointerData *pointer)
Definition: itemptr.h:103
#define IndexTupleSize(itup)
Definition: itup.h:70
#define BTMaxItemSizeNoHeapTid(page)
Definition: nbtree.h:169
#define BTREE_VERSION
Definition: nbtree.h:150
#define BTMaxItemSize(page)
Definition: nbtree.h:164
#define BTREE_NOVAC_VERSION
Definition: nbtree.h:152
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:5960

References BTMaxItemSize, BTMaxItemSizeNoHeapTid, BTPageGetOpaque, BTREE_NOVAC_VERSION, BTREE_VERSION, BTreeTupleGetHeapTID(), elog(), ereport, errcode(), errdetail(), errhint(), errmsg(), ERROR, errtableconstraint(), IndexTupleSize, ItemPointerGetBlockNumber(), ItemPointerGetOffsetNumber(), MAXALIGN, P_ISLEAF, and RelationGetRelationName.

Referenced by _bt_buildadd(), and _bt_findinsertloc().

◆ _bt_checkkeys()

bool _bt_checkkeys ( IndexScanDesc  scan,
IndexTuple  tuple,
int  tupnatts,
ScanDirection  dir,
bool continuescan 
)

Definition at line 1362 of file nbtutils.c.

1364 {
1365  TupleDesc tupdesc;
1366  BTScanOpaque so;
1367  int keysz;
1368  int ikey;
1369  ScanKey key;
1370 
1371  Assert(BTreeTupleGetNAtts(tuple, scan->indexRelation) == tupnatts);
1372 
1373  *continuescan = true; /* default assumption */
1374 
1375  tupdesc = RelationGetDescr(scan->indexRelation);
1376  so = (BTScanOpaque) scan->opaque;
1377  keysz = so->numberOfKeys;
1378 
1379  for (key = so->keyData, ikey = 0; ikey < keysz; key++, ikey++)
1380  {
1381  Datum datum;
1382  bool isNull;
1383  Datum test;
1384 
1385  if (key->sk_attno > tupnatts)
1386  {
1387  /*
1388  * This attribute is truncated (must be high key). The value for
1389  * this attribute in the first non-pivot tuple on the page to the
1390  * right could be any possible value. Assume that truncated
1391  * attribute passes the qual.
1392  */
1394  Assert(BTreeTupleIsPivot(tuple));
1395  continue;
1396  }
1397 
1398  /* row-comparison keys need special processing */
1399  if (key->sk_flags & SK_ROW_HEADER)
1400  {
1401  if (_bt_check_rowcompare(key, tuple, tupnatts, tupdesc, dir,
1402  continuescan))
1403  continue;
1404  return false;
1405  }
1406 
1407  datum = index_getattr(tuple,
1408  key->sk_attno,
1409  tupdesc,
1410  &isNull);
1411 
1412  if (key->sk_flags & SK_ISNULL)
1413  {
1414  /* Handle IS NULL/NOT NULL tests */
1415  if (key->sk_flags & SK_SEARCHNULL)
1416  {
1417  if (isNull)
1418  continue; /* tuple satisfies this qual */
1419  }
1420  else
1421  {
1422  Assert(key->sk_flags & SK_SEARCHNOTNULL);
1423  if (!isNull)
1424  continue; /* tuple satisfies this qual */
1425  }
1426 
1427  /*
1428  * Tuple fails this qual. If it's a required qual for the current
1429  * scan direction, then we can conclude no further tuples will
1430  * pass, either.
1431  */
1432  if ((key->sk_flags & SK_BT_REQFWD) &&
1434  *continuescan = false;
1435  else if ((key->sk_flags & SK_BT_REQBKWD) &&
1437  *continuescan = false;
1438 
1439  /*
1440  * In any case, this indextuple doesn't match the qual.
1441  */
1442  return false;
1443  }
1444 
1445  if (isNull)
1446  {
1447  if (key->sk_flags & SK_BT_NULLS_FIRST)
1448  {
1449  /*
1450  * Since NULLs are sorted before non-NULLs, we know we have
1451  * reached the lower limit of the range of values for this
1452  * index attr. On a backward scan, we can stop if this qual
1453  * is one of the "must match" subset. We can stop regardless
1454  * of whether the qual is > or <, so long as it's required,
1455  * because it's not possible for any future tuples to pass. On
1456  * a forward scan, however, we must keep going, because we may
1457  * have initially positioned to the start of the index.
1458  */
1459  if ((key->sk_flags & (SK_BT_REQFWD | SK_BT_REQBKWD)) &&
1461  *continuescan = false;
1462  }
1463  else
1464  {
1465  /*
1466  * Since NULLs are sorted after non-NULLs, we know we have
1467  * reached the upper limit of the range of values for this
1468  * index attr. On a forward scan, we can stop if this qual is
1469  * one of the "must match" subset. We can stop regardless of
1470  * whether the qual is > or <, so long as it's required,
1471  * because it's not possible for any future tuples to pass. On
1472  * a backward scan, however, we must keep going, because we
1473  * may have initially positioned to the end of the index.
1474  */
1475  if ((key->sk_flags & (SK_BT_REQFWD | SK_BT_REQBKWD)) &&
1477  *continuescan = false;
1478  }
1479 
1480  /*
1481  * In any case, this indextuple doesn't match the qual.
1482  */
1483  return false;
1484  }
1485 
1486  test = FunctionCall2Coll(&key->sk_func, key->sk_collation,
1487  datum, key->sk_argument);
1488 
1489  if (!DatumGetBool(test))
1490  {
1491  /*
1492  * Tuple fails this qual. If it's a required qual for the current
1493  * scan direction, then we can conclude no further tuples will
1494  * pass, either.
1495  *
1496  * Note: because we stop the scan as soon as any required equality
1497  * qual fails, it is critical that equality quals be used for the
1498  * initial positioning in _bt_first() when they are available. See
1499  * comments in _bt_first().
1500  */
1501  if ((key->sk_flags & SK_BT_REQFWD) &&
1503  *continuescan = false;
1504  else if ((key->sk_flags & SK_BT_REQBKWD) &&
1506  *continuescan = false;
1507 
1508  /*
1509  * In any case, this indextuple doesn't match the qual.
1510  */
1511  return false;
1512  }
1513  }
1514 
1515  /* If we get here, the tuple passes all index quals. */
1516  return true;
1517 }
static bool _bt_check_rowcompare(ScanKey skey, IndexTuple tuple, int tupnatts, TupleDesc tupdesc, ScanDirection dir, bool *continuescan)
Definition: nbtutils.c:1529
static void test(void)
#define RelationGetDescr(relation)
Definition: rel.h:530
#define SK_ROW_HEADER
Definition: skey.h:117
#define SK_SEARCHNOTNULL
Definition: skey.h:122
#define SK_SEARCHNULL
Definition: skey.h:121
ScanKey keyData
Definition: nbtree.h:1039
Relation indexRelation
Definition: relscan.h:118

References _bt_check_rowcompare(), Assert(), BTreeTupleGetNAtts, BTreeTupleIsPivot(), DatumGetBool(), FunctionCall2Coll(), index_getattr(), IndexScanDescData::indexRelation, sort-test::key, BTScanOpaqueData::keyData, BTScanOpaqueData::numberOfKeys, IndexScanDescData::opaque, RelationGetDescr, ScanDirectionIsBackward, ScanDirectionIsForward, SK_BT_NULLS_FIRST, SK_BT_REQBKWD, SK_BT_REQFWD, SK_ISNULL, SK_ROW_HEADER, SK_SEARCHNOTNULL, SK_SEARCHNULL, and test().

Referenced by _bt_readpage().

◆ _bt_compare_array_elements()

static int _bt_compare_array_elements ( const void *  a,
const void *  b,
void *  arg 
)
static

Definition at line 503 of file nbtutils.c.

504 {
505  Datum da = *((const Datum *) a);
506  Datum db = *((const Datum *) b);
508  int32 compare;
509 
511  cxt->collation,
512  da, db));
513  if (cxt->reverse)
515  return compare;
516 }
static int compare(const void *arg1, const void *arg2)
Definition: geqo_pool.c:145
int b
Definition: isn.c:70
int a
Definition: isn.c:69
void * arg
FmgrInfo flinfo
Definition: nbtutils.c:36

References a, arg, b, BTSortArrayContext::collation, compare(), DatumGetInt32(), BTSortArrayContext::flinfo, FunctionCall2Coll(), INVERT_COMPARE_RESULT, and BTSortArrayContext::reverse.

Referenced by _bt_sort_array_elements().

◆ _bt_compare_scankey_args()

static bool _bt_compare_scankey_args ( IndexScanDesc  scan,
ScanKey  op,
ScanKey  leftarg,
ScanKey  rightarg,
bool result 
)
static

Definition at line 1039 of file nbtutils.c.

1042 {
1043  Relation rel = scan->indexRelation;
1044  Oid lefttype,
1045  righttype,
1046  optype,
1047  opcintype,
1048  cmp_op;
1049  StrategyNumber strat;
1050 
1051  /*
1052  * First, deal with cases where one or both args are NULL. This should
1053  * only happen when the scankeys represent IS NULL/NOT NULL conditions.
1054  */
1055  if ((leftarg->sk_flags | rightarg->sk_flags) & SK_ISNULL)
1056  {
1057  bool leftnull,
1058  rightnull;
1059 
1060  if (leftarg->sk_flags & SK_ISNULL)
1061  {
1063  leftnull = true;
1064  }
1065  else
1066  leftnull = false;
1067  if (rightarg->sk_flags & SK_ISNULL)
1068  {
1069  Assert(rightarg->sk_flags & (SK_SEARCHNULL | SK_SEARCHNOTNULL));
1070  rightnull = true;
1071  }
1072  else
1073  rightnull = false;
1074 
1075  /*
1076  * We treat NULL as either greater than or less than all other values.
1077  * Since true > false, the tests below work correctly for NULLS LAST
1078  * logic. If the index is NULLS FIRST, we need to flip the strategy.
1079  */
1080  strat = op->sk_strategy;
1081  if (op->sk_flags & SK_BT_NULLS_FIRST)
1082  strat = BTCommuteStrategyNumber(strat);
1083 
1084  switch (strat)
1085  {
1086  case BTLessStrategyNumber:
1087  *result = (leftnull < rightnull);
1088  break;
1090  *result = (leftnull <= rightnull);
1091  break;
1092  case BTEqualStrategyNumber:
1093  *result = (leftnull == rightnull);
1094  break;
1096  *result = (leftnull >= rightnull);
1097  break;
1099  *result = (leftnull > rightnull);
1100  break;
1101  default:
1102  elog(ERROR, "unrecognized StrategyNumber: %d", (int) strat);
1103  *result = false; /* keep compiler quiet */
1104  break;
1105  }
1106  return true;
1107  }
1108 
1109  /*
1110  * The opfamily we need to worry about is identified by the index column.
1111  */
1112  Assert(leftarg->sk_attno == rightarg->sk_attno);
1113 
1114  opcintype = rel->rd_opcintype[leftarg->sk_attno - 1];
1115 
1116  /*
1117  * Determine the actual datatypes of the ScanKey arguments. We have to
1118  * support the convention that sk_subtype == InvalidOid means the opclass
1119  * input type; this is a hack to simplify life for ScanKeyInit().
1120  */
1121  lefttype = leftarg->sk_subtype;
1122  if (lefttype == InvalidOid)
1123  lefttype = opcintype;
1124  righttype = rightarg->sk_subtype;
1125  if (righttype == InvalidOid)
1126  righttype = opcintype;
1127  optype = op->sk_subtype;
1128  if (optype == InvalidOid)
1129  optype = opcintype;
1130 
1131  /*
1132  * If leftarg and rightarg match the types expected for the "op" scankey,
1133  * we can use its already-looked-up comparison function.
1134  */
1135  if (lefttype == opcintype && righttype == optype)
1136  {
1137  *result = DatumGetBool(FunctionCall2Coll(&op->sk_func,
1138  op->sk_collation,
1139  leftarg->sk_argument,
1140  rightarg->sk_argument));
1141  return true;
1142  }
1143 
1144  /*
1145  * Otherwise, we need to go to the syscache to find the appropriate
1146  * operator. (This cannot result in infinite recursion, since no
1147  * indexscan initiated by syscache lookup will use cross-data-type
1148  * operators.)
1149  *
1150  * If the sk_strategy was flipped by _bt_fix_scankey_strategy, we have to
1151  * un-flip it to get the correct opfamily member.
1152  */
1153  strat = op->sk_strategy;
1154  if (op->sk_flags & SK_BT_DESC)
1155  strat = BTCommuteStrategyNumber(strat);
1156 
1157  cmp_op = get_opfamily_member(rel->rd_opfamily[leftarg->sk_attno - 1],
1158  lefttype,
1159  righttype,
1160  strat);
1161  if (OidIsValid(cmp_op))
1162  {
1163  RegProcedure cmp_proc = get_opcode(cmp_op);
1164 
1165  if (RegProcedureIsValid(cmp_proc))
1166  {
1167  *result = DatumGetBool(OidFunctionCall2Coll(cmp_proc,
1168  op->sk_collation,
1169  leftarg->sk_argument,
1170  rightarg->sk_argument));
1171  return true;
1172  }
1173  }
1174 
1175  /* Can't make the comparison */
1176  *result = false; /* suppress compiler warnings */
1177  return false;
1178 }
#define RegProcedureIsValid(p)
Definition: c.h:761
regproc RegProcedure
Definition: c.h:634
Datum OidFunctionCall2Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1392
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1267
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:165
#define BTCommuteStrategyNumber(strat)
Definition: nbtree.h:682
#define InvalidOid
Definition: postgres_ext.h:36
uint16 StrategyNumber
Definition: stratnum.h:22
#define BTEqualStrategyNumber
Definition: stratnum.h:31
Oid sk_subtype
Definition: skey.h:69

References Assert(), BTCommuteStrategyNumber, BTEqualStrategyNumber, BTGreaterEqualStrategyNumber, BTGreaterStrategyNumber, BTLessEqualStrategyNumber, BTLessStrategyNumber, DatumGetBool(), elog(), ERROR, FunctionCall2Coll(), get_opcode(), get_opfamily_member(), IndexScanDescData::indexRelation, InvalidOid, OidFunctionCall2Coll(), OidIsValid, RelationData::rd_opcintype, RelationData::rd_opfamily, RegProcedureIsValid, ScanKeyData::sk_argument, ScanKeyData::sk_attno, SK_BT_DESC, SK_BT_NULLS_FIRST, ScanKeyData::sk_collation, ScanKeyData::sk_flags, ScanKeyData::sk_func, SK_ISNULL, SK_SEARCHNOTNULL, SK_SEARCHNULL, ScanKeyData::sk_strategy, and ScanKeyData::sk_subtype.

Referenced by _bt_preprocess_keys().

◆ _bt_end_vacuum()

void _bt_end_vacuum ( Relation  rel)

Definition at line 2034 of file nbtutils.c.

2035 {
2036  int i;
2037 
2038  LWLockAcquire(BtreeVacuumLock, LW_EXCLUSIVE);
2039 
2040  /* Find the array entry */
2041  for (i = 0; i < btvacinfo->num_vacuums; i++)
2042  {
2043  BTOneVacInfo *vac = &btvacinfo->vacuums[i];
2044 
2045  if (vac->relid.relId == rel->rd_lockInfo.lockRelId.relId &&
2046  vac->relid.dbId == rel->rd_lockInfo.lockRelId.dbId)
2047  {
2048  /* Remove it by shifting down the last entry */
2049  *vac = btvacinfo->vacuums[btvacinfo->num_vacuums - 1];
2051  break;
2052  }
2053  }
2054 
2055  LWLockRelease(BtreeVacuumLock);
2056 }
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1195
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
@ LW_EXCLUSIVE
Definition: lwlock.h:116
static BTVacInfo * btvacinfo
Definition: nbtutils.c:1930
LockRelId relid
Definition: nbtutils.c:1918
int num_vacuums
Definition: nbtutils.c:1925
BTOneVacInfo vacuums[FLEXIBLE_ARRAY_MEMBER]
Definition: nbtutils.c:1927
LockRelId lockRelId
Definition: rel.h:46
Oid relId
Definition: rel.h:40
Oid dbId
Definition: rel.h:41
LockInfoData rd_lockInfo
Definition: rel.h:114

References btvacinfo, LockRelId::dbId, i, LockInfoData::lockRelId, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), BTVacInfo::num_vacuums, RelationData::rd_lockInfo, BTOneVacInfo::relid, LockRelId::relId, and BTVacInfo::vacuums.

Referenced by _bt_end_vacuum_callback(), and btbulkdelete().

◆ _bt_end_vacuum_callback()

void _bt_end_vacuum_callback ( int  code,
Datum  arg 
)

Definition at line 2062 of file nbtutils.c.

2063 {
2065 }
void _bt_end_vacuum(Relation rel)
Definition: nbtutils.c:2034

References _bt_end_vacuum(), arg, and DatumGetPointer().

Referenced by btbulkdelete().

◆ _bt_find_extreme_element()

static Datum _bt_find_extreme_element ( IndexScanDesc  scan,
ScanKey  skey,
StrategyNumber  strat,
Datum elems,
int  nelems 
)
static

Definition at line 382 of file nbtutils.c.

385 {
386  Relation rel = scan->indexRelation;
387  Oid elemtype,
388  cmp_op;
389  RegProcedure cmp_proc;
390  FmgrInfo flinfo;
391  Datum result;
392  int i;
393 
394  /*
395  * Determine the nominal datatype of the array elements. We have to
396  * support the convention that sk_subtype == InvalidOid means the opclass
397  * input type; this is a hack to simplify life for ScanKeyInit().
398  */
399  elemtype = skey->sk_subtype;
400  if (elemtype == InvalidOid)
401  elemtype = rel->rd_opcintype[skey->sk_attno - 1];
402 
403  /*
404  * Look up the appropriate comparison operator in the opfamily.
405  *
406  * Note: it's possible that this would fail, if the opfamily is
407  * incomplete, but it seems quite unlikely that an opfamily would omit
408  * non-cross-type comparison operators for any datatype that it supports
409  * at all.
410  */
411  cmp_op = get_opfamily_member(rel->rd_opfamily[skey->sk_attno - 1],
412  elemtype,
413  elemtype,
414  strat);
415  if (!OidIsValid(cmp_op))
416  elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
417  strat, elemtype, elemtype,
418  rel->rd_opfamily[skey->sk_attno - 1]);
419  cmp_proc = get_opcode(cmp_op);
420  if (!RegProcedureIsValid(cmp_proc))
421  elog(ERROR, "missing oprcode for operator %u", cmp_op);
422 
423  fmgr_info(cmp_proc, &flinfo);
424 
425  Assert(nelems > 0);
426  result = elems[0];
427  for (i = 1; i < nelems; i++)
428  {
429  if (DatumGetBool(FunctionCall2Coll(&flinfo,
430  skey->sk_collation,
431  elems[i],
432  result)))
433  result = elems[i];
434  }
435 
436  return result;
437 }
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:127
Definition: fmgr.h:57

References Assert(), DatumGetBool(), elog(), ERROR, fmgr_info(), FunctionCall2Coll(), get_opcode(), get_opfamily_member(), i, IndexScanDescData::indexRelation, InvalidOid, OidIsValid, RelationData::rd_opcintype, RelationData::rd_opfamily, RegProcedureIsValid, ScanKeyData::sk_attno, ScanKeyData::sk_collation, and ScanKeyData::sk_subtype.

Referenced by _bt_preprocess_array_keys().

◆ _bt_fix_scankey_strategy()

static bool _bt_fix_scankey_strategy ( ScanKey  skey,
int16 indoption 
)
static

Definition at line 1203 of file nbtutils.c.

1204 {
1205  int addflags;
1206 
1207  addflags = indoption[skey->sk_attno - 1] << SK_BT_INDOPTION_SHIFT;
1208 
1209  /*
1210  * We treat all btree operators as strict (even if they're not so marked
1211  * in pg_proc). This means that it is impossible for an operator condition
1212  * with a NULL comparison constant to succeed, and we can reject it right
1213  * away.
1214  *
1215  * However, we now also support "x IS NULL" clauses as search conditions,
1216  * so in that case keep going. The planner has not filled in any
1217  * particular strategy in this case, so set it to BTEqualStrategyNumber
1218  * --- we can treat IS NULL as an equality operator for purposes of search
1219  * strategy.
1220  *
1221  * Likewise, "x IS NOT NULL" is supported. We treat that as either "less
1222  * than NULL" in a NULLS LAST index, or "greater than NULL" in a NULLS
1223  * FIRST index.
1224  *
1225  * Note: someday we might have to fill in sk_collation from the index
1226  * column's collation. At the moment this is a non-issue because we'll
1227  * never actually call the comparison operator on a NULL.
1228  */
1229  if (skey->sk_flags & SK_ISNULL)
1230  {
1231  /* SK_ISNULL shouldn't be set in a row header scankey */
1232  Assert(!(skey->sk_flags & SK_ROW_HEADER));
1233 
1234  /* Set indoption flags in scankey (might be done already) */
1235  skey->sk_flags |= addflags;
1236 
1237  /* Set correct strategy for IS NULL or NOT NULL search */
1238  if (skey->sk_flags & SK_SEARCHNULL)
1239  {
1241  skey->sk_subtype = InvalidOid;
1242  skey->sk_collation = InvalidOid;
1243  }
1244  else if (skey->sk_flags & SK_SEARCHNOTNULL)
1245  {
1246  if (skey->sk_flags & SK_BT_NULLS_FIRST)
1248  else
1250  skey->sk_subtype = InvalidOid;
1251  skey->sk_collation = InvalidOid;
1252  }
1253  else
1254  {
1255  /* regular qual, so it cannot be satisfied */
1256  return false;
1257  }
1258 
1259  /* Needn't do the rest */
1260  return true;
1261  }
1262 
1263  /* Adjust strategy for DESC, if we didn't already */
1264  if ((addflags & SK_BT_DESC) && !(skey->sk_flags & SK_BT_DESC))
1266  skey->sk_flags |= addflags;
1267 
1268  /* If it's a row header, fix row member flags and strategies similarly */
1269  if (skey->sk_flags & SK_ROW_HEADER)
1270  {
1271  ScanKey subkey = (ScanKey) DatumGetPointer(skey->sk_argument);
1272 
1273  for (;;)
1274  {
1275  Assert(subkey->sk_flags & SK_ROW_MEMBER);
1276  addflags = indoption[subkey->sk_attno - 1] << SK_BT_INDOPTION_SHIFT;
1277  if ((addflags & SK_BT_DESC) && !(subkey->sk_flags & SK_BT_DESC))
1278  subkey->sk_strategy = BTCommuteStrategyNumber(subkey->sk_strategy);
1279  subkey->sk_flags |= addflags;
1280  if (subkey->sk_flags & SK_ROW_END)
1281  break;
1282  subkey++;
1283  }
1284  }
1285 
1286  return true;
1287 }
#define SK_BT_INDOPTION_SHIFT
Definition: nbtree.h:1085

References Assert(), BTCommuteStrategyNumber, BTEqualStrategyNumber, BTGreaterStrategyNumber, BTLessStrategyNumber, DatumGetPointer(), InvalidOid, ScanKeyData::sk_argument, ScanKeyData::sk_attno, SK_BT_DESC, SK_BT_INDOPTION_SHIFT, SK_BT_NULLS_FIRST, ScanKeyData::sk_collation, ScanKeyData::sk_flags, SK_ISNULL, SK_ROW_END, SK_ROW_HEADER, SK_ROW_MEMBER, SK_SEARCHNOTNULL, SK_SEARCHNULL, ScanKeyData::sk_strategy, and ScanKeyData::sk_subtype.

Referenced by _bt_preprocess_keys().

◆ _bt_freestack()

void _bt_freestack ( BTStack  stack)

Definition at line 182 of file nbtutils.c.

183 {
184  BTStack ostack;
185 
186  while (stack != NULL)
187  {
188  ostack = stack;
189  stack = stack->bts_parent;
190  pfree(ostack);
191  }
192 }
void pfree(void *pointer)
Definition: mcxt.c:1456
struct BTStackData * bts_parent
Definition: nbtree.h:733

References BTStackData::bts_parent, and pfree().

Referenced by _bt_doinsert(), _bt_first(), and bt_rootdescend().

◆ _bt_keep_natts()

static int _bt_keep_natts ( Relation  rel,
IndexTuple  lastleft,
IndexTuple  firstright,
BTScanInsert  itup_key 
)
static

Definition at line 2351 of file nbtutils.c.

2353 {
2354  int nkeyatts = IndexRelationGetNumberOfKeyAttributes(rel);
2355  TupleDesc itupdesc = RelationGetDescr(rel);
2356  int keepnatts;
2357  ScanKey scankey;
2358 
2359  /*
2360  * _bt_compare() treats truncated key attributes as having the value minus
2361  * infinity, which would break searches within !heapkeyspace indexes. We
2362  * must still truncate away non-key attribute values, though.
2363  */
2364  if (!itup_key->heapkeyspace)
2365  return nkeyatts;
2366 
2367  scankey = itup_key->scankeys;
2368  keepnatts = 1;
2369  for (int attnum = 1; attnum <= nkeyatts; attnum++, scankey++)
2370  {
2371  Datum datum1,
2372  datum2;
2373  bool isNull1,
2374  isNull2;
2375 
2376  datum1 = index_getattr(lastleft, attnum, itupdesc, &isNull1);
2377  datum2 = index_getattr(firstright, attnum, itupdesc, &isNull2);
2378 
2379  if (isNull1 != isNull2)
2380  break;
2381 
2382  if (!isNull1 &&
2384  scankey->sk_collation,
2385  datum1,
2386  datum2)) != 0)
2387  break;
2388 
2389  keepnatts++;
2390  }
2391 
2392  /*
2393  * Assert that _bt_keep_natts_fast() agrees with us in passing. This is
2394  * expected in an allequalimage index.
2395  */
2396  Assert(!itup_key->allequalimage ||
2397  keepnatts == _bt_keep_natts_fast(rel, lastleft, firstright));
2398 
2399  return keepnatts;
2400 }
int _bt_keep_natts_fast(Relation rel, IndexTuple lastleft, IndexTuple firstright)
Definition: nbtutils.c:2425
int16 attnum
Definition: pg_attribute.h:74
bool allequalimage
Definition: nbtree.h:789
bool heapkeyspace
Definition: nbtree.h:788
ScanKeyData scankeys[INDEX_MAX_KEYS]
Definition: nbtree.h:795

References _bt_keep_natts_fast(), BTScanInsertData::allequalimage, Assert(), attnum, DatumGetInt32(), FunctionCall2Coll(), BTScanInsertData::heapkeyspace, index_getattr(), IndexRelationGetNumberOfKeyAttributes, RelationGetDescr, BTScanInsertData::scankeys, ScanKeyData::sk_collation, and ScanKeyData::sk_func.

Referenced by _bt_truncate().

◆ _bt_keep_natts_fast()

int _bt_keep_natts_fast ( Relation  rel,
IndexTuple  lastleft,
IndexTuple  firstright 
)

Definition at line 2425 of file nbtutils.c.

2426 {
2427  TupleDesc itupdesc = RelationGetDescr(rel);
2428  int keysz = IndexRelationGetNumberOfKeyAttributes(rel);
2429  int keepnatts;
2430 
2431  keepnatts = 1;
2432  for (int attnum = 1; attnum <= keysz; attnum++)
2433  {
2434  Datum datum1,
2435  datum2;
2436  bool isNull1,
2437  isNull2;
2438  Form_pg_attribute att;
2439 
2440  datum1 = index_getattr(lastleft, attnum, itupdesc, &isNull1);
2441  datum2 = index_getattr(firstright, attnum, itupdesc, &isNull2);
2442  att = TupleDescAttr(itupdesc, attnum - 1);
2443 
2444  if (isNull1 != isNull2)
2445  break;
2446 
2447  if (!isNull1 &&
2448  !datum_image_eq(datum1, datum2, att->attbyval, att->attlen))
2449  break;
2450 
2451  keepnatts++;
2452  }
2453 
2454  return keepnatts;
2455 }
bool datum_image_eq(Datum value1, Datum value2, bool typByVal, int typLen)
Definition: datum.c:266
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

References attnum, datum_image_eq(), index_getattr(), IndexRelationGetNumberOfKeyAttributes, RelationGetDescr, and TupleDescAttr.

Referenced by _bt_afternewitemoff(), _bt_bottomupdel_pass(), _bt_dedup_pass(), _bt_do_singleval(), _bt_keep_natts(), _bt_load(), _bt_split_penalty(), and _bt_strategy().

◆ _bt_killitems()

void _bt_killitems ( IndexScanDesc  scan)

Definition at line 1725 of file nbtutils.c.

1726 {
1727  BTScanOpaque so = (BTScanOpaque) scan->opaque;
1728  Page page;
1729  BTPageOpaque opaque;
1730  OffsetNumber minoff;
1731  OffsetNumber maxoff;
1732  int i;
1733  int numKilled = so->numKilled;
1734  bool killedsomething = false;
1735  bool droppedpin PG_USED_FOR_ASSERTS_ONLY;
1736 
1738 
1739  /*
1740  * Always reset the scan state, so we don't look for same items on other
1741  * pages.
1742  */
1743  so->numKilled = 0;
1744 
1745  if (BTScanPosIsPinned(so->currPos))
1746  {
1747  /*
1748  * We have held the pin on this page since we read the index tuples,
1749  * so all we need to do is lock it. The pin will have prevented
1750  * re-use of any TID on the page, so there is no need to check the
1751  * LSN.
1752  */
1753  droppedpin = false;
1755 
1756  page = BufferGetPage(so->currPos.buf);
1757  }
1758  else
1759  {
1760  Buffer buf;
1761 
1762  droppedpin = true;
1763  /* Attempt to re-read the buffer, getting pin and lock. */
1764  buf = _bt_getbuf(scan->indexRelation, scan->heapRelation,
1765  so->currPos.currPage, BT_READ);
1766 
1767  page = BufferGetPage(buf);
1768  if (BufferGetLSNAtomic(buf) == so->currPos.lsn)
1769  so->currPos.buf = buf;
1770  else
1771  {
1772  /* Modified while not pinned means hinting is not safe. */
1773  _bt_relbuf(scan->indexRelation, buf);
1774  return;
1775  }
1776  }
1777 
1778  opaque = BTPageGetOpaque(page);
1779  minoff = P_FIRSTDATAKEY(opaque);
1780  maxoff = PageGetMaxOffsetNumber(page);
1781 
1782  for (i = 0; i < numKilled; i++)
1783  {
1784  int itemIndex = so->killedItems[i];
1785  BTScanPosItem *kitem = &so->currPos.items[itemIndex];
1786  OffsetNumber offnum = kitem->indexOffset;
1787 
1788  Assert(itemIndex >= so->currPos.firstItem &&
1789  itemIndex <= so->currPos.lastItem);
1790  if (offnum < minoff)
1791  continue; /* pure paranoia */
1792  while (offnum <= maxoff)
1793  {
1794  ItemId iid = PageGetItemId(page, offnum);
1795  IndexTuple ituple = (IndexTuple) PageGetItem(page, iid);
1796  bool killtuple = false;
1797 
1798  if (BTreeTupleIsPosting(ituple))
1799  {
1800  int pi = i + 1;
1801  int nposting = BTreeTupleGetNPosting(ituple);
1802  int j;
1803 
1804  /*
1805  * We rely on the convention that heap TIDs in the scanpos
1806  * items array are stored in ascending heap TID order for a
1807  * group of TIDs that originally came from a posting list
1808  * tuple. This convention even applies during backwards
1809  * scans, where returning the TIDs in descending order might
1810  * seem more natural. This is about effectiveness, not
1811  * correctness.
1812  *
1813  * Note that the page may have been modified in almost any way
1814  * since we first read it (in the !droppedpin case), so it's
1815  * possible that this posting list tuple wasn't a posting list
1816  * tuple when we first encountered its heap TIDs.
1817  */
1818  for (j = 0; j < nposting; j++)
1819  {
1820  ItemPointer item = BTreeTupleGetPostingN(ituple, j);
1821 
1822  if (!ItemPointerEquals(item, &kitem->heapTid))
1823  break; /* out of posting list loop */
1824 
1825  /*
1826  * kitem must have matching offnum when heap TIDs match,
1827  * though only in the common case where the page can't
1828  * have been concurrently modified
1829  */
1830  Assert(kitem->indexOffset == offnum || !droppedpin);
1831 
1832  /*
1833  * Read-ahead to later kitems here.
1834  *
1835  * We rely on the assumption that not advancing kitem here
1836  * will prevent us from considering the posting list tuple
1837  * fully dead by not matching its next heap TID in next
1838  * loop iteration.
1839  *
1840  * If, on the other hand, this is the final heap TID in
1841  * the posting list tuple, then tuple gets killed
1842  * regardless (i.e. we handle the case where the last
1843  * kitem is also the last heap TID in the last index tuple
1844  * correctly -- posting tuple still gets killed).
1845  */
1846  if (pi < numKilled)
1847  kitem = &so->currPos.items[so->killedItems[pi++]];
1848  }
1849 
1850  /*
1851  * Don't bother advancing the outermost loop's int iterator to
1852  * avoid processing killed items that relate to the same
1853  * offnum/posting list tuple. This micro-optimization hardly
1854  * seems worth it. (Further iterations of the outermost loop
1855  * will fail to match on this same posting list's first heap
1856  * TID instead, so we'll advance to the next offnum/index
1857  * tuple pretty quickly.)
1858  */
1859  if (j == nposting)
1860  killtuple = true;
1861  }
1862  else if (ItemPointerEquals(&ituple->t_tid, &kitem->heapTid))
1863  killtuple = true;
1864 
1865  /*
1866  * Mark index item as dead, if it isn't already. Since this
1867  * happens while holding a buffer lock possibly in shared mode,
1868  * it's possible that multiple processes attempt to do this
1869  * simultaneously, leading to multiple full-page images being sent
1870  * to WAL (if wal_log_hints or data checksums are enabled), which
1871  * is undesirable.
1872  */
1873  if (killtuple && !ItemIdIsDead(iid))
1874  {
1875  /* found the item/all posting list items */
1876  ItemIdMarkDead(iid);
1877  killedsomething = true;
1878  break; /* out of inner search loop */
1879  }
1880  offnum = OffsetNumberNext(offnum);
1881  }
1882  }
1883 
1884  /*
1885  * Since this can be redone later if needed, mark as dirty hint.
1886  *
1887  * Whenever we mark anything LP_DEAD, we also set the page's
1888  * BTP_HAS_GARBAGE flag, which is likewise just a hint. (Note that we
1889  * only rely on the page-level flag in !heapkeyspace indexes.)
1890  */
1891  if (killedsomething)
1892  {
1893  opaque->btpo_flags |= BTP_HAS_GARBAGE;
1894  MarkBufferDirtyHint(so->currPos.buf, true);
1895  }
1896 
1897  _bt_unlockbuf(scan->indexRelation, so->currPos.buf);
1898 }
int Buffer
Definition: buf.h:23
XLogRecPtr BufferGetLSNAtomic(Buffer buffer)
Definition: bufmgr.c:3551
void MarkBufferDirtyHint(Buffer buffer, bool buffer_std)
Definition: bufmgr.c:4544
static Page BufferGetPage(Buffer buffer)
Definition: bufmgr.h:355
Pointer Page
Definition: bufpage.h:78
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:166
int j
Definition: isn.c:74
#define ItemIdMarkDead(itemId)
Definition: itemid.h:179
#define ItemIdIsDead(itemId)
Definition: itemid.h:113
bool ItemPointerEquals(ItemPointer pointer1, ItemPointer pointer2)
Definition: itemptr.c:35
void _bt_relbuf(Relation rel, Buffer buf)
Definition: nbtpage.c:1020
Buffer _bt_getbuf(Relation rel, Relation heaprel, BlockNumber blkno, int access)
Definition: nbtpage.c:872
void _bt_unlockbuf(Relation rel, Buffer buf)
Definition: nbtpage.c:1067
void _bt_lockbuf(Relation rel, Buffer buf, int access)
Definition: nbtpage.c:1036
#define BTScanPosIsPinned(scanpos)
Definition: nbtree.h:992
static uint16 BTreeTupleGetNPosting(IndexTuple posting)
Definition: nbtree.h:515
#define BTP_HAS_GARBAGE
Definition: nbtree.h:82
#define BTScanPosIsValid(scanpos)
Definition: nbtree.h:1009
static ItemPointer BTreeTupleGetPostingN(IndexTuple posting, int n)
Definition: nbtree.h:541
#define BT_READ
Definition: nbtree.h:716
#define OffsetNumberNext(offsetNumber)
Definition: off.h:52
uint16 OffsetNumber
Definition: off.h:24
static char * buf
Definition: pg_test_fsync.c:67
BTScanPosData currPos
Definition: nbtree.h:1072
int * killedItems
Definition: nbtree.h:1051
Buffer buf
Definition: nbtree.h:955
BlockNumber currPage
Definition: nbtree.h:958
int firstItem
Definition: nbtree.h:983
BTScanPosItem items[MaxTIDsPerBTreePage]
Definition: nbtree.h:987
XLogRecPtr lsn
Definition: nbtree.h:957
ItemPointerData heapTid
Definition: nbtree.h:948
OffsetNumber indexOffset
Definition: nbtree.h:949
Relation heapRelation
Definition: relscan.h:117

References _bt_getbuf(), _bt_lockbuf(), _bt_relbuf(), _bt_unlockbuf(), Assert(), BT_READ, BTP_HAS_GARBAGE, BTPageGetOpaque, BTreeTupleGetNPosting(), BTreeTupleGetPostingN(), BTreeTupleIsPosting(), BTScanPosIsPinned, BTScanPosIsValid, buf, BTScanPosData::buf, BufferGetLSNAtomic(), BufferGetPage(), BTScanPosData::currPage, BTScanOpaqueData::currPos, BTScanPosData::firstItem, IndexScanDescData::heapRelation, BTScanPosItem::heapTid, i, BTScanPosItem::indexOffset, IndexScanDescData::indexRelation, ItemIdIsDead, ItemIdMarkDead, ItemPointerEquals(), BTScanPosData::items, j, BTScanOpaqueData::killedItems, BTScanPosData::lsn, MarkBufferDirtyHint(), BTScanOpaqueData::numKilled, OffsetNumberNext, IndexScanDescData::opaque, P_FIRSTDATAKEY, PageGetItem(), PageGetItemId(), PageGetMaxOffsetNumber(), PG_USED_FOR_ASSERTS_ONLY, and IndexTupleData::t_tid.

Referenced by _bt_steppage(), btendscan(), btrescan(), and btrestrpos().

◆ _bt_mark_array_keys()

void _bt_mark_array_keys ( IndexScanDesc  scan)

Definition at line 610 of file nbtutils.c.

611 {
612  BTScanOpaque so = (BTScanOpaque) scan->opaque;
613  int i;
614 
615  for (i = 0; i < so->numArrayKeys; i++)
616  {
617  BTArrayKeyInfo *curArrayKey = &so->arrayKeys[i];
618 
619  curArrayKey->mark_elem = curArrayKey->cur_elem;
620  }
621 }

References BTScanOpaqueData::arrayKeys, BTArrayKeyInfo::cur_elem, i, BTArrayKeyInfo::mark_elem, BTScanOpaqueData::numArrayKeys, and IndexScanDescData::opaque.

◆ _bt_mark_scankey_required()

static void _bt_mark_scankey_required ( ScanKey  skey)
static

Definition at line 1305 of file nbtutils.c.

1306 {
1307  int addflags;
1308 
1309  switch (skey->sk_strategy)
1310  {
1311  case BTLessStrategyNumber:
1313  addflags = SK_BT_REQFWD;
1314  break;
1315  case BTEqualStrategyNumber:
1316  addflags = SK_BT_REQFWD | SK_BT_REQBKWD;
1317  break;
1320  addflags = SK_BT_REQBKWD;
1321  break;
1322  default:
1323  elog(ERROR, "unrecognized StrategyNumber: %d",
1324  (int) skey->sk_strategy);
1325  addflags = 0; /* keep compiler quiet */
1326  break;
1327  }
1328 
1329  skey->sk_flags |= addflags;
1330 
1331  if (skey->sk_flags & SK_ROW_HEADER)
1332  {
1333  ScanKey subkey = (ScanKey) DatumGetPointer(skey->sk_argument);
1334 
1335  /* First subkey should be same column/operator as the header */
1336  Assert(subkey->sk_flags & SK_ROW_MEMBER);
1337  Assert(subkey->sk_attno == skey->sk_attno);
1338  Assert(subkey->sk_strategy == skey->sk_strategy);
1339  subkey->sk_flags |= addflags;
1340  }
1341 }

References Assert(), BTEqualStrategyNumber, BTGreaterEqualStrategyNumber, BTGreaterStrategyNumber, BTLessEqualStrategyNumber, BTLessStrategyNumber, DatumGetPointer(), elog(), ERROR, ScanKeyData::sk_argument, ScanKeyData::sk_attno, SK_BT_REQBKWD, SK_BT_REQFWD, ScanKeyData::sk_flags, SK_ROW_HEADER, SK_ROW_MEMBER, and ScanKeyData::sk_strategy.

Referenced by _bt_preprocess_keys().

◆ _bt_mkscankey()

BTScanInsert _bt_mkscankey ( Relation  rel,
Relation  heaprel,
IndexTuple  itup 
)

Definition at line 90 of file nbtutils.c.

91 {
93  ScanKey skey;
94  TupleDesc itupdesc;
95  int indnkeyatts;
96  int16 *indoption;
97  int tupnatts;
98  int i;
99 
100  itupdesc = RelationGetDescr(rel);
101  indnkeyatts = IndexRelationGetNumberOfKeyAttributes(rel);
102  indoption = rel->rd_indoption;
103  tupnatts = itup ? BTreeTupleGetNAtts(itup, rel) : 0;
104 
105  Assert(tupnatts <= IndexRelationGetNumberOfAttributes(rel));
106 
107  /*
108  * We'll execute search using scan key constructed on key columns.
109  * Truncated attributes and non-key attributes are omitted from the final
110  * scan key.
111  */
112  key = palloc(offsetof(BTScanInsertData, scankeys) +
113  sizeof(ScanKeyData) * indnkeyatts);
114  if (itup)
115  _bt_metaversion(rel, heaprel, &key->heapkeyspace, &key->allequalimage);
116  else
117  {
118  /* Utility statement callers can set these fields themselves */
119  key->heapkeyspace = true;
120  key->allequalimage = false;
121  }
122  key->anynullkeys = false; /* initial assumption */
123  key->nextkey = false;
124  key->pivotsearch = false;
125  key->keysz = Min(indnkeyatts, tupnatts);
126  key->scantid = key->heapkeyspace && itup ?
127  BTreeTupleGetHeapTID(itup) : NULL;
128  skey = key->scankeys;
129  for (i = 0; i < indnkeyatts; i++)
130  {
131  FmgrInfo *procinfo;
132  Datum arg;
133  bool null;
134  int flags;
135 
136  /*
137  * We can use the cached (default) support procs since no cross-type
138  * comparison can be needed.
139  */
140  procinfo = index_getprocinfo(rel, i + 1, BTORDER_PROC);
141 
142  /*
143  * Key arguments built from truncated attributes (or when caller
144  * provides no tuple) are defensively represented as NULL values. They
145  * should never be used.
146  */
147  if (i < tupnatts)
148  arg = index_getattr(itup, i + 1, itupdesc, &null);
149  else
150  {
151  arg = (Datum) 0;
152  null = true;
153  }
154  flags = (null ? SK_ISNULL : 0) | (indoption[i] << SK_BT_INDOPTION_SHIFT);
156  flags,
157  (AttrNumber) (i + 1),
159  InvalidOid,
160  rel->rd_indcollation[i],
161  procinfo,
162  arg);
163  /* Record if any key attribute is NULL (or truncated) */
164  if (null)
165  key->anynullkeys = true;
166  }
167 
168  /*
169  * In NULLS NOT DISTINCT mode, we pretend that there are no null keys, so
170  * that full uniqueness check is done.
171  */
172  if (rel->rd_index->indnullsnotdistinct)
173  key->anynullkeys = false;
174 
175  return key;
176 }
int16 AttrNumber
Definition: attnum.h:21
#define Min(x, y)
Definition: c.h:988
FmgrInfo * index_getprocinfo(Relation irel, AttrNumber attnum, uint16 procnum)
Definition: indexam.c:811
void * palloc(Size size)
Definition: mcxt.c:1226
void _bt_metaversion(Relation rel, Relation heaprel, bool *heapkeyspace, bool *allequalimage)
Definition: nbtpage.c:735
#define BTORDER_PROC
Definition: nbtree.h:704
void ScanKeyEntryInitializeWithInfo(ScanKey entry, int flags, AttrNumber attributeNumber, StrategyNumber strategy, Oid subtype, Oid collation, FmgrInfo *finfo, Datum argument)
Definition: scankey.c:101
#define InvalidStrategy
Definition: stratnum.h:24
int16 * rd_indoption
Definition: rel.h:210
Form_pg_index rd_index
Definition: rel.h:191

References _bt_metaversion(), arg, Assert(), BTORDER_PROC, BTreeTupleGetHeapTID(), BTreeTupleGetNAtts, i, index_getattr(), index_getprocinfo(), IndexRelationGetNumberOfAttributes, IndexRelationGetNumberOfKeyAttributes, InvalidOid, InvalidStrategy, sort-test::key, Min, palloc(), RelationData::rd_indcollation, RelationData::rd_index, RelationData::rd_indoption, RelationGetDescr, ScanKeyEntryInitializeWithInfo(), SK_BT_INDOPTION_SHIFT, and SK_ISNULL.

Referenced by _bt_doinsert(), _bt_leafbuild(), _bt_pagedel(), bt_mkscankey_pivotsearch(), bt_rootdescend(), tuplesort_begin_cluster(), and tuplesort_begin_index_btree().

◆ _bt_preprocess_array_keys()

void _bt_preprocess_array_keys ( IndexScanDesc  scan)

Definition at line 210 of file nbtutils.c.

211 {
212  BTScanOpaque so = (BTScanOpaque) scan->opaque;
213  int numberOfKeys = scan->numberOfKeys;
214  int16 *indoption = scan->indexRelation->rd_indoption;
215  int numArrayKeys;
216  ScanKey cur;
217  int i;
218  MemoryContext oldContext;
219 
220  /* Quick check to see if there are any array keys */
221  numArrayKeys = 0;
222  for (i = 0; i < numberOfKeys; i++)
223  {
224  cur = &scan->keyData[i];
225  if (cur->sk_flags & SK_SEARCHARRAY)
226  {
227  numArrayKeys++;
228  Assert(!(cur->sk_flags & (SK_ROW_HEADER | SK_SEARCHNULL | SK_SEARCHNOTNULL)));
229  /* If any arrays are null as a whole, we can quit right now. */
230  if (cur->sk_flags & SK_ISNULL)
231  {
232  so->numArrayKeys = -1;
233  so->arrayKeyData = NULL;
234  return;
235  }
236  }
237  }
238 
239  /* Quit if nothing to do. */
240  if (numArrayKeys == 0)
241  {
242  so->numArrayKeys = 0;
243  so->arrayKeyData = NULL;
244  return;
245  }
246 
247  /*
248  * Make a scan-lifespan context to hold array-associated data, or reset it
249  * if we already have one from a previous rescan cycle.
250  */
251  if (so->arrayContext == NULL)
253  "BTree array context",
255  else
257 
258  oldContext = MemoryContextSwitchTo(so->arrayContext);
259 
260  /* Create modifiable copy of scan->keyData in the workspace context */
261  so->arrayKeyData = (ScanKey) palloc(scan->numberOfKeys * sizeof(ScanKeyData));
262  memcpy(so->arrayKeyData,
263  scan->keyData,
264  scan->numberOfKeys * sizeof(ScanKeyData));
265 
266  /* Allocate space for per-array data in the workspace context */
267  so->arrayKeys = (BTArrayKeyInfo *) palloc0(numArrayKeys * sizeof(BTArrayKeyInfo));
268 
269  /* Now process each array key */
270  numArrayKeys = 0;
271  for (i = 0; i < numberOfKeys; i++)
272  {
273  ArrayType *arrayval;
274  int16 elmlen;
275  bool elmbyval;
276  char elmalign;
277  int num_elems;
278  Datum *elem_values;
279  bool *elem_nulls;
280  int num_nonnulls;
281  int j;
282 
283  cur = &so->arrayKeyData[i];
284  if (!(cur->sk_flags & SK_SEARCHARRAY))
285  continue;
286 
287  /*
288  * First, deconstruct the array into elements. Anything allocated
289  * here (including a possibly detoasted array value) is in the
290  * workspace context.
291  */
292  arrayval = DatumGetArrayTypeP(cur->sk_argument);
293  /* We could cache this data, but not clear it's worth it */
295  &elmlen, &elmbyval, &elmalign);
296  deconstruct_array(arrayval,
297  ARR_ELEMTYPE(arrayval),
298  elmlen, elmbyval, elmalign,
299  &elem_values, &elem_nulls, &num_elems);
300 
301  /*
302  * Compress out any null elements. We can ignore them since we assume
303  * all btree operators are strict.
304  */
305  num_nonnulls = 0;
306  for (j = 0; j < num_elems; j++)
307  {
308  if (!elem_nulls[j])
309  elem_values[num_nonnulls++] = elem_values[j];
310  }
311 
312  /* We could pfree(elem_nulls) now, but not worth the cycles */
313 
314  /* If there's no non-nulls, the scan qual is unsatisfiable */
315  if (num_nonnulls == 0)
316  {
317  numArrayKeys = -1;
318  break;
319  }
320 
321  /*
322  * If the comparison operator is not equality, then the array qual
323  * degenerates to a simple comparison against the smallest or largest
324  * non-null array element, as appropriate.
325  */
326  switch (cur->sk_strategy)
327  {
330  cur->sk_argument =
333  elem_values, num_nonnulls);
334  continue;
336  /* proceed with rest of loop */
337  break;
340  cur->sk_argument =
343  elem_values, num_nonnulls);
344  continue;
345  default:
346  elog(ERROR, "unrecognized StrategyNumber: %d",
347  (int) cur->sk_strategy);
348  break;
349  }
350 
351  /*
352  * Sort the non-null elements and eliminate any duplicates. We must
353  * sort in the same ordering used by the index column, so that the
354  * successive primitive indexscans produce data in index order.
355  */
356  num_elems = _bt_sort_array_elements(scan, cur,
357  (indoption[cur->sk_attno - 1] & INDOPTION_DESC) != 0,
358  elem_values, num_nonnulls);
359 
360  /*
361  * And set up the BTArrayKeyInfo data.
362  */
363  so->arrayKeys[numArrayKeys].scan_key = i;
364  so->arrayKeys[numArrayKeys].num_elems = num_elems;
365  so->arrayKeys[numArrayKeys].elem_values = elem_values;
366  numArrayKeys++;
367  }
368 
369  so->numArrayKeys = numArrayKeys;
370 
371  MemoryContextSwitchTo(oldContext);
372 }
#define DatumGetArrayTypeP(X)
Definition: array.h:254
#define ARR_ELEMTYPE(a)
Definition: array.h:285
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3599
struct cursor * cur
Definition: ecpg.c:28
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:2229
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:330
void * palloc0(Size size)
Definition: mcxt.c:1257
MemoryContext CurrentMemoryContext
Definition: mcxt.c:135
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:163
static Datum _bt_find_extreme_element(IndexScanDesc scan, ScanKey skey, StrategyNumber strat, Datum *elems, int nelems)
Definition: nbtutils.c:382
static int _bt_sort_array_elements(IndexScanDesc scan, ScanKey skey, bool reverse, Datum *elems, int nelems)
Definition: nbtutils.c:449
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:138
#define SK_SEARCHARRAY
Definition: skey.h:120
MemoryContext arrayContext
Definition: nbtree.h:1048
struct ScanKeyData * keyData
Definition: relscan.h:122

References _bt_find_extreme_element(), _bt_sort_array_elements(), ALLOCSET_SMALL_SIZES, AllocSetContextCreate, ARR_ELEMTYPE, BTScanOpaqueData::arrayContext, BTScanOpaqueData::arrayKeyData, BTScanOpaqueData::arrayKeys, Assert(), BTEqualStrategyNumber, BTGreaterEqualStrategyNumber, BTGreaterStrategyNumber, BTLessEqualStrategyNumber, BTLessStrategyNumber, cur, CurrentMemoryContext, DatumGetArrayTypeP, deconstruct_array(), BTArrayKeyInfo::elem_values, elog(), ERROR, get_typlenbyvalalign(), i, IndexScanDescData::indexRelation, j, IndexScanDescData::keyData, MemoryContextReset(), MemoryContextSwitchTo(), BTArrayKeyInfo::num_elems, BTScanOpaqueData::numArrayKeys, IndexScanDescData::numberOfKeys, IndexScanDescData::opaque, palloc(), palloc0(), RelationData::rd_indoption, BTArrayKeyInfo::scan_key, SK_ISNULL, SK_ROW_HEADER, SK_SEARCHARRAY, SK_SEARCHNOTNULL, and SK_SEARCHNULL.

Referenced by btrescan().

◆ _bt_preprocess_keys()

void _bt_preprocess_keys ( IndexScanDesc  scan)

Definition at line 749 of file nbtutils.c.

750 {
751  BTScanOpaque so = (BTScanOpaque) scan->opaque;
752  int numberOfKeys = scan->numberOfKeys;
753  int16 *indoption = scan->indexRelation->rd_indoption;
754  int new_numberOfKeys;
755  int numberOfEqualCols;
756  ScanKey inkeys;
757  ScanKey outkeys;
758  ScanKey cur;
760  bool test_result;
761  int i,
762  j;
763  AttrNumber attno;
764 
765  /* initialize result variables */
766  so->qual_ok = true;
767  so->numberOfKeys = 0;
768 
769  if (numberOfKeys < 1)
770  return; /* done if qual-less scan */
771 
772  /*
773  * Read so->arrayKeyData if array keys are present, else scan->keyData
774  */
775  if (so->arrayKeyData != NULL)
776  inkeys = so->arrayKeyData;
777  else
778  inkeys = scan->keyData;
779 
780  outkeys = so->keyData;
781  cur = &inkeys[0];
782  /* we check that input keys are correctly ordered */
783  if (cur->sk_attno < 1)
784  elog(ERROR, "btree index keys must be ordered by attribute");
785 
786  /* We can short-circuit most of the work if there's just one key */
787  if (numberOfKeys == 1)
788  {
789  /* Apply indoption to scankey (might change sk_strategy!) */
790  if (!_bt_fix_scankey_strategy(cur, indoption))
791  so->qual_ok = false;
792  memcpy(outkeys, cur, sizeof(ScanKeyData));
793  so->numberOfKeys = 1;
794  /* We can mark the qual as required if it's for first index col */
795  if (cur->sk_attno == 1)
796  _bt_mark_scankey_required(outkeys);
797  return;
798  }
799 
800  /*
801  * Otherwise, do the full set of pushups.
802  */
803  new_numberOfKeys = 0;
804  numberOfEqualCols = 0;
805 
806  /*
807  * Initialize for processing of keys for attr 1.
808  *
809  * xform[i] points to the currently best scan key of strategy type i+1; it
810  * is NULL if we haven't yet found such a key for this attr.
811  */
812  attno = 1;
813  memset(xform, 0, sizeof(xform));
814 
815  /*
816  * Loop iterates from 0 to numberOfKeys inclusive; we use the last pass to
817  * handle after-last-key processing. Actual exit from the loop is at the
818  * "break" statement below.
819  */
820  for (i = 0;; cur++, i++)
821  {
822  if (i < numberOfKeys)
823  {
824  /* Apply indoption to scankey (might change sk_strategy!) */
825  if (!_bt_fix_scankey_strategy(cur, indoption))
826  {
827  /* NULL can't be matched, so give up */
828  so->qual_ok = false;
829  return;
830  }
831  }
832 
833  /*
834  * If we are at the end of the keys for a particular attr, finish up
835  * processing and emit the cleaned-up keys.
836  */
837  if (i == numberOfKeys || cur->sk_attno != attno)
838  {
839  int priorNumberOfEqualCols = numberOfEqualCols;
840 
841  /* check input keys are correctly ordered */
842  if (i < numberOfKeys && cur->sk_attno < attno)
843  elog(ERROR, "btree index keys must be ordered by attribute");
844 
845  /*
846  * If = has been specified, all other keys can be eliminated as
847  * redundant. If we have a case like key = 1 AND key > 2, we can
848  * set qual_ok to false and abandon further processing.
849  *
850  * We also have to deal with the case of "key IS NULL", which is
851  * unsatisfiable in combination with any other index condition. By
852  * the time we get here, that's been classified as an equality
853  * check, and we've rejected any combination of it with a regular
854  * equality condition; but not with other types of conditions.
855  */
856  if (xform[BTEqualStrategyNumber - 1])
857  {
858  ScanKey eq = xform[BTEqualStrategyNumber - 1];
859 
860  for (j = BTMaxStrategyNumber; --j >= 0;)
861  {
862  ScanKey chk = xform[j];
863 
864  if (!chk || j == (BTEqualStrategyNumber - 1))
865  continue;
866 
867  if (eq->sk_flags & SK_SEARCHNULL)
868  {
869  /* IS NULL is contradictory to anything else */
870  so->qual_ok = false;
871  return;
872  }
873 
874  if (_bt_compare_scankey_args(scan, chk, eq, chk,
875  &test_result))
876  {
877  if (!test_result)
878  {
879  /* keys proven mutually contradictory */
880  so->qual_ok = false;
881  return;
882  }
883  /* else discard the redundant non-equality key */
884  xform[j] = NULL;
885  }
886  /* else, cannot determine redundancy, keep both keys */
887  }
888  /* track number of attrs for which we have "=" keys */
889  numberOfEqualCols++;
890  }
891 
892  /* try to keep only one of <, <= */
893  if (xform[BTLessStrategyNumber - 1]
894  && xform[BTLessEqualStrategyNumber - 1])
895  {
896  ScanKey lt = xform[BTLessStrategyNumber - 1];
897  ScanKey le = xform[BTLessEqualStrategyNumber - 1];
898 
899  if (_bt_compare_scankey_args(scan, le, lt, le,
900  &test_result))
901  {
902  if (test_result)
903  xform[BTLessEqualStrategyNumber - 1] = NULL;
904  else
905  xform[BTLessStrategyNumber - 1] = NULL;
906  }
907  }
908 
909  /* try to keep only one of >, >= */
910  if (xform[BTGreaterStrategyNumber - 1]
911  && xform[BTGreaterEqualStrategyNumber - 1])
912  {
913  ScanKey gt = xform[BTGreaterStrategyNumber - 1];
914  ScanKey ge = xform[BTGreaterEqualStrategyNumber - 1];
915 
916  if (_bt_compare_scankey_args(scan, ge, gt, ge,
917  &test_result))
918  {
919  if (test_result)
920  xform[BTGreaterEqualStrategyNumber - 1] = NULL;
921  else
922  xform[BTGreaterStrategyNumber - 1] = NULL;
923  }
924  }
925 
926  /*
927  * Emit the cleaned-up keys into the outkeys[] array, and then
928  * mark them if they are required. They are required (possibly
929  * only in one direction) if all attrs before this one had "=".
930  */
931  for (j = BTMaxStrategyNumber; --j >= 0;)
932  {
933  if (xform[j])
934  {
935  ScanKey outkey = &outkeys[new_numberOfKeys++];
936 
937  memcpy(outkey, xform[j], sizeof(ScanKeyData));
938  if (priorNumberOfEqualCols == attno - 1)
940  }
941  }
942 
943  /*
944  * Exit loop here if done.
945  */
946  if (i == numberOfKeys)
947  break;
948 
949  /* Re-initialize for new attno */
950  attno = cur->sk_attno;
951  memset(xform, 0, sizeof(xform));
952  }
953 
954  /* check strategy this key's operator corresponds to */
955  j = cur->sk_strategy - 1;
956 
957  /* if row comparison, push it directly to the output array */
958  if (cur->sk_flags & SK_ROW_HEADER)
959  {
960  ScanKey outkey = &outkeys[new_numberOfKeys++];
961 
962  memcpy(outkey, cur, sizeof(ScanKeyData));
963  if (numberOfEqualCols == attno - 1)
965 
966  /*
967  * We don't support RowCompare using equality; such a qual would
968  * mess up the numberOfEqualCols tracking.
969  */
970  Assert(j != (BTEqualStrategyNumber - 1));
971  continue;
972  }
973 
974  /* have we seen one of these before? */
975  if (xform[j] == NULL)
976  {
977  /* nope, so remember this scankey */
978  xform[j] = cur;
979  }
980  else
981  {
982  /* yup, keep only the more restrictive key */
983  if (_bt_compare_scankey_args(scan, cur, cur, xform[j],
984  &test_result))
985  {
986  if (test_result)
987  xform[j] = cur;
988  else if (j == (BTEqualStrategyNumber - 1))
989  {
990  /* key == a && key == b, but a != b */
991  so->qual_ok = false;
992  return;
993  }
994  /* else old key is more restrictive, keep it */
995  }
996  else
997  {
998  /*
999  * We can't determine which key is more restrictive. Keep the
1000  * previous one in xform[j] and push this one directly to the
1001  * output array.
1002  */
1003  ScanKey outkey = &outkeys[new_numberOfKeys++];
1004 
1005  memcpy(outkey, cur, sizeof(ScanKeyData));
1006  if (numberOfEqualCols == attno - 1)
1007  _bt_mark_scankey_required(outkey);
1008  }
1009  }
1010  }
1011 
1012  so->numberOfKeys = new_numberOfKeys;
1013 }
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
static bool _bt_fix_scankey_strategy(ScanKey skey, int16 *indoption)
Definition: nbtutils.c:1203
static bool _bt_compare_scankey_args(IndexScanDesc scan, ScanKey op, ScanKey leftarg, ScanKey rightarg, bool *result)
Definition: nbtutils.c:1039
static void _bt_mark_scankey_required(ScanKey skey)
Definition: nbtutils.c:1305
#define BTMaxStrategyNumber
Definition: stratnum.h:35

References _bt_compare_scankey_args(), _bt_fix_scankey_strategy(), _bt_mark_scankey_required(), BTScanOpaqueData::arrayKeyData, Assert(), BTEqualStrategyNumber, BTGreaterEqualStrategyNumber, BTGreaterStrategyNumber, BTLessEqualStrategyNumber, BTLessStrategyNumber, BTMaxStrategyNumber, cur, elog(), ERROR, i, if(), IndexScanDescData::indexRelation, j, BTScanOpaqueData::keyData, IndexScanDescData::keyData, BTScanOpaqueData::numberOfKeys, IndexScanDescData::numberOfKeys, IndexScanDescData::opaque, BTScanOpaqueData::qual_ok, RelationData::rd_indoption, ScanKeyData::sk_flags, SK_ROW_HEADER, and SK_SEARCHNULL.

Referenced by _bt_first(), and _bt_restore_array_keys().

◆ _bt_restore_array_keys()

void _bt_restore_array_keys ( IndexScanDesc  scan)

Definition at line 629 of file nbtutils.c.

630 {
631  BTScanOpaque so = (BTScanOpaque) scan->opaque;
632  bool changed = false;
633  int i;
634 
635  /* Restore each array key to its position when the mark was set */
636  for (i = 0; i < so->numArrayKeys; i++)
637  {
638  BTArrayKeyInfo *curArrayKey = &so->arrayKeys[i];
639  ScanKey skey = &so->arrayKeyData[curArrayKey->scan_key];
640  int mark_elem = curArrayKey->mark_elem;
641 
642  if (curArrayKey->cur_elem != mark_elem)
643  {
644  curArrayKey->cur_elem = mark_elem;
645  skey->sk_argument = curArrayKey->elem_values[mark_elem];
646  changed = true;
647  }
648  }
649 
650  /*
651  * If we changed any keys, we must redo _bt_preprocess_keys. That might
652  * sound like overkill, but in cases with multiple keys per index column
653  * it seems necessary to do the full set of pushups.
654  */
655  if (changed)
656  {
657  _bt_preprocess_keys(scan);
658  /* The mark should have been set on a consistent set of keys... */
659  Assert(so->qual_ok);
660  }
661 }
void _bt_preprocess_keys(IndexScanDesc scan)
Definition: nbtutils.c:749

References _bt_preprocess_keys(), BTScanOpaqueData::arrayKeyData, BTScanOpaqueData::arrayKeys, Assert(), BTArrayKeyInfo::cur_elem, BTArrayKeyInfo::elem_values, i, BTArrayKeyInfo::mark_elem, BTScanOpaqueData::numArrayKeys, IndexScanDescData::opaque, BTScanOpaqueData::qual_ok, BTArrayKeyInfo::scan_key, and ScanKeyData::sk_argument.

Referenced by btrestrpos().

◆ _bt_sort_array_elements()

static int _bt_sort_array_elements ( IndexScanDesc  scan,
ScanKey  skey,
bool  reverse,
Datum elems,
int  nelems 
)
static

Definition at line 449 of file nbtutils.c.

452 {
453  Relation rel = scan->indexRelation;
454  Oid elemtype;
455  RegProcedure cmp_proc;
456  BTSortArrayContext cxt;
457 
458  if (nelems <= 1)
459  return nelems; /* no work to do */
460 
461  /*
462  * Determine the nominal datatype of the array elements. We have to
463  * support the convention that sk_subtype == InvalidOid means the opclass
464  * input type; this is a hack to simplify life for ScanKeyInit().
465  */
466  elemtype = skey->sk_subtype;
467  if (elemtype == InvalidOid)
468  elemtype = rel->rd_opcintype[skey->sk_attno - 1];
469 
470  /*
471  * Look up the appropriate comparison function in the opfamily.
472  *
473  * Note: it's possible that this would fail, if the opfamily is
474  * incomplete, but it seems quite unlikely that an opfamily would omit
475  * non-cross-type support functions for any datatype that it supports at
476  * all.
477  */
478  cmp_proc = get_opfamily_proc(rel->rd_opfamily[skey->sk_attno - 1],
479  elemtype,
480  elemtype,
481  BTORDER_PROC);
482  if (!RegProcedureIsValid(cmp_proc))
483  elog(ERROR, "missing support function %d(%u,%u) in opfamily %u",
484  BTORDER_PROC, elemtype, elemtype,
485  rel->rd_opfamily[skey->sk_attno - 1]);
486 
487  /* Sort the array elements */
488  fmgr_info(cmp_proc, &cxt.flinfo);
489  cxt.collation = skey->sk_collation;
490  cxt.reverse = reverse;
491  qsort_arg(elems, nelems, sizeof(Datum),
493 
494  /* Now scan the sorted elements and remove duplicates */
495  return qunique_arg(elems, nelems, sizeof(Datum),
497 }
static int _bt_compare_array_elements(const void *a, const void *b, void *arg)
Definition: nbtutils.c:503
void qsort_arg(void *base, size_t nel, size_t elsize, qsort_arg_comparator cmp, void *arg)
static size_t qunique_arg(void *array, size_t elements, size_t width, int(*compare)(const void *, const void *, void *), void *arg)
Definition: qunique.h:46

References _bt_compare_array_elements(), BTORDER_PROC, BTSortArrayContext::collation, elog(), ERROR, BTSortArrayContext::flinfo, fmgr_info(), get_opfamily_proc(), IndexScanDescData::indexRelation, InvalidOid, qsort_arg(), qunique_arg(), RelationData::rd_opcintype, RelationData::rd_opfamily, RegProcedureIsValid, BTSortArrayContext::reverse, ScanKeyData::sk_attno, ScanKeyData::sk_collation, and ScanKeyData::sk_subtype.

Referenced by _bt_preprocess_array_keys().

◆ _bt_start_array_keys()

void _bt_start_array_keys ( IndexScanDesc  scan,
ScanDirection  dir 
)

Definition at line 525 of file nbtutils.c.

526 {
527  BTScanOpaque so = (BTScanOpaque) scan->opaque;
528  int i;
529 
530  for (i = 0; i < so->numArrayKeys; i++)
531  {
532  BTArrayKeyInfo *curArrayKey = &so->arrayKeys[i];
533  ScanKey skey = &so->arrayKeyData[curArrayKey->scan_key];
534 
535  Assert(curArrayKey->num_elems > 0);
536  if (ScanDirectionIsBackward(dir))
537  curArrayKey->cur_elem = curArrayKey->num_elems - 1;
538  else
539  curArrayKey->cur_elem = 0;
540  skey->sk_argument = curArrayKey->elem_values[curArrayKey->cur_elem];
541  }
542 }

References BTScanOpaqueData::arrayKeyData, BTScanOpaqueData::arrayKeys, Assert(), BTArrayKeyInfo::cur_elem, BTArrayKeyInfo::elem_values, i, BTArrayKeyInfo::num_elems, BTScanOpaqueData::numArrayKeys, IndexScanDescData::opaque, BTArrayKeyInfo::scan_key, ScanDirectionIsBackward, and ScanKeyData::sk_argument.

Referenced by btgetbitmap(), and btgettuple().

◆ _bt_start_vacuum()

BTCycleId _bt_start_vacuum ( Relation  rel)

Definition at line 1977 of file nbtutils.c.

1978 {
1979  BTCycleId result;
1980  int i;
1981  BTOneVacInfo *vac;
1982 
1983  LWLockAcquire(BtreeVacuumLock, LW_EXCLUSIVE);
1984 
1985  /*
1986  * Assign the next cycle ID, being careful to avoid zero as well as the
1987  * reserved high values.
1988  */
1989  result = ++(btvacinfo->cycle_ctr);
1990  if (result == 0 || result > MAX_BT_CYCLE_ID)
1991  result = btvacinfo->cycle_ctr = 1;
1992 
1993  /* Let's just make sure there's no entry already for this index */
1994  for (i = 0; i < btvacinfo->num_vacuums; i++)
1995  {
1996  vac = &btvacinfo->vacuums[i];
1997  if (vac->relid.relId == rel->rd_lockInfo.lockRelId.relId &&
1998  vac->relid.dbId == rel->rd_lockInfo.lockRelId.dbId)
1999  {
2000  /*
2001  * Unlike most places in the backend, we have to explicitly
2002  * release our LWLock before throwing an error. This is because
2003  * we expect _bt_end_vacuum() to be called before transaction
2004  * abort cleanup can run to release LWLocks.
2005  */
2006  LWLockRelease(BtreeVacuumLock);
2007  elog(ERROR, "multiple active vacuums for index \"%s\"",
2009  }
2010  }
2011 
2012  /* OK, add an entry */
2014  {
2015  LWLockRelease(BtreeVacuumLock);
2016  elog(ERROR, "out of btvacinfo slots");
2017  }
2019  vac->relid = rel->rd_lockInfo.lockRelId;
2020  vac->cycleid = result;
2022 
2023  LWLockRelease(BtreeVacuumLock);
2024  return result;
2025 }
#define MAX_BT_CYCLE_ID
Definition: nbtree.h:93
uint16 BTCycleId
Definition: nbtree.h:29
BTCycleId cycleid
Definition: nbtutils.c:1919
BTCycleId cycle_ctr
Definition: nbtutils.c:1924
int max_vacuums
Definition: nbtutils.c:1926

References btvacinfo, BTVacInfo::cycle_ctr, BTOneVacInfo::cycleid, LockRelId::dbId, elog(), ERROR, i, LockInfoData::lockRelId, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MAX_BT_CYCLE_ID, BTVacInfo::max_vacuums, BTVacInfo::num_vacuums, RelationData::rd_lockInfo, RelationGetRelationName, BTOneVacInfo::relid, LockRelId::relId, and BTVacInfo::vacuums.

Referenced by btbulkdelete().

◆ _bt_truncate()

IndexTuple _bt_truncate ( Relation  rel,
IndexTuple  lastleft,
IndexTuple  firstright,
BTScanInsert  itup_key 
)

Definition at line 2206 of file nbtutils.c.

2208 {
2209  TupleDesc itupdesc = RelationGetDescr(rel);
2211  int keepnatts;
2212  IndexTuple pivot;
2213  IndexTuple tidpivot;
2214  ItemPointer pivotheaptid;
2215  Size newsize;
2216 
2217  /*
2218  * We should only ever truncate non-pivot tuples from leaf pages. It's
2219  * never okay to truncate when splitting an internal page.
2220  */
2221  Assert(!BTreeTupleIsPivot(lastleft) && !BTreeTupleIsPivot(firstright));
2222 
2223  /* Determine how many attributes must be kept in truncated tuple */
2224  keepnatts = _bt_keep_natts(rel, lastleft, firstright, itup_key);
2225 
2226 #ifdef DEBUG_NO_TRUNCATE
2227  /* Force truncation to be ineffective for testing purposes */
2228  keepnatts = nkeyatts + 1;
2229 #endif
2230 
2231  pivot = index_truncate_tuple(itupdesc, firstright,
2232  Min(keepnatts, nkeyatts));
2233 
2234  if (BTreeTupleIsPosting(pivot))
2235  {
2236  /*
2237  * index_truncate_tuple() just returns a straight copy of firstright
2238  * when it has no attributes to truncate. When that happens, we may
2239  * need to truncate away a posting list here instead.
2240  */
2241  Assert(keepnatts == nkeyatts || keepnatts == nkeyatts + 1);
2242  Assert(IndexRelationGetNumberOfAttributes(rel) == nkeyatts);
2243  pivot->t_info &= ~INDEX_SIZE_MASK;
2244  pivot->t_info |= MAXALIGN(BTreeTupleGetPostingOffset(firstright));
2245  }
2246 
2247  /*
2248  * If there is a distinguishing key attribute within pivot tuple, we're
2249  * done
2250  */
2251  if (keepnatts <= nkeyatts)
2252  {
2253  BTreeTupleSetNAtts(pivot, keepnatts, false);
2254  return pivot;
2255  }
2256 
2257  /*
2258  * We have to store a heap TID in the new pivot tuple, since no non-TID
2259  * key attribute value in firstright distinguishes the right side of the
2260  * split from the left side. nbtree conceptualizes this case as an
2261  * inability to truncate away any key attributes, since heap TID is
2262  * treated as just another key attribute (despite lacking a pg_attribute
2263  * entry).
2264  *
2265  * Use enlarged space that holds a copy of pivot. We need the extra space
2266  * to store a heap TID at the end (using the special pivot tuple
2267  * representation). Note that the original pivot already has firstright's
2268  * possible posting list/non-key attribute values removed at this point.
2269  */
2270  newsize = MAXALIGN(IndexTupleSize(pivot)) + MAXALIGN(sizeof(ItemPointerData));
2271  tidpivot = palloc0(newsize);
2272  memcpy(tidpivot, pivot, MAXALIGN(IndexTupleSize(pivot)));
2273  /* Cannot leak memory here */
2274  pfree(pivot);
2275 
2276  /*
2277  * Store all of firstright's key attribute values plus a tiebreaker heap
2278  * TID value in enlarged pivot tuple
2279  */
2280  tidpivot->t_info &= ~INDEX_SIZE_MASK;
2281  tidpivot->t_info |= newsize;
2282  BTreeTupleSetNAtts(tidpivot, nkeyatts, true);
2283  pivotheaptid = BTreeTupleGetHeapTID(tidpivot);
2284 
2285  /*
2286  * Lehman & Yao use lastleft as the leaf high key in all cases, but don't
2287  * consider suffix truncation. It seems like a good idea to follow that
2288  * example in cases where no truncation takes place -- use lastleft's heap
2289  * TID. (This is also the closest value to negative infinity that's
2290  * legally usable.)
2291  */
2292  ItemPointerCopy(BTreeTupleGetMaxHeapTID(lastleft), pivotheaptid);
2293 
2294  /*
2295  * We're done. Assert() that heap TID invariants hold before returning.
2296  *
2297  * Lehman and Yao require that the downlink to the right page, which is to
2298  * be inserted into the parent page in the second phase of a page split be
2299  * a strict lower bound on items on the right page, and a non-strict upper
2300  * bound for items on the left page. Assert that heap TIDs follow these
2301  * invariants, since a heap TID value is apparently needed as a
2302  * tiebreaker.
2303  */
2304 #ifndef DEBUG_NO_TRUNCATE
2306  BTreeTupleGetHeapTID(firstright)) < 0);
2307  Assert(ItemPointerCompare(pivotheaptid,
2308  BTreeTupleGetHeapTID(lastleft)) >= 0);
2309  Assert(ItemPointerCompare(pivotheaptid,
2310  BTreeTupleGetHeapTID(firstright)) < 0);
2311 #else
2312 
2313  /*
2314  * Those invariants aren't guaranteed to hold for lastleft + firstright
2315  * heap TID attribute values when they're considered here only because
2316  * DEBUG_NO_TRUNCATE is defined (a heap TID is probably not actually
2317  * needed as a tiebreaker). DEBUG_NO_TRUNCATE must therefore use a heap
2318  * TID value that always works as a strict lower bound for items to the
2319  * right. In particular, it must avoid using firstright's leading key
2320  * attribute values along with lastleft's heap TID value when lastleft's
2321  * TID happens to be greater than firstright's TID.
2322  */
2323  ItemPointerCopy(BTreeTupleGetHeapTID(firstright), pivotheaptid);
2324 
2325  /*
2326  * Pivot heap TID should never be fully equal to firstright. Note that
2327  * the pivot heap TID will still end up equal to lastleft's heap TID when
2328  * that's the only usable value.
2329  */
2330  ItemPointerSetOffsetNumber(pivotheaptid,
2332  Assert(ItemPointerCompare(pivotheaptid,
2333  BTreeTupleGetHeapTID(firstright)) < 0);
2334 #endif
2335 
2336  return tidpivot;
2337 }
IndexTuple index_truncate_tuple(TupleDesc sourceDescriptor, IndexTuple source, int leavenatts)
Definition: indextuple.c:576
int32 ItemPointerCompare(ItemPointer arg1, ItemPointer arg2)
Definition: itemptr.c:51
static void ItemPointerSetOffsetNumber(ItemPointerData *pointer, OffsetNumber offsetNumber)
Definition: itemptr.h:158
static void ItemPointerCopy(const ItemPointerData *fromPointer, ItemPointerData *toPointer)
Definition: itemptr.h:172
#define INDEX_SIZE_MASK
Definition: itup.h:65
static uint32 BTreeTupleGetPostingOffset(IndexTuple posting)
Definition: nbtree.h:526
static ItemPointer BTreeTupleGetMaxHeapTID(IndexTuple itup)
Definition: nbtree.h:661
static void BTreeTupleSetNAtts(IndexTuple itup, uint16 nkeyatts, bool heaptid)
Definition: nbtree.h:592
static int _bt_keep_natts(Relation rel, IndexTuple lastleft, IndexTuple firstright, BTScanInsert itup_key)
Definition: nbtutils.c:2351
#define OffsetNumberPrev(offsetNumber)
Definition: off.h:54
unsigned short t_info
Definition: itup.h:49

References _bt_keep_natts(), Assert(), BTreeTupleGetHeapTID(), BTreeTupleGetMaxHeapTID(), BTreeTupleGetPostingOffset(), BTreeTupleIsPivot(), BTreeTupleIsPosting(), BTreeTupleSetNAtts(), INDEX_SIZE_MASK, index_truncate_tuple(), IndexRelationGetNumberOfAttributes, IndexRelationGetNumberOfKeyAttributes, IndexTupleSize, ItemPointerCompare(), ItemPointerCopy(), ItemPointerGetOffsetNumber(), ItemPointerSetOffsetNumber(), MAXALIGN, Min, OffsetNumberPrev, palloc0(), pfree(), RelationGetDescr, and IndexTupleData::t_info.

Referenced by _bt_buildadd(), and _bt_split().

◆ _bt_vacuum_cycleid()

BTCycleId _bt_vacuum_cycleid ( Relation  rel)

Definition at line 1943 of file nbtutils.c.

1944 {
1945  BTCycleId result = 0;
1946  int i;
1947 
1948  /* Share lock is enough since this is a read-only operation */
1949  LWLockAcquire(BtreeVacuumLock, LW_SHARED);
1950 
1951  for (i = 0; i < btvacinfo->num_vacuums; i++)
1952  {
1953  BTOneVacInfo *vac = &btvacinfo->vacuums[i];
1954 
1955  if (vac->relid.relId == rel->rd_lockInfo.lockRelId.relId &&
1956  vac->relid.dbId == rel->rd_lockInfo.lockRelId.dbId)
1957  {
1958  result = vac->cycleid;
1959  break;
1960  }
1961  }
1962 
1963  LWLockRelease(BtreeVacuumLock);
1964  return result;
1965 }
@ LW_SHARED
Definition: lwlock.h:117

References btvacinfo, BTOneVacInfo::cycleid, LockRelId::dbId, i, LockInfoData::lockRelId, LW_SHARED, LWLockAcquire(), LWLockRelease(), BTVacInfo::num_vacuums, RelationData::rd_lockInfo, BTOneVacInfo::relid, LockRelId::relId, and BTVacInfo::vacuums.

Referenced by _bt_split().

◆ btbuildphasename()

char* btbuildphasename ( int64  phasenum)

Definition at line 2158 of file nbtutils.c.

2159 {
2160  switch (phasenum)
2161  {
2163  return "initializing";
2165  return "scanning table";
2167  return "sorting live tuples";
2169  return "sorting dead tuples";
2171  return "loading tuples in tree";
2172  default:
2173  return NULL;
2174  }
2175 }
#define PROGRESS_BTREE_PHASE_PERFORMSORT_2
Definition: nbtree.h:1118
#define PROGRESS_BTREE_PHASE_LEAF_LOAD
Definition: nbtree.h:1119
#define PROGRESS_BTREE_PHASE_INDEXBUILD_TABLESCAN
Definition: nbtree.h:1116
#define PROGRESS_BTREE_PHASE_PERFORMSORT_1
Definition: nbtree.h:1117
#define PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE
Definition: progress.h:104

References PROGRESS_BTREE_PHASE_INDEXBUILD_TABLESCAN, PROGRESS_BTREE_PHASE_LEAF_LOAD, PROGRESS_BTREE_PHASE_PERFORMSORT_1, PROGRESS_BTREE_PHASE_PERFORMSORT_2, and PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE.

Referenced by bthandler().

◆ btoptions()

bytea* btoptions ( Datum  reloptions,
bool  validate 
)

Definition at line 2112 of file nbtutils.c.

2113 {
2114  static const relopt_parse_elt tab[] = {
2115  {"fillfactor", RELOPT_TYPE_INT, offsetof(BTOptions, fillfactor)},
2116  {"vacuum_cleanup_index_scale_factor", RELOPT_TYPE_REAL,
2117  offsetof(BTOptions, vacuum_cleanup_index_scale_factor)},
2118  {"deduplicate_items", RELOPT_TYPE_BOOL,
2119  offsetof(BTOptions, deduplicate_items)}
2120  };
2121 
2122  return (bytea *) build_reloptions(reloptions, validate,
2124  sizeof(BTOptions),
2125  tab, lengthof(tab));
2126 }
#define lengthof(array)
Definition: c.h:772
int fillfactor
Definition: pgbench.c:197
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_BTREE
Definition: reloptions.h:44
@ RELOPT_TYPE_INT
Definition: reloptions.h:32
@ RELOPT_TYPE_BOOL
Definition: reloptions.h:31
@ RELOPT_TYPE_REAL
Definition: reloptions.h:33
Definition: c.h:671

References build_reloptions(), fillfactor, lengthof, RELOPT_KIND_BTREE, RELOPT_TYPE_BOOL, RELOPT_TYPE_INT, and RELOPT_TYPE_REAL.

Referenced by bthandler().

◆ btproperty()

bool btproperty ( Oid  index_oid,
int  attno,
IndexAMProperty  prop,
const char *  propname,
bool res,
bool isnull 
)

Definition at line 2135 of file nbtutils.c.

2138 {
2139  switch (prop)
2140  {
2141  case AMPROP_RETURNABLE:
2142  /* answer only for columns, not AM or whole index */
2143  if (attno == 0)
2144  return false;
2145  /* otherwise, btree can always return data */
2146  *res = true;
2147  return true;
2148 
2149  default:
2150  return false; /* punt to generic code */
2151  }
2152 }
@ AMPROP_RETURNABLE
Definition: amapi.h:43

References AMPROP_RETURNABLE, and res.

Referenced by bthandler().

◆ BTreeShmemInit()

void BTreeShmemInit ( void  )

Definition at line 2084 of file nbtutils.c.

2085 {
2086  bool found;
2087 
2088  btvacinfo = (BTVacInfo *) ShmemInitStruct("BTree Vacuum State",
2089  BTreeShmemSize(),
2090  &found);
2091 
2092  if (!IsUnderPostmaster)
2093  {
2094  /* Initialize shared memory area */
2095  Assert(!found);
2096 
2097  /*
2098  * It doesn't really matter what the cycle counter starts at, but
2099  * having it always start the same doesn't seem good. Seed with
2100  * low-order bits of time() instead.
2101  */
2102  btvacinfo->cycle_ctr = (BTCycleId) time(NULL);
2103 
2104  btvacinfo->num_vacuums = 0;
2106  }
2107  else
2108  Assert(found);
2109 }
bool IsUnderPostmaster
Definition: globals.c:113
int MaxBackends
Definition: globals.c:140
Size BTreeShmemSize(void)
Definition: nbtutils.c:2071
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:396

References Assert(), BTreeShmemSize(), btvacinfo, BTVacInfo::cycle_ctr, IsUnderPostmaster, BTVacInfo::max_vacuums, MaxBackends, BTVacInfo::num_vacuums, and ShmemInitStruct().

Referenced by CreateSharedMemoryAndSemaphores().

◆ BTreeShmemSize()

Size BTreeShmemSize ( void  )

Definition at line 2071 of file nbtutils.c.

2072 {
2073  Size size;
2074 
2075  size = offsetof(BTVacInfo, vacuums);
2076  size = add_size(size, mul_size(MaxBackends, sizeof(BTOneVacInfo)));
2077  return size;
2078 }
Size add_size(Size s1, Size s2)
Definition: shmem.c:502
Size mul_size(Size s1, Size s2)
Definition: shmem.c:519

References add_size(), MaxBackends, and mul_size().

Referenced by BTreeShmemInit(), and CalculateShmemSize().

Variable Documentation

◆ btvacinfo

BTVacInfo* btvacinfo
static

Definition at line 1930 of file nbtutils.c.

Referenced by _bt_end_vacuum(), _bt_start_vacuum(), _bt_vacuum_cycleid(), and BTreeShmemInit().