]> granicus.if.org Git - postgresql/blob - src/backend/access/index/indexam.c
Run pgindent on 9.2 source tree in preparation for first 9.3
[postgresql] / src / backend / access / index / indexam.c
1 /*-------------------------------------------------------------------------
2  *
3  * indexam.c
4  *        general index access method routines
5  *
6  * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        src/backend/access/index/indexam.c
12  *
13  * INTERFACE ROUTINES
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
32  *
33  * NOTES
34  *              This file contains the index_ routines which used
35  *              to be a scattered collection of stuff in access/genam.
36  *
37  *
38  * old comments
39  *              Scans are implemented as follows:
40  *
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.
46  *
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
49  *              identically.
50  *
51  *                              State   Result
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)
57  *
58  *              All other states cannot occur.
59  *
60  *              Note: It would be possible to cache the status of the previous and
61  *                        next item pointer using the flags.
62  *
63  *-------------------------------------------------------------------------
64  */
65
66 #include "postgres.h"
67
68 #include "access/relscan.h"
69 #include "access/transam.h"
70 #include "catalog/index.h"
71 #include "pgstat.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"
77
78
79 /* ----------------------------------------------------------------
80  *                                      macros used in index_ routines
81  *
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  * ----------------------------------------------------------------
90  */
91 #define RELATION_CHECKS \
92 ( \
93         AssertMacro(RelationIsValid(indexRelation)), \
94         AssertMacro(PointerIsValid(indexRelation->rd_am)), \
95         AssertMacro(!ReindexIsProcessingIndex(RelationGetRelid(indexRelation))) \
96 )
97
98 #define SCAN_CHECKS \
99 ( \
100         AssertMacro(IndexScanIsValid(scan)), \
101         AssertMacro(RelationIsValid(scan->indexRelation)), \
102         AssertMacro(PointerIsValid(scan->indexRelation->rd_am)) \
103 )
104
105 #define GET_REL_PROCEDURE(pname) \
106 do { \
107         procedure = &indexRelation->rd_aminfo->pname; \
108         if (!OidIsValid(procedure->fn_oid)) \
109         { \
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); \
114         } \
115 } while(0)
116
117 #define GET_SCAN_PROCEDURE(pname) \
118 do { \
119         procedure = &scan->indexRelation->rd_aminfo->pname; \
120         if (!OidIsValid(procedure->fn_oid)) \
121         { \
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); \
126         } \
127 } while(0)
128
129 static IndexScanDesc index_beginscan_internal(Relation indexRelation,
130                                                  int nkeys, int norderbys, Snapshot snapshot);
131
132
133 /* ----------------------------------------------------------------
134  *                                 index_ interface functions
135  * ----------------------------------------------------------------
136  */
137
138 /* ----------------
139  *              index_open - open an index relation by relation OID
140  *
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
144  *              index already.)
145  *
146  *              An error is raised if the index does not exist.
147  *
148  *              This is a convenience routine adapted for indexscan use.
149  *              Some callers may prefer to use relation_open directly.
150  * ----------------
151  */
152 Relation
153 index_open(Oid relationId, LOCKMODE lockmode)
154 {
155         Relation        r;
156
157         r = relation_open(relationId, lockmode);
158
159         if (r->rd_rel->relkind != RELKIND_INDEX)
160                 ereport(ERROR,
161                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
162                                  errmsg("\"%s\" is not an index",
163                                                 RelationGetRelationName(r))));
164
165         return r;
166 }
167
168 /* ----------------
169  *              index_close - close an index relation
170  *
171  *              If lockmode is not "NoLock", we then release the specified lock.
172  *
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.
175  * ----------------
176  */
177 void
178 index_close(Relation relation, LOCKMODE lockmode)
179 {
180         LockRelId       relid = relation->rd_lockInfo.lockRelId;
181
182         Assert(lockmode >= NoLock && lockmode < MAX_LOCKMODES);
183
184         /* The relcache does the real work... */
185         RelationClose(relation);
186
187         if (lockmode != NoLock)
188                 UnlockRelationId(&relid, lockmode);
189 }
190
191 /* ----------------
192  *              index_insert - insert an index tuple into a relation
193  * ----------------
194  */
195 bool
196 index_insert(Relation indexRelation,
197                          Datum *values,
198                          bool *isnull,
199                          ItemPointer heap_t_ctid,
200                          Relation heapRelation,
201                          IndexUniqueCheck checkUnique)
202 {
203         FmgrInfo   *procedure;
204
205         RELATION_CHECKS;
206         GET_REL_PROCEDURE(aminsert);
207
208         if (!(indexRelation->rd_am->ampredlocks))
209                 CheckForSerializableConflictIn(indexRelation,
210                                                                            (HeapTuple) NULL,
211                                                                            InvalidBuffer);
212
213         /*
214          * have the am's insert proc do all the work.
215          */
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)));
223 }
224
225 /*
226  * index_beginscan - start a scan of an index with amgettuple
227  *
228  * Caller must be holding suitable locks on the heap and the index.
229  */
230 IndexScanDesc
231 index_beginscan(Relation heapRelation,
232                                 Relation indexRelation,
233                                 Snapshot snapshot,
234                                 int nkeys, int norderbys)
235 {
236         IndexScanDesc scan;
237
238         scan = index_beginscan_internal(indexRelation, nkeys, norderbys, snapshot);
239
240         /*
241          * Save additional parameters into the scandesc.  Everything else was set
242          * up by RelationGetIndexScan.
243          */
244         scan->heapRelation = heapRelation;
245         scan->xs_snapshot = snapshot;
246
247         return scan;
248 }
249
250 /*
251  * index_beginscan_bitmap - start a scan of an index with amgetbitmap
252  *
253  * As above, caller had better be holding some lock on the parent heap
254  * relation, even though it's not explicitly mentioned here.
255  */
256 IndexScanDesc
257 index_beginscan_bitmap(Relation indexRelation,
258                                            Snapshot snapshot,
259                                            int nkeys)
260 {
261         IndexScanDesc scan;
262
263         scan = index_beginscan_internal(indexRelation, nkeys, 0, snapshot);
264
265         /*
266          * Save additional parameters into the scandesc.  Everything else was set
267          * up by RelationGetIndexScan.
268          */
269         scan->xs_snapshot = snapshot;
270
271         return scan;
272 }
273
274 /*
275  * index_beginscan_internal --- common code for index_beginscan variants
276  */
277 static IndexScanDesc
278 index_beginscan_internal(Relation indexRelation,
279                                                  int nkeys, int norderbys, Snapshot snapshot)
280 {
281         IndexScanDesc scan;
282         FmgrInfo   *procedure;
283
284         RELATION_CHECKS;
285         GET_REL_PROCEDURE(ambeginscan);
286
287         if (!(indexRelation->rd_am->ampredlocks))
288                 PredicateLockRelation(indexRelation, snapshot);
289
290         /*
291          * We hold a reference count to the relcache entry throughout the scan.
292          */
293         RelationIncrementReferenceCount(indexRelation);
294
295         /*
296          * Tell the AM to open a scan.
297          */
298         scan = (IndexScanDesc)
299                 DatumGetPointer(FunctionCall3(procedure,
300                                                                           PointerGetDatum(indexRelation),
301                                                                           Int32GetDatum(nkeys),
302                                                                           Int32GetDatum(norderbys)));
303
304         return scan;
305 }
306
307 /* ----------------
308  *              index_rescan  - (re)start a scan of an index
309  *
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.)
317  * ----------------
318  */
319 void
320 index_rescan(IndexScanDesc scan,
321                          ScanKey keys, int nkeys,
322                          ScanKey orderbys, int norderbys)
323 {
324         FmgrInfo   *procedure;
325
326         SCAN_CHECKS;
327         GET_SCAN_PROCEDURE(amrescan);
328
329         Assert(nkeys == scan->numberOfKeys);
330         Assert(norderbys == scan->numberOfOrderBys);
331
332         /* Release any held pin on a heap page */
333         if (BufferIsValid(scan->xs_cbuf))
334         {
335                 ReleaseBuffer(scan->xs_cbuf);
336                 scan->xs_cbuf = InvalidBuffer;
337         }
338
339         scan->xs_continue_hot = false;
340
341         scan->kill_prior_tuple = false;         /* for safety */
342
343         FunctionCall5(procedure,
344                                   PointerGetDatum(scan),
345                                   PointerGetDatum(keys),
346                                   Int32GetDatum(nkeys),
347                                   PointerGetDatum(orderbys),
348                                   Int32GetDatum(norderbys));
349 }
350
351 /* ----------------
352  *              index_endscan - end a scan
353  * ----------------
354  */
355 void
356 index_endscan(IndexScanDesc scan)
357 {
358         FmgrInfo   *procedure;
359
360         SCAN_CHECKS;
361         GET_SCAN_PROCEDURE(amendscan);
362
363         /* Release any held pin on a heap page */
364         if (BufferIsValid(scan->xs_cbuf))
365         {
366                 ReleaseBuffer(scan->xs_cbuf);
367                 scan->xs_cbuf = InvalidBuffer;
368         }
369
370         /* End the AM's scan */
371         FunctionCall1(procedure, PointerGetDatum(scan));
372
373         /* Release index refcount acquired by index_beginscan */
374         RelationDecrementReferenceCount(scan->indexRelation);
375
376         /* Release the scan data structure itself */
377         IndexScanEnd(scan);
378 }
379
380 /* ----------------
381  *              index_markpos  - mark a scan position
382  * ----------------
383  */
384 void
385 index_markpos(IndexScanDesc scan)
386 {
387         FmgrInfo   *procedure;
388
389         SCAN_CHECKS;
390         GET_SCAN_PROCEDURE(ammarkpos);
391
392         FunctionCall1(procedure, PointerGetDatum(scan));
393 }
394
395 /* ----------------
396  *              index_restrpos  - restore a scan position
397  *
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().
401  *
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.
409  * ----------------
410  */
411 void
412 index_restrpos(IndexScanDesc scan)
413 {
414         FmgrInfo   *procedure;
415
416         Assert(IsMVCCSnapshot(scan->xs_snapshot));
417
418         SCAN_CHECKS;
419         GET_SCAN_PROCEDURE(amrestrpos);
420
421         scan->xs_continue_hot = false;
422
423         scan->kill_prior_tuple = false;         /* for safety */
424
425         FunctionCall1(procedure, PointerGetDatum(scan));
426 }
427
428 /* ----------------
429  * index_getnext_tid - get the next TID from a scan
430  *
431  * The result is the next TID satisfying the scan keys,
432  * or NULL if no more matching tuples exist.
433  * ----------------
434  */
435 ItemPointer
436 index_getnext_tid(IndexScanDesc scan, ScanDirection direction)
437 {
438         FmgrInfo   *procedure;
439         bool            found;
440
441         SCAN_CHECKS;
442         GET_SCAN_PROCEDURE(amgettuple);
443
444         Assert(TransactionIdIsValid(RecentGlobalXmin));
445
446         /*
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.
451          */
452         found = DatumGetBool(FunctionCall2(procedure,
453                                                                            PointerGetDatum(scan),
454                                                                            Int32GetDatum(direction)));
455
456         /* Reset kill flag immediately for safety */
457         scan->kill_prior_tuple = false;
458
459         /* If we're out of index entries, we're done */
460         if (!found)
461         {
462                 /* ... but first, release any held pin on a heap page */
463                 if (BufferIsValid(scan->xs_cbuf))
464                 {
465                         ReleaseBuffer(scan->xs_cbuf);
466                         scan->xs_cbuf = InvalidBuffer;
467                 }
468                 return NULL;
469         }
470
471         pgstat_count_index_tuples(scan->indexRelation, 1);
472
473         /* Return the TID of the tuple we found. */
474         return &scan->xs_ctup.t_self;
475 }
476
477 /* ----------------
478  *              index_fetch_heap - get the scan's next heap tuple
479  *
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.)
485  *
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
488  * call).
489  *
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.
493  * ----------------
494  */
495 HeapTuple
496 index_fetch_heap(IndexScanDesc scan)
497 {
498         ItemPointer tid = &scan->xs_ctup.t_self;
499         bool            all_dead = false;
500         bool            got_heap_tuple;
501
502         /* We can skip the buffer-switching logic if we're in mid-HOT chain. */
503         if (!scan->xs_continue_hot)
504         {
505                 /* Switch to correct buffer if we don't have it already */
506                 Buffer          prev_buf = scan->xs_cbuf;
507
508                 scan->xs_cbuf = ReleaseAndReadBuffer(scan->xs_cbuf,
509                                                                                          scan->heapRelation,
510                                                                                          ItemPointerGetBlockNumber(tid));
511
512                 /*
513                  * Prune page, but only if we weren't already on this page
514                  */
515                 if (prev_buf != scan->xs_cbuf)
516                         heap_page_prune_opt(scan->heapRelation, scan->xs_cbuf,
517                                                                 RecentGlobalXmin);
518         }
519
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,
523                                                                                         scan->xs_cbuf,
524                                                                                         scan->xs_snapshot,
525                                                                                         &scan->xs_ctup,
526                                                                                         &all_dead,
527                                                                                         !scan->xs_continue_hot);
528         LockBuffer(scan->xs_cbuf, BUFFER_LOCK_UNLOCK);
529
530         if (got_heap_tuple)
531         {
532                 /*
533                  * Only in a non-MVCC snapshot can more than one member of the HOT
534                  * chain be visible.
535                  */
536                 scan->xs_continue_hot = !IsMVCCSnapshot(scan->xs_snapshot);
537                 pgstat_count_heap_fetch(scan->indexRelation);
538                 return &scan->xs_ctup;
539         }
540
541         /* We've reached the end of the HOT chain. */
542         scan->xs_continue_hot = false;
543
544         /*
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().
550          */
551         if (!scan->xactStartedInRecovery)
552                 scan->kill_prior_tuple = all_dead;
553
554         return NULL;
555 }
556
557 /* ----------------
558  *              index_getnext - get the next heap tuple from a scan
559  *
560  * The result is the next heap tuple satisfying the scan keys and the
561  * snapshot, or NULL if no more matching tuples exist.
562  *
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
565  * call).
566  *
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.
570  * ----------------
571  */
572 HeapTuple
573 index_getnext(IndexScanDesc scan, ScanDirection direction)
574 {
575         HeapTuple       heapTuple;
576         ItemPointer tid;
577
578         for (;;)
579         {
580                 if (scan->xs_continue_hot)
581                 {
582                         /*
583                          * We are resuming scan of a HOT chain after having returned an
584                          * earlier member.      Must still hold pin on current heap page.
585                          */
586                         Assert(BufferIsValid(scan->xs_cbuf));
587                         Assert(ItemPointerGetBlockNumber(&scan->xs_ctup.t_self) ==
588                                    BufferGetBlockNumber(scan->xs_cbuf));
589                 }
590                 else
591                 {
592                         /* Time to fetch the next TID from the index */
593                         tid = index_getnext_tid(scan, direction);
594
595                         /* If we're out of index entries, we're done */
596                         if (tid == NULL)
597                                 break;
598                 }
599
600                 /*
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
603                  * the index.
604                  */
605                 heapTuple = index_fetch_heap(scan);
606                 if (heapTuple != NULL)
607                         return heapTuple;
608         }
609
610         return NULL;                            /* failure exit */
611 }
612
613 /* ----------------
614  *              index_getbitmap - get all tuples at once from an index scan
615  *
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
620  * to it.
621  *
622  * Returns the number of matching tuples found.  (Note: this might be only
623  * approximate, so it should only be used for statistical purposes.)
624  * ----------------
625  */
626 int64
627 index_getbitmap(IndexScanDesc scan, TIDBitmap *bitmap)
628 {
629         FmgrInfo   *procedure;
630         int64           ntids;
631         Datum           d;
632
633         SCAN_CHECKS;
634         GET_SCAN_PROCEDURE(amgetbitmap);
635
636         /* just make sure this is false... */
637         scan->kill_prior_tuple = false;
638
639         /*
640          * have the am's getbitmap proc do all the work.
641          */
642         d = FunctionCall2(procedure,
643                                           PointerGetDatum(scan),
644                                           PointerGetDatum(bitmap));
645
646         ntids = DatumGetInt64(d);
647
648         /* If int8 is pass-by-ref, must free the result to avoid memory leak */
649 #ifndef USE_FLOAT8_BYVAL
650         pfree(DatumGetPointer(d));
651 #endif
652
653         pgstat_count_index_tuples(scan->indexRelation, ntids);
654
655         return ntids;
656 }
657
658 /* ----------------
659  *              index_bulk_delete - do mass deletion of index entries
660  *
661  *              callback routine tells whether a given main-heap tuple is
662  *              to be deleted
663  *
664  *              return value is an optional palloc'd struct of statistics
665  * ----------------
666  */
667 IndexBulkDeleteResult *
668 index_bulk_delete(IndexVacuumInfo *info,
669                                   IndexBulkDeleteResult *stats,
670                                   IndexBulkDeleteCallback callback,
671                                   void *callback_state)
672 {
673         Relation        indexRelation = info->index;
674         FmgrInfo   *procedure;
675         IndexBulkDeleteResult *result;
676
677         RELATION_CHECKS;
678         GET_REL_PROCEDURE(ambulkdelete);
679
680         result = (IndexBulkDeleteResult *)
681                 DatumGetPointer(FunctionCall4(procedure,
682                                                                           PointerGetDatum(info),
683                                                                           PointerGetDatum(stats),
684                                                                           PointerGetDatum((Pointer) callback),
685                                                                           PointerGetDatum(callback_state)));
686
687         return result;
688 }
689
690 /* ----------------
691  *              index_vacuum_cleanup - do post-deletion cleanup of an index
692  *
693  *              return value is an optional palloc'd struct of statistics
694  * ----------------
695  */
696 IndexBulkDeleteResult *
697 index_vacuum_cleanup(IndexVacuumInfo *info,
698                                          IndexBulkDeleteResult *stats)
699 {
700         Relation        indexRelation = info->index;
701         FmgrInfo   *procedure;
702         IndexBulkDeleteResult *result;
703
704         RELATION_CHECKS;
705         GET_REL_PROCEDURE(amvacuumcleanup);
706
707         result = (IndexBulkDeleteResult *)
708                 DatumGetPointer(FunctionCall2(procedure,
709                                                                           PointerGetDatum(info),
710                                                                           PointerGetDatum(stats)));
711
712         return result;
713 }
714
715 /* ----------------
716  *              index_can_return - does index support index-only scans?
717  * ----------------
718  */
719 bool
720 index_can_return(Relation indexRelation)
721 {
722         FmgrInfo   *procedure;
723
724         RELATION_CHECKS;
725
726         /* amcanreturn is optional; assume FALSE if not provided by AM */
727         if (!RegProcedureIsValid(indexRelation->rd_am->amcanreturn))
728                 return false;
729
730         GET_REL_PROCEDURE(amcanreturn);
731
732         return DatumGetBool(FunctionCall1(procedure,
733                                                                           PointerGetDatum(indexRelation)));
734 }
735
736 /* ----------------
737  *              index_getprocid
738  *
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.
747  *
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
756  *              functions.
757  *
758  *              This routine returns the requested default procedure OID for a
759  *              particular indexed attribute.
760  * ----------------
761  */
762 RegProcedure
763 index_getprocid(Relation irel,
764                                 AttrNumber attnum,
765                                 uint16 procnum)
766 {
767         RegProcedure *loc;
768         int                     nproc;
769         int                     procindex;
770
771         nproc = irel->rd_am->amsupport;
772
773         Assert(procnum > 0 && procnum <= (uint16) nproc);
774
775         procindex = (nproc * (attnum - 1)) + (procnum - 1);
776
777         loc = irel->rd_support;
778
779         Assert(loc != NULL);
780
781         return loc[procindex];
782 }
783
784 /* ----------------
785  *              index_getprocinfo
786  *
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.
790  *
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.
794  * ----------------
795  */
796 FmgrInfo *
797 index_getprocinfo(Relation irel,
798                                   AttrNumber attnum,
799                                   uint16 procnum)
800 {
801         FmgrInfo   *locinfo;
802         int                     nproc;
803         int                     procindex;
804
805         nproc = irel->rd_am->amsupport;
806
807         Assert(procnum > 0 && procnum <= (uint16) nproc);
808
809         procindex = (nproc * (attnum - 1)) + (procnum - 1);
810
811         locinfo = irel->rd_supportinfo;
812
813         Assert(locinfo != NULL);
814
815         locinfo += procindex;
816
817         /* Initialize the lookup info if first time through */
818         if (locinfo->fn_oid == InvalidOid)
819         {
820                 RegProcedure *loc = irel->rd_support;
821                 RegProcedure procId;
822
823                 Assert(loc != NULL);
824
825                 procId = loc[procindex];
826
827                 /*
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.)
832                  */
833                 if (!RegProcedureIsValid(procId))
834                         elog(ERROR, "missing support function %d for attribute %d of index \"%s\"",
835                                  procnum, attnum, RelationGetRelationName(irel));
836
837                 fmgr_info_cxt(procId, locinfo, irel->rd_indexcxt);
838         }
839
840         return locinfo;
841 }