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