]> granicus.if.org Git - postgresql/blob - src/backend/access/index/indexam.c
Create new routines systable_beginscan_ordered, systable_getnext_ordered,
[postgresql] / src / backend / access / index / indexam.c
1 /*-------------------------------------------------------------------------
2  *
3  * indexam.c
4  *        general index access method routines
5  *
6  * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/backend/access/index/indexam.c,v 1.106 2008/04/12 23:14:21 tgl Exp $
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   - get the next tuple from a scan
24  *              index_getbitmap - get all 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
29  *
30  * NOTES
31  *              This file contains the index_ routines which used
32  *              to be a scattered collection of stuff in access/genam.
33  *
34  *
35  * old comments
36  *              Scans are implemented as follows:
37  *
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.
43  *
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
46  *              identically.
47  *
48  *                              State   Result
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)
54  *
55  *              All other states cannot occur.
56  *
57  *              Note: It would be possible to cache the status of the previous and
58  *                        next item pointer using the flags.
59  *
60  *-------------------------------------------------------------------------
61  */
62
63 #include "postgres.h"
64
65 #include "access/genam.h"
66 #include "access/heapam.h"
67 #include "access/transam.h"
68 #include "pgstat.h"
69 #include "utils/relcache.h"
70 #include "utils/snapmgr.h"
71 #include "utils/tqual.h"
72
73
74 /* ----------------------------------------------------------------
75  *                                      macros used in index_ routines
76  * ----------------------------------------------------------------
77  */
78 #define RELATION_CHECKS \
79 ( \
80         AssertMacro(RelationIsValid(indexRelation)), \
81         AssertMacro(PointerIsValid(indexRelation->rd_am)) \
82 )
83
84 #define SCAN_CHECKS \
85 ( \
86         AssertMacro(IndexScanIsValid(scan)), \
87         AssertMacro(RelationIsValid(scan->indexRelation)), \
88         AssertMacro(PointerIsValid(scan->indexRelation->rd_am)) \
89 )
90
91 #define GET_REL_PROCEDURE(pname) \
92 do { \
93         procedure = &indexRelation->rd_aminfo->pname; \
94         if (!OidIsValid(procedure->fn_oid)) \
95         { \
96                 RegProcedure    procOid = indexRelation->rd_am->pname; \
97                 if (!RegProcedureIsValid(procOid)) \
98                         elog(ERROR, "invalid %s regproc", CppAsString(pname)); \
99                 fmgr_info_cxt(procOid, procedure, indexRelation->rd_indexcxt); \
100         } \
101 } while(0)
102
103 #define GET_SCAN_PROCEDURE(pname) \
104 do { \
105         procedure = &scan->indexRelation->rd_aminfo->pname; \
106         if (!OidIsValid(procedure->fn_oid)) \
107         { \
108                 RegProcedure    procOid = scan->indexRelation->rd_am->pname; \
109                 if (!RegProcedureIsValid(procOid)) \
110                         elog(ERROR, "invalid %s regproc", CppAsString(pname)); \
111                 fmgr_info_cxt(procOid, procedure, scan->indexRelation->rd_indexcxt); \
112         } \
113 } while(0)
114
115 static IndexScanDesc index_beginscan_internal(Relation indexRelation,
116                                                  int nkeys, ScanKey key);
117
118
119 /* ----------------------------------------------------------------
120  *                                 index_ interface functions
121  * ----------------------------------------------------------------
122  */
123
124 /* ----------------
125  *              index_open - open an index relation by relation OID
126  *
127  *              If lockmode is not "NoLock", the specified kind of lock is
128  *              obtained on the index.  (Generally, NoLock should only be
129  *              used if the caller knows it has some appropriate lock on the
130  *              index already.)
131  *
132  *              An error is raised if the index does not exist.
133  *
134  *              This is a convenience routine adapted for indexscan use.
135  *              Some callers may prefer to use relation_open directly.
136  * ----------------
137  */
138 Relation
139 index_open(Oid relationId, LOCKMODE lockmode)
140 {
141         Relation        r;
142
143         r = relation_open(relationId, lockmode);
144
145         if (r->rd_rel->relkind != RELKIND_INDEX)
146                 ereport(ERROR,
147                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
148                                  errmsg("\"%s\" is not an index",
149                                                 RelationGetRelationName(r))));
150
151         return r;
152 }
153
154 /* ----------------
155  *              index_close - close an index relation
156  *
157  *              If lockmode is not "NoLock", we then release the specified lock.
158  *
159  *              Note that it is often sensible to hold a lock beyond index_close;
160  *              in that case, the lock is released automatically at xact end.
161  * ----------------
162  */
163 void
164 index_close(Relation relation, LOCKMODE lockmode)
165 {
166         LockRelId       relid = relation->rd_lockInfo.lockRelId;
167
168         Assert(lockmode >= NoLock && lockmode < MAX_LOCKMODES);
169
170         /* The relcache does the real work... */
171         RelationClose(relation);
172
173         if (lockmode != NoLock)
174                 UnlockRelationId(&relid, lockmode);
175 }
176
177 /* ----------------
178  *              index_insert - insert an index tuple into a relation
179  * ----------------
180  */
181 bool
182 index_insert(Relation indexRelation,
183                          Datum *values,
184                          bool *isnull,
185                          ItemPointer heap_t_ctid,
186                          Relation heapRelation,
187                          bool check_uniqueness)
188 {
189         FmgrInfo   *procedure;
190
191         RELATION_CHECKS;
192         GET_REL_PROCEDURE(aminsert);
193
194         /*
195          * have the am's insert proc do all the work.
196          */
197         return DatumGetBool(FunctionCall6(procedure,
198                                                                           PointerGetDatum(indexRelation),
199                                                                           PointerGetDatum(values),
200                                                                           PointerGetDatum(isnull),
201                                                                           PointerGetDatum(heap_t_ctid),
202                                                                           PointerGetDatum(heapRelation),
203                                                                           BoolGetDatum(check_uniqueness)));
204 }
205
206 /*
207  * index_beginscan - start a scan of an index with amgettuple
208  *
209  * Caller must be holding suitable locks on the heap and the index.
210  */
211 IndexScanDesc
212 index_beginscan(Relation heapRelation,
213                                 Relation indexRelation,
214                                 Snapshot snapshot,
215                                 int nkeys, ScanKey key)
216 {
217         IndexScanDesc scan;
218
219         scan = index_beginscan_internal(indexRelation, nkeys, key);
220
221         /*
222          * Save additional parameters into the scandesc.  Everything else was set
223          * up by RelationGetIndexScan.
224          */
225         scan->heapRelation = heapRelation;
226         scan->xs_snapshot = snapshot;
227
228         return scan;
229 }
230
231 /*
232  * index_beginscan_bitmap - start a scan of an index with amgetbitmap
233  *
234  * As above, caller had better be holding some lock on the parent heap
235  * relation, even though it's not explicitly mentioned here.
236  */
237 IndexScanDesc
238 index_beginscan_bitmap(Relation indexRelation,
239                                            Snapshot snapshot,
240                                            int nkeys, ScanKey key)
241 {
242         IndexScanDesc scan;
243
244         scan = index_beginscan_internal(indexRelation, nkeys, key);
245
246         /*
247          * Save additional parameters into the scandesc.  Everything else was set
248          * up by RelationGetIndexScan.
249          */
250         scan->xs_snapshot = snapshot;
251
252         return scan;
253 }
254
255 /*
256  * index_beginscan_internal --- common code for index_beginscan variants
257  */
258 static IndexScanDesc
259 index_beginscan_internal(Relation indexRelation,
260                                                  int nkeys, ScanKey key)
261 {
262         IndexScanDesc scan;
263         FmgrInfo   *procedure;
264
265         RELATION_CHECKS;
266         GET_REL_PROCEDURE(ambeginscan);
267
268         /*
269          * We hold a reference count to the relcache entry throughout the scan.
270          */
271         RelationIncrementReferenceCount(indexRelation);
272
273         /*
274          * Tell the AM to open a scan.
275          */
276         scan = (IndexScanDesc)
277                 DatumGetPointer(FunctionCall3(procedure,
278                                                                           PointerGetDatum(indexRelation),
279                                                                           Int32GetDatum(nkeys),
280                                                                           PointerGetDatum(key)));
281
282         return scan;
283 }
284
285 /* ----------------
286  *              index_rescan  - (re)start a scan of an index
287  *
288  * The caller may specify a new set of scankeys (but the number of keys
289  * cannot change).      To restart the scan without changing keys, pass NULL
290  * for the key array.
291  *
292  * Note that this is also called when first starting an indexscan;
293  * see RelationGetIndexScan.  Keys *must* be passed in that case,
294  * unless scan->numberOfKeys is zero.
295  * ----------------
296  */
297 void
298 index_rescan(IndexScanDesc scan, ScanKey key)
299 {
300         FmgrInfo   *procedure;
301
302         SCAN_CHECKS;
303         GET_SCAN_PROCEDURE(amrescan);
304
305         /* Release any held pin on a heap page */
306         if (BufferIsValid(scan->xs_cbuf))
307         {
308                 ReleaseBuffer(scan->xs_cbuf);
309                 scan->xs_cbuf = InvalidBuffer;
310         }
311
312         scan->xs_next_hot = InvalidOffsetNumber;
313
314         scan->kill_prior_tuple = false;         /* for safety */
315
316         FunctionCall2(procedure,
317                                   PointerGetDatum(scan),
318                                   PointerGetDatum(key));
319 }
320
321 /* ----------------
322  *              index_endscan - end a scan
323  * ----------------
324  */
325 void
326 index_endscan(IndexScanDesc scan)
327 {
328         FmgrInfo   *procedure;
329
330         SCAN_CHECKS;
331         GET_SCAN_PROCEDURE(amendscan);
332
333         /* Release any held pin on a heap page */
334         if (BufferIsValid(scan->xs_cbuf))
335         {
336                 ReleaseBuffer(scan->xs_cbuf);
337                 scan->xs_cbuf = InvalidBuffer;
338         }
339
340         /* End the AM's scan */
341         FunctionCall1(procedure, PointerGetDatum(scan));
342
343         /* Release index refcount acquired by index_beginscan */
344         RelationDecrementReferenceCount(scan->indexRelation);
345
346         /* Release the scan data structure itself */
347         IndexScanEnd(scan);
348 }
349
350 /* ----------------
351  *              index_markpos  - mark a scan position
352  * ----------------
353  */
354 void
355 index_markpos(IndexScanDesc scan)
356 {
357         FmgrInfo   *procedure;
358
359         SCAN_CHECKS;
360         GET_SCAN_PROCEDURE(ammarkpos);
361
362         FunctionCall1(procedure, PointerGetDatum(scan));
363 }
364
365 /* ----------------
366  *              index_restrpos  - restore a scan position
367  *
368  * NOTE: this only restores the internal scan state of the index AM.
369  * The current result tuple (scan->xs_ctup) doesn't change.  See comments
370  * for ExecRestrPos().
371  *
372  * NOTE: in the presence of HOT chains, mark/restore only works correctly
373  * if the scan's snapshot is MVCC-safe; that ensures that there's at most one
374  * returnable tuple in each HOT chain, and so restoring the prior state at the
375  * granularity of the index AM is sufficient.  Since the only current user
376  * of mark/restore functionality is nodeMergejoin.c, this effectively means
377  * that merge-join plans only work for MVCC snapshots.  This could be fixed
378  * if necessary, but for now it seems unimportant.
379  * ----------------
380  */
381 void
382 index_restrpos(IndexScanDesc scan)
383 {
384         FmgrInfo   *procedure;
385
386         Assert(IsMVCCSnapshot(scan->xs_snapshot));
387
388         SCAN_CHECKS;
389         GET_SCAN_PROCEDURE(amrestrpos);
390
391         scan->xs_next_hot = InvalidOffsetNumber;
392
393         scan->kill_prior_tuple = false;         /* for safety */
394
395         FunctionCall1(procedure, PointerGetDatum(scan));
396 }
397
398 /* ----------------
399  *              index_getnext - get the next heap tuple from a scan
400  *
401  * The result is the next heap tuple satisfying the scan keys and the
402  * snapshot, or NULL if no more matching tuples exist.  On success,
403  * the buffer containing the heap tuple is pinned (the pin will be dropped
404  * at the next index_getnext or index_endscan).
405  * ----------------
406  */
407 HeapTuple
408 index_getnext(IndexScanDesc scan, ScanDirection direction)
409 {
410         HeapTuple       heapTuple = &scan->xs_ctup;
411         ItemPointer tid = &heapTuple->t_self;
412         FmgrInfo   *procedure;
413
414         SCAN_CHECKS;
415         GET_SCAN_PROCEDURE(amgettuple);
416
417         /*
418          * We always reset xs_hot_dead; if we are here then either we are just
419          * starting the scan, or we previously returned a visible tuple, and in
420          * either case it's inappropriate to kill the prior index entry.
421          */
422         scan->xs_hot_dead = false;
423
424         for (;;)
425         {
426                 OffsetNumber offnum;
427                 bool            at_chain_start;
428                 Page            dp;
429
430                 if (scan->xs_next_hot != InvalidOffsetNumber)
431                 {
432                         /*
433                          * We are resuming scan of a HOT chain after having returned an
434                          * earlier member.      Must still hold pin on current heap page.
435                          */
436                         Assert(BufferIsValid(scan->xs_cbuf));
437                         Assert(ItemPointerGetBlockNumber(tid) ==
438                                    BufferGetBlockNumber(scan->xs_cbuf));
439                         Assert(TransactionIdIsValid(scan->xs_prev_xmax));
440                         offnum = scan->xs_next_hot;
441                         at_chain_start = false;
442                         scan->xs_next_hot = InvalidOffsetNumber;
443                 }
444                 else
445                 {
446                         bool            found;
447                         Buffer          prev_buf;
448
449                         /*
450                          * If we scanned a whole HOT chain and found only dead tuples,
451                          * tell index AM to kill its entry for that TID.
452                          */
453                         scan->kill_prior_tuple = scan->xs_hot_dead;
454
455                         /*
456                          * The AM's gettuple proc finds the next index entry matching the
457                          * scan keys, and puts the TID in xs_ctup.t_self (ie, *tid).
458                          */
459                         found = DatumGetBool(FunctionCall2(procedure,
460                                                                                            PointerGetDatum(scan),
461                                                                                            Int32GetDatum(direction)));
462
463                         /* Reset kill flag immediately for safety */
464                         scan->kill_prior_tuple = false;
465
466                         /* If we're out of index entries, break out of outer loop */
467                         if (!found)
468                                 break;
469
470                         pgstat_count_index_tuples(scan->indexRelation, 1);
471
472                         /* Switch to correct buffer if we don't have it already */
473                         prev_buf = scan->xs_cbuf;
474                         scan->xs_cbuf = ReleaseAndReadBuffer(scan->xs_cbuf,
475                                                                                                  scan->heapRelation,
476                                                                                          ItemPointerGetBlockNumber(tid));
477
478                         /*
479                          * Prune page, but only if we weren't already on this page
480                          */
481                         if (prev_buf != scan->xs_cbuf)
482                                 heap_page_prune_opt(scan->heapRelation, scan->xs_cbuf,
483                                                                         RecentGlobalXmin);
484
485                         /* Prepare to scan HOT chain starting at index-referenced offnum */
486                         offnum = ItemPointerGetOffsetNumber(tid);
487                         at_chain_start = true;
488
489                         /* We don't know what the first tuple's xmin should be */
490                         scan->xs_prev_xmax = InvalidTransactionId;
491
492                         /* Initialize flag to detect if all entries are dead */
493                         scan->xs_hot_dead = true;
494                 }
495
496                 /* Obtain share-lock on the buffer so we can examine visibility */
497                 LockBuffer(scan->xs_cbuf, BUFFER_LOCK_SHARE);
498
499                 dp = (Page) BufferGetPage(scan->xs_cbuf);
500
501                 /* Scan through possible multiple members of HOT-chain */
502                 for (;;)
503                 {
504                         ItemId          lp;
505                         ItemPointer ctid;
506
507                         /* check for bogus TID */
508                         if (offnum < FirstOffsetNumber ||
509                                 offnum > PageGetMaxOffsetNumber(dp))
510                                 break;
511
512                         lp = PageGetItemId(dp, offnum);
513
514                         /* check for unused, dead, or redirected items */
515                         if (!ItemIdIsNormal(lp))
516                         {
517                                 /* We should only see a redirect at start of chain */
518                                 if (ItemIdIsRedirected(lp) && at_chain_start)
519                                 {
520                                         /* Follow the redirect */
521                                         offnum = ItemIdGetRedirect(lp);
522                                         at_chain_start = false;
523                                         continue;
524                                 }
525                                 /* else must be end of chain */
526                                 break;
527                         }
528
529                         /*
530                          * We must initialize all of *heapTuple (ie, scan->xs_ctup) since
531                          * it is returned to the executor on success.
532                          */
533                         heapTuple->t_data = (HeapTupleHeader) PageGetItem(dp, lp);
534                         heapTuple->t_len = ItemIdGetLength(lp);
535                         ItemPointerSetOffsetNumber(tid, offnum);
536                         heapTuple->t_tableOid = RelationGetRelid(scan->heapRelation);
537                         ctid = &heapTuple->t_data->t_ctid;
538
539                         /*
540                          * Shouldn't see a HEAP_ONLY tuple at chain start.  (This test
541                          * should be unnecessary, since the chain root can't be removed
542                          * while we have pin on the index entry, but let's make it
543                          * anyway.)
544                          */
545                         if (at_chain_start && HeapTupleIsHeapOnly(heapTuple))
546                                 break;
547
548                         /*
549                          * The xmin should match the previous xmax value, else chain is
550                          * broken.      (Note: this test is not optional because it protects
551                          * us against the case where the prior chain member's xmax aborted
552                          * since we looked at it.)
553                          */
554                         if (TransactionIdIsValid(scan->xs_prev_xmax) &&
555                                 !TransactionIdEquals(scan->xs_prev_xmax,
556                                                                   HeapTupleHeaderGetXmin(heapTuple->t_data)))
557                                 break;
558
559                         /* If it's visible per the snapshot, we must return it */
560                         if (HeapTupleSatisfiesVisibility(heapTuple, scan->xs_snapshot,
561                                                                                          scan->xs_cbuf))
562                         {
563                                 /*
564                                  * If the snapshot is MVCC, we know that it could accept at
565                                  * most one member of the HOT chain, so we can skip examining
566                                  * any more members.  Otherwise, check for continuation of the
567                                  * HOT-chain, and set state for next time.
568                                  */
569                                 if (IsMVCCSnapshot(scan->xs_snapshot))
570                                         scan->xs_next_hot = InvalidOffsetNumber;
571                                 else if (HeapTupleIsHotUpdated(heapTuple))
572                                 {
573                                         Assert(ItemPointerGetBlockNumber(ctid) ==
574                                                    ItemPointerGetBlockNumber(tid));
575                                         scan->xs_next_hot = ItemPointerGetOffsetNumber(ctid);
576                                         scan->xs_prev_xmax = HeapTupleHeaderGetXmax(heapTuple->t_data);
577                                 }
578                                 else
579                                         scan->xs_next_hot = InvalidOffsetNumber;
580
581                                 LockBuffer(scan->xs_cbuf, BUFFER_LOCK_UNLOCK);
582
583                                 pgstat_count_heap_fetch(scan->indexRelation);
584
585                                 return heapTuple;
586                         }
587
588                         /*
589                          * If we can't see it, maybe no one else can either.  Check to see
590                          * if the tuple is dead to all transactions.  If we find that all
591                          * the tuples in the HOT chain are dead, we'll signal the index AM
592                          * to not return that TID on future indexscans.
593                          */
594                         if (scan->xs_hot_dead &&
595                                 HeapTupleSatisfiesVacuum(heapTuple->t_data, RecentGlobalXmin,
596                                                                                  scan->xs_cbuf) != HEAPTUPLE_DEAD)
597                                 scan->xs_hot_dead = false;
598
599                         /*
600                          * Check to see if HOT chain continues past this tuple; if so
601                          * fetch the next offnum (we don't bother storing it into
602                          * xs_next_hot, but must store xs_prev_xmax), and loop around.
603                          */
604                         if (HeapTupleIsHotUpdated(heapTuple))
605                         {
606                                 Assert(ItemPointerGetBlockNumber(ctid) ==
607                                            ItemPointerGetBlockNumber(tid));
608                                 offnum = ItemPointerGetOffsetNumber(ctid);
609                                 at_chain_start = false;
610                                 scan->xs_prev_xmax = HeapTupleHeaderGetXmax(heapTuple->t_data);
611                         }
612                         else
613                                 break;                  /* end of chain */
614                 }                                               /* loop over a single HOT chain */
615
616                 LockBuffer(scan->xs_cbuf, BUFFER_LOCK_UNLOCK);
617
618                 /* Loop around to ask index AM for another TID */
619                 scan->xs_next_hot = InvalidOffsetNumber;
620         }
621
622         /* Release any held pin on a heap page */
623         if (BufferIsValid(scan->xs_cbuf))
624         {
625                 ReleaseBuffer(scan->xs_cbuf);
626                 scan->xs_cbuf = InvalidBuffer;
627         }
628
629         return NULL;                            /* failure exit */
630 }
631
632 /* ----------------
633  *              index_getbitmap - get all tuples at once from an index scan
634  *
635  * Adds the TIDs of all heap tuples satisfying the scan keys to a bitmap.
636  * Since there's no interlock between the index scan and the eventual heap
637  * access, this is only safe to use with MVCC-based snapshots: the heap
638  * item slot could have been replaced by a newer tuple by the time we get
639  * to it.
640  *
641  * Returns the number of matching tuples found.
642  * ----------------
643  */
644 int64
645 index_getbitmap(IndexScanDesc scan, TIDBitmap *bitmap)
646 {
647         FmgrInfo   *procedure;
648         int64           ntids;
649
650         SCAN_CHECKS;
651         GET_SCAN_PROCEDURE(amgetbitmap);
652
653         /* just make sure this is false... */
654         scan->kill_prior_tuple = false;
655
656         /*
657          * have the am's getbitmap proc do all the work.
658          */
659         ntids = DatumGetInt64(FunctionCall2(procedure,
660                                                                                 PointerGetDatum(scan),
661                                                                                 PointerGetDatum(bitmap)));
662
663         pgstat_count_index_tuples(scan->indexRelation, ntids);
664
665         return ntids;
666 }
667
668 /* ----------------
669  *              index_bulk_delete - do mass deletion of index entries
670  *
671  *              callback routine tells whether a given main-heap tuple is
672  *              to be deleted
673  *
674  *              return value is an optional palloc'd struct of statistics
675  * ----------------
676  */
677 IndexBulkDeleteResult *
678 index_bulk_delete(IndexVacuumInfo *info,
679                                   IndexBulkDeleteResult *stats,
680                                   IndexBulkDeleteCallback callback,
681                                   void *callback_state)
682 {
683         Relation        indexRelation = info->index;
684         FmgrInfo   *procedure;
685         IndexBulkDeleteResult *result;
686
687         RELATION_CHECKS;
688         GET_REL_PROCEDURE(ambulkdelete);
689
690         result = (IndexBulkDeleteResult *)
691                 DatumGetPointer(FunctionCall4(procedure,
692                                                                           PointerGetDatum(info),
693                                                                           PointerGetDatum(stats),
694                                                                           PointerGetDatum((Pointer) callback),
695                                                                           PointerGetDatum(callback_state)));
696
697         return result;
698 }
699
700 /* ----------------
701  *              index_vacuum_cleanup - do post-deletion cleanup of an index
702  *
703  *              return value is an optional palloc'd struct of statistics
704  * ----------------
705  */
706 IndexBulkDeleteResult *
707 index_vacuum_cleanup(IndexVacuumInfo *info,
708                                          IndexBulkDeleteResult *stats)
709 {
710         Relation        indexRelation = info->index;
711         FmgrInfo   *procedure;
712         IndexBulkDeleteResult *result;
713
714         RELATION_CHECKS;
715         GET_REL_PROCEDURE(amvacuumcleanup);
716
717         result = (IndexBulkDeleteResult *)
718                 DatumGetPointer(FunctionCall2(procedure,
719                                                                           PointerGetDatum(info),
720                                                                           PointerGetDatum(stats)));
721
722         return result;
723 }
724
725 /* ----------------
726  *              index_getprocid
727  *
728  *              Index access methods typically require support routines that are
729  *              not directly the implementation of any WHERE-clause query operator
730  *              and so cannot be kept in pg_amop.  Instead, such routines are kept
731  *              in pg_amproc.  These registered procedure OIDs are assigned numbers
732  *              according to a convention established by the access method.
733  *              The general index code doesn't know anything about the routines
734  *              involved; it just builds an ordered list of them for
735  *              each attribute on which an index is defined.
736  *
737  *              As of Postgres 8.3, support routines within an operator family
738  *              are further subdivided by the "left type" and "right type" of the
739  *              query operator(s) that they support.  The "default" functions for a
740  *              particular indexed attribute are those with both types equal to
741  *              the index opclass' opcintype (note that this is subtly different
742  *              from the indexed attribute's own type: it may be a binary-compatible
743  *              type instead).  Only the default functions are stored in relcache
744  *              entries --- access methods can use the syscache to look up non-default
745  *              functions.
746  *
747  *              This routine returns the requested default procedure OID for a
748  *              particular indexed attribute.
749  * ----------------
750  */
751 RegProcedure
752 index_getprocid(Relation irel,
753                                 AttrNumber attnum,
754                                 uint16 procnum)
755 {
756         RegProcedure *loc;
757         int                     nproc;
758         int                     procindex;
759
760         nproc = irel->rd_am->amsupport;
761
762         Assert(procnum > 0 && procnum <= (uint16) nproc);
763
764         procindex = (nproc * (attnum - 1)) + (procnum - 1);
765
766         loc = irel->rd_support;
767
768         Assert(loc != NULL);
769
770         return loc[procindex];
771 }
772
773 /* ----------------
774  *              index_getprocinfo
775  *
776  *              This routine allows index AMs to keep fmgr lookup info for
777  *              support procs in the relcache.  As above, only the "default"
778  *              functions for any particular indexed attribute are cached.
779  *
780  * Note: the return value points into cached data that will be lost during
781  * any relcache rebuild!  Therefore, either use the callinfo right away,
782  * or save it only after having acquired some type of lock on the index rel.
783  * ----------------
784  */
785 FmgrInfo *
786 index_getprocinfo(Relation irel,
787                                   AttrNumber attnum,
788                                   uint16 procnum)
789 {
790         FmgrInfo   *locinfo;
791         int                     nproc;
792         int                     procindex;
793
794         nproc = irel->rd_am->amsupport;
795
796         Assert(procnum > 0 && procnum <= (uint16) nproc);
797
798         procindex = (nproc * (attnum - 1)) + (procnum - 1);
799
800         locinfo = irel->rd_supportinfo;
801
802         Assert(locinfo != NULL);
803
804         locinfo += procindex;
805
806         /* Initialize the lookup info if first time through */
807         if (locinfo->fn_oid == InvalidOid)
808         {
809                 RegProcedure *loc = irel->rd_support;
810                 RegProcedure procId;
811
812                 Assert(loc != NULL);
813
814                 procId = loc[procindex];
815
816                 /*
817                  * Complain if function was not found during IndexSupportInitialize.
818                  * This should not happen unless the system tables contain bogus
819                  * entries for the index opclass.  (If an AM wants to allow a support
820                  * function to be optional, it can use index_getprocid.)
821                  */
822                 if (!RegProcedureIsValid(procId))
823                         elog(ERROR, "missing support function %d for attribute %d of index \"%s\"",
824                                  procnum, attnum, RelationGetRelationName(irel));
825
826                 fmgr_info_cxt(procId, locinfo, irel->rd_indexcxt);
827         }
828
829         return locinfo;
830 }