1 /*-------------------------------------------------------------------------
4 * general index access method routines
6 * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/access/index/indexam.c
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_bitmap - start a scan of an index with amgetbitmap
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_tid - get the next TID from a scan
24 * index_fetch_heap - get the scan's next heap tuple
25 * index_getnext - get the next heap tuple from a scan
26 * index_getbitmap - get all tuples from a scan
27 * index_bulk_delete - bulk deletion of index tuples
28 * index_vacuum_cleanup - post-deletion cleanup of an index
29 * index_can_return - does index support index-only scans?
30 * index_getprocid - get a support procedure OID
31 * index_getprocinfo - get a support procedure's lookup info
34 * This file contains the index_ routines which used
35 * to be a scattered collection of stuff in access/genam.
39 * Scans are implemented as follows:
41 * `0' represents an invalid item pointer.
42 * `-' represents an unknown item pointer.
43 * `X' represents a known item pointers.
44 * `+' represents known or invalid item pointers.
45 * `*' represents any item pointers.
47 * State is represented by a triple of these symbols in the order of
48 * previous, current, next. Note that the case of reverse scans works
52 * (1) + + - + 0 0 (if the next item pointer is invalid)
53 * (2) + X - (otherwise)
54 * (3) * 0 0 * 0 0 (no change)
55 * (4) + X 0 X 0 0 (shift)
56 * (5) * + X + X - (shift, add unknown)
58 * All other states cannot occur.
60 * Note: It would be possible to cache the status of the previous and
61 * next item pointer using the flags.
63 *-------------------------------------------------------------------------
68 #include "access/relscan.h"
69 #include "access/transam.h"
70 #include "catalog/index.h"
72 #include "storage/bufmgr.h"
73 #include "storage/lmgr.h"
74 #include "storage/predicate.h"
75 #include "utils/snapmgr.h"
76 #include "utils/tqual.h"
79 /* ----------------------------------------------------------------
80 * macros used in index_ routines
82 * Note: the ReindexIsProcessingIndex() check in RELATION_CHECKS is there
83 * to check that we don't try to scan or do retail insertions into an index
84 * that is currently being rebuilt or pending rebuild. This helps to catch
85 * things that don't work when reindexing system catalogs. The assertion
86 * doesn't prevent the actual rebuild because we don't use RELATION_CHECKS
87 * when calling the index AM's ambuild routine, and there is no reason for
88 * ambuild to call its subsidiary routines through this file.
89 * ----------------------------------------------------------------
91 #define RELATION_CHECKS \
93 AssertMacro(RelationIsValid(indexRelation)), \
94 AssertMacro(PointerIsValid(indexRelation->rd_am)), \
95 AssertMacro(!ReindexIsProcessingIndex(RelationGetRelid(indexRelation))) \
100 AssertMacro(IndexScanIsValid(scan)), \
101 AssertMacro(RelationIsValid(scan->indexRelation)), \
102 AssertMacro(PointerIsValid(scan->indexRelation->rd_am)) \
105 #define GET_REL_PROCEDURE(pname) \
107 procedure = &indexRelation->rd_aminfo->pname; \
108 if (!OidIsValid(procedure->fn_oid)) \
110 RegProcedure procOid = indexRelation->rd_am->pname; \
111 if (!RegProcedureIsValid(procOid)) \
112 elog(ERROR, "invalid %s regproc", CppAsString(pname)); \
113 fmgr_info_cxt(procOid, procedure, indexRelation->rd_indexcxt); \
117 #define GET_UNCACHED_REL_PROCEDURE(pname) \
119 if (!RegProcedureIsValid(indexRelation->rd_am->pname)) \
120 elog(ERROR, "invalid %s regproc", CppAsString(pname)); \
121 fmgr_info(indexRelation->rd_am->pname, &procedure); \
124 #define GET_SCAN_PROCEDURE(pname) \
126 procedure = &scan->indexRelation->rd_aminfo->pname; \
127 if (!OidIsValid(procedure->fn_oid)) \
129 RegProcedure procOid = scan->indexRelation->rd_am->pname; \
130 if (!RegProcedureIsValid(procOid)) \
131 elog(ERROR, "invalid %s regproc", CppAsString(pname)); \
132 fmgr_info_cxt(procOid, procedure, scan->indexRelation->rd_indexcxt); \
136 static IndexScanDesc index_beginscan_internal(Relation indexRelation,
137 int nkeys, int norderbys, Snapshot snapshot);
140 /* ----------------------------------------------------------------
141 * index_ interface functions
142 * ----------------------------------------------------------------
146 * index_open - open an index relation by relation OID
148 * If lockmode is not "NoLock", the specified kind of lock is
149 * obtained on the index. (Generally, NoLock should only be
150 * used if the caller knows it has some appropriate lock on the
153 * An error is raised if the index does not exist.
155 * This is a convenience routine adapted for indexscan use.
156 * Some callers may prefer to use relation_open directly.
160 index_open(Oid relationId, LOCKMODE lockmode)
164 r = relation_open(relationId, lockmode);
166 if (r->rd_rel->relkind != RELKIND_INDEX)
168 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
169 errmsg("\"%s\" is not an index",
170 RelationGetRelationName(r))));
176 * index_close - close an index relation
178 * If lockmode is not "NoLock", we then release the specified lock.
180 * Note that it is often sensible to hold a lock beyond index_close;
181 * in that case, the lock is released automatically at xact end.
185 index_close(Relation relation, LOCKMODE lockmode)
187 LockRelId relid = relation->rd_lockInfo.lockRelId;
189 Assert(lockmode >= NoLock && lockmode < MAX_LOCKMODES);
191 /* The relcache does the real work... */
192 RelationClose(relation);
194 if (lockmode != NoLock)
195 UnlockRelationId(&relid, lockmode);
199 * index_insert - insert an index tuple into a relation
203 index_insert(Relation indexRelation,
206 ItemPointer heap_t_ctid,
207 Relation heapRelation,
208 IndexUniqueCheck checkUnique)
213 GET_REL_PROCEDURE(aminsert);
215 if (!(indexRelation->rd_am->ampredlocks))
216 CheckForSerializableConflictIn(indexRelation,
221 * have the am's insert proc do all the work.
223 return DatumGetBool(FunctionCall6(procedure,
224 PointerGetDatum(indexRelation),
225 PointerGetDatum(values),
226 PointerGetDatum(isnull),
227 PointerGetDatum(heap_t_ctid),
228 PointerGetDatum(heapRelation),
229 Int32GetDatum((int32) checkUnique)));
233 * index_beginscan - start a scan of an index with amgettuple
235 * Caller must be holding suitable locks on the heap and the index.
238 index_beginscan(Relation heapRelation,
239 Relation indexRelation,
241 int nkeys, int norderbys)
245 scan = index_beginscan_internal(indexRelation, nkeys, norderbys, snapshot);
248 * Save additional parameters into the scandesc. Everything else was set
249 * up by RelationGetIndexScan.
251 scan->heapRelation = heapRelation;
252 scan->xs_snapshot = snapshot;
258 * index_beginscan_bitmap - start a scan of an index with amgetbitmap
260 * As above, caller had better be holding some lock on the parent heap
261 * relation, even though it's not explicitly mentioned here.
264 index_beginscan_bitmap(Relation indexRelation,
270 scan = index_beginscan_internal(indexRelation, nkeys, 0, snapshot);
273 * Save additional parameters into the scandesc. Everything else was set
274 * up by RelationGetIndexScan.
276 scan->xs_snapshot = snapshot;
282 * index_beginscan_internal --- common code for index_beginscan variants
285 index_beginscan_internal(Relation indexRelation,
286 int nkeys, int norderbys, Snapshot snapshot)
292 GET_REL_PROCEDURE(ambeginscan);
294 if (!(indexRelation->rd_am->ampredlocks))
295 PredicateLockRelation(indexRelation, snapshot);
298 * We hold a reference count to the relcache entry throughout the scan.
300 RelationIncrementReferenceCount(indexRelation);
303 * Tell the AM to open a scan.
305 scan = (IndexScanDesc)
306 DatumGetPointer(FunctionCall3(procedure,
307 PointerGetDatum(indexRelation),
308 Int32GetDatum(nkeys),
309 Int32GetDatum(norderbys)));
315 * index_rescan - (re)start a scan of an index
317 * During a restart, the caller may specify a new set of scankeys and/or
318 * orderbykeys; but the number of keys cannot differ from what index_beginscan
319 * was told. (Later we might relax that to "must not exceed", but currently
320 * the index AMs tend to assume that scan->numberOfKeys is what to believe.)
321 * To restart the scan without changing keys, pass NULL for the key arrays.
322 * (Of course, keys *must* be passed on the first call, unless
323 * scan->numberOfKeys is zero.)
327 index_rescan(IndexScanDesc scan,
328 ScanKey keys, int nkeys,
329 ScanKey orderbys, int norderbys)
334 GET_SCAN_PROCEDURE(amrescan);
336 Assert(nkeys == scan->numberOfKeys);
337 Assert(norderbys == scan->numberOfOrderBys);
339 /* Release any held pin on a heap page */
340 if (BufferIsValid(scan->xs_cbuf))
342 ReleaseBuffer(scan->xs_cbuf);
343 scan->xs_cbuf = InvalidBuffer;
346 scan->xs_continue_hot = false;
348 scan->kill_prior_tuple = false; /* for safety */
350 FunctionCall5(procedure,
351 PointerGetDatum(scan),
352 PointerGetDatum(keys),
353 Int32GetDatum(nkeys),
354 PointerGetDatum(orderbys),
355 Int32GetDatum(norderbys));
359 * index_endscan - end a scan
363 index_endscan(IndexScanDesc scan)
368 GET_SCAN_PROCEDURE(amendscan);
370 /* Release any held pin on a heap page */
371 if (BufferIsValid(scan->xs_cbuf))
373 ReleaseBuffer(scan->xs_cbuf);
374 scan->xs_cbuf = InvalidBuffer;
377 /* End the AM's scan */
378 FunctionCall1(procedure, PointerGetDatum(scan));
380 /* Release index refcount acquired by index_beginscan */
381 RelationDecrementReferenceCount(scan->indexRelation);
383 /* Release the scan data structure itself */
388 * index_markpos - mark a scan position
392 index_markpos(IndexScanDesc scan)
397 GET_SCAN_PROCEDURE(ammarkpos);
399 FunctionCall1(procedure, PointerGetDatum(scan));
403 * index_restrpos - restore a scan position
405 * NOTE: this only restores the internal scan state of the index AM.
406 * The current result tuple (scan->xs_ctup) doesn't change. See comments
407 * for ExecRestrPos().
409 * NOTE: in the presence of HOT chains, mark/restore only works correctly
410 * if the scan's snapshot is MVCC-safe; that ensures that there's at most one
411 * returnable tuple in each HOT chain, and so restoring the prior state at the
412 * granularity of the index AM is sufficient. Since the only current user
413 * of mark/restore functionality is nodeMergejoin.c, this effectively means
414 * that merge-join plans only work for MVCC snapshots. This could be fixed
415 * if necessary, but for now it seems unimportant.
419 index_restrpos(IndexScanDesc scan)
423 Assert(IsMVCCSnapshot(scan->xs_snapshot));
426 GET_SCAN_PROCEDURE(amrestrpos);
428 scan->xs_continue_hot = false;
430 scan->kill_prior_tuple = false; /* for safety */
432 FunctionCall1(procedure, PointerGetDatum(scan));
436 * index_getnext_tid - get the next TID from a scan
438 * The result is the next TID satisfying the scan keys,
439 * or NULL if no more matching tuples exist.
443 index_getnext_tid(IndexScanDesc scan, ScanDirection direction)
449 GET_SCAN_PROCEDURE(amgettuple);
451 Assert(TransactionIdIsValid(RecentGlobalXmin));
454 * The AM's amgettuple proc finds the next index entry matching the scan
455 * keys, and puts the TID into scan->xs_ctup.t_self. It should also set
456 * scan->xs_recheck and possibly scan->xs_itup, though we pay no attention
457 * to those fields here.
459 found = DatumGetBool(FunctionCall2(procedure,
460 PointerGetDatum(scan),
461 Int32GetDatum(direction)));
463 /* Reset kill flag immediately for safety */
464 scan->kill_prior_tuple = false;
466 /* If we're out of index entries, we're done */
469 /* ... but first, release any held pin on a heap page */
470 if (BufferIsValid(scan->xs_cbuf))
472 ReleaseBuffer(scan->xs_cbuf);
473 scan->xs_cbuf = InvalidBuffer;
478 pgstat_count_index_tuples(scan->indexRelation, 1);
480 /* Return the TID of the tuple we found. */
481 return &scan->xs_ctup.t_self;
485 * index_fetch_heap - get the scan's next heap tuple
487 * The result is a visible heap tuple associated with the index TID most
488 * recently fetched by index_getnext_tid, or NULL if no more matching tuples
489 * exist. (There can be more than one matching tuple because of HOT chains,
490 * although when using an MVCC snapshot it should be impossible for more than
491 * one such tuple to exist.)
493 * On success, the buffer containing the heap tup is pinned (the pin will be
494 * dropped in a future index_getnext_tid, index_fetch_heap or index_endscan
497 * Note: caller must check scan->xs_recheck, and perform rechecking of the
498 * scan keys if required. We do not do that here because we don't have
499 * enough information to do it efficiently in the general case.
503 index_fetch_heap(IndexScanDesc scan)
505 ItemPointer tid = &scan->xs_ctup.t_self;
506 bool all_dead = false;
509 /* We can skip the buffer-switching logic if we're in mid-HOT chain. */
510 if (!scan->xs_continue_hot)
512 /* Switch to correct buffer if we don't have it already */
513 Buffer prev_buf = scan->xs_cbuf;
515 scan->xs_cbuf = ReleaseAndReadBuffer(scan->xs_cbuf,
517 ItemPointerGetBlockNumber(tid));
520 * Prune page, but only if we weren't already on this page
522 if (prev_buf != scan->xs_cbuf)
523 heap_page_prune_opt(scan->heapRelation, scan->xs_cbuf,
527 /* Obtain share-lock on the buffer so we can examine visibility */
528 LockBuffer(scan->xs_cbuf, BUFFER_LOCK_SHARE);
529 got_heap_tuple = heap_hot_search_buffer(tid, scan->heapRelation,
534 !scan->xs_continue_hot);
535 LockBuffer(scan->xs_cbuf, BUFFER_LOCK_UNLOCK);
540 * Only in a non-MVCC snapshot can more than one member of the HOT
543 scan->xs_continue_hot = !IsMVCCSnapshot(scan->xs_snapshot);
544 pgstat_count_heap_fetch(scan->indexRelation);
545 return &scan->xs_ctup;
548 /* We've reached the end of the HOT chain. */
549 scan->xs_continue_hot = false;
552 * If we scanned a whole HOT chain and found only dead tuples, tell index
553 * AM to kill its entry for that TID (this will take effect in the next
554 * amgettuple call, in index_getnext_tid). We do not do this when in
555 * recovery because it may violate MVCC to do so. See comments in
556 * RelationGetIndexScan().
558 if (!scan->xactStartedInRecovery)
559 scan->kill_prior_tuple = all_dead;
565 * index_getnext - get the next heap tuple from a scan
567 * The result is the next heap tuple satisfying the scan keys and the
568 * snapshot, or NULL if no more matching tuples exist.
570 * On success, the buffer containing the heap tup is pinned (the pin will be
571 * dropped in a future index_getnext_tid, index_fetch_heap or index_endscan
574 * Note: caller must check scan->xs_recheck, and perform rechecking of the
575 * scan keys if required. We do not do that here because we don't have
576 * enough information to do it efficiently in the general case.
580 index_getnext(IndexScanDesc scan, ScanDirection direction)
587 if (scan->xs_continue_hot)
590 * We are resuming scan of a HOT chain after having returned an
591 * earlier member. Must still hold pin on current heap page.
593 Assert(BufferIsValid(scan->xs_cbuf));
594 Assert(ItemPointerGetBlockNumber(&scan->xs_ctup.t_self) ==
595 BufferGetBlockNumber(scan->xs_cbuf));
599 /* Time to fetch the next TID from the index */
600 tid = index_getnext_tid(scan, direction);
602 /* If we're out of index entries, we're done */
608 * Fetch the next (or only) visible heap tuple for this index entry.
609 * If we don't find anything, loop around and grab the next TID from
612 heapTuple = index_fetch_heap(scan);
613 if (heapTuple != NULL)
617 return NULL; /* failure exit */
621 * index_getbitmap - get all tuples at once from an index scan
623 * Adds the TIDs of all heap tuples satisfying the scan keys to a bitmap.
624 * Since there's no interlock between the index scan and the eventual heap
625 * access, this is only safe to use with MVCC-based snapshots: the heap
626 * item slot could have been replaced by a newer tuple by the time we get
629 * Returns the number of matching tuples found. (Note: this might be only
630 * approximate, so it should only be used for statistical purposes.)
634 index_getbitmap(IndexScanDesc scan, TIDBitmap *bitmap)
641 GET_SCAN_PROCEDURE(amgetbitmap);
643 /* just make sure this is false... */
644 scan->kill_prior_tuple = false;
647 * have the am's getbitmap proc do all the work.
649 d = FunctionCall2(procedure,
650 PointerGetDatum(scan),
651 PointerGetDatum(bitmap));
653 ntids = DatumGetInt64(d);
655 /* If int8 is pass-by-ref, must free the result to avoid memory leak */
656 #ifndef USE_FLOAT8_BYVAL
657 pfree(DatumGetPointer(d));
660 pgstat_count_index_tuples(scan->indexRelation, ntids);
666 * index_bulk_delete - do mass deletion of index entries
668 * callback routine tells whether a given main-heap tuple is
671 * return value is an optional palloc'd struct of statistics
674 IndexBulkDeleteResult *
675 index_bulk_delete(IndexVacuumInfo *info,
676 IndexBulkDeleteResult *stats,
677 IndexBulkDeleteCallback callback,
678 void *callback_state)
680 Relation indexRelation = info->index;
682 IndexBulkDeleteResult *result;
685 GET_UNCACHED_REL_PROCEDURE(ambulkdelete);
687 result = (IndexBulkDeleteResult *)
688 DatumGetPointer(FunctionCall4(&procedure,
689 PointerGetDatum(info),
690 PointerGetDatum(stats),
691 PointerGetDatum((Pointer) callback),
692 PointerGetDatum(callback_state)));
698 * index_vacuum_cleanup - do post-deletion cleanup of an index
700 * return value is an optional palloc'd struct of statistics
703 IndexBulkDeleteResult *
704 index_vacuum_cleanup(IndexVacuumInfo *info,
705 IndexBulkDeleteResult *stats)
707 Relation indexRelation = info->index;
709 IndexBulkDeleteResult *result;
712 GET_UNCACHED_REL_PROCEDURE(amvacuumcleanup);
714 result = (IndexBulkDeleteResult *)
715 DatumGetPointer(FunctionCall2(&procedure,
716 PointerGetDatum(info),
717 PointerGetDatum(stats)));
723 * index_can_return - does index support index-only scans?
727 index_can_return(Relation indexRelation)
733 /* amcanreturn is optional; assume FALSE if not provided by AM */
734 if (!RegProcedureIsValid(indexRelation->rd_am->amcanreturn))
737 GET_REL_PROCEDURE(amcanreturn);
739 return DatumGetBool(FunctionCall1(procedure,
740 PointerGetDatum(indexRelation)));
746 * Index access methods typically require support routines that are
747 * not directly the implementation of any WHERE-clause query operator
748 * and so cannot be kept in pg_amop. Instead, such routines are kept
749 * in pg_amproc. These registered procedure OIDs are assigned numbers
750 * according to a convention established by the access method.
751 * The general index code doesn't know anything about the routines
752 * involved; it just builds an ordered list of them for
753 * each attribute on which an index is defined.
755 * As of Postgres 8.3, support routines within an operator family
756 * are further subdivided by the "left type" and "right type" of the
757 * query operator(s) that they support. The "default" functions for a
758 * particular indexed attribute are those with both types equal to
759 * the index opclass' opcintype (note that this is subtly different
760 * from the indexed attribute's own type: it may be a binary-compatible
761 * type instead). Only the default functions are stored in relcache
762 * entries --- access methods can use the syscache to look up non-default
765 * This routine returns the requested default procedure OID for a
766 * particular indexed attribute.
770 index_getprocid(Relation irel,
778 nproc = irel->rd_am->amsupport;
780 Assert(procnum > 0 && procnum <= (uint16) nproc);
782 procindex = (nproc * (attnum - 1)) + (procnum - 1);
784 loc = irel->rd_support;
788 return loc[procindex];
794 * This routine allows index AMs to keep fmgr lookup info for
795 * support procs in the relcache. As above, only the "default"
796 * functions for any particular indexed attribute are cached.
798 * Note: the return value points into cached data that will be lost during
799 * any relcache rebuild! Therefore, either use the callinfo right away,
800 * or save it only after having acquired some type of lock on the index rel.
804 index_getprocinfo(Relation irel,
812 nproc = irel->rd_am->amsupport;
814 Assert(procnum > 0 && procnum <= (uint16) nproc);
816 procindex = (nproc * (attnum - 1)) + (procnum - 1);
818 locinfo = irel->rd_supportinfo;
820 Assert(locinfo != NULL);
822 locinfo += procindex;
824 /* Initialize the lookup info if first time through */
825 if (locinfo->fn_oid == InvalidOid)
827 RegProcedure *loc = irel->rd_support;
832 procId = loc[procindex];
835 * Complain if function was not found during IndexSupportInitialize.
836 * This should not happen unless the system tables contain bogus
837 * entries for the index opclass. (If an AM wants to allow a support
838 * function to be optional, it can use index_getprocid.)
840 if (!RegProcedureIsValid(procId))
841 elog(ERROR, "missing support function %d for attribute %d of index \"%s\"",
842 procnum, attnum, RelationGetRelationName(irel));
844 fmgr_info_cxt(procId, locinfo, irel->rd_indexcxt);