]> granicus.if.org Git - postgresql/blob - src/backend/access/index/indexam.c
Create core infrastructure for KNNGIST.
[postgresql] / src / backend / access / index / indexam.c
1 /*-------------------------------------------------------------------------
2  *
3  * indexam.c
4  *        general index access method routines
5  *
6  * Portions Copyright (c) 1996-2010, 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   - 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, int norderbys);
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                          IndexUniqueCheck checkUnique)
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                                                                           Int32GetDatum((int32) checkUnique)));
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, int norderbys)
217 {
218         IndexScanDesc scan;
219
220         scan = index_beginscan_internal(indexRelation, nkeys, norderbys);
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)
242 {
243         IndexScanDesc scan;
244
245         scan = index_beginscan_internal(indexRelation, nkeys, 0);
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, int norderbys)
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                                                                           Int32GetDatum(norderbys)));
282
283         return scan;
284 }
285
286 /* ----------------
287  *              index_rescan  - (re)start a scan of an index
288  *
289  * During a restart, the caller may specify a new set of scankeys and/or
290  * orderbykeys; but the number of keys cannot differ from what index_beginscan
291  * was told.  (Later we might relax that to "must not exceed", but currently
292  * the index AMs tend to assume that scan->numberOfKeys is what to believe.)
293  * To restart the scan without changing keys, pass NULL for the key arrays.
294  * (Of course, keys *must* be passed on the first call, unless
295  * scan->numberOfKeys is zero.)
296  * ----------------
297  */
298 void
299 index_rescan(IndexScanDesc scan,
300                          ScanKey keys, int nkeys,
301                          ScanKey orderbys, int norderbys)
302 {
303         FmgrInfo   *procedure;
304
305         SCAN_CHECKS;
306         GET_SCAN_PROCEDURE(amrescan);
307
308         Assert(nkeys == scan->numberOfKeys);
309         Assert(norderbys == scan->numberOfOrderBys);
310
311         /* Release any held pin on a heap page */
312         if (BufferIsValid(scan->xs_cbuf))
313         {
314                 ReleaseBuffer(scan->xs_cbuf);
315                 scan->xs_cbuf = InvalidBuffer;
316         }
317
318         scan->xs_next_hot = InvalidOffsetNumber;
319
320         scan->kill_prior_tuple = false;         /* for safety */
321
322         FunctionCall5(procedure,
323                                   PointerGetDatum(scan),
324                                   PointerGetDatum(keys),
325                                   Int32GetDatum(nkeys),
326                                   PointerGetDatum(orderbys),
327                                   Int32GetDatum(norderbys));
328 }
329
330 /* ----------------
331  *              index_endscan - end a scan
332  * ----------------
333  */
334 void
335 index_endscan(IndexScanDesc scan)
336 {
337         FmgrInfo   *procedure;
338
339         SCAN_CHECKS;
340         GET_SCAN_PROCEDURE(amendscan);
341
342         /* Release any held pin on a heap page */
343         if (BufferIsValid(scan->xs_cbuf))
344         {
345                 ReleaseBuffer(scan->xs_cbuf);
346                 scan->xs_cbuf = InvalidBuffer;
347         }
348
349         /* End the AM's scan */
350         FunctionCall1(procedure, PointerGetDatum(scan));
351
352         /* Release index refcount acquired by index_beginscan */
353         RelationDecrementReferenceCount(scan->indexRelation);
354
355         /* Release the scan data structure itself */
356         IndexScanEnd(scan);
357 }
358
359 /* ----------------
360  *              index_markpos  - mark a scan position
361  * ----------------
362  */
363 void
364 index_markpos(IndexScanDesc scan)
365 {
366         FmgrInfo   *procedure;
367
368         SCAN_CHECKS;
369         GET_SCAN_PROCEDURE(ammarkpos);
370
371         FunctionCall1(procedure, PointerGetDatum(scan));
372 }
373
374 /* ----------------
375  *              index_restrpos  - restore a scan position
376  *
377  * NOTE: this only restores the internal scan state of the index AM.
378  * The current result tuple (scan->xs_ctup) doesn't change.  See comments
379  * for ExecRestrPos().
380  *
381  * NOTE: in the presence of HOT chains, mark/restore only works correctly
382  * if the scan's snapshot is MVCC-safe; that ensures that there's at most one
383  * returnable tuple in each HOT chain, and so restoring the prior state at the
384  * granularity of the index AM is sufficient.  Since the only current user
385  * of mark/restore functionality is nodeMergejoin.c, this effectively means
386  * that merge-join plans only work for MVCC snapshots.  This could be fixed
387  * if necessary, but for now it seems unimportant.
388  * ----------------
389  */
390 void
391 index_restrpos(IndexScanDesc scan)
392 {
393         FmgrInfo   *procedure;
394
395         Assert(IsMVCCSnapshot(scan->xs_snapshot));
396
397         SCAN_CHECKS;
398         GET_SCAN_PROCEDURE(amrestrpos);
399
400         scan->xs_next_hot = InvalidOffsetNumber;
401
402         scan->kill_prior_tuple = false;         /* for safety */
403
404         FunctionCall1(procedure, PointerGetDatum(scan));
405 }
406
407 /* ----------------
408  *              index_getnext - get the next heap tuple from a scan
409  *
410  * The result is the next heap tuple satisfying the scan keys and the
411  * snapshot, or NULL if no more matching tuples exist.  On success,
412  * the buffer containing the heap tuple is pinned (the pin will be dropped
413  * at the next index_getnext or index_endscan).
414  *
415  * Note: caller must check scan->xs_recheck, and perform rechecking of the
416  * scan keys if required.  We do not do that here because we don't have
417  * enough information to do it efficiently in the general case.
418  * ----------------
419  */
420 HeapTuple
421 index_getnext(IndexScanDesc scan, ScanDirection direction)
422 {
423         HeapTuple       heapTuple = &scan->xs_ctup;
424         ItemPointer tid = &heapTuple->t_self;
425         FmgrInfo   *procedure;
426
427         SCAN_CHECKS;
428         GET_SCAN_PROCEDURE(amgettuple);
429
430         Assert(TransactionIdIsValid(RecentGlobalXmin));
431
432         /*
433          * We always reset xs_hot_dead; if we are here then either we are just
434          * starting the scan, or we previously returned a visible tuple, and in
435          * either case it's inappropriate to kill the prior index entry.
436          */
437         scan->xs_hot_dead = false;
438
439         for (;;)
440         {
441                 OffsetNumber offnum;
442                 bool            at_chain_start;
443                 Page            dp;
444
445                 if (scan->xs_next_hot != InvalidOffsetNumber)
446                 {
447                         /*
448                          * We are resuming scan of a HOT chain after having returned an
449                          * earlier member.      Must still hold pin on current heap page.
450                          */
451                         Assert(BufferIsValid(scan->xs_cbuf));
452                         Assert(ItemPointerGetBlockNumber(tid) ==
453                                    BufferGetBlockNumber(scan->xs_cbuf));
454                         Assert(TransactionIdIsValid(scan->xs_prev_xmax));
455                         offnum = scan->xs_next_hot;
456                         at_chain_start = false;
457                         scan->xs_next_hot = InvalidOffsetNumber;
458                 }
459                 else
460                 {
461                         bool            found;
462                         Buffer          prev_buf;
463
464                         /*
465                          * If we scanned a whole HOT chain and found only dead tuples,
466                          * tell index AM to kill its entry for that TID. We do not do this
467                          * when in recovery because it may violate MVCC to do so. see
468                          * comments in RelationGetIndexScan().
469                          */
470                         if (!scan->xactStartedInRecovery)
471                                 scan->kill_prior_tuple = scan->xs_hot_dead;
472
473                         /*
474                          * The AM's gettuple proc finds the next index entry matching the
475                          * scan keys, and puts the TID in xs_ctup.t_self (ie, *tid). It
476                          * should also set scan->xs_recheck, though we pay no attention to
477                          * that here.
478                          */
479                         found = DatumGetBool(FunctionCall2(procedure,
480                                                                                            PointerGetDatum(scan),
481                                                                                            Int32GetDatum(direction)));
482
483                         /* Reset kill flag immediately for safety */
484                         scan->kill_prior_tuple = false;
485
486                         /* If we're out of index entries, break out of outer loop */
487                         if (!found)
488                                 break;
489
490                         pgstat_count_index_tuples(scan->indexRelation, 1);
491
492                         /* Switch to correct buffer if we don't have it already */
493                         prev_buf = scan->xs_cbuf;
494                         scan->xs_cbuf = ReleaseAndReadBuffer(scan->xs_cbuf,
495                                                                                                  scan->heapRelation,
496                                                                                          ItemPointerGetBlockNumber(tid));
497
498                         /*
499                          * Prune page, but only if we weren't already on this page
500                          */
501                         if (prev_buf != scan->xs_cbuf)
502                                 heap_page_prune_opt(scan->heapRelation, scan->xs_cbuf,
503                                                                         RecentGlobalXmin);
504
505                         /* Prepare to scan HOT chain starting at index-referenced offnum */
506                         offnum = ItemPointerGetOffsetNumber(tid);
507                         at_chain_start = true;
508
509                         /* We don't know what the first tuple's xmin should be */
510                         scan->xs_prev_xmax = InvalidTransactionId;
511
512                         /* Initialize flag to detect if all entries are dead */
513                         scan->xs_hot_dead = true;
514                 }
515
516                 /* Obtain share-lock on the buffer so we can examine visibility */
517                 LockBuffer(scan->xs_cbuf, BUFFER_LOCK_SHARE);
518
519                 dp = (Page) BufferGetPage(scan->xs_cbuf);
520
521                 /* Scan through possible multiple members of HOT-chain */
522                 for (;;)
523                 {
524                         ItemId          lp;
525                         ItemPointer ctid;
526
527                         /* check for bogus TID */
528                         if (offnum < FirstOffsetNumber ||
529                                 offnum > PageGetMaxOffsetNumber(dp))
530                                 break;
531
532                         lp = PageGetItemId(dp, offnum);
533
534                         /* check for unused, dead, or redirected items */
535                         if (!ItemIdIsNormal(lp))
536                         {
537                                 /* We should only see a redirect at start of chain */
538                                 if (ItemIdIsRedirected(lp) && at_chain_start)
539                                 {
540                                         /* Follow the redirect */
541                                         offnum = ItemIdGetRedirect(lp);
542                                         at_chain_start = false;
543                                         continue;
544                                 }
545                                 /* else must be end of chain */
546                                 break;
547                         }
548
549                         /*
550                          * We must initialize all of *heapTuple (ie, scan->xs_ctup) since
551                          * it is returned to the executor on success.
552                          */
553                         heapTuple->t_data = (HeapTupleHeader) PageGetItem(dp, lp);
554                         heapTuple->t_len = ItemIdGetLength(lp);
555                         ItemPointerSetOffsetNumber(tid, offnum);
556                         heapTuple->t_tableOid = RelationGetRelid(scan->heapRelation);
557                         ctid = &heapTuple->t_data->t_ctid;
558
559                         /*
560                          * Shouldn't see a HEAP_ONLY tuple at chain start.  (This test
561                          * should be unnecessary, since the chain root can't be removed
562                          * while we have pin on the index entry, but let's make it
563                          * anyway.)
564                          */
565                         if (at_chain_start && HeapTupleIsHeapOnly(heapTuple))
566                                 break;
567
568                         /*
569                          * The xmin should match the previous xmax value, else chain is
570                          * broken.      (Note: this test is not optional because it protects
571                          * us against the case where the prior chain member's xmax aborted
572                          * since we looked at it.)
573                          */
574                         if (TransactionIdIsValid(scan->xs_prev_xmax) &&
575                                 !TransactionIdEquals(scan->xs_prev_xmax,
576                                                                   HeapTupleHeaderGetXmin(heapTuple->t_data)))
577                                 break;
578
579                         /* If it's visible per the snapshot, we must return it */
580                         if (HeapTupleSatisfiesVisibility(heapTuple, scan->xs_snapshot,
581                                                                                          scan->xs_cbuf))
582                         {
583                                 /*
584                                  * If the snapshot is MVCC, we know that it could accept at
585                                  * most one member of the HOT chain, so we can skip examining
586                                  * any more members.  Otherwise, check for continuation of the
587                                  * HOT-chain, and set state for next time.
588                                  */
589                                 if (IsMVCCSnapshot(scan->xs_snapshot))
590                                         scan->xs_next_hot = InvalidOffsetNumber;
591                                 else if (HeapTupleIsHotUpdated(heapTuple))
592                                 {
593                                         Assert(ItemPointerGetBlockNumber(ctid) ==
594                                                    ItemPointerGetBlockNumber(tid));
595                                         scan->xs_next_hot = ItemPointerGetOffsetNumber(ctid);
596                                         scan->xs_prev_xmax = HeapTupleHeaderGetXmax(heapTuple->t_data);
597                                 }
598                                 else
599                                         scan->xs_next_hot = InvalidOffsetNumber;
600
601                                 LockBuffer(scan->xs_cbuf, BUFFER_LOCK_UNLOCK);
602
603                                 pgstat_count_heap_fetch(scan->indexRelation);
604
605                                 return heapTuple;
606                         }
607
608                         /*
609                          * If we can't see it, maybe no one else can either.  Check to see
610                          * if the tuple is dead to all transactions.  If we find that all
611                          * the tuples in the HOT chain are dead, we'll signal the index AM
612                          * to not return that TID on future indexscans.
613                          */
614                         if (scan->xs_hot_dead &&
615                                 HeapTupleSatisfiesVacuum(heapTuple->t_data, RecentGlobalXmin,
616                                                                                  scan->xs_cbuf) != HEAPTUPLE_DEAD)
617                                 scan->xs_hot_dead = false;
618
619                         /*
620                          * Check to see if HOT chain continues past this tuple; if so
621                          * fetch the next offnum (we don't bother storing it into
622                          * xs_next_hot, but must store xs_prev_xmax), and loop around.
623                          */
624                         if (HeapTupleIsHotUpdated(heapTuple))
625                         {
626                                 Assert(ItemPointerGetBlockNumber(ctid) ==
627                                            ItemPointerGetBlockNumber(tid));
628                                 offnum = ItemPointerGetOffsetNumber(ctid);
629                                 at_chain_start = false;
630                                 scan->xs_prev_xmax = HeapTupleHeaderGetXmax(heapTuple->t_data);
631                         }
632                         else
633                                 break;                  /* end of chain */
634                 }                                               /* loop over a single HOT chain */
635
636                 LockBuffer(scan->xs_cbuf, BUFFER_LOCK_UNLOCK);
637
638                 /* Loop around to ask index AM for another TID */
639                 scan->xs_next_hot = InvalidOffsetNumber;
640         }
641
642         /* Release any held pin on a heap page */
643         if (BufferIsValid(scan->xs_cbuf))
644         {
645                 ReleaseBuffer(scan->xs_cbuf);
646                 scan->xs_cbuf = InvalidBuffer;
647         }
648
649         return NULL;                            /* failure exit */
650 }
651
652 /* ----------------
653  *              index_getbitmap - get all tuples at once from an index scan
654  *
655  * Adds the TIDs of all heap tuples satisfying the scan keys to a bitmap.
656  * Since there's no interlock between the index scan and the eventual heap
657  * access, this is only safe to use with MVCC-based snapshots: the heap
658  * item slot could have been replaced by a newer tuple by the time we get
659  * to it.
660  *
661  * Returns the number of matching tuples found.  (Note: this might be only
662  * approximate, so it should only be used for statistical purposes.)
663  * ----------------
664  */
665 int64
666 index_getbitmap(IndexScanDesc scan, TIDBitmap *bitmap)
667 {
668         FmgrInfo   *procedure;
669         int64           ntids;
670         Datum           d;
671
672         SCAN_CHECKS;
673         GET_SCAN_PROCEDURE(amgetbitmap);
674
675         /* just make sure this is false... */
676         scan->kill_prior_tuple = false;
677
678         /*
679          * have the am's getbitmap proc do all the work.
680          */
681         d = FunctionCall2(procedure,
682                                           PointerGetDatum(scan),
683                                           PointerGetDatum(bitmap));
684
685         ntids = DatumGetInt64(d);
686
687         /* If int8 is pass-by-ref, must free the result to avoid memory leak */
688 #ifndef USE_FLOAT8_BYVAL
689         pfree(DatumGetPointer(d));
690 #endif
691
692         pgstat_count_index_tuples(scan->indexRelation, ntids);
693
694         return ntids;
695 }
696
697 /* ----------------
698  *              index_bulk_delete - do mass deletion of index entries
699  *
700  *              callback routine tells whether a given main-heap tuple is
701  *              to be deleted
702  *
703  *              return value is an optional palloc'd struct of statistics
704  * ----------------
705  */
706 IndexBulkDeleteResult *
707 index_bulk_delete(IndexVacuumInfo *info,
708                                   IndexBulkDeleteResult *stats,
709                                   IndexBulkDeleteCallback callback,
710                                   void *callback_state)
711 {
712         Relation        indexRelation = info->index;
713         FmgrInfo   *procedure;
714         IndexBulkDeleteResult *result;
715
716         RELATION_CHECKS;
717         GET_REL_PROCEDURE(ambulkdelete);
718
719         result = (IndexBulkDeleteResult *)
720                 DatumGetPointer(FunctionCall4(procedure,
721                                                                           PointerGetDatum(info),
722                                                                           PointerGetDatum(stats),
723                                                                           PointerGetDatum((Pointer) callback),
724                                                                           PointerGetDatum(callback_state)));
725
726         return result;
727 }
728
729 /* ----------------
730  *              index_vacuum_cleanup - do post-deletion cleanup of an index
731  *
732  *              return value is an optional palloc'd struct of statistics
733  * ----------------
734  */
735 IndexBulkDeleteResult *
736 index_vacuum_cleanup(IndexVacuumInfo *info,
737                                          IndexBulkDeleteResult *stats)
738 {
739         Relation        indexRelation = info->index;
740         FmgrInfo   *procedure;
741         IndexBulkDeleteResult *result;
742
743         RELATION_CHECKS;
744         GET_REL_PROCEDURE(amvacuumcleanup);
745
746         result = (IndexBulkDeleteResult *)
747                 DatumGetPointer(FunctionCall2(procedure,
748                                                                           PointerGetDatum(info),
749                                                                           PointerGetDatum(stats)));
750
751         return result;
752 }
753
754 /* ----------------
755  *              index_getprocid
756  *
757  *              Index access methods typically require support routines that are
758  *              not directly the implementation of any WHERE-clause query operator
759  *              and so cannot be kept in pg_amop.  Instead, such routines are kept
760  *              in pg_amproc.  These registered procedure OIDs are assigned numbers
761  *              according to a convention established by the access method.
762  *              The general index code doesn't know anything about the routines
763  *              involved; it just builds an ordered list of them for
764  *              each attribute on which an index is defined.
765  *
766  *              As of Postgres 8.3, support routines within an operator family
767  *              are further subdivided by the "left type" and "right type" of the
768  *              query operator(s) that they support.  The "default" functions for a
769  *              particular indexed attribute are those with both types equal to
770  *              the index opclass' opcintype (note that this is subtly different
771  *              from the indexed attribute's own type: it may be a binary-compatible
772  *              type instead).  Only the default functions are stored in relcache
773  *              entries --- access methods can use the syscache to look up non-default
774  *              functions.
775  *
776  *              This routine returns the requested default procedure OID for a
777  *              particular indexed attribute.
778  * ----------------
779  */
780 RegProcedure
781 index_getprocid(Relation irel,
782                                 AttrNumber attnum,
783                                 uint16 procnum)
784 {
785         RegProcedure *loc;
786         int                     nproc;
787         int                     procindex;
788
789         nproc = irel->rd_am->amsupport;
790
791         Assert(procnum > 0 && procnum <= (uint16) nproc);
792
793         procindex = (nproc * (attnum - 1)) + (procnum - 1);
794
795         loc = irel->rd_support;
796
797         Assert(loc != NULL);
798
799         return loc[procindex];
800 }
801
802 /* ----------------
803  *              index_getprocinfo
804  *
805  *              This routine allows index AMs to keep fmgr lookup info for
806  *              support procs in the relcache.  As above, only the "default"
807  *              functions for any particular indexed attribute are cached.
808  *
809  * Note: the return value points into cached data that will be lost during
810  * any relcache rebuild!  Therefore, either use the callinfo right away,
811  * or save it only after having acquired some type of lock on the index rel.
812  * ----------------
813  */
814 FmgrInfo *
815 index_getprocinfo(Relation irel,
816                                   AttrNumber attnum,
817                                   uint16 procnum)
818 {
819         FmgrInfo   *locinfo;
820         int                     nproc;
821         int                     procindex;
822
823         nproc = irel->rd_am->amsupport;
824
825         Assert(procnum > 0 && procnum <= (uint16) nproc);
826
827         procindex = (nproc * (attnum - 1)) + (procnum - 1);
828
829         locinfo = irel->rd_supportinfo;
830
831         Assert(locinfo != NULL);
832
833         locinfo += procindex;
834
835         /* Initialize the lookup info if first time through */
836         if (locinfo->fn_oid == InvalidOid)
837         {
838                 RegProcedure *loc = irel->rd_support;
839                 RegProcedure procId;
840
841                 Assert(loc != NULL);
842
843                 procId = loc[procindex];
844
845                 /*
846                  * Complain if function was not found during IndexSupportInitialize.
847                  * This should not happen unless the system tables contain bogus
848                  * entries for the index opclass.  (If an AM wants to allow a support
849                  * function to be optional, it can use index_getprocid.)
850                  */
851                 if (!RegProcedureIsValid(procId))
852                         elog(ERROR, "missing support function %d for attribute %d of index \"%s\"",
853                                  procnum, attnum, RelationGetRelationName(irel));
854
855                 fmgr_info_cxt(procId, locinfo, irel->rd_indexcxt);
856         }
857
858         return locinfo;
859 }