]> granicus.if.org Git - postgresql/blob - src/include/access/gist_private.h
Minor cleanup of GiST code, for readability.
[postgresql] / src / include / access / gist_private.h
1 /*-------------------------------------------------------------------------
2  *
3  * gist_private.h
4  *        private declarations for GiST -- declarations related to the
5  *        internal implementation of GiST, not the public API
6  *
7  * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  * src/include/access/gist_private.h
11  *
12  *-------------------------------------------------------------------------
13  */
14 #ifndef GIST_PRIVATE_H
15 #define GIST_PRIVATE_H
16
17 #include "access/gist.h"
18 #include "access/itup.h"
19 #include "access/xlogreader.h"
20 #include "fmgr.h"
21 #include "lib/pairingheap.h"
22 #include "storage/bufmgr.h"
23 #include "storage/buffile.h"
24 #include "utils/hsearch.h"
25
26 /*
27  * Maximum number of "halves" a page can be split into in one operation.
28  * Typically a split produces 2 halves, but can be more if keys have very
29  * different lengths, or when inserting multiple keys in one operation (as
30  * when inserting downlinks to an internal node).  There is no theoretical
31  * limit on this, but in practice if you get more than a handful page halves
32  * in one split, there's something wrong with the opclass implementation.
33  * GIST_MAX_SPLIT_PAGES is an arbitrary limit on that, used to size some
34  * local arrays used during split.  Note that there is also a limit on the
35  * number of buffers that can be held locked at a time, MAX_SIMUL_LWLOCKS,
36  * so if you raise this higher than that limit, you'll just get a different
37  * error.
38  */
39 #define GIST_MAX_SPLIT_PAGES            75
40
41 /* Buffer lock modes */
42 #define GIST_SHARE      BUFFER_LOCK_SHARE
43 #define GIST_EXCLUSIVE  BUFFER_LOCK_EXCLUSIVE
44 #define GIST_UNLOCK BUFFER_LOCK_UNLOCK
45
46 typedef struct
47 {
48         BlockNumber prev;
49         uint32          freespace;
50         char            tupledata[FLEXIBLE_ARRAY_MEMBER];
51 } GISTNodeBufferPage;
52
53 #define BUFFER_PAGE_DATA_OFFSET MAXALIGN(offsetof(GISTNodeBufferPage, tupledata))
54 /* Returns free space in node buffer page */
55 #define PAGE_FREE_SPACE(nbp) (nbp->freespace)
56 /* Checks if node buffer page is empty */
57 #define PAGE_IS_EMPTY(nbp) (nbp->freespace == BLCKSZ - BUFFER_PAGE_DATA_OFFSET)
58 /* Checks if node buffers page don't contain sufficient space for index tuple */
59 #define PAGE_NO_SPACE(nbp, itup) (PAGE_FREE_SPACE(nbp) < \
60                                                                                 MAXALIGN(IndexTupleSize(itup)))
61
62 /*
63  * GISTSTATE: information needed for any GiST index operation
64  *
65  * This struct retains call info for the index's opclass-specific support
66  * functions (per index column), plus the index's tuple descriptor.
67  *
68  * scanCxt holds the GISTSTATE itself as well as any data that lives for the
69  * lifetime of the index operation.  We pass this to the support functions
70  * via fn_mcxt, so that they can store scan-lifespan data in it.  The
71  * functions are invoked in tempCxt, which is typically short-lifespan
72  * (that is, it's reset after each tuple).  However, tempCxt can be the same
73  * as scanCxt if we're not bothering with per-tuple context resets.
74  */
75 typedef struct GISTSTATE
76 {
77         MemoryContext scanCxt;          /* context for scan-lifespan data */
78         MemoryContext tempCxt;          /* short-term context for calling functions */
79
80         TupleDesc       tupdesc;                /* index's tuple descriptor */
81
82         FmgrInfo        consistentFn[INDEX_MAX_KEYS];
83         FmgrInfo        unionFn[INDEX_MAX_KEYS];
84         FmgrInfo        compressFn[INDEX_MAX_KEYS];
85         FmgrInfo        decompressFn[INDEX_MAX_KEYS];
86         FmgrInfo        penaltyFn[INDEX_MAX_KEYS];
87         FmgrInfo        picksplitFn[INDEX_MAX_KEYS];
88         FmgrInfo        equalFn[INDEX_MAX_KEYS];
89         FmgrInfo        distanceFn[INDEX_MAX_KEYS];
90
91         /* Collations to pass to the support functions */
92         Oid                     supportCollation[INDEX_MAX_KEYS];
93 } GISTSTATE;
94
95
96 /*
97  * During a GiST index search, we must maintain a queue of unvisited items,
98  * which can be either individual heap tuples or whole index pages.  If it
99  * is an ordered search, the unvisited items should be visited in distance
100  * order.  Unvisited items at the same distance should be visited in
101  * depth-first order, that is heap items first, then lower index pages, then
102  * upper index pages; this rule avoids doing extra work during a search that
103  * ends early due to LIMIT.
104  *
105  * To perform an ordered search, we use an RBTree to manage the distance-order
106  * queue.  Each GISTSearchTreeItem stores all unvisited items of the same
107  * distance; they are GISTSearchItems chained together via their next fields.
108  *
109  * In a non-ordered search (no order-by operators), the RBTree degenerates
110  * to a single item, which we use as a queue of unvisited index pages only.
111  * In this case matched heap items from the current index leaf page are
112  * remembered in GISTScanOpaqueData.pageData[] and returned directly from
113  * there, instead of building a separate GISTSearchItem for each one.
114  */
115
116 /* Individual heap tuple to be visited */
117 typedef struct GISTSearchHeapItem
118 {
119         ItemPointerData heapPtr;
120         bool            recheck;                /* T if quals must be rechecked */
121 } GISTSearchHeapItem;
122
123 /* Unvisited item, either index page or heap tuple */
124 typedef struct GISTSearchItem
125 {
126         pairingheap_node phNode;
127         BlockNumber blkno;                      /* index page number, or InvalidBlockNumber */
128         union
129         {
130                 GistNSN         parentlsn;      /* parent page's LSN, if index page */
131                 /* we must store parentlsn to detect whether a split occurred */
132                 GISTSearchHeapItem heap;        /* heap info, if heap tuple */
133         }                       data;
134         double          distances[FLEXIBLE_ARRAY_MEMBER];               /* numberOfOrderBys
135                                                                                                                  * entries */
136 } GISTSearchItem;
137
138 #define GISTSearchItemIsHeap(item)      ((item).blkno == InvalidBlockNumber)
139
140 #define SizeOfGISTSearchItem(n_distances) (offsetof(GISTSearchItem, distances) + sizeof(double) * (n_distances))
141
142 /*
143  * GISTScanOpaqueData: private state for a scan of a GiST index
144  */
145 typedef struct GISTScanOpaqueData
146 {
147         GISTSTATE  *giststate;          /* index information, see above */
148         pairingheap *queue;                     /* queue of unvisited items */
149         MemoryContext queueCxt;         /* context holding the queue */
150         bool            qual_ok;                /* false if qual can never be satisfied */
151         bool            firstCall;              /* true until first gistgettuple call */
152
153         /* pre-allocated workspace arrays */
154         double     *distances;          /* output area for gistindex_keytest */
155
156         /* In a non-ordered search, returnable heap items are stored here: */
157         GISTSearchHeapItem pageData[BLCKSZ / sizeof(IndexTupleData)];
158         OffsetNumber nPageData;         /* number of valid items in array */
159         OffsetNumber curPageData;       /* next item to return */
160 } GISTScanOpaqueData;
161
162 typedef GISTScanOpaqueData *GISTScanOpaque;
163
164
165 /* XLog stuff */
166
167 #define XLOG_GIST_PAGE_UPDATE           0x00
168  /* #define XLOG_GIST_NEW_ROOT                   0x20 */        /* not used anymore */
169 #define XLOG_GIST_PAGE_SPLIT            0x30
170  /* #define XLOG_GIST_INSERT_COMPLETE    0x40 */        /* not used anymore */
171 #define XLOG_GIST_CREATE_INDEX          0x50
172  /* #define XLOG_GIST_PAGE_DELETE                0x60 */        /* not used anymore */
173
174 /*
175  * Backup Blk 0: updated page.
176  * Backup Blk 1: If this operation completes a page split, by inserting a
177  *                               downlink for the split page, the left half of the split
178  */
179 typedef struct gistxlogPageUpdate
180 {
181         /* number of deleted offsets */
182         uint16          ntodelete;
183         uint16          ntoinsert;
184
185         /*
186          * In payload of blk 0 : 1. todelete OffsetNumbers 2. tuples to insert
187          */
188 } gistxlogPageUpdate;
189
190 /*
191  * Backup Blk 0: If this operation completes a page split, by inserting a
192  *                               downlink for the split page, the left half of the split
193  * Backup Blk 1 - npage: split pages (1 is the original page)
194  */
195 typedef struct gistxlogPageSplit
196 {
197         BlockNumber origrlink;          /* rightlink of the page before split */
198         GistNSN         orignsn;                /* NSN of the page before split */
199         bool            origleaf;               /* was splitted page a leaf page? */
200
201         uint16          npage;                  /* # of pages in the split */
202         bool            markfollowright;        /* set F_FOLLOW_RIGHT flags */
203
204         /*
205          * follow: 1. gistxlogPage and array of IndexTupleData per page
206          */
207 } gistxlogPageSplit;
208
209 typedef struct gistxlogPage
210 {
211         BlockNumber blkno;
212         int                     num;                    /* number of index tuples following */
213 } gistxlogPage;
214
215 /* SplitedPageLayout - gistSplit function result */
216 typedef struct SplitedPageLayout
217 {
218         gistxlogPage block;
219         IndexTupleData *list;
220         int                     lenlist;
221         IndexTuple      itup;                   /* union key for page */
222         Page            page;                   /* to operate */
223         Buffer          buffer;                 /* to write after all proceed */
224
225         struct SplitedPageLayout *next;
226 } SplitedPageLayout;
227
228 /*
229  * GISTInsertStack used for locking buffers and transfer arguments during
230  * insertion
231  */
232 typedef struct GISTInsertStack
233 {
234         /* current page */
235         BlockNumber blkno;
236         Buffer          buffer;
237         Page            page;
238
239         /*
240          * log sequence number from page->lsn to recognize page update and compare
241          * it with page's nsn to recognize page split
242          */
243         GistNSN         lsn;
244
245         /* offset of the downlink in the parent page, that points to this page */
246         OffsetNumber downlinkoffnum;
247
248         /* pointer to parent */
249         struct GISTInsertStack *parent;
250 } GISTInsertStack;
251
252 /* Working state and results for multi-column split logic in gistsplit.c */
253 typedef struct GistSplitVector
254 {
255         GIST_SPLITVEC splitVector;      /* passed to/from user PickSplit method */
256
257         Datum           spl_lattr[INDEX_MAX_KEYS];              /* Union of subkeys in
258                                                                                                  * splitVector.spl_left */
259         bool            spl_lisnull[INDEX_MAX_KEYS];
260
261         Datum           spl_rattr[INDEX_MAX_KEYS];              /* Union of subkeys in
262                                                                                                  * splitVector.spl_right */
263         bool            spl_risnull[INDEX_MAX_KEYS];
264
265         bool       *spl_dontcare;       /* flags tuples which could go to either side
266                                                                  * of the split for zero penalty */
267 } GistSplitVector;
268
269 typedef struct
270 {
271         Relation        r;
272         Size            freespace;              /* free space to be left */
273
274         GISTInsertStack *stack;
275 } GISTInsertState;
276
277 /* root page of a gist index */
278 #define GIST_ROOT_BLKNO                         0
279
280 /*
281  * Before PostgreSQL 9.1, we used rely on so-called "invalid tuples" on inner
282  * pages to finish crash recovery of incomplete page splits. If a crash
283  * happened in the middle of a page split, so that the downlink pointers were
284  * not yet inserted, crash recovery inserted a special downlink pointer. The
285  * semantics of an invalid tuple was that it if you encounter one in a scan,
286  * it must always be followed, because we don't know if the tuples on the
287  * child page match or not.
288  *
289  * We no longer create such invalid tuples, we now mark the left-half of such
290  * an incomplete split with the F_FOLLOW_RIGHT flag instead, and finish the
291  * split properly the next time we need to insert on that page. To retain
292  * on-disk compatibility for the sake of pg_upgrade, we still store 0xffff as
293  * the offset number of all inner tuples. If we encounter any invalid tuples
294  * with 0xfffe during insertion, we throw an error, though scans still handle
295  * them. You should only encounter invalid tuples if you pg_upgrade a pre-9.1
296  * gist index which already has invalid tuples in it because of a crash. That
297  * should be rare, and you are recommended to REINDEX anyway if you have any
298  * invalid tuples in an index, so throwing an error is as far as we go with
299  * supporting that.
300  */
301 #define TUPLE_IS_VALID          0xffff
302 #define TUPLE_IS_INVALID        0xfffe
303
304 #define  GistTupleIsInvalid(itup)       ( ItemPointerGetOffsetNumber( &((itup)->t_tid) ) == TUPLE_IS_INVALID )
305 #define  GistTupleSetValid(itup)        ItemPointerSetOffsetNumber( &((itup)->t_tid), TUPLE_IS_VALID )
306
307
308
309
310 /*
311  * A buffer attached to an internal node, used when building an index in
312  * buffering mode.
313  */
314 typedef struct
315 {
316         BlockNumber nodeBlocknum;       /* index block # this buffer is for */
317         int32           blocksCount;    /* current # of blocks occupied by buffer */
318
319         BlockNumber pageBlocknum;       /* temporary file block # */
320         GISTNodeBufferPage *pageBuffer;         /* in-memory buffer page */
321
322         /* is this buffer queued for emptying? */
323         bool            queuedForEmptying;
324
325         /* is this a temporary copy, not in the hash table? */
326         bool            isTemp;
327
328         int                     level;                  /* 0 == leaf */
329 } GISTNodeBuffer;
330
331 /*
332  * Does specified level have buffers? (Beware of multiple evaluation of
333  * arguments.)
334  */
335 #define LEVEL_HAS_BUFFERS(nlevel, gfbb) \
336         ((nlevel) != 0 && (nlevel) % (gfbb)->levelStep == 0 && \
337          (nlevel) != (gfbb)->rootlevel)
338
339 /* Is specified buffer at least half-filled (should be queued for emptying)? */
340 #define BUFFER_HALF_FILLED(nodeBuffer, gfbb) \
341         ((nodeBuffer)->blocksCount > (gfbb)->pagesPerBuffer / 2)
342
343 /*
344  * Is specified buffer full? Our buffers can actually grow indefinitely,
345  * beyond the "maximum" size, so this just means whether the buffer has grown
346  * beyond the nominal maximum size.
347  */
348 #define BUFFER_OVERFLOWED(nodeBuffer, gfbb) \
349         ((nodeBuffer)->blocksCount > (gfbb)->pagesPerBuffer)
350
351 /*
352  * Data structure with general information about build buffers.
353  */
354 typedef struct GISTBuildBuffers
355 {
356         /* Persistent memory context for the buffers and metadata. */
357         MemoryContext context;
358
359         BufFile    *pfile;                      /* Temporary file to store buffers in */
360         long            nFileBlocks;    /* Current size of the temporary file */
361
362         /*
363          * resizable array of free blocks.
364          */
365         long       *freeBlocks;
366         int                     nFreeBlocks;    /* # of currently free blocks in the array */
367         int                     freeBlocksLen;  /* current allocated length of the array */
368
369         /* Hash for buffers by block number */
370         HTAB       *nodeBuffersTab;
371
372         /* List of buffers scheduled for emptying */
373         List       *bufferEmptyingQueue;
374
375         /*
376          * Parameters to the buffering build algorithm. levelStep determines which
377          * levels in the tree have buffers, and pagesPerBuffer determines how
378          * large each buffer is.
379          */
380         int                     levelStep;
381         int                     pagesPerBuffer;
382
383         /* Array of lists of buffers on each level, for final emptying */
384         List      **buffersOnLevels;
385         int                     buffersOnLevelsLen;
386
387         /*
388          * Dynamically-sized array of buffers that currently have their last page
389          * loaded in main memory.
390          */
391         GISTNodeBuffer **loadedBuffers;
392         int                     loadedBuffersCount;             /* # of entries in loadedBuffers */
393         int                     loadedBuffersLen;               /* allocated size of loadedBuffers */
394
395         /* Level of the current root node (= height of the index tree - 1) */
396         int                     rootlevel;
397 } GISTBuildBuffers;
398
399 /*
400  * Storage type for GiST's reloptions
401  */
402 typedef struct GiSTOptions
403 {
404         int32           vl_len_;                /* varlena header (do not touch directly!) */
405         int                     fillfactor;             /* page fill factor in percent (0..100) */
406         int                     bufferingModeOffset;    /* use buffering build? */
407 } GiSTOptions;
408
409 /* gist.c */
410 extern Datum gistbuildempty(PG_FUNCTION_ARGS);
411 extern Datum gistinsert(PG_FUNCTION_ARGS);
412 extern MemoryContext createTempGistContext(void);
413 extern GISTSTATE *initGISTstate(Relation index);
414 extern void freeGISTstate(GISTSTATE *giststate);
415 extern void gistdoinsert(Relation r,
416                          IndexTuple itup,
417                          Size freespace,
418                          GISTSTATE *GISTstate);
419
420 /* A List of these is returned from gistplacetopage() in *splitinfo */
421 typedef struct
422 {
423         Buffer          buf;                    /* the split page "half" */
424         IndexTuple      downlink;               /* downlink for this half. */
425 } GISTPageSplitInfo;
426
427 extern bool gistplacetopage(Relation rel, Size freespace, GISTSTATE *giststate,
428                                 Buffer buffer,
429                                 IndexTuple *itup, int ntup,
430                                 OffsetNumber oldoffnum, BlockNumber *newblkno,
431                                 Buffer leftchildbuf,
432                                 List **splitinfo,
433                                 bool markleftchild);
434
435 extern SplitedPageLayout *gistSplit(Relation r, Page page, IndexTuple *itup,
436                   int len, GISTSTATE *giststate);
437
438 /* gistxlog.c */
439 extern void gist_redo(XLogReaderState *record);
440 extern void gist_desc(StringInfo buf, XLogReaderState *record);
441 extern const char *gist_identify(uint8 info);
442 extern void gist_xlog_startup(void);
443 extern void gist_xlog_cleanup(void);
444
445 extern XLogRecPtr gistXLogUpdate(RelFileNode node, Buffer buffer,
446                            OffsetNumber *todelete, int ntodelete,
447                            IndexTuple *itup, int ntup,
448                            Buffer leftchild);
449
450 extern XLogRecPtr gistXLogSplit(RelFileNode node,
451                           BlockNumber blkno, bool page_is_leaf,
452                           SplitedPageLayout *dist,
453                           BlockNumber origrlink, GistNSN oldnsn,
454                           Buffer leftchild, bool markfollowright);
455
456 /* gistget.c */
457 extern Datum gistgettuple(PG_FUNCTION_ARGS);
458 extern Datum gistgetbitmap(PG_FUNCTION_ARGS);
459
460 /* gistutil.c */
461
462 #define GiSTPageSize   \
463         ( BLCKSZ - SizeOfPageHeaderData - MAXALIGN(sizeof(GISTPageOpaqueData)) )
464
465 #define GIST_MIN_FILLFACTOR                     10
466 #define GIST_DEFAULT_FILLFACTOR         90
467
468 extern Datum gistoptions(PG_FUNCTION_ARGS);
469 extern bool gistfitpage(IndexTuple *itvec, int len);
470 extern bool gistnospace(Page page, IndexTuple *itvec, int len, OffsetNumber todelete, Size freespace);
471 extern void gistcheckpage(Relation rel, Buffer buf);
472 extern Buffer gistNewBuffer(Relation r);
473 extern void gistfillbuffer(Page page, IndexTuple *itup, int len,
474                            OffsetNumber off);
475 extern IndexTuple *gistextractpage(Page page, int *len /* out */ );
476 extern IndexTuple *gistjoinvector(
477                            IndexTuple *itvec, int *len,
478                            IndexTuple *additvec, int addlen);
479 extern IndexTupleData *gistfillitupvec(IndexTuple *vec, int veclen, int *memlen);
480
481 extern IndexTuple gistunion(Relation r, IndexTuple *itvec,
482                   int len, GISTSTATE *giststate);
483 extern IndexTuple gistgetadjusted(Relation r,
484                                 IndexTuple oldtup,
485                                 IndexTuple addtup,
486                                 GISTSTATE *giststate);
487 extern IndexTuple gistFormTuple(GISTSTATE *giststate,
488                           Relation r, Datum *attdata, bool *isnull, bool isleaf);
489
490 extern OffsetNumber gistchoose(Relation r, Page p,
491                    IndexTuple it,
492                    GISTSTATE *giststate);
493
494 extern void GISTInitBuffer(Buffer b, uint32 f);
495 extern void gistdentryinit(GISTSTATE *giststate, int nkey, GISTENTRY *e,
496                            Datum k, Relation r, Page pg, OffsetNumber o,
497                            bool l, bool isNull);
498
499 extern float gistpenalty(GISTSTATE *giststate, int attno,
500                         GISTENTRY *key1, bool isNull1,
501                         GISTENTRY *key2, bool isNull2);
502 extern void gistMakeUnionItVec(GISTSTATE *giststate, IndexTuple *itvec, int len,
503                                    Datum *attr, bool *isnull);
504 extern bool gistKeyIsEQ(GISTSTATE *giststate, int attno, Datum a, Datum b);
505 extern void gistDeCompressAtt(GISTSTATE *giststate, Relation r, IndexTuple tuple, Page p,
506                                   OffsetNumber o, GISTENTRY *attdata, bool *isnull);
507
508 extern void gistMakeUnionKey(GISTSTATE *giststate, int attno,
509                                  GISTENTRY *entry1, bool isnull1,
510                                  GISTENTRY *entry2, bool isnull2,
511                                  Datum *dst, bool *dstisnull);
512
513 extern XLogRecPtr gistGetFakeLSN(Relation rel);
514
515 /* gistvacuum.c */
516 extern Datum gistbulkdelete(PG_FUNCTION_ARGS);
517 extern Datum gistvacuumcleanup(PG_FUNCTION_ARGS);
518
519 /* gistsplit.c */
520 extern void gistSplitByKey(Relation r, Page page, IndexTuple *itup,
521                            int len, GISTSTATE *giststate,
522                            GistSplitVector *v,
523                            int attno);
524
525 /* gistbuild.c */
526 extern Datum gistbuild(PG_FUNCTION_ARGS);
527 extern void gistValidateBufferingOption(char *value);
528
529 /* gistbuildbuffers.c */
530 extern GISTBuildBuffers *gistInitBuildBuffers(int pagesPerBuffer, int levelStep,
531                                          int maxLevel);
532 extern GISTNodeBuffer *gistGetNodeBuffer(GISTBuildBuffers *gfbb,
533                                   GISTSTATE *giststate,
534                                   BlockNumber blkno, int level);
535 extern void gistPushItupToNodeBuffer(GISTBuildBuffers *gfbb,
536                                                  GISTNodeBuffer *nodeBuffer, IndexTuple item);
537 extern bool gistPopItupFromNodeBuffer(GISTBuildBuffers *gfbb,
538                                                   GISTNodeBuffer *nodeBuffer, IndexTuple *item);
539 extern void gistFreeBuildBuffers(GISTBuildBuffers *gfbb);
540 extern void gistRelocateBuildBuffersOnSplit(GISTBuildBuffers *gfbb,
541                                                                 GISTSTATE *giststate, Relation r,
542                                                                 int level, Buffer buffer,
543                                                                 List *splitinfo);
544 extern void gistUnloadNodeBuffers(GISTBuildBuffers *gfbb);
545
546 #endif   /* GIST_PRIVATE_H */