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 "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, 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, bool continuescanPrechecked, bool haveFirstMatch)
 
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 544 of file nbtutils.c.

545 {
546  BTScanOpaque so = (BTScanOpaque) scan->opaque;
547  bool found = false;
548  int i;
549 
550  /*
551  * We must advance the last array key most quickly, since it will
552  * correspond to the lowest-order index column among the available
553  * qualifications. This is necessary to ensure correct ordering of output
554  * when there are multiple array keys.
555  */
556  for (i = so->numArrayKeys - 1; i >= 0; i--)
557  {
558  BTArrayKeyInfo *curArrayKey = &so->arrayKeys[i];
559  ScanKey skey = &so->arrayKeyData[curArrayKey->scan_key];
560  int cur_elem = curArrayKey->cur_elem;
561  int num_elems = curArrayKey->num_elems;
562 
563  if (ScanDirectionIsBackward(dir))
564  {
565  if (--cur_elem < 0)
566  {
567  cur_elem = num_elems - 1;
568  found = false; /* need to advance next array key */
569  }
570  else
571  found = true;
572  }
573  else
574  {
575  if (++cur_elem >= num_elems)
576  {
577  cur_elem = 0;
578  found = false; /* need to advance next array key */
579  }
580  else
581  found = true;
582  }
583 
584  curArrayKey->cur_elem = cur_elem;
585  skey->sk_argument = curArrayKey->elem_values[cur_elem];
586  if (found)
587  break;
588  }
589 
590  /* advance parallel scan */
591  if (scan->parallel_scan != NULL)
593 
594  /*
595  * When no new array keys were found, the scan is "past the end" of the
596  * array keys. _bt_start_array_keys can still "restart" the array keys if
597  * a rescan is required.
598  */
599  if (!found)
600  so->arraysStarted = false;
601 
602  return found;
603 }
int i
Definition: isn.c:73
void _bt_parallel_advance_array_keys(IndexScanDesc scan)
Definition: nbtree.c:746
BTScanOpaqueData * BTScanOpaque
Definition: nbtree.h:1076
for(int i=0;i< RT_NUM_SIZE_CLASSES;i++)
Definition: radixtree.h:1810
#define ScanDirectionIsBackward(direction)
Definition: sdir.h:50
Datum * elem_values
Definition: nbtree.h:1029
BTArrayKeyInfo * arrayKeys
Definition: nbtree.h:1047
bool arraysStarted
Definition: nbtree.h:1041
ScanKey arrayKeyData
Definition: nbtree.h:1040
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, BTScanOpaqueData::arraysStarted, BTArrayKeyInfo::cur_elem, BTArrayKeyInfo::elem_values, for(), 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 2740 of file nbtutils.c.

