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

Go to the source code of this file.

Data Structures

struct  BTOneVacInfo
 
struct  BTVacInfo
 

Macros

#define LOOK_AHEAD_REQUIRED_RECHECKS   3
 
#define LOOK_AHEAD_DEFAULT_DISTANCE   5
 
#define NSKIPADVANCES_THRESHOLD   3
 

Typedefs

typedef struct BTOneVacInfo BTOneVacInfo
 
typedef struct BTVacInfo BTVacInfo
 

Functions

static int32 _bt_compare_array_skey (FmgrInfo *orderproc, Datum tupdatum, bool tupnull, Datum arrdatum, ScanKey cur)
 
static void _bt_binsrch_skiparray_skey (bool cur_elem_trig, ScanDirection dir, Datum tupdatum, bool tupnull, BTArrayKeyInfo *array, ScanKey cur, int32 *set_elem_result)
 
static void _bt_skiparray_set_element (Relation rel, ScanKey skey, BTArrayKeyInfo *array, int32 set_elem_result, Datum tupdatum, bool tupnull)
 
static void _bt_skiparray_set_isnull (Relation rel, ScanKey skey, BTArrayKeyInfo *array)
 
static void _bt_array_set_low_or_high (Relation rel, ScanKey skey, BTArrayKeyInfo *array, bool low_not_high)
 
static bool _bt_array_decrement (Relation rel, ScanKey skey, BTArrayKeyInfo *array)
 
static bool _bt_array_increment (Relation rel, ScanKey skey, BTArrayKeyInfo *array)
 
static bool _bt_advance_array_keys_increment (IndexScanDesc scan, ScanDirection dir, bool *skip_array_set)
 
static void _bt_rewind_nonrequired_arrays (IndexScanDesc scan, ScanDirection dir)
 
static bool _bt_tuple_before_array_skeys (IndexScanDesc scan, ScanDirection dir, IndexTuple tuple, TupleDesc tupdesc, int tupnatts, bool readpagetup, int sktrig, bool *scanBehind)
 
static bool _bt_advance_array_keys (IndexScanDesc scan, BTReadPageState *pstate, IndexTuple tuple, int tupnatts, TupleDesc tupdesc, int sktrig, bool sktrig_required)
 
static bool _bt_oppodir_checkkeys (IndexScanDesc scan, ScanDirection dir, IndexTuple finaltup)
 
static bool _bt_check_compare (IndexScanDesc scan, ScanDirection dir, IndexTuple tuple, int tupnatts, TupleDesc tupdesc, bool advancenonrequired, bool forcenonrequired, bool *continuescan, int *ikey)
 
static bool _bt_check_rowcompare (ScanKey skey, IndexTuple tuple, int tupnatts, TupleDesc tupdesc, ScanDirection dir, bool forcenonrequired, bool *continuescan)
 
static void _bt_checkkeys_look_ahead (IndexScanDesc scan, BTReadPageState *pstate, int tupnatts, TupleDesc tupdesc)
 
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)
 
int _bt_binsrch_array_skey (FmgrInfo *orderproc, bool cur_elem_trig, ScanDirection dir, Datum tupdatum, bool tupnull, BTArrayKeyInfo *array, ScanKey cur, int32 *set_elem_result)
 
void _bt_start_array_keys (IndexScanDesc scan, ScanDirection dir)
 
bool _bt_start_prim_scan (IndexScanDesc scan, ScanDirection dir)
 
bool _bt_checkkeys (IndexScanDesc scan, BTReadPageState *pstate, bool arrayKeys, IndexTuple tuple, int tupnatts)
 
bool _bt_scanbehind_checkkeys (IndexScanDesc scan, ScanDirection dir, IndexTuple finaltup)
 
void _bt_set_startikey (IndexScanDesc scan, BTReadPageState *pstate)
 
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
 

Macro Definition Documentation

◆ LOOK_AHEAD_DEFAULT_DISTANCE

#define LOOK_AHEAD_DEFAULT_DISTANCE   5

Definition at line 28 of file nbtutils.c.

◆ LOOK_AHEAD_REQUIRED_RECHECKS

#define LOOK_AHEAD_REQUIRED_RECHECKS   3

Definition at line 27 of file nbtutils.c.

◆ NSKIPADVANCES_THRESHOLD

#define NSKIPADVANCES_THRESHOLD   3

Definition at line 29 of file nbtutils.c.

Typedef Documentation

◆ BTOneVacInfo

typedef struct BTOneVacInfo BTOneVacInfo

◆ BTVacInfo

typedef struct BTVacInfo BTVacInfo

Function Documentation

◆ _bt_advance_array_keys()

static bool _bt_advance_array_keys ( IndexScanDesc  scan,
BTReadPageState pstate,
IndexTuple  tuple,
int  tupnatts,
TupleDesc  tupdesc,
int  sktrig,
bool  sktrig_required 
)
static

Definition at line 1460 of file nbtutils.c.

