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_SCAN_PROCEDURE(pname) \
119 procedure = &scan->indexRelation->rd_aminfo->pname; \
120 if (!OidIsValid(procedure->fn_oid)) \
122 RegProcedure procOid = scan->indexRelation->rd_am->pname; \
123 if (!RegProcedureIsValid(procOid)) \
124 elog(ERROR, "invalid %s regproc", CppAsString(pname)); \
125 fmgr_info_cxt(procOid, procedure, scan->indexRelation->rd_indexcxt); \
129 static IndexScanDesc index_beginscan_internal(Relation indexRelation,
130 int nkeys, int norderbys, Snapshot snapshot);
133 /* ----------------------------------------------------------------
134 * index_ interface functions
135 * ----------------------------------------------------------------
139 * index_open - open an index relation by relation OID
141 * If lockmode is not "NoLock", the specified kind of lock is
142 * obtained on the index. (Generally, NoLock should only be
143 * used if the caller knows it has some appropriate lock on the
146 * An error is raised if the index does not exist.
148 * This is a convenience routine adapted for indexscan use.
149 * Some callers may prefer to use relation_open directly.
153 index_open(Oid relationId, LOCKMODE lockmode)
157 r = relation_open(relationId, lockmode);
159 if (r->rd_rel->relkind != RELKIND_INDEX)
161 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
162 errmsg("\"%s\" is not an index",
163 RelationGetRelationName(r))));
169 * index_close - close an index relation
171 * If lockmode is not "NoLock", we then release the specified lock.
173 * Note that it is often sensible to hold a lock beyond index_close;
174 * in that case, the lock is released automatically at xact end.
178 index_close(Relation relation, LOCKMODE lockmode)
180 LockRelId relid = relation->rd_lockInfo.lockRelId;
182 Assert(lockmode >= NoLock && lockmode < MAX_LOCKMODES);
184 /* The relcache does the real work... */
185 RelationClose(relation);
187 if (lockmode != NoLock)
188 UnlockRelationId(&relid, lockmode);
192 * index_insert - insert an index tuple into a relation
196 index_insert(Relation indexRelation,
199 ItemPointer heap_t_ctid,
200 Relation heapRelation,
201 IndexUniqueCheck checkUnique)
206 GET_REL_PROCEDURE(aminsert);
208 if (!(indexRelation->rd_am->ampredlocks))
209 CheckForSerializableConflictIn(indexRelation,
214 * have the am's insert proc do all the work.
216 return DatumGetBool(FunctionCall6(procedure,
217 PointerGetDatum(indexRelation),
218 PointerGetDatum(values),
219 PointerGetDatum(isnull),
220 PointerGetDatum(heap_t_ctid),
221 PointerGetDatum(heapRelation),
222 Int32GetDatum((int32) checkUnique)));
226 * index_beginscan - start a scan of an index with amgettuple
228 * Caller must be holding suitable locks on the heap and the index.
231 index_beginscan(Relation heapRelation,
232 Relation indexRelation,
234 int nkeys, int norderbys)
238 scan = index_beginscan_internal(indexRelation, nkeys, norderbys, snapshot);
241 * Save additional parameters into the scandesc. Everything else was set
242 * up by RelationGetIndexScan.
244 scan->heapRelation = heapRelation;
245 scan->xs_snapshot = snapshot;
251 * index_beginscan_bitmap - start a scan of an index with amgetbitmap
253 * As above, caller had better be holding some lock on the parent heap
254 * relation, even though it's not explicitly mentioned here.
257 index_beginscan_bitmap(Relation indexRelation,
263 scan = index_beginscan_internal(indexRelation, nkeys, 0, snapshot);
266 * Save additional parameters into the scandesc. Everything else was set
267 * up by RelationGetIndexScan.
269 scan->xs_snapshot = snapshot;
275 * index_beginscan_internal --- common code for index_beginscan variants
278 index_beginscan_internal(Relation indexRelation,
279 int nkeys, int norderbys, Snapshot snapshot)
285 GET_REL_PROCEDURE(ambeginscan);
287 if (!(indexRelation->rd_am->ampredlocks))
288 PredicateLockRelation(indexRelation, snapshot);
291 * We hold a reference count to the relcache entry throughout the scan.
293 RelationIncrementReferenceCount(indexRelation);
296 * Tell the AM to open a scan.
298 scan = (IndexScanDesc)
299 DatumGetPointer(FunctionCall3(procedure,
300 PointerGetDatum(indexRelation),
301 Int32GetDatum(nkeys),
302 Int32GetDatum(norderbys)));
308 * index_rescan - (re)start a scan of an index
310 * During a restart, the caller may specify a new set of scankeys and/or
311 * orderbykeys; but the number of keys cannot differ from what index_beginscan
312 * was told. (Later we might relax that to "must not exceed", but currently
313 * the index AMs tend to assume that scan->numberOfKeys is what to believe.)
314 * To restart the scan without changing keys, pass NULL for the key arrays.
315 * (Of course, keys *must* be passed on the first call, unless
316 * scan->numberOfKeys is zero.)
320 index_rescan(IndexScanDesc scan,
321 ScanKey keys, int nkeys,
322 ScanKey orderbys, int norderbys)
327 GET_SCAN_PROCEDURE(amrescan);
329 Assert(nkeys == scan->numberOfKeys);
330 Assert(norderbys == scan->numberOfOrderBys);
332 /* Release any held pin on a heap page */
333 if (BufferIsValid(scan->xs_cbuf))
335 ReleaseBuffer(scan->xs_cbuf);
336 scan->xs_cbuf = InvalidBuffer;
339 scan->xs_continue_hot = false;
341 scan->kill_prior_tuple = false; /* for safety */
343 FunctionCall5(procedure,
344 PointerGetDatum(scan),
345 PointerGetDatum(keys),
346 Int32GetDatum(nkeys),
347 PointerGetDatum(orderbys),
348 Int32GetDatum(norderbys));
352 * index_endscan - end a scan
356 index_endscan(IndexScanDesc scan)
361 GET_SCAN_PROCEDURE(amendscan);
363 /* Release any held pin on a heap page */
364 if (BufferIsValid(scan->xs_cbuf))
366 ReleaseBuffer(scan->xs_cbuf);
367 scan->xs_cbuf = InvalidBuffer;
370 /* End the AM's scan */
371 FunctionCall1(procedure, PointerGetDatum(scan));
373 /* Release index refcount acquired by index_beginscan */
374 RelationDecrementReferenceCount(scan->indexRelation);
376 /* Release the scan data structure itself */
381 * index_markpos - mark a scan position
385 index_markpos(IndexScanDesc scan)
390 GET_SCAN_PROCEDURE(ammarkpos);
392 FunctionCall1(procedure, PointerGetDatum(scan));
396 * index_restrpos - restore a scan position
398 * NOTE: this only restores the internal scan state of the index AM.
399 * The current result tuple (scan->xs_ctup) doesn't change. See comments
400 * for ExecRestrPos().
402 * NOTE: in the presence of HOT chains, mark/restore only works correctly
403 * if the scan's snapshot is MVCC-safe; that ensures that there's at most one
404 * returnable tuple in each HOT chain, and so restoring the prior state at the
405 * granularity of the index AM is sufficient. Since the only current user
406 * of mark/restore functionality is nodeMergejoin.c, this effectively means
407 * that merge-join plans only work for MVCC snapshots. This could be fixed
408 * if necessary, but for now it seems unimportant.
412 index_restrpos(IndexScanDesc scan)
416 Assert(IsMVCCSnapshot(scan->xs_snapshot));
419 GET_SCAN_PROCEDURE(amrestrpos);
421 scan->xs_continue_hot = false;
423 scan->kill_prior_tuple = false; /* for safety */
425 FunctionCall1(procedure, PointerGetDatum(scan));
429 * index_getnext_tid - get the next TID from a scan
431 * The result is the next TID satisfying the scan keys,
432 * or NULL if no more matching tuples exist.
436 index_getnext_tid(IndexScanDesc scan, ScanDirection direction)
442 GET_SCAN_PROCEDURE(amgettuple);
444 Assert(TransactionIdIsValid(RecentGlobalXmin));
447 * The AM's amgettuple proc finds the next index entry matching the scan
448 * keys, and puts the TID into scan->xs_ctup.t_self. It should also set
449 * scan->xs_recheck and possibly scan->xs_itup, though we pay no attention
450 * to those fields here.
452 found = DatumGetBool(FunctionCall2(procedure,
453 PointerGetDatum(scan),
454 Int32GetDatum(direction)));
456 /* Reset kill flag immediately for safety */
457 scan->kill_prior_tuple = false;
459 /* If we're out of index entries, we're done */
462 /* ... but first, release any held pin on a heap page */
463 if (BufferIsValid(scan->xs_cbuf))
465 ReleaseBuffer(scan->xs_cbuf);
466 scan->xs_cbuf = InvalidBuffer;
471 pgstat_count_index_tuples(scan->indexRelation, 1);
473 /* Return the TID of the tuple we found. */
474 return &scan->xs_ctup.t_self;
478 * index_fetch_heap - get the scan's next heap tuple
480 * The result is a visible heap tuple associated with the index TID most
481 * recently fetched by index_getnext_tid, or NULL if no more matching tuples
482 * exist. (There can be more than one matching tuple because of HOT chains,
483 * although when using an MVCC snapshot it should be impossible for more than
484 * one such tuple to exist.)
486 * On success, the buffer containing the heap tup is pinned (the pin will be
487 * dropped in a future index_getnext_tid, index_fetch_heap or index_endscan
490 * Note: caller must check scan->xs_recheck, and perform rechecking of the
491 * scan keys if required. We do not do that here because we don't have
492 * enough information to do it efficiently in the general case.
496 index_fetch_heap(IndexScanDesc scan)
498 ItemPointer tid = &scan->xs_ctup.t_self;
499 bool all_dead = false;
502 /* We can skip the buffer-switching logic if we're in mid-HOT chain. */
503 if (!scan->xs_continue_hot)
505 /* Switch to correct buffer if we don't have it already */
506 Buffer prev_buf = scan->xs_cbuf;
508 scan->xs_cbuf = ReleaseAndReadBuffer(scan->xs_cbuf,
510 ItemPointerGetBlockNumber(tid));
513 * Prune page, but only if we weren't already on this page
515 if (prev_buf != scan->xs_cbuf)
516 heap_page_prune_opt(scan->heapRelation, scan->xs_cbuf,
520 /* Obtain share-lock on the buffer so we can examine visibility */
521 LockBuffer(scan->xs_cbuf, BUFFER_LOCK_SHARE);
522 got_heap_tuple = heap_hot_search_buffer(tid, scan->heapRelation,
527 !scan->xs_continue_hot);
528 LockBuffer(scan->xs_cbuf, BUFFER_LOCK_UNLOCK);
533 * Only in a non-MVCC snapshot can more than one member of the HOT
536 scan->xs_continue_hot = !IsMVCCSnapshot(scan->xs_snapshot);
537 pgstat_count_heap_fetch(scan->indexRelation);
538 return &scan->xs_ctup;
541 /* We've reached the end of the HOT chain. */
542 scan->xs_continue_hot = false;
545 * If we scanned a whole HOT chain and found only dead tuples, tell index
546 * AM to kill its entry for that TID (this will take effect in the next
547 * amgettuple call, in index_getnext_tid). We do not do this when in
548 * recovery because it may violate MVCC to do so. See comments in
549 * RelationGetIndexScan().
551 if (!scan->xactStartedInRecovery)
552 scan->kill_prior_tuple = all_dead;
558 * index_getnext - get the next heap tuple from a scan
560 * The result is the next heap tuple satisfying the scan keys and the
561 * snapshot, or NULL if no more matching tuples exist.
563 * On success, the buffer containing the heap tup is pinned (the pin will be
564 * dropped in a future index_getnext_tid, index_fetch_heap or index_endscan
567 * Note: caller must check scan->xs_recheck, and perform rechecking of the
568 * scan keys if required. We do not do that here because we don't have
569 * enough information to do it efficiently in the general case.
573 index_getnext(IndexScanDesc scan, ScanDirection direction)
580 if (scan->xs_continue_hot)
583 * We are resuming scan of a HOT chain after having returned an
584 * earlier member. Must still hold pin on current heap page.
586 Assert(BufferIsValid(scan->xs_cbuf));
587 Assert(ItemPointerGetBlockNumber(&scan->xs_ctup.t_self) ==
588 BufferGetBlockNumber(scan->xs_cbuf));
592 /* Time to fetch the next TID from the index */
593 tid = index_getnext_tid(scan, direction);
595 /* If we're out of index entries, we're done */
601 * Fetch the next (or only) visible heap tuple for this index entry.
602 * If we don't find anything, loop around and grab the next TID from
605 heapTuple = index_fetch_heap(scan);
606 if (heapTuple != NULL)
610 return NULL; /* failure exit */
614 * index_getbitmap - get all tuples at once from an index scan
616 * Adds the TIDs of all heap tuples satisfying the scan keys to a bitmap.
617 * Since there's no interlock between the index scan and the eventual heap
618 * access, this is only safe to use with MVCC-based snapshots: the heap
619 * item slot could have been replaced by a newer tuple by the time we get
622 * Returns the number of matching tuples found. (Note: this might be only
623 * approximate, so it should only be used for statistical purposes.)
627 index_getbitmap(IndexScanDesc scan, TIDBitmap *bitmap)
634 GET_SCAN_PROCEDURE(amgetbitmap);
636 /* just make sure this is false... */
637 scan->kill_prior_tuple = false;
640 * have the am's getbitmap proc do all the work.
642 d = FunctionCall2(procedure,
643 PointerGetDatum(scan),
644 PointerGetDatum(bitmap));
646 ntids = DatumGetInt64(d);
648 /* If int8 is pass-by-ref, must free the result to avoid memory leak */
649 #ifndef USE_FLOAT8_BYVAL
650 pfree(DatumGetPointer(d));
653 pgstat_count_index_tuples(scan->indexRelation, ntids);
659 * index_bulk_delete - do mass deletion of index entries
661 * callback routine tells whether a given main-heap tuple is
664 * return value is an optional palloc'd struct of statistics
667 IndexBulkDeleteResult *
668 index_bulk_delete(IndexVacuumInfo *info,
669 IndexBulkDeleteResult *stats,
670 IndexBulkDeleteCallback callback,
671 void *callback_state)
673 Relation indexRelation = info->index;
675 IndexBulkDeleteResult *result;
678 GET_REL_PROCEDURE(ambulkdelete);
680 result = (IndexBulkDeleteResult *)
681 DatumGetPointer(FunctionCall4(procedure,
682 PointerGetDatum(info),
683 PointerGetDatum(stats),
684 PointerGetDatum((Pointer) callback),
685 PointerGetDatum(callback_state)));
691 * index_vacuum_cleanup - do post-deletion cleanup of an index
693 * return value is an optional palloc'd struct of statistics
696 IndexBulkDeleteResult *
697 index_vacuum_cleanup(IndexVacuumInfo *info,
698 IndexBulkDeleteResult *stats)
700 Relation indexRelation = info->index;
702 IndexBulkDeleteResult *result;
705 GET_REL_PROCEDURE(amvacuumcleanup);
707 result = (IndexBulkDeleteResult *)
708 DatumGetPointer(FunctionCall2(procedure,
709 PointerGetDatum(info),
710 PointerGetDatum(stats)));
716 * index_can_return - does index support index-only scans?
720 index_can_return(Relation indexRelation)
726 /* amcanreturn is optional; assume FALSE if not provided by AM */
727 if (!RegProcedureIsValid(indexRelation->rd_am->amcanreturn))
730 GET_REL_PROCEDURE(amcanreturn);
732 return DatumGetBool(FunctionCall1(procedure,
733 PointerGetDatum(indexRelation)));
739 * Index access methods typically require support routines that are
740 * not directly the implementation of any WHERE-clause query operator
741 * and so cannot be kept in pg_amop. Instead, such routines are kept
742 * in pg_amproc. These registered procedure OIDs are assigned numbers
743 * according to a convention established by the access method.
744 * The general index code doesn't know anything about the routines
745 * involved; it just builds an ordered list of them for
746 * each attribute on which an index is defined.
748 * As of Postgres 8.3, support routines within an operator family
749 * are further subdivided by the "left type" and "right type" of the
750 * query operator(s) that they support. The "default" functions for a
751 * particular indexed attribute are those with both types equal to
752 * the index opclass' opcintype (note that this is subtly different
753 * from the indexed attribute's own type: it may be a binary-compatible
754 * type instead). Only the default functions are stored in relcache
755 * entries --- access methods can use the syscache to look up non-default
758 * This routine returns the requested default procedure OID for a
759 * particular indexed attribute.
763 index_getprocid(Relation irel,
771 nproc = irel->rd_am->amsupport;
773 Assert(procnum > 0 && procnum <= (uint16) nproc);
775 procindex = (nproc * (attnum - 1)) + (procnum - 1);
777 loc = irel->rd_support;
781 return loc[procindex];
787 * This routine allows index AMs to keep fmgr lookup info for
788 * support procs in the relcache. As above, only the "default"
789 * functions for any particular indexed attribute are cached.
791 * Note: the return value points into cached data that will be lost during
792 * any relcache rebuild! Therefore, either use the callinfo right away,
793 * or save it only after having acquired some type of lock on the index rel.
797 index_getprocinfo(Relation irel,
805 nproc = irel->rd_am->amsupport;
807 Assert(procnum > 0 && procnum <= (uint16) nproc);
809 procindex = (nproc * (attnum - 1)) + (procnum - 1);
811 locinfo = irel->rd_supportinfo;
813 Assert(locinfo != NULL);
815 locinfo += procindex;
817 /* Initialize the lookup info if first time through */
818 if (locinfo->fn_oid == InvalidOid)
820 RegProcedure *loc = irel->rd_support;
825 procId = loc[procindex];
828 * Complain if function was not found during IndexSupportInitialize.
829 * This should not happen unless the system tables contain bogus
830 * entries for the index opclass. (If an AM wants to allow a support
831 * function to be optional, it can use index_getprocid.)
833 if (!RegProcedureIsValid(procId))
834 elog(ERROR, "missing support function %d for attribute %d of index \"%s\"",
835 procnum, attnum, RelationGetRelationName(irel));
837 fmgr_info_cxt(procId, locinfo, irel->rd_indexcxt);