2741 {
2742  bool allequalimage = true;
2743 
2744  /* INCLUDE indexes can never support deduplication */
2747  return false;
2748 
2749  for (int i = 0; i < IndexRelationGetNumberOfKeyAttributes(rel); i++)
2750  {
2751  Oid opfamily = rel->rd_opfamily[i];
2752  Oid opcintype = rel->rd_opcintype[i];
2753  Oid collation = rel->rd_indcollation[i];
2754  Oid equalimageproc;
2755 
2756  equalimageproc = get_opfamily_proc(opfamily, opcintype, opcintype,
2758 
2759  /*
2760  * If there is no BTEQUALIMAGE_PROC then deduplication is assumed to
2761  * be unsafe. Otherwise, actually call proc and see what it says.
2762  */
2763  if (!OidIsValid(equalimageproc) ||
2764  !DatumGetBool(OidFunctionCall1Coll(equalimageproc, collation,
2765  ObjectIdGetDatum(opcintype))))
2766  {
2767  allequalimage = false;
2768  break;
2769  }
2770  }
2771 
2772  if (debugmessage)
2773  {
2774  if (allequalimage)
2775  elog(DEBUG1, "index \"%s\" can safely use deduplication",
2777  else
2778  elog(DEBUG1, "index \"%s\" cannot use deduplication",
2780  }
2781 
2782  return allequalimage;
2783 }
#define OidIsValid(objectId)
Definition: c.h:762
#define DEBUG1
Definition: elog.h:30
#define elog(elevel,...)
Definition: elog.h:224
Datum OidFunctionCall1Coll(Oid functionId, Oid collation, Datum arg1)
Definition: fmgr.c:1411
Oid get_opfamily_proc(Oid opfamily, Oid lefttype, Oid righttype, int16 procnum)
Definition: lsyscache.c:796
#define BTEQUALIMAGE_PROC
Definition: nbtree.h:710
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:541
#define IndexRelationGetNumberOfAttributes(relation)
Definition: rel.h:519
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:526
Oid * rd_opcintype
Definition: rel.h:208
Oid * rd_opfamily
Definition: rel.h:207
Oid * rd_indcollation
Definition: rel.h:217

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 2522 of file nbtutils.c.

2523 {
2526  BTPageOpaque opaque = BTPageGetOpaque(page);
2527  IndexTuple itup;
2528  int tupnatts;
2529 
2530  /*
2531  * We cannot reliably test a deleted or half-dead page, since they have
2532  * dummy high keys
2533  */
2534  if (P_IGNORE(opaque))
2535  return true;
2536 
2537  Assert(offnum >= FirstOffsetNumber &&
2538  offnum <= PageGetMaxOffsetNumber(page));
2539 
2540  itup = (IndexTuple) PageGetItem(page, PageGetItemId(page, offnum));
2541  tupnatts = BTreeTupleGetNAtts(itup, rel);
2542 
2543  /* !heapkeyspace indexes do not support deduplication */
2544  if (!heapkeyspace && BTreeTupleIsPosting(itup))
2545  return false;
2546 
2547  /* Posting list tuples should never have "pivot heap TID" bit set */
2548  if (BTreeTupleIsPosting(itup) &&
2550  BT_PIVOT_HEAP_TID_ATTR) != 0)
2551  return false;
2552 
2553  /* INCLUDE indexes do not support deduplication */
2554  if (natts != nkeyatts && BTreeTupleIsPosting(itup))
2555  return false;
2556 
2557  if (P_ISLEAF(opaque))
2558  {
2559  if (offnum >= P_FIRSTDATAKEY(opaque))
2560  {
2561  /*
2562  * Non-pivot tuple should never be explicitly marked as a pivot
2563  * tuple
2564  */
2565  if (BTreeTupleIsPivot(itup))
2566  return false;
2567 
2568  /*
2569  * Leaf tuples that are not the page high key (non-pivot tuples)
2570  * should never be truncated. (Note that tupnatts must have been
2571  * inferred, even with a posting list tuple, because only pivot
2572  * tuples store tupnatts directly.)
2573  */
2574  return tupnatts == natts;
2575  }
2576  else
2577  {
2578  /*
2579  * Rightmost page doesn't contain a page high key, so tuple was
2580  * checked above as ordinary leaf tuple
2581  */
2582  Assert(!P_RIGHTMOST(opaque));
2583 
2584  /*
2585  * !heapkeyspace high key tuple contains only key attributes. Note
2586  * that tupnatts will only have been explicitly represented in
2587  * !heapkeyspace indexes that happen to have non-key attributes.
2588  */
2589  if (!heapkeyspace)
2590  return tupnatts == nkeyatts;
2591 
2592  /* Use generic heapkeyspace pivot tuple handling */
2593  }
2594  }
2595  else /* !P_ISLEAF(opaque) */
2596  {
2597  if (offnum == P_FIRSTDATAKEY(opaque))
2598  {
2599  /*
2600  * The first tuple on any internal page (possibly the first after
2601  * its high key) is its negative infinity tuple. Negative
2602  * infinity tuples are always truncated to zero attributes. They
2603  * are a particular kind of pivot tuple.
2604  */
2605  if (heapkeyspace)
2606  return tupnatts == 0;
2607 
2608  /*
2609  * The number of attributes won't be explicitly represented if the
2610  * negative infinity tuple was generated during a page split that
2611  * occurred with a version of Postgres before v11. There must be
2612  * a problem when there is an explicit representation that is
2613  * non-zero, or when there is no explicit representation and the
2614  * tuple is evidently not a pre-pg_upgrade tuple.
2615  *
2616  * Prior to v11, downlinks always had P_HIKEY as their offset.
2617  * Accept that as an alternative indication of a valid
2618  * !heapkeyspace negative infinity tuple.
2619  */
2620  return tupnatts == 0 ||
2622  }
2623  else
2624  {
2625  /*
2626  * !heapkeyspace downlink tuple with separator key contains only
2627  * key attributes. Note that tupnatts will only have been
2628  * explicitly represented in !heapkeyspace indexes that happen to
2629  * have non-key attributes.
2630  */
2631  if (!heapkeyspace)
2632  return tupnatts == nkeyatts;
2633 
2634  /* Use generic heapkeyspace pivot tuple handling */
2635  }
2636  }
2637 
2638  /* Handle heapkeyspace pivot tuples (excluding minus infinity items) */
2639  Assert(heapkeyspace);
2640 
2641  /*
2642  * Explicit representation of the number of attributes is mandatory with
2643  * heapkeyspace index pivot tuples, regardless of whether or not there are
2644  * non-key attributes.
2645  */
2646  if (!BTreeTupleIsPivot(itup))
2647  return false;
2648 
2649  /* Pivot tuple should not use posting list representation (redundant) */
2650  if (BTreeTupleIsPosting(itup))
2651  return false;
2652 
2653  /*
2654  * Heap TID is a tiebreaker key attribute, so it cannot be untruncated
2655  * when any other key attribute is truncated
2656  */
2657  if (BTreeTupleGetHeapTID(itup) != NULL && tupnatts != nkeyatts)
2658  return false;
2659 
2660  /*
2661  * Pivot tuple must have at least one untruncated key attribute (minus
2662  * infinity pivot tuples are the only exception). Pivot tuples can never
2663  * represent that there is a value present for a key attribute that
2664  * exceeds pg_index.indnkeyatts for the index.
2665  */
2666  return tupnatts > 0 && tupnatts <= nkeyatts;
2667 }
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:480
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:465
static bool BTreeTupleIsPivot(IndexTuple itup)
Definition: nbtree.h:480
#define P_ISLEAF(opaque)
Definition: nbtree.h:220
#define P_HIKEY
Definition: nbtree.h:367
#define BTPageGetOpaque(page)
Definition: nbtree.h:73
#define P_FIRSTDATAKEY(opaque)
Definition: nbtree.h:369
#define P_RIGHTMOST(opaque)
Definition: nbtree.h:219
#define P_IGNORE(opaque)
Definition: nbtree.h:225
static bool BTreeTupleIsPosting(IndexTuple itup)
Definition: nbtree.h:492
static ItemPointer BTreeTupleGetHeapTID(IndexTuple itup)
Definition: nbtree.h:638
#define BTreeTupleGetNAtts(itup, rel)
Definition: nbtree.h:577
#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 1580 of file nbtutils.c.

1582 {
1583  ScanKey subkey = (ScanKey) DatumGetPointer(skey->sk_argument);
1584  int32 cmpresult = 0;
1585  bool result;
1586 
1587  /* First subkey should be same as the header says */
1588  Assert(subkey->sk_attno == skey->sk_attno);
1589 
1590  /* Loop over columns of the row condition */
1591  for (;;)
1592  {
1593  Datum datum;
1594  bool isNull;
1595 
1596  Assert(subkey->sk_flags & SK_ROW_MEMBER);
1597 
1598  if (subkey->sk_attno > tupnatts)
1599  {
1600  /*
1601  * This attribute is truncated (must be high key). The value for
1602  * this attribute in the first non-pivot tuple on the page to the
1603  * right could be any possible value. Assume that truncated
1604  * attribute passes the qual.
1605  */
1607  Assert(BTreeTupleIsPivot(tuple));
1608  cmpresult = 0;
1609  if (subkey->sk_flags & SK_ROW_END)
1610  break;
1611  subkey++;
1612  continue;
1613  }
1614 
1615  datum = index_getattr(tuple,
1616  subkey->sk_attno,
1617  tupdesc,
1618  &isNull);
1619 
1620  if (isNull)
1621  {
1622  if (subkey->sk_flags & SK_BT_NULLS_FIRST)
1623  {
1624  /*
1625  * Since NULLs are sorted before non-NULLs, we know we have
1626  * reached the lower limit of the range of values for this
1627  * index attr. On a backward scan, we can stop if this qual
1628  * is one of the "must match" subset. We can stop regardless
1629  * of whether the qual is > or <, so long as it's required,
1630  * because it's not possible for any future tuples to pass. On
1631  * a forward scan, however, we must keep going, because we may
1632  * have initially positioned to the start of the index.
1633  */
1634  if ((subkey->sk_flags & (SK_BT_REQFWD | SK_BT_REQBKWD)) &&
1636  *continuescan = false;
1637  }
1638  else
1639  {
1640  /*
1641  * Since NULLs are sorted after non-NULLs, we know we have
1642  * reached the upper limit of the range of values for this
1643  * index attr. On a forward scan, we can stop if this qual is
1644  * one of the "must match" subset. We can stop regardless of
1645  * whether the qual is > or <, so long as it's required,
1646  * because it's not possible for any future tuples to pass. On
1647  * a backward scan, however, we must keep going, because we
1648  * may have initially positioned to the end of the index.
1649  */
1650  if ((subkey->sk_flags & (SK_BT_REQFWD | SK_BT_REQBKWD)) &&
1652  *continuescan = false;
1653  }
1654 
1655  /*
1656  * In any case, this indextuple doesn't match the qual.
1657  */
1658  return false;
1659  }
1660 
1661  if (subkey->sk_flags & SK_ISNULL)
1662  {
1663  /*
1664  * Unlike the simple-scankey case, this isn't a disallowed case.
1665  * But it can never match. If all the earlier row comparison
1666  * columns are required for the scan direction, we can stop the
1667  * scan, because there can't be another tuple that will succeed.
1668  */
1669  if (subkey != (ScanKey) DatumGetPointer(skey->sk_argument))
1670  subkey--;
1671  if ((subkey->sk_flags & SK_BT_REQFWD) &&
1673  *continuescan = false;
1674  else if ((subkey->sk_flags & SK_BT_REQBKWD) &&
1676  *continuescan = false;
1677  return false;
1678  }
1679 
1680  /* Perform the test --- three-way comparison not bool operator */
1681  cmpresult = DatumGetInt32(FunctionCall2Coll(&subkey->sk_func,
1682  subkey->sk_collation,
1683  datum,
1684  subkey->sk_argument));
1685 
1686  if (subkey->sk_flags & SK_BT_DESC)
1687  INVERT_COMPARE_RESULT(cmpresult);
1688 
1689  /* Done comparing if unequal, else advance to next column */
1690  if (cmpresult != 0)
1691  break;
1692 
1693  if (subkey->sk_flags & SK_ROW_END)
1694  break;
1695  subkey++;
1696  }
1697 
1698  /*
1699  * At this point cmpresult indicates the overall result of the row
1700  * comparison, and subkey points to the deciding column (or the last
1701  * column if the result is "=").
1702  */
1703  switch (subkey->sk_strategy)
1704  {
1705  /* EQ and NE cases aren't allowed here */
1706  case BTLessStrategyNumber:
1707  result = (cmpresult < 0);
1708  break;
1710  result = (cmpresult <= 0);
1711  break;
1713  result = (cmpresult >= 0);
1714  break;
1716  result = (cmpresult > 0);
1717  break;
1718  default:
1719  elog(ERROR, "unrecognized RowCompareType: %d",
1720  (int) subkey->sk_strategy);
1721  result = 0; /* keep compiler quiet */
1722  break;
1723  }
1724 
1725  if (!result)
1726  {
1727  /*
1728  * Tuple fails this qual. If it's a required qual for the current
1729  * scan direction, then we can conclude no further tuples will pass,
1730  * either. Note we have to look at the deciding column, not
1731  * necessarily the first or last column of the row condition.
1732  */
1733  if ((subkey->sk_flags & SK_BT_REQFWD) &&
1735  *continuescan = false;
1736  else if ((subkey->sk_flags & SK_BT_REQBKWD) &&
1738  *continuescan = false;
1739  }
1740 
1741  return result;
1742 }
#define INVERT_COMPARE_RESULT(var)
Definition: c.h:1093
signed int int32
Definition: c.h:481
#define ERROR
Definition: elog.h:39
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1149
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 2682 of file nbtutils.c.

2684 {
2685  Size itemsz;
2686  BTPageOpaque opaque;
2687 
2688  itemsz = MAXALIGN(IndexTupleSize(newtup));
2689 
2690  /* Double check item size against limit */
2691  if (itemsz <= BTMaxItemSize(page))
2692  return;
2693 
2694  /*
2695  * Tuple is probably too large to fit on page, but it's possible that the
2696  * index uses version 2 or version 3, or that page is an internal page, in
2697  * which case a slightly higher limit applies.
2698  */
2699  if (!needheaptidspace && itemsz <= BTMaxItemSizeNoHeapTid(page))
2700  return;
2701 
2702  /*
2703  * Internal page insertions cannot fail here, because that would mean that
2704  * an earlier leaf level insertion that should have failed didn't
2705  */
2706  opaque = BTPageGetOpaque(page);
2707  if (!P_ISLEAF(opaque))
2708  elog(ERROR, "cannot insert oversized tuple of size %zu on internal page of index \"%s\"",
2709  itemsz, RelationGetRelationName(rel));
2710 
2711  ereport(ERROR,
2712  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
2713  errmsg("index row size %zu exceeds btree version %u maximum %zu for index \"%s\"",
2714  itemsz,
2715  needheaptidspace ? BTREE_VERSION : BTREE_NOVAC_VERSION,
2716  needheaptidspace ? BTMaxItemSize(page) :
2717  BTMaxItemSizeNoHeapTid(page),
2719  errdetail("Index row references tuple (%u,%u) in relation \"%s\".",
2722  RelationGetRelationName(heap)),
2723  errhint("Values larger than 1/3 of a buffer page cannot be indexed.\n"
2724  "Consider a function index of an MD5 hash of the value, "
2725  "or use full text indexing."),
2727 }
#define MAXALIGN(LEN)
Definition: c.h:798
size_t Size
Definition: c.h:592
int errdetail(const char *fmt,...)
Definition: elog.c:1205
int errhint(const char *fmt,...)
Definition: elog.c:1319
int errcode(int sqlerrcode)
Definition: elog.c:859
int errmsg(const char *fmt,...)
Definition: elog.c:1072
#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:5990

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,
bool  continuescanPrechecked,
bool  haveFirstMatch 
)

Definition at line 1372 of file nbtutils.c.

1375 {
1376  TupleDesc tupdesc;
1377  BTScanOpaque so;
1378  int keysz;
1379  int ikey;
1380  ScanKey key;
1381 
1382  Assert(BTreeTupleGetNAtts(tuple, scan->indexRelation) == tupnatts);
1383 
1384  *continuescan = true; /* default assumption */
1385 
1386  tupdesc = RelationGetDescr(scan->indexRelation);
1387  so = (BTScanOpaque) scan->opaque;
1388  keysz = so->numberOfKeys;
1389 
1390  for (key = so->keyData, ikey = 0; ikey < keysz; key++, ikey++)
1391  {
1392  Datum datum;
1393  bool isNull;
1394  Datum test;
1395  bool requiredSameDir = false,
1396  requiredOppositeDir = false;
1397 
1398  /*
1399  * Check if the key is required for ordered scan in the same or
1400  * opposite direction. Save as flag variables for future usage.
1401  */
1402  if (((key->sk_flags & SK_BT_REQFWD) && ScanDirectionIsForward(dir)) ||
1403  ((key->sk_flags & SK_BT_REQBKWD) && ScanDirectionIsBackward(dir)))
1404  requiredSameDir = true;
1405  else if (((key->sk_flags & SK_BT_REQFWD) && ScanDirectionIsBackward(dir)) ||
1406  ((key->sk_flags & SK_BT_REQBKWD) && ScanDirectionIsForward(dir)))
1407  requiredOppositeDir = true;
1408 
1409  /*
1410  * If the caller told us the *continuescan flag is known to be true
1411  * for the last item on the page, then we know the keys required for
1412  * the current direction scan should be matched. Otherwise, the
1413  * *continuescan flag would be set for the current item and
1414  * subsequently the last item on the page accordingly.
1415  *
1416  * If the key is required for the opposite direction scan, we can skip
1417  * the check if the caller tells us there was already at least one
1418  * matching item on the page. Also, we require the *continuescan flag
1419  * to be true for the last item on the page to know there are no
1420  * NULLs.
1421  *
1422  * Both cases above work except for the row keys, where NULLs could be
1423  * found in the middle of matching values.
1424  */
1425  if ((requiredSameDir || (requiredOppositeDir && haveFirstMatch)) &&
1426  !(key->sk_flags & SK_ROW_HEADER) && continuescanPrechecked)
1427  continue;
1428 
1429  if (key->sk_attno > tupnatts)
1430  {
1431  /*
1432  * This attribute is truncated (must be high key). The value for
1433  * this attribute in the first non-pivot tuple on the page to the
1434  * right could be any possible value. Assume that truncated
1435  * attribute passes the qual.
1436  */
1438  Assert(BTreeTupleIsPivot(tuple));
1439  continue;
1440  }
1441 
1442  /* row-comparison keys need special processing */
1443  if (key->sk_flags & SK_ROW_HEADER)
1444  {
1445  if (_bt_check_rowcompare(key, tuple, tupnatts, tupdesc, dir,
1446  continuescan))
1447  continue;
1448  return false;
1449  }
1450 
1451  datum = index_getattr(tuple,
1452  key->sk_attno,
1453  tupdesc,
1454  &isNull);
1455 
1456  if (key->sk_flags & SK_ISNULL)
1457  {
1458  /* Handle IS NULL/NOT NULL tests */
1459  if (key->sk_flags & SK_SEARCHNULL)
1460  {
1461  if (isNull)
1462  continue; /* tuple satisfies this qual */
1463  }
1464  else
1465  {
1466  Assert(key->sk_flags & SK_SEARCHNOTNULL);
1467  if (!isNull)
1468  continue; /* tuple satisfies this qual */
1469  }
1470 
1471  /*
1472  * Tuple fails this qual. If it's a required qual for the current
1473  * scan direction, then we can conclude no further tuples will
1474  * pass, either.
1475  */
1476  if (requiredSameDir)
1477  *continuescan = false;
1478 
1479  /*
1480  * In any case, this indextuple doesn't match the qual.
1481  */
1482  return false;
1483  }
1484 
1485  if (isNull)
1486  {
1487  if (key->sk_flags & SK_BT_NULLS_FIRST)
1488  {
1489  /*
1490  * Since NULLs are sorted before non-NULLs, we know we have
1491  * reached the lower limit of the range of values for this
1492  * index attr. On a backward scan, we can stop if this qual
1493  * is one of the "must match" subset. We can stop regardless
1494  * of whether the qual is > or <, so long as it's required,
1495  * because it's not possible for any future tuples to pass. On
1496  * a forward scan, however, we must keep going, because we may
1497  * have initially positioned to the start of the index.
1498  */
1499  if ((key->sk_flags & (SK_BT_REQFWD | SK_BT_REQBKWD)) &&
1501  *continuescan = false;
1502  }
1503  else
1504  {
1505  /*
1506  * Since NULLs are sorted after non-NULLs, we know we have
1507  * reached the upper limit of the range of values for this
1508  * index attr. On a forward scan, we can stop if this qual is
1509  * one of the "must match" subset. We can stop regardless of
1510  * whether the qual is > or <, so long as it's required,
1511  * because it's not possible for any future tuples to pass. On
1512  * a backward scan, however, we must keep going, because we
1513  * may have initially positioned to the end of the index.
1514  */
1515  if ((key->sk_flags & (SK_BT_REQFWD | SK_BT_REQBKWD)) &&
1517  *continuescan = false;
1518  }
1519 
1520  /*
1521  * In any case, this indextuple doesn't match the qual.
1522  */
1523  return false;
1524  }
1525 
1526  /*
1527  * Apply the key-checking function. When the key is required for the
1528  * opposite direction scan, it must be already satisfied as soon as
1529  * there is already match on the page. Except for the NULLs checking,
1530  * which have already done above.
1531  */
1532  if (!(requiredOppositeDir && haveFirstMatch))
1533  {
1534  test = FunctionCall2Coll(&key->sk_func, key->sk_collation,
1535  datum, key->sk_argument);
1536  }
1537  else
1538  {
1539  test = true;
1540  Assert(test == FunctionCall2Coll(&key->sk_func, key->sk_collation,
1541  datum, key->sk_argument));
1542  }
1543 
1544  if (!DatumGetBool(test))
1545  {
1546  /*
1547  * Tuple fails this qual. If it's a required qual for the current
1548  * scan direction, then we can conclude no further tuples will
1549  * pass, either.
1550  *
1551  * Note: because we stop the scan as soon as any required equality
1552  * qual fails, it is critical that equality quals be used for the
1553  * initial positioning in _bt_first() when they are available. See
1554  * comments in _bt_first().
1555  */
1556  if (requiredSameDir)
1557  *continuescan = false;
1558 
1559  /*
1560  * In any case, this indextuple doesn't match the qual.
1561  */
1562  return false;
1563  }
1564  }
1565 
1566  /* If we get here, the tuple passes all index quals. */
1567  return true;
1568 }
static bool _bt_check_rowcompare(ScanKey skey, IndexTuple tuple, int tupnatts, TupleDesc tupdesc, ScanDirection dir, bool *continuescan)
Definition: nbtutils.c:1580
static void test(void)
#define RelationGetDescr(relation)
Definition: rel.h:533
#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:1037
Relation indexRelation
Definition: relscan.h:118

References _bt_check_rowcompare(), Assert(), BTreeTupleGetNAtts, BTreeTupleIsPivot(), DatumGetBool(), for(), 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 494 of file nbtutils.c.

495 {
496  Datum da = *((const Datum *) a);
497  Datum db = *((const Datum *) b);
499  int32 compare;
500 
502  cxt->collation,
503  da, db));
504  if (cxt->reverse)
506  return compare;
507 }
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:35

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 1045 of file nbtutils.c.

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

2085 {
2086  int i;
2087 
2088  LWLockAcquire(BtreeVacuumLock, LW_EXCLUSIVE);
2089 
2090  /* Find the array entry */
2091  for (i = 0; i < btvacinfo->num_vacuums; i++)
2092  {
2093  BTOneVacInfo *vac = &btvacinfo->vacuums[i];
2094 
2095  if (vac->relid.relId == rel->rd_lockInfo.lockRelId.relId &&
2096  vac->relid.dbId == rel->rd_lockInfo.lockRelId.dbId)
2097  {
2098  /* Remove it by shifting down the last entry */
2099  *vac = btvacinfo->vacuums[btvacinfo->num_vacuums - 1];
2101  break;
2102  }
2103  }
2104 
2105  LWLockRelease(BtreeVacuumLock);
2106 }
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1169
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1782
@ LW_EXCLUSIVE
Definition: lwlock.h:114
static BTVacInfo * btvacinfo
Definition: nbtutils.c:1980
LockRelId relid
Definition: nbtutils.c:1968
int num_vacuums
Definition: nbtutils.c:1975
BTOneVacInfo vacuums[FLEXIBLE_ARRAY_MEMBER]
Definition: nbtutils.c:1977
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 2112 of file nbtutils.c.

2113 {
2115 }
void _bt_end_vacuum(Relation rel)
Definition: nbtutils.c:2084

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 373 of file nbtutils.c.

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

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

174 {
175  BTStack ostack;
176 
177  while (stack != NULL)
178  {
179  ostack = stack;
180  stack = stack->bts_parent;
181  pfree(ostack);
182  }
183 }
void pfree(void *pointer)
Definition: mcxt.c:1508
struct BTStackData * bts_parent
Definition: nbtree.h:736

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 2401 of file nbtutils.c.

2403 {
2404  int nkeyatts = IndexRelationGetNumberOfKeyAttributes(rel);
2405  TupleDesc itupdesc = RelationGetDescr(rel);
2406  int keepnatts;
2407  ScanKey scankey;
2408 
2409  /*
2410  * _bt_compare() treats truncated key attributes as having the value minus
2411  * infinity, which would break searches within !heapkeyspace indexes. We
2412  * must still truncate away non-key attribute values, though.
2413  */
2414  if (!itup_key->heapkeyspace)
2415  return nkeyatts;
2416 
2417  scankey = itup_key->scankeys;
2418  keepnatts = 1;
2419  for (int attnum = 1; attnum <= nkeyatts; attnum++, scankey++)
2420  {
2421  Datum datum1,
2422  datum2;
2423  bool isNull1,
2424  isNull2;
2425 
2426  datum1 = index_getattr(lastleft, attnum, itupdesc, &isNull1);
2427  datum2 = index_getattr(firstright, attnum, itupdesc, &isNull2);
2428 
2429  if (isNull1 != isNull2)
2430  break;
2431 
2432  if (!isNull1 &&
2434  scankey->sk_collation,
2435  datum1,
2436  datum2)) != 0)
2437  break;
2438 
2439  keepnatts++;
2440  }
2441 
2442  /*
2443  * Assert that _bt_keep_natts_fast() agrees with us in passing. This is
2444  * expected in an allequalimage index.
2445  */
2446  Assert(!itup_key->allequalimage ||
2447  keepnatts == _bt_keep_natts_fast(rel, lastleft, firstright));
2448 
2449  return keepnatts;
2450 }
int _bt_keep_natts_fast(Relation rel, IndexTuple lastleft, IndexTuple firstright)
Definition: nbtutils.c:2475
int16 attnum
Definition: pg_attribute.h:74
bool allequalimage
Definition: nbtree.h:787
bool heapkeyspace
Definition: nbtree.h:786
ScanKeyData scankeys[INDEX_MAX_KEYS]
Definition: nbtree.h:793

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 2475 of file nbtutils.c.

2476 {
2477  TupleDesc itupdesc = RelationGetDescr(rel);
2478  int keysz = IndexRelationGetNumberOfKeyAttributes(rel);
2479  int keepnatts;
2480 
2481  keepnatts = 1;
2482  for (int attnum = 1; attnum <= keysz; attnum++)
2483  {
2484  Datum datum1,
2485  datum2;
2486  bool isNull1,
2487  isNull2;
2488  Form_pg_attribute att;
2489 
2490  datum1 = index_getattr(lastleft, attnum, itupdesc, &isNull1);
2491  datum2 = index_getattr(firstright, attnum, itupdesc, &isNull2);
2492  att = TupleDescAttr(itupdesc, attnum - 1);
2493 
2494  if (isNull1 != isNull2)
2495  break;
2496 
2497  if (!isNull1 &&
2498  !datum_image_eq(datum1, datum2, att->attbyval, att->attlen))
2499  break;
2500 
2501  keepnatts++;
2502  }
2503 
2504  return keepnatts;
2505 }
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 1776 of file nbtutils.c.

1777 {
1778  BTScanOpaque so = (BTScanOpaque) scan->opaque;
1779  Page page;
1780  BTPageOpaque opaque;
1781  OffsetNumber minoff;
1782  OffsetNumber maxoff;
1783  int i;
1784  int numKilled = so->numKilled;
1785  bool killedsomething = false;
1786  bool droppedpin PG_USED_FOR_ASSERTS_ONLY;
1787 
1789 
1790  /*
1791  * Always reset the scan state, so we don't look for same items on other
1792  * pages.
1793  */
1794  so->numKilled = 0;
1795 
1796  if (BTScanPosIsPinned(so->currPos))
1797  {
1798  /*
1799  * We have held the pin on this page since we read the index tuples,
1800  * so all we need to do is lock it. The pin will have prevented
1801  * re-use of any TID on the page, so there is no need to check the
1802  * LSN.
1803  */
1804  droppedpin = false;
1806 
1807  page = BufferGetPage(so->currPos.buf);
1808  }
1809  else
1810  {
1811  Buffer buf;
1812 
1813  droppedpin = true;
1814  /* Attempt to re-read the buffer, getting pin and lock. */
1816 
1817  page = BufferGetPage(buf);
1818  if (BufferGetLSNAtomic(buf) == so->currPos.lsn)
1819  so->currPos.buf = buf;
1820  else
1821  {
1822  /* Modified while not pinned means hinting is not safe. */
1823  _bt_relbuf(scan->indexRelation, buf);
1824  return;
1825  }
1826  }
1827 
1828  opaque = BTPageGetOpaque(page);
1829  minoff = P_FIRSTDATAKEY(opaque);
1830  maxoff = PageGetMaxOffsetNumber(page);
1831 
1832  for (i = 0; i < numKilled; i++)
1833  {
1834  int itemIndex = so->killedItems[i];
1835  BTScanPosItem *kitem = &so->currPos.items[itemIndex];
1836  OffsetNumber offnum = kitem->indexOffset;
1837 
1838  Assert(itemIndex >= so->currPos.firstItem &&
1839  itemIndex <= so->currPos.lastItem);
1840  if (offnum < minoff)
1841  continue; /* pure paranoia */
1842  while (offnum <= maxoff)
1843  {
1844  ItemId iid = PageGetItemId(page, offnum);
1845  IndexTuple ituple = (IndexTuple) PageGetItem(page, iid);
1846  bool killtuple = false;
1847 
1848  if (BTreeTupleIsPosting(ituple))
1849  {
1850  int pi = i + 1;
1851  int nposting = BTreeTupleGetNPosting(ituple);
1852  int j;
1853 
1854  /*
1855  * We rely on the convention that heap TIDs in the scanpos
1856  * items array are stored in ascending heap TID order for a
1857  * group of TIDs that originally came from a posting list
1858  * tuple. This convention even applies during backwards
1859  * scans, where returning the TIDs in descending order might
1860  * seem more natural. This is about effectiveness, not
1861  * correctness.
1862  *
1863  * Note that the page may have been modified in almost any way
1864  * since we first read it (in the !droppedpin case), so it's
1865  * possible that this posting list tuple wasn't a posting list
1866  * tuple when we first encountered its heap TIDs.
1867  */
1868  for (j = 0; j < nposting; j++)
1869  {
1870  ItemPointer item = BTreeTupleGetPostingN(ituple, j);
1871 
1872  if (!ItemPointerEquals(item, &kitem->heapTid))
1873  break; /* out of posting list loop */
1874 
1875  /*
1876  * kitem must have matching offnum when heap TIDs match,
1877  * though only in the common case where the page can't
1878  * have been concurrently modified
1879  */
1880  Assert(kitem->indexOffset == offnum || !droppedpin);
1881 
1882  /*
1883  * Read-ahead to later kitems here.
1884  *
1885  * We rely on the assumption that not advancing kitem here
1886  * will prevent us from considering the posting list tuple
1887  * fully dead by not matching its next heap TID in next
1888  * loop iteration.
1889  *
1890  * If, on the other hand, this is the final heap TID in
1891  * the posting list tuple, then tuple gets killed
1892  * regardless (i.e. we handle the case where the last
1893  * kitem is also the last heap TID in the last index tuple
1894  * correctly -- posting tuple still gets killed).
1895  */
1896  if (pi < numKilled)
1897  kitem = &so->currPos.items[so->killedItems[pi++]];
1898  }
1899 
1900  /*
1901  * Don't bother advancing the outermost loop's int iterator to
1902  * avoid processing killed items that relate to the same
1903  * offnum/posting list tuple. This micro-optimization hardly
1904  * seems worth it. (Further iterations of the outermost loop
1905  * will fail to match on this same posting list's first heap
1906  * TID instead, so we'll advance to the next offnum/index
1907  * tuple pretty quickly.)
1908  */
1909  if (j == nposting)
1910  killtuple = true;
1911  }
1912  else if (ItemPointerEquals(&ituple->t_tid, &kitem->heapTid))
1913  killtuple = true;
1914 
1915  /*
1916  * Mark index item as dead, if it isn't already. Since this
1917  * happens while holding a buffer lock possibly in shared mode,
1918  * it's possible that multiple processes attempt to do this
1919  * simultaneously, leading to multiple full-page images being sent
1920  * to WAL (if wal_log_hints or data checksums are enabled), which
1921  * is undesirable.
1922  */
1923  if (killtuple && !ItemIdIsDead(iid))
1924  {
1925  /* found the item/all posting list items */
1926  ItemIdMarkDead(iid);
1927  killedsomething = true;
1928  break; /* out of inner search loop */
1929  }
1930  offnum = OffsetNumberNext(offnum);
1931  }
1932  }
1933 
1934  /*
1935  * Since this can be redone later if needed, mark as dirty hint.
1936  *
1937  * Whenever we mark anything LP_DEAD, we also set the page's
1938  * BTP_HAS_GARBAGE flag, which is likewise just a hint. (Note that we
1939  * only rely on the page-level flag in !heapkeyspace indexes.)
1940  */
1941  if (killedsomething)
1942  {
1943  opaque->btpo_flags |= BTP_HAS_GARBAGE;
1944  MarkBufferDirtyHint(so->currPos.buf, true);
1945  }
1946 
1947  _bt_unlockbuf(scan->indexRelation, so->currPos.buf);
1948 }
int Buffer
Definition: buf.h:23
XLogRecPtr BufferGetLSNAtomic(Buffer buffer)
Definition: bufmgr.c:3638
void MarkBufferDirtyHint(Buffer buffer, bool buffer_std)
Definition: bufmgr.c:4624
static Page BufferGetPage(Buffer buffer)
Definition: bufmgr.h:350
Pointer Page
Definition: bufpage.h:78
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:169
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:1023
Buffer _bt_getbuf(Relation rel, BlockNumber blkno, int access)
Definition: nbtpage.c:845
void _bt_unlockbuf(Relation rel, Buffer buf)
Definition: nbtpage.c:1070
void _bt_lockbuf(Relation rel, Buffer buf, int access)
Definition: nbtpage.c:1039
#define BTScanPosIsPinned(scanpos)
Definition: nbtree.h:990
static uint16 BTreeTupleGetNPosting(IndexTuple posting)
Definition: nbtree.h:518
#define BTP_HAS_GARBAGE
Definition: nbtree.h:82
#define BTScanPosIsValid(scanpos)
Definition: nbtree.h:1007
static ItemPointer BTreeTupleGetPostingN(IndexTuple posting, int n)
Definition: nbtree.h:544
#define BT_READ
Definition: nbtree.h:719
#define OffsetNumberNext(offsetNumber)
Definition: off.h:52
uint16 OffsetNumber
Definition: off.h:24
static char * buf
Definition: pg_test_fsync.c:73
BTScanPosData currPos
Definition: nbtree.h:1072
int * killedItems
Definition: nbtree.h:1051
Buffer buf
Definition: nbtree.h:953
BlockNumber currPage
Definition: nbtree.h:956
int firstItem
Definition: nbtree.h:981
BTScanPosItem items[MaxTIDsPerBTreePage]
Definition: nbtree.h:985
XLogRecPtr lsn
Definition: nbtree.h:955
ItemPointerData heapTid
Definition: nbtree.h:946
OffsetNumber indexOffset
Definition: nbtree.h:947

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, 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 611 of file nbtutils.c.

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

References BTScanOpaqueData::arrayKeys, BTArrayKeyInfo::cur_elem, for(), 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 1311 of file nbtutils.c.

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

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,
IndexTuple  itup 
)

Definition at line 81 of file nbtutils.c.

82 {
84  ScanKey skey;
85  TupleDesc itupdesc;
86  int indnkeyatts;
87  int16 *indoption;
88  int tupnatts;
89  int i;
90 
91  itupdesc = RelationGetDescr(rel);
92  indnkeyatts = IndexRelationGetNumberOfKeyAttributes(rel);
93  indoption = rel->rd_indoption;
94  tupnatts = itup ? BTreeTupleGetNAtts(itup, rel) : 0;
95 
97 
98  /*
99  * We'll execute search using scan key constructed on key columns.
100  * Truncated attributes and non-key attributes are omitted from the final
101  * scan key.
102  */
103  key = palloc(offsetof(BTScanInsertData, scankeys) +
104  sizeof(ScanKeyData) * indnkeyatts);
105  if (itup)
106  _bt_metaversion(rel, &key->heapkeyspace, &key->allequalimage);
107  else
108  {
109  /* Utility statement callers can set these fields themselves */
110  key->heapkeyspace = true;
111  key->allequalimage = false;
112  }
113  key->anynullkeys = false; /* initial assumption */
114  key->nextkey = false; /* usual case, required by btinsert */
115  key->backward = false; /* usual case, required by btinsert */
116  key->keysz = Min(indnkeyatts, tupnatts);
117  key->scantid = key->heapkeyspace && itup ?
118  BTreeTupleGetHeapTID(itup) : NULL;
119  skey = key->scankeys;
120  for (i = 0; i < indnkeyatts; i++)
121  {
122  FmgrInfo *procinfo;
123  Datum arg;
124  bool null;
125  int flags;
126 
127  /*
128  * We can use the cached (default) support procs since no cross-type
129  * comparison can be needed.
130  */
131  procinfo = index_getprocinfo(rel, i + 1, BTORDER_PROC);
132 
133  /*
134  * Key arguments built from truncated attributes (or when caller
135  * provides no tuple) are defensively represented as NULL values. They
136  * should never be used.
137  */
138  if (i < tupnatts)
139  arg = index_getattr(itup, i + 1, itupdesc, &null);
140  else
141  {
142  arg = (Datum) 0;
143  null = true;
144  }
145  flags = (null ? SK_ISNULL : 0) | (indoption[i] << SK_BT_INDOPTION_SHIFT);
147  flags,
148  (AttrNumber) (i + 1),
150  InvalidOid,
151  rel->rd_indcollation[i],
152  procinfo,
153  arg);
154  /* Record if any key attribute is NULL (or truncated) */
155  if (null)
156  key->anynullkeys = true;
157  }
158 
159  /*
160  * In NULLS NOT DISTINCT mode, we pretend that there are no null keys, so
161  * that full uniqueness check is done.
162  */
163  if (rel->rd_index->indnullsnotdistinct)
164  key->anynullkeys = false;
165 
166  return key;
167 }
int16 AttrNumber
Definition: attnum.h:21
#define Min(x, y)
Definition: c.h:991
FmgrInfo * index_getprocinfo(Relation irel, AttrNumber attnum, uint16 procnum)
Definition: indexam.c:863
void * palloc(Size size)
Definition: mcxt.c:1304
void _bt_metaversion(Relation rel, bool *heapkeyspace, bool *allequalimage)
Definition: nbtpage.c:739
#define BTORDER_PROC
Definition: nbtree.h:707
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:211
Form_pg_index rd_index
Definition: rel.h:192

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 201 of file nbtutils.c.

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

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

631 {
632  BTScanOpaque so = (BTScanOpaque) scan->opaque;
633  bool changed = false;
634  int i;
635 
636  /* Restore each array key to its position when the mark was set */
637  for (i = 0; i < so->numArrayKeys; i++)
638  {
639  BTArrayKeyInfo *curArrayKey = &so->arrayKeys[i];
640  ScanKey skey = &so->arrayKeyData[curArrayKey->scan_key];
641  int mark_elem = curArrayKey->mark_elem;
642 
643  if (curArrayKey->cur_elem != mark_elem)
644  {
645  curArrayKey->cur_elem = mark_elem;
646  skey->sk_argument = curArrayKey->elem_values[mark_elem];
647  changed = true;
648  }
649  }
650 
651  /*
652  * If we changed any keys, we must redo _bt_preprocess_keys. That might
653  * sound like overkill, but in cases with multiple keys per index column
654  * it seems necessary to do the full set of pushups.
655  *
656  * Also do this whenever the scan's set of array keys "wrapped around" at
657  * the end of the last primitive index scan. There won't have been a call
658  * to _bt_preprocess_keys from some other place following wrap around, so
659  * we do it for ourselves.
660  */
661  if (changed || !so->arraysStarted)
662  {
663  _bt_preprocess_keys(scan);
664  /* The mark should have been set on a consistent set of keys... */
665  Assert(so->qual_ok);
666  }
667 }
void _bt_preprocess_keys(IndexScanDesc scan)
Definition: nbtutils.c:755

References _bt_preprocess_keys(), BTScanOpaqueData::arrayKeyData, BTScanOpaqueData::arrayKeys, BTScanOpaqueData::arraysStarted, Assert(), BTArrayKeyInfo::cur_elem, BTArrayKeyInfo::elem_values, for(), 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 440 of file nbtutils.c.

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

517 {
518  BTScanOpaque so = (BTScanOpaque) scan->opaque;
519  int i;
520 
521  for (i = 0; i < so->numArrayKeys; i++)
522  {
523  BTArrayKeyInfo *curArrayKey = &so->arrayKeys[i];
524  ScanKey skey = &so->arrayKeyData[curArrayKey->scan_key];
525 
526  Assert(curArrayKey->num_elems > 0);
527  if (ScanDirectionIsBackward(dir))
528  curArrayKey->cur_elem = curArrayKey->num_elems - 1;
529  else
530  curArrayKey->cur_elem = 0;
531  skey->sk_argument = curArrayKey->elem_values[curArrayKey->cur_elem];
532  }
533 
534  so->arraysStarted = true;
535 }

References BTScanOpaqueData::arrayKeyData, BTScanOpaqueData::arrayKeys, BTScanOpaqueData::arraysStarted, Assert(), BTArrayKeyInfo::cur_elem, BTArrayKeyInfo::elem_values, for(), 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 2027 of file nbtutils.c.

2028 {
2029  BTCycleId result;
2030  int i;
2031  BTOneVacInfo *vac;
2032 
2033  LWLockAcquire(BtreeVacuumLock, LW_EXCLUSIVE);
2034 
2035  /*
2036  * Assign the next cycle ID, being careful to avoid zero as well as the
2037  * reserved high values.
2038  */
2039  result = ++(btvacinfo->cycle_ctr);
2040  if (result == 0 || result > MAX_BT_CYCLE_ID)
2041  result = btvacinfo->cycle_ctr = 1;
2042 
2043  /* Let's just make sure there's no entry already for this index */
2044  for (i = 0; i < btvacinfo->num_vacuums; i++)
2045  {
2046  vac = &btvacinfo->vacuums[i];
2047  if (vac->relid.relId == rel->rd_lockInfo.lockRelId.relId &&
2048  vac->relid.dbId == rel->rd_lockInfo.lockRelId.dbId)
2049  {
2050  /*
2051  * Unlike most places in the backend, we have to explicitly
2052  * release our LWLock before throwing an error. This is because
2053  * we expect _bt_end_vacuum() to be called before transaction
2054  * abort cleanup can run to release LWLocks.
2055  */
2056  LWLockRelease(BtreeVacuumLock);
2057  elog(ERROR, "multiple active vacuums for index \"%s\"",
2059  }
2060  }
2061 
2062  /* OK, add an entry */
2064  {
2065  LWLockRelease(BtreeVacuumLock);
2066  elog(ERROR, "out of btvacinfo slots");
2067  }
2069  vac->relid = rel->rd_lockInfo.lockRelId;
2070  vac->cycleid = result;
2072 
2073  LWLockRelease(BtreeVacuumLock);
2074  return result;
2075 }
#define MAX_BT_CYCLE_ID
Definition: nbtree.h:93
uint16 BTCycleId
Definition: nbtree.h:29
BTCycleId cycleid
Definition: nbtutils.c:1969
BTCycleId cycle_ctr
Definition: nbtutils.c:1974
int max_vacuums
Definition: nbtutils.c:1976

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 2256 of file nbtutils.c.

2258 {
2259  TupleDesc itupdesc = RelationGetDescr(rel);
2261  int keepnatts;
2262  IndexTuple pivot;
2263  IndexTuple tidpivot;
2264  ItemPointer pivotheaptid;
2265  Size newsize;
2266 
2267  /*
2268  * We should only ever truncate non-pivot tuples from leaf pages. It's
2269  * never okay to truncate when splitting an internal page.
2270  */
2271  Assert(!BTreeTupleIsPivot(lastleft) && !BTreeTupleIsPivot(firstright));
2272 
2273  /* Determine how many attributes must be kept in truncated tuple */
2274  keepnatts = _bt_keep_natts(rel, lastleft, firstright, itup_key);
2275 
2276 #ifdef DEBUG_NO_TRUNCATE
2277  /* Force truncation to be ineffective for testing purposes */
2278  keepnatts = nkeyatts + 1;
2279 #endif
2280 
2281  pivot = index_truncate_tuple(itupdesc, firstright,
2282  Min(keepnatts, nkeyatts));
2283 
2284  if (BTreeTupleIsPosting(pivot))
2285  {
2286  /*
2287  * index_truncate_tuple() just returns a straight copy of firstright
2288  * when it has no attributes to truncate. When that happens, we may
2289  * need to truncate away a posting list here instead.
2290  */
2291  Assert(keepnatts == nkeyatts || keepnatts == nkeyatts + 1);
2292  Assert(IndexRelationGetNumberOfAttributes(rel) == nkeyatts);
2293  pivot->t_info &= ~INDEX_SIZE_MASK;
2294  pivot->t_info |= MAXALIGN(BTreeTupleGetPostingOffset(firstright));
2295  }
2296 
2297  /*
2298  * If there is a distinguishing key attribute within pivot tuple, we're
2299  * done
2300  */
2301  if (keepnatts <= nkeyatts)
2302  {
2303  BTreeTupleSetNAtts(pivot, keepnatts, false);
2304  return pivot;
2305  }
2306 
2307  /*
2308  * We have to store a heap TID in the new pivot tuple, since no non-TID
2309  * key attribute value in firstright distinguishes the right side of the
2310  * split from the left side. nbtree conceptualizes this case as an
2311  * inability to truncate away any key attributes, since heap TID is
2312  * treated as just another key attribute (despite lacking a pg_attribute
2313  * entry).
2314  *
2315  * Use enlarged space that holds a copy of pivot. We need the extra space
2316  * to store a heap TID at the end (using the special pivot tuple
2317  * representation). Note that the original pivot already has firstright's
2318  * possible posting list/non-key attribute values removed at this point.
2319  */
2320  newsize = MAXALIGN(IndexTupleSize(pivot)) + MAXALIGN(sizeof(ItemPointerData));
2321  tidpivot = palloc0(newsize);
2322  memcpy(tidpivot, pivot, MAXALIGN(IndexTupleSize(pivot)));
2323  /* Cannot leak memory here */
2324  pfree(pivot);
2325 
2326  /*
2327  * Store all of firstright's key attribute values plus a tiebreaker heap
2328  * TID value in enlarged pivot tuple
2329  */
2330  tidpivot->t_info &= ~INDEX_SIZE_MASK;
2331  tidpivot->t_info |= newsize;
2332  BTreeTupleSetNAtts(tidpivot, nkeyatts, true);
2333  pivotheaptid = BTreeTupleGetHeapTID(tidpivot);
2334 
2335  /*
2336  * Lehman & Yao use lastleft as the leaf high key in all cases, but don't
2337  * consider suffix truncation. It seems like a good idea to follow that
2338  * example in cases where no truncation takes place -- use lastleft's heap
2339  * TID. (This is also the closest value to negative infinity that's
2340  * legally usable.)
2341  */
2342  ItemPointerCopy(BTreeTupleGetMaxHeapTID(lastleft), pivotheaptid);
2343 
2344  /*
2345  * We're done. Assert() that heap TID invariants hold before returning.
2346  *
2347  * Lehman and Yao require that the downlink to the right page, which is to
2348  * be inserted into the parent page in the second phase of a page split be
2349  * a strict lower bound on items on the right page, and a non-strict upper
2350  * bound for items on the left page. Assert that heap TIDs follow these
2351  * invariants, since a heap TID value is apparently needed as a
2352  * tiebreaker.
2353  */
2354 #ifndef DEBUG_NO_TRUNCATE
2356  BTreeTupleGetHeapTID(firstright)) < 0);
2357  Assert(ItemPointerCompare(pivotheaptid,
2358  BTreeTupleGetHeapTID(lastleft)) >= 0);
2359  Assert(ItemPointerCompare(pivotheaptid,
2360  BTreeTupleGetHeapTID(firstright)) < 0);
2361 #else
2362 
2363  /*
2364  * Those invariants aren't guaranteed to hold for lastleft + firstright
2365  * heap TID attribute values when they're considered here only because
2366  * DEBUG_NO_TRUNCATE is defined (a heap TID is probably not actually
2367  * needed as a tiebreaker). DEBUG_NO_TRUNCATE must therefore use a heap
2368  * TID value that always works as a strict lower bound for items to the
2369  * right. In particular, it must avoid using firstright's leading key
2370  * attribute values along with lastleft's heap TID value when lastleft's
2371  * TID happens to be greater than firstright's TID.
2372  */
2373  ItemPointerCopy(BTreeTupleGetHeapTID(firstright), pivotheaptid);
2374 
2375  /*
2376  * Pivot heap TID should never be fully equal to firstright. Note that
2377  * the pivot heap TID will still end up equal to lastleft's heap TID when
2378  * that's the only usable value.
2379  */
2380  ItemPointerSetOffsetNumber(pivotheaptid,
2382  Assert(ItemPointerCompare(pivotheaptid,
2383  BTreeTupleGetHeapTID(firstright)) < 0);
2384 #endif
2385 
2386  return tidpivot;
2387 }
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:529
static ItemPointer BTreeTupleGetMaxHeapTID(IndexTuple itup)
Definition: nbtree.h:664
static void BTreeTupleSetNAtts(IndexTuple itup, uint16 nkeyatts, bool heaptid)
Definition: nbtree.h:595
static int _bt_keep_natts(Relation rel, IndexTuple lastleft, IndexTuple firstright, BTScanInsert itup_key)
Definition: nbtutils.c:2401
#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 1993 of file nbtutils.c.

1994 {
1995  BTCycleId result = 0;
1996  int i;
1997 
1998  /* Share lock is enough since this is a read-only operation */
1999  LWLockAcquire(BtreeVacuumLock, LW_SHARED);
2000 
2001  for (i = 0; i < btvacinfo->num_vacuums; i++)
2002  {
2003  BTOneVacInfo *vac = &btvacinfo->vacuums[i];
2004 
2005  if (vac->relid.relId == rel->rd_lockInfo.lockRelId.relId &&
2006  vac->relid.dbId == rel->rd_lockInfo.lockRelId.dbId)
2007  {
2008  result = vac->cycleid;
2009  break;
2010  }
2011  }
2012 
2013  LWLockRelease(BtreeVacuumLock);
2014  return result;
2015 }
@ LW_SHARED
Definition: lwlock.h:115

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 2208 of file nbtutils.c.

2209 {
2210  switch (phasenum)
2211  {
2213  return "initializing";
2215  return "scanning table";
2217  return "sorting live tuples";
2219  return "sorting dead tuples";
2221  return "loading tuples in tree";
2222  default:
2223  return NULL;
2224  }
2225 }
#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:106

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 2162 of file nbtutils.c.

2163 {
2164  static const relopt_parse_elt tab[] = {
2165  {"fillfactor", RELOPT_TYPE_INT, offsetof(BTOptions, fillfactor)},
2166  {"vacuum_cleanup_index_scale_factor", RELOPT_TYPE_REAL,
2167  offsetof(BTOptions, vacuum_cleanup_index_scale_factor)},
2168  {"deduplicate_items", RELOPT_TYPE_BOOL,
2169  offsetof(BTOptions, deduplicate_items)}
2170  };
2171 
2172  return (bytea *) build_reloptions(reloptions, validate,
2174  sizeof(BTOptions),
2175  tab, lengthof(tab));
2176 }
#define lengthof(array)
Definition: c.h:775
int fillfactor
Definition: pgbench.c:187
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:1908
@ 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:674

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 2185 of file nbtutils.c.

2188 {
2189  switch (prop)
2190  {
2191  case AMPROP_RETURNABLE:
2192  /* answer only for columns, not AM or whole index */
2193  if (attno == 0)
2194  return false;
2195  /* otherwise, btree can always return data */
2196  *res = true;
2197  return true;
2198 
2199  default:
2200  return false; /* punt to generic code */
2201  }
2202 }
@ AMPROP_RETURNABLE
Definition: amapi.h:43

References AMPROP_RETURNABLE, and res.

Referenced by bthandler().

◆ BTreeShmemInit()

void BTreeShmemInit ( void  )

Definition at line 2134 of file nbtutils.c.

2135 {
2136  bool found;
2137 
2138  btvacinfo = (BTVacInfo *) ShmemInitStruct("BTree Vacuum State",
2139  BTreeShmemSize(),
2140  &found);
2141 
2142  if (!IsUnderPostmaster)
2143  {
2144  /* Initialize shared memory area */
2145  Assert(!found);
2146 
2147  /*
2148  * It doesn't really matter what the cycle counter starts at, but
2149  * having it always start the same doesn't seem good. Seed with
2150  * low-order bits of time() instead.
2151  */
2152  btvacinfo->cycle_ctr = (BTCycleId) time(NULL);
2153 
2154  btvacinfo->num_vacuums = 0;
2156  }
2157  else
2158  Assert(found);
2159 }
bool IsUnderPostmaster
Definition: globals.c:117
int MaxBackends
Definition: globals.c:143
Size BTreeShmemSize(void)
Definition: nbtutils.c:2121
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:387

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

Referenced by CreateOrAttachShmemStructs().

◆ BTreeShmemSize()

Size BTreeShmemSize ( void  )

Definition at line 2121 of file nbtutils.c.

2122 {
2123  Size size;
2124 
2125  size = offsetof(BTVacInfo, vacuums);
2127  return size;
2128 }
Size add_size(Size s1, Size s2)
Definition: shmem.c:493
Size mul_size(Size s1, Size s2)
Definition: shmem.c:510
static pg_noinline void Size size
Definition: slab.c:607

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

Referenced by BTreeShmemInit(), and CalculateShmemSize().

Variable Documentation

◆ btvacinfo

BTVacInfo* btvacinfo
static

Definition at line 1980 of file nbtutils.c.

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