1463{
1464 BTScanOpaque so = (BTScanOpaque) scan->opaque;
1465 Relation rel = scan->indexRelation;
1466 ScanDirection dir = so->currPos.dir;
1467 int arrayidx = 0;
1468 bool beyond_end_advance = false,
1469 skip_array_advanced = false,
1470 has_required_opposite_direction_only = false,
1471 all_required_satisfied = true,
1472 all_satisfied = true;
1473
1474 Assert(!so->needPrimScan && !so->scanBehind && !so->oppositeDirCheck);
1475 Assert(_bt_verify_keys_with_arraykeys(scan));
1476
1477 if (sktrig_required)
1478 {
1479 /*
1480 * Precondition array state assertion
1481 */
1482 Assert(!_bt_tuple_before_array_skeys(scan, dir, tuple, tupdesc,
1483 tupnatts, false, 0, NULL));
1484
1485 /*
1486 * Once we return we'll have a new set of required array keys, so
1487 * reset state used by "look ahead" optimization
1488 */
1489 pstate->rechecks = 0;
1490 pstate->targetdistance = 0;
1491 }
1492 else if (sktrig < so->numberOfKeys - 1 &&
1493 !(so->keyData[so->numberOfKeys - 1].sk_flags & SK_SEARCHARRAY))
1494 {
1495 int least_sign_ikey = so->numberOfKeys - 1;
1496 bool continuescan;
1497
1498 /*
1499 * Optimization: perform a precheck of the least significant key
1500 * during !sktrig_required calls when it isn't already our sktrig
1501 * (provided the precheck key is not itself an array).
1502 *
1503 * When the precheck works out we'll avoid an expensive binary search
1504 * of sktrig's array (plus any other arrays before least_sign_ikey).
1505 */
1506 Assert(so->keyData[sktrig].sk_flags & SK_SEARCHARRAY);
1507 if (!_bt_check_compare(scan, dir, tuple, tupnatts, tupdesc, false,
1508 false, &continuescan,
1509 &least_sign_ikey))
1510 return false;
1511 }
1512
1513 for (int ikey = 0; ikey < so->numberOfKeys; ikey++)
1514 {
1515 ScanKey cur = so->keyData + ikey;
1516 BTArrayKeyInfo *array = NULL;
1517 Datum tupdatum;
1518 bool required = false,
1519 required_opposite_direction_only = false,
1520 tupnull;
1521 int32 result;
1522 int set_elem = 0;
1523
1524 if (cur->sk_strategy == BTEqualStrategyNumber)
1525 {
1526 /* Manage array state */
1527 if (cur->sk_flags & SK_SEARCHARRAY)
1528 {
1529 array = &so->arrayKeys[arrayidx++];
1530 Assert(array->scan_key == ikey);
1531 }
1532 }
1533 else
1534 {
1535 /*
1536 * Are any inequalities required in the opposite direction only
1537 * present here?
1538 */
1539 if (((ScanDirectionIsForward(dir) &&
1540 (cur->sk_flags & (SK_BT_REQBKWD))) ||
1542 (cur->sk_flags & (SK_BT_REQFWD)))))
1543 has_required_opposite_direction_only =
1544 required_opposite_direction_only = true;
1545 }
1546
1547 /* Optimization: skip over known-satisfied scan keys */
1548 if (ikey < sktrig)
1549 continue;
1550
1551 if (cur->sk_flags & (SK_BT_REQFWD | SK_BT_REQBKWD))
1552 {
1553 required = true;
1554
1555 if (cur->sk_attno > tupnatts)
1556 {
1557 /* Set this just like _bt_tuple_before_array_skeys */
1558 Assert(sktrig < ikey);
1559 so->scanBehind = true;
1560 }
1561 }
1562
1563 /*
1564 * Handle a required non-array scan key that the initial call to
1565 * _bt_check_compare indicated triggered array advancement, if any.
1566 *
1567 * The non-array scan key's strategy will be <, <=, or = during a
1568 * forwards scan (or any one of =, >=, or > during a backwards scan).
1569 * It follows that the corresponding tuple attribute's value must now
1570 * be either > or >= the scan key value (for backwards scans it must
1571 * be either < or <= that value).
1572 *
1573 * If this is a required equality strategy scan key, this is just an
1574 * optimization; _bt_tuple_before_array_skeys already confirmed that
1575 * this scan key places us ahead of caller's tuple. There's no need
1576 * to repeat that work now. (The same underlying principle also gets
1577 * applied by the cur_elem_trig optimization used to speed up searches
1578 * for the next array element.)
1579 *
1580 * If this is a required inequality strategy scan key, we _must_ rely
1581 * on _bt_check_compare like this; we aren't capable of directly
1582 * evaluating required inequality strategy scan keys here, on our own.
1583 */
1584 if (ikey == sktrig && !array)
1585 {
1586 Assert(sktrig_required && required && all_required_satisfied);
1587
1588 /* Use "beyond end" advancement. See below for an explanation. */
1589 beyond_end_advance = true;
1590 all_satisfied = all_required_satisfied = false;
1591
1592 continue;
1593 }
1594
1595 /*
1596 * Nothing more for us to do with an inequality strategy scan key that
1597 * wasn't the one that _bt_check_compare stopped on, though.
1598 *
1599 * Note: if our later call to _bt_check_compare (to recheck caller's
1600 * tuple) sets continuescan=false due to finding this same inequality
1601 * unsatisfied (possible when it's required in the scan direction),
1602 * we'll deal with it via a recursive "second pass" call.
1603 */
1604 else if (cur->sk_strategy != BTEqualStrategyNumber)
1605 continue;
1606
1607 /*
1608 * Nothing for us to do with an equality strategy scan key that isn't
1609 * marked required, either -- unless it's a non-required array
1610 */
1611 else if (!required && !array)
1612 continue;
1613
1614 /*
1615 * Here we perform steps for all array scan keys after a required
1616 * array scan key whose binary search triggered "beyond end of array
1617 * element" array advancement due to encountering a tuple attribute
1618 * value > the closest matching array key (or < for backwards scans).
1619 */
1620 if (beyond_end_advance)
1621 {
1622 if (array)
1623 _bt_array_set_low_or_high(rel, cur, array,
1625
1626 continue;
1627 }
1628
1629 /*
1630 * Here we perform steps for all array scan keys after a required
1631 * array scan key whose tuple attribute was < the closest matching
1632 * array key when we dealt with it (or > for backwards scans).
1633 *
1634 * This earlier required array key already puts us ahead of caller's
1635 * tuple in the key space (for the current scan direction). We must
1636 * make sure that subsequent lower-order array keys do not put us too
1637 * far ahead (ahead of tuples that have yet to be seen by our caller).
1638 * For example, when a tuple "(a, b) = (42, 5)" advances the array
1639 * keys on "a" from 40 to 45, we must also set "b" to whatever the
1640 * first array element for "b" is. It would be wrong to allow "b" to
1641 * be set based on the tuple value.
1642 *
1643 * Perform the same steps with truncated high key attributes. You can
1644 * think of this as a "binary search" for the element closest to the
1645 * value -inf. Again, the arrays must never get ahead of the scan.
1646 */
1647 if (!all_required_satisfied || cur->sk_attno > tupnatts)
1648 {
1649 if (array)
1650 _bt_array_set_low_or_high(rel, cur, array,
1652
1653 continue;
1654 }
1655
1656 /*
1657 * Search in scankey's array for the corresponding tuple attribute
1658 * value from caller's tuple
1659 */
1660 tupdatum = index_getattr(tuple, cur->sk_attno, tupdesc, &tupnull);
1661
1662 if (array)
1663 {
1664 bool cur_elem_trig = (sktrig_required && ikey == sktrig);
1665
1666 /*
1667 * "Binary search" by checking if tupdatum/tupnull are within the
1668 * range of the skip array
1669 */
1670 if (array->num_elems == -1)
1671 _bt_binsrch_skiparray_skey(cur_elem_trig, dir,
1672 tupdatum, tupnull, array, cur,
1673 &result);
1674
1675 /*
1676 * Binary search for the closest match from the SAOP array
1677 */
1678 else
1679 set_elem = _bt_binsrch_array_skey(&so->orderProcs[ikey],
1680 cur_elem_trig, dir,
1681 tupdatum, tupnull, array, cur,
1682 &result);
1683 }
1684 else
1685 {
1687
1688 /*
1689 * This is a required non-array equality strategy scan key, which
1690 * we'll treat as a degenerate single element array.
1691 *
1692 * This scan key's imaginary "array" can't really advance, but it
1693 * can still roll over like any other array. (Actually, this is
1694 * no different to real single value arrays, which never advance
1695 * without rolling over -- they can never truly advance, either.)
1696 */
1697 result = _bt_compare_array_skey(&so->orderProcs[ikey],
1698 tupdatum, tupnull,
1699 cur->sk_argument, cur);
1700 }
1701
1702 /*
1703 * Consider "beyond end of array element" array advancement.
1704 *
1705 * When the tuple attribute value is > the closest matching array key
1706 * (or < in the backwards scan case), we need to ratchet this array
1707 * forward (backward) by one increment, so that caller's tuple ends up
1708 * being < final array value instead (or > final array value instead).
1709 * This process has to work for all of the arrays, not just this one:
1710 * it must "carry" to higher-order arrays when the set_elem that we
1711 * just found happens to be the final one for the scan's direction.
1712 * Incrementing (decrementing) set_elem itself isn't good enough.
1713 *
1714 * Our approach is to provisionally use set_elem as if it was an exact
1715 * match now, then set each later/less significant array to whatever
1716 * its final element is. Once outside the loop we'll then "increment
1717 * this array's set_elem" by calling _bt_advance_array_keys_increment.
1718 * That way the process rolls over to higher order arrays as needed.
1719 *
1720 * Under this scheme any required arrays only ever ratchet forwards
1721 * (or backwards), and always do so to the maximum possible extent
1722 * that we can know will be safe without seeing the scan's next tuple.
1723 * We don't need any special handling for required scan keys that lack
1724 * a real array to advance, nor for redundant scan keys that couldn't
1725 * be eliminated by _bt_preprocess_keys. It won't matter if some of
1726 * our "true" array scan keys (or even all of them) are non-required.
1727 */
1728 if (sktrig_required && required &&
1729 ((ScanDirectionIsForward(dir) && result > 0) ||
1730 (ScanDirectionIsBackward(dir) && result < 0)))
1731 beyond_end_advance = true;
1732
1733 Assert(all_required_satisfied && all_satisfied);
1734 if (result != 0)
1735 {
1736 /*
1737 * Track whether caller's tuple satisfies our new post-advancement
1738 * qual, for required scan keys, as well as for the entire set of
1739 * interesting scan keys (all required scan keys plus non-required
1740 * array scan keys are considered interesting.)
1741 */
1742 all_satisfied = false;
1743 if (sktrig_required && required)
1744 all_required_satisfied = false;
1745 else
1746 {
1747 /*
1748 * There's no need to advance the arrays using the best
1749 * available match for a non-required array. Give up now.
1750 * (Though note that sktrig_required calls still have to do
1751 * all the usual post-advancement steps, including the recheck
1752 * call to _bt_check_compare.)
1753 */
1754 break;
1755 }
1756 }
1757
1758 /* Advance array keys, even when we don't have an exact match */
1759 if (array)
1760 {
1761 if (array->num_elems == -1)
1762 {
1763 /* Skip array's new element is tupdatum (or MINVAL/MAXVAL) */
1764 _bt_skiparray_set_element(rel, cur, array, result,
1765 tupdatum, tupnull);
1766 skip_array_advanced = true;
1767 }
1768 else if (array->cur_elem != set_elem)
1769 {
1770 /* SAOP array's new element is set_elem datum */
1771 array->cur_elem = set_elem;
1772 cur->sk_argument = array->elem_values[set_elem];
1773 }
1774 }
1775 }
1776
1777 /*
1778 * Advance the array keys incrementally whenever "beyond end of array
1779 * element" array advancement happens, so that advancement will carry to
1780 * higher-order arrays (might exhaust all the scan's arrays instead, which
1781 * ends the top-level scan).
1782 */
1783 if (beyond_end_advance &&
1784 !_bt_advance_array_keys_increment(scan, dir, &skip_array_advanced))
1785 goto end_toplevel_scan;
1786
1787 Assert(_bt_verify_keys_with_arraykeys(scan));
1788
1789 /*
1790 * Maintain a page-level count of the number of times the scan's array
1791 * keys advanced in a way that affected at least one skip array
1792 */
1793 if (sktrig_required && skip_array_advanced)
1794 pstate->nskipadvances++;
1795
1796 /*
1797 * Does tuple now satisfy our new qual? Recheck with _bt_check_compare.
1798 *
1799 * Calls triggered by an unsatisfied required scan key, whose tuple now
1800 * satisfies all required scan keys, but not all nonrequired array keys,
1801 * will still require a recheck call to _bt_check_compare. They'll still
1802 * need its "second pass" handling of required inequality scan keys.
1803 * (Might have missed a still-unsatisfied required inequality scan key
1804 * that caller didn't detect as the sktrig scan key during its initial
1805 * _bt_check_compare call that used the old/original qual.)
1806 *
1807 * Calls triggered by an unsatisfied nonrequired array scan key never need
1808 * "second pass" handling of required inequalities (nor any other handling
1809 * of any required scan key). All that matters is whether caller's tuple
1810 * satisfies the new qual, so it's safe to just skip the _bt_check_compare
1811 * recheck when we've already determined that it can only return 'false'.
1812 *
1813 * Note: In practice most scan keys are marked required by preprocessing,
1814 * if necessary by generating a preceding skip array. We nevertheless
1815 * often handle array keys marked required as if they were nonrequired.
1816 * This behavior is requested by our _bt_check_compare caller, though only
1817 * when it is passed "forcenonrequired=true" by _bt_checkkeys.
1818 */
1819 if ((sktrig_required && all_required_satisfied) ||
1820 (!sktrig_required && all_satisfied))
1821 {
1822 int nsktrig = sktrig + 1;
1823 bool continuescan;
1824
1825 Assert(all_required_satisfied);
1826
1827 /* Recheck _bt_check_compare on behalf of caller */
1828 if (_bt_check_compare(scan, dir, tuple, tupnatts, tupdesc, false,
1829 !sktrig_required, &continuescan,
1830 &nsktrig) &&
1831 !so->scanBehind)
1832 {
1833 /* This tuple satisfies the new qual */
1834 Assert(all_satisfied && continuescan);
1835
1836 if (pstate)
1837 pstate->continuescan = true;
1838
1839 return true;
1840 }
1841
1842 /*
1843 * Consider "second pass" handling of required inequalities.
1844 *
1845 * It's possible that our _bt_check_compare call indicated that the
1846 * scan should end due to some unsatisfied inequality that wasn't
1847 * initially recognized as such by us. Handle this by calling
1848 * ourselves recursively, this time indicating that the trigger is the
1849 * inequality that we missed first time around (and using a set of
1850 * required array/equality keys that are now exact matches for tuple).
1851 *
1852 * We make a strong, general guarantee that every _bt_checkkeys call
1853 * here will advance the array keys to the maximum possible extent
1854 * that we can know to be safe based on caller's tuple alone. If we
1855 * didn't perform this step, then that guarantee wouldn't quite hold.
1856 */
1857 if (unlikely(!continuescan))
1858 {
1859 bool satisfied PG_USED_FOR_ASSERTS_ONLY;
1860
1861 Assert(sktrig_required);
1863
1864 /*
1865 * The tuple must use "beyond end" advancement during the
1866 * recursive call, so we cannot possibly end up back here when
1867 * recursing. We'll consume a small, fixed amount of stack space.
1868 */
1869 Assert(!beyond_end_advance);
1870
1871 /* Advance the array keys a second time using same tuple */
1872 satisfied = _bt_advance_array_keys(scan, pstate, tuple, tupnatts,
1873 tupdesc, nsktrig, true);
1874
1875 /* This tuple doesn't satisfy the inequality */
1876 Assert(!satisfied);
1877 return false;
1878 }
1879
1880 /*
1881 * Some non-required scan key (from new qual) still not satisfied.
1882 *
1883 * All scan keys required in the current scan direction must still be
1884 * satisfied, though, so we can trust all_required_satisfied below.
1885 */
1886 }
1887
1888 /*
1889 * When we were called just to deal with "advancing" non-required arrays,
1890 * this is as far as we can go (cannot stop the scan for these callers)
1891 */
1892 if (!sktrig_required)
1893 {
1894 /* Caller's tuple doesn't match any qual */
1895 return false;
1896 }
1897
1898 /*
1899 * Postcondition array state assertion (for still-unsatisfied tuples).
1900 *
1901 * By here we have established that the scan's required arrays (scan must
1902 * have at least one required array) advanced, without becoming exhausted.
1903 *
1904 * Caller's tuple is now < the newly advanced array keys (or > when this
1905 * is a backwards scan), except in the case where we only got this far due
1906 * to an unsatisfied non-required scan key. Verify that with an assert.
1907 *
1908 * Note: we don't just quit at this point when all required scan keys were
1909 * found to be satisfied because we need to consider edge-cases involving
1910 * scan keys required in the opposite direction only; those aren't tracked
1911 * by all_required_satisfied.
1912 */
1913 Assert(_bt_tuple_before_array_skeys(scan, dir, tuple, tupdesc, tupnatts,
1914 false, 0, NULL) ==
1915 !all_required_satisfied);
1916
1917 /*
1918 * We generally permit primitive index scans to continue onto the next
1919 * sibling page when the page's finaltup satisfies all required scan keys
1920 * at the point where we're between pages.
1921 *
1922 * If caller's tuple is also the page's finaltup, and we see that required
1923 * scan keys still aren't satisfied, start a new primitive index scan.
1924 */
1925 if (!all_required_satisfied && pstate->finaltup == tuple)
1926 goto new_prim_scan;
1927
1928 /*
1929 * Proactively check finaltup (don't wait until finaltup is reached by the
1930 * scan) when it might well turn out to not be satisfied later on.
1931 *
1932 * Note: if so->scanBehind hasn't already been set for finaltup by us,
1933 * it'll be set during this call to _bt_tuple_before_array_skeys. Either
1934 * way, it'll be set correctly (for the whole page) after this point.
1935 */
1936 if (!all_required_satisfied && pstate->finaltup &&
1937 _bt_tuple_before_array_skeys(scan, dir, pstate->finaltup, tupdesc,
1938 BTreeTupleGetNAtts(pstate->finaltup, rel),
1939 false, 0, &so->scanBehind))
1940 goto new_prim_scan;
1941
1942 /*
1943 * When we encounter a truncated finaltup high key attribute, we're
1944 * optimistic about the chances of its corresponding required scan key
1945 * being satisfied when we go on to recheck it against tuples from this
1946 * page's right sibling leaf page. We consider truncated attributes to be
1947 * satisfied by required scan keys, which allows the primitive index scan
1948 * to continue to the next leaf page. We must set so->scanBehind to true
1949 * to remember that the last page's finaltup had "satisfied" required scan
1950 * keys for one or more truncated attribute values (scan keys required in
1951 * _either_ scan direction).
1952 *
1953 * There is a chance that _bt_readpage (which checks so->scanBehind) will
1954 * find that even the sibling leaf page's finaltup is < the new array
1955 * keys. When that happens, our optimistic policy will have incurred a
1956 * single extra leaf page access that could have been avoided.
1957 *
1958 * A pessimistic policy would give backward scans a gratuitous advantage
1959 * over forward scans. We'd punish forward scans for applying more
1960 * accurate information from the high key, rather than just using the
1961 * final non-pivot tuple as finaltup, in the style of backward scans.
1962 * Being pessimistic would also give some scans with non-required arrays a
1963 * perverse advantage over similar scans that use required arrays instead.
1964 *
1965 * This is similar to our scan-level heuristics, below. They also set
1966 * scanBehind to speculatively continue the primscan onto the next page.
1967 */
1968 if (so->scanBehind)
1969 {
1970 /* Truncated high key -- _bt_scanbehind_checkkeys recheck scheduled */
1971 }
1972
1973 /*
1974 * Handle inequalities marked required in the opposite scan direction.
1975 * They can also signal that we should start a new primitive index scan.
1976 *
1977 * It's possible that the scan is now positioned where "matching" tuples
1978 * begin, and that caller's tuple satisfies all scan keys required in the
1979 * current scan direction. But if caller's tuple still doesn't satisfy
1980 * other scan keys that are required in the opposite scan direction only
1981 * (e.g., a required >= strategy scan key when scan direction is forward),
1982 * it's still possible that there are many leaf pages before the page that
1983 * _bt_first could skip straight to. Groveling through all those pages
1984 * will always give correct answers, but it can be very inefficient. We
1985 * must avoid needlessly scanning extra pages.
1986 *
1987 * Separately, it's possible that _bt_check_compare set continuescan=false
1988 * for a scan key that's required in the opposite direction only. This is
1989 * a special case, that happens only when _bt_check_compare sees that the
1990 * inequality encountered a NULL value. This signals the end of non-NULL
1991 * values in the current scan direction, which is reason enough to end the
1992 * (primitive) scan. If this happens at the start of a large group of
1993 * NULL values, then we shouldn't expect to be called again until after
1994 * the scan has already read indefinitely-many leaf pages full of tuples
1995 * with NULL suffix values. (_bt_first is expected to skip over the group
1996 * of NULLs by applying a similar "deduce NOT NULL" rule of its own, which
1997 * involves consing up an explicit SK_SEARCHNOTNULL key.)
1998 *
1999 * Apply a test against finaltup to detect and recover from the problem:
2000 * if even finaltup doesn't satisfy such an inequality, we just skip by
2001 * starting a new primitive index scan. When we skip, we know for sure
2002 * that all of the tuples on the current page following caller's tuple are
2003 * also before the _bt_first-wise start of tuples for our new qual. That
2004 * at least suggests many more skippable pages beyond the current page.
2005 * (when so->scanBehind and so->oppositeDirCheck are set, this'll happen
2006 * when we test the next page's finaltup/high key instead.)
2007 */
2008 else if (has_required_opposite_direction_only && pstate->finaltup &&
2009 unlikely(!_bt_oppodir_checkkeys(scan, dir, pstate->finaltup)))
2010 {
2011 /*
2012 * Make sure that any SAOP arrays that were not marked required by
2013 * preprocessing are reset to their first element for this direction
2014 */
2016 goto new_prim_scan;
2017 }
2018
2019continue_scan:
2020
2021 /*
2022 * Stick with the ongoing primitive index scan for now.
2023 *
2024 * It's possible that later tuples will also turn out to have values that
2025 * are still < the now-current array keys (or > the current array keys).
2026 * Our caller will handle this by performing what amounts to a linear
2027 * search of the page, implemented by calling _bt_check_compare and then
2028 * _bt_tuple_before_array_skeys for each tuple.
2029 *
2030 * This approach has various advantages over a binary search of the page.
2031 * Repeated binary searches of the page (one binary search for every array
2032 * advancement) won't outperform a continuous linear search. While there
2033 * are workloads that a naive linear search won't handle well, our caller
2034 * has a "look ahead" fallback mechanism to deal with that problem.
2035 */
2036 pstate->continuescan = true; /* Override _bt_check_compare */
2037 so->needPrimScan = false; /* _bt_readpage has more tuples to check */
2038
2039 if (so->scanBehind)
2040 {
2041 /*
2042 * Remember if recheck needs to call _bt_oppodir_checkkeys for next
2043 * page's finaltup (see above comments about "Handle inequalities
2044 * marked required in the opposite scan direction" for why).
2045 */
2046 so->oppositeDirCheck = has_required_opposite_direction_only;
2047
2049
2050 /*
2051 * skip by setting "look ahead" mechanism's offnum for forwards scans
2052 * (backwards scans check scanBehind flag directly instead)
2053 */
2054 if (ScanDirectionIsForward(dir))
2055 pstate->skip = pstate->maxoff + 1;
2056 }
2057
2058 /* Caller's tuple doesn't match the new qual */
2059 return false;
2060
2061new_prim_scan:
2062
2063 Assert(pstate->finaltup); /* not on rightmost/leftmost page */
2064
2065 /*
2066 * Looks like another primitive index scan is required. But consider
2067 * continuing the current primscan based on scan-level heuristics.
2068 *
2069 * Continue the ongoing primitive scan (and schedule a recheck for when
2070 * the scan arrives on the next sibling leaf page) when it has already
2071 * read at least one leaf page before the one we're reading now. This
2072 * makes primscan scheduling more efficient when scanning subsets of an
2073 * index with many distinct attribute values matching many array elements.
2074 * It encourages fewer, larger primitive scans where that makes sense.
2075 * This will in turn encourage _bt_readpage to apply the pstate.startikey
2076 * optimization more often.
2077 *
2078 * Also continue the ongoing primitive index scan when it is still on the
2079 * first page if there have been more than NSKIPADVANCES_THRESHOLD calls
2080 * here that each advanced at least one of the scan's skip arrays
2081 * (deliberately ignore advancements that only affected SAOP arrays here).
2082 * A page that cycles through this many skip array elements is quite
2083 * likely to neighbor similar pages, that we'll also need to read.
2084 *
2085 * Note: These heuristics aren't as aggressive as you might think. We're
2086 * conservative about allowing a primitive scan to step from the first
2087 * leaf page it reads to the page's sibling page (we only allow it on
2088 * first pages whose finaltup strongly suggests that it'll work out, as
2089 * well as first pages that have a large number of skip array advances).
2090 * Clearing this first page finaltup hurdle is a strong signal in itself.
2091 *
2092 * Note: The NSKIPADVANCES_THRESHOLD heuristic exists only to avoid
2093 * pathological cases. Specifically, cases where a skip scan should just
2094 * behave like a traditional full index scan, but ends up "skipping" again
2095 * and again, descending to the prior leaf page's direct sibling leaf page
2096 * each time. This misbehavior would otherwise be possible during scans
2097 * that never quite manage to "clear the first page finaltup hurdle".
2098 */
2099 if (!pstate->firstpage || pstate->nskipadvances > NSKIPADVANCES_THRESHOLD)
2100 {
2101 /* Schedule a recheck once on the next (or previous) page */
2102 so->scanBehind = true;
2103
2104 /* Continue the current primitive scan after all */
2105 goto continue_scan;
2106 }
2107
2108 /*
2109 * End this primitive index scan, but schedule another.
2110 *
2111 * Note: We make a soft assumption that the current scan direction will
2112 * also be used within _bt_next, when it is asked to step off this page.
2113 * It is up to _bt_next to cancel this scheduled primitive index scan
2114 * whenever it steps to a page in the direction opposite currPos.dir.
2115 */
2116 pstate->continuescan = false; /* Tell _bt_readpage we're done... */
2117 so->needPrimScan = true; /* ...but call _bt_first again */
2118
2119 if (scan->parallel_scan)
2121
2122 /* Caller's tuple doesn't match the new qual */
2123 return false;
2124
2125end_toplevel_scan:
2126
2127 /*
2128 * End the current primitive index scan, but don't schedule another.
2129 *
2130 * This ends the entire top-level scan in the current scan direction.
2131 *
2132 * Note: The scan's arrays (including any non-required arrays) are now in
2133 * their final positions for the current scan direction. If the scan
2134 * direction happens to change, then the arrays will already be in their
2135 * first positions for what will then be the current scan direction.
2136 */
2137 pstate->continuescan = false; /* Tell _bt_readpage we're done... */
2138 so->needPrimScan = false; /* ...and don't call _bt_first again */
2139
2140 /* Caller's tuple doesn't match any qual */
2141 return false;
2142}
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:224
int32_t int32
Definition: c.h:498
#define unlikely(x)
Definition: c.h:347
struct cursor * cur
Definition: ecpg.c:29
Assert(PointerIsAligned(start, uint64))
static Datum index_getattr(IndexTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Definition: itup.h:131
void _bt_parallel_primscan_schedule(IndexScanDesc scan, BlockNumber curr_page)
Definition: nbtree.c:999
#define SK_BT_REQBKWD
Definition: nbtree.h:1135
#define SK_BT_REQFWD
Definition: nbtree.h:1134
#define BTreeTupleGetNAtts(itup, rel)
Definition: nbtree.h:578
BTScanOpaqueData * BTScanOpaque
Definition: nbtree.h:1096
static void _bt_rewind_nonrequired_arrays(IndexScanDesc scan, ScanDirection dir)
Definition: nbtutils.c:1076
static void _bt_binsrch_skiparray_skey(bool cur_elem_trig, ScanDirection dir, Datum tupdatum, bool tupnull, BTArrayKeyInfo *array, ScanKey cur, int32 *set_elem_result)
Definition: nbtutils.c:443
static void _bt_array_set_low_or_high(Relation rel, ScanKey skey, BTArrayKeyInfo *array, bool low_not_high)
Definition: nbtutils.c:639
static void _bt_skiparray_set_element(Relation rel, ScanKey skey, BTArrayKeyInfo *array, int32 set_elem_result, Datum tupdatum, bool tupnull)
Definition: nbtutils.c:550
#define NSKIPADVANCES_THRESHOLD
Definition: nbtutils.c:29
int _bt_binsrch_array_skey(FmgrInfo *orderproc, bool cur_elem_trig, ScanDirection dir, Datum tupdatum, bool tupnull, BTArrayKeyInfo *array, ScanKey cur, int32 *set_elem_result)
Definition: nbtutils.c:287
static bool _bt_advance_array_keys(IndexScanDesc scan, BTReadPageState *pstate, IndexTuple tuple, int tupnatts, TupleDesc tupdesc, int sktrig, bool sktrig_required)
Definition: nbtutils.c:1460
static bool _bt_oppodir_checkkeys(IndexScanDesc scan, ScanDirection dir, IndexTuple finaltup)
Definition: nbtutils.c:2428
static bool _bt_check_compare(IndexScanDesc scan, ScanDirection dir, IndexTuple tuple, int tupnatts, TupleDesc tupdesc, bool advancenonrequired, bool forcenonrequired, bool *continuescan, int *ikey)
Definition: nbtutils.c:2795
static bool _bt_tuple_before_array_skeys(IndexScanDesc scan, ScanDirection dir, IndexTuple tuple, TupleDesc tupdesc, int tupnatts, bool readpagetup, int sktrig, bool *scanBehind)
Definition: nbtutils.c:1147
static bool _bt_advance_array_keys_increment(IndexScanDesc scan, ScanDirection dir, bool *skip_array_set)
Definition: nbtutils.c:975
static int32 _bt_compare_array_skey(FmgrInfo *orderproc, Datum tupdatum, bool tupnull, Datum arrdatum, ScanKey cur)
Definition: nbtutils.c:216
uintptr_t Datum
Definition: postgres.h:69
#define ScanDirectionIsForward(direction)
Definition: sdir.h:64
#define ScanDirectionIsBackward(direction)
Definition: sdir.h:50
ScanDirection
Definition: sdir.h:25
#define SK_SEARCHARRAY
Definition: skey.h:120
#define BTEqualStrategyNumber
Definition: stratnum.h:31
Datum * elem_values
Definition: nbtree.h:1041
bool continuescan
Definition: nbtree.h:1117
bool firstpage
Definition: nbtree.h:1108
IndexTuple finaltup
Definition: nbtree.h:1106
int16 targetdistance
Definition: nbtree.h:1124
int16 nskipadvances
Definition: nbtree.h:1125
int16 rechecks
Definition: nbtree.h:1123
OffsetNumber skip
Definition: nbtree.h:1116
OffsetNumber maxoff
Definition: nbtree.h:1105
bool needPrimScan
Definition: nbtree.h:1063
BTArrayKeyInfo * arrayKeys
Definition: nbtree.h:1066
FmgrInfo * orderProcs
Definition: nbtree.h:1067
BTScanPosData currPos
Definition: nbtree.h:1092
bool oppositeDirCheck
Definition: nbtree.h:1065
ScanKey keyData
Definition: nbtree.h:1058
BlockNumber currPage
Definition: nbtree.h:967
ScanDirection dir
Definition: nbtree.h:973
struct ParallelIndexScanDescData * parallel_scan
Definition: relscan.h:191
Relation indexRelation
Definition: relscan.h:137
int sk_flags
Definition: skey.h:66
StrategyNumber sk_strategy
Definition: skey.h:68

References _bt_advance_array_keys(), _bt_advance_array_keys_increment(), _bt_array_set_low_or_high(), _bt_binsrch_array_skey(), _bt_binsrch_skiparray_skey(), _bt_check_compare(), _bt_compare_array_skey(), _bt_oppodir_checkkeys(), _bt_parallel_primscan_schedule(), _bt_rewind_nonrequired_arrays(), _bt_skiparray_set_element(), _bt_tuple_before_array_skeys(), BTScanOpaqueData::arrayKeys, Assert(), BTEqualStrategyNumber, BTreeTupleGetNAtts, BTReadPageState::continuescan, cur, BTArrayKeyInfo::cur_elem, BTScanPosData::currPage, BTScanOpaqueData::currPos, BTScanPosData::dir, BTArrayKeyInfo::elem_values, BTReadPageState::finaltup, BTReadPageState::firstpage, index_getattr(), IndexScanDescData::indexRelation, BTScanOpaqueData::keyData, BTReadPageState::maxoff, BTScanOpaqueData::needPrimScan, BTReadPageState::nskipadvances, NSKIPADVANCES_THRESHOLD, BTArrayKeyInfo::num_elems, BTScanOpaqueData::numberOfKeys, IndexScanDescData::opaque, BTScanOpaqueData::oppositeDirCheck, BTScanOpaqueData::orderProcs, IndexScanDescData::parallel_scan, PG_USED_FOR_ASSERTS_ONLY, BTReadPageState::rechecks, generate_unaccent_rules::required, BTArrayKeyInfo::scan_key, BTScanOpaqueData::scanBehind, ScanDirectionIsBackward, ScanDirectionIsForward, SK_BT_REQBKWD, SK_BT_REQFWD, ScanKeyData::sk_flags, SK_SEARCHARRAY, ScanKeyData::sk_strategy, BTReadPageState::skip, BTReadPageState::targetdistance, and unlikely.

Referenced by _bt_advance_array_keys(), _bt_check_compare(), and _bt_checkkeys().

◆ _bt_advance_array_keys_increment()

static bool _bt_advance_array_keys_increment ( IndexScanDesc  scan,
ScanDirection  dir,
bool *  skip_array_set 
)
static

Definition at line 975 of file nbtutils.c.

977{
978 Relation rel = scan->indexRelation;
979 BTScanOpaque so = (BTScanOpaque) scan->opaque;
980
981 /*
982 * We must advance the last array key most quickly, since it will
983 * correspond to the lowest-order index column among the available
984 * qualifications
985 */
986 for (int i = so->numArrayKeys - 1; i >= 0; i--)
987 {
988 BTArrayKeyInfo *array = &so->arrayKeys[i];
989 ScanKey skey = &so->keyData[array->scan_key];
990
991 if (array->num_elems == -1)
992 *skip_array_set = true;
993
994 if (ScanDirectionIsForward(dir))
995 {
996 if (_bt_array_increment(rel, skey, array))
997 return true;
998 }
999 else
1000 {
1001 if (_bt_array_decrement(rel, skey, array))
1002 return true;
1003 }
1004
1005 /*
1006 * Couldn't increment (or decrement) array. Handle array roll over.
1007 *
1008 * Start over at the array's lowest sorting value (or its highest
1009 * value, for backward scans)...
1010 */
1011 _bt_array_set_low_or_high(rel, skey, array,
1013
1014 /* ...then increment (or decrement) next most significant array */
1015 }
1016
1017 /*
1018 * The array keys are now exhausted.
1019 *
1020 * Restore the array keys to the state they were in immediately before we
1021 * were called. This ensures that the arrays only ever ratchet in the
1022 * current scan direction.
1023 *
1024 * Without this, scans could overlook matching tuples when the scan
1025 * direction gets reversed just before btgettuple runs out of items to
1026 * return, but just after _bt_readpage prepares all the items from the
1027 * scan's final page in so->currPos. When we're on the final page it is
1028 * typical for so->currPos to get invalidated once btgettuple finally
1029 * returns false, which'll effectively invalidate the scan's array keys.
1030 * That hasn't happened yet, though -- and in general it may never happen.
1031 */
1032 _bt_start_array_keys(scan, -dir);
1033
1034 return false;
1035}
for(;;)
int i
Definition: isn.c:77
static bool _bt_array_decrement(Relation rel, ScanKey skey, BTArrayKeyInfo *array)
Definition: nbtutils.c:703
void _bt_start_array_keys(IndexScanDesc scan, ScanDirection dir)
Definition: nbtutils.c:611
static bool _bt_array_increment(Relation rel, ScanKey skey, BTArrayKeyInfo *array)
Definition: nbtutils.c:836

References _bt_array_decrement(), _bt_array_increment(), _bt_array_set_low_or_high(), _bt_start_array_keys(), BTScanOpaqueData::arrayKeys, for(), i, IndexScanDescData::indexRelation, BTScanOpaqueData::keyData, BTArrayKeyInfo::num_elems, BTScanOpaqueData::numArrayKeys, IndexScanDescData::opaque, BTArrayKeyInfo::scan_key, and ScanDirectionIsForward.

Referenced by _bt_advance_array_keys().

◆ _bt_allequalimage()

bool _bt_allequalimage ( Relation  rel,
bool  debugmessage 
)

Definition at line 4282 of file nbtutils.c.

4283{
4284 bool allequalimage = true;
4285
4286 /* INCLUDE indexes can never support deduplication */
4289 return false;
4290
4291 for (int i = 0; i < IndexRelationGetNumberOfKeyAttributes(rel); i++)
4292 {
4293 Oid opfamily = rel->rd_opfamily[i];
4294 Oid opcintype = rel->rd_opcintype[i];
4295 Oid collation = rel->rd_indcollation[i];
4296 Oid equalimageproc;
4297
4298 equalimageproc = get_opfamily_proc(opfamily, opcintype, opcintype,
4300
4301 /*
4302 * If there is no BTEQUALIMAGE_PROC then deduplication is assumed to
4303 * be unsafe. Otherwise, actually call proc and see what it says.
4304 */
4305 if (!OidIsValid(equalimageproc) ||
4306 !DatumGetBool(OidFunctionCall1Coll(equalimageproc, collation,
4307 ObjectIdGetDatum(opcintype))))
4308 {
4309 allequalimage = false;
4310 break;
4311 }
4312 }
4313
4314 if (debugmessage)
4315 {
4316 if (allequalimage)
4317 elog(DEBUG1, "index \"%s\" can safely use deduplication",
4319 else
4320 elog(DEBUG1, "index \"%s\" cannot use deduplication",
4322 }
4323
4324 return allequalimage;
4325}
#define OidIsValid(objectId)
Definition: c.h:746
#define DEBUG1
Definition: elog.h:30
#define elog(elevel,...)
Definition: elog.h:225
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:888
#define BTEQUALIMAGE_PROC
Definition: nbtree.h:720
static bool DatumGetBool(Datum X)
Definition: postgres.h:95
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:257
unsigned int Oid
Definition: postgres_ext.h:30
#define RelationGetRelationName(relation)
Definition: rel.h:550
#define IndexRelationGetNumberOfAttributes(relation)
Definition: rel.h:528
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:535
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_callback(), and btbuildempty().

◆ _bt_array_decrement()

static bool _bt_array_decrement ( Relation  rel,
ScanKey  skey,
BTArrayKeyInfo array 
)
static

Definition at line 703 of file nbtutils.c.

704{
705 bool uflow = false;
706 Datum dec_sk_argument;
707
710
711 /* SAOP array? */
712 if (array->num_elems != -1)
713 {
715 if (array->cur_elem > 0)
716 {
717 /*
718 * Just decrement current element, and assign its datum to skey
719 * (only skip arrays need us to free existing sk_argument memory)
720 */
721 array->cur_elem--;
722 skey->sk_argument = array->elem_values[array->cur_elem];
723
724 /* Successfully decremented array */
725 return true;
726 }
727
728 /* Cannot decrement to before first array element */
729 return false;
730 }
731
732 /* Nope, this is a skip array */
733 Assert(skey->sk_flags & SK_BT_SKIP);
734
735 /*
736 * The sentinel value that represents the minimum value within the range
737 * of a skip array (often just -inf) is never decrementable
738 */
739 if (skey->sk_flags & SK_BT_MINVAL)
740 return false;
741
742 /*
743 * When the current array element is NULL, and the lowest sorting value in
744 * the index is also NULL, we cannot decrement before first array element
745 */
746 if ((skey->sk_flags & SK_ISNULL) && (skey->sk_flags & SK_BT_NULLS_FIRST))
747 return false;
748
749 /*
750 * Opclasses without skip support "decrement" the scan key's current
751 * element by setting the PRIOR flag. The true prior value is determined
752 * by repositioning to the last index tuple < existing sk_argument/current
753 * array element. Note that this works in the usual way when the scan key
754 * is already marked ISNULL (i.e. when the current element is NULL).
755 */
756 if (!array->sksup)
757 {
758 /* Successfully "decremented" array */
759 skey->sk_flags |= SK_BT_PRIOR;
760 return true;
761 }
762
763 /*
764 * Opclasses with skip support directly decrement sk_argument
765 */
766 if (skey->sk_flags & SK_ISNULL)
767 {
769
770 /*
771 * Existing sk_argument/array element is NULL (for an IS NULL qual).
772 *
773 * "Decrement" from NULL to the high_elem value provided by opclass
774 * skip support routine.
775 */
776 skey->sk_flags &= ~(SK_SEARCHNULL | SK_ISNULL);
777 skey->sk_argument = datumCopy(array->sksup->high_elem,
778 array->attbyval, array->attlen);
779 return true;
780 }
781
782 /*
783 * Ask opclass support routine to provide decremented copy of existing
784 * non-NULL sk_argument
785 */
786 dec_sk_argument = array->sksup->decrement(rel, skey->sk_argument, &uflow);
787 if (unlikely(uflow))
788 {
789 /* dec_sk_argument has undefined value (so no pfree) */
790 if (array->null_elem && (skey->sk_flags & SK_BT_NULLS_FIRST))
791 {
792 _bt_skiparray_set_isnull(rel, skey, array);
793
794 /* Successfully "decremented" array to NULL */
795 return true;
796 }
797
798 /* Cannot decrement to before first array element */
799 return false;
800 }
801
802 /*
803 * Successfully decremented sk_argument to a non-NULL value. Make sure
804 * that the decremented value is still within the range of the array.
805 */
806 if (array->low_compare &&
809 dec_sk_argument,
810 array->low_compare->sk_argument)))
811 {
812 /* Keep existing sk_argument after all */
813 if (!array->attbyval)
814 pfree(DatumGetPointer(dec_sk_argument));
815
816 /* Cannot decrement to before first array element */
817 return false;
818 }
819
820 /* Accept value returned by opclass decrement callback */
821 if (!array->attbyval && skey->sk_argument)
823 skey->sk_argument = dec_sk_argument;
824
825 /* Successfully decremented array */
826 return true;
827}
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:132
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1149
void pfree(void *pointer)
Definition: mcxt.c:2152
#define SK_BT_SKIP
Definition: nbtree.h:1136
#define SK_BT_PRIOR
Definition: nbtree.h:1142
#define SK_BT_NEXT
Definition: nbtree.h:1141
#define SK_BT_NULLS_FIRST
Definition: nbtree.h:1147
#define SK_BT_MAXVAL
Definition: nbtree.h:1140
#define SK_BT_MINVAL
Definition: nbtree.h:1139
static void _bt_skiparray_set_isnull(Relation rel, ScanKey skey, BTArrayKeyInfo *array)
Definition: nbtutils.c:587
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:317
#define SK_SEARCHNULL
Definition: skey.h:121
#define SK_ISNULL
Definition: skey.h:115
bool attbyval
Definition: nbtree.h:1046
ScanKey low_compare
Definition: nbtree.h:1049
SkipSupport sksup
Definition: nbtree.h:1048
int16 attlen
Definition: nbtree.h:1045
bool null_elem
Definition: nbtree.h:1047
Datum sk_argument
Definition: skey.h:72
FmgrInfo sk_func
Definition: skey.h:71
Oid sk_collation
Definition: skey.h:70
SkipSupportIncDec decrement
Definition: skipsupport.h:91

References _bt_skiparray_set_isnull(), Assert(), BTArrayKeyInfo::attbyval, BTArrayKeyInfo::attlen, BTArrayKeyInfo::cur_elem, datumCopy(), DatumGetBool(), DatumGetPointer(), SkipSupportData::decrement, BTArrayKeyInfo::elem_values, FunctionCall2Coll(), SkipSupportData::high_elem, BTArrayKeyInfo::low_compare, BTArrayKeyInfo::null_elem, BTArrayKeyInfo::num_elems, pfree(), ScanKeyData::sk_argument, SK_BT_MAXVAL, SK_BT_MINVAL, SK_BT_NEXT, SK_BT_NULLS_FIRST, SK_BT_PRIOR, SK_BT_SKIP, ScanKeyData::sk_collation, ScanKeyData::sk_flags, ScanKeyData::sk_func, SK_ISNULL, SK_SEARCHARRAY, SK_SEARCHNULL, BTArrayKeyInfo::sksup, and unlikely.

Referenced by _bt_advance_array_keys_increment().

◆ _bt_array_increment()

static bool _bt_array_increment ( Relation  rel,
ScanKey  skey,
BTArrayKeyInfo array 
)
static

Definition at line 836 of file nbtutils.c.

837{
838 bool oflow = false;
839 Datum inc_sk_argument;
840
843
844 /* SAOP array? */
845 if (array->num_elems != -1)
846 {
848 if (array->cur_elem < array->num_elems - 1)
849 {
850 /*
851 * Just increment current element, and assign its datum to skey
852 * (only skip arrays need us to free existing sk_argument memory)
853 */
854 array->cur_elem++;
855 skey->sk_argument = array->elem_values[array->cur_elem];
856
857 /* Successfully incremented array */
858 return true;
859 }
860
861 /* Cannot increment past final array element */
862 return false;
863 }
864
865 /* Nope, this is a skip array */
866 Assert(skey->sk_flags & SK_BT_SKIP);
867
868 /*
869 * The sentinel value that represents the maximum value within the range
870 * of a skip array (often just +inf) is never incrementable
871 */
872 if (skey->sk_flags & SK_BT_MAXVAL)
873 return false;
874
875 /*
876 * When the current array element is NULL, and the highest sorting value
877 * in the index is also NULL, we cannot increment past the final element
878 */
879 if ((skey->sk_flags & SK_ISNULL) && !(skey->sk_flags & SK_BT_NULLS_FIRST))
880 return false;
881
882 /*
883 * Opclasses without skip support "increment" the scan key's current
884 * element by setting the NEXT flag. The true next value is determined by
885 * repositioning to the first index tuple > existing sk_argument/current
886 * array element. Note that this works in the usual way when the scan key
887 * is already marked ISNULL (i.e. when the current element is NULL).
888 */
889 if (!array->sksup)
890 {
891 /* Successfully "incremented" array */
892 skey->sk_flags |= SK_BT_NEXT;
893 return true;
894 }
895
896 /*
897 * Opclasses with skip support directly increment sk_argument
898 */
899 if (skey->sk_flags & SK_ISNULL)
900 {
902
903 /*
904 * Existing sk_argument/array element is NULL (for an IS NULL qual).
905 *
906 * "Increment" from NULL to the low_elem value provided by opclass
907 * skip support routine.
908 */
909 skey->sk_flags &= ~(SK_SEARCHNULL | SK_ISNULL);
910 skey->sk_argument = datumCopy(array->sksup->low_elem,
911 array->attbyval, array->attlen);
912 return true;
913 }
914
915 /*
916 * Ask opclass support routine to provide incremented copy of existing
917 * non-NULL sk_argument
918 */
919 inc_sk_argument = array->sksup->increment(rel, skey->sk_argument, &oflow);
920 if (unlikely(oflow))
921 {
922 /* inc_sk_argument has undefined value (so no pfree) */
923 if (array->null_elem && !(skey->sk_flags & SK_BT_NULLS_FIRST))
924 {
925 _bt_skiparray_set_isnull(rel, skey, array);
926
927 /* Successfully "incremented" array to NULL */
928 return true;
929 }
930
931 /* Cannot increment past final array element */
932 return false;
933 }
934
935 /*
936 * Successfully incremented sk_argument to a non-NULL value. Make sure
937 * that the incremented value is still within the range of the array.
938 */
939 if (array->high_compare &&
942 inc_sk_argument,
943 array->high_compare->sk_argument)))
944 {
945 /* Keep existing sk_argument after all */
946 if (!array->attbyval)
947 pfree(DatumGetPointer(inc_sk_argument));
948
949 /* Cannot increment past final array element */
950 return false;
951 }
952
953 /* Accept value returned by opclass increment callback */
954 if (!array->attbyval && skey->sk_argument)
956 skey->sk_argument = inc_sk_argument;
957
958 /* Successfully incremented array */
959 return true;
960}
ScanKey high_compare
Definition: nbtree.h:1050
SkipSupportIncDec increment
Definition: skipsupport.h:92

References _bt_skiparray_set_isnull(), Assert(), BTArrayKeyInfo::attbyval, BTArrayKeyInfo::attlen, BTArrayKeyInfo::cur_elem, datumCopy(), DatumGetBool(), DatumGetPointer(), BTArrayKeyInfo::elem_values, FunctionCall2Coll(), BTArrayKeyInfo::high_compare, SkipSupportData::increment, SkipSupportData::low_elem, BTArrayKeyInfo::null_elem, BTArrayKeyInfo::num_elems, pfree(), ScanKeyData::sk_argument, SK_BT_MAXVAL, SK_BT_MINVAL, SK_BT_NEXT, SK_BT_NULLS_FIRST, SK_BT_PRIOR, SK_BT_SKIP, ScanKeyData::sk_collation, ScanKeyData::sk_flags, ScanKeyData::sk_func, SK_ISNULL, SK_SEARCHARRAY, SK_SEARCHNULL, BTArrayKeyInfo::sksup, and unlikely.

Referenced by _bt_advance_array_keys_increment().

◆ _bt_array_set_low_or_high()

static void _bt_array_set_low_or_high ( Relation  rel,
ScanKey  skey,
BTArrayKeyInfo array,
bool  low_not_high 
)
static

Definition at line 639 of file nbtutils.c.

641{
643
644 if (array->num_elems != -1)
645 {
646 /* set low or high element for SAOP array */
647 int set_elem = 0;
648
649 Assert(!(skey->sk_flags & SK_BT_SKIP));
650
651 if (!low_not_high)
652 set_elem = array->num_elems - 1;
653
654 /*
655 * Just copy over array datum (only skip arrays require freeing and
656 * allocating memory for sk_argument)
657 */
658 array->cur_elem = set_elem;
659 skey->sk_argument = array->elem_values[set_elem];
660
661 return;
662 }
663
664 /* set low or high element for skip array */
665 Assert(skey->sk_flags & SK_BT_SKIP);
666 Assert(array->num_elems == -1);
667
668 /* Free memory previously allocated for sk_argument if needed */
669 if (!array->attbyval && skey->sk_argument)
671
672 /* Reset flags */
673 skey->sk_argument = (Datum) 0;
674 skey->sk_flags &= ~(SK_SEARCHNULL | SK_ISNULL |
677
678 if (array->null_elem &&
679 (low_not_high == ((skey->sk_flags & SK_BT_NULLS_FIRST) != 0)))
680 {
681 /* Requested element (either lowest or highest) has the value NULL */
682 skey->sk_flags |= (SK_SEARCHNULL | SK_ISNULL);
683 }
684 else if (low_not_high)
685 {
686 /* Setting array to lowest element (according to low_compare) */
687 skey->sk_flags |= SK_BT_MINVAL;
688 }
689 else
690 {
691 /* Setting array to highest element (according to high_compare) */
692 skey->sk_flags |= SK_BT_MAXVAL;
693 }
694}

References Assert(), BTArrayKeyInfo::attbyval, BTArrayKeyInfo::cur_elem, DatumGetPointer(), BTArrayKeyInfo::elem_values, BTArrayKeyInfo::null_elem, BTArrayKeyInfo::num_elems, pfree(), ScanKeyData::sk_argument, SK_BT_MAXVAL, SK_BT_MINVAL, SK_BT_NEXT, SK_BT_NULLS_FIRST, SK_BT_PRIOR, SK_BT_SKIP, ScanKeyData::sk_flags, SK_ISNULL, SK_SEARCHARRAY, and SK_SEARCHNULL.

Referenced by _bt_advance_array_keys(), _bt_advance_array_keys_increment(), _bt_rewind_nonrequired_arrays(), _bt_skiparray_set_element(), and _bt_start_array_keys().

◆ _bt_binsrch_array_skey()

int _bt_binsrch_array_skey ( FmgrInfo orderproc,
bool  cur_elem_trig,
ScanDirection  dir,
Datum  tupdatum,
bool  tupnull,
BTArrayKeyInfo array,
ScanKey  cur,
int32 set_elem_result 
)

Definition at line 287 of file nbtutils.c.

292{
293 int low_elem = 0,
294 mid_elem = -1,
295 high_elem = array->num_elems - 1,
296 result = 0;
297 Datum arrdatum;
298
299 Assert(cur->sk_flags & SK_SEARCHARRAY);
300 Assert(!(cur->sk_flags & SK_BT_SKIP));
301 Assert(!(cur->sk_flags & SK_ISNULL)); /* SAOP arrays never have NULLs */
302 Assert(cur->sk_strategy == BTEqualStrategyNumber);
303
304 if (cur_elem_trig)
305 {
307 Assert(cur->sk_flags & SK_BT_REQFWD);
308
309 /*
310 * When the scan key that triggered array advancement is a required
311 * array scan key, it is now certain that the current array element
312 * (plus all prior elements relative to the current scan direction)
313 * cannot possibly be at or ahead of the corresponding tuple value.
314 * (_bt_checkkeys must have called _bt_tuple_before_array_skeys, which
315 * makes sure this is true as a condition of advancing the arrays.)
316 *
317 * This makes it safe to exclude array elements up to and including
318 * the former-current array element from our search.
319 *
320 * Separately, when array advancement was triggered by a required scan
321 * key, the array element immediately after the former-current element
322 * is often either an exact tupdatum match, or a "close by" near-match
323 * (a near-match tupdatum is one whose key space falls _between_ the
324 * former-current and new-current array elements). We'll detect both
325 * cases via an optimistic comparison of the new search lower bound
326 * (or new search upper bound in the case of backwards scans).
327 */
328 if (ScanDirectionIsForward(dir))
329 {
330 low_elem = array->cur_elem + 1; /* old cur_elem exhausted */
331
332 /* Compare prospective new cur_elem (also the new lower bound) */
333 if (high_elem >= low_elem)
334 {
335 arrdatum = array->elem_values[low_elem];
336 result = _bt_compare_array_skey(orderproc, tupdatum, tupnull,
337 arrdatum, cur);
338
339 if (result <= 0)
340 {
341 /* Optimistic comparison optimization worked out */
342 *set_elem_result = result;
343 return low_elem;
344 }
345 mid_elem = low_elem;
346 low_elem++; /* this cur_elem exhausted, too */
347 }
348
349 if (high_elem < low_elem)
350 {
351 /* Caller needs to perform "beyond end" array advancement */
352 *set_elem_result = 1;
353 return high_elem;
354 }
355 }
356 else
357 {
358 high_elem = array->cur_elem - 1; /* old cur_elem exhausted */
359
360 /* Compare prospective new cur_elem (also the new upper bound) */
361 if (high_elem >= low_elem)
362 {
363 arrdatum = array->elem_values[high_elem];
364 result = _bt_compare_array_skey(orderproc, tupdatum, tupnull,
365 arrdatum, cur);
366
367 if (result >= 0)
368 {
369 /* Optimistic comparison optimization worked out */
370 *set_elem_result = result;
371 return high_elem;
372 }
373 mid_elem = high_elem;
374 high_elem--; /* this cur_elem exhausted, too */
375 }
376
377 if (high_elem < low_elem)
378 {
379 /* Caller needs to perform "beyond end" array advancement */
380 *set_elem_result = -1;
381 return low_elem;
382 }
383 }
384 }
385
386 while (high_elem > low_elem)
387 {
388 mid_elem = low_elem + ((high_elem - low_elem) / 2);
389 arrdatum = array->elem_values[mid_elem];
390
391 result = _bt_compare_array_skey(orderproc, tupdatum, tupnull,
392 arrdatum, cur);
393
394 if (result == 0)
395 {
396 /*
397 * It's safe to quit as soon as we see an equal array element.
398 * This often saves an extra comparison or two...
399 */
400 low_elem = mid_elem;
401 break;
402 }
403
404 if (result > 0)
405 low_elem = mid_elem + 1;
406 else
407 high_elem = mid_elem;
408 }
409
410 /*
411 * ...but our caller also cares about how its searched-for tuple datum
412 * compares to the low_elem datum. Must always set *set_elem_result with
413 * the result of that comparison specifically.
414 */
415 if (low_elem != mid_elem)
416 result = _bt_compare_array_skey(orderproc, tupdatum, tupnull,
417 array->elem_values[low_elem], cur);
418
419 *set_elem_result = result;
420
421 return low_elem;
422}
#define ScanDirectionIsNoMovement(direction)
Definition: sdir.h:57

References _bt_compare_array_skey(), Assert(), BTEqualStrategyNumber, cur, BTArrayKeyInfo::cur_elem, BTArrayKeyInfo::elem_values, BTArrayKeyInfo::num_elems, ScanDirectionIsForward, ScanDirectionIsNoMovement, SK_BT_REQFWD, SK_BT_SKIP, SK_ISNULL, and SK_SEARCHARRAY.

Referenced by _bt_advance_array_keys(), _bt_saoparray_shrink(), and _bt_set_startikey().

◆ _bt_binsrch_skiparray_skey()

static void _bt_binsrch_skiparray_skey ( bool  cur_elem_trig,
ScanDirection  dir,
Datum  tupdatum,
bool  tupnull,
BTArrayKeyInfo array,
ScanKey  cur,
int32 set_elem_result 
)
static

Definition at line 443 of file nbtutils.c.

447{
448 Assert(cur->sk_flags & SK_BT_SKIP);
449 Assert(cur->sk_flags & SK_SEARCHARRAY);
450 Assert(cur->sk_flags & SK_BT_REQFWD);
451 Assert(array->num_elems == -1);
453
454 if (array->null_elem)
455 {
456 Assert(!array->low_compare && !array->high_compare);
457
458 *set_elem_result = 0;
459 return;
460 }
461
462 if (tupnull) /* NULL tupdatum */
463 {
464 if (cur->sk_flags & SK_BT_NULLS_FIRST)
465 *set_elem_result = -1; /* NULL "<" NOT_NULL */
466 else
467 *set_elem_result = 1; /* NULL ">" NOT_NULL */
468 return;
469 }
470
471 /*
472 * Array inequalities determine whether tupdatum is within the range of
473 * caller's skip array
474 */
475 *set_elem_result = 0;
476 if (ScanDirectionIsForward(dir))
477 {
478 /*
479 * Evaluate low_compare first (unless cur_elem_trig tells us that it
480 * cannot possibly fail to be satisfied), then evaluate high_compare
481 */
482 if (!cur_elem_trig && array->low_compare &&
485 tupdatum,
486 array->low_compare->sk_argument)))
487 *set_elem_result = -1;
488 else if (array->high_compare &&
491 tupdatum,
492 array->high_compare->sk_argument)))
493 *set_elem_result = 1;
494 }
495 else
496 {
497 /*
498 * Evaluate high_compare first (unless cur_elem_trig tells us that it
499 * cannot possibly fail to be satisfied), then evaluate low_compare
500 */
501 if (!cur_elem_trig && array->high_compare &&
504 tupdatum,
505 array->high_compare->sk_argument)))
506 *set_elem_result = 1;
507 else if (array->low_compare &&
510 tupdatum,
511 array->low_compare->sk_argument)))
512 *set_elem_result = -1;
513 }
514
515 /*
516 * Assert that any keys that were assumed to be satisfied already (due to
517 * caller passing cur_elem_trig=true) really are satisfied as expected
518 */
519#ifdef USE_ASSERT_CHECKING
520 if (cur_elem_trig)
521 {
522 if (ScanDirectionIsForward(dir) && array->low_compare)
525 tupdatum,
526 array->low_compare->sk_argument)));
527
528 if (ScanDirectionIsBackward(dir) && array->high_compare)
531 tupdatum,
532 array->high_compare->sk_argument)));
533 }
534#endif
535}

