1 /*-------------------------------------------------------------------------
4 * general index access method routines
6 * Portions Copyright (c) 1996-2006, 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.96 2006/12/23 00:43:08 tgl 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"
68 #include "utils/relcache.h"
71 /* ----------------------------------------------------------------
72 * macros used in index_ routines
73 * ----------------------------------------------------------------
75 #define RELATION_CHECKS \
77 AssertMacro(RelationIsValid(indexRelation)), \
78 AssertMacro(PointerIsValid(indexRelation->rd_am)) \
83 AssertMacro(IndexScanIsValid(scan)), \
84 AssertMacro(RelationIsValid(scan->indexRelation)), \
85 AssertMacro(PointerIsValid(scan->indexRelation->rd_am)) \
88 #define GET_REL_PROCEDURE(pname) \
90 procedure = &indexRelation->rd_aminfo->pname; \
91 if (!OidIsValid(procedure->fn_oid)) \
93 RegProcedure procOid = indexRelation->rd_am->pname; \
94 if (!RegProcedureIsValid(procOid)) \
95 elog(ERROR, "invalid %s regproc", CppAsString(pname)); \
96 fmgr_info_cxt(procOid, procedure, indexRelation->rd_indexcxt); \
100 #define GET_SCAN_PROCEDURE(pname) \
102 procedure = &scan->indexRelation->rd_aminfo->pname; \
103 if (!OidIsValid(procedure->fn_oid)) \
105 RegProcedure procOid = scan->indexRelation->rd_am->pname; \
106 if (!RegProcedureIsValid(procOid)) \
107 elog(ERROR, "invalid %s regproc", CppAsString(pname)); \
108 fmgr_info_cxt(procOid, procedure, scan->indexRelation->rd_indexcxt); \
112 static IndexScanDesc index_beginscan_internal(Relation indexRelation,
113 int nkeys, ScanKey key);
116 /* ----------------------------------------------------------------
117 * index_ interface functions
118 * ----------------------------------------------------------------
122 * index_open - open an index relation by relation OID
124 * If lockmode is not "NoLock", the specified kind of lock is
125 * obtained on the index. (Generally, NoLock should only be
126 * used if the caller knows it has some appropriate lock on the
129 * An error is raised if the index does not exist.
131 * This is a convenience routine adapted for indexscan use.
132 * Some callers may prefer to use relation_open directly.
136 index_open(Oid relationId, LOCKMODE lockmode)
140 r = relation_open(relationId, lockmode);
142 if (r->rd_rel->relkind != RELKIND_INDEX)
144 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
145 errmsg("\"%s\" is not an index",
146 RelationGetRelationName(r))));
148 pgstat_initstats(&r->pgstat_info, r);
154 * index_close - close an index relation
156 * If lockmode is not "NoLock", we then release the specified lock.
158 * Note that it is often sensible to hold a lock beyond index_close;
159 * in that case, the lock is released automatically at xact end.
163 index_close(Relation relation, LOCKMODE lockmode)
165 LockRelId relid = relation->rd_lockInfo.lockRelId;
167 Assert(lockmode >= NoLock && lockmode < MAX_LOCKMODES);
169 /* The relcache does the real work... */
170 RelationClose(relation);
172 if (lockmode != NoLock)
173 UnlockRelationId(&relid, lockmode);
177 * index_insert - insert an index tuple into a relation
181 index_insert(Relation indexRelation,
184 ItemPointer heap_t_ctid,
185 Relation heapRelation,
186 bool check_uniqueness)
191 GET_REL_PROCEDURE(aminsert);
194 * have the am's insert proc do all the work.
196 return DatumGetBool(FunctionCall6(procedure,
197 PointerGetDatum(indexRelation),
198 PointerGetDatum(values),
199 PointerGetDatum(isnull),
200 PointerGetDatum(heap_t_ctid),
201 PointerGetDatum(heapRelation),
202 BoolGetDatum(check_uniqueness)));
206 * index_beginscan - start a scan of an index with amgettuple
208 * Note: heapRelation may be NULL if there is no intention of calling
209 * index_getnext on this scan; index_getnext_indexitem will not use the
210 * heapRelation link (nor the snapshot). However, the caller had better
211 * be holding some kind of lock on the heap relation in any case, to ensure
212 * no one deletes it (or the index) out from under us. Caller must also
213 * be holding a lock on the index.
216 index_beginscan(Relation heapRelation,
217 Relation indexRelation,
219 int nkeys, ScanKey key)
223 scan = index_beginscan_internal(indexRelation, nkeys, key);
226 * Save additional parameters into the scandesc. Everything else was set
227 * up by RelationGetIndexScan.
229 scan->is_multiscan = false;
230 scan->heapRelation = heapRelation;
231 scan->xs_snapshot = snapshot;
237 * index_beginscan_multi - start a scan of an index with amgetmulti
239 * As above, caller had better be holding some lock on the parent heap
240 * relation, even though it's not explicitly mentioned here.
243 index_beginscan_multi(Relation indexRelation,
245 int nkeys, ScanKey key)
249 scan = index_beginscan_internal(indexRelation, nkeys, key);
252 * Save additional parameters into the scandesc. Everything else was set
253 * up by RelationGetIndexScan.
255 scan->is_multiscan = true;
256 scan->xs_snapshot = snapshot;
262 * index_beginscan_internal --- common code for index_beginscan variants
265 index_beginscan_internal(Relation indexRelation,
266 int nkeys, ScanKey key)
272 GET_REL_PROCEDURE(ambeginscan);
275 * We hold a reference count to the relcache entry throughout the scan.
277 RelationIncrementReferenceCount(indexRelation);
280 * Tell the AM to open a scan.
282 scan = (IndexScanDesc)
283 DatumGetPointer(FunctionCall3(procedure,
284 PointerGetDatum(indexRelation),
285 Int32GetDatum(nkeys),
286 PointerGetDatum(key)));
292 * index_rescan - (re)start a scan of an index
294 * The caller may specify a new set of scankeys (but the number of keys
295 * cannot change). To restart the scan without changing keys, pass NULL
298 * Note that this is also called when first starting an indexscan;
299 * see RelationGetIndexScan. Keys *must* be passed in that case,
300 * unless scan->numberOfKeys is zero.
304 index_rescan(IndexScanDesc scan, ScanKey key)
309 GET_SCAN_PROCEDURE(amrescan);
311 /* Release any held pin on a heap page */
312 if (BufferIsValid(scan->xs_cbuf))
314 ReleaseBuffer(scan->xs_cbuf);
315 scan->xs_cbuf = InvalidBuffer;
318 scan->kill_prior_tuple = false; /* for safety */
320 FunctionCall2(procedure,
321 PointerGetDatum(scan),
322 PointerGetDatum(key));
326 * index_endscan - end a scan
330 index_endscan(IndexScanDesc scan)
335 GET_SCAN_PROCEDURE(amendscan);
337 /* Release any held pin on a heap page */
338 if (BufferIsValid(scan->xs_cbuf))
340 ReleaseBuffer(scan->xs_cbuf);
341 scan->xs_cbuf = InvalidBuffer;
344 /* End the AM's scan */
345 FunctionCall1(procedure, PointerGetDatum(scan));
347 /* Release index refcount acquired by index_beginscan */
348 RelationDecrementReferenceCount(scan->indexRelation);
350 /* Release the scan data structure itself */
355 * index_markpos - mark a scan position
359 index_markpos(IndexScanDesc scan)
364 GET_SCAN_PROCEDURE(ammarkpos);
366 FunctionCall1(procedure, PointerGetDatum(scan));
370 * index_restrpos - restore a scan position
372 * NOTE: this only restores the internal scan state of the index AM.
373 * The current result tuple (scan->xs_ctup) doesn't change. See comments
374 * for ExecRestrPos().
378 index_restrpos(IndexScanDesc scan)
383 GET_SCAN_PROCEDURE(amrestrpos);
385 scan->kill_prior_tuple = false; /* for safety */
387 FunctionCall1(procedure, PointerGetDatum(scan));
391 * index_getnext - get the next heap tuple from a scan
393 * The result is the next heap tuple satisfying the scan keys and the
394 * snapshot, or NULL if no more matching tuples exist. On success,
395 * the buffer containing the heap tuple is pinned (the pin will be dropped
396 * at the next index_getnext or index_endscan).
400 index_getnext(IndexScanDesc scan, ScanDirection direction)
402 HeapTuple heapTuple = &scan->xs_ctup;
406 GET_SCAN_PROCEDURE(amgettuple);
408 /* just make sure this is false... */
409 scan->kill_prior_tuple = false;
416 * The AM's gettuple proc finds the next tuple matching the scan keys.
418 found = DatumGetBool(FunctionCall2(procedure,
419 PointerGetDatum(scan),
420 Int32GetDatum(direction)));
422 /* Reset kill flag immediately for safety */
423 scan->kill_prior_tuple = false;
427 /* Release any held pin on a heap page */
428 if (BufferIsValid(scan->xs_cbuf))
430 ReleaseBuffer(scan->xs_cbuf);
431 scan->xs_cbuf = InvalidBuffer;
433 return NULL; /* failure exit */
436 pgstat_count_index_tuples(&scan->xs_pgstat_info, 1);
439 * Fetch the heap tuple and see if it matches the snapshot.
441 if (heap_release_fetch(scan->heapRelation, scan->xs_snapshot,
442 heapTuple, &scan->xs_cbuf, true,
443 &scan->xs_pgstat_info))
446 /* Skip if no undeleted tuple at this location */
447 if (heapTuple->t_data == NULL)
451 * If we can't see it, maybe no one else can either. Check to see if
452 * the tuple is dead to all transactions. If so, signal the index AM
453 * to not return it on future indexscans.
455 * We told heap_release_fetch to keep a pin on the buffer, so we can
456 * re-access the tuple here. But we must re-lock the buffer first.
458 LockBuffer(scan->xs_cbuf, BUFFER_LOCK_SHARE);
460 if (HeapTupleSatisfiesVacuum(heapTuple->t_data, RecentGlobalXmin,
461 scan->xs_cbuf) == HEAPTUPLE_DEAD)
462 scan->kill_prior_tuple = true;
464 LockBuffer(scan->xs_cbuf, BUFFER_LOCK_UNLOCK);
472 * index_getnext_indexitem - get the next index tuple from a scan
474 * Finds the next index tuple satisfying the scan keys. Note that the
475 * corresponding heap tuple is not accessed, and thus no time qual (snapshot)
476 * check is done, other than the index AM's internal check for killed tuples
477 * (which most callers of this routine will probably want to suppress by
478 * setting scan->ignore_killed_tuples = false).
480 * On success (TRUE return), the heap TID of the found index entry is in
481 * scan->xs_ctup.t_self. scan->xs_cbuf is untouched.
485 index_getnext_indexitem(IndexScanDesc scan,
486 ScanDirection direction)
492 GET_SCAN_PROCEDURE(amgettuple);
494 /* just make sure this is false... */
495 scan->kill_prior_tuple = false;
498 * have the am's gettuple proc do all the work.
500 found = DatumGetBool(FunctionCall2(procedure,
501 PointerGetDatum(scan),
502 Int32GetDatum(direction)));
505 pgstat_count_index_tuples(&scan->xs_pgstat_info, 1);
511 * index_getmulti - get multiple tuples from an index scan
513 * Collects the TIDs of multiple heap tuples satisfying the scan keys.
514 * Since there's no interlock between the index scan and the eventual heap
515 * access, this is only safe to use with MVCC-based snapshots: the heap
516 * item slot could have been replaced by a newer tuple by the time we get
519 * A TRUE result indicates more calls should occur; a FALSE result says the
520 * scan is done. *returned_tids could be zero or nonzero in either case.
524 index_getmulti(IndexScanDesc scan,
525 ItemPointer tids, int32 max_tids,
526 int32 *returned_tids)
532 GET_SCAN_PROCEDURE(amgetmulti);
534 /* just make sure this is false... */
535 scan->kill_prior_tuple = false;
538 * have the am's getmulti proc do all the work.
540 found = DatumGetBool(FunctionCall4(procedure,
541 PointerGetDatum(scan),
542 PointerGetDatum(tids),
543 Int32GetDatum(max_tids),
544 PointerGetDatum(returned_tids)));
546 pgstat_count_index_tuples(&scan->xs_pgstat_info, *returned_tids);
552 * index_bulk_delete - do mass deletion of index entries
554 * callback routine tells whether a given main-heap tuple is
557 * return value is an optional palloc'd struct of statistics
560 IndexBulkDeleteResult *
561 index_bulk_delete(IndexVacuumInfo *info,
562 IndexBulkDeleteResult *stats,
563 IndexBulkDeleteCallback callback,
564 void *callback_state)
566 Relation indexRelation = info->index;
568 IndexBulkDeleteResult *result;
571 GET_REL_PROCEDURE(ambulkdelete);
573 result = (IndexBulkDeleteResult *)
574 DatumGetPointer(FunctionCall4(procedure,
575 PointerGetDatum(info),
576 PointerGetDatum(stats),
577 PointerGetDatum((Pointer) callback),
578 PointerGetDatum(callback_state)));
584 * index_vacuum_cleanup - do post-deletion cleanup of an index
586 * return value is an optional palloc'd struct of statistics
589 IndexBulkDeleteResult *
590 index_vacuum_cleanup(IndexVacuumInfo *info,
591 IndexBulkDeleteResult *stats)
593 Relation indexRelation = info->index;
595 IndexBulkDeleteResult *result;
598 GET_REL_PROCEDURE(amvacuumcleanup);
600 result = (IndexBulkDeleteResult *)
601 DatumGetPointer(FunctionCall2(procedure,
602 PointerGetDatum(info),
603 PointerGetDatum(stats)));
611 * Index access methods typically require support routines that are
612 * not directly the implementation of any WHERE-clause query operator
613 * and so cannot be kept in pg_amop. Instead, such routines are kept
614 * in pg_amproc. These registered procedure OIDs are assigned numbers
615 * according to a convention established by the access method.
616 * The general index code doesn't know anything about the routines
617 * involved; it just builds an ordered list of them for
618 * each attribute on which an index is defined.
620 * As of Postgres 8.3, support routines within an operator family
621 * are further subdivided by the "left type" and "right type" of the
622 * query operator(s) that they support. The "default" functions for a
623 * particular indexed attribute are those with both types equal to
624 * the index opclass' opcintype (note that this is subtly different
625 * from the indexed attribute's own type: it may be a binary-compatible
626 * type instead). Only the default functions are stored in relcache
627 * entries --- access methods can use the syscache to look up non-default
630 * This routine returns the requested default procedure OID for a
631 * particular indexed attribute.
635 index_getprocid(Relation irel,
643 nproc = irel->rd_am->amsupport;
645 Assert(procnum > 0 && procnum <= (uint16) nproc);
647 procindex = (nproc * (attnum - 1)) + (procnum - 1);
649 loc = irel->rd_support;
653 return loc[procindex];
659 * This routine allows index AMs to keep fmgr lookup info for
660 * support procs in the relcache. As above, only the "default"
661 * functions for any particular indexed attribute are cached.
663 * Note: the return value points into cached data that will be lost during
664 * any relcache rebuild! Therefore, either use the callinfo right away,
665 * or save it only after having acquired some type of lock on the index rel.
669 index_getprocinfo(Relation irel,
677 nproc = irel->rd_am->amsupport;
679 Assert(procnum > 0 && procnum <= (uint16) nproc);
681 procindex = (nproc * (attnum - 1)) + (procnum - 1);
683 locinfo = irel->rd_supportinfo;
685 Assert(locinfo != NULL);
687 locinfo += procindex;
689 /* Initialize the lookup info if first time through */
690 if (locinfo->fn_oid == InvalidOid)
692 RegProcedure *loc = irel->rd_support;
697 procId = loc[procindex];
700 * Complain if function was not found during IndexSupportInitialize.
701 * This should not happen unless the system tables contain bogus
702 * entries for the index opclass. (If an AM wants to allow a support
703 * function to be optional, it can use index_getprocid.)
705 if (!RegProcedureIsValid(procId))
706 elog(ERROR, "missing support function %d for attribute %d of index \"%s\"",
707 procnum, attnum, RelationGetRelationName(irel));
709 fmgr_info_cxt(procId, locinfo, irel->rd_indexcxt);