OSDN Git Service

Rename several destroy* functions/tags to drop*.
[pg-rex/syncrep.git] / src / backend / access / gist / gist.c
1 /*-------------------------------------------------------------------------
2  *
3  * gist.c
4  *        interface routines for the postgres GiST index access method.
5  *
6  *
7  *
8  * IDENTIFICATION
9  *        $Header: /cvsroot/pgsql/src/backend/access/gist/gist.c,v 1.48 1999/12/10 03:55:42 momjian Exp $
10  *
11  *-------------------------------------------------------------------------
12  */
13
14 #include "postgres.h"
15
16 #include "access/genam.h"
17 #include "access/gist.h"
18 #include "access/gistscan.h"
19 #include "access/heapam.h"
20 #include "catalog/index.h"
21 #include "catalog/pg_index.h"
22 #include "executor/executor.h"
23 #include "miscadmin.h"
24 #include "utils/syscache.h"
25
26
27 /* non-export function prototypes */
28 static InsertIndexResult gistdoinsert(Relation r, IndexTuple itup,
29                          GISTSTATE *GISTstate);
30 static InsertIndexResult gistentryinsert(Relation r, GISTSTACK *stk,
31                                 IndexTuple tup,
32                                 GISTSTATE *giststate);
33 static void gistentryinserttwo(Relation r, GISTSTACK *stk, IndexTuple ltup,
34                                    IndexTuple rtup, GISTSTATE *giststate);
35 static void gistAdjustKeys(Relation r, GISTSTACK *stk, BlockNumber blk,
36                            char *datum, int att_size, GISTSTATE *giststate);
37 static void gistintinsert(Relation r, GISTSTACK *stk, IndexTuple ltup,
38                           IndexTuple rtup, GISTSTATE *giststate);
39 static InsertIndexResult gistSplit(Relation r, Buffer buffer,
40                   GISTSTACK *stack, IndexTuple itup,
41                   GISTSTATE *giststate);
42 static void gistnewroot(GISTSTATE *giststate, Relation r, IndexTuple lt,
43                         IndexTuple rt);
44 static void GISTInitBuffer(Buffer b, uint32 f);
45 static BlockNumber gistChooseSubtree(Relation r, IndexTuple itup, int level,
46                                   GISTSTATE *giststate,
47                                   GISTSTACK **retstack, Buffer *leafbuf);
48 static OffsetNumber gistchoose(Relation r, Page p, IndexTuple it,
49                    GISTSTATE *giststate);
50 static int      gistnospace(Page p, IndexTuple it);
51 void            gistdelete(Relation r, ItemPointer tid);
52 static IndexTuple gist_tuple_replacekey(Relation r, GISTENTRY entry, IndexTuple t);
53 static void gistcentryinit(GISTSTATE *giststate, GISTENTRY *e, char *pr,
54                            Relation r, Page pg, OffsetNumber o, int b, bool l);
55 #ifdef GISTDEBUG
56 static char *int_range_out(INTRANGE *r);
57 #endif
58
59 /*
60 ** routine to build an index.  Basically calls insert over and over
61 */
62 void
63 gistbuild(Relation heap,
64                   Relation index,
65                   int natts,
66                   AttrNumber *attnum,
67                   IndexStrategy istrat,
68                   uint16 pint,
69                   Datum *params,
70                   FuncIndexInfo *finfo,
71                   PredInfo *predInfo)
72 {
73         HeapScanDesc scan;
74         AttrNumber      i;
75         HeapTuple       htup;
76         IndexTuple      itup;
77         TupleDesc       hd,
78                                 id;
79         InsertIndexResult res;
80         Datum      *d;
81         bool       *nulls;
82         int                     nb,
83                                 nh,
84                                 ni;
85
86 #ifndef OMIT_PARTIAL_INDEX
87         ExprContext *econtext;
88         TupleTable      tupleTable;
89         TupleTableSlot *slot;
90
91 #endif
92         Node       *pred,
93                            *oldPred;
94         GISTSTATE       giststate;
95         GISTENTRY       tmpcentry;
96         Buffer          buffer = InvalidBuffer;
97         bool       *compvec;
98
99         /* no locking is needed */
100
101         setheapoverride(true);          /* so we can see the new pg_index tuple */
102         initGISTstate(&giststate, index);
103         setheapoverride(false);
104
105         pred = predInfo->pred;
106         oldPred = predInfo->oldPred;
107
108         /*
109          * We expect to be called exactly once for any index relation. If
110          * that's not the case, big trouble's what we have.
111          */
112
113         if (oldPred == NULL && (nb = RelationGetNumberOfBlocks(index)) != 0)
114                 elog(ERROR, "%s already contains data", RelationGetRelationName(index));
115
116         /* initialize the root page (if this is a new index) */
117         if (oldPred == NULL)
118         {
119                 buffer = ReadBuffer(index, P_NEW);
120                 GISTInitBuffer(buffer, F_LEAF);
121                 WriteBuffer(buffer);
122         }
123
124         /* init the tuple descriptors and get set for a heap scan */
125         hd = RelationGetDescr(heap);
126         id = RelationGetDescr(index);
127         d = (Datum *) palloc(natts * sizeof(*d));
128         nulls = (bool *) palloc(natts * sizeof(*nulls));
129
130         /*
131          * If this is a predicate (partial) index, we will need to evaluate
132          * the predicate using ExecQual, which requires the current tuple to
133          * be in a slot of a TupleTable.  In addition, ExecQual must have an
134          * ExprContext referring to that slot.  Here, we initialize dummy
135          * TupleTable and ExprContext objects for this purpose. --Nels, Feb
136          * '92
137          */
138 #ifndef OMIT_PARTIAL_INDEX
139         if (pred != NULL || oldPred != NULL)
140         {
141                 tupleTable = ExecCreateTupleTable(1);
142                 slot = ExecAllocTableSlot(tupleTable);
143                 econtext = makeNode(ExprContext);
144                 FillDummyExprContext(econtext, slot, hd, InvalidBuffer);
145         }
146         else
147 /* shut the compiler up */
148         {
149                 tupleTable = NULL;
150                 slot = NULL;
151                 econtext = NULL;
152         }
153 #endif   /* OMIT_PARTIAL_INDEX */
154         /* int the tuples as we insert them */
155         nh = ni = 0;
156
157         scan = heap_beginscan(heap, 0, SnapshotNow, 0, (ScanKey) NULL);
158
159         while (HeapTupleIsValid(htup = heap_getnext(scan, 0)))
160         {
161                 nh++;
162
163                 /*
164                  * If oldPred != NULL, this is an EXTEND INDEX command, so skip
165                  * this tuple if it was already in the existing partial index
166                  */
167                 if (oldPred != NULL)
168                 {
169 #ifndef OMIT_PARTIAL_INDEX
170                         /* SetSlotContents(slot, htup); */
171                         slot->val = htup;
172                         if (ExecQual((List *) oldPred, econtext) == true)
173                         {
174                                 ni++;
175                                 continue;
176                         }
177 #endif   /* OMIT_PARTIAL_INDEX */
178                 }
179
180                 /*
181                  * Skip this tuple if it doesn't satisfy the partial-index
182                  * predicate
183                  */
184                 if (pred != NULL)
185                 {
186 #ifndef OMIT_PARTIAL_INDEX
187                         /* SetSlotContents(slot, htup); */
188                         slot->val = htup;
189                         if (ExecQual((List *) pred, econtext) == false)
190                                 continue;
191 #endif   /* OMIT_PARTIAL_INDEX */
192                 }
193
194                 ni++;
195
196                 /*
197                  * For the current heap tuple, extract all the attributes we use
198                  * in this index, and note which are null.
199                  */
200
201                 for (i = 1; i <= natts; i++)
202                 {
203                         int                     attoff;
204                         bool            attnull;
205
206                         /*
207                          * Offsets are from the start of the tuple, and are
208                          * zero-based; indices are one-based.  The next call returns i
209                          * - 1.  That's data hiding for you.
210                          */
211
212                         attoff = AttrNumberGetAttrOffset(i);
213
214                         /*
215                          * d[attoff] = HeapTupleGetAttributeValue(htup, buffer,
216                          */
217                         d[attoff] = GetIndexValue(htup,
218                                                                           hd,
219                                                                           attoff,
220                                                                           attnum,
221                                                                           finfo,
222                                                                           &attnull);
223                         nulls[attoff] = (attnull ? 'n' : ' ');
224                 }
225
226                 /* immediately compress keys to normalize */
227                 compvec = (bool *) palloc(sizeof(bool) * natts);
228                 for (i = 0; i < natts; i++)
229                 {
230                         gistcentryinit(&giststate, &tmpcentry, (char *) d[i],
231                                                    (Relation) NULL, (Page) NULL, (OffsetNumber) 0,
232                                                    -1 /* size is currently bogus */ , TRUE);
233                         if (d[i] != (Datum) tmpcentry.pred && !(giststate.keytypbyval))
234                                 compvec[i] = TRUE;
235                         else
236                                 compvec[i] = FALSE;
237                         d[i] = (Datum) tmpcentry.pred;
238                 }
239
240                 /* form an index tuple and point it at the heap tuple */
241                 itup = index_formtuple(id, &d[0], nulls);
242                 itup->t_tid = htup->t_self;
243
244                 /*
245                  * Since we already have the index relation locked, we call
246                  * gistdoinsert directly.  Normal access method calls dispatch
247                  * through gistinsert, which locks the relation for write.      This
248                  * is the right thing to do if you're inserting single tups, but
249                  * not when you're initializing the whole index at once.
250                  */
251
252                 res = gistdoinsert(index, itup, &giststate);
253                 for (i = 0; i < natts; i++)
254                         if (compvec[i] == TRUE)
255                                 pfree((char *) d[i]);
256                 pfree(itup);
257                 pfree(res);
258                 pfree(compvec);
259         }
260
261         /* okay, all heap tuples are indexed */
262         heap_endscan(scan);
263
264         if (pred != NULL || oldPred != NULL)
265         {
266 #ifndef OMIT_PARTIAL_INDEX
267                 ExecDropTupleTable(tupleTable, true);
268                 pfree(econtext);
269 #endif   /* OMIT_PARTIAL_INDEX */
270         }
271
272         /*
273          * Since we just counted the tuples in the heap, we update its stats
274          * in pg_class to guarantee that the planner takes advantage of the
275          * index we just created.  But, only update statistics during
276          * normal index definitions, not for indices on system catalogs
277          * created during bootstrap processing.  We must close the relations
278          * before updating statistics to guarantee that the relcache entries
279          * are flushed when we increment the command counter in UpdateStats().
280          * But we do not release any locks on the relations; those will be
281          * held until end of transaction.
282          */
283         if (IsNormalProcessingMode())
284         {
285                 Oid             hrelid = RelationGetRelid(heap);
286                 Oid             irelid = RelationGetRelid(index);
287
288                 heap_close(heap, NoLock);
289                 index_close(index);
290                 UpdateStats(hrelid, nh, true);
291                 UpdateStats(irelid, ni, false);
292                 if (oldPred != NULL)
293                 {
294                         if (ni == nh)
295                                 pred = NULL;
296                         UpdateIndexPredicate(irelid, oldPred, pred);
297                 }
298         }
299
300         /* be tidy */
301         pfree(nulls);
302         pfree(d);
303 }
304
305 /*
306  *      gistinsert -- wrapper for GiST tuple insertion.
307  *
308  *        This is the public interface routine for tuple insertion in GiSTs.
309  *        It doesn't do any work; just locks the relation and passes the buck.
310  */
311 InsertIndexResult
312 gistinsert(Relation r, Datum *datum, char *nulls, ItemPointer ht_ctid, Relation heapRel)
313 {
314         InsertIndexResult res;
315         IndexTuple      itup;
316         GISTSTATE       giststate;
317         GISTENTRY       tmpentry;
318         int                     i;
319         bool       *compvec;
320
321         initGISTstate(&giststate, r);
322
323         /* immediately compress keys to normalize */
324         compvec = (bool *) palloc(sizeof(bool) * r->rd_att->natts);
325         for (i = 0; i < r->rd_att->natts; i++)
326         {
327                 gistcentryinit(&giststate, &tmpentry, (char *) datum[i],
328                                            (Relation) NULL, (Page) NULL, (OffsetNumber) 0,
329                                            -1 /* size is currently bogus */ , TRUE);
330                 if (datum[i] != (Datum) tmpentry.pred && !(giststate.keytypbyval))
331                         compvec[i] = TRUE;
332                 else
333                         compvec[i] = FALSE;
334                 datum[i] = (Datum) tmpentry.pred;
335         }
336         itup = index_formtuple(RelationGetDescr(r), datum, nulls);
337         itup->t_tid = *ht_ctid;
338
339         /*
340          * Notes in ExecUtils:ExecOpenIndices()
341          *
342          * RelationSetLockForWrite(r);
343          */
344
345         res = gistdoinsert(r, itup, &giststate);
346         for (i = 0; i < r->rd_att->natts; i++)
347                 if (compvec[i] == TRUE)
348                         pfree((char *) datum[i]);
349         pfree(itup);
350         pfree(compvec);
351
352         return res;
353 }
354
355 /*
356 ** Take a compressed entry, and install it on a page.  Since we now know
357 ** where the entry will live, we decompress it and recompress it using
358 ** that knowledge (some compression routines may want to fish around
359 ** on the page, for example, or do something special for leaf nodes.)
360 */
361 static OffsetNumber
362 gistPageAddItem(GISTSTATE *giststate,
363                                 Relation r,
364                                 Page page,
365                                 Item item,
366                                 Size size,
367                                 OffsetNumber offsetNumber,
368                                 ItemIdFlags flags,
369                                 GISTENTRY *dentry,
370                                 IndexTuple *newtup)
371 {
372         GISTENTRY       tmpcentry;
373         IndexTuple      itup = (IndexTuple) item;
374
375         /*
376          * recompress the item given that we now know the exact page and
377          * offset for insertion
378          */
379         gistdentryinit(giststate, dentry,
380                                    (((char *) itup) + sizeof(IndexTupleData)),
381                           (Relation) 0, (Page) 0, (OffsetNumber) InvalidOffsetNumber,
382                                    IndexTupleSize(itup) - sizeof(IndexTupleData), FALSE);
383         gistcentryinit(giststate, &tmpcentry, dentry->pred, r, page,
384                                    offsetNumber, dentry->bytes, FALSE);
385         *newtup = gist_tuple_replacekey(r, *dentry, itup);
386         /* be tidy */
387         if (tmpcentry.pred != dentry->pred
388                 && tmpcentry.pred != (((char *) itup) + sizeof(IndexTupleData)))
389                 pfree(tmpcentry.pred);
390
391         return (PageAddItem(page, (Item) *newtup, IndexTupleSize(*newtup),
392                                                 offsetNumber, flags));
393 }
394
395
396 static InsertIndexResult
397 gistdoinsert(Relation r,
398                          IndexTuple itup,       /* itup contains compressed entry */
399                          GISTSTATE *giststate)
400 {
401         GISTENTRY       tmpdentry;
402         InsertIndexResult res;
403         OffsetNumber l;
404         GISTSTACK  *stack;
405         Buffer          buffer;
406         BlockNumber blk;
407         Page            page;
408         OffsetNumber off;
409         IndexTuple      newtup;
410
411         /* 3rd arg is ignored for now */
412         blk = gistChooseSubtree(r, itup, 0, giststate, &stack, &buffer);
413         page = (Page) BufferGetPage(buffer);
414
415         if (gistnospace(page, itup))
416         {
417                 /* need to do a split */
418                 res = gistSplit(r, buffer, stack, itup, giststate);
419                 gistfreestack(stack);
420                 WriteBuffer(buffer);    /* don't forget to release buffer! */
421                 return res;
422         }
423
424         if (PageIsEmpty(page))
425                 off = FirstOffsetNumber;
426         else
427                 off = OffsetNumberNext(PageGetMaxOffsetNumber(page));
428
429         /* add the item and write the buffer */
430         l = gistPageAddItem(giststate, r, page, (Item) itup, IndexTupleSize(itup),
431                                                 off, LP_USED, &tmpdentry, &newtup);
432         WriteBuffer(buffer);
433
434         /* now expand the page boundary in the parent to include the new child */
435         gistAdjustKeys(r, stack, blk, tmpdentry.pred, tmpdentry.bytes, giststate);
436         gistfreestack(stack);
437
438         /* be tidy */
439         if (itup != newtup)
440                 pfree(newtup);
441         if (tmpdentry.pred != (((char *) itup) + sizeof(IndexTupleData)))
442                 pfree(tmpdentry.pred);
443
444         /* build and return an InsertIndexResult for this insertion */
445         res = (InsertIndexResult) palloc(sizeof(InsertIndexResultData));
446         ItemPointerSet(&(res->pointerData), blk, l);
447
448         return res;
449 }
450
451
452 static BlockNumber
453 gistChooseSubtree(Relation r, IndexTuple itup,  /* itup has compressed
454                                                                                                  * entry */
455                                   int level,
456                                   GISTSTATE *giststate,
457                                   GISTSTACK **retstack /* out */ ,
458                                   Buffer *leafbuf /* out */ )
459 {
460         Buffer          buffer;
461         BlockNumber blk;
462         GISTSTACK  *stack;
463         Page            page;
464         GISTPageOpaque opaque;
465         IndexTuple      which;
466
467         blk = GISTP_ROOT;
468         buffer = InvalidBuffer;
469         stack = (GISTSTACK *) NULL;
470
471         do
472         {
473                 /* let go of current buffer before getting next */
474                 if (buffer != InvalidBuffer)
475                         ReleaseBuffer(buffer);
476
477                 /* get next buffer */
478                 buffer = ReadBuffer(r, blk);
479                 page = (Page) BufferGetPage(buffer);
480
481                 opaque = (GISTPageOpaque) PageGetSpecialPointer(page);
482                 if (!(opaque->flags & F_LEAF))
483                 {
484                         GISTSTACK  *n;
485                         ItemId          iid;
486
487                         n = (GISTSTACK *) palloc(sizeof(GISTSTACK));
488                         n->gs_parent = stack;
489                         n->gs_blk = blk;
490                         n->gs_child = gistchoose(r, page, itup, giststate);
491                         stack = n;
492
493                         iid = PageGetItemId(page, n->gs_child);
494                         which = (IndexTuple) PageGetItem(page, iid);
495                         blk = ItemPointerGetBlockNumber(&(which->t_tid));
496                 }
497         } while (!(opaque->flags & F_LEAF));
498
499         *retstack = stack;
500         *leafbuf = buffer;
501
502         return blk;
503 }
504
505
506 static void
507 gistAdjustKeys(Relation r,
508                            GISTSTACK *stk,
509                            BlockNumber blk,
510                            char *datum,         /* datum is uncompressed */
511                            int att_size,
512                            GISTSTATE *giststate)
513 {
514         char       *oldud;
515         Page            p;
516         Buffer          b;
517         bool            result;
518         bytea      *evec;
519         GISTENTRY       centry,
520                            *ev0p,
521                            *ev1p;
522         int                     size,
523                                 datumsize;
524         IndexTuple      tid;
525
526         if (stk == (GISTSTACK *) NULL)
527                 return;
528
529         b = ReadBuffer(r, stk->gs_blk);
530         p = BufferGetPage(b);
531
532         oldud = (char *) PageGetItem(p, PageGetItemId(p, stk->gs_child));
533         tid = (IndexTuple) oldud;
534         size = IndexTupleSize((IndexTuple) oldud) - sizeof(IndexTupleData);
535         oldud += sizeof(IndexTupleData);
536
537         evec = (bytea *) palloc(2 * sizeof(GISTENTRY) + VARHDRSZ);
538         VARSIZE(evec) = 2 * sizeof(GISTENTRY) + VARHDRSZ;
539
540         /* insert decompressed oldud into entry vector */
541         gistdentryinit(giststate, &((GISTENTRY *) VARDATA(evec))[0],
542                                    oldud, r, p, stk->gs_child,
543                                    size, FALSE);
544         ev0p = &((GISTENTRY *) VARDATA(evec))[0];
545
546         /* insert datum entry into entry vector */
547         gistentryinit(((GISTENTRY *) VARDATA(evec))[1], datum,
548                 (Relation) NULL, (Page) NULL, (OffsetNumber) 0, att_size, FALSE);
549         ev1p = &((GISTENTRY *) VARDATA(evec))[1];
550
551         /* form union of decompressed entries */
552         datum = (*fmgr_faddr(&giststate->unionFn)) (evec, &datumsize);
553
554         /* did union leave decompressed version of oldud unchanged? */
555         (*fmgr_faddr(&giststate->equalFn)) (ev0p->pred, datum, &result);
556         if (!result)
557         {
558                 TupleDesc       td = RelationGetDescr(r);
559
560                 /* compress datum for storage on page */
561                 gistcentryinit(giststate, &centry, datum, ev0p->rel, ev0p->page,
562                                            ev0p->offset, datumsize, FALSE);
563                 if (td->attrs[0]->attlen >= 0)
564                 {
565                         memmove(oldud, centry.pred, att_size);
566                         gistAdjustKeys(r, stk->gs_parent, stk->gs_blk, datum, att_size,
567                                                    giststate);
568                 }
569                 else if (VARSIZE(centry.pred) == VARSIZE(oldud))
570                 {
571                         memmove(oldud, centry.pred, VARSIZE(centry.pred));
572                         gistAdjustKeys(r, stk->gs_parent, stk->gs_blk, datum, att_size,
573                                                    giststate);
574                 }
575                 else
576                 {
577
578                         /*
579                          * * new datum is not the same size as the old. * We have to
580                          * delete the old entry and insert the new * one.  Note that
581                          * this may cause a split here!
582                          */
583                         IndexTuple      newtup;
584                         ItemPointerData oldtid;
585                         char       *isnull;
586                         TupleDesc       tupDesc;
587                         InsertIndexResult res;
588
589                         /* delete old tuple */
590                         ItemPointerSet(&oldtid, stk->gs_blk, stk->gs_child);
591                         gistdelete(r, (ItemPointer) &oldtid);
592
593                         /* generate and insert new tuple */
594                         tupDesc = r->rd_att;
595                         isnull = (char *) palloc(r->rd_rel->relnatts);
596                         MemSet(isnull, ' ', r->rd_rel->relnatts);
597                         newtup = (IndexTuple) index_formtuple(tupDesc,
598                                                                                  (Datum *) &centry.pred, isnull);
599                         pfree(isnull);
600                         /* set pointer in new tuple to point to current child */
601                         ItemPointerSet(&oldtid, blk, 1);
602                         newtup->t_tid = oldtid;
603
604                         /* inserting the new entry also adjust keys above */
605                         res = gistentryinsert(r, stk, newtup, giststate);
606
607                         /* in stack, set info to point to new tuple */
608                         stk->gs_blk = ItemPointerGetBlockNumber(&(res->pointerData));
609                         stk->gs_child = ItemPointerGetOffsetNumber(&(res->pointerData));
610
611                         pfree(res);
612                 }
613                 WriteBuffer(b);
614
615                 if (centry.pred != datum)
616                         pfree(datum);
617         }
618         else
619                 ReleaseBuffer(b);
620         pfree(evec);
621 }
622
623 /*
624  *      gistSplit -- split a page in the tree.
625  *
626  */
627 static InsertIndexResult
628 gistSplit(Relation r,
629                   Buffer buffer,
630                   GISTSTACK *stack,
631                   IndexTuple itup,              /* contains compressed entry */
632                   GISTSTATE *giststate)
633 {
634         Page            p;
635         Buffer          leftbuf,
636                                 rightbuf;
637         Page            left,
638                                 right;
639         ItemId          itemid;
640         IndexTuple      item;
641         IndexTuple      ltup,
642                                 rtup,
643                                 newtup;
644         OffsetNumber maxoff;
645         OffsetNumber i;
646         OffsetNumber leftoff,
647                                 rightoff;
648         BlockNumber lbknum,
649                                 rbknum;
650         BlockNumber bufblock;
651         GISTPageOpaque opaque;
652         int                     blank;
653         InsertIndexResult res;
654         char       *isnull;
655         GIST_SPLITVEC v;
656         TupleDesc       tupDesc;
657         bytea      *entryvec;
658         bool       *decompvec;
659         IndexTuple      item_1;
660         GISTENTRY       tmpdentry,
661                                 tmpentry;
662
663         isnull = (char *) palloc(r->rd_rel->relnatts);
664         for (blank = 0; blank < r->rd_rel->relnatts; blank++)
665                 isnull[blank] = ' ';
666         p = (Page) BufferGetPage(buffer);
667         opaque = (GISTPageOpaque) PageGetSpecialPointer(p);
668
669
670         /*
671          * The root of the tree is the first block in the relation.  If we're
672          * about to split the root, we need to do some hocus-pocus to enforce
673          * this guarantee.
674          */
675
676         if (BufferGetBlockNumber(buffer) == GISTP_ROOT)
677         {
678                 leftbuf = ReadBuffer(r, P_NEW);
679                 GISTInitBuffer(leftbuf, opaque->flags);
680                 lbknum = BufferGetBlockNumber(leftbuf);
681                 left = (Page) BufferGetPage(leftbuf);
682         }
683         else
684         {
685                 leftbuf = buffer;
686                 IncrBufferRefCount(buffer);
687                 lbknum = BufferGetBlockNumber(buffer);
688                 left = (Page) PageGetTempPage(p, sizeof(GISTPageOpaqueData));
689         }
690
691         rightbuf = ReadBuffer(r, P_NEW);
692         GISTInitBuffer(rightbuf, opaque->flags);
693         rbknum = BufferGetBlockNumber(rightbuf);
694         right = (Page) BufferGetPage(rightbuf);
695
696         /* generate the item array */
697         maxoff = PageGetMaxOffsetNumber(p);
698         entryvec = (bytea *) palloc(VARHDRSZ + (maxoff + 2) * sizeof(GISTENTRY));
699         decompvec = (bool *) palloc(VARHDRSZ + (maxoff + 2) * sizeof(bool));
700         for (i = FirstOffsetNumber; i <= maxoff; i = OffsetNumberNext(i))
701         {
702                 item_1 = (IndexTuple) PageGetItem(p, PageGetItemId(p, i));
703                 gistdentryinit(giststate, &((GISTENTRY *) VARDATA(entryvec))[i],
704                                            (((char *) item_1) + sizeof(IndexTupleData)),
705                                            r, p, i,
706                                  IndexTupleSize(item_1) - sizeof(IndexTupleData), FALSE);
707                 if ((char *) (((GISTENTRY *) VARDATA(entryvec))[i].pred)
708                         == (((char *) item_1) + sizeof(IndexTupleData)))
709                         decompvec[i] = FALSE;
710                 else
711                         decompvec[i] = TRUE;
712         }
713
714         /* add the new datum as the last entry */
715         gistdentryinit(giststate, &(((GISTENTRY *) VARDATA(entryvec))[maxoff + 1]),
716                                    (((char *) itup) + sizeof(IndexTupleData)),
717                                    (Relation) NULL, (Page) NULL,
718                                    (OffsetNumber) 0, tmpentry.bytes, FALSE);
719         if ((char *) (((GISTENTRY *) VARDATA(entryvec))[maxoff + 1]).pred !=
720                 (((char *) itup) + sizeof(IndexTupleData)))
721                 decompvec[maxoff + 1] = TRUE;
722         else
723                 decompvec[maxoff + 1] = FALSE;
724
725         VARSIZE(entryvec) = (maxoff + 2) * sizeof(GISTENTRY) + VARHDRSZ;
726
727         /* now let the user-defined picksplit function set up the split vector */
728         (*fmgr_faddr(&giststate->picksplitFn)) (entryvec, &v);
729
730         /* compress ldatum and rdatum */
731         gistcentryinit(giststate, &tmpentry, v.spl_ldatum, (Relation) NULL,
732                                    (Page) NULL, (OffsetNumber) 0,
733                                    ((GISTENTRY *) VARDATA(entryvec))[i].bytes, FALSE);
734         if (v.spl_ldatum != tmpentry.pred)
735                 pfree(v.spl_ldatum);
736         v.spl_ldatum = tmpentry.pred;
737
738         gistcentryinit(giststate, &tmpentry, v.spl_rdatum, (Relation) NULL,
739                                    (Page) NULL, (OffsetNumber) 0,
740                                    ((GISTENTRY *) VARDATA(entryvec))[i].bytes, FALSE);
741         if (v.spl_rdatum != tmpentry.pred)
742                 pfree(v.spl_rdatum);
743         v.spl_rdatum = tmpentry.pred;
744
745         /* clean up the entry vector: its preds need to be deleted, too */
746         for (i = FirstOffsetNumber; i <= maxoff + 1; i = OffsetNumberNext(i))
747                 if (decompvec[i])
748                         pfree(((GISTENTRY *) VARDATA(entryvec))[i].pred);
749         pfree(entryvec);
750         pfree(decompvec);
751
752         leftoff = rightoff = FirstOffsetNumber;
753         maxoff = PageGetMaxOffsetNumber(p);
754         for (i = FirstOffsetNumber; i <= maxoff; i = OffsetNumberNext(i))
755         {
756                 itemid = PageGetItemId(p, i);
757                 item = (IndexTuple) PageGetItem(p, itemid);
758
759                 if (i == *(v.spl_left))
760                 {
761                         gistPageAddItem(giststate, r, left, (Item) item,
762                                                         IndexTupleSize(item),
763                                                         leftoff, LP_USED, &tmpdentry, &newtup);
764                         leftoff = OffsetNumberNext(leftoff);
765                         v.spl_left++;           /* advance in left split vector */
766                         /* be tidy */
767                         if (tmpdentry.pred != (((char *) item) + sizeof(IndexTupleData)))
768                                 pfree(tmpdentry.pred);
769                         if ((IndexTuple) item != newtup)
770                                 pfree(newtup);
771                 }
772                 else
773                 {
774                         gistPageAddItem(giststate, r, right, (Item) item,
775                                                         IndexTupleSize(item),
776                                                         rightoff, LP_USED, &tmpdentry, &newtup);
777                         rightoff = OffsetNumberNext(rightoff);
778                         v.spl_right++;          /* advance in right split vector */
779                         /* be tidy */
780                         if (tmpdentry.pred != (((char *) item) + sizeof(IndexTupleData)))
781                                 pfree(tmpdentry.pred);
782                         if (item != newtup)
783                                 pfree(newtup);
784                 }
785         }
786
787         /* build an InsertIndexResult for this insertion */
788         res = (InsertIndexResult) palloc(sizeof(InsertIndexResultData));
789
790         /* now insert the new index tuple */
791         if (*(v.spl_left) != FirstOffsetNumber)
792         {
793                 gistPageAddItem(giststate, r, left, (Item) itup,
794                                                 IndexTupleSize(itup),
795                                                 leftoff, LP_USED, &tmpdentry, &newtup);
796                 leftoff = OffsetNumberNext(leftoff);
797                 ItemPointerSet(&(res->pointerData), lbknum, leftoff);
798                 /* be tidy */
799                 if (tmpdentry.pred != (((char *) itup) + sizeof(IndexTupleData)))
800                         pfree(tmpdentry.pred);
801                 if (itup != newtup)
802                         pfree(newtup);
803         }
804         else
805         {
806                 gistPageAddItem(giststate, r, right, (Item) itup,
807                                                 IndexTupleSize(itup),
808                                                 rightoff, LP_USED, &tmpdentry, &newtup);
809                 rightoff = OffsetNumberNext(rightoff);
810                 ItemPointerSet(&(res->pointerData), rbknum, rightoff);
811                 /* be tidy */
812                 if (tmpdentry.pred != (((char *) itup) + sizeof(IndexTupleData)))
813                         pfree(tmpdentry.pred);
814                 if (itup != newtup)
815                         pfree(newtup);
816         }
817
818         if ((bufblock = BufferGetBlockNumber(buffer)) != GISTP_ROOT)
819                 PageRestoreTempPage(left, p);
820         WriteBuffer(leftbuf);
821         WriteBuffer(rightbuf);
822
823         /*
824          * Okay, the page is split.  We have three things left to do:
825          *
826          * 1)  Adjust any active scans on this index to cope with changes we
827          * introduced in its structure by splitting this page.
828          *
829          * 2)  "Tighten" the bounding box of the pointer to the left page in the
830          * parent node in the tree, if any.  Since we moved a bunch of stuff
831          * off the left page, we expect it to get smaller.      This happens in
832          * the internal insertion routine.
833          *
834          * 3)  Insert a pointer to the right page in the parent.  This may cause
835          * the parent to split.  If it does, we need to repeat steps one and
836          * two for each split node in the tree.
837          */
838
839         /* adjust active scans */
840         gistadjscans(r, GISTOP_SPLIT, bufblock, FirstOffsetNumber);
841
842         tupDesc = r->rd_att;
843
844         ltup = (IndexTuple) index_formtuple(tupDesc,
845                                                                           (Datum *) &(v.spl_ldatum), isnull);
846         rtup = (IndexTuple) index_formtuple(tupDesc,
847                                                                           (Datum *) &(v.spl_rdatum), isnull);
848         pfree(isnull);
849
850         /* set pointers to new child pages in the internal index tuples */
851         ItemPointerSet(&(ltup->t_tid), lbknum, 1);
852         ItemPointerSet(&(rtup->t_tid), rbknum, 1);
853
854         gistintinsert(r, stack, ltup, rtup, giststate);
855
856         pfree(ltup);
857         pfree(rtup);
858
859         return res;
860 }
861
862 /*
863 ** After a split, we need to overwrite the old entry's key in the parent,
864 ** and install install an entry for the new key into the parent.
865 */
866 static void
867 gistintinsert(Relation r,
868                           GISTSTACK *stk,
869                           IndexTuple ltup,      /* new version of entry for old page */
870                           IndexTuple rtup,      /* entry for new page */
871                           GISTSTATE *giststate)
872 {
873         ItemPointerData ltid;
874
875         if (stk == (GISTSTACK *) NULL)
876         {
877                 gistnewroot(giststate, r, ltup, rtup);
878                 return;
879         }
880
881         /* remove old left pointer, insert the 2 new entries */
882         ItemPointerSet(&ltid, stk->gs_blk, stk->gs_child);
883         gistdelete(r, (ItemPointer) &ltid);
884         gistentryinserttwo(r, stk, ltup, rtup, giststate);
885 }
886
887
888 /*
889 ** Insert two entries onto one page, handling a split for either one!
890 */
891 static void
892 gistentryinserttwo(Relation r, GISTSTACK *stk, IndexTuple ltup,
893                                    IndexTuple rtup, GISTSTATE *giststate)
894 {
895         Buffer          b;
896         Page            p;
897         InsertIndexResult res;
898         GISTENTRY       tmpentry;
899         IndexTuple      newtup;
900
901         b = ReadBuffer(r, stk->gs_blk);
902         p = BufferGetPage(b);
903
904         if (gistnospace(p, ltup))
905         {
906                 res = gistSplit(r, b, stk->gs_parent, ltup, giststate);
907                 WriteBuffer(b);                 /* don't forget to release buffer!  -
908                                                                  * 01/31/94 */
909                 pfree(res);
910                 gistdoinsert(r, rtup, giststate);
911         }
912         else
913         {
914                 gistPageAddItem(giststate, r, p, (Item) ltup,
915                                                 IndexTupleSize(ltup), InvalidOffsetNumber,
916                                                 LP_USED, &tmpentry, &newtup);
917                 WriteBuffer(b);
918                 gistAdjustKeys(r, stk->gs_parent, stk->gs_blk, tmpentry.pred,
919                                            tmpentry.bytes, giststate);
920                 /* be tidy */
921                 if (tmpentry.pred != (((char *) ltup) + sizeof(IndexTupleData)))
922                         pfree(tmpentry.pred);
923                 if (ltup != newtup)
924                         pfree(newtup);
925                 gistentryinsert(r, stk, rtup, giststate);
926         }
927 }
928
929
930 /*
931 ** Insert an entry onto a page
932 */
933 static InsertIndexResult
934 gistentryinsert(Relation r, GISTSTACK *stk, IndexTuple tup,
935                                 GISTSTATE *giststate)
936 {
937         Buffer          b;
938         Page            p;
939         InsertIndexResult res;
940         OffsetNumber off;
941         GISTENTRY       tmpentry;
942         IndexTuple      newtup;
943
944         b = ReadBuffer(r, stk->gs_blk);
945         p = BufferGetPage(b);
946
947         if (gistnospace(p, tup))
948         {
949                 res = gistSplit(r, b, stk->gs_parent, tup, giststate);
950                 WriteBuffer(b);                 /* don't forget to release buffer!  -
951                                                                  * 01/31/94 */
952                 return res;
953         }
954         else
955         {
956                 res = (InsertIndexResult) palloc(sizeof(InsertIndexResultData));
957                 off = gistPageAddItem(giststate, r, p, (Item) tup, IndexTupleSize(tup),
958                                            InvalidOffsetNumber, LP_USED, &tmpentry, &newtup);
959                 WriteBuffer(b);
960                 ItemPointerSet(&(res->pointerData), stk->gs_blk, off);
961                 gistAdjustKeys(r, stk->gs_parent, stk->gs_blk, tmpentry.pred,
962                                            tmpentry.bytes, giststate);
963                 /* be tidy */
964                 if (tmpentry.pred != (((char *) tup) + sizeof(IndexTupleData)))
965                         pfree(tmpentry.pred);
966                 if (tup != newtup)
967                         pfree(newtup);
968                 return res;
969         }
970 }
971
972
973 static void
974 gistnewroot(GISTSTATE *giststate, Relation r, IndexTuple lt, IndexTuple rt)
975 {
976         Buffer          b;
977         Page            p;
978         GISTENTRY       tmpentry;
979         IndexTuple      newtup;
980
981         b = ReadBuffer(r, GISTP_ROOT);
982         GISTInitBuffer(b, 0);
983         p = BufferGetPage(b);
984         gistPageAddItem(giststate, r, p, (Item) lt, IndexTupleSize(lt),
985                                         FirstOffsetNumber,
986                                         LP_USED, &tmpentry, &newtup);
987         /* be tidy */
988         if (tmpentry.pred != (((char *) lt) + sizeof(IndexTupleData)))
989                 pfree(tmpentry.pred);
990         if (lt != newtup)
991                 pfree(newtup);
992         gistPageAddItem(giststate, r, p, (Item) rt, IndexTupleSize(rt),
993                                         OffsetNumberNext(FirstOffsetNumber), LP_USED,
994                                         &tmpentry, &newtup);
995         /* be tidy */
996         if (tmpentry.pred != (((char *) rt) + sizeof(IndexTupleData)))
997                 pfree(tmpentry.pred);
998         if (rt != newtup)
999                 pfree(newtup);
1000         WriteBuffer(b);
1001 }
1002
1003 static void
1004 GISTInitBuffer(Buffer b, uint32 f)
1005 {
1006         GISTPageOpaque opaque;
1007         Page            page;
1008         Size            pageSize;
1009
1010         pageSize = BufferGetPageSize(b);
1011
1012         page = BufferGetPage(b);
1013         MemSet(page, 0, (int) pageSize);
1014         PageInit(page, pageSize, sizeof(GISTPageOpaqueData));
1015
1016         opaque = (GISTPageOpaque) PageGetSpecialPointer(page);
1017         opaque->flags = f;
1018 }
1019
1020
1021 /*
1022 ** find entry with lowest penalty
1023 */
1024 static OffsetNumber
1025 gistchoose(Relation r, Page p, IndexTuple it,   /* it has compressed entry */
1026                    GISTSTATE *giststate)
1027 {
1028         OffsetNumber maxoff;
1029         OffsetNumber i;
1030         char       *id;
1031         char       *datum;
1032         float           usize;
1033         OffsetNumber which;
1034         float           which_grow;
1035         GISTENTRY       entry,
1036                                 identry;
1037         int                     size,
1038                                 idsize;
1039
1040         idsize = IndexTupleSize(it) - sizeof(IndexTupleData);
1041         id = ((char *) it) + sizeof(IndexTupleData);
1042         maxoff = PageGetMaxOffsetNumber(p);
1043         which_grow = -1.0;
1044         which = -1;
1045
1046         gistdentryinit(giststate, &identry, id, (Relation) NULL, (Page) NULL,
1047                                    (OffsetNumber) 0, idsize, FALSE);
1048
1049         for (i = FirstOffsetNumber; i <= maxoff; i = OffsetNumberNext(i))
1050         {
1051                 datum = (char *) PageGetItem(p, PageGetItemId(p, i));
1052                 size = IndexTupleSize(datum) - sizeof(IndexTupleData);
1053                 datum += sizeof(IndexTupleData);
1054                 gistdentryinit(giststate, &entry, datum, r, p, i, size, FALSE);
1055                 (*fmgr_faddr(&giststate->penaltyFn)) (&entry, &identry, &usize);
1056                 if (which_grow < 0 || usize < which_grow)
1057                 {
1058                         which = i;
1059                         which_grow = usize;
1060                         if (which_grow == 0)
1061                                 break;
1062                 }
1063                 if (entry.pred != datum)
1064                         pfree(entry.pred);
1065         }
1066         if (identry.pred != id)
1067                 pfree(identry.pred);
1068
1069         return which;
1070 }
1071
1072 static int
1073 gistnospace(Page p, IndexTuple it)
1074 {
1075         return PageGetFreeSpace(p) < IndexTupleSize(it);
1076 }
1077
1078 void
1079 gistfreestack(GISTSTACK *s)
1080 {
1081         GISTSTACK  *p;
1082
1083         while (s != (GISTSTACK *) NULL)
1084         {
1085                 p = s->gs_parent;
1086                 pfree(s);
1087                 s = p;
1088         }
1089 }
1090
1091
1092 /*
1093 ** remove an entry from a page
1094 */
1095 void
1096 gistdelete(Relation r, ItemPointer tid)
1097 {
1098         BlockNumber blkno;
1099         OffsetNumber offnum;
1100         Buffer          buf;
1101         Page            page;
1102
1103         /*
1104          * Notes in ExecUtils:ExecOpenIndices() Also note that only vacuum
1105          * deletes index tuples now...
1106          *
1107          * RelationSetLockForWrite(r);
1108          */
1109
1110         blkno = ItemPointerGetBlockNumber(tid);
1111         offnum = ItemPointerGetOffsetNumber(tid);
1112
1113         /* adjust any scans that will be affected by this deletion */
1114         gistadjscans(r, GISTOP_DEL, blkno, offnum);
1115
1116         /* delete the index tuple */
1117         buf = ReadBuffer(r, blkno);
1118         page = BufferGetPage(buf);
1119
1120         PageIndexTupleDelete(page, offnum);
1121
1122         WriteBuffer(buf);
1123
1124 }
1125
1126 void
1127 initGISTstate(GISTSTATE *giststate, Relation index)
1128 {
1129         RegProcedure consistent_proc,
1130                                 union_proc,
1131                                 compress_proc,
1132                                 decompress_proc;
1133         RegProcedure penalty_proc,
1134                                 picksplit_proc,
1135                                 equal_proc;
1136         HeapTuple       htup;
1137         Form_pg_index itupform;
1138
1139         consistent_proc = index_getprocid(index, 1, GIST_CONSISTENT_PROC);
1140         union_proc = index_getprocid(index, 1, GIST_UNION_PROC);
1141         compress_proc = index_getprocid(index, 1, GIST_COMPRESS_PROC);
1142         decompress_proc = index_getprocid(index, 1, GIST_DECOMPRESS_PROC);
1143         penalty_proc = index_getprocid(index, 1, GIST_PENALTY_PROC);
1144         picksplit_proc = index_getprocid(index, 1, GIST_PICKSPLIT_PROC);
1145         equal_proc = index_getprocid(index, 1, GIST_EQUAL_PROC);
1146         fmgr_info(consistent_proc, &giststate->consistentFn);
1147         fmgr_info(union_proc, &giststate->unionFn);
1148         fmgr_info(compress_proc, &giststate->compressFn);
1149         fmgr_info(decompress_proc, &giststate->decompressFn);
1150         fmgr_info(penalty_proc, &giststate->penaltyFn);
1151         fmgr_info(picksplit_proc, &giststate->picksplitFn);
1152         fmgr_info(equal_proc, &giststate->equalFn);
1153
1154         /* see if key type is different from type of attribute being indexed */
1155         htup = SearchSysCacheTuple(INDEXRELID,
1156                                                            ObjectIdGetDatum(RelationGetRelid(index)),
1157                                                            0, 0, 0);
1158         itupform = (Form_pg_index) GETSTRUCT(htup);
1159         if (!HeapTupleIsValid(htup))
1160                 elog(ERROR, "initGISTstate: index %u not found",
1161                          RelationGetRelid(index));
1162         giststate->haskeytype = itupform->indhaskeytype;
1163         if (giststate->haskeytype)
1164         {
1165                 /* key type is different -- is it byval? */
1166                 htup = SearchSysCacheTuple(ATTNUM,
1167                                                                    ObjectIdGetDatum(itupform->indexrelid),
1168                                                                    UInt16GetDatum(FirstOffsetNumber),
1169                                                                    0, 0);
1170                 if (!HeapTupleIsValid(htup))
1171                 {
1172                         elog(ERROR, "initGISTstate: no attribute tuple %u %d",
1173                                  itupform->indexrelid, FirstOffsetNumber);
1174                         return;
1175                 }
1176                 giststate->keytypbyval = (((Form_pg_attribute) htup)->attbyval);
1177         }
1178         else
1179                 giststate->keytypbyval = FALSE;
1180         return;
1181 }
1182
1183
1184 /*
1185 ** Given an IndexTuple to be inserted on a page, this routine replaces
1186 ** the key with another key, which may involve generating a new IndexTuple
1187 ** if the sizes don't match
1188 */
1189 static IndexTuple
1190 gist_tuple_replacekey(Relation r, GISTENTRY entry, IndexTuple t)
1191 {
1192         char       *datum = (((char *) t) + sizeof(IndexTupleData));
1193
1194         /* if new entry fits in index tuple, copy it in */
1195         if (entry.bytes < IndexTupleSize(t) - sizeof(IndexTupleData))
1196         {
1197                 memcpy(datum, entry.pred, entry.bytes);
1198                 /* clear out old size */
1199                 t->t_info &= 0xe000;
1200                 /* or in new size */
1201                 t->t_info |= MAXALIGN(entry.bytes + sizeof(IndexTupleData));
1202
1203                 return t;
1204         }
1205         else
1206         {
1207                 /* generate a new index tuple for the compressed entry */
1208                 TupleDesc       tupDesc = r->rd_att;
1209                 IndexTuple      newtup;
1210                 char       *isnull;
1211                 int                     blank;
1212
1213                 isnull = (char *) palloc(r->rd_rel->relnatts);
1214                 for (blank = 0; blank < r->rd_rel->relnatts; blank++)
1215                         isnull[blank] = ' ';
1216                 newtup = (IndexTuple) index_formtuple(tupDesc,
1217                                                                                           (Datum *) &(entry.pred),
1218                                                                                           isnull);
1219                 newtup->t_tid = t->t_tid;
1220                 pfree(isnull);
1221                 return newtup;
1222         }
1223 }
1224
1225
1226 /*
1227 ** initialize a GiST entry with a decompressed version of pred
1228 */
1229 void
1230 gistdentryinit(GISTSTATE *giststate, GISTENTRY *e, char *pr, Relation r,
1231                            Page pg, OffsetNumber o, int b, bool l)
1232 {
1233         GISTENTRY  *dep;
1234
1235         gistentryinit(*e, pr, r, pg, o, b, l);
1236         if (giststate->haskeytype)
1237         {
1238                 dep = (GISTENTRY *) ((*fmgr_faddr(&giststate->decompressFn)) (e));
1239                 gistentryinit(*e, dep->pred, dep->rel, dep->page, dep->offset, dep->bytes,
1240                                           dep->leafkey);
1241                 if (dep != e)
1242                         pfree(dep);
1243         }
1244 }
1245
1246
1247 /*
1248 ** initialize a GiST entry with a compressed version of pred
1249 */
1250 static void
1251 gistcentryinit(GISTSTATE *giststate, GISTENTRY *e, char *pr, Relation r,
1252                            Page pg, OffsetNumber o, int b, bool l)
1253 {
1254         GISTENTRY  *cep;
1255
1256         gistentryinit(*e, pr, r, pg, o, b, l);
1257         if (giststate->haskeytype)
1258         {
1259                 cep = (GISTENTRY *) ((*fmgr_faddr(&giststate->compressFn)) (e));
1260                 gistentryinit(*e, cep->pred, cep->rel, cep->page, cep->offset, cep->bytes,
1261                                           cep->leafkey);
1262                 if (cep != e)
1263                         pfree(cep);
1264         }
1265 }
1266
1267
1268
1269 #ifdef GISTDEBUG
1270
1271 /*
1272 ** sloppy debugging support routine, requires recompilation with appropriate
1273 ** "out" method for the index keys.  Could be fixed to find that info
1274 ** in the catalogs...
1275 */
1276 void
1277 _gistdump(Relation r)
1278 {
1279         Buffer          buf;
1280         Page            page;
1281         OffsetNumber offnum,
1282                                 maxoff;
1283         BlockNumber blkno;
1284         BlockNumber nblocks;
1285         GISTPageOpaque po;
1286         IndexTuple      itup;
1287         BlockNumber itblkno;
1288         OffsetNumber itoffno;
1289         char       *datum;
1290         char       *itkey;
1291
1292         nblocks = RelationGetNumberOfBlocks(r);
1293         for (blkno = 0; blkno < nblocks; blkno++)
1294         {
1295                 buf = ReadBuffer(r, blkno);
1296                 page = BufferGetPage(buf);
1297                 po = (GISTPageOpaque) PageGetSpecialPointer(page);
1298                 maxoff = PageGetMaxOffsetNumber(page);
1299                 printf("Page %d maxoff %d <%s>\n", blkno, maxoff,
1300                            (po->flags & F_LEAF ? "LEAF" : "INTERNAL"));
1301
1302                 if (PageIsEmpty(page))
1303                 {
1304                         ReleaseBuffer(buf);
1305                         continue;
1306                 }
1307
1308                 for (offnum = FirstOffsetNumber;
1309                          offnum <= maxoff;
1310                          offnum = OffsetNumberNext(offnum))
1311                 {
1312                         itup = (IndexTuple) PageGetItem(page, PageGetItemId(page, offnum));
1313                         itblkno = ItemPointerGetBlockNumber(&(itup->t_tid));
1314                         itoffno = ItemPointerGetOffsetNumber(&(itup->t_tid));
1315                         datum = ((char *) itup);
1316                         datum += sizeof(IndexTupleData);
1317                         /* get out function for type of key, and out it! */
1318                         itkey = (char *) int_range_out((INTRANGE *) datum);
1319                         /* itkey = " unable to print"; */
1320                         printf("\t[%d] size %d heap <%d,%d> key:%s\n",
1321                                    offnum, IndexTupleSize(itup), itblkno, itoffno, itkey);
1322                         pfree(itkey);
1323                 }
1324
1325                 ReleaseBuffer(buf);
1326         }
1327 }
1328
1329 static char *
1330 int_range_out(INTRANGE *r)
1331 {
1332         char       *result;
1333
1334         if (r == NULL)
1335                 return NULL;
1336         result = (char *) palloc(80);
1337         snprintf(result, 80, "[%d,%d): %d", r->lower, r->upper, r->flag);
1338
1339         return result;
1340 }
1341
1342 #endif   /* defined GISTDEBUG */