3 #include "access/genam.h"
4 #include "access/gin.h"
5 #if PG_VERSION_NUM >= 90400
6 #include "utils/snapmgr.h"
8 #if PG_VERSION_NUM >= 90100
9 #include "access/gin_private.h"
11 #include "access/gist.h"
12 #include "access/gist_private.h"
13 #include "access/gistscan.h"
14 #if PG_VERSION_NUM >= 90200
15 #include "access/spgist_private.h"
16 #include "access/spgist.h"
17 #include "utils/datum.h"
19 #include "access/heapam.h"
20 #include "catalog/index.h"
21 #if PG_VERSION_NUM >= 90600
22 #include <catalog/pg_am.h>
24 #include "miscadmin.h"
25 #include "storage/lmgr.h"
26 #include "catalog/namespace.h"
27 #if PG_VERSION_NUM >= 80300
28 #include <tsearch/ts_utils.h>
30 #if PG_VERSION_NUM >= 100000
31 #include <utils/regproc.h>
32 #include <utils/varlena.h>
34 #include <utils/tqual.h>
35 #include "utils/builtins.h"
36 #include "utils/lsyscache.h"
37 #include "utils/datum.h"
38 #include "utils/fmgroids.h"
41 #include <access/heapam.h>
42 #include <catalog/pg_type.h>
43 #include <access/relscan.h>
46 #define PAGESIZE (BLCKSZ - MAXALIGN(sizeof(PageHeaderData) + sizeof(ItemIdData)))
49 #define PG_NARGS() (fcinfo->nargs)
52 #if PG_VERSION_NUM >= 90600
54 #define ISNOTNULL false
55 #define heap_formtuple heap_form_tuple
63 char *out=palloc(VARSIZE(in));
65 memcpy(out, VARDATA(in), VARSIZE(in)-VARHDRSZ);
66 out[ VARSIZE(in)-VARHDRSZ ] ='\0';
77 static Relation checkOpenedRelation(Relation r, Oid PgAmOid);
79 #ifdef PG_MODULE_MAGIC
85 gist_index_open(RangeVar *relvar) {
86 #if PG_VERSION_NUM < 90200
87 Oid relOid = RangeVarGetRelid(relvar, false);
89 Oid relOid = RangeVarGetRelid(relvar, NoLock, false);
91 return checkOpenedRelation(
92 index_open(relOid, AccessExclusiveLock), GIST_AM_OID);
95 #define gist_index_close(r) index_close((r), AccessExclusiveLock)
98 gin_index_open(RangeVar *relvar) {
99 #if PG_VERSION_NUM < 90200
100 Oid relOid = RangeVarGetRelid(relvar, false);
102 Oid relOid = RangeVarGetRelid(relvar, NoLock, false);
104 return checkOpenedRelation(
105 index_open(relOid, AccessShareLock), GIN_AM_OID);
108 #define gin_index_close(r) index_close((r), AccessShareLock)
113 gist_index_open(RangeVar *relvar) {
114 Relation rel = index_openrv(relvar);
116 LockRelation(rel, AccessExclusiveLock);
117 return checkOpenedRelation(rel, GIST_AM_OID);
121 gist_index_close(Relation rel) {
122 UnlockRelation(rel, AccessExclusiveLock);
127 gin_index_open(RangeVar *relvar) {
128 Relation rel = index_openrv(relvar);
130 LockRelation(rel, AccessShareLock);
131 return checkOpenedRelation(rel, GIN_AM_OID);
135 gin_index_close(Relation rel) {
136 UnlockRelation(rel, AccessShareLock);
142 #if PG_VERSION_NUM >= 80300
143 #define stringToQualifiedNameList(x,y) stringToQualifiedNameList(x)
146 #if PG_VERSION_NUM < 80300
147 #define SET_VARSIZE(p,l) VARATT_SIZEP(p)=(l)
151 checkOpenedRelation(Relation r, Oid PgAmOid) {
152 if ( r->rd_index == NULL )
153 elog(ERROR, "Relation %s.%s is not an index",
154 get_namespace_name(RelationGetNamespace(r)),
155 RelationGetRelationName(r)
158 if ( r->rd_rel->relam != PgAmOid )
159 elog(ERROR, "Index %s.%s has wrong type",
160 get_namespace_name(RelationGetNamespace(r)),
161 RelationGetRelationName(r)
168 gist_dumptree(Relation r, int level, BlockNumber blk, OffsetNumber coff, IdxInfo *info) {
178 pred = (char *) palloc(sizeof(char) * level * 4 + 1);
179 MemSet(pred, ' ', level*4);
180 pred[level*4] = '\0';
182 buffer = ReadBuffer(r, blk);
183 page = (Page) BufferGetPage(buffer);
185 maxoff = PageGetMaxOffsetNumber(page);
188 while ( (info->ptr-((char*)info->txt)) + level*4 + 128 >= info->len ) {
189 int dist=info->ptr-((char*)info->txt);
191 info->txt=(text*)repalloc(info->txt, info->len);
192 info->ptr = ((char*)info->txt)+dist;
195 sprintf(info->ptr, "%s%d(l:%d) blk: %u numTuple: %d free: %db(%.2f%%) rightlink:%u (%s)\n",
201 (int) PageGetFreeSpace(page),
202 100.0*(((float)PAGESIZE)-(float)PageGetFreeSpace(page))/((float)PAGESIZE),
203 GistPageGetOpaque(page)->rightlink,
204 ( GistPageGetOpaque(page)->rightlink == InvalidBlockNumber ) ? "InvalidBlockNumber" : "OK" );
205 info->ptr=strchr(info->ptr,'\0');
207 if (!GistPageIsLeaf(page) && ( info->maxlevel<0 || level<info->maxlevel ) )
208 for (i = FirstOffsetNumber; i <= maxoff; i = OffsetNumberNext(i)) {
209 iid = PageGetItemId(page, i);
210 which = (IndexTuple) PageGetItem(page, iid);
211 cblk = ItemPointerGetBlockNumber(&(which->t_tid));
212 gist_dumptree(r, level + 1, cblk, i, info);
214 ReleaseBuffer(buffer);
218 PG_FUNCTION_INFO_V1(gist_tree);
219 Datum gist_tree(PG_FUNCTION_ARGS);
221 gist_tree(PG_FUNCTION_ARGS) {
222 text *name=PG_GETARG_TEXT_P(0);
223 char *relname=t2c(name);
229 relname_list = stringToQualifiedNameList(relname, "gist_tree");
230 relvar = makeRangeVarFromNameList(relname_list);
231 index = gist_index_open(relvar);
232 PG_FREE_IF_COPY(name,0);
234 info.maxlevel = ( PG_NARGS() > 1 ) ? PG_GETARG_INT32(1) : -1;
236 info.txt=(text*)palloc( info.len );
237 info.ptr=((char*)info.txt)+VARHDRSZ;
239 gist_dumptree(index, 0, GIST_ROOT_BLKNO, 0, &info);
241 gist_index_close(index);
244 SET_VARSIZE(info.txt, info.ptr-((char*)info.txt));
245 PG_RETURN_POINTER(info.txt);
256 uint64 leaftuplesize;
261 gist_stattree(Relation r, int level, BlockNumber blk, OffsetNumber coff, IdxStat *info) {
271 pred = (char *) palloc(sizeof(char) * level * 4 + 1);
272 MemSet(pred, ' ', level*4);
273 pred[level*4] = '\0';
275 buffer = ReadBuffer(r, blk);
276 page = (Page) BufferGetPage(buffer);
278 maxoff = PageGetMaxOffsetNumber(page);
281 info->tuplesize+=PAGESIZE-PageGetFreeSpace(page);
282 info->totalsize+=BLCKSZ;
283 info->numtuple+=maxoff;
284 if ( info->level < level )
287 if (GistPageIsLeaf(page)) {
288 info->numleafpages++;
289 info->leaftuplesize+=PAGESIZE-PageGetFreeSpace(page);
290 info->numleaftuple+=maxoff;
292 for (i = FirstOffsetNumber; i <= maxoff; i = OffsetNumberNext(i)) {
293 iid = PageGetItemId(page, i);
294 which = (IndexTuple) PageGetItem(page, iid);
295 if ( GistTupleIsInvalid(which) )
296 info->numinvalidtuple++;
297 cblk = ItemPointerGetBlockNumber(&(which->t_tid));
298 gist_stattree(r, level + 1, cblk, i, info);
302 ReleaseBuffer(buffer);
306 PG_FUNCTION_INFO_V1(gist_stat);
307 Datum gist_stat(PG_FUNCTION_ARGS);
309 gist_stat(PG_FUNCTION_ARGS) {
310 text *name=PG_GETARG_TEXT_P(0);
311 char *relname=t2c(name);
316 text *out=(text*)palloc(1024);
317 char *ptr=((char*)out)+VARHDRSZ;
320 relname_list = stringToQualifiedNameList(relname, "gist_tree");
321 relvar = makeRangeVarFromNameList(relname_list);
322 index = gist_index_open(relvar);
323 PG_FREE_IF_COPY(name,0);
325 memset(&info, 0, sizeof(IdxStat));
327 gist_stattree(index, 0, GIST_ROOT_BLKNO, 0, &info);
329 gist_index_close(index);
333 "Number of levels: %d\n"
334 "Number of pages: %d\n"
335 "Number of leaf pages: %d\n"
336 "Number of tuples: %d\n"
337 "Number of invalid tuples: %d\n"
338 "Number of leaf tuples: %d\n"
339 "Total size of tuples: "INT64_FORMAT" bytes\n"
340 "Total size of leaf tuples: "INT64_FORMAT" bytes\n"
341 "Total size of index: "INT64_FORMAT" bytes\n",
346 info.numinvalidtuple,
352 ptr=strchr(ptr,'\0');
354 SET_VARSIZE(out, ptr-((char*)out));
355 PG_RETURN_POINTER(out);
358 typedef struct GPItem {
371 #if PG_VERSION_NUM >= 90600
380 openGPPage( FuncCallContext *funcctx, BlockNumber blk ) {
382 MemoryContext oldcontext;
383 Relation index = ( (TypeStorage*)(funcctx->user_fctx) )->index;
385 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
386 nitem = (GPItem*)palloc( sizeof(GPItem) );
387 memset(nitem,0,sizeof(GPItem));
389 nitem->buffer = ReadBuffer(index, blk);
390 nitem->page = (Page) BufferGetPage(nitem->buffer);
391 nitem->offset=FirstOffsetNumber;
392 nitem->next = ( (TypeStorage*)(funcctx->user_fctx) )->item;
393 nitem->level = ( nitem->next ) ? nitem->next->level+1 : 1;
394 ( (TypeStorage*)(funcctx->user_fctx) )->item = nitem;
396 MemoryContextSwitchTo(oldcontext);
401 closeGPPage( FuncCallContext *funcctx ) {
402 GPItem *oitem = ( (TypeStorage*)(funcctx->user_fctx) )->item;
404 ( (TypeStorage*)(funcctx->user_fctx) )->item = oitem->next;
406 ReleaseBuffer(oitem->buffer);
408 return ( (TypeStorage*)(funcctx->user_fctx) )->item;
412 setup_firstcall(FuncCallContext *funcctx, text *name) {
413 MemoryContext oldcontext;
415 char *relname=t2c(name);
417 char attname[NAMEDATALEN];
420 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
422 st=(TypeStorage*)palloc( sizeof(TypeStorage) );
423 memset(st,0,sizeof(TypeStorage));
424 st->relname_list = stringToQualifiedNameList(relname, "gist_tree");
425 st->relvar = makeRangeVarFromNameList(st->relname_list);
426 st->index = gist_index_open(st->relvar);
427 funcctx->user_fctx = (void*)st;
429 tupdesc = CreateTemplateTupleDesc(st->index->rd_att->natts+2, false);
430 TupleDescInitEntry(tupdesc, 1, "level", INT4OID, -1, 0);
431 TupleDescInitEntry(tupdesc, 2, "valid", BOOLOID, -1, 0);
432 for (i = 0; i < st->index->rd_att->natts; i++) {
433 sprintf(attname, "z%d", i+2);
438 st->index->rd_att->attrs[i]->atttypid,
439 st->index->rd_att->attrs[i]->atttypmod,
440 st->index->rd_att->attrs[i]->attndims
444 st->dvalues = (Datum *) palloc((tupdesc->natts+2) * sizeof(Datum));
445 st->nulls = (char *) palloc((tupdesc->natts+2) * sizeof(*st->nulls));
447 funcctx->slot = TupleDescGetSlot(tupdesc);
448 funcctx->attinmeta = TupleDescGetAttInMetadata(tupdesc);
450 MemoryContextSwitchTo(oldcontext);
453 st->item=openGPPage(funcctx, GIST_ROOT_BLKNO);
457 close_call( FuncCallContext *funcctx ) {
458 TypeStorage *st = (TypeStorage*)(funcctx->user_fctx);
460 while(st->item && closeGPPage(funcctx));
465 gist_index_close(st->index);
468 PG_FUNCTION_INFO_V1(gist_print);
469 Datum gist_print(PG_FUNCTION_ARGS);
471 gist_print(PG_FUNCTION_ARGS) {
472 FuncCallContext *funcctx;
474 Datum result=(Datum)0;
481 if (SRF_IS_FIRSTCALL()) {
482 text *name=PG_GETARG_TEXT_P(0);
483 funcctx = SRF_FIRSTCALL_INIT();
484 setup_firstcall(funcctx, name);
485 PG_FREE_IF_COPY(name,0);
488 funcctx = SRF_PERCALL_SETUP();
489 st = (TypeStorage*)(funcctx->user_fctx);
493 SRF_RETURN_DONE(funcctx);
496 while( st->item->offset > PageGetMaxOffsetNumber( st->item->page ) ) {
497 if ( ! closeGPPage(funcctx) ) {
499 SRF_RETURN_DONE(funcctx);
503 iid = PageGetItemId( st->item->page, st->item->offset );
504 ituple = (IndexTuple) PageGetItem(st->item->page, iid);
506 st->dvalues[0] = Int32GetDatum( st->item->level );
507 st->nulls[0] = ISNOTNULL;
508 st->dvalues[1] = BoolGetDatum( (!GistPageIsLeaf(st->item->page) && GistTupleIsInvalid(ituple)) ? false : true );
509 st->nulls[1] = ISNOTNULL;
510 for(i=2; i<funcctx->attinmeta->tupdesc->natts; i++) {
511 if ( !GistPageIsLeaf(st->item->page) && GistTupleIsInvalid(ituple) ) {
512 st->dvalues[i] = (Datum)0;
513 st->nulls[i] = ISNULL;
515 st->dvalues[i] = index_getattr(ituple, i-1, st->index->rd_att, &isnull);
516 st->nulls[i] = ( isnull ) ? ISNULL : ISNOTNULL;
520 htuple = heap_formtuple(funcctx->attinmeta->tupdesc, st->dvalues, st->nulls);
521 result = TupleGetDatum(funcctx->slot, htuple);
522 st->item->offset = OffsetNumberNext(st->item->offset);
523 if ( !GistPageIsLeaf(st->item->page) )
524 openGPPage(funcctx, ItemPointerGetBlockNumber(&(ituple->t_tid)) );
526 SRF_RETURN_NEXT(funcctx, result);
529 typedef struct GinStatState {
537 #if PG_VERSION_NUM >= 90100
538 GinNullCategory category;
545 moveRightIfItNeeded( GinStatState *st )
547 Page page = BufferGetPage(st->buffer);
549 if ( st->offset > PageGetMaxOffsetNumber(page) ) {
551 * We scaned the whole page, so we should take right page
553 BlockNumber blkno = GinPageGetOpaque(page)->rightlink;
555 if ( GinPageRightMost(page) )
556 return false; /* no more page */
558 LockBuffer(st->buffer, GIN_UNLOCK);
559 st->buffer = ReleaseAndReadBuffer(st->buffer, st->index, blkno);
560 LockBuffer(st->buffer, GIN_SHARE);
561 st->offset = FirstOffsetNumber;
568 * Refinds a previois position, at returns it has correctly
569 * set offset and buffer is locked
572 refindPosition(GinStatState *st)
576 /* find left if needed (it causes only for first search) */
581 LockBuffer(st->buffer, GIN_SHARE);
583 page = BufferGetPage(st->buffer);
584 if (GinPageIsLeaf(page))
587 itup = (IndexTuple) PageGetItem(page, PageGetItemId(page, FirstOffsetNumber));
588 blkno = GinItemPointerGetBlockNumber(&(itup)->t_tid);
590 LockBuffer(st->buffer,GIN_UNLOCK);
591 st->buffer = ReleaseAndReadBuffer(st->buffer, st->index, blkno);
594 if (st->offset == InvalidOffsetNumber) {
595 return (PageGetMaxOffsetNumber(page) >= FirstOffsetNumber ) ? true : false; /* first one */
600 #if PG_VERSION_NUM >= 90100
601 GinNullCategory category;
602 #elif PG_VERSION_NUM < 80400
608 if (moveRightIfItNeeded(st)==false)
611 itup = (IndexTuple) PageGetItem(page, PageGetItemId(page, st->offset));
612 #if PG_VERSION_NUM >= 90100
613 datum = gintuple_get_key(&st->ginstate, itup, &category);
614 cmp = ginCompareAttEntries(&st->ginstate,
615 st->attnum + 1, st->curval, st->category,
616 gintuple_get_attrnum(&st->ginstate, itup), datum, category);
617 #elif PG_VERSION_NUM >= 80400
618 datum = gin_index_getattr(&st->ginstate, itup);
620 cmp = compareAttEntries(&st->ginstate,
621 st->attnum + 1, st->curval,
622 gintuple_get_attrnum(&st->ginstate, itup), datum);
624 datum = index_getattr(itup, FirstOffsetNumber, st->ginstate.tupdesc, &isnull);
628 &st->ginstate.compareFn,
635 if ( st->curval && !st->index->rd_att->attrs[st->attnum]->attbyval )
636 pfree( (void*) st->curval );
647 gin_setup_firstcall(FuncCallContext *funcctx, text *name, int attnum) {
648 MemoryContext oldcontext;
650 char *relname=t2c(name);
653 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
655 st=(GinStatState*)palloc( sizeof(GinStatState) );
656 memset(st,0,sizeof(GinStatState));
657 st->index = gin_index_open(
658 makeRangeVarFromNameList(stringToQualifiedNameList(relname, "gin_stat")));
659 initGinState( &st->ginstate, st->index );
661 #if PG_VERSION_NUM >= 80400
662 if (attnum < 0 || attnum >= st->index->rd_att->natts)
663 elog(ERROR,"Wrong column's number");
669 funcctx->user_fctx = (void*)st;
671 tupdesc = CreateTemplateTupleDesc(2, false);
672 TupleDescInitEntry(tupdesc, 1, "value",
673 st->index->rd_att->attrs[st->attnum]->atttypid,
674 st->index->rd_att->attrs[st->attnum]->atttypmod,
675 st->index->rd_att->attrs[st->attnum]->attndims);
676 TupleDescInitEntry(tupdesc, 2, "nrow", INT4OID, -1, 0);
678 memset( st->nulls, ISNOTNULL, 2*sizeof(*st->nulls) );
680 funcctx->slot = TupleDescGetSlot(tupdesc);
681 funcctx->attinmeta = TupleDescGetAttInMetadata(tupdesc);
683 MemoryContextSwitchTo(oldcontext);
686 st->offset = InvalidOffsetNumber;
687 st->buffer = ReadBuffer( st->index, GIN_ROOT_BLKNO );
691 processTuple( FuncCallContext *funcctx, GinStatState *st, IndexTuple itup ) {
692 MemoryContext oldcontext;
693 #if PG_VERSION_NUM >= 90100
695 #elif PG_VERSION_NUM < 80400
699 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
701 #if PG_VERSION_NUM >= 90100
702 key = gintuple_get_key(&st->ginstate, itup, &st->category);
704 if (st->category != GIN_CAT_NORM_KEY)
705 st->curval = (Datum)0;
708 st->curval = datumCopy(
709 #if PG_VERSION_NUM >= 90100
711 #elif PG_VERSION_NUM >= 80400
712 gin_index_getattr(&st->ginstate, itup),
714 index_getattr(itup, FirstOffsetNumber, st->ginstate.tupdesc, &isnull),
716 st->index->rd_att->attrs[st->attnum]->attbyval,
717 st->index->rd_att->attrs[st->attnum]->attlen );
718 MemoryContextSwitchTo(oldcontext);
720 st->dvalues[0] = st->curval;
721 #if PG_VERSION_NUM >= 90100
722 /* do no distiguish various null category */
723 st->nulls[0] = (st->category == GIN_CAT_NORM_KEY) ? ISNOTNULL : ISNULL;
726 if ( GinIsPostingTree(itup) ) {
727 BlockNumber rootblkno = GinGetPostingTree(itup);
728 #if PG_VERSION_NUM >= 90400
730 GinBtreeStack *stack;
731 ItemPointerData minItem;
735 GinPostingTreeScan *gdi;
739 uint32 predictNumber;
741 LockBuffer(st->buffer, GIN_UNLOCK);
742 #if PG_VERSION_NUM >= 90400
743 stack = ginScanBeginPostingTree(&btree, st->index, rootblkno
744 #if PG_VERSION_NUM >= 90600
748 page = BufferGetPage(stack->buffer);
749 ItemPointerSetMin(&minItem);
750 list = GinDataLeafPageGetItems(page, &nlist, minItem);
752 predictNumber = stack->predictNumber;
753 st->dvalues[1] = Int32GetDatum( predictNumber * nlist );
754 #elif PG_VERSION_NUM >= 90100
755 gdi = ginPrepareScanPostingTree(st->index, rootblkno, TRUE);
756 entrybuffer = ginScanBeginPostingTree(gdi);
757 page = BufferGetPage(entrybuffer);
758 predictNumber = gdi->stack->predictNumber;
759 st->dvalues[1] = Int32GetDatum( predictNumber * GinPageGetOpaque(page)->maxoff );
761 gdi = prepareScanPostingTree(st->index, rootblkno, TRUE);
762 entrybuffer = scanBeginPostingTree(gdi);
763 page = BufferGetPage(entrybuffer);
764 predictNumber = gdi->stack->predictNumber;
765 st->dvalues[1] = Int32GetDatum( predictNumber * GinPageGetOpaque(page)->maxoff );
768 #if PG_VERSION_NUM < 90400
769 LockBuffer(entrybuffer, GIN_UNLOCK);
770 freeGinBtreeStack(gdi->stack);
773 LockBuffer(stack->buffer, GIN_UNLOCK);
774 freeGinBtreeStack(stack);
777 st->dvalues[1] = Int32GetDatum( GinGetNPosting(itup) );
778 LockBuffer(st->buffer, GIN_UNLOCK);
782 PG_FUNCTION_INFO_V1(gin_stat);
783 Datum gin_stat(PG_FUNCTION_ARGS);
785 gin_stat(PG_FUNCTION_ARGS) {
786 FuncCallContext *funcctx;
788 Datum result=(Datum)0;
793 if (SRF_IS_FIRSTCALL()) {
794 text *name=PG_GETARG_TEXT_P(0);
795 funcctx = SRF_FIRSTCALL_INIT();
796 gin_setup_firstcall(funcctx, name, (PG_NARGS()==2) ? PG_GETARG_INT32(1) : 0 );
797 PG_FREE_IF_COPY(name,0);
800 funcctx = SRF_PERCALL_SETUP();
801 st = (GinStatState*)(funcctx->user_fctx);
803 if ( refindPosition(st) == false ) {
804 UnlockReleaseBuffer( st->buffer );
805 gin_index_close(st->index);
807 SRF_RETURN_DONE(funcctx);
813 if (moveRightIfItNeeded(st)==false) {
814 UnlockReleaseBuffer( st->buffer );
815 gin_index_close(st->index);
817 SRF_RETURN_DONE(funcctx);
820 page = BufferGetPage(st->buffer);
821 ituple = (IndexTuple) PageGetItem(page, PageGetItemId(page, st->offset));
823 #if PG_VERSION_NUM >= 80400
824 if (st->attnum + 1 == gintuple_get_attrnum(&st->ginstate, ituple))
829 processTuple( funcctx, st, ituple );
831 htuple = heap_formtuple(funcctx->attinmeta->tupdesc, st->dvalues, st->nulls);
832 result = TupleGetDatum(funcctx->slot, htuple);
834 SRF_RETURN_NEXT(funcctx, result);
837 PG_FUNCTION_INFO_V1(gin_count_estimate);
838 Datum gin_count_estimate(PG_FUNCTION_ARGS);
839 #if PG_VERSION_NUM >= 80300
841 gin_count_estimate(PG_FUNCTION_ARGS) {
842 text *name=PG_GETARG_TEXT_P(0);
846 char *relname=t2c(name);
848 #if PG_VERSION_NUM >= 80400
849 TIDBitmap *bitmap = tbm_create(work_mem * 1024L
850 #if PG_VERSION_NUM >= 100000
856 ItemPointerData tids[MAXTIDS];
861 index = gin_index_open(
862 makeRangeVarFromNameList(stringToQualifiedNameList(relname, "gin_count_estimate")));
864 if ( index->rd_opcintype[0] != TSVECTOROID ) {
865 gin_index_close(index);
866 elog(ERROR, "Column type is not a tsvector");
871 key.sk_strategy = TSearchStrategyNumber;
873 key.sk_argument = PG_GETARG_DATUM(1);
875 fmgr_info( F_TS_MATCH_VQ , &key.sk_func );
877 #if PG_VERSION_NUM >= 90100
878 #if PG_VERSION_NUM >= 90400
879 scan = index_beginscan_bitmap(index, SnapshotSelf, 1);
881 scan = index_beginscan_bitmap(index, SnapshotNow, 1);
883 index_rescan(scan, &key, 1, NULL, 0);
885 count = index_getbitmap(scan, bitmap);
887 #elif PG_VERSION_NUM >= 80400
888 scan = index_beginscan_bitmap(index, SnapshotNow, 1, &key);
890 count = index_getbitmap(scan, bitmap);
893 scan = index_beginscan_multi(index, SnapshotNow, 1, &key);
896 more = index_getmulti(scan, tids, MAXTIDS, &returned_tids);
897 count += returned_tids;
901 index_endscan( scan );
902 gin_index_close(index);
904 PG_RETURN_INT64(count);
908 gin_count_estimate(PG_FUNCTION_ARGS) {
909 elog(NOTICE, "Function is not working under PgSQL < 8.3");
915 PG_FUNCTION_INFO_V1(spgist_stat);
916 Datum spgist_stat(PG_FUNCTION_ARGS);
918 spgist_stat(PG_FUNCTION_ARGS)
920 #if PG_VERSION_NUM < 90200
921 elog(NOTICE, "Function is not working under PgSQL < 9.2");
923 PG_RETURN_TEXT_P(CStringGetTextDatum("???"));
925 text *name = PG_GETARG_TEXT_P(0);
929 BlockNumber totalPages = 0,
934 double usedSpace = 0.0,
936 usedInnerSpace = 0.0;
939 int64 innerTuples = 0,
942 nLeafPlaceholder = 0,
943 nInnerPlaceholder = 0,
947 #define IS_INDEX(r) ((r)->rd_rel->relkind == RELKIND_INDEX)
948 #define IS_SPGIST(r) ((r)->rd_rel->relam == SPGIST_AM_OID)
950 relvar = makeRangeVarFromNameList(textToQualifiedNameList(name));
951 index = relation_openrv(relvar, AccessExclusiveLock);
953 if (!IS_INDEX(index) || !IS_SPGIST(index))
954 elog(ERROR, "relation \"%s\" is not an SPGiST index",
955 RelationGetRelationName(index));
957 totalPages = RelationGetNumberOfBlocks(index);
959 for (blkno = SPGIST_ROOT_BLKNO; blkno < totalPages; blkno++)
965 buffer = ReadBuffer(index, blkno);
966 LockBuffer(buffer, BUFFER_LOCK_SHARE);
968 page = BufferGetPage(buffer);
970 if (PageIsNew(page) || SpGistPageIsDeleted(page))
973 UnlockReleaseBuffer(buffer);
977 if (SpGistPageIsLeaf(page))
980 leafTuples += PageGetMaxOffsetNumber(page);
981 nLeafPlaceholder += SpGistPageGetOpaque(page)->nPlaceholder;
982 nLeafRedirect += SpGistPageGetOpaque(page)->nRedirection;
990 max = PageGetMaxOffsetNumber(page);
992 nInnerPlaceholder += SpGistPageGetOpaque(page)->nPlaceholder;
993 nInnerRedirect += SpGistPageGetOpaque(page)->nRedirection;
994 for (i = FirstOffsetNumber; i <= max; i++)
998 it = (SpGistInnerTuple) PageGetItem(page,
999 PageGetItemId(page, i));
1006 bufferSize = BufferGetPageSize(buffer)
1007 - MAXALIGN(sizeof(SpGistPageOpaqueData))
1008 - SizeOfPageHeaderData;
1010 pageFree = PageGetExactFreeSpace(page);
1012 usedSpace += bufferSize - pageFree;
1013 if (SpGistPageIsLeaf(page))
1014 usedLeafSpace += bufferSize - pageFree;
1016 usedInnerSpace += bufferSize - pageFree;
1018 if (pageFree == bufferSize)
1021 UnlockReleaseBuffer(buffer);
1024 index_close(index, AccessExclusiveLock);
1026 totalPages--; /* discount metapage */
1028 snprintf(res, sizeof(res),
1030 "deletedPages: %u\n"
1034 "usedSpace: %.2f kbytes\n"
1035 "usedInnerSpace: %.2f kbytes\n"
1036 "usedLeafSpace: %.2f kbytes\n"
1037 "freeSpace: %.2f kbytes\n"
1038 "fillRatio: %.2f%%\n"
1039 "leafTuples: " INT64_FORMAT "\n"
1040 "innerTuples: " INT64_FORMAT "\n"
1041 "innerAllTheSame: " INT64_FORMAT "\n"
1042 "leafPlaceholders: " INT64_FORMAT "\n"
1043 "innerPlaceholders: " INT64_FORMAT "\n"
1044 "leafRedirects: " INT64_FORMAT "\n"
1045 "innerRedirects: " INT64_FORMAT,
1046 totalPages, deletedPages, innerPages, leafPages, emptyPages,
1048 usedInnerSpace / 1024.0,
1049 usedLeafSpace / 1024.0,
1050 (((double) bufferSize) * ((double) totalPages) - usedSpace) / 1024,
1051 100.0 * (usedSpace / (((double) bufferSize) * ((double) totalPages))),
1052 leafTuples, innerTuples, nAllTheSame,
1053 nLeafPlaceholder, nInnerPlaceholder,
1054 nLeafRedirect, nInnerRedirect);
1056 PG_RETURN_TEXT_P(CStringGetTextDatum(res));
1060 #if PG_VERSION_NUM >= 90200
1062 typedef struct SPGistPrintStackElem {
1063 ItemPointerData iptr;
1066 } SPGistPrintStackElem;
1068 typedef struct SPGistPrint {
1071 Datum dvalues[8 /* see CreateTemplateTupleDesc call */];
1072 char nulls[8 /* see CreateTemplateTupleDesc call */];
1077 pushSPGistPrint(FuncCallContext *funcctx, SPGistPrint *prst, ItemPointer ip, int level) {
1078 MemoryContext oldcontext;
1079 SPGistPrintStackElem *e;
1081 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1083 e = palloc(sizeof(*e));
1087 prst->stack = lcons(e, prst->stack);
1089 MemoryContextSwitchTo(oldcontext);
1093 close_spgist_print(SPGistPrint *prst) {
1094 index_close(prst->index, AccessExclusiveLock);
1098 PG_FUNCTION_INFO_V1(spgist_print);
1099 Datum spgist_print(PG_FUNCTION_ARGS);
1101 spgist_print(PG_FUNCTION_ARGS)
1103 #if PG_VERSION_NUM < 90200
1104 elog(NOTICE, "Function is not working under PgSQL < 9.2");
1106 PG_RETURN_TEXT_P(CStringGetTextDatum("???"));
1108 FuncCallContext *funcctx;
1110 SPGistPrintStackElem *s;
1113 MemoryContext oldcontext;
1115 if (SRF_IS_FIRSTCALL()) {
1116 text *name=PG_GETARG_TEXT_P(0);
1119 ItemPointerData ipd;
1122 funcctx = SRF_FIRSTCALL_INIT();
1123 relvar = makeRangeVarFromNameList(textToQualifiedNameList(name));
1124 index = relation_openrv(relvar, AccessExclusiveLock);
1126 if (!IS_INDEX(index) || !IS_SPGIST(index))
1127 elog(ERROR, "relation \"%s\" is not an SPGiST index",
1128 RelationGetRelationName(index));
1130 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1132 prst = palloc(sizeof(*prst));
1134 prst->index = index;
1135 initSpGistState(&prst->state, index);
1137 tupdesc = CreateTemplateTupleDesc(3 /* types */ + 1 /* level */ + 1 /* nlabel */ + 2 /* tids */ + 1, false);
1138 TupleDescInitEntry(tupdesc, 1, "tid", TIDOID, -1, 0);
1139 TupleDescInitEntry(tupdesc, 2, "allthesame", BOOLOID, -1, 0);
1140 TupleDescInitEntry(tupdesc, 3, "node", INT4OID, -1, 0);
1141 TupleDescInitEntry(tupdesc, 4, "level", INT4OID, -1, 0);
1142 TupleDescInitEntry(tupdesc, 5, "tid_pointer", TIDOID, -1, 0);
1143 TupleDescInitEntry(tupdesc, 6, "prefix",
1144 (prst->state.attPrefixType.type == VOIDOID) ? INT4OID : prst->state.attPrefixType.type, -1, 0);
1145 TupleDescInitEntry(tupdesc, 7, "label",
1146 (prst->state.attLabelType.type == VOIDOID) ? INT4OID : prst->state.attLabelType.type, -1, 0);
1147 TupleDescInitEntry(tupdesc, 8, "leaf",
1148 (prst->state.attType.type == VOIDOID) ? INT4OID : prst->state.attType.type, -1, 0);
1150 funcctx->slot = TupleDescGetSlot(tupdesc);
1151 funcctx->attinmeta = TupleDescGetAttInMetadata(tupdesc);
1153 funcctx->user_fctx = (void*)prst;
1155 MemoryContextSwitchTo(oldcontext);
1157 ItemPointerSet(&ipd, SPGIST_ROOT_BLKNO, FirstOffsetNumber);
1159 pushSPGistPrint(funcctx, prst, &ipd, 1);
1161 PG_FREE_IF_COPY(name,0);
1164 funcctx = SRF_PERCALL_SETUP();
1165 prst = (SPGistPrint*)(funcctx->user_fctx);
1169 if ( prst->stack == NIL ) {
1170 close_spgist_print(prst);
1171 SRF_RETURN_DONE(funcctx);
1174 CHECK_FOR_INTERRUPTS();
1176 s = (SPGistPrintStackElem*)linitial(prst->stack);
1177 prst->stack = list_delete_first(prst->stack);
1179 if (ItemPointerIsValid(&s->iptr))
1187 SpGistDeadTuple dtuple;
1190 buffer = ReadBuffer(prst->index, ItemPointerGetBlockNumber(&s->iptr));
1191 LockBuffer(buffer, BUFFER_LOCK_SHARE);
1193 page = BufferGetPage(buffer);
1194 if (ItemPointerGetOffsetNumber(&s->iptr) > PageGetMaxOffsetNumber(page)) {
1195 UnlockReleaseBuffer(buffer);
1200 dtuple = (SpGistDeadTuple)PageGetItem(page, PageGetItemId(page, ItemPointerGetOffsetNumber(&s->iptr)));
1202 if (dtuple->tupstate != SPGIST_LIVE) {
1203 UnlockReleaseBuffer(buffer);
1208 if (SpGistPageIsLeaf(page)) {
1209 SpGistLeafTuple leafTuple = (SpGistLeafTuple)dtuple;
1211 tid = palloc(sizeof(ItemPointerData));
1213 prst->dvalues[0] = PointerGetDatum(tid);
1214 prst->nulls[0] = ISNOTNULL;
1215 prst->nulls[1] = ISNULL;
1216 prst->nulls[2] = ISNULL;
1217 prst->dvalues[3] = s->level;
1218 prst->nulls[3] = ISNOTNULL;
1219 prst->nulls[4] = ISNULL;
1220 prst->nulls[5] = ISNULL;
1221 prst->nulls[6] = ISNULL;
1222 prst->dvalues[7] = datumCopy(SGLTDATUM(leafTuple, &prst->state),
1223 prst->state.attType.attbyval, prst->state.attType.attlen);
1224 prst->nulls[7] = ISNOTNULL;
1226 SpGistInnerTuple innerTuple = (SpGistInnerTuple)dtuple;
1228 SpGistNodeTuple node;
1230 SGITITERATE(innerTuple, i, node) {
1231 if (ItemPointerIsValid(&node->t_tid)) {
1237 if (i >= innerTuple->nNodes) {
1238 UnlockReleaseBuffer(buffer);
1243 tid = palloc(sizeof(ItemPointerData));
1245 prst->dvalues[0] = PointerGetDatum(tid);
1246 prst->nulls[0] = ISNOTNULL;
1247 prst->dvalues[1] = innerTuple->allTheSame;
1248 prst->nulls[1] = ISNOTNULL;
1249 prst->dvalues[2] = Int32GetDatum(s->nlabel);
1250 prst->nulls[2] = ISNOTNULL;
1251 prst->dvalues[3] = s->level;
1252 prst->nulls[3] = ISNOTNULL;
1253 tid = palloc(sizeof(ItemPointerData));
1255 prst->dvalues[4] = PointerGetDatum(tid);
1256 prst->nulls[5] = ISNOTNULL;
1257 if (innerTuple->prefixSize > 0) {
1258 prst->dvalues[5] = datumCopy(SGITDATUM(innerTuple, &prst->state),
1259 prst->state.attPrefixType.attbyval, prst->state.attPrefixType.attlen);
1260 prst->nulls[5] = ISNOTNULL;
1262 prst->nulls[5] = ISNULL;
1263 if (!IndexTupleHasNulls(node)) {
1264 prst->dvalues[6] = datumCopy(SGNTDATUM(node, &prst->state),
1265 prst->state.attLabelType.attbyval, prst->state.attLabelType.attlen);
1266 prst->nulls[6] = ISNOTNULL;
1268 prst->nulls[6] = ISNULL;
1269 prst->nulls[7] = ISNULL;
1271 pushSPGistPrint(funcctx, prst, &node->t_tid, s->level + 1);
1273 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1274 prst->stack = lcons(s, prst->stack);
1275 MemoryContextSwitchTo(oldcontext);
1279 UnlockReleaseBuffer(buffer);
1283 htuple = heap_formtuple(funcctx->attinmeta->tupdesc, prst->dvalues, prst->nulls);
1284 result = TupleGetDatum(funcctx->slot, htuple);
1286 SRF_RETURN_NEXT(funcctx, result);
1291 PG_FUNCTION_INFO_V1(gin_statpage);
1292 Datum gin_statpage(PG_FUNCTION_ARGS);
1294 gin_statpage(PG_FUNCTION_ARGS)
1296 #if PG_VERSION_NUM < 90400
1297 elog(NOTICE, "Function is not working under PgSQL < 9.4");
1299 PG_RETURN_TEXT_P(CStringGetTextDatum("???"));
1301 text *name = PG_GETARG_TEXT_P(0);
1311 entryInnerPages = 0,
1314 uint64 dataInnerFreeSpace = 0,
1315 dataLeafFreeSpace = 0,
1316 dataInnerTuplesCount = 0,
1317 dataLeafIptrsCount = 0,
1318 entryInnerFreeSpace = 0,
1319 entryLeafFreeSpace = 0,
1320 entryInnerTuplesCount = 0,
1321 entryLeafTuplesCount = 0,
1322 entryPostingSize = 0,
1323 entryPostingCount = 0,
1327 relvar = makeRangeVarFromNameList(textToQualifiedNameList(name));
1328 index = relation_openrv(relvar, AccessExclusiveLock);
1330 if (index->rd_rel->relkind != RELKIND_INDEX ||
1331 index->rd_rel->relam != GIN_AM_OID)
1332 elog(ERROR, "relation \"%s\" is not an SPGiST index",
1333 RelationGetRelationName(index));
1335 totalPages = RelationGetNumberOfBlocks(index);
1337 for (blkno = GIN_ROOT_BLKNO; blkno < totalPages; blkno++)
1343 buffer = ReadBuffer(index, blkno);
1344 LockBuffer(buffer, BUFFER_LOCK_SHARE);
1346 page = BufferGetPage(buffer);
1347 header = (PageHeader)page;
1349 if (GinPageIsData(page))
1352 if (GinPageIsLeaf(page))
1354 ItemPointerData minItem;
1358 dataLeafFreeSpace += header->pd_upper - header->pd_lower;
1359 ItemPointerSetMin(&minItem);
1360 pfree(GinDataLeafPageGetItems(page, &nlist, minItem));
1361 dataLeafIptrsCount += nlist;
1366 dataInnerFreeSpace += header->pd_upper - header->pd_lower;
1367 dataInnerTuplesCount += GinPageGetOpaque(page)->maxoff;
1373 OffsetNumber i, maxoff;
1375 maxoff = PageGetMaxOffsetNumber(page);
1378 if (GinPageIsLeaf(page))
1381 entryLeafFreeSpace += header->pd_upper - header->pd_lower;
1382 entryLeafTuplesCount += maxoff;
1387 entryInnerFreeSpace += header->pd_upper - header->pd_lower;
1388 entryInnerTuplesCount += maxoff;
1391 for (i = 1; i <= maxoff; i++)
1393 itup = (IndexTuple) PageGetItem(page, PageGetItemId(page, i));
1395 if (GinPageIsLeaf(page))
1397 GinPostingList *list = (GinPostingList *)GinGetPosting(itup);
1398 entryPostingCount += GinGetNPosting(itup);
1399 entryPostingSize += SizeOfGinPostingList(list);
1400 entryAttrSize += GinGetPostingOffset(itup) - IndexInfoFindDataOffset((itup)->t_info);
1404 entryAttrSize += IndexTupleSize(itup) - IndexInfoFindDataOffset((itup)->t_info);
1409 UnlockReleaseBuffer(buffer);
1412 index_close(index, AccessExclusiveLock);
1415 snprintf(res, sizeof(res),
1418 "dataInnerPages: %u\n"
1419 "dataLeafPages: %u\n"
1420 "dataInnerFreeSpace: " INT64_FORMAT "\n"
1421 "dataLeafFreeSpace: " INT64_FORMAT "\n"
1422 "dataInnerTuplesCount: " INT64_FORMAT "\n"
1423 "dataLeafIptrsCount: " INT64_FORMAT "\n"
1425 "entryInnerPages: %u\n"
1426 "entryLeafPages: %u\n"
1427 "entryInnerFreeSpace: " INT64_FORMAT "\n"
1428 "entryLeafFreeSpace: " INT64_FORMAT "\n"
1429 "entryInnerTuplesCount: " INT64_FORMAT "\n"
1430 "entryLeafTuplesCount: " INT64_FORMAT "\n"
1431 "entryPostingSize: " INT64_FORMAT "\n"
1432 "entryPostingCount: " INT64_FORMAT "\n"
1433 "entryAttrSize: " INT64_FORMAT "\n"
1441 dataInnerTuplesCount,
1446 entryInnerFreeSpace,
1448 entryInnerTuplesCount,
1449 entryLeafTuplesCount,
1455 PG_RETURN_TEXT_P(CStringGetTextDatum(res));