1 /*-------------------------------------------------------------------------
4 * general index access method routines
6 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/access/index/indexam.c,v 1.101 2008/01/01 19:45:46 momjian Exp $
14 * index_open - open an index relation by relation OID
15 * index_close - close an index relation
16 * index_beginscan - start a scan of an index with amgettuple
17 * index_beginscan_multi - start a scan of an index with amgetmulti
18 * index_rescan - restart a scan of an index
19 * index_endscan - end a scan
20 * index_insert - insert an index tuple into a relation
21 * index_markpos - mark a scan position
22 * index_restrpos - restore a scan position
23 * index_getnext - get the next tuple from a scan
24 * index_getmulti - get multiple tuples from a scan
25 * index_bulk_delete - bulk deletion of index tuples
26 * index_vacuum_cleanup - post-deletion cleanup of an index
27 * index_getprocid - get a support procedure OID
28 * index_getprocinfo - get a support procedure's lookup info
31 * This file contains the index_ routines which used
32 * to be a scattered collection of stuff in access/genam.
36 * Scans are implemented as follows:
38 * `0' represents an invalid item pointer.
39 * `-' represents an unknown item pointer.
40 * `X' represents a known item pointers.
41 * `+' represents known or invalid item pointers.
42 * `*' represents any item pointers.
44 * State is represented by a triple of these symbols in the order of
45 * previous, current, next. Note that the case of reverse scans works
49 * (1) + + - + 0 0 (if the next item pointer is invalid)
50 * (2) + X - (otherwise)
51 * (3) * 0 0 * 0 0 (no change)
52 * (4) + X 0 X 0 0 (shift)
53 * (5) * + X + X - (shift, add unknown)
55 * All other states cannot occur.
57 * Note: It would be possible to cache the status of the previous and
58 * next item pointer using the flags.
60 *-------------------------------------------------------------------------
65 #include "access/genam.h"
66 #include "access/heapam.h"
67 #include "access/transam.h"
69 #include "utils/relcache.h"
72 /* ----------------------------------------------------------------
73 * macros used in index_ routines
74 * ----------------------------------------------------------------
76 #define RELATION_CHECKS \
78 AssertMacro(RelationIsValid(indexRelation)), \
79 AssertMacro(PointerIsValid(indexRelation->rd_am)) \
84 AssertMacro(IndexScanIsValid(scan)), \
85 AssertMacro(RelationIsValid(scan->indexRelation)), \
86 AssertMacro(PointerIsValid(scan->indexRelation->rd_am)) \
89 #define GET_REL_PROCEDURE(pname) \
91 procedure = &indexRelation->rd_aminfo->pname; \
92 if (!OidIsValid(procedure->fn_oid)) \
94 RegProcedure procOid = indexRelation->rd_am->pname; \
95 if (!RegProcedureIsValid(procOid)) \
96 elog(ERROR, "invalid %s regproc", CppAsString(pname)); \
97 fmgr_info_cxt(procOid, procedure, indexRelation->rd_indexcxt); \
101 #define GET_SCAN_PROCEDURE(pname) \
103 procedure = &scan->indexRelation->rd_aminfo->pname; \
104 if (!OidIsValid(procedure->fn_oid)) \
106 RegProcedure procOid = scan->indexRelation->rd_am->pname; \
107 if (!RegProcedureIsValid(procOid)) \
108 elog(ERROR, "invalid %s regproc", CppAsString(pname)); \
109 fmgr_info_cxt(procOid, procedure, scan->indexRelation->rd_indexcxt); \
113 static IndexScanDesc index_beginscan_internal(Relation indexRelation,
114 int nkeys, ScanKey key);
117 /* ----------------------------------------------------------------
118 * index_ interface functions
119 * ----------------------------------------------------------------
123 * index_open - open an index relation by relation OID
125 * If lockmode is not "NoLock", the specified kind of lock is
126 * obtained on the index. (Generally, NoLock should only be
127 * used if the caller knows it has some appropriate lock on the
130 * An error is raised if the index does not exist.
132 * This is a convenience routine adapted for indexscan use.
133 * Some callers may prefer to use relation_open directly.
137 index_open(Oid relationId, LOCKMODE lockmode)
141 r = relation_open(relationId, lockmode);
143 if (r->rd_rel->relkind != RELKIND_INDEX)
145 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
146 errmsg("\"%s\" is not an index",
147 RelationGetRelationName(r))));
153 * index_close - close an index relation
155 * If lockmode is not "NoLock", we then release the specified lock.
157 * Note that it is often sensible to hold a lock beyond index_close;
158 * in that case, the lock is released automatically at xact end.
162 index_close(Relation relation, LOCKMODE lockmode)
164 LockRelId relid = relation->rd_lockInfo.lockRelId;
166 Assert(lockmode >= NoLock && lockmode < MAX_LOCKMODES);
168 /* The relcache does the real work... */
169 RelationClose(relation);
171 if (lockmode != NoLock)
172 UnlockRelationId(&relid, lockmode);
176 * index_insert - insert an index tuple into a relation
180 index_insert(Relation indexRelation,
183 ItemPointer heap_t_ctid,
184 Relation heapRelation,
185 bool check_uniqueness)
190 GET_REL_PROCEDURE(aminsert);
193 * have the am's insert proc do all the work.
195 return DatumGetBool(FunctionCall6(procedure,
196 PointerGetDatum(indexRelation),
197 PointerGetDatum(values),
198 PointerGetDatum(isnull),
199 PointerGetDatum(heap_t_ctid),
200 PointerGetDatum(heapRelation),
201 BoolGetDatum(check_uniqueness)));
205 * index_beginscan - start a scan of an index with amgettuple
207 * Note: heapRelation may be NULL if there is no intention of calling
208 * index_getnext on this scan; index_getnext_indexitem will not use the
209 * heapRelation link (nor the snapshot). However, the caller had better
210 * be holding some kind of lock on the heap relation in any case, to ensure
211 * no one deletes it (or the index) out from under us. Caller must also
212 * be holding a lock on the index.
215 index_beginscan(Relation heapRelation,
216 Relation indexRelation,
218 int nkeys, ScanKey key)
222 scan = index_beginscan_internal(indexRelation, nkeys, key);
225 * Save additional parameters into the scandesc. Everything else was set
226 * up by RelationGetIndexScan.
228 scan->is_multiscan = false;
229 scan->heapRelation = heapRelation;
230 scan->xs_snapshot = snapshot;
236 * index_beginscan_multi - start a scan of an index with amgetmulti
238 * As above, caller had better be holding some lock on the parent heap
239 * relation, even though it's not explicitly mentioned here.
242 index_beginscan_multi(Relation indexRelation,
244 int nkeys, ScanKey key)
248 scan = index_beginscan_internal(indexRelation, nkeys, key);
251 * Save additional parameters into the scandesc. Everything else was set
252 * up by RelationGetIndexScan.
254 scan->is_multiscan = true;
255 scan->xs_snapshot = snapshot;
261 * index_beginscan_internal --- common code for index_beginscan variants
264 index_beginscan_internal(Relation indexRelation,
265 int nkeys, ScanKey key)
271 GET_REL_PROCEDURE(ambeginscan);
274 * We hold a reference count to the relcache entry throughout the scan.
276 RelationIncrementReferenceCount(indexRelation);
279 * Tell the AM to open a scan.
281 scan = (IndexScanDesc)
282 DatumGetPointer(FunctionCall3(procedure,
283 PointerGetDatum(indexRelation),
284 Int32GetDatum(nkeys),
285 PointerGetDatum(key)));
291 * index_rescan - (re)start a scan of an index
293 * The caller may specify a new set of scankeys (but the number of keys
294 * cannot change). To restart the scan without changing keys, pass NULL
297 * Note that this is also called when first starting an indexscan;
298 * see RelationGetIndexScan. Keys *must* be passed in that case,
299 * unless scan->numberOfKeys is zero.
303 index_rescan(IndexScanDesc scan, ScanKey key)
308 GET_SCAN_PROCEDURE(amrescan);
310 /* Release any held pin on a heap page */
311 if (BufferIsValid(scan->xs_cbuf))
313 ReleaseBuffer(scan->xs_cbuf);
314 scan->xs_cbuf = InvalidBuffer;
317 scan->xs_next_hot = InvalidOffsetNumber;
319 scan->kill_prior_tuple = false; /* for safety */
321 FunctionCall2(procedure,
322 PointerGetDatum(scan),
323 PointerGetDatum(key));
327 * index_endscan - end a scan
331 index_endscan(IndexScanDesc scan)
336 GET_SCAN_PROCEDURE(amendscan);
338 /* Release any held pin on a heap page */
339 if (BufferIsValid(scan->xs_cbuf))
341 ReleaseBuffer(scan->xs_cbuf);
342 scan->xs_cbuf = InvalidBuffer;
345 /* End the AM's scan */
346 FunctionCall1(procedure, PointerGetDatum(scan));
348 /* Release index refcount acquired by index_beginscan */
349 RelationDecrementReferenceCount(scan->indexRelation);
351 /* Release the scan data structure itself */
356 * index_markpos - mark a scan position
360 index_markpos(IndexScanDesc scan)
365 GET_SCAN_PROCEDURE(ammarkpos);
367 FunctionCall1(procedure, PointerGetDatum(scan));
371 * index_restrpos - restore a scan position
373 * NOTE: this only restores the internal scan state of the index AM.
374 * The current result tuple (scan->xs_ctup) doesn't change. See comments
375 * for ExecRestrPos().
377 * NOTE: in the presence of HOT chains, mark/restore only works correctly
378 * if the scan's snapshot is MVCC-safe; that ensures that there's at most one
379 * returnable tuple in each HOT chain, and so restoring the prior state at the
380 * granularity of the index AM is sufficient. Since the only current user
381 * of mark/restore functionality is nodeMergejoin.c, this effectively means
382 * that merge-join plans only work for MVCC snapshots. This could be fixed
383 * if necessary, but for now it seems unimportant.
387 index_restrpos(IndexScanDesc scan)
391 Assert(IsMVCCSnapshot(scan->xs_snapshot));
394 GET_SCAN_PROCEDURE(amrestrpos);
396 scan->xs_next_hot = InvalidOffsetNumber;
398 scan->kill_prior_tuple = false; /* for safety */
400 FunctionCall1(procedure, PointerGetDatum(scan));
404 * index_getnext - get the next heap tuple from a scan
406 * The result is the next heap tuple satisfying the scan keys and the
407 * snapshot, or NULL if no more matching tuples exist. On success,
408 * the buffer containing the heap tuple is pinned (the pin will be dropped
409 * at the next index_getnext or index_endscan).
413 index_getnext(IndexScanDesc scan, ScanDirection direction)
415 HeapTuple heapTuple = &scan->xs_ctup;
416 ItemPointer tid = &heapTuple->t_self;
420 GET_SCAN_PROCEDURE(amgettuple);
423 * We always reset xs_hot_dead; if we are here then either we are just
424 * starting the scan, or we previously returned a visible tuple, and in
425 * either case it's inappropriate to kill the prior index entry.
427 scan->xs_hot_dead = false;
435 if (scan->xs_next_hot != InvalidOffsetNumber)
438 * We are resuming scan of a HOT chain after having returned an
439 * earlier member. Must still hold pin on current heap page.
441 Assert(BufferIsValid(scan->xs_cbuf));
442 Assert(ItemPointerGetBlockNumber(tid) ==
443 BufferGetBlockNumber(scan->xs_cbuf));
444 Assert(TransactionIdIsValid(scan->xs_prev_xmax));
445 offnum = scan->xs_next_hot;
446 at_chain_start = false;
447 scan->xs_next_hot = InvalidOffsetNumber;
455 * If we scanned a whole HOT chain and found only dead tuples,
456 * tell index AM to kill its entry for that TID.
458 scan->kill_prior_tuple = scan->xs_hot_dead;
461 * The AM's gettuple proc finds the next index entry matching the
462 * scan keys, and puts the TID in xs_ctup.t_self (ie, *tid).
464 found = DatumGetBool(FunctionCall2(procedure,
465 PointerGetDatum(scan),
466 Int32GetDatum(direction)));
468 /* Reset kill flag immediately for safety */
469 scan->kill_prior_tuple = false;
471 /* If we're out of index entries, break out of outer loop */
475 pgstat_count_index_tuples(scan->indexRelation, 1);
477 /* Switch to correct buffer if we don't have it already */
478 prev_buf = scan->xs_cbuf;
479 scan->xs_cbuf = ReleaseAndReadBuffer(scan->xs_cbuf,
481 ItemPointerGetBlockNumber(tid));
484 * Prune page, but only if we weren't already on this page
486 if (prev_buf != scan->xs_cbuf)
487 heap_page_prune_opt(scan->heapRelation, scan->xs_cbuf,
490 /* Prepare to scan HOT chain starting at index-referenced offnum */
491 offnum = ItemPointerGetOffsetNumber(tid);
492 at_chain_start = true;
494 /* We don't know what the first tuple's xmin should be */
495 scan->xs_prev_xmax = InvalidTransactionId;
497 /* Initialize flag to detect if all entries are dead */
498 scan->xs_hot_dead = true;
501 /* Obtain share-lock on the buffer so we can examine visibility */
502 LockBuffer(scan->xs_cbuf, BUFFER_LOCK_SHARE);
504 dp = (Page) BufferGetPage(scan->xs_cbuf);
506 /* Scan through possible multiple members of HOT-chain */
512 /* check for bogus TID */
513 if (offnum < FirstOffsetNumber ||
514 offnum > PageGetMaxOffsetNumber(dp))
517 lp = PageGetItemId(dp, offnum);
519 /* check for unused, dead, or redirected items */
520 if (!ItemIdIsNormal(lp))
522 /* We should only see a redirect at start of chain */
523 if (ItemIdIsRedirected(lp) && at_chain_start)
525 /* Follow the redirect */
526 offnum = ItemIdGetRedirect(lp);
527 at_chain_start = false;
530 /* else must be end of chain */
535 * We must initialize all of *heapTuple (ie, scan->xs_ctup) since
536 * it is returned to the executor on success.
538 heapTuple->t_data = (HeapTupleHeader) PageGetItem(dp, lp);
539 heapTuple->t_len = ItemIdGetLength(lp);
540 ItemPointerSetOffsetNumber(tid, offnum);
541 heapTuple->t_tableOid = RelationGetRelid(scan->heapRelation);
542 ctid = &heapTuple->t_data->t_ctid;
545 * Shouldn't see a HEAP_ONLY tuple at chain start. (This test
546 * should be unnecessary, since the chain root can't be removed
547 * while we have pin on the index entry, but let's make it
550 if (at_chain_start && HeapTupleIsHeapOnly(heapTuple))
554 * The xmin should match the previous xmax value, else chain is
555 * broken. (Note: this test is not optional because it protects
556 * us against the case where the prior chain member's xmax aborted
557 * since we looked at it.)
559 if (TransactionIdIsValid(scan->xs_prev_xmax) &&
560 !TransactionIdEquals(scan->xs_prev_xmax,
561 HeapTupleHeaderGetXmin(heapTuple->t_data)))
564 /* If it's visible per the snapshot, we must return it */
565 if (HeapTupleSatisfiesVisibility(heapTuple, scan->xs_snapshot,
569 * If the snapshot is MVCC, we know that it could accept at
570 * most one member of the HOT chain, so we can skip examining
571 * any more members. Otherwise, check for continuation of the
572 * HOT-chain, and set state for next time.
574 if (IsMVCCSnapshot(scan->xs_snapshot))
575 scan->xs_next_hot = InvalidOffsetNumber;
576 else if (HeapTupleIsHotUpdated(heapTuple))
578 Assert(ItemPointerGetBlockNumber(ctid) ==
579 ItemPointerGetBlockNumber(tid));
580 scan->xs_next_hot = ItemPointerGetOffsetNumber(ctid);
581 scan->xs_prev_xmax = HeapTupleHeaderGetXmax(heapTuple->t_data);
584 scan->xs_next_hot = InvalidOffsetNumber;
586 LockBuffer(scan->xs_cbuf, BUFFER_LOCK_UNLOCK);
588 pgstat_count_heap_fetch(scan->indexRelation);
594 * If we can't see it, maybe no one else can either. Check to see
595 * if the tuple is dead to all transactions. If we find that all
596 * the tuples in the HOT chain are dead, we'll signal the index AM
597 * to not return that TID on future indexscans.
599 if (scan->xs_hot_dead &&
600 HeapTupleSatisfiesVacuum(heapTuple->t_data, RecentGlobalXmin,
601 scan->xs_cbuf) != HEAPTUPLE_DEAD)
602 scan->xs_hot_dead = false;
605 * Check to see if HOT chain continues past this tuple; if so
606 * fetch the next offnum (we don't bother storing it into
607 * xs_next_hot, but must store xs_prev_xmax), and loop around.
609 if (HeapTupleIsHotUpdated(heapTuple))
611 Assert(ItemPointerGetBlockNumber(ctid) ==
612 ItemPointerGetBlockNumber(tid));
613 offnum = ItemPointerGetOffsetNumber(ctid);
614 at_chain_start = false;
615 scan->xs_prev_xmax = HeapTupleHeaderGetXmax(heapTuple->t_data);
618 break; /* end of chain */
619 } /* loop over a single HOT chain */
621 LockBuffer(scan->xs_cbuf, BUFFER_LOCK_UNLOCK);
623 /* Loop around to ask index AM for another TID */
624 scan->xs_next_hot = InvalidOffsetNumber;
627 /* Release any held pin on a heap page */
628 if (BufferIsValid(scan->xs_cbuf))
630 ReleaseBuffer(scan->xs_cbuf);
631 scan->xs_cbuf = InvalidBuffer;
634 return NULL; /* failure exit */
638 * index_getnext_indexitem - get the next index tuple from a scan
640 * Finds the next index tuple satisfying the scan keys. Note that the
641 * corresponding heap tuple is not accessed, and thus no time qual (snapshot)
642 * check is done, other than the index AM's internal check for killed tuples
643 * (which most callers of this routine will probably want to suppress by
644 * setting scan->ignore_killed_tuples = false).
646 * On success (TRUE return), the heap TID of the found index entry is in
647 * scan->xs_ctup.t_self. scan->xs_cbuf is untouched.
651 index_getnext_indexitem(IndexScanDesc scan,
652 ScanDirection direction)
658 GET_SCAN_PROCEDURE(amgettuple);
660 /* just make sure this is false... */
661 scan->kill_prior_tuple = false;
664 * have the am's gettuple proc do all the work.
666 found = DatumGetBool(FunctionCall2(procedure,
667 PointerGetDatum(scan),
668 Int32GetDatum(direction)));
671 pgstat_count_index_tuples(scan->indexRelation, 1);
677 * index_getmulti - get multiple tuples from an index scan
679 * Collects the TIDs of multiple heap tuples satisfying the scan keys.
680 * Since there's no interlock between the index scan and the eventual heap
681 * access, this is only safe to use with MVCC-based snapshots: the heap
682 * item slot could have been replaced by a newer tuple by the time we get
685 * A TRUE result indicates more calls should occur; a FALSE result says the
686 * scan is done. *returned_tids could be zero or nonzero in either case.
690 index_getmulti(IndexScanDesc scan,
691 ItemPointer tids, int32 max_tids,
692 int32 *returned_tids)
698 GET_SCAN_PROCEDURE(amgetmulti);
700 /* just make sure this is false... */
701 scan->kill_prior_tuple = false;
704 * have the am's getmulti proc do all the work.
706 found = DatumGetBool(FunctionCall4(procedure,
707 PointerGetDatum(scan),
708 PointerGetDatum(tids),
709 Int32GetDatum(max_tids),
710 PointerGetDatum(returned_tids)));
712 pgstat_count_index_tuples(scan->indexRelation, *returned_tids);
718 * index_bulk_delete - do mass deletion of index entries
720 * callback routine tells whether a given main-heap tuple is
723 * return value is an optional palloc'd struct of statistics
726 IndexBulkDeleteResult *
727 index_bulk_delete(IndexVacuumInfo *info,
728 IndexBulkDeleteResult *stats,
729 IndexBulkDeleteCallback callback,
730 void *callback_state)
732 Relation indexRelation = info->index;
734 IndexBulkDeleteResult *result;
737 GET_REL_PROCEDURE(ambulkdelete);
739 result = (IndexBulkDeleteResult *)
740 DatumGetPointer(FunctionCall4(procedure,
741 PointerGetDatum(info),
742 PointerGetDatum(stats),
743 PointerGetDatum((Pointer) callback),
744 PointerGetDatum(callback_state)));
750 * index_vacuum_cleanup - do post-deletion cleanup of an index
752 * return value is an optional palloc'd struct of statistics
755 IndexBulkDeleteResult *
756 index_vacuum_cleanup(IndexVacuumInfo *info,
757 IndexBulkDeleteResult *stats)
759 Relation indexRelation = info->index;
761 IndexBulkDeleteResult *result;
764 GET_REL_PROCEDURE(amvacuumcleanup);
766 result = (IndexBulkDeleteResult *)
767 DatumGetPointer(FunctionCall2(procedure,
768 PointerGetDatum(info),
769 PointerGetDatum(stats)));
777 * Index access methods typically require support routines that are
778 * not directly the implementation of any WHERE-clause query operator
779 * and so cannot be kept in pg_amop. Instead, such routines are kept
780 * in pg_amproc. These registered procedure OIDs are assigned numbers
781 * according to a convention established by the access method.
782 * The general index code doesn't know anything about the routines
783 * involved; it just builds an ordered list of them for
784 * each attribute on which an index is defined.
786 * As of Postgres 8.3, support routines within an operator family
787 * are further subdivided by the "left type" and "right type" of the
788 * query operator(s) that they support. The "default" functions for a
789 * particular indexed attribute are those with both types equal to
790 * the index opclass' opcintype (note that this is subtly different
791 * from the indexed attribute's own type: it may be a binary-compatible
792 * type instead). Only the default functions are stored in relcache
793 * entries --- access methods can use the syscache to look up non-default
796 * This routine returns the requested default procedure OID for a
797 * particular indexed attribute.
801 index_getprocid(Relation irel,
809 nproc = irel->rd_am->amsupport;
811 Assert(procnum > 0 && procnum <= (uint16) nproc);
813 procindex = (nproc * (attnum - 1)) + (procnum - 1);
815 loc = irel->rd_support;
819 return loc[procindex];
825 * This routine allows index AMs to keep fmgr lookup info for
826 * support procs in the relcache. As above, only the "default"
827 * functions for any particular indexed attribute are cached.
829 * Note: the return value points into cached data that will be lost during
830 * any relcache rebuild! Therefore, either use the callinfo right away,
831 * or save it only after having acquired some type of lock on the index rel.
835 index_getprocinfo(Relation irel,
843 nproc = irel->rd_am->amsupport;
845 Assert(procnum > 0 && procnum <= (uint16) nproc);
847 procindex = (nproc * (attnum - 1)) + (procnum - 1);
849 locinfo = irel->rd_supportinfo;
851 Assert(locinfo != NULL);
853 locinfo += procindex;
855 /* Initialize the lookup info if first time through */
856 if (locinfo->fn_oid == InvalidOid)
858 RegProcedure *loc = irel->rd_support;
863 procId = loc[procindex];
866 * Complain if function was not found during IndexSupportInitialize.
867 * This should not happen unless the system tables contain bogus
868 * entries for the index opclass. (If an AM wants to allow a support
869 * function to be optional, it can use index_getprocid.)
871 if (!RegProcedureIsValid(procId))
872 elog(ERROR, "missing support function %d for attribute %d of index \"%s\"",
873 procnum, attnum, RelationGetRelationName(irel));
875 fmgr_info_cxt(procId, locinfo, irel->rd_indexcxt);