1 /*-------------------------------------------------------------------------
4 * general index access method routines
6 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/access/index/indexam.c,v 1.62 2002/09/04 20:31:09 momjian Exp $
14 * index_open - open an index relation by relation OID
15 * index_openrv - open an index relation specified by a RangeVar
16 * index_openr - open a system index relation by name
17 * index_close - close an index relation
18 * index_beginscan - start a scan of an index
19 * index_rescan - restart a scan of an index
20 * index_endscan - end a scan
21 * index_insert - insert an index tuple into a relation
22 * index_markpos - mark a scan position
23 * index_restrpos - restore a scan position
24 * index_getnext - get the next tuple from a scan
25 * index_bulk_delete - bulk deletion of index tuples
26 * index_cost_estimator - fetch amcostestimate procedure OID
27 * index_getprocid - get a support procedure OID
30 * This file contains the index_ routines which used
31 * to be a scattered collection of stuff in access/genam.
35 * Scans are implemented as follows:
37 * `0' represents an invalid item pointer.
38 * `-' represents an unknown item pointer.
39 * `X' represents a known item pointers.
40 * `+' represents known or invalid item pointers.
41 * `*' represents any item pointers.
43 * State is represented by a triple of these symbols in the order of
44 * previous, current, next. Note that the case of reverse scans works
48 * (1) + + - + 0 0 (if the next item pointer is invalid)
49 * (2) + X - (otherwise)
50 * (3) * 0 0 * 0 0 (no change)
51 * (4) + X 0 X 0 0 (shift)
52 * (5) * + X + X - (shift, add unknown)
54 * All other states cannot occur.
56 * Note: It would be possible to cache the status of the previous and
57 * next item pointer using the flags.
59 *-------------------------------------------------------------------------
64 #include "access/genam.h"
65 #include "access/heapam.h"
66 #include "utils/relcache.h"
70 /* ----------------------------------------------------------------
71 * macros used in index_ routines
72 * ----------------------------------------------------------------
74 #define RELATION_CHECKS \
76 AssertMacro(RelationIsValid(indexRelation)), \
77 AssertMacro(PointerIsValid(indexRelation->rd_am)) \
82 AssertMacro(IndexScanIsValid(scan)), \
83 AssertMacro(RelationIsValid(scan->indexRelation)), \
84 AssertMacro(PointerIsValid(scan->indexRelation->rd_am)) \
87 #define GET_REL_PROCEDURE(x,y) \
89 procedure = indexRelation->rd_am->y, \
90 (!RegProcedureIsValid(procedure)) ? \
91 elog(ERROR, "index_%s: invalid %s regproc", \
92 CppAsString(x), CppAsString(y)) \
96 #define GET_SCAN_PROCEDURE(x,y) \
98 procedure = scan->indexRelation->rd_am->y, \
99 (!RegProcedureIsValid(procedure)) ? \
100 elog(ERROR, "index_%s: invalid %s regproc", \
101 CppAsString(x), CppAsString(y)) \
106 /* ----------------------------------------------------------------
107 * index_ interface functions
108 * ----------------------------------------------------------------
112 * index_open - open an index relation by relation OID
114 * Note: we acquire no lock on the index. An AccessShareLock is
115 * acquired by index_beginscan (and released by index_endscan).
116 * Generally, the caller should already hold some type of lock on
117 * the parent relation to ensure that the index doesn't disappear.
119 * This is a convenience routine adapted for indexscan use.
120 * Some callers may prefer to use relation_open directly.
124 index_open(Oid relationId)
128 r = relation_open(relationId, NoLock);
130 if (r->rd_rel->relkind != RELKIND_INDEX)
131 elog(ERROR, "%s is not an index relation",
132 RelationGetRelationName(r));
134 pgstat_initstats(&r->pgstat_info, r);
140 * index_openrv - open an index relation specified
143 * As above, but relation is specified by a RangeVar.
147 index_openrv(const RangeVar *relation)
151 r = relation_openrv(relation, NoLock);
153 if (r->rd_rel->relkind != RELKIND_INDEX)
154 elog(ERROR, "%s is not an index relation",
155 RelationGetRelationName(r));
157 pgstat_initstats(&r->pgstat_info, r);
163 * index_openr - open a system index relation specified by name.
165 * As above, but the relation is specified by an unqualified name;
166 * it is assumed to live in the system catalog namespace.
170 index_openr(const char *sysRelationName)
174 r = relation_openr(sysRelationName, NoLock);
176 if (r->rd_rel->relkind != RELKIND_INDEX)
177 elog(ERROR, "%s is not an index relation",
178 RelationGetRelationName(r));
180 pgstat_initstats(&r->pgstat_info, r);
186 * index_close - close a index relation
188 * presently the relcache routines do all the work we need
189 * to open/close index relations.
193 index_close(Relation relation)
195 RelationClose(relation);
199 * index_insert - insert an index tuple into a relation
203 index_insert(Relation indexRelation,
206 ItemPointer heap_t_ctid,
207 Relation heapRelation,
208 bool check_uniqueness)
210 RegProcedure procedure;
211 InsertIndexResult specificResult;
214 GET_REL_PROCEDURE(insert, aminsert);
217 * have the am's insert proc do all the work.
219 specificResult = (InsertIndexResult)
220 DatumGetPointer(OidFunctionCall6(procedure,
221 PointerGetDatum(indexRelation),
222 PointerGetDatum(datums),
223 PointerGetDatum(nulls),
224 PointerGetDatum(heap_t_ctid),
225 PointerGetDatum(heapRelation),
226 BoolGetDatum(check_uniqueness)));
228 /* must be pfree'ed */
229 return specificResult;
233 * index_beginscan - start a scan of an index
235 * Note: heapRelation may be NULL if there is no intention of calling
236 * index_getnext on this scan; index_getnext_indexitem will not use the
237 * heapRelation link (nor the snapshot). However, the caller had better
238 * be holding some kind of lock on the heap relation in any case, to ensure
239 * no one deletes it (or the index) out from under us.
243 index_beginscan(Relation heapRelation,
244 Relation indexRelation,
246 int nkeys, ScanKey key)
249 RegProcedure procedure;
252 GET_REL_PROCEDURE(beginscan, ambeginscan);
254 RelationIncrementReferenceCount(indexRelation);
257 * Acquire AccessShareLock for the duration of the scan
259 * Note: we could get an SI inval message here and consequently have to
260 * rebuild the relcache entry. The refcount increment above ensures
261 * that we will rebuild it and not just flush it...
263 LockRelation(indexRelation, AccessShareLock);
266 * Tell the AM to open a scan.
268 scan = (IndexScanDesc)
269 DatumGetPointer(OidFunctionCall3(procedure,
270 PointerGetDatum(indexRelation),
271 Int32GetDatum(nkeys),
272 PointerGetDatum(key)));
275 * Save additional parameters into the scandesc. Everything else was
276 * set up by RelationGetIndexScan.
278 scan->heapRelation = heapRelation;
279 scan->xs_snapshot = snapshot;
282 * We want to look up the amgettuple procedure just once per scan, not
283 * once per index_getnext call. So do it here and save the fmgr info
284 * result in the scan descriptor.
286 GET_SCAN_PROCEDURE(beginscan, amgettuple);
287 fmgr_info(procedure, &scan->fn_getnext);
293 * index_rescan - (re)start a scan of an index
295 * The caller may specify a new set of scankeys (but the number of keys
296 * cannot change). Note that this is also called when first starting
297 * an indexscan; see RelationGetIndexScan.
301 index_rescan(IndexScanDesc scan, ScanKey key)
303 RegProcedure procedure;
306 GET_SCAN_PROCEDURE(rescan, amrescan);
308 scan->kill_prior_tuple = false; /* for safety */
309 scan->keys_are_unique = false; /* may be set by amrescan */
310 scan->got_tuple = false;
312 OidFunctionCall2(procedure,
313 PointerGetDatum(scan),
314 PointerGetDatum(key));
316 pgstat_reset_index_scan(&scan->xs_pgstat_info);
320 * index_endscan - end a scan
324 index_endscan(IndexScanDesc scan)
326 RegProcedure procedure;
329 GET_SCAN_PROCEDURE(endscan, amendscan);
331 /* Release any held pin on a heap page */
332 if (BufferIsValid(scan->xs_cbuf))
334 ReleaseBuffer(scan->xs_cbuf);
335 scan->xs_cbuf = InvalidBuffer;
338 /* End the AM's scan */
339 OidFunctionCall1(procedure, PointerGetDatum(scan));
341 /* Release index lock and refcount acquired by index_beginscan */
343 UnlockRelation(scan->indexRelation, AccessShareLock);
345 RelationDecrementReferenceCount(scan->indexRelation);
347 /* Release the scan data structure itself */
352 * index_markpos - mark a scan position
356 index_markpos(IndexScanDesc scan)
358 RegProcedure procedure;
361 GET_SCAN_PROCEDURE(markpos, ammarkpos);
363 OidFunctionCall1(procedure, PointerGetDatum(scan));
367 * index_restrpos - restore a scan position
371 index_restrpos(IndexScanDesc scan)
373 RegProcedure procedure;
376 GET_SCAN_PROCEDURE(restrpos, amrestrpos);
378 scan->kill_prior_tuple = false; /* for safety */
379 scan->got_tuple = false;
381 OidFunctionCall1(procedure, PointerGetDatum(scan));
385 * index_getnext - get the next heap tuple from a scan
387 * The result is the next heap tuple satisfying the scan keys and the
388 * snapshot, or NULL if no more matching tuples exist. On success,
389 * the buffer containing the heap tuple is pinned (the pin will be dropped
390 * at the next index_getnext or index_endscan). The index TID corresponding
391 * to the heap tuple can be obtained if needed from scan->currentItemData.
395 index_getnext(IndexScanDesc scan, ScanDirection direction)
397 HeapTuple heapTuple = &scan->xs_ctup;
401 /* Release any previously held pin */
402 if (BufferIsValid(scan->xs_cbuf))
404 ReleaseBuffer(scan->xs_cbuf);
405 scan->xs_cbuf = InvalidBuffer;
408 /* just make sure this is false... */
409 scan->kill_prior_tuple = false;
412 * Can skip entering the index AM if we already got a tuple and it
415 if (scan->keys_are_unique && scan->got_tuple)
423 pgstat_count_index_scan(&scan->xs_pgstat_info);
426 * The AM's gettuple proc finds the next tuple matching the scan
427 * keys. index_beginscan already set up fn_getnext.
429 found = DatumGetBool(FunctionCall2(&scan->fn_getnext,
430 PointerGetDatum(scan),
431 Int32GetDatum(direction)));
433 /* Reset kill flag immediately for safety */
434 scan->kill_prior_tuple = false;
437 return NULL; /* failure exit */
440 * Fetch the heap tuple and see if it matches the snapshot.
442 if (heap_fetch(scan->heapRelation, scan->xs_snapshot,
443 heapTuple, &scan->xs_cbuf, true,
444 &scan->xs_pgstat_info))
447 /* Skip if no tuple at this location */
448 if (heapTuple->t_data == NULL)
449 continue; /* should we raise an error instead? */
452 * If we can't see it, maybe no one else can either. Check to see
453 * if the tuple is dead to all transactions. If so, signal the
454 * index AM to not return it on future indexscans.
456 * We told heap_fetch to keep a pin on the buffer, so we can
457 * re-access the tuple here. But we must re-lock the buffer
458 * first. Also, it's just barely possible for an update of hint
459 * bits to occur here.
461 LockBuffer(scan->xs_cbuf, BUFFER_LOCK_SHARE);
462 sv_infomask = heapTuple->t_data->t_infomask;
464 if (HeapTupleSatisfiesVacuum(heapTuple->t_data, RecentGlobalXmin) ==
466 scan->kill_prior_tuple = true;
468 if (sv_infomask != heapTuple->t_data->t_infomask)
469 SetBufferCommitInfoNeedsSave(scan->xs_cbuf);
470 LockBuffer(scan->xs_cbuf, BUFFER_LOCK_UNLOCK);
471 ReleaseBuffer(scan->xs_cbuf);
472 scan->xs_cbuf = InvalidBuffer;
476 scan->got_tuple = true;
478 pgstat_count_index_getnext(&scan->xs_pgstat_info);
484 * index_getnext_indexitem - get the next index tuple from a scan
486 * Finds the next index tuple satisfying the scan keys. Note that the
487 * corresponding heap tuple is not accessed, and thus no time qual (snapshot)
488 * check is done, other than the index AM's internal check for killed tuples
489 * (which most callers of this routine will probably want to suppress by
490 * setting scan->ignore_killed_tuples = false).
492 * On success (TRUE return), the found index TID is in scan->currentItemData,
493 * and its heap TID is in scan->xs_ctup.t_self. scan->xs_cbuf is untouched.
497 index_getnext_indexitem(IndexScanDesc scan,
498 ScanDirection direction)
504 /* just make sure this is false... */
505 scan->kill_prior_tuple = false;
508 * have the am's gettuple proc do all the work. index_beginscan
509 * already set up fn_getnext.
511 found = DatumGetBool(FunctionCall2(&scan->fn_getnext,
512 PointerGetDatum(scan),
513 Int32GetDatum(direction)));
519 * index_bulk_delete - do mass deletion of index entries
521 * callback routine tells whether a given main-heap tuple is
524 * return value is an optional palloc'd struct of statistics
527 IndexBulkDeleteResult *
528 index_bulk_delete(Relation indexRelation,
529 IndexBulkDeleteCallback callback,
530 void *callback_state)
532 RegProcedure procedure;
533 IndexBulkDeleteResult *result;
536 GET_REL_PROCEDURE(bulk_delete, ambulkdelete);
538 result = (IndexBulkDeleteResult *)
539 DatumGetPointer(OidFunctionCall3(procedure,
540 PointerGetDatum(indexRelation),
541 PointerGetDatum((Pointer) callback),
542 PointerGetDatum(callback_state)));
548 * index_cost_estimator
550 * Fetch the amcostestimate procedure OID for an index.
552 * We could combine fetching and calling the procedure,
553 * as index_insert does for example; but that would require
554 * importing a bunch of planner/optimizer stuff into this file.
558 index_cost_estimator(Relation indexRelation)
560 RegProcedure procedure;
563 GET_REL_PROCEDURE(cost_estimator, amcostestimate);
571 * Some indexed access methods may require support routines that are
572 * not in the operator class/operator model imposed by pg_am. These
573 * access methods may store the OIDs of registered procedures they
574 * need in pg_amproc. These registered procedure OIDs are ordered in
575 * a way that makes sense to the access method, and used only by the
576 * access method. The general index code doesn't know anything about
577 * the routines involved; it just builds an ordered list of them for
578 * each attribute on which an index is defined.
580 * This routine returns the requested procedure OID for a particular
585 index_getprocid(Relation irel,
593 nproc = irel->rd_am->amsupport;
595 Assert(procnum > 0 && procnum <= (uint16) nproc);
597 procindex = (nproc * (attnum - 1)) + (procnum - 1);
599 loc = irel->rd_support;
603 return loc[procindex];
609 * This routine allows index AMs to keep fmgr lookup info for
610 * support procs in the relcache.
614 index_getprocinfo(Relation irel,
622 nproc = irel->rd_am->amsupport;
624 Assert(procnum > 0 && procnum <= (uint16) nproc);
626 procindex = (nproc * (attnum - 1)) + (procnum - 1);
628 locinfo = irel->rd_supportinfo;
630 Assert(locinfo != NULL);
632 locinfo += procindex;
634 /* Initialize the lookup info if first time through */
635 if (locinfo->fn_oid == InvalidOid)
637 RegProcedure *loc = irel->rd_support;
642 procId = loc[procindex];
645 * Complain if function was not found during
646 * IndexSupportInitialize. This should not happen unless the
647 * system tables contain bogus entries for the index opclass. (If
648 * an AM wants to allow a support function to be optional, it can
649 * use index_getprocid.)
651 if (!RegProcedureIsValid(procId))
652 elog(ERROR, "Missing support function %d for attribute %d of index %s",
653 procnum, attnum, RelationGetRelationName(irel));
655 fmgr_info_cxt(procId, locinfo, irel->rd_indexcxt);