References Assert(), cur, DatumGetBool(), FunctionCall2Coll(), BTArrayKeyInfo::high_compare, BTArrayKeyInfo::low_compare, BTArrayKeyInfo::null_elem, BTArrayKeyInfo::num_elems, ScanDirectionIsBackward, ScanDirectionIsForward, ScanDirectionIsNoMovement, ScanKeyData::sk_argument, SK_BT_NULLS_FIRST, SK_BT_REQFWD, SK_BT_SKIP, ScanKeyData::sk_collation, ScanKeyData::sk_func, and SK_SEARCHARRAY.

Referenced by _bt_advance_array_keys(), _bt_set_startikey(), and _bt_tuple_before_array_skeys().

◆ _bt_check_compare()

static bool _bt_check_compare ( IndexScanDesc  scan,
ScanDirection  dir,
IndexTuple  tuple,
int  tupnatts,
TupleDesc  tupdesc,
bool  advancenonrequired,
bool  forcenonrequired,
bool *  continuescan,
int *  ikey 
)
static

Definition at line 2795 of file nbtutils.c.

2799{
2800 BTScanOpaque so = (BTScanOpaque) scan->opaque;
2801
2802 *continuescan = true; /* default assumption */
2803
2804 for (; *ikey < so->numberOfKeys; (*ikey)++)
2805 {
2806 ScanKey key = so->keyData + *ikey;
2807 Datum datum;
2808 bool isNull;
2809 bool requiredSameDir = false,
2810 requiredOppositeDirOnly = false;
2811
2812 /*
2813 * Check if the key is required in the current scan direction, in the
2814 * opposite scan direction _only_, or in neither direction (except
2815 * when we're forced to treat all scan keys as nonrequired)
2816 */
2817 if (forcenonrequired)
2818 {
2819 /* treating scan's keys as non-required */
2820 }
2821 else if (((key->sk_flags & SK_BT_REQFWD) && ScanDirectionIsForward(dir)) ||
2822 ((key->sk_flags & SK_BT_REQBKWD) && ScanDirectionIsBackward(dir)))
2823 requiredSameDir = true;
2824 else if (((key->sk_flags & SK_BT_REQFWD) && ScanDirectionIsBackward(dir)) ||
2825 ((key->sk_flags & SK_BT_REQBKWD) && ScanDirectionIsForward(dir)))
2826 requiredOppositeDirOnly = true;
2827
2828 if (key->sk_attno > tupnatts)
2829 {
2830 /*
2831 * This attribute is truncated (must be high key). The value for
2832 * this attribute in the first non-pivot tuple on the page to the
2833 * right could be any possible value. Assume that truncated
2834 * attribute passes the qual.
2835 */
2836 Assert(BTreeTupleIsPivot(tuple));
2837 continue;
2838 }
2839
2840 /*
2841 * A skip array scan key uses one of several sentinel values. We just
2842 * fall back on _bt_tuple_before_array_skeys when we see such a value.
2843 */
2844 if (key->sk_flags & (SK_BT_MINVAL | SK_BT_MAXVAL |
2846 {
2847 Assert(key->sk_flags & SK_SEARCHARRAY);
2848 Assert(key->sk_flags & SK_BT_SKIP);
2849 Assert(requiredSameDir || forcenonrequired);
2850
2851 /*
2852 * Cannot fall back on _bt_tuple_before_array_skeys when we're
2853 * treating the scan's keys as nonrequired, though. Just handle
2854 * this like any other non-required equality-type array key.
2855 */
2856 if (forcenonrequired)
2857 return _bt_advance_array_keys(scan, NULL, tuple, tupnatts,
2858 tupdesc, *ikey, false);
2859
2860 *continuescan = false;
2861 return false;
2862 }
2863
2864 /* row-comparison keys need special processing */
2865 if (key->sk_flags & SK_ROW_HEADER)
2866 {
2867 if (_bt_check_rowcompare(key, tuple, tupnatts, tupdesc, dir,
2868 forcenonrequired, continuescan))
2869 continue;
2870 return false;
2871 }
2872
2873 datum = index_getattr(tuple,
2874 key->sk_attno,
2875 tupdesc,
2876 &isNull);
2877
2878 if (key->sk_flags & SK_ISNULL)
2879 {
2880 /* Handle IS NULL/NOT NULL tests */
2881 if (key->sk_flags & SK_SEARCHNULL)
2882 {
2883 if (isNull)
2884 continue; /* tuple satisfies this qual */
2885 }
2886 else
2887 {
2888 Assert(key->sk_flags & SK_SEARCHNOTNULL);
2889 Assert(!(key->sk_flags & SK_BT_SKIP));
2890 if (!isNull)
2891 continue; /* tuple satisfies this qual */
2892 }
2893
2894 /*
2895 * Tuple fails this qual. If it's a required qual for the current
2896 * scan direction, then we can conclude no further tuples will
2897 * pass, either.
2898 */
2899 if (requiredSameDir)
2900 *continuescan = false;
2901 else if (unlikely(key->sk_flags & SK_BT_SKIP))
2902 {
2903 /*
2904 * If we're treating scan keys as nonrequired, and encounter a
2905 * skip array scan key whose current element is NULL, then it
2906 * must be a non-range skip array. It must be satisfied, so
2907 * there's no need to call _bt_advance_array_keys to check.
2908 */
2909 Assert(forcenonrequired && *ikey > 0);
2910 continue;
2911 }
2912
2913 /*
2914 * This indextuple doesn't match the qual.
2915 */
2916 return false;
2917 }
2918
2919 if (isNull)
2920 {
2921 /*
2922 * Scalar scan key isn't satisfied by NULL tuple value.
2923 *
2924 * If we're treating scan keys as nonrequired, and key is for a
2925 * skip array, then we must attempt to advance the array to NULL
2926 * (if we're successful then the tuple might match the qual).
2927 */
2928 if (unlikely(forcenonrequired && key->sk_flags & SK_BT_SKIP))
2929 return _bt_advance_array_keys(scan, NULL, tuple, tupnatts,
2930 tupdesc, *ikey, false);
2931
2932 if (key->sk_flags & SK_BT_NULLS_FIRST)
2933 {
2934 /*
2935 * Since NULLs are sorted before non-NULLs, we know we have
2936 * reached the lower limit of the range of values for this
2937 * index attr. On a backward scan, we can stop if this qual
2938 * is one of the "must match" subset. We can stop regardless
2939 * of whether the qual is > or <, so long as it's required,
2940 * because it's not possible for any future tuples to pass. On
2941 * a forward scan, however, we must keep going, because we may
2942 * have initially positioned to the start of the index.
2943 * (_bt_advance_array_keys also relies on this behavior during
2944 * forward scans.)
2945 */
2946 if ((requiredSameDir || requiredOppositeDirOnly) &&
2948 *continuescan = false;
2949 }
2950 else
2951 {
2952 /*
2953 * Since NULLs are sorted after non-NULLs, we know we have
2954 * reached the upper limit of the range of values for this
2955 * index attr. On a forward scan, we can stop if this qual is
2956 * one of the "must match" subset. We can stop regardless of
2957 * whether the qual is > or <, so long as it's required,
2958 * because it's not possible for any future tuples to pass. On
2959 * a backward scan, however, we must keep going, because we
2960 * may have initially positioned to the end of the index.
2961 * (_bt_advance_array_keys also relies on this behavior during
2962 * backward scans.)
2963 */
2964 if ((requiredSameDir || requiredOppositeDirOnly) &&
2966 *continuescan = false;
2967 }
2968
2969 /*
2970 * This indextuple doesn't match the qual.
2971 */
2972 return false;
2973 }
2974
2975 if (!DatumGetBool(FunctionCall2Coll(&key->sk_func, key->sk_collation,
2976 datum, key->sk_argument)))
2977 {
2978 /*
2979 * Tuple fails this qual. If it's a required qual for the current
2980 * scan direction, then we can conclude no further tuples will
2981 * pass, either.
2982 *
2983 * Note: because we stop the scan as soon as any required equality
2984 * qual fails, it is critical that equality quals be used for the
2985 * initial positioning in _bt_first() when they are available. See
2986 * comments in _bt_first().
2987 */
2988 if (requiredSameDir)
2989 *continuescan = false;
2990
2991 /*
2992 * If this is a non-required equality-type array key, the tuple
2993 * needs to be checked against every possible array key. Handle
2994 * this by "advancing" the scan key's array to a matching value
2995 * (if we're successful then the tuple might match the qual).
2996 */
2997 else if (advancenonrequired &&
2998 key->sk_strategy == BTEqualStrategyNumber &&
2999 (key->sk_flags & SK_SEARCHARRAY))
3000 return _bt_advance_array_keys(scan, NULL, tuple, tupnatts,
3001 tupdesc, *ikey, false);
3002
3003 /*
3004 * This indextuple doesn't match the qual.
3005 */
3006 return false;
3007 }
3008 }
3009
3010 /* If we get here, the tuple passes all index quals. */
3011 return true;
3012}
static bool BTreeTupleIsPivot(IndexTuple itup)
Definition: nbtree.h:481
static bool _bt_check_rowcompare(ScanKey skey, IndexTuple tuple, int tupnatts, TupleDesc tupdesc, ScanDirection dir, bool forcenonrequired, bool *continuescan)
Definition: nbtutils.c:3024
#define SK_ROW_HEADER
Definition: skey.h:117
#define SK_SEARCHNOTNULL
Definition: skey.h:122

References _bt_advance_array_keys(), _bt_check_rowcompare(), Assert(), BTEqualStrategyNumber, BTreeTupleIsPivot(), DatumGetBool(), for(), FunctionCall2Coll(), index_getattr(), sort-test::key, BTScanOpaqueData::keyData, BTScanOpaqueData::numberOfKeys, IndexScanDescData::opaque, ScanDirectionIsBackward, ScanDirectionIsForward, SK_BT_MAXVAL, SK_BT_MINVAL, SK_BT_NEXT, SK_BT_NULLS_FIRST, SK_BT_PRIOR, SK_BT_REQBKWD, SK_BT_REQFWD, SK_BT_SKIP, SK_ISNULL, SK_ROW_HEADER, SK_SEARCHARRAY, SK_SEARCHNOTNULL, SK_SEARCHNULL, and unlikely.

Referenced by _bt_advance_array_keys(), _bt_checkkeys(), and _bt_oppodir_checkkeys().

◆ _bt_check_natts()

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

Definition at line 4065 of file nbtutils.c.

4066{
4069 BTPageOpaque opaque = BTPageGetOpaque(page);
4070 IndexTuple itup;
4071 int tupnatts;
4072
4073 /*
4074 * We cannot reliably test a deleted or half-dead page, since they have
4075 * dummy high keys
4076 */
4077 if (P_IGNORE(opaque))
4078 return true;
4079
4080 Assert(offnum >= FirstOffsetNumber &&
4081 offnum <= PageGetMaxOffsetNumber(page));
4082
4083 itup = (IndexTuple) PageGetItem(page, PageGetItemId(page, offnum));
4084 tupnatts = BTreeTupleGetNAtts(itup, rel);
4085
4086 /* !heapkeyspace indexes do not support deduplication */
4087 if (!heapkeyspace && BTreeTupleIsPosting(itup))
4088 return false;
4089
4090 /* Posting list tuples should never have "pivot heap TID" bit set */
4091 if (BTreeTupleIsPosting(itup) &&
4094 return false;
4095
4096 /* INCLUDE indexes do not support deduplication */
4097 if (natts != nkeyatts && BTreeTupleIsPosting(itup))
4098 return false;
4099
4100 if (P_ISLEAF(opaque))
4101 {
4102 if (offnum >= P_FIRSTDATAKEY(opaque))
4103 {
4104 /*
4105 * Non-pivot tuple should never be explicitly marked as a pivot
4106 * tuple
4107 */
4108 if (BTreeTupleIsPivot(itup))
4109 return false;
4110
4111 /*
4112 * Leaf tuples that are not the page high key (non-pivot tuples)
4113 * should never be truncated. (Note that tupnatts must have been
4114 * inferred, even with a posting list tuple, because only pivot
4115 * tuples store tupnatts directly.)
4116 */
4117 return tupnatts == natts;
4118 }
4119 else
4120 {
4121 /*
4122 * Rightmost page doesn't contain a page high key, so tuple was
4123 * checked above as ordinary leaf tuple
4124 */
4125 Assert(!P_RIGHTMOST(opaque));
4126
4127 /*
4128 * !heapkeyspace high key tuple contains only key attributes. Note
4129 * that tupnatts will only have been explicitly represented in
4130 * !heapkeyspace indexes that happen to have non-key attributes.
4131 */
4132 if (!heapkeyspace)
4133 return tupnatts == nkeyatts;
4134
4135 /* Use generic heapkeyspace pivot tuple handling */
4136 }
4137 }
4138 else /* !P_ISLEAF(opaque) */
4139 {
4140 if (offnum == P_FIRSTDATAKEY(opaque))
4141 {
4142 /*
4143 * The first tuple on any internal page (possibly the first after
4144 * its high key) is its negative infinity tuple. Negative
4145 * infinity tuples are always truncated to zero attributes. They
4146 * are a particular kind of pivot tuple.
4147 */
4148 if (heapkeyspace)
4149 return tupnatts == 0;
4150
4151 /*
4152 * The number of attributes won't be explicitly represented if the
4153 * negative infinity tuple was generated during a page split that
4154 * occurred with a version of Postgres before v11. There must be
4155 * a problem when there is an explicit representation that is
4156 * non-zero, or when there is no explicit representation and the
4157 * tuple is evidently not a pre-pg_upgrade tuple.
4158 *
4159 * Prior to v11, downlinks always had P_HIKEY as their offset.
4160 * Accept that as an alternative indication of a valid
4161 * !heapkeyspace negative infinity tuple.
4162 */
4163 return tupnatts == 0 ||
4165 }
4166 else
4167 {
4168 /*
4169 * !heapkeyspace downlink tuple with separator key contains only
4170 * key attributes. Note that tupnatts will only have been
4171 * explicitly represented in !heapkeyspace indexes that happen to
4172 * have non-key attributes.
4173 */
4174 if (!heapkeyspace)
4175 return tupnatts == nkeyatts;
4176
4177 /* Use generic heapkeyspace pivot tuple handling */
4178 }
4179 }
4180
4181 /* Handle heapkeyspace pivot tuples (excluding minus infinity items) */
4182 Assert(heapkeyspace);
4183
4184 /*
4185 * Explicit representation of the number of attributes is mandatory with
4186 * heapkeyspace index pivot tuples, regardless of whether or not there are
4187 * non-key attributes.
4188 */
4189 if (!BTreeTupleIsPivot(itup))
4190 return false;
4191
4192 /* Pivot tuple should not use posting list representation (redundant) */
4193 if (BTreeTupleIsPosting(itup))
4194 return false;
4195
4196 /*
4197 * Heap TID is a tiebreaker key attribute, so it cannot be untruncated
4198 * when any other key attribute is truncated
4199 */
4200 if (BTreeTupleGetHeapTID(itup) != NULL && tupnatts != nkeyatts)
4201 return false;
4202
4203 /*
4204 * Pivot tuple must have at least one untruncated key attribute (minus
4205 * infinity pivot tuples are the only exception). Pivot tuples can never
4206 * represent that there is a value present for a key attribute that
4207 * exceeds pg_index.indnkeyatts for the index.
4208 */
4209 return tupnatts > 0 && tupnatts <= nkeyatts;
4210}
static Item PageGetItem(const PageData *page, const ItemIdData *itemId)
Definition: bufpage.h:354
static ItemId PageGetItemId(Page page, OffsetNumber offsetNumber)
Definition: bufpage.h:244
static OffsetNumber PageGetMaxOffsetNumber(const PageData *page)
Definition: bufpage.h:372
int16_t int16
Definition: c.h:497
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
#define BT_PIVOT_HEAP_TID_ATTR
Definition: nbtree.h:466
#define P_ISLEAF(opaque)
Definition: nbtree.h:221
#define P_HIKEY
Definition: nbtree.h:368
#define BTPageGetOpaque(page)
Definition: nbtree.h:74
#define P_FIRSTDATAKEY(opaque)
Definition: nbtree.h:370
#define P_RIGHTMOST(opaque)
Definition: nbtree.h:220
#define P_IGNORE(opaque)
Definition: nbtree.h:226
static bool BTreeTupleIsPosting(IndexTuple itup)
Definition: nbtree.h:493
static ItemPointer BTreeTupleGetHeapTID(IndexTuple itup)
Definition: nbtree.h:639
#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  forcenonrequired,
bool *  continuescan 
)
static

Definition at line 3024 of file nbtutils.c.

3027{
3028 ScanKey subkey = (ScanKey) DatumGetPointer(skey->sk_argument);
3029 int32 cmpresult = 0;
3030 bool result;
3031
3032 /* First subkey should be same as the header says */
3033 Assert(subkey->sk_attno == skey->sk_attno);
3034
3035 /* Loop over columns of the row condition */
3036 for (;;)
3037 {
3038 Datum datum;
3039 bool isNull;
3040
3041 Assert(subkey->sk_flags & SK_ROW_MEMBER);
3042
3043 if (subkey->sk_attno > tupnatts)
3044 {
3045 /*
3046 * This attribute is truncated (must be high key). The value for
3047 * this attribute in the first non-pivot tuple on the page to the
3048 * right could be any possible value. Assume that truncated
3049 * attribute passes the qual.
3050 */
3051 Assert(BTreeTupleIsPivot(tuple));
3052 cmpresult = 0;
3053 if (subkey->sk_flags & SK_ROW_END)
3054 break;
3055 subkey++;
3056 continue;
3057 }
3058
3059 datum = index_getattr(tuple,
3060 subkey->sk_attno,
3061 tupdesc,
3062 &isNull);
3063
3064 if (isNull)
3065 {
3066 if (forcenonrequired)
3067 {
3068 /* treating scan's keys as non-required */
3069 }
3070 else if (subkey->sk_flags & SK_BT_NULLS_FIRST)
3071 {
3072 /*
3073 * Since NULLs are sorted before non-NULLs, we know we have
3074 * reached the lower limit of the range of values for this
3075 * index attr. On a backward scan, we can stop if this qual
3076 * is one of the "must match" subset. We can stop regardless
3077 * of whether the qual is > or <, so long as it's required,
3078 * because it's not possible for any future tuples to pass. On
3079 * a forward scan, however, we must keep going, because we may
3080 * have initially positioned to the start of the index.
3081 * (_bt_advance_array_keys also relies on this behavior during
3082 * forward scans.)
3083 */
3084 if ((subkey->sk_flags & (SK_BT_REQFWD | SK_BT_REQBKWD)) &&
3086 *continuescan = false;
3087 }
3088 else
3089 {
3090 /*
3091 * Since NULLs are sorted after non-NULLs, we know we have
3092 * reached the upper limit of the range of values for this
3093 * index attr. On a forward scan, we can stop if this qual is
3094 * one of the "must match" subset. We can stop regardless of
3095 * whether the qual is > or <, so long as it's required,
3096 * because it's not possible for any future tuples to pass. On
3097 * a backward scan, however, we must keep going, because we
3098 * may have initially positioned to the end of the index.
3099 * (_bt_advance_array_keys also relies on this behavior during
3100 * backward scans.)
3101 */
3102 if ((subkey->sk_flags & (SK_BT_REQFWD | SK_BT_REQBKWD)) &&
3104 *continuescan = false;
3105 }
3106
3107 /*
3108 * In any case, this indextuple doesn't match the qual.
3109 */
3110 return false;
3111 }
3112
3113 if (subkey->sk_flags & SK_ISNULL)
3114 {
3115 /*
3116 * Unlike the simple-scankey case, this isn't a disallowed case
3117 * (except when it's the first row element that has the NULL arg).
3118 * But it can never match. If all the earlier row comparison
3119 * columns are required for the scan direction, we can stop the
3120 * scan, because there can't be another tuple that will succeed.
3121 */
3122 Assert(subkey != (ScanKey) DatumGetPointer(skey->sk_argument));
3123 subkey--;
3124 if (forcenonrequired)
3125 {
3126 /* treating scan's keys as non-required */
3127 }
3128 else if ((subkey->sk_flags & SK_BT_REQFWD) &&
3130 *continuescan = false;
3131 else if ((subkey->sk_flags & SK_BT_REQBKWD) &&
3133 *continuescan = false;
3134 return false;
3135 }
3136
3137 /* Perform the test --- three-way comparison not bool operator */
3138 cmpresult = DatumGetInt32(FunctionCall2Coll(&subkey->sk_func,
3139 subkey->sk_collation,
3140 datum,
3141 subkey->sk_argument));
3142
3143 if (subkey->sk_flags & SK_BT_DESC)
3144 INVERT_COMPARE_RESULT(cmpresult);
3145
3146 /* Done comparing if unequal, else advance to next column */
3147 if (cmpresult != 0)
3148 break;
3149
3150 if (subkey->sk_flags & SK_ROW_END)
3151 break;
3152 subkey++;
3153 }
3154
3155 /*
3156 * At this point cmpresult indicates the overall result of the row
3157 * comparison, and subkey points to the deciding column (or the last
3158 * column if the result is "=").
3159 */
3160 switch (subkey->sk_strategy)
3161 {
3162 /* EQ and NE cases aren't allowed here */
3164 result = (cmpresult < 0);
3165 break;
3167 result = (cmpresult <= 0);
3168 break;
3170 result = (cmpresult >= 0);
3171 break;
3173 result = (cmpresult > 0);
3174 break;
3175 default:
3176 elog(ERROR, "unexpected strategy number %d", subkey->sk_strategy);
3177 result = 0; /* keep compiler quiet */
3178 break;
3179 }
3180
3181 if (!result && !forcenonrequired)
3182 {
3183 /*
3184 * Tuple fails this qual. If it's a required qual for the current
3185 * scan direction, then we can conclude no further tuples will pass,
3186 * either. Note we have to look at the deciding column, not
3187 * necessarily the first or last column of the row condition.
3188 */
3189 if ((subkey->sk_flags & SK_BT_REQFWD) &&
3191 *continuescan = false;
3192 else if ((subkey->sk_flags & SK_BT_REQBKWD) &&
3194 *continuescan = false;
3195 }
3196
3197 return result;
3198}
#define INVERT_COMPARE_RESULT(var)
Definition: c.h:1077
#define ERROR
Definition: elog.h:39
#define SK_BT_DESC
Definition: nbtree.h:1146
static int32 DatumGetInt32(Datum X)
Definition: postgres.h:207
#define SK_ROW_MEMBER
Definition: skey.h:118
#define SK_ROW_END
Definition: skey.h:119
ScanKeyData * ScanKey
Definition: skey.h:75
#define BTGreaterStrategyNumber
Definition: stratnum.h:33
#define BTLessStrategyNumber
Definition: stratnum.h:29
#define BTLessEqualStrategyNumber
Definition: stratnum.h:30
#define BTGreaterEqualStrategyNumber
Definition: stratnum.h:32
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_check_compare().

◆ _bt_check_third_page()

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

Definition at line 4225 of file nbtutils.c.

4227{
4228 Size itemsz;
4229 BTPageOpaque opaque;
4230
4231 itemsz = MAXALIGN(IndexTupleSize(newtup));
4232
4233 /* Double check item size against limit */
4234 if (itemsz <= BTMaxItemSize)
4235 return;
4236
4237 /*
4238 * Tuple is probably too large to fit on page, but it's possible that the
4239 * index uses version 2 or version 3, or that page is an internal page, in
4240 * which case a slightly higher limit applies.
4241 */
4242 if (!needheaptidspace && itemsz <= BTMaxItemSizeNoHeapTid)
4243 return;
4244
4245 /*
4246 * Internal page insertions cannot fail here, because that would mean that
4247 * an earlier leaf level insertion that should have failed didn't
4248 */
4249 opaque = BTPageGetOpaque(page);
4250 if (!P_ISLEAF(opaque))
4251 elog(ERROR, "cannot insert oversized tuple of size %zu on internal page of index \"%s\"",
4252 itemsz, RelationGetRelationName(rel));
4253
4254 ereport(ERROR,
4255 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
4256 errmsg("index row size %zu exceeds btree version %u maximum %zu for index \"%s\"",
4257 itemsz,
4258 needheaptidspace ? BTREE_VERSION : BTREE_NOVAC_VERSION,
4259 needheaptidspace ? BTMaxItemSize : BTMaxItemSizeNoHeapTid,
4261 errdetail("Index row references tuple (%u,%u) in relation \"%s\".",
4265 errhint("Values larger than 1/3 of a buffer page cannot be indexed.\n"
4266 "Consider a function index of an MD5 hash of the value, "
4267 "or use full text indexing."),
4269}
#define MAXALIGN(LEN)
Definition: c.h:782
size_t Size
Definition: c.h:576
int errdetail(const char *fmt,...)
Definition: elog.c:1204
int errhint(const char *fmt,...)
Definition: elog.c:1318
int errcode(int sqlerrcode)
Definition: elog.c:854
int errmsg(const char *fmt,...)
Definition: elog.c:1071
#define ereport(elevel,...)
Definition: elog.h:149
static BlockNumber ItemPointerGetBlockNumber(const ItemPointerData *pointer)
Definition: itemptr.h:103
static Size IndexTupleSize(const IndexTupleData *itup)
Definition: itup.h:71
#define BTREE_VERSION
Definition: nbtree.h:151
#define BTREE_NOVAC_VERSION
Definition: nbtree.h:153
#define BTMaxItemSizeNoHeapTid
Definition: nbtree.h:170
#define BTMaxItemSize
Definition: nbtree.h:165
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:6100

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,
BTReadPageState pstate,
bool  arrayKeys,
IndexTuple  tuple,
int  tupnatts 
)

Definition at line 2261 of file nbtutils.c.

2263{
2264 TupleDesc tupdesc = RelationGetDescr(scan->indexRelation);
2265 BTScanOpaque so = (BTScanOpaque) scan->opaque;
2266 ScanDirection dir = so->currPos.dir;
2267 int ikey = pstate->startikey;
2268 bool res;
2269
2270 Assert(BTreeTupleGetNAtts(tuple, scan->indexRelation) == tupnatts);
2271 Assert(!so->needPrimScan && !so->scanBehind && !so->oppositeDirCheck);
2272 Assert(arrayKeys || so->numArrayKeys == 0);
2273
2274 res = _bt_check_compare(scan, dir, tuple, tupnatts, tupdesc, arrayKeys,
2275 pstate->forcenonrequired, &pstate->continuescan,
2276 &ikey);
2277
2278 /*
2279 * If _bt_check_compare relied on the pstate.startikey optimization, call
2280 * again (in assert-enabled builds) to verify it didn't affect our answer.
2281 *
2282 * Note: we can't do this when !pstate.forcenonrequired, since any arrays
2283 * before pstate.startikey won't have advanced on this page at all.
2284 */
2285 Assert(!pstate->forcenonrequired || arrayKeys);
2286#ifdef USE_ASSERT_CHECKING
2287 if (pstate->startikey > 0 && !pstate->forcenonrequired)
2288 {
2289 bool dres,
2290 dcontinuescan;
2291 int dikey = 0;
2292
2293 /* Pass arrayKeys=false to avoid array side-effects */
2294 dres = _bt_check_compare(scan, dir, tuple, tupnatts, tupdesc, false,
2295 pstate->forcenonrequired, &dcontinuescan,
2296 &dikey);
2297 Assert(res == dres);
2298 Assert(pstate->continuescan == dcontinuescan);
2299
2300 /*
2301 * Should also get the same ikey result. We need a slightly weaker
2302 * assertion during arrayKeys calls, since they might be using an
2303 * array that couldn't be marked required during preprocessing.
2304 */
2305 Assert(arrayKeys || ikey == dikey);
2306 Assert(ikey <= dikey);
2307 }
2308#endif
2309
2310 /*
2311 * Only one _bt_check_compare call is required in the common case where
2312 * there are no equality strategy array scan keys. Otherwise we can only
2313 * accept _bt_check_compare's answer unreservedly when it didn't set
2314 * pstate.continuescan=false.
2315 */
2316 if (!arrayKeys || pstate->continuescan)
2317 return res;
2318
2319 /*
2320 * _bt_check_compare call set continuescan=false in the presence of
2321 * equality type array keys. This could mean that the tuple is just past
2322 * the end of matches for the current array keys.
2323 *
2324 * It's also possible that the scan is still _before_ the _start_ of
2325 * tuples matching the current set of array keys. Check for that first.
2326 */
2327 Assert(!pstate->forcenonrequired);
2328 if (_bt_tuple_before_array_skeys(scan, dir, tuple, tupdesc, tupnatts, true,
2329 ikey, NULL))
2330 {
2331 /* Override _bt_check_compare, continue primitive scan */
2332 pstate->continuescan = true;
2333
2334 /*
2335 * We will end up here repeatedly given a group of tuples > the
2336 * previous array keys and < the now-current keys (for a backwards
2337 * scan it's just the same, though the operators swap positions).
2338 *
2339 * We must avoid allowing this linear search process to scan very many
2340 * tuples from well before the start of tuples matching the current
2341 * array keys (or from well before the point where we'll once again
2342 * have to advance the scan's array keys).
2343 *
2344 * We keep the overhead under control by speculatively "looking ahead"
2345 * to later still-unscanned items from this same leaf page. We'll
2346 * only attempt this once the number of tuples that the linear search
2347 * process has examined starts to get out of hand.
2348 */
2349 pstate->rechecks++;
2351 {
2352 /* See if we should skip ahead within the current leaf page */
2353 _bt_checkkeys_look_ahead(scan, pstate, tupnatts, tupdesc);
2354
2355 /*
2356 * Might have set pstate.skip to a later page offset. When that
2357 * happens then _bt_readpage caller will inexpensively skip ahead
2358 * to a later tuple from the same page (the one just after the
2359 * tuple we successfully "looked ahead" to).
2360 */
2361 }
2362
2363 /* This indextuple doesn't match the current qual, in any case */
2364 return false;
2365 }
2366
2367 /*
2368 * Caller's tuple is >= the current set of array keys and other equality
2369 * constraint scan keys (or <= if this is a backwards scan). It's now
2370 * clear that we _must_ advance any required array keys in lockstep with
2371 * the scan.
2372 */
2373 return _bt_advance_array_keys(scan, pstate, tuple, tupnatts, tupdesc,
2374 ikey, true);
2375}
#define LOOK_AHEAD_REQUIRED_RECHECKS
Definition: nbtutils.c:27
static void _bt_checkkeys_look_ahead(IndexScanDesc scan, BTReadPageState *pstate, int tupnatts, TupleDesc tupdesc)
Definition: nbtutils.c:3217
#define RelationGetDescr(relation)
Definition: rel.h:542
bool forcenonrequired
Definition: nbtree.h:1109

References _bt_advance_array_keys(), _bt_check_compare(), _bt_checkkeys_look_ahead(), _bt_tuple_before_array_skeys(), Assert(), BTreeTupleGetNAtts, BTReadPageState::continuescan, BTScanOpaqueData::currPos, BTScanPosData::dir, BTReadPageState::forcenonrequired, IndexScanDescData::indexRelation, LOOK_AHEAD_REQUIRED_RECHECKS, BTScanOpaqueData::needPrimScan, BTScanOpaqueData::numArrayKeys, IndexScanDescData::opaque, BTScanOpaqueData::oppositeDirCheck, BTReadPageState::rechecks, RelationGetDescr, BTScanOpaqueData::scanBehind, and BTReadPageState::startikey.

Referenced by _bt_readpage().

◆ _bt_checkkeys_look_ahead()

static void _bt_checkkeys_look_ahead ( IndexScanDesc  scan,
BTReadPageState pstate,
int  tupnatts,
TupleDesc  tupdesc 
)
static

Definition at line 3217 of file nbtutils.c.

3219{
3220 BTScanOpaque so = (BTScanOpaque) scan->opaque;
3221 ScanDirection dir = so->currPos.dir;
3222 OffsetNumber aheadoffnum;
3223 IndexTuple ahead;
3224
3225 Assert(!pstate->forcenonrequired);
3226
3227 /* Avoid looking ahead when comparing the page high key */
3228 if (pstate->offnum < pstate->minoff)
3229 return;
3230
3231 /*
3232 * Don't look ahead when there aren't enough tuples remaining on the page
3233 * (in the current scan direction) for it to be worth our while
3234 */
3235 if (ScanDirectionIsForward(dir) &&
3236 pstate->offnum >= pstate->maxoff - LOOK_AHEAD_DEFAULT_DISTANCE)
3237 return;
3238 else if (ScanDirectionIsBackward(dir) &&
3239 pstate->offnum <= pstate->minoff + LOOK_AHEAD_DEFAULT_DISTANCE)
3240 return;
3241
3242 /*
3243 * The look ahead distance starts small, and ramps up as each call here
3244 * allows _bt_readpage to skip over more tuples
3245 */
3246 if (!pstate->targetdistance)
3248 else if (pstate->targetdistance < MaxIndexTuplesPerPage / 2)
3249 pstate->targetdistance *= 2;
3250
3251 /* Don't read past the end (or before the start) of the page, though */
3252 if (ScanDirectionIsForward(dir))
3253 aheadoffnum = Min((int) pstate->maxoff,
3254 (int) pstate->offnum + pstate->targetdistance);
3255 else
3256 aheadoffnum = Max((int) pstate->minoff,
3257 (int) pstate->offnum - pstate->targetdistance);
3258
3259 ahead = (IndexTuple) PageGetItem(pstate->page,
3260 PageGetItemId(pstate->page, aheadoffnum));
3261 if (_bt_tuple_before_array_skeys(scan, dir, ahead, tupdesc, tupnatts,
3262 false, 0, NULL))
3263 {
3264 /*
3265 * Success -- instruct _bt_readpage to skip ahead to very next tuple
3266 * after the one we determined was still before the current array keys
3267 */
3268 if (ScanDirectionIsForward(dir))
3269 pstate->skip = aheadoffnum + 1;
3270 else
3271 pstate->skip = aheadoffnum - 1;
3272 }
3273 else
3274 {
3275 /*
3276 * Failure -- "ahead" tuple is too far ahead (we were too aggressive).
3277 *
3278 * Reset the number of rechecks, and aggressively reduce the target
3279 * distance (we're much more aggressive here than we were when the
3280 * distance was initially ramped up).
3281 */
3282 pstate->rechecks = 0;
3283 pstate->targetdistance = Max(pstate->targetdistance / 8, 1);
3284 }
3285}
#define Min(x, y)
Definition: c.h:975
#define Max(x, y)
Definition: c.h:969
#define MaxIndexTuplesPerPage
Definition: itup.h:181
#define LOOK_AHEAD_DEFAULT_DISTANCE
Definition: nbtutils.c:28
uint16 OffsetNumber
Definition: off.h:24
OffsetNumber minoff
Definition: nbtree.h:1104
OffsetNumber offnum
Definition: nbtree.h:1113

References _bt_tuple_before_array_skeys(), Assert(), BTScanOpaqueData::currPos, BTScanPosData::dir, BTReadPageState::forcenonrequired, LOOK_AHEAD_DEFAULT_DISTANCE, Max, MaxIndexTuplesPerPage, BTReadPageState::maxoff, Min, BTReadPageState::minoff, BTReadPageState::offnum, IndexScanDescData::opaque, BTReadPageState::page, PageGetItem(), PageGetItemId(), BTReadPageState::rechecks, ScanDirectionIsBackward, ScanDirectionIsForward, BTReadPageState::skip, and BTReadPageState::targetdistance.

Referenced by _bt_checkkeys().

◆ _bt_compare_array_skey()

static int32 _bt_compare_array_skey ( FmgrInfo orderproc,
Datum  tupdatum,
bool  tupnull,
Datum  arrdatum,
ScanKey  cur 
)
inlinestatic

Definition at line 216 of file nbtutils.c.

219{
220 int32 result = 0;
221
222 Assert(cur->sk_strategy == BTEqualStrategyNumber);
223 Assert(!(cur->sk_flags & (SK_BT_MINVAL | SK_BT_MAXVAL)));
224
225 if (tupnull) /* NULL tupdatum */
226 {
227 if (cur->sk_flags & SK_ISNULL)
228 result = 0; /* NULL "=" NULL */
229 else if (cur->sk_flags & SK_BT_NULLS_FIRST)
230 result = -1; /* NULL "<" NOT_NULL */
231 else
232 result = 1; /* NULL ">" NOT_NULL */
233 }
234 else if (cur->sk_flags & SK_ISNULL) /* NOT_NULL tupdatum, NULL arrdatum */
235 {
236 if (cur->sk_flags & SK_BT_NULLS_FIRST)
237 result = 1; /* NOT_NULL ">" NULL */
238 else
239 result = -1; /* NOT_NULL "<" NULL */
240 }
241 else
242 {
243 /*
244 * Like _bt_compare, we need to be careful of cross-type comparisons,
245 * so the left value has to be the value that came from an index tuple
246 */
247 result = DatumGetInt32(FunctionCall2Coll(orderproc, cur->sk_collation,
248 tupdatum, arrdatum));
249
250 /*
251 * We flip the sign by following the obvious rule: flip whenever the
252 * column is a DESC column.
253 *
254 * _bt_compare does it the wrong way around (flip when *ASC*) in order
255 * to compensate for passing its orderproc arguments backwards. We
256 * don't need to play these games because we find it natural to pass
257 * tupdatum as the left value (and arrdatum as the right value).
258 */
259 if (cur->sk_flags & SK_BT_DESC)
260 INVERT_COMPARE_RESULT(result);
261 }
262
263 return result;
264}

References Assert(), BTEqualStrategyNumber, cur, DatumGetInt32(), FunctionCall2Coll(), INVERT_COMPARE_RESULT, SK_BT_DESC, SK_BT_MAXVAL, SK_BT_MINVAL, SK_BT_NULLS_FIRST, and SK_ISNULL.

Referenced by _bt_advance_array_keys(), _bt_binsrch_array_skey(), and _bt_tuple_before_array_skeys().

◆ _bt_end_vacuum()

void _bt_end_vacuum ( Relation  rel)

Definition at line 3627 of file nbtutils.c.

3628{
3629 int i;
3630
3631 LWLockAcquire(BtreeVacuumLock, LW_EXCLUSIVE);
3632
3633 /* Find the array entry */
3634 for (i = 0; i < btvacinfo->num_vacuums; i++)
3635 {
3636 BTOneVacInfo *vac = &btvacinfo->vacuums[i];
3637
3638 if (vac->relid.relId == rel->rd_lockInfo.lockRelId.relId &&
3639 vac->relid.dbId == rel->rd_lockInfo.lockRelId.dbId)
3640 {
3641 /* Remove it by shifting down the last entry */
3642 *vac = btvacinfo->vacuums[btvacinfo->num_vacuums - 1];
3644 break;
3645 }
3646 }
3647
3648 LWLockRelease(BtreeVacuumLock);
3649}
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1182
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1902
@ LW_EXCLUSIVE
Definition: lwlock.h:114
static BTVacInfo * btvacinfo
Definition: nbtutils.c:3523
LockRelId relid
Definition: nbtutils.c:3511
int num_vacuums
Definition: nbtutils.c:3518
BTOneVacInfo vacuums[FLEXIBLE_ARRAY_MEMBER]
Definition: nbtutils.c:3520
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 3655 of file nbtutils.c.

3656{
3658}
void _bt_end_vacuum(Relation rel)
Definition: nbtutils.c:3627
void * arg

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

Referenced by btbulkdelete().

◆ _bt_freestack()

void _bt_freestack ( BTStack  stack)

Definition at line 187 of file nbtutils.c.

188{
189 BTStack ostack;
190
191 while (stack != NULL)
192 {
193 ostack = stack;
194 stack = stack->bts_parent;
195 pfree(ostack);
196 }
197}
struct BTStackData * bts_parent
Definition: nbtree.h:747

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

3946{
3947 int nkeyatts = IndexRelationGetNumberOfKeyAttributes(rel);
3948 TupleDesc itupdesc = RelationGetDescr(rel);
3949 int keepnatts;
3950 ScanKey scankey;
3951
3952 /*
3953 * _bt_compare() treats truncated key attributes as having the value minus
3954 * infinity, which would break searches within !heapkeyspace indexes. We
3955 * must still truncate away non-key attribute values, though.
3956 */
3957 if (!itup_key->heapkeyspace)
3958 return nkeyatts;
3959
3960 scankey = itup_key->scankeys;
3961 keepnatts = 1;
3962 for (int attnum = 1; attnum <= nkeyatts; attnum++, scankey++)
3963 {
3964 Datum datum1,
3965 datum2;
3966 bool isNull1,
3967 isNull2;
3968
3969 datum1 = index_getattr(lastleft, attnum, itupdesc, &isNull1);
3970 datum2 = index_getattr(firstright, attnum, itupdesc, &isNull2);
3971
3972 if (isNull1 != isNull2)
3973 break;
3974
3975 if (!isNull1 &&
3977 scankey->sk_collation,
3978 datum1,
3979 datum2)) != 0)
3980 break;
3981
3982 keepnatts++;
3983 }
3984
3985 /*
3986 * Assert that _bt_keep_natts_fast() agrees with us in passing. This is
3987 * expected in an allequalimage index.
3988 */
3989 Assert(!itup_key->allequalimage ||
3990 keepnatts == _bt_keep_natts_fast(rel, lastleft, firstright));
3991
3992 return keepnatts;
3993}
int _bt_keep_natts_fast(Relation rel, IndexTuple lastleft, IndexTuple firstright)
Definition: nbtutils.c:4018
int16 attnum
Definition: pg_attribute.h:74
bool allequalimage
Definition: nbtree.h:798
bool heapkeyspace
Definition: nbtree.h:797
ScanKeyData scankeys[INDEX_MAX_KEYS]
Definition: nbtree.h:804

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

4019{
4020 TupleDesc itupdesc = RelationGetDescr(rel);
4022 int keepnatts;
4023
4024 keepnatts = 1;
4025 for (int attnum = 1; attnum <= keysz; attnum++)
4026 {
4027 Datum datum1,
4028 datum2;
4029 bool isNull1,
4030 isNull2;
4031 CompactAttribute *att;
4032
4033 datum1 = index_getattr(lastleft, attnum, itupdesc, &isNull1);
4034 datum2 = index_getattr(firstright, attnum, itupdesc, &isNull2);
4035 att = TupleDescCompactAttr(itupdesc, attnum - 1);
4036
4037 if (isNull1 != isNull2)
4038 break;
4039
4040 if (!isNull1 &&
4041 !datum_image_eq(datum1, datum2, att->attbyval, att->attlen))
4042 break;
4043
4044 keepnatts++;
4045 }
4046
4047 return keepnatts;
4048}
bool datum_image_eq(Datum value1, Datum value2, bool typByVal, int typLen)
Definition: datum.c:266
int16 attlen
Definition: tupdesc.h:71
static CompactAttribute * TupleDescCompactAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:175

References CompactAttribute::attbyval, CompactAttribute::attlen, attnum, datum_image_eq(), index_getattr(), IndexRelationGetNumberOfKeyAttributes, RelationGetDescr, and TupleDescCompactAttr().

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

◆ _bt_killitems()

void _bt_killitems ( IndexScanDesc  scan)

Definition at line 3319 of file nbtutils.c.

3320{
3321 BTScanOpaque so = (BTScanOpaque) scan->opaque;
3322 Page page;
3323 BTPageOpaque opaque;
3324 OffsetNumber minoff;
3325 OffsetNumber maxoff;
3326 int i;
3327 int numKilled = so->numKilled;
3328 bool killedsomething = false;
3329 bool droppedpin PG_USED_FOR_ASSERTS_ONLY;
3330
3332
3333 /*
3334 * Always reset the scan state, so we don't look for same items on other
3335 * pages.
3336 */
3337 so->numKilled = 0;
3338
3339 if (BTScanPosIsPinned(so->currPos))
3340 {
3341 /*
3342 * We have held the pin on this page since we read the index tuples,
3343 * so all we need to do is lock it. The pin will have prevented
3344 * re-use of any TID on the page, so there is no need to check the
3345 * LSN.
3346 */
3347 droppedpin = false;
3349
3350 page = BufferGetPage(so->currPos.buf);
3351 }
3352 else
3353 {
3354 Buffer buf;
3355
3356 droppedpin = true;
3357 /* Attempt to re-read the buffer, getting pin and lock. */
3359
3360 page = BufferGetPage(buf);
3361 if (BufferGetLSNAtomic(buf) == so->currPos.lsn)
3362 so->currPos.buf = buf;
3363 else
3364 {
3365 /* Modified while not pinned means hinting is not safe. */
3367 return;
3368 }
3369 }
3370
3371 opaque = BTPageGetOpaque(page);
3372 minoff = P_FIRSTDATAKEY(opaque);
3373 maxoff = PageGetMaxOffsetNumber(page);
3374
3375 for (i = 0; i < numKilled; i++)
3376 {
3377 int itemIndex = so->killedItems[i];
3378 BTScanPosItem *kitem = &so->currPos.items[itemIndex];
3379 OffsetNumber offnum = kitem->indexOffset;
3380
3381 Assert(itemIndex >= so->currPos.firstItem &&
3382 itemIndex <= so->currPos.lastItem);
3383 if (offnum < minoff)
3384 continue; /* pure paranoia */
3385 while (offnum <= maxoff)
3386 {
3387 ItemId iid = PageGetItemId(page, offnum);
3388 IndexTuple ituple = (IndexTuple) PageGetItem(page, iid);
3389 bool killtuple = false;
3390
3391 if (BTreeTupleIsPosting(ituple))
3392 {
3393 int pi = i + 1;
3394 int nposting = BTreeTupleGetNPosting(ituple);
3395 int j;
3396
3397 /*
3398 * We rely on the convention that heap TIDs in the scanpos
3399 * items array are stored in ascending heap TID order for a
3400 * group of TIDs that originally came from a posting list
3401 * tuple. This convention even applies during backwards
3402 * scans, where returning the TIDs in descending order might
3403 * seem more natural. This is about effectiveness, not
3404 * correctness.
3405 *
3406 * Note that the page may have been modified in almost any way
3407 * since we first read it (in the !droppedpin case), so it's
3408 * possible that this posting list tuple wasn't a posting list
3409 * tuple when we first encountered its heap TIDs.
3410 */
3411 for (j = 0; j < nposting; j++)
3412 {
3413 ItemPointer item = BTreeTupleGetPostingN(ituple, j);
3414
3415 if (!ItemPointerEquals(item, &kitem->heapTid))
3416 break; /* out of posting list loop */
3417
3418 /*
3419 * kitem must have matching offnum when heap TIDs match,
3420 * though only in the common case where the page can't
3421 * have been concurrently modified
3422 */
3423 Assert(kitem->indexOffset == offnum || !droppedpin);
3424
3425 /*
3426 * Read-ahead to later kitems here.
3427 *
3428 * We rely on the assumption that not advancing kitem here
3429 * will prevent us from considering the posting list tuple
3430 * fully dead by not matching its next heap TID in next
3431 * loop iteration.
3432 *
3433 * If, on the other hand, this is the final heap TID in
3434 * the posting list tuple, then tuple gets killed
3435 * regardless (i.e. we handle the case where the last
3436 * kitem is also the last heap TID in the last index tuple
3437 * correctly -- posting tuple still gets killed).
3438 */
3439 if (pi < numKilled)
3440 kitem = &so->currPos.items[so->killedItems[pi++]];
3441 }
3442
3443 /*
3444 * Don't bother advancing the outermost loop's int iterator to
3445 * avoid processing killed items that relate to the same
3446 * offnum/posting list tuple. This micro-optimization hardly
3447 * seems worth it. (Further iterations of the outermost loop
3448 * will fail to match on this same posting list's first heap
3449 * TID instead, so we'll advance to the next offnum/index
3450 * tuple pretty quickly.)
3451 */
3452 if (j == nposting)
3453 killtuple = true;
3454 }
3455 else if (ItemPointerEquals(&ituple->t_tid, &kitem->heapTid))
3456 killtuple = true;
3457
3458 /*
3459 * Mark index item as dead, if it isn't already. Since this
3460 * happens while holding a buffer lock possibly in shared mode,
3461 * it's possible that multiple processes attempt to do this
3462 * simultaneously, leading to multiple full-page images being sent
3463 * to WAL (if wal_log_hints or data checksums are enabled), which
3464 * is undesirable.
3465 */
3466 if (killtuple && !ItemIdIsDead(iid))
3467 {
3468 /* found the item/all posting list items */
3469 ItemIdMarkDead(iid);
3470 killedsomething = true;
3471 break; /* out of inner search loop */
3472 }
3473 offnum = OffsetNumberNext(offnum);
3474 }
3475 }
3476
3477 /*
3478 * Since this can be redone later if needed, mark as dirty hint.
3479 *
3480 * Whenever we mark anything LP_DEAD, we also set the page's
3481 * BTP_HAS_GARBAGE flag, which is likewise just a hint. (Note that we
3482 * only rely on the page-level flag in !heapkeyspace indexes.)
3483 */
3484 if (killedsomething)
3485 {
3486 opaque->btpo_flags |= BTP_HAS_GARBAGE;
3487 MarkBufferDirtyHint(so->currPos.buf, true);
3488 }
3489
3491}
int Buffer
Definition: buf.h:23
XLogRecPtr BufferGetLSNAtomic(Buffer buffer)
Definition: bufmgr.c:4493
void MarkBufferDirtyHint(Buffer buffer, bool buffer_std)
Definition: bufmgr.c:5437
static Page BufferGetPage(Buffer buffer)
Definition: bufmgr.h:417
PageData * Page
Definition: bufpage.h:82
int j
Definition: isn.c:78
#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:1004
static uint16 BTreeTupleGetNPosting(IndexTuple posting)
Definition: nbtree.h:519
#define BTP_HAS_GARBAGE
Definition: nbtree.h:83
#define BTScanPosIsValid(scanpos)
Definition: nbtree.h:1021
static ItemPointer BTreeTupleGetPostingN(IndexTuple posting, int n)
Definition: nbtree.h:545
#define BT_READ
Definition: nbtree.h:730
#define OffsetNumberNext(offsetNumber)
Definition: off.h:52
static char * buf
Definition: pg_test_fsync.c:72
int * killedItems
Definition: nbtree.h:1071
Buffer buf
Definition: nbtree.h:964
int firstItem
Definition: nbtree.h:995
BTScanPosItem items[MaxTIDsPerBTreePage]
Definition: nbtree.h:999
XLogRecPtr lsn
Definition: nbtree.h:970
ItemPointerData heapTid
Definition: nbtree.h:957
OffsetNumber indexOffset
Definition: nbtree.h:958

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_mkscankey()

BTScanInsert _bt_mkscankey ( Relation  rel,
IndexTuple  itup 
)

Definition at line 95 of file nbtutils.c.

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

static bool _bt_oppodir_checkkeys ( IndexScanDesc  scan,
ScanDirection  dir,
IndexTuple  finaltup 
)
static

Definition at line 2428 of file nbtutils.c.

2430{
2431 Relation rel = scan->indexRelation;
2432 TupleDesc tupdesc = RelationGetDescr(rel);
2433 BTScanOpaque so = (BTScanOpaque) scan->opaque;
2434 int nfinaltupatts = BTreeTupleGetNAtts(finaltup, rel);
2435 bool continuescan;
2436 ScanDirection flipped = -dir;
2437 int ikey = 0;
2438
2439 Assert(so->numArrayKeys);
2440
2441 _bt_check_compare(scan, flipped, finaltup, nfinaltupatts, tupdesc, false,
2442 false, &continuescan,
2443 &ikey);
2444
2445 if (!continuescan && so->keyData[ikey].sk_strategy != BTEqualStrategyNumber)
2446 return false;
2447
2448 return true;
2449}

References _bt_check_compare(), Assert(), BTEqualStrategyNumber, BTreeTupleGetNAtts, IndexScanDescData::indexRelation, BTScanOpaqueData::keyData, BTScanOpaqueData::numArrayKeys, IndexScanDescData::opaque, RelationGetDescr, and ScanKeyData::sk_strategy.

Referenced by _bt_advance_array_keys(), and _bt_scanbehind_checkkeys().

◆ _bt_rewind_nonrequired_arrays()

static void _bt_rewind_nonrequired_arrays ( IndexScanDesc  scan,
ScanDirection  dir 
)
static

Definition at line 1076 of file nbtutils.c.

1077{
1078 Relation rel = scan->indexRelation;
1079 BTScanOpaque so = (BTScanOpaque) scan->opaque;
1080 int arrayidx = 0;
1081
1082 for (int ikey = 0; ikey < so->numberOfKeys; ikey++)
1083 {
1084 ScanKey cur = so->keyData + ikey;
1085 BTArrayKeyInfo *array = NULL;
1086
1087 if (!(cur->sk_flags & SK_SEARCHARRAY) ||
1088 cur->sk_strategy != BTEqualStrategyNumber)
1089 continue;
1090
1091 array = &so->arrayKeys[arrayidx++];
1092 Assert(array->scan_key == ikey);
1093
1094 if ((cur->sk_flags & (SK_BT_REQFWD | SK_BT_REQBKWD)))
1095 continue;
1096
1097 Assert(array->num_elems != -1); /* No non-required skip arrays */
1098
1099 _bt_array_set_low_or_high(rel, cur, array,
1101 }
1102}

References _bt_array_set_low_or_high(), BTScanOpaqueData::arrayKeys, Assert(), BTEqualStrategyNumber, cur, for(), IndexScanDescData::indexRelation, BTScanOpaqueData::keyData, BTArrayKeyInfo::num_elems, BTScanOpaqueData::numberOfKeys, IndexScanDescData::opaque, BTArrayKeyInfo::scan_key, ScanDirectionIsForward, SK_BT_REQBKWD, SK_BT_REQFWD, and SK_SEARCHARRAY.

Referenced by _bt_advance_array_keys().

◆ _bt_scanbehind_checkkeys()

bool _bt_scanbehind_checkkeys ( IndexScanDesc  scan,
ScanDirection  dir,
IndexTuple  finaltup 
)

Definition at line 2389 of file nbtutils.c.

2391{
2392 Relation rel = scan->indexRelation;
2393 TupleDesc tupdesc = RelationGetDescr(rel);
2394 BTScanOpaque so = (BTScanOpaque) scan->opaque;
2395 int nfinaltupatts = BTreeTupleGetNAtts(finaltup, rel);
2396
2397 Assert(so->numArrayKeys);
2398
2399 if (_bt_tuple_before_array_skeys(scan, dir, finaltup, tupdesc,
2400 nfinaltupatts, false, 0, NULL))
2401 return false;
2402
2403 if (!so->oppositeDirCheck)
2404 return true;
2405
2406 return _bt_oppodir_checkkeys(scan, dir, finaltup);
2407}

References _bt_oppodir_checkkeys(), _bt_tuple_before_array_skeys(), Assert(), BTreeTupleGetNAtts, IndexScanDescData::indexRelation, BTScanOpaqueData::numArrayKeys, IndexScanDescData::opaque, BTScanOpaqueData::oppositeDirCheck, and RelationGetDescr.

Referenced by _bt_readpage().

◆ _bt_set_startikey()

void _bt_set_startikey ( IndexScanDesc  scan,
BTReadPageState pstate 
)

Definition at line 2485 of file nbtutils.c.

2486{
2487 BTScanOpaque so = (BTScanOpaque) scan->opaque;
2488 Relation rel = scan->indexRelation;
2489 TupleDesc tupdesc = RelationGetDescr(rel);
2490 ItemId iid;
2491 IndexTuple firsttup,
2492 lasttup;
2493 int startikey = 0,
2494 arrayidx = 0,
2495 firstchangingattnum;
2496 bool start_past_saop_eq = false;
2497
2498 Assert(!so->scanBehind);
2499 Assert(pstate->minoff < pstate->maxoff);
2500 Assert(!pstate->firstpage);
2501 Assert(pstate->startikey == 0);
2502 Assert(!so->numArrayKeys || pstate->finaltup ||
2503 P_RIGHTMOST(BTPageGetOpaque(pstate->page)) ||
2504 P_LEFTMOST(BTPageGetOpaque(pstate->page)));
2505
2506 if (so->numberOfKeys == 0)
2507 return;
2508
2509 /* minoff is an offset to the lowest non-pivot tuple on the page */
2510 iid = PageGetItemId(pstate->page, pstate->minoff);
2511 firsttup = (IndexTuple) PageGetItem(pstate->page, iid);
2512
2513 /* maxoff is an offset to the highest non-pivot tuple on the page */
2514 iid = PageGetItemId(pstate->page, pstate->maxoff);
2515 lasttup = (IndexTuple) PageGetItem(pstate->page, iid);
2516
2517 /* Determine the first attribute whose values change on caller's page */
2518 firstchangingattnum = _bt_keep_natts_fast(rel, firsttup, lasttup);
2519
2520 for (; startikey < so->numberOfKeys; startikey++)
2521 {
2522 ScanKey key = so->keyData + startikey;
2523 BTArrayKeyInfo *array;
2524 Datum firstdatum,
2525 lastdatum;
2526 bool firstnull,
2527 lastnull;
2528 int32 result;
2529
2530 /*
2531 * Determine if it's safe to set pstate.startikey to an offset to a
2532 * key that comes after this key, by examining this key
2533 */
2534 if (!(key->sk_flags & (SK_BT_REQFWD | SK_BT_REQBKWD)))
2535 {
2536 /* Scan key isn't marked required (corner case) */
2537 Assert(!(key->sk_flags & SK_ROW_HEADER));
2538 break; /* unsafe */
2539 }
2540 if (key->sk_flags & SK_ROW_HEADER)
2541 {
2542 /*
2543 * Can't let pstate.startikey get set to an ikey beyond a
2544 * RowCompare inequality
2545 */
2546 break; /* unsafe */
2547 }
2548 if (key->sk_strategy != BTEqualStrategyNumber)
2549 {
2550 /*
2551 * Scalar inequality key.
2552 *
2553 * It's definitely safe for _bt_checkkeys to avoid assessing this
2554 * inequality when the page's first and last non-pivot tuples both
2555 * satisfy the inequality (since the same must also be true of all
2556 * the tuples in between these two).
2557 *
2558 * Unlike the "=" case, it doesn't matter if this attribute has
2559 * more than one distinct value (though it _is_ necessary for any
2560 * and all _prior_ attributes to contain no more than one distinct
2561 * value amongst all of the tuples from pstate.page).
2562 */
2563 if (key->sk_attno > firstchangingattnum) /* >, not >= */
2564 break; /* unsafe, preceding attr has multiple
2565 * distinct values */
2566
2567 firstdatum = index_getattr(firsttup, key->sk_attno, tupdesc, &firstnull);
2568 lastdatum = index_getattr(lasttup, key->sk_attno, tupdesc, &lastnull);
2569
2570 if (key->sk_flags & SK_ISNULL)
2571 {
2572 /* IS NOT NULL key */
2573 Assert(key->sk_flags & SK_SEARCHNOTNULL);
2574
2575 if (firstnull || lastnull)
2576 break; /* unsafe */
2577
2578 /* Safe, IS NOT NULL key satisfied by every tuple */
2579 continue;
2580 }
2581
2582 /* Test firsttup */
2583 if (firstnull ||
2585 key->sk_collation, firstdatum,
2586 key->sk_argument)))
2587 break; /* unsafe */
2588
2589 /* Test lasttup */
2590 if (lastnull ||
2592 key->sk_collation, lastdatum,
2593 key->sk_argument)))
2594 break; /* unsafe */
2595
2596 /* Safe, scalar inequality satisfied by every tuple */
2597 continue;
2598 }
2599
2600 /* Some = key (could be a scalar = key, could be an array = key) */
2601 Assert(key->sk_strategy == BTEqualStrategyNumber);
2602
2603 if (!(key->sk_flags & SK_SEARCHARRAY))
2604 {
2605 /*
2606 * Scalar = key (possibly an IS NULL key).
2607 *
2608 * It is unsafe to set pstate.startikey to an ikey beyond this
2609 * key, unless the = key is satisfied by every possible tuple on
2610 * the page (possible only when attribute has just one distinct
2611 * value among all tuples on the page).
2612 */
2613 if (key->sk_attno >= firstchangingattnum)
2614 break; /* unsafe, multiple distinct attr values */
2615
2616 firstdatum = index_getattr(firsttup, key->sk_attno, tupdesc,
2617 &firstnull);
2618 if (key->sk_flags & SK_ISNULL)
2619 {
2620 /* IS NULL key */
2621 Assert(key->sk_flags & SK_SEARCHNULL);
2622
2623 if (!firstnull)
2624 break; /* unsafe */
2625
2626 /* Safe, IS NULL key satisfied by every tuple */
2627 continue;
2628 }
2629 if (firstnull ||
2631 key->sk_collation, firstdatum,
2632 key->sk_argument)))
2633 break; /* unsafe */
2634
2635 /* Safe, scalar = key satisfied by every tuple */
2636 continue;
2637 }
2638
2639 /* = array key (could be a SAOP array, could be a skip array) */
2640 array = &so->arrayKeys[arrayidx++];
2641 Assert(array->scan_key == startikey);
2642 if (array->num_elems != -1)
2643 {
2644 /*
2645 * SAOP array = key.
2646 *
2647 * Handle this like we handle scalar = keys (though binary search
2648 * for a matching element, to avoid relying on key's sk_argument).
2649 */
2650 if (key->sk_attno >= firstchangingattnum)
2651 break; /* unsafe, multiple distinct attr values */
2652
2653 firstdatum = index_getattr(firsttup, key->sk_attno, tupdesc,
2654 &firstnull);
2655 _bt_binsrch_array_skey(&so->orderProcs[startikey],
2657 firstdatum, firstnull, array, key,
2658 &result);
2659 if (result != 0)
2660 break; /* unsafe */
2661
2662 /* Safe, SAOP = key satisfied by every tuple */
2663 start_past_saop_eq = true;
2664 continue;
2665 }
2666
2667 /*
2668 * Skip array = key
2669 */
2670 Assert(key->sk_flags & SK_BT_SKIP);
2671 if (array->null_elem)
2672 {
2673 /*
2674 * Non-range skip array = key.
2675 *
2676 * Safe, non-range skip array "satisfied" by every tuple on page
2677 * (safe even when "key->sk_attno > firstchangingattnum").
2678 */
2679 continue;
2680 }
2681
2682 /*
2683 * Range skip array = key.
2684 *
2685 * Handle this like we handle scalar inequality keys (but avoid using
2686 * key's sk_argument directly, as in the SAOP array case).
2687 */
2688 if (key->sk_attno > firstchangingattnum) /* >, not >= */
2689 break; /* unsafe, preceding attr has multiple
2690 * distinct values */
2691
2692 firstdatum = index_getattr(firsttup, key->sk_attno, tupdesc, &firstnull);
2693 lastdatum = index_getattr(lasttup, key->sk_attno, tupdesc, &lastnull);
2694
2695 /* Test firsttup */
2697 firstdatum, firstnull, array, key,
2698 &result);
2699 if (result != 0)
2700 break; /* unsafe */
2701
2702 /* Test lasttup */
2704 lastdatum, lastnull, array, key,
2705 &result);
2706 if (result != 0)
2707 break; /* unsafe */
2708
2709 /* Safe, range skip array satisfied by every tuple on page */
2710 }
2711
2712 /*
2713 * Use of forcenonrequired is typically undesirable, since it'll force
2714 * _bt_readpage caller to read every tuple on the page -- even though, in
2715 * general, it might well be possible to end the scan on an earlier tuple.
2716 * However, caller must use forcenonrequired when start_past_saop_eq=true,
2717 * since the usual required array behavior might fail to roll over to the
2718 * SAOP array.
2719 *
2720 * We always prefer forcenonrequired=true during scans with skip arrays
2721 * (except on the first page of each primitive index scan), though -- even
2722 * when "startikey == 0". That way, _bt_advance_array_keys's low-order
2723 * key precheck optimization can always be used (unless on the first page
2724 * of the scan). It seems slightly preferable to check more tuples when
2725 * that allows us to do significantly less skip array maintenance.
2726 */
2727 pstate->forcenonrequired = (start_past_saop_eq || so->skipScan);
2728 pstate->startikey = startikey;
2729
2730 /*
2731 * _bt_readpage caller is required to call _bt_checkkeys against page's
2732 * finaltup with forcenonrequired=false whenever we initially set
2733 * forcenonrequired=true. That way the scan's arrays will reliably track
2734 * its progress through the index's key space.
2735 *
2736 * We don't expect this when _bt_readpage caller has no finaltup due to
2737 * its page being the rightmost (or the leftmost, during backwards scans).
2738 * When we see that _bt_readpage has no finaltup, back out of everything.
2739 */
2740 Assert(!pstate->forcenonrequired || so->numArrayKeys);
2741 if (pstate->forcenonrequired && !pstate->finaltup)
2742 {
2743 pstate->forcenonrequired = false;
2744 pstate->startikey = 0;
2745 }
2746}
#define P_LEFTMOST(opaque)
Definition: nbtree.h:219
@ NoMovementScanDirection
Definition: sdir.h:27
@ ForwardScanDirection
Definition: sdir.h:28

References _bt_binsrch_array_skey(), _bt_binsrch_skiparray_skey(), _bt_keep_natts_fast(), BTScanOpaqueData::arrayKeys, Assert(), BTEqualStrategyNumber, BTPageGetOpaque, DatumGetBool(), BTReadPageState::finaltup, BTReadPageState::firstpage, BTReadPageState::forcenonrequired, ForwardScanDirection, FunctionCall2Coll(), index_getattr(), IndexScanDescData::indexRelation, sort-test::key, BTScanOpaqueData::keyData, BTReadPageState::maxoff, BTReadPageState::minoff, NoMovementScanDirection, BTArrayKeyInfo::null_elem, BTArrayKeyInfo::num_elems, BTScanOpaqueData::numArrayKeys, BTScanOpaqueData::numberOfKeys, IndexScanDescData::opaque, BTScanOpaqueData::orderProcs, P_LEFTMOST, P_RIGHTMOST, BTReadPageState::page, PageGetItem(), PageGetItemId(), RelationGetDescr, BTArrayKeyInfo::scan_key, BTScanOpaqueData::scanBehind, SK_BT_REQBKWD, SK_BT_REQFWD, SK_BT_SKIP, SK_ISNULL, SK_ROW_HEADER, SK_SEARCHARRAY, SK_SEARCHNOTNULL, SK_SEARCHNULL, BTScanOpaqueData::skipScan, and BTReadPageState::startikey.

Referenced by _bt_readpage().

◆ _bt_skiparray_set_element()

static void _bt_skiparray_set_element ( Relation  rel,
ScanKey  skey,
BTArrayKeyInfo array,
int32  set_elem_result,
Datum  tupdatum,
bool  tupnull 
)
static

Definition at line 550 of file nbtutils.c.

552{
553 Assert(skey->sk_flags & SK_BT_SKIP);
555
556 if (set_elem_result)
557 {
558 /* tupdatum/tupnull is out of the range of the skip array */
559 Assert(!array->null_elem);
560
561 _bt_array_set_low_or_high(rel, skey, array, set_elem_result < 0);
562 return;
563 }
564
565 /* Advance skip array to tupdatum (or tupnull) value */
566 if (unlikely(tupnull))
567 {
568 _bt_skiparray_set_isnull(rel, skey, array);
569 return;
570 }
571
572 /* Free memory previously allocated for sk_argument if needed */
573 if (!array->attbyval && skey->sk_argument)
575
576 /* tupdatum becomes new sk_argument/new current element */
577 skey->sk_flags &= ~(SK_SEARCHNULL | SK_ISNULL |
580 skey->sk_argument = datumCopy(tupdatum, array->attbyval, array->attlen);
581}

References _bt_array_set_low_or_high(), _bt_skiparray_set_isnull(), Assert(), BTArrayKeyInfo::attbyval, BTArrayKeyInfo::attlen, datumCopy(), DatumGetPointer(), BTArrayKeyInfo::null_elem, pfree(), ScanKeyData::sk_argument, SK_BT_MAXVAL, SK_BT_MINVAL, SK_BT_NEXT, SK_BT_PRIOR, SK_BT_SKIP, ScanKeyData::sk_flags, SK_ISNULL, SK_SEARCHARRAY, SK_SEARCHNULL, and unlikely.

Referenced by _bt_advance_array_keys().

◆ _bt_skiparray_set_isnull()

static void _bt_skiparray_set_isnull ( Relation  rel,
ScanKey  skey,
BTArrayKeyInfo array 
)
static

Definition at line 587 of file nbtutils.c.

588{
589 Assert(skey->sk_flags & SK_BT_SKIP);
591 Assert(array->null_elem && !array->low_compare && !array->high_compare);
592
593 /* Free memory previously allocated for sk_argument if needed */
594 if (!array->attbyval && skey->sk_argument)
596
597 /* NULL becomes new sk_argument/new current element */
598 skey->sk_argument = (Datum) 0;
599 skey->sk_flags &= ~(SK_BT_MINVAL | SK_BT_MAXVAL |
601 skey->sk_flags |= (SK_SEARCHNULL | SK_ISNULL);
602}

References Assert(), BTArrayKeyInfo::attbyval, DatumGetPointer(), BTArrayKeyInfo::high_compare, BTArrayKeyInfo::low_compare, BTArrayKeyInfo::null_elem, pfree(), ScanKeyData::sk_argument, SK_BT_MAXVAL, SK_BT_MINVAL, SK_BT_NEXT, SK_BT_PRIOR, SK_BT_SKIP, ScanKeyData::sk_flags, SK_ISNULL, SK_SEARCHARRAY, and SK_SEARCHNULL.

Referenced by _bt_array_decrement(), _bt_array_increment(), and _bt_skiparray_set_element().

◆ _bt_start_array_keys()

◆ _bt_start_prim_scan()

bool _bt_start_prim_scan ( IndexScanDesc  scan,
ScanDirection  dir 
)

Definition at line 1339 of file nbtutils.c.

1340{
1341 BTScanOpaque so = (BTScanOpaque) scan->opaque;
1342
1343 Assert(so->numArrayKeys);
1344
1345 so->scanBehind = so->oppositeDirCheck = false; /* reset */
1346
1347 /*
1348 * Array keys are advanced within _bt_checkkeys when the scan reaches the
1349 * leaf level (more precisely, they're advanced when the scan reaches the
1350 * end of each distinct set of array elements). This process avoids
1351 * repeat access to leaf pages (across multiple primitive index scans) by
1352 * advancing the scan's array keys when it allows the primitive index scan
1353 * to find nearby matching tuples (or when it eliminates ranges of array
1354 * key space that can't possibly be satisfied by any index tuple).
1355 *
1356 * _bt_checkkeys sets a simple flag variable to schedule another primitive
1357 * index scan. The flag tells us what to do.
1358 *
1359 * We cannot rely on _bt_first always reaching _bt_checkkeys. There are
1360 * various cases where that won't happen. For example, if the index is
1361 * completely empty, then _bt_first won't call _bt_readpage/_bt_checkkeys.
1362 * We also don't expect a call to _bt_checkkeys during searches for a
1363 * non-existent value that happens to be lower/higher than any existing
1364 * value in the index.
1365 *
1366 * We don't require special handling for these cases -- we don't need to
1367 * be explicitly instructed to _not_ perform another primitive index scan.
1368 * It's up to code under the control of _bt_first to always set the flag
1369 * when another primitive index scan will be required.
1370 *
1371 * This works correctly, even with the tricky cases listed above, which
1372 * all involve access to leaf pages "near the boundaries of the key space"
1373 * (whether it's from a leftmost/rightmost page, or an imaginary empty
1374 * leaf root page). If _bt_checkkeys cannot be reached by a primitive
1375 * index scan for one set of array keys, then it also won't be reached for
1376 * any later set ("later" in terms of the direction that we scan the index
1377 * and advance the arrays). The array keys won't have advanced in these
1378 * cases, but that's the correct behavior (even _bt_advance_array_keys
1379 * won't always advance the arrays at the point they become "exhausted").
1380 */
1381 if (so->needPrimScan)
1382 {
1383 Assert(_bt_verify_arrays_bt_first(scan, dir));
1384
1385 /*
1386 * Flag was set -- must call _bt_first again, which will reset the
1387 * scan's needPrimScan flag
1388 */
1389 return true;
1390 }
1391
1392 /* The top-level index scan ran out of tuples in this scan direction */
1393 if (scan->parallel_scan != NULL)
1394 _bt_parallel_done(scan);
1395
1396 return false;
1397}
void _bt_parallel_done(IndexScanDesc scan)
Definition: nbtree.c:949

References _bt_parallel_done(), Assert(), BTScanOpaqueData::needPrimScan, BTScanOpaqueData::numArrayKeys, IndexScanDescData::opaque, BTScanOpaqueData::oppositeDirCheck, IndexScanDescData::parallel_scan, and BTScanOpaqueData::scanBehind.

◆ _bt_start_vacuum()

BTCycleId _bt_start_vacuum ( Relation  rel)

Definition at line 3570 of file nbtutils.c.

3571{
3572 BTCycleId result;
3573 int i;
3574 BTOneVacInfo *vac;
3575
3576 LWLockAcquire(BtreeVacuumLock, LW_EXCLUSIVE);
3577
3578 /*
3579 * Assign the next cycle ID, being careful to avoid zero as well as the
3580 * reserved high values.
3581 */
3582 result = ++(btvacinfo->cycle_ctr);
3583 if (result == 0 || result > MAX_BT_CYCLE_ID)
3584 result = btvacinfo->cycle_ctr = 1;
3585
3586 /* Let's just make sure there's no entry already for this index */
3587 for (i = 0; i < btvacinfo->num_vacuums; i++)
3588 {
3589 vac = &btvacinfo->vacuums[i];
3590 if (vac->relid.relId == rel->rd_lockInfo.lockRelId.relId &&
3591 vac->relid.dbId == rel->rd_lockInfo.lockRelId.dbId)
3592 {
3593 /*
3594 * Unlike most places in the backend, we have to explicitly
3595 * release our LWLock before throwing an error. This is because
3596 * we expect _bt_end_vacuum() to be called before transaction
3597 * abort cleanup can run to release LWLocks.
3598 */
3599 LWLockRelease(BtreeVacuumLock);
3600 elog(ERROR, "multiple active vacuums for index \"%s\"",
3602 }
3603 }
3604
3605 /* OK, add an entry */
3607 {
3608 LWLockRelease(BtreeVacuumLock);
3609 elog(ERROR, "out of btvacinfo slots");
3610 }
3612 vac->relid = rel->rd_lockInfo.lockRelId;
3613 vac->cycleid = result;
3615
3616 LWLockRelease(BtreeVacuumLock);
3617 return result;
3618}
#define MAX_BT_CYCLE_ID
Definition: nbtree.h:94
uint16 BTCycleId
Definition: nbtree.h:30
BTCycleId cycleid
Definition: nbtutils.c:3512
BTCycleId cycle_ctr
Definition: nbtutils.c:3517
int max_vacuums
Definition: nbtutils.c:3519

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

3801{
3802 TupleDesc itupdesc = RelationGetDescr(rel);
3804 int keepnatts;
3805 IndexTuple pivot;
3806 IndexTuple tidpivot;
3807 ItemPointer pivotheaptid;
3808 Size newsize;
3809
3810 /*
3811 * We should only ever truncate non-pivot tuples from leaf pages. It's
3812 * never okay to truncate when splitting an internal page.
3813 */
3814 Assert(!BTreeTupleIsPivot(lastleft) && !BTreeTupleIsPivot(firstright));
3815
3816 /* Determine how many attributes must be kept in truncated tuple */
3817 keepnatts = _bt_keep_natts(rel, lastleft, firstright, itup_key);
3818
3819#ifdef DEBUG_NO_TRUNCATE
3820 /* Force truncation to be ineffective for testing purposes */
3821 keepnatts = nkeyatts + 1;
3822#endif
3823
3824 pivot = index_truncate_tuple(itupdesc, firstright,
3825 Min(keepnatts, nkeyatts));
3826
3827 if (BTreeTupleIsPosting(pivot))
3828 {
3829 /*
3830 * index_truncate_tuple() just returns a straight copy of firstright
3831 * when it has no attributes to truncate. When that happens, we may
3832 * need to truncate away a posting list here instead.
3833 */
3834 Assert(keepnatts == nkeyatts || keepnatts == nkeyatts + 1);
3836 pivot->t_info &= ~INDEX_SIZE_MASK;
3837 pivot->t_info |= MAXALIGN(BTreeTupleGetPostingOffset(firstright));
3838 }
3839
3840 /*
3841 * If there is a distinguishing key attribute within pivot tuple, we're
3842 * done
3843 */
3844 if (keepnatts <= nkeyatts)
3845 {
3846 BTreeTupleSetNAtts(pivot, keepnatts, false);
3847 return pivot;
3848 }
3849
3850 /*
3851 * We have to store a heap TID in the new pivot tuple, since no non-TID
3852 * key attribute value in firstright distinguishes the right side of the
3853 * split from the left side. nbtree conceptualizes this case as an
3854 * inability to truncate away any key attributes, since heap TID is
3855 * treated as just another key attribute (despite lacking a pg_attribute
3856 * entry).
3857 *
3858 * Use enlarged space that holds a copy of pivot. We need the extra space
3859 * to store a heap TID at the end (using the special pivot tuple
3860 * representation). Note that the original pivot already has firstright's
3861 * possible posting list/non-key attribute values removed at this point.
3862 */
3863 newsize = MAXALIGN(IndexTupleSize(pivot)) + MAXALIGN(sizeof(ItemPointerData));
3864 tidpivot = palloc0(newsize);
3865 memcpy(tidpivot, pivot, MAXALIGN(IndexTupleSize(pivot)));
3866 /* Cannot leak memory here */
3867 pfree(pivot);
3868
3869 /*
3870 * Store all of firstright's key attribute values plus a tiebreaker heap
3871 * TID value in enlarged pivot tuple
3872 */
3873 tidpivot->t_info &= ~INDEX_SIZE_MASK;
3874 tidpivot->t_info |= newsize;
3875 BTreeTupleSetNAtts(tidpivot, nkeyatts, true);
3876 pivotheaptid = BTreeTupleGetHeapTID(tidpivot);
3877
3878 /*
3879 * Lehman & Yao use lastleft as the leaf high key in all cases, but don't
3880 * consider suffix truncation. It seems like a good idea to follow that
3881 * example in cases where no truncation takes place -- use lastleft's heap
3882 * TID. (This is also the closest value to negative infinity that's
3883 * legally usable.)
3884 */
3885 ItemPointerCopy(BTreeTupleGetMaxHeapTID(lastleft), pivotheaptid);
3886
3887 /*
3888 * We're done. Assert() that heap TID invariants hold before returning.
3889 *
3890 * Lehman and Yao require that the downlink to the right page, which is to
3891 * be inserted into the parent page in the second phase of a page split be
3892 * a strict lower bound on items on the right page, and a non-strict upper
3893 * bound for items on the left page. Assert that heap TIDs follow these
3894 * invariants, since a heap TID value is apparently needed as a
3895 * tiebreaker.
3896 */
3897#ifndef DEBUG_NO_TRUNCATE
3899 BTreeTupleGetHeapTID(firstright)) < 0);
3900 Assert(ItemPointerCompare(pivotheaptid,
3901 BTreeTupleGetHeapTID(lastleft)) >= 0);
3902 Assert(ItemPointerCompare(pivotheaptid,
3903 BTreeTupleGetHeapTID(firstright)) < 0);
3904#else
3905
3906 /*
3907 * Those invariants aren't guaranteed to hold for lastleft + firstright
3908 * heap TID attribute values when they're considered here only because
3909 * DEBUG_NO_TRUNCATE is defined (a heap TID is probably not actually
3910 * needed as a tiebreaker). DEBUG_NO_TRUNCATE must therefore use a heap
3911 * TID value that always works as a strict lower bound for items to the
3912 * right. In particular, it must avoid using firstright's leading key
3913 * attribute values along with lastleft's heap TID value when lastleft's
3914 * TID happens to be greater than firstright's TID.
3915 */
3916 ItemPointerCopy(BTreeTupleGetHeapTID(firstright), pivotheaptid);
3917
3918 /*
3919 * Pivot heap TID should never be fully equal to firstright. Note that
3920 * the pivot heap TID will still end up equal to lastleft's heap TID when
3921 * that's the only usable value.
3922 */
3923 ItemPointerSetOffsetNumber(pivotheaptid,
3925 Assert(ItemPointerCompare(pivotheaptid,
3926 BTreeTupleGetHeapTID(firstright)) < 0);
3927#endif
3928
3929 return tidpivot;
3930}
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
void * palloc0(Size size)
Definition: mcxt.c:1975
static uint32 BTreeTupleGetPostingOffset(IndexTuple posting)
Definition: nbtree.h:530
static ItemPointer BTreeTupleGetMaxHeapTID(IndexTuple itup)
Definition: nbtree.h:665
static void BTreeTupleSetNAtts(IndexTuple itup, uint16 nkeyatts, bool heaptid)
Definition: nbtree.h:596
static int _bt_keep_natts(Relation rel, IndexTuple lastleft, IndexTuple firstright, BTScanInsert itup_key)
Definition: nbtutils.c:3944
#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_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_tuple_before_array_skeys()

static bool _bt_tuple_before_array_skeys ( IndexScanDesc  scan,
ScanDirection  dir,
IndexTuple  tuple,
TupleDesc  tupdesc,
int  tupnatts,
bool  readpagetup,
int  sktrig,
bool *  scanBehind 
)
static

Definition at line 1147 of file nbtutils.c.

1150{
1151 BTScanOpaque so = (BTScanOpaque) scan->opaque;
1152
1153 Assert(so->numArrayKeys);
1154 Assert(so->numberOfKeys);
1155 Assert(sktrig == 0 || readpagetup);
1156 Assert(!readpagetup || scanBehind == NULL);
1157
1158 if (scanBehind)
1159 *scanBehind = false;
1160
1161 for (int ikey = sktrig; ikey < so->numberOfKeys; ikey++)
1162 {
1163 ScanKey cur = so->keyData + ikey;
1164 Datum tupdatum;
1165 bool tupnull;
1166 int32 result;
1167
1168 /* readpagetup calls require one ORDER proc comparison (at most) */
1169 Assert(!readpagetup || ikey == sktrig);
1170
1171 /*
1172 * Once we reach a non-required scan key, we're completely done.
1173 *
1174 * Note: we deliberately don't consider the scan direction here.
1175 * _bt_advance_array_keys caller requires that we track *scanBehind
1176 * without concern for scan direction.
1177 */
1178 if ((cur->sk_flags & (SK_BT_REQFWD | SK_BT_REQBKWD)) == 0)
1179 {
1180 Assert(!readpagetup);
1181 Assert(ikey > sktrig || ikey == 0);
1182 return false;
1183 }
1184
1185 if (cur->sk_attno > tupnatts)
1186 {
1187 Assert(!readpagetup);
1188
1189 /*
1190 * When we reach a high key's truncated attribute, assume that the
1191 * tuple attribute's value is >= the scan's equality constraint
1192 * scan keys (but set *scanBehind to let interested callers know
1193 * that a truncated attribute might have affected our answer).
1194 */
1195 if (scanBehind)
1196 *scanBehind = true;
1197
1198 return false;
1199 }
1200
1201 /*
1202 * Deal with inequality strategy scan keys that _bt_check_compare set
1203 * continuescan=false for
1204 */
1205 if (cur->sk_strategy != BTEqualStrategyNumber)
1206 {
1207 /*
1208 * When _bt_check_compare indicated that a required inequality
1209 * scan key wasn't satisfied, there's no need to verify anything;
1210 * caller always calls _bt_advance_array_keys with this sktrig.
1211 */
1212 if (readpagetup)
1213 return false;
1214
1215 /*
1216 * Otherwise we can't give up, since we must check all required
1217 * scan keys (required in either direction) in order to correctly
1218 * track *scanBehind for caller
1219 */
1220 continue;
1221 }
1222
1223 tupdatum = index_getattr(tuple, cur->sk_attno, tupdesc, &tupnull);
1224
1225 if (likely(!(cur->sk_flags & (SK_BT_MINVAL | SK_BT_MAXVAL))))
1226 {
1227 /* Scankey has a valid/comparable sk_argument value */
1228 result = _bt_compare_array_skey(&so->orderProcs[ikey],
1229 tupdatum, tupnull,
1230 cur->sk_argument, cur);
1231
1232 if (result == 0)
1233 {
1234 /*
1235 * Interpret result in a way that takes NEXT/PRIOR into
1236 * account
1237 */
1238 if (cur->sk_flags & SK_BT_NEXT)
1239 result = -1;
1240 else if (cur->sk_flags & SK_BT_PRIOR)
1241 result = 1;
1242
1243 Assert(result == 0 || (cur->sk_flags & SK_BT_SKIP));
1244 }
1245 }
1246 else
1247 {
1248 BTArrayKeyInfo *array = NULL;
1249
1250 /*
1251 * Current array element/array = scan key value is a sentinel
1252 * value that represents the lowest (or highest) possible value
1253 * that's still within the range of the array.
1254 *
1255 * Like _bt_first, we only see MINVAL keys during forwards scans
1256 * (and similarly only see MAXVAL keys during backwards scans).
1257 * Even if the scan's direction changes, we'll stop at some higher
1258 * order key before we can ever reach any MAXVAL (or MINVAL) keys.
1259 * (However, unlike _bt_first we _can_ get to keys marked either
1260 * NEXT or PRIOR, regardless of the scan's current direction.)
1261 */
1263 !(cur->sk_flags & SK_BT_MAXVAL) :
1264 !(cur->sk_flags & SK_BT_MINVAL));
1265
1266 /*
1267 * There are no valid sk_argument values in MINVAL/MAXVAL keys.
1268 * Check if tupdatum is within the range of skip array instead.
1269 */
1270 for (int arrayidx = 0; arrayidx < so->numArrayKeys; arrayidx++)
1271 {
1272 array = &so->arrayKeys[arrayidx];
1273 if (array->scan_key == ikey)
1274 break;
1275 }
1276
1277 _bt_binsrch_skiparray_skey(false, dir, tupdatum, tupnull,
1278 array, cur, &result);
1279
1280 if (result == 0)
1281 {
1282 /*
1283 * tupdatum satisfies both low_compare and high_compare, so
1284 * it's time to advance the array keys.
1285 *
1286 * Note: It's possible that the skip array will "advance" from
1287 * its MINVAL (or MAXVAL) representation to an alternative,
1288 * logically equivalent representation of the same value: a
1289 * representation where the = key gets a valid datum in its
1290 * sk_argument. This is only possible when low_compare uses
1291 * the >= strategy (or high_compare uses the <= strategy).
1292 */
1293 return false;
1294 }
1295 }
1296
1297 /*
1298 * Does this comparison indicate that caller must _not_ advance the
1299 * scan's arrays just yet?
1300 */
1301 if ((ScanDirectionIsForward(dir) && result < 0) ||
1302 (ScanDirectionIsBackward(dir) && result > 0))
1303 return true;
1304
1305 /*
1306 * Does this comparison indicate that caller should now advance the
1307 * scan's arrays? (Must be if we get here during a readpagetup call.)
1308 */
1309 if (readpagetup || result != 0)
1310 {
1311 Assert(result != 0);
1312 return false;
1313 }
1314
1315 /*
1316 * Inconclusive -- need to check later scan keys, too.
1317 *
1318 * This must be a finaltup precheck, or a call made from an assertion.
1319 */
1320 Assert(result == 0);
1321 }
1322
1323 Assert(!readpagetup);
1324
1325 return false;
1326}
#define likely(x)
Definition: c.h:346

References _bt_binsrch_skiparray_skey(), _bt_compare_array_skey(), BTScanOpaqueData::arrayKeys, Assert(), BTEqualStrategyNumber, cur, index_getattr(), BTScanOpaqueData::keyData, likely, BTScanOpaqueData::numArrayKeys, BTScanOpaqueData::numberOfKeys, IndexScanDescData::opaque, BTScanOpaqueData::orderProcs, BTArrayKeyInfo::scan_key, ScanDirectionIsBackward, ScanDirectionIsForward, SK_BT_MAXVAL, SK_BT_MINVAL, SK_BT_NEXT, SK_BT_PRIOR, SK_BT_REQBKWD, SK_BT_REQFWD, and SK_BT_SKIP.

Referenced by _bt_advance_array_keys(), _bt_checkkeys(), _bt_checkkeys_look_ahead(), and _bt_scanbehind_checkkeys().

◆ _bt_vacuum_cycleid()

BTCycleId _bt_vacuum_cycleid ( Relation  rel)

Definition at line 3536 of file nbtutils.c.

3537{
3538 BTCycleId result = 0;
3539 int i;
3540
3541 /* Share lock is enough since this is a read-only operation */
3542 LWLockAcquire(BtreeVacuumLock, LW_SHARED);
3543
3544 for (i = 0; i < btvacinfo->num_vacuums; i++)
3545 {
3546 BTOneVacInfo *vac = &btvacinfo->vacuums[i];
3547
3548 if (vac->relid.relId == rel->rd_lockInfo.lockRelId.relId &&
3549 vac->relid.dbId == rel->rd_lockInfo.lockRelId.dbId)
3550 {
3551 result = vac->cycleid;
3552 break;
3553 }
3554 }
3555
3556 LWLockRelease(BtreeVacuumLock);
3557 return result;
3558}
@ 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 3751 of file nbtutils.c.

3752{
3753 switch (phasenum)
3754 {
3756 return "initializing";
3758 return "scanning table";
3760 return "sorting live tuples";
3762 return "sorting dead tuples";
3764 return "loading tuples in tree";
3765 default:
3766 return NULL;
3767 }
3768}
#define PROGRESS_BTREE_PHASE_PERFORMSORT_2
Definition: nbtree.h:1178
#define PROGRESS_BTREE_PHASE_LEAF_LOAD
Definition: nbtree.h:1179
#define PROGRESS_BTREE_PHASE_INDEXBUILD_TABLESCAN
Definition: nbtree.h:1176
#define PROGRESS_BTREE_PHASE_PERFORMSORT_1
Definition: nbtree.h:1177
#define PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE
Definition: progress.h:109

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

3706{
3707 static const relopt_parse_elt tab[] = {
3708 {"fillfactor", RELOPT_TYPE_INT, offsetof(BTOptions, fillfactor)},
3709 {"vacuum_cleanup_index_scale_factor", RELOPT_TYPE_REAL,
3710 offsetof(BTOptions, vacuum_cleanup_index_scale_factor)},
3711 {"deduplicate_items", RELOPT_TYPE_BOOL,
3712 offsetof(BTOptions, deduplicate_items)}
3713 };
3714
3715 return (bytea *) build_reloptions(reloptions, validate,
3717 sizeof(BTOptions),
3718 tab, lengthof(tab));
3719}
static bool validate(Port *port, const char *auth)
Definition: auth-oauth.c:638
#define lengthof(array)
Definition: c.h:759
static int fillfactor
Definition: pgbench.c:188
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:1934
@ 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:658

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

Referenced by bthandler().

◆ btproperty()

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

Definition at line 3728 of file nbtutils.c.

3731{
3732 switch (prop)
3733 {
3734 case AMPROP_RETURNABLE:
3735 /* answer only for columns, not AM or whole index */
3736 if (attno == 0)
3737 return false;
3738 /* otherwise, btree can always return data */
3739 *res = true;
3740 return true;
3741
3742 default:
3743 return false; /* punt to generic code */
3744 }
3745}
@ AMPROP_RETURNABLE
Definition: amapi.h:45

References AMPROP_RETURNABLE.

Referenced by bthandler().

◆ BTreeShmemInit()

void BTreeShmemInit ( void  )

Definition at line 3677 of file nbtutils.c.

3678{
3679 bool found;
3680
3681 btvacinfo = (BTVacInfo *) ShmemInitStruct("BTree Vacuum State",
3683 &found);
3684
3685 if (!IsUnderPostmaster)
3686 {
3687 /* Initialize shared memory area */
3688 Assert(!found);
3689
3690 /*
3691 * It doesn't really matter what the cycle counter starts at, but
3692 * having it always start the same doesn't seem good. Seed with
3693 * low-order bits of time() instead.
3694 */
3695 btvacinfo->cycle_ctr = (BTCycleId) time(NULL);
3696
3699 }
3700 else
3701 Assert(found);
3702}
bool IsUnderPostmaster
Definition: globals.c:121
int MaxBackends
Definition: globals.c:147
Size BTreeShmemSize(void)
Definition: nbtutils.c:3664
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 3664 of file nbtutils.c.

3665{
3666 Size size;
3667
3668 size = offsetof(BTVacInfo, vacuums);
3669 size = add_size(size, mul_size(MaxBackends, sizeof(BTOneVacInfo)));
3670 return size;
3671}
Size add_size(Size s1, Size s2)
Definition: shmem.c:493
Size mul_size(Size s1, Size s2)
Definition: shmem.c:510

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

Referenced by BTreeShmemInit(), and CalculateShmemSize().

Variable Documentation

◆ btvacinfo

BTVacInfo* btvacinfo
static

Definition at line 3523 of file nbtutils.c.

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