LCOV - code coverage report
Current view: top level - src/backend/access/spgist - spgutils.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 423 466 90.8 %
Date: 2024-11-21 08:14:44 Functions: 26 26 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * spgutils.c
       4             :  *    various support functions for SP-GiST
       5             :  *
       6             :  *
       7             :  * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
       8             :  * Portions Copyright (c) 1994, Regents of the University of California
       9             :  *
      10             :  * IDENTIFICATION
      11             :  *          src/backend/access/spgist/spgutils.c
      12             :  *
      13             :  *-------------------------------------------------------------------------
      14             :  */
      15             : 
      16             : #include "postgres.h"
      17             : 
      18             : #include "access/amvalidate.h"
      19             : #include "access/htup_details.h"
      20             : #include "access/reloptions.h"
      21             : #include "access/spgist_private.h"
      22             : #include "access/toast_compression.h"
      23             : #include "access/transam.h"
      24             : #include "access/xact.h"
      25             : #include "catalog/pg_amop.h"
      26             : #include "commands/vacuum.h"
      27             : #include "nodes/nodeFuncs.h"
      28             : #include "parser/parse_coerce.h"
      29             : #include "storage/bufmgr.h"
      30             : #include "storage/indexfsm.h"
      31             : #include "utils/catcache.h"
      32             : #include "utils/fmgrprotos.h"
      33             : #include "utils/index_selfuncs.h"
      34             : #include "utils/lsyscache.h"
      35             : #include "utils/rel.h"
      36             : #include "utils/syscache.h"
      37             : 
      38             : 
      39             : /*
      40             :  * SP-GiST handler function: return IndexAmRoutine with access method parameters
      41             :  * and callbacks.
      42             :  */
      43             : Datum
      44        1238 : spghandler(PG_FUNCTION_ARGS)
      45             : {
      46        1238 :     IndexAmRoutine *amroutine = makeNode(IndexAmRoutine);
      47             : 
      48        1238 :     amroutine->amstrategies = 0;
      49        1238 :     amroutine->amsupport = SPGISTNProc;
      50        1238 :     amroutine->amoptsprocnum = SPGIST_OPTIONS_PROC;
      51        1238 :     amroutine->amcanorder = false;
      52        1238 :     amroutine->amcanorderbyop = true;
      53        1238 :     amroutine->amcanbackward = false;
      54        1238 :     amroutine->amcanunique = false;
      55        1238 :     amroutine->amcanmulticol = false;
      56        1238 :     amroutine->amoptionalkey = true;
      57        1238 :     amroutine->amsearcharray = false;
      58        1238 :     amroutine->amsearchnulls = true;
      59        1238 :     amroutine->amstorage = true;
      60        1238 :     amroutine->amclusterable = false;
      61        1238 :     amroutine->ampredlocks = false;
      62        1238 :     amroutine->amcanparallel = false;
      63        1238 :     amroutine->amcanbuildparallel = false;
      64        1238 :     amroutine->amcaninclude = true;
      65        1238 :     amroutine->amusemaintenanceworkmem = false;
      66        1238 :     amroutine->amsummarizing = false;
      67        1238 :     amroutine->amparallelvacuumoptions =
      68             :         VACUUM_OPTION_PARALLEL_BULKDEL | VACUUM_OPTION_PARALLEL_COND_CLEANUP;
      69        1238 :     amroutine->amkeytype = InvalidOid;
      70             : 
      71        1238 :     amroutine->ambuild = spgbuild;
      72        1238 :     amroutine->ambuildempty = spgbuildempty;
      73        1238 :     amroutine->aminsert = spginsert;
      74        1238 :     amroutine->aminsertcleanup = NULL;
      75        1238 :     amroutine->ambulkdelete = spgbulkdelete;
      76        1238 :     amroutine->amvacuumcleanup = spgvacuumcleanup;
      77        1238 :     amroutine->amcanreturn = spgcanreturn;
      78        1238 :     amroutine->amcostestimate = spgcostestimate;
      79        1238 :     amroutine->amgettreeheight = NULL;
      80        1238 :     amroutine->amoptions = spgoptions;
      81        1238 :     amroutine->amproperty = spgproperty;
      82        1238 :     amroutine->ambuildphasename = NULL;
      83        1238 :     amroutine->amvalidate = spgvalidate;
      84        1238 :     amroutine->amadjustmembers = spgadjustmembers;
      85        1238 :     amroutine->ambeginscan = spgbeginscan;
      86        1238 :     amroutine->amrescan = spgrescan;
      87        1238 :     amroutine->amgettuple = spggettuple;
      88        1238 :     amroutine->amgetbitmap = spggetbitmap;
      89        1238 :     amroutine->amendscan = spgendscan;
      90        1238 :     amroutine->ammarkpos = NULL;
      91        1238 :     amroutine->amrestrpos = NULL;
      92        1238 :     amroutine->amestimateparallelscan = NULL;
      93        1238 :     amroutine->aminitparallelscan = NULL;
      94        1238 :     amroutine->amparallelrescan = NULL;
      95             : 
      96        1238 :     PG_RETURN_POINTER(amroutine);
      97             : }
      98             : 
      99             : /*
     100             :  * GetIndexInputType
     101             :  *      Determine the nominal input data type for an index column
     102             :  *
     103             :  * We define the "nominal" input type as the associated opclass's opcintype,
     104             :  * or if that is a polymorphic type, the base type of the heap column or
     105             :  * expression that is the index's input.  The reason for preferring the
     106             :  * opcintype is that non-polymorphic opclasses probably don't want to hear
     107             :  * about binary-compatible input types.  For instance, if a text opclass
     108             :  * is being used with a varchar heap column, we want to report "text" not
     109             :  * "varchar".  Likewise, opclasses don't want to hear about domain types,
     110             :  * so if we do consult the actual input type, we make sure to flatten domains.
     111             :  *
     112             :  * At some point maybe this should go somewhere else, but it's not clear
     113             :  * if any other index AMs have a use for it.
     114             :  */
     115             : static Oid
     116         404 : GetIndexInputType(Relation index, AttrNumber indexcol)
     117             : {
     118             :     Oid         opcintype;
     119             :     AttrNumber  heapcol;
     120             :     List       *indexprs;
     121             :     ListCell   *indexpr_item;
     122             : 
     123             :     Assert(index->rd_index != NULL);
     124             :     Assert(indexcol > 0 && indexcol <= index->rd_index->indnkeyatts);
     125         404 :     opcintype = index->rd_opcintype[indexcol - 1];
     126         404 :     if (!IsPolymorphicType(opcintype))
     127         300 :         return opcintype;
     128         104 :     heapcol = index->rd_index->indkey.values[indexcol - 1];
     129         104 :     if (heapcol != 0)           /* Simple index column? */
     130          92 :         return getBaseType(get_atttype(index->rd_index->indrelid, heapcol));
     131             : 
     132             :     /*
     133             :      * If the index expressions are already cached, skip calling
     134             :      * RelationGetIndexExpressions, as it will make a copy which is overkill.
     135             :      * We're not going to modify the trees, and we're not going to do anything
     136             :      * that would invalidate the relcache entry before we're done.
     137             :      */
     138          12 :     if (index->rd_indexprs)
     139           0 :         indexprs = index->rd_indexprs;
     140             :     else
     141          12 :         indexprs = RelationGetIndexExpressions(index);
     142          12 :     indexpr_item = list_head(indexprs);
     143          12 :     for (int i = 1; i <= index->rd_index->indnkeyatts; i++)
     144             :     {
     145          12 :         if (index->rd_index->indkey.values[i - 1] == 0)
     146             :         {
     147             :             /* expression column */
     148          12 :             if (indexpr_item == NULL)
     149           0 :                 elog(ERROR, "wrong number of index expressions");
     150          12 :             if (i == indexcol)
     151          12 :                 return getBaseType(exprType((Node *) lfirst(indexpr_item)));
     152           0 :             indexpr_item = lnext(indexprs, indexpr_item);
     153             :         }
     154             :     }
     155           0 :     elog(ERROR, "wrong number of index expressions");
     156             :     return InvalidOid;          /* keep compiler quiet */
     157             : }
     158             : 
     159             : /* Fill in a SpGistTypeDesc struct with info about the specified data type */
     160             : static void
     161        1242 : fillTypeDesc(SpGistTypeDesc *desc, Oid type)
     162             : {
     163             :     HeapTuple   tp;
     164             :     Form_pg_type typtup;
     165             : 
     166        1242 :     desc->type = type;
     167        1242 :     tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(type));
     168        1242 :     if (!HeapTupleIsValid(tp))
     169           0 :         elog(ERROR, "cache lookup failed for type %u", type);
     170        1242 :     typtup = (Form_pg_type) GETSTRUCT(tp);
     171        1242 :     desc->attlen = typtup->typlen;
     172        1242 :     desc->attbyval = typtup->typbyval;
     173        1242 :     desc->attalign = typtup->typalign;
     174        1242 :     desc->attstorage = typtup->typstorage;
     175        1242 :     ReleaseSysCache(tp);
     176        1242 : }
     177             : 
     178             : /*
     179             :  * Fetch local cache of AM-specific info about the index, initializing it
     180             :  * if necessary
     181             :  */
     182             : SpGistCache *
     183     2670492 : spgGetCache(Relation index)
     184             : {
     185             :     SpGistCache *cache;
     186             : 
     187     2670492 :     if (index->rd_amcache == NULL)
     188             :     {
     189             :         Oid         atttype;
     190             :         spgConfigIn in;
     191             :         FmgrInfo   *procinfo;
     192             : 
     193         404 :         cache = MemoryContextAllocZero(index->rd_indexcxt,
     194             :                                        sizeof(SpGistCache));
     195             : 
     196             :         /* SPGiST must have one key column and can also have INCLUDE columns */
     197             :         Assert(IndexRelationGetNumberOfKeyAttributes(index) == 1);
     198             :         Assert(IndexRelationGetNumberOfAttributes(index) <= INDEX_MAX_KEYS);
     199             : 
     200             :         /*
     201             :          * Get the actual (well, nominal) data type of the key column.  We
     202             :          * pass this to the opclass config function so that polymorphic
     203             :          * opclasses are possible.
     204             :          */
     205         404 :         atttype = GetIndexInputType(index, spgKeyColumn + 1);
     206             : 
     207             :         /* Call the config function to get config info for the opclass */
     208         404 :         in.attType = atttype;
     209             : 
     210         404 :         procinfo = index_getprocinfo(index, 1, SPGIST_CONFIG_PROC);
     211         404 :         FunctionCall2Coll(procinfo,
     212         404 :                           index->rd_indcollation[spgKeyColumn],
     213             :                           PointerGetDatum(&in),
     214         404 :                           PointerGetDatum(&cache->config));
     215             : 
     216             :         /*
     217             :          * If leafType isn't specified, use the declared index column type,
     218             :          * which index.c will have derived from the opclass's opcintype.
     219             :          * (Although we now make spgvalidate.c warn if these aren't the same,
     220             :          * old user-defined opclasses may not set the STORAGE parameter
     221             :          * correctly, so believe leafType if it's given.)
     222             :          */
     223         404 :         if (!OidIsValid(cache->config.leafType))
     224             :         {
     225         374 :             cache->config.leafType =
     226         374 :                 TupleDescAttr(RelationGetDescr(index), spgKeyColumn)->atttypid;
     227             : 
     228             :             /*
     229             :              * If index column type is binary-coercible to atttype (for
     230             :              * example, it's a domain over atttype), treat it as plain atttype
     231             :              * to avoid thinking we need to compress.
     232             :              */
     233         388 :             if (cache->config.leafType != atttype &&
     234          14 :                 IsBinaryCoercible(cache->config.leafType, atttype))
     235          14 :                 cache->config.leafType = atttype;
     236             :         }
     237             : 
     238             :         /* Get the information we need about each relevant datatype */
     239         404 :         fillTypeDesc(&cache->attType, atttype);
     240             : 
     241         404 :         if (cache->config.leafType != atttype)
     242             :         {
     243          30 :             if (!OidIsValid(index_getprocid(index, 1, SPGIST_COMPRESS_PROC)))
     244           0 :                 ereport(ERROR,
     245             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     246             :                          errmsg("compress method must be defined when leaf type is different from input type")));
     247             : 
     248          30 :             fillTypeDesc(&cache->attLeafType, cache->config.leafType);
     249             :         }
     250             :         else
     251             :         {
     252             :             /* Save lookups in this common case */
     253         374 :             cache->attLeafType = cache->attType;
     254             :         }
     255             : 
     256         404 :         fillTypeDesc(&cache->attPrefixType, cache->config.prefixType);
     257         404 :         fillTypeDesc(&cache->attLabelType, cache->config.labelType);
     258             : 
     259             :         /*
     260             :          * Finally, if it's a real index (not a partitioned one), get the
     261             :          * lastUsedPages data from the metapage
     262             :          */
     263         404 :         if (index->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
     264             :         {
     265             :             Buffer      metabuffer;
     266             :             SpGistMetaPageData *metadata;
     267             : 
     268         398 :             metabuffer = ReadBuffer(index, SPGIST_METAPAGE_BLKNO);
     269         398 :             LockBuffer(metabuffer, BUFFER_LOCK_SHARE);
     270             : 
     271         398 :             metadata = SpGistPageGetMeta(BufferGetPage(metabuffer));
     272             : 
     273         398 :             if (metadata->magicNumber != SPGIST_MAGIC_NUMBER)
     274           0 :                 elog(ERROR, "index \"%s\" is not an SP-GiST index",
     275             :                      RelationGetRelationName(index));
     276             : 
     277         398 :             cache->lastUsedPages = metadata->lastUsedPages;
     278             : 
     279         398 :             UnlockReleaseBuffer(metabuffer);
     280             :         }
     281             : 
     282         404 :         index->rd_amcache = (void *) cache;
     283             :     }
     284             :     else
     285             :     {
     286             :         /* assume it's up to date */
     287     2670088 :         cache = (SpGistCache *) index->rd_amcache;
     288             :     }
     289             : 
     290     2670492 :     return cache;
     291             : }
     292             : 
     293             : /*
     294             :  * Compute a tuple descriptor for leaf tuples or index-only-scan result tuples.
     295             :  *
     296             :  * We can use the relcache's tupdesc as-is in many cases, and it's always
     297             :  * OK so far as any INCLUDE columns are concerned.  However, the entry for
     298             :  * the key column has to match leafType in the first case or attType in the
     299             :  * second case.  While the relcache's tupdesc *should* show leafType, this
     300             :  * might not hold for legacy user-defined opclasses, since before v14 they
     301             :  * were not allowed to declare their true storage type in CREATE OPCLASS.
     302             :  * Also, attType can be different from what is in the relcache.
     303             :  *
     304             :  * This function gives back either a pointer to the relcache's tupdesc
     305             :  * if that is suitable, or a palloc'd copy that's been adjusted to match
     306             :  * the specified key column type.  We can avoid doing any catalog lookups
     307             :  * here by insisting that the caller pass an SpGistTypeDesc not just an OID.
     308             :  */
     309             : TupleDesc
     310      244742 : getSpGistTupleDesc(Relation index, SpGistTypeDesc *keyType)
     311             : {
     312             :     TupleDesc   outTupDesc;
     313             :     Form_pg_attribute att;
     314             : 
     315      244742 :     if (keyType->type ==
     316      244742 :         TupleDescAttr(RelationGetDescr(index), spgKeyColumn)->atttypid)
     317      244612 :         outTupDesc = RelationGetDescr(index);
     318             :     else
     319             :     {
     320         130 :         outTupDesc = CreateTupleDescCopy(RelationGetDescr(index));
     321         130 :         att = TupleDescAttr(outTupDesc, spgKeyColumn);
     322             :         /* It's sufficient to update the type-dependent fields of the column */
     323         130 :         att->atttypid = keyType->type;
     324         130 :         att->atttypmod = -1;
     325         130 :         att->attlen = keyType->attlen;
     326         130 :         att->attbyval = keyType->attbyval;
     327         130 :         att->attalign = keyType->attalign;
     328         130 :         att->attstorage = keyType->attstorage;
     329             :         /* We shouldn't need to bother with making these valid: */
     330         130 :         att->attcompression = InvalidCompressionMethod;
     331         130 :         att->attcollation = InvalidOid;
     332             :         /* In case we changed typlen, we'd better reset following offsets */
     333         146 :         for (int i = spgFirstIncludeColumn; i < outTupDesc->natts; i++)
     334          16 :             TupleDescAttr(outTupDesc, i)->attcacheoff = -1;
     335             :     }
     336      244742 :     return outTupDesc;
     337             : }
     338             : 
     339             : /* Initialize SpGistState for working with the given index */
     340             : void
     341      243838 : initSpGistState(SpGistState *state, Relation index)
     342             : {
     343             :     SpGistCache *cache;
     344             : 
     345      243838 :     state->index = index;
     346             : 
     347             :     /* Get cached static information about index */
     348      243838 :     cache = spgGetCache(index);
     349             : 
     350      243838 :     state->config = cache->config;
     351      243838 :     state->attType = cache->attType;
     352      243838 :     state->attLeafType = cache->attLeafType;
     353      243838 :     state->attPrefixType = cache->attPrefixType;
     354      243838 :     state->attLabelType = cache->attLabelType;
     355             : 
     356             :     /* Ensure we have a valid descriptor for leaf tuples */
     357      243838 :     state->leafTupDesc = getSpGistTupleDesc(state->index, &state->attLeafType);
     358             : 
     359             :     /* Make workspace for constructing dead tuples */
     360      243838 :     state->deadTupleStorage = palloc0(SGDTSIZE);
     361             : 
     362             :     /*
     363             :      * Set horizon XID to use in redirection tuples.  Use our own XID if we
     364             :      * have one, else use InvalidTransactionId.  The latter case can happen in
     365             :      * VACUUM or REINDEX CONCURRENTLY, and in neither case would it be okay to
     366             :      * force an XID to be assigned.  VACUUM won't create any redirection
     367             :      * tuples anyway, but REINDEX CONCURRENTLY can.  Fortunately, REINDEX
     368             :      * CONCURRENTLY doesn't mark the index valid until the end, so there could
     369             :      * never be any concurrent scans "in flight" to a redirection tuple it has
     370             :      * inserted.  And it locks out VACUUM until the end, too.  So it's okay
     371             :      * for VACUUM to immediately expire a redirection tuple that contains an
     372             :      * invalid xid.
     373             :      */
     374      243838 :     state->redirectXid = GetTopTransactionIdIfAny();
     375             : 
     376             :     /* Assume we're not in an index build (spgbuild will override) */
     377      243838 :     state->isBuild = false;
     378      243838 : }
     379             : 
     380             : /*
     381             :  * Allocate a new page (either by recycling, or by extending the index file).
     382             :  *
     383             :  * The returned buffer is already pinned and exclusive-locked.
     384             :  * Caller is responsible for initializing the page by calling SpGistInitBuffer.
     385             :  */
     386             : Buffer
     387        6546 : SpGistNewBuffer(Relation index)
     388             : {
     389             :     Buffer      buffer;
     390             : 
     391             :     /* First, try to get a page from FSM */
     392             :     for (;;)
     393           0 :     {
     394        6546 :         BlockNumber blkno = GetFreeIndexPage(index);
     395             : 
     396        6546 :         if (blkno == InvalidBlockNumber)
     397        6538 :             break;              /* nothing known to FSM */
     398             : 
     399             :         /*
     400             :          * The fixed pages shouldn't ever be listed in FSM, but just in case
     401             :          * one is, ignore it.
     402             :          */
     403           8 :         if (SpGistBlockIsFixed(blkno))
     404           0 :             continue;
     405             : 
     406           8 :         buffer = ReadBuffer(index, blkno);
     407             : 
     408             :         /*
     409             :          * We have to guard against the possibility that someone else already
     410             :          * recycled this page; the buffer may be locked if so.
     411             :          */
     412           8 :         if (ConditionalLockBuffer(buffer))
     413             :         {
     414           8 :             Page        page = BufferGetPage(buffer);
     415             : 
     416           8 :             if (PageIsNew(page))
     417           0 :                 return buffer;  /* OK to use, if never initialized */
     418             : 
     419           8 :             if (SpGistPageIsDeleted(page) || PageIsEmpty(page))
     420           8 :                 return buffer;  /* OK to use */
     421             : 
     422           0 :             LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
     423             :         }
     424             : 
     425             :         /* Can't use it, so release buffer and try again */
     426           0 :         ReleaseBuffer(buffer);
     427             :     }
     428             : 
     429        6538 :     buffer = ExtendBufferedRel(BMR_REL(index), MAIN_FORKNUM, NULL,
     430             :                                EB_LOCK_FIRST);
     431             : 
     432        6538 :     return buffer;
     433             : }
     434             : 
     435             : /*
     436             :  * Update index metapage's lastUsedPages info from local cache, if possible
     437             :  *
     438             :  * Updating meta page isn't critical for index working, so
     439             :  * 1 use ConditionalLockBuffer to improve concurrency
     440             :  * 2 don't WAL-log metabuffer changes to decrease WAL traffic
     441             :  */
     442             : void
     443      242866 : SpGistUpdateMetaPage(Relation index)
     444             : {
     445      242866 :     SpGistCache *cache = (SpGistCache *) index->rd_amcache;
     446             : 
     447      242866 :     if (cache != NULL)
     448             :     {
     449             :         Buffer      metabuffer;
     450             : 
     451      242866 :         metabuffer = ReadBuffer(index, SPGIST_METAPAGE_BLKNO);
     452             : 
     453      242866 :         if (ConditionalLockBuffer(metabuffer))
     454             :         {
     455      242858 :             Page        metapage = BufferGetPage(metabuffer);
     456      242858 :             SpGistMetaPageData *metadata = SpGistPageGetMeta(metapage);
     457             : 
     458      242858 :             metadata->lastUsedPages = cache->lastUsedPages;
     459             : 
     460             :             /*
     461             :              * Set pd_lower just past the end of the metadata.  This is
     462             :              * essential, because without doing so, metadata will be lost if
     463             :              * xlog.c compresses the page.  (We must do this here because
     464             :              * pre-v11 versions of PG did not set the metapage's pd_lower
     465             :              * correctly, so a pg_upgraded index might contain the wrong
     466             :              * value.)
     467             :              */
     468      242858 :             ((PageHeader) metapage)->pd_lower =
     469      242858 :                 ((char *) metadata + sizeof(SpGistMetaPageData)) - (char *) metapage;
     470             : 
     471      242858 :             MarkBufferDirty(metabuffer);
     472      242858 :             UnlockReleaseBuffer(metabuffer);
     473             :         }
     474             :         else
     475             :         {
     476           8 :             ReleaseBuffer(metabuffer);
     477             :         }
     478             :     }
     479      242866 : }
     480             : 
     481             : /* Macro to select proper element of lastUsedPages cache depending on flags */
     482             : /* Masking flags with SPGIST_CACHED_PAGES is just for paranoia's sake */
     483             : #define GET_LUP(c, f)  (&(c)->lastUsedPages.cachedPage[((unsigned int) (f)) % SPGIST_CACHED_PAGES])
     484             : 
     485             : /*
     486             :  * Allocate and initialize a new buffer of the type and parity specified by
     487             :  * flags.  The returned buffer is already pinned and exclusive-locked.
     488             :  *
     489             :  * When requesting an inner page, if we get one with the wrong parity,
     490             :  * we just release the buffer and try again.  We will get a different page
     491             :  * because GetFreeIndexPage will have marked the page used in FSM.  The page
     492             :  * is entered in our local lastUsedPages cache, so there's some hope of
     493             :  * making use of it later in this session, but otherwise we rely on VACUUM
     494             :  * to eventually re-enter the page in FSM, making it available for recycling.
     495             :  * Note that such a page does not get marked dirty here, so unless it's used
     496             :  * fairly soon, the buffer will just get discarded and the page will remain
     497             :  * as it was on disk.
     498             :  *
     499             :  * When we return a buffer to the caller, the page is *not* entered into
     500             :  * the lastUsedPages cache; we expect the caller will do so after it's taken
     501             :  * whatever space it will use.  This is because after the caller has used up
     502             :  * some space, the page might have less space than whatever was cached already
     503             :  * so we'd rather not trash the old cache entry.
     504             :  */
     505             : static Buffer
     506        5836 : allocNewBuffer(Relation index, int flags)
     507             : {
     508        5836 :     SpGistCache *cache = spgGetCache(index);
     509        5836 :     uint16      pageflags = 0;
     510             : 
     511        5836 :     if (GBUF_REQ_LEAF(flags))
     512        5730 :         pageflags |= SPGIST_LEAF;
     513        5836 :     if (GBUF_REQ_NULLS(flags))
     514           0 :         pageflags |= SPGIST_NULLS;
     515             : 
     516             :     for (;;)
     517          86 :     {
     518             :         Buffer      buffer;
     519             : 
     520        5922 :         buffer = SpGistNewBuffer(index);
     521        5922 :         SpGistInitBuffer(buffer, pageflags);
     522             : 
     523        5922 :         if (pageflags & SPGIST_LEAF)
     524             :         {
     525             :             /* Leaf pages have no parity concerns, so just use it */
     526        5730 :             return buffer;
     527             :         }
     528             :         else
     529             :         {
     530         192 :             BlockNumber blkno = BufferGetBlockNumber(buffer);
     531         192 :             int         blkFlags = GBUF_INNER_PARITY(blkno);
     532             : 
     533         192 :             if ((flags & GBUF_PARITY_MASK) == blkFlags)
     534             :             {
     535             :                 /* Page has right parity, use it */
     536         106 :                 return buffer;
     537             :             }
     538             :             else
     539             :             {
     540             :                 /* Page has wrong parity, record it in cache and try again */
     541          86 :                 if (pageflags & SPGIST_NULLS)
     542           0 :                     blkFlags |= GBUF_NULLS;
     543          86 :                 cache->lastUsedPages.cachedPage[blkFlags].blkno = blkno;
     544          86 :                 cache->lastUsedPages.cachedPage[blkFlags].freeSpace =
     545          86 :                     PageGetExactFreeSpace(BufferGetPage(buffer));
     546          86 :                 UnlockReleaseBuffer(buffer);
     547             :             }
     548             :         }
     549             :     }
     550             : }
     551             : 
     552             : /*
     553             :  * Get a buffer of the type and parity specified by flags, having at least
     554             :  * as much free space as indicated by needSpace.  We use the lastUsedPages
     555             :  * cache to assign the same buffer previously requested when possible.
     556             :  * The returned buffer is already pinned and exclusive-locked.
     557             :  *
     558             :  * *isNew is set true if the page was initialized here, false if it was
     559             :  * already valid.
     560             :  */
     561             : Buffer
     562       10892 : SpGistGetBuffer(Relation index, int flags, int needSpace, bool *isNew)
     563             : {
     564       10892 :     SpGistCache *cache = spgGetCache(index);
     565             :     SpGistLastUsedPage *lup;
     566             : 
     567             :     /* Bail out if even an empty page wouldn't meet the demand */
     568       10892 :     if (needSpace > SPGIST_PAGE_CAPACITY)
     569           0 :         elog(ERROR, "desired SPGiST tuple size is too big");
     570             : 
     571             :     /*
     572             :      * If possible, increase the space request to include relation's
     573             :      * fillfactor.  This ensures that when we add unrelated tuples to a page,
     574             :      * we try to keep 100-fillfactor% available for adding tuples that are
     575             :      * related to the ones already on it.  But fillfactor mustn't cause an
     576             :      * error for requests that would otherwise be legal.
     577             :      */
     578       10892 :     needSpace += SpGistGetTargetPageFreeSpace(index);
     579       10892 :     needSpace = Min(needSpace, SPGIST_PAGE_CAPACITY);
     580             : 
     581             :     /* Get the cache entry for this flags setting */
     582       10892 :     lup = GET_LUP(cache, flags);
     583             : 
     584             :     /* If we have nothing cached, just turn it over to allocNewBuffer */
     585       10892 :     if (lup->blkno == InvalidBlockNumber)
     586             :     {
     587         182 :         *isNew = true;
     588         182 :         return allocNewBuffer(index, flags);
     589             :     }
     590             : 
     591             :     /* fixed pages should never be in cache */
     592             :     Assert(!SpGistBlockIsFixed(lup->blkno));
     593             : 
     594             :     /* If cached freeSpace isn't enough, don't bother looking at the page */
     595       10710 :     if (lup->freeSpace >= needSpace)
     596             :     {
     597             :         Buffer      buffer;
     598             :         Page        page;
     599             : 
     600        5056 :         buffer = ReadBuffer(index, lup->blkno);
     601             : 
     602        5056 :         if (!ConditionalLockBuffer(buffer))
     603             :         {
     604             :             /*
     605             :              * buffer is locked by another process, so return a new buffer
     606             :              */
     607           0 :             ReleaseBuffer(buffer);
     608           0 :             *isNew = true;
     609           0 :             return allocNewBuffer(index, flags);
     610             :         }
     611             : 
     612        5056 :         page = BufferGetPage(buffer);
     613             : 
     614        5056 :         if (PageIsNew(page) || SpGistPageIsDeleted(page) || PageIsEmpty(page))
     615             :         {
     616             :             /* OK to initialize the page */
     617         186 :             uint16      pageflags = 0;
     618             : 
     619         186 :             if (GBUF_REQ_LEAF(flags))
     620         180 :                 pageflags |= SPGIST_LEAF;
     621         186 :             if (GBUF_REQ_NULLS(flags))
     622           0 :                 pageflags |= SPGIST_NULLS;
     623         186 :             SpGistInitBuffer(buffer, pageflags);
     624         186 :             lup->freeSpace = PageGetExactFreeSpace(page) - needSpace;
     625         186 :             *isNew = true;
     626         186 :             return buffer;
     627             :         }
     628             : 
     629             :         /*
     630             :          * Check that page is of right type and has enough space.  We must
     631             :          * recheck this since our cache isn't necessarily up to date.
     632             :          */
     633        9740 :         if ((GBUF_REQ_LEAF(flags) ? SpGistPageIsLeaf(page) : !SpGistPageIsLeaf(page)) &&
     634        4870 :             (GBUF_REQ_NULLS(flags) ? SpGistPageStoresNulls(page) : !SpGistPageStoresNulls(page)))
     635             :         {
     636        4870 :             int         freeSpace = PageGetExactFreeSpace(page);
     637             : 
     638        4870 :             if (freeSpace >= needSpace)
     639             :             {
     640             :                 /* Success, update freespace info and return the buffer */
     641        4870 :                 lup->freeSpace = freeSpace - needSpace;
     642        4870 :                 *isNew = false;
     643        4870 :                 return buffer;
     644             :             }
     645             :         }
     646             : 
     647             :         /*
     648             :          * fallback to allocation of new buffer
     649             :          */
     650           0 :         UnlockReleaseBuffer(buffer);
     651             :     }
     652             : 
     653             :     /* No success with cache, so return a new buffer */
     654        5654 :     *isNew = true;
     655        5654 :     return allocNewBuffer(index, flags);
     656             : }
     657             : 
     658             : /*
     659             :  * Update lastUsedPages cache when done modifying a page.
     660             :  *
     661             :  * We update the appropriate cache entry if it already contained this page
     662             :  * (its freeSpace is likely obsolete), or if this page has more space than
     663             :  * whatever we had cached.
     664             :  */
     665             : void
     666     2408100 : SpGistSetLastUsedPage(Relation index, Buffer buffer)
     667             : {
     668     2408100 :     SpGistCache *cache = spgGetCache(index);
     669             :     SpGistLastUsedPage *lup;
     670             :     int         freeSpace;
     671     2408100 :     Page        page = BufferGetPage(buffer);
     672     2408100 :     BlockNumber blkno = BufferGetBlockNumber(buffer);
     673             :     int         flags;
     674             : 
     675             :     /* Never enter fixed pages (root pages) in cache, though */
     676     2408100 :     if (SpGistBlockIsFixed(blkno))
     677      805444 :         return;
     678             : 
     679     1602656 :     if (SpGistPageIsLeaf(page))
     680      817594 :         flags = GBUF_LEAF;
     681             :     else
     682      785062 :         flags = GBUF_INNER_PARITY(blkno);
     683     1602656 :     if (SpGistPageStoresNulls(page))
     684           0 :         flags |= GBUF_NULLS;
     685             : 
     686     1602656 :     lup = GET_LUP(cache, flags);
     687             : 
     688     1602656 :     freeSpace = PageGetExactFreeSpace(page);
     689     1602656 :     if (lup->blkno == InvalidBlockNumber || lup->blkno == blkno ||
     690      436600 :         lup->freeSpace < freeSpace)
     691             :     {
     692     1174722 :         lup->blkno = blkno;
     693     1174722 :         lup->freeSpace = freeSpace;
     694             :     }
     695             : }
     696             : 
     697             : /*
     698             :  * Initialize an SPGiST page to empty, with specified flags
     699             :  */
     700             : void
     701        7602 : SpGistInitPage(Page page, uint16 f)
     702             : {
     703             :     SpGistPageOpaque opaque;
     704             : 
     705        7602 :     PageInit(page, BLCKSZ, sizeof(SpGistPageOpaqueData));
     706        7602 :     opaque = SpGistPageGetOpaque(page);
     707        7602 :     opaque->flags = f;
     708        7602 :     opaque->spgist_page_id = SPGIST_PAGE_ID;
     709        7602 : }
     710             : 
     711             : /*
     712             :  * Initialize a buffer's page to empty, with specified flags
     713             :  */
     714             : void
     715        7370 : SpGistInitBuffer(Buffer b, uint16 f)
     716             : {
     717             :     Assert(BufferGetPageSize(b) == BLCKSZ);
     718        7370 :     SpGistInitPage(BufferGetPage(b), f);
     719        7370 : }
     720             : 
     721             : /*
     722             :  * Initialize metadata page
     723             :  */
     724             : void
     725         216 : SpGistInitMetapage(Page page)
     726             : {
     727             :     SpGistMetaPageData *metadata;
     728             :     int         i;
     729             : 
     730         216 :     SpGistInitPage(page, SPGIST_META);
     731         216 :     metadata = SpGistPageGetMeta(page);
     732         216 :     memset(metadata, 0, sizeof(SpGistMetaPageData));
     733         216 :     metadata->magicNumber = SPGIST_MAGIC_NUMBER;
     734             : 
     735             :     /* initialize last-used-page cache to empty */
     736        1944 :     for (i = 0; i < SPGIST_CACHED_PAGES; i++)
     737        1728 :         metadata->lastUsedPages.cachedPage[i].blkno = InvalidBlockNumber;
     738             : 
     739             :     /*
     740             :      * Set pd_lower just past the end of the metadata.  This is essential,
     741             :      * because without doing so, metadata will be lost if xlog.c compresses
     742             :      * the page.
     743             :      */
     744         216 :     ((PageHeader) page)->pd_lower =
     745         216 :         ((char *) metadata + sizeof(SpGistMetaPageData)) - (char *) page;
     746         216 : }
     747             : 
     748             : /*
     749             :  * reloptions processing for SPGiST
     750             :  */
     751             : bytea *
     752         118 : spgoptions(Datum reloptions, bool validate)
     753             : {
     754             :     static const relopt_parse_elt tab[] = {
     755             :         {"fillfactor", RELOPT_TYPE_INT, offsetof(SpGistOptions, fillfactor)},
     756             :     };
     757             : 
     758         118 :     return (bytea *) build_reloptions(reloptions, validate,
     759             :                                       RELOPT_KIND_SPGIST,
     760             :                                       sizeof(SpGistOptions),
     761             :                                       tab, lengthof(tab));
     762             : }
     763             : 
     764             : /*
     765             :  * Get the space needed to store a non-null datum of the indicated type
     766             :  * in an inner tuple (that is, as a prefix or node label).
     767             :  * Note the result is already rounded up to a MAXALIGN boundary.
     768             :  * Here we follow the convention that pass-by-val types are just stored
     769             :  * in their Datum representation (compare memcpyInnerDatum).
     770             :  */
     771             : unsigned int
     772       12314 : SpGistGetInnerTypeSize(SpGistTypeDesc *att, Datum datum)
     773             : {
     774             :     unsigned int size;
     775             : 
     776       12314 :     if (att->attbyval)
     777        6460 :         size = sizeof(Datum);
     778        5854 :     else if (att->attlen > 0)
     779        3968 :         size = att->attlen;
     780             :     else
     781        1886 :         size = VARSIZE_ANY(datum);
     782             : 
     783       12314 :     return MAXALIGN(size);
     784             : }
     785             : 
     786             : /*
     787             :  * Copy the given non-null datum to *target, in the inner-tuple case
     788             :  */
     789             : static void
     790       12314 : memcpyInnerDatum(void *target, SpGistTypeDesc *att, Datum datum)
     791             : {
     792             :     unsigned int size;
     793             : 
     794       12314 :     if (att->attbyval)
     795             :     {
     796        6460 :         memcpy(target, &datum, sizeof(Datum));
     797             :     }
     798             :     else
     799             :     {
     800        5854 :         size = (att->attlen > 0) ? att->attlen : VARSIZE_ANY(datum);
     801        5854 :         memcpy(target, DatumGetPointer(datum), size);
     802             :     }
     803       12314 : }
     804             : 
     805             : /*
     806             :  * Compute space required for a leaf tuple holding the given data.
     807             :  *
     808             :  * This must match the size-calculation portion of spgFormLeafTuple.
     809             :  */
     810             : Size
     811    19458994 : SpGistGetLeafTupleSize(TupleDesc tupleDescriptor,
     812             :                        const Datum *datums, const bool *isnulls)
     813             : {
     814             :     Size        size;
     815             :     Size        data_size;
     816    19458994 :     bool        needs_null_mask = false;
     817    19458994 :     int         natts = tupleDescriptor->natts;
     818             : 
     819             :     /*
     820             :      * Decide whether we need a nulls bitmask.
     821             :      *
     822             :      * If there is only a key attribute (natts == 1), never use a bitmask, for
     823             :      * compatibility with the pre-v14 layout of leaf tuples.  Otherwise, we
     824             :      * need one if any attribute is null.
     825             :      */
     826    19458994 :     if (natts > 1)
     827             :     {
     828     1004074 :         for (int i = 0; i < natts; i++)
     829             :         {
     830      687438 :             if (isnulls[i])
     831             :             {
     832       18254 :                 needs_null_mask = true;
     833       18254 :                 break;
     834             :             }
     835             :         }
     836             :     }
     837             : 
     838             :     /*
     839             :      * Calculate size of the data part; same as for heap tuples.
     840             :      */
     841    19458994 :     data_size = heap_compute_data_size(tupleDescriptor, datums, isnulls);
     842             : 
     843             :     /*
     844             :      * Compute total size.
     845             :      */
     846    19458994 :     size = SGLTHDRSZ(needs_null_mask);
     847    19458994 :     size += data_size;
     848    19458994 :     size = MAXALIGN(size);
     849             : 
     850             :     /*
     851             :      * Ensure that we can replace the tuple with a dead tuple later. This test
     852             :      * is unnecessary when there are any non-null attributes, but be safe.
     853             :      */
     854    19458994 :     if (size < SGDTSIZE)
     855           0 :         size = SGDTSIZE;
     856             : 
     857    19458994 :     return size;
     858             : }
     859             : 
     860             : /*
     861             :  * Construct a leaf tuple containing the given heap TID and datum values
     862             :  */
     863             : SpGistLeafTuple
     864     1527694 : spgFormLeafTuple(SpGistState *state, ItemPointer heapPtr,
     865             :                  const Datum *datums, const bool *isnulls)
     866             : {
     867             :     SpGistLeafTuple tup;
     868     1527694 :     TupleDesc   tupleDescriptor = state->leafTupDesc;
     869             :     Size        size;
     870             :     Size        hoff;
     871             :     Size        data_size;
     872     1527694 :     bool        needs_null_mask = false;
     873     1527694 :     int         natts = tupleDescriptor->natts;
     874             :     char       *tp;             /* ptr to tuple data */
     875     1527694 :     uint16      tupmask = 0;    /* unused heap_fill_tuple output */
     876             : 
     877             :     /*
     878             :      * Decide whether we need a nulls bitmask.
     879             :      *
     880             :      * If there is only a key attribute (natts == 1), never use a bitmask, for
     881             :      * compatibility with the pre-v14 layout of leaf tuples.  Otherwise, we
     882             :      * need one if any attribute is null.
     883             :      */
     884     1527694 :     if (natts > 1)
     885             :     {
     886      425884 :         for (int i = 0; i < natts; i++)
     887             :         {
     888      295466 :             if (isnulls[i])
     889             :             {
     890       11662 :                 needs_null_mask = true;
     891       11662 :                 break;
     892             :             }
     893             :         }
     894             :     }
     895             : 
     896             :     /*
     897             :      * Calculate size of the data part; same as for heap tuples.
     898             :      */
     899     1527694 :     data_size = heap_compute_data_size(tupleDescriptor, datums, isnulls);
     900             : 
     901             :     /*
     902             :      * Compute total size.
     903             :      */
     904     1527694 :     hoff = SGLTHDRSZ(needs_null_mask);
     905     1527694 :     size = hoff + data_size;
     906     1527694 :     size = MAXALIGN(size);
     907             : 
     908             :     /*
     909             :      * Ensure that we can replace the tuple with a dead tuple later. This test
     910             :      * is unnecessary when there are any non-null attributes, but be safe.
     911             :      */
     912     1527694 :     if (size < SGDTSIZE)
     913           0 :         size = SGDTSIZE;
     914             : 
     915             :     /* OK, form the tuple */
     916     1527694 :     tup = (SpGistLeafTuple) palloc0(size);
     917             : 
     918     1527694 :     tup->size = size;
     919     1527694 :     SGLT_SET_NEXTOFFSET(tup, InvalidOffsetNumber);
     920     1527694 :     tup->heapPtr = *heapPtr;
     921             : 
     922     1527694 :     tp = (char *) tup + hoff;
     923             : 
     924     1527694 :     if (needs_null_mask)
     925             :     {
     926             :         bits8      *bp;         /* ptr to null bitmap in tuple */
     927             : 
     928             :         /* Set nullmask presence bit in SpGistLeafTuple header */
     929       11662 :         SGLT_SET_HASNULLMASK(tup, true);
     930             :         /* Fill the data area and null mask */
     931       11662 :         bp = (bits8 *) ((char *) tup + sizeof(SpGistLeafTupleData));
     932       11662 :         heap_fill_tuple(tupleDescriptor, datums, isnulls, tp, data_size,
     933             :                         &tupmask, bp);
     934             :     }
     935     1516032 :     else if (natts > 1 || !isnulls[spgKeyColumn])
     936             :     {
     937             :         /* Fill data area only */
     938     1515960 :         heap_fill_tuple(tupleDescriptor, datums, isnulls, tp, data_size,
     939             :                         &tupmask, (bits8 *) NULL);
     940             :     }
     941             :     /* otherwise we have no data, nor a bitmap, to fill */
     942             : 
     943     1527694 :     return tup;
     944             : }
     945             : 
     946             : /*
     947             :  * Construct a node (to go into an inner tuple) containing the given label
     948             :  *
     949             :  * Note that the node's downlink is just set invalid here.  Caller will fill
     950             :  * it in later.
     951             :  */
     952             : SpGistNodeTuple
     953       40498 : spgFormNodeTuple(SpGistState *state, Datum label, bool isnull)
     954             : {
     955             :     SpGistNodeTuple tup;
     956             :     unsigned int size;
     957       40498 :     unsigned short infomask = 0;
     958             : 
     959             :     /* compute space needed (note result is already maxaligned) */
     960       40498 :     size = SGNTHDRSZ;
     961       40498 :     if (!isnull)
     962        5770 :         size += SpGistGetInnerTypeSize(&state->attLabelType, label);
     963             : 
     964             :     /*
     965             :      * Here we make sure that the size will fit in the field reserved for it
     966             :      * in t_info.
     967             :      */
     968       40498 :     if ((size & INDEX_SIZE_MASK) != size)
     969           0 :         ereport(ERROR,
     970             :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
     971             :                  errmsg("index row requires %zu bytes, maximum size is %zu",
     972             :                         (Size) size, (Size) INDEX_SIZE_MASK)));
     973             : 
     974       40498 :     tup = (SpGistNodeTuple) palloc0(size);
     975             : 
     976       40498 :     if (isnull)
     977       34728 :         infomask |= INDEX_NULL_MASK;
     978             :     /* we don't bother setting the INDEX_VAR_MASK bit */
     979       40498 :     infomask |= size;
     980       40498 :     tup->t_info = infomask;
     981             : 
     982             :     /* The TID field will be filled in later */
     983       40498 :     ItemPointerSetInvalid(&tup->t_tid);
     984             : 
     985       40498 :     if (!isnull)
     986        5770 :         memcpyInnerDatum(SGNTDATAPTR(tup), &state->attLabelType, label);
     987             : 
     988       40498 :     return tup;
     989             : }
     990             : 
     991             : /*
     992             :  * Construct an inner tuple containing the given prefix and node array
     993             :  */
     994             : SpGistInnerTuple
     995        8538 : spgFormInnerTuple(SpGistState *state, bool hasPrefix, Datum prefix,
     996             :                   int nNodes, SpGistNodeTuple *nodes)
     997             : {
     998             :     SpGistInnerTuple tup;
     999             :     unsigned int size;
    1000             :     unsigned int prefixSize;
    1001             :     int         i;
    1002             :     char       *ptr;
    1003             : 
    1004             :     /* Compute size needed */
    1005        8538 :     if (hasPrefix)
    1006        6544 :         prefixSize = SpGistGetInnerTypeSize(&state->attPrefixType, prefix);
    1007             :     else
    1008        1994 :         prefixSize = 0;
    1009             : 
    1010        8538 :     size = SGITHDRSZ + prefixSize;
    1011             : 
    1012             :     /* Note: we rely on node tuple sizes to be maxaligned already */
    1013       59308 :     for (i = 0; i < nNodes; i++)
    1014       50770 :         size += IndexTupleSize(nodes[i]);
    1015             : 
    1016             :     /*
    1017             :      * Ensure that we can replace the tuple with a dead tuple later.  This
    1018             :      * test is unnecessary given current tuple layouts, but let's be safe.
    1019             :      */
    1020        8538 :     if (size < SGDTSIZE)
    1021           0 :         size = SGDTSIZE;
    1022             : 
    1023             :     /*
    1024             :      * Inner tuple should be small enough to fit on a page
    1025             :      */
    1026        8538 :     if (size > SPGIST_PAGE_CAPACITY - sizeof(ItemIdData))
    1027           0 :         ereport(ERROR,
    1028             :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    1029             :                  errmsg("SP-GiST inner tuple size %zu exceeds maximum %zu",
    1030             :                         (Size) size,
    1031             :                         SPGIST_PAGE_CAPACITY - sizeof(ItemIdData)),
    1032             :                  errhint("Values larger than a buffer page cannot be indexed.")));
    1033             : 
    1034             :     /*
    1035             :      * Check for overflow of header fields --- probably can't fail if the
    1036             :      * above succeeded, but let's be paranoid
    1037             :      */
    1038        8538 :     if (size > SGITMAXSIZE ||
    1039        8538 :         prefixSize > SGITMAXPREFIXSIZE ||
    1040             :         nNodes > SGITMAXNNODES)
    1041           0 :         elog(ERROR, "SPGiST inner tuple header field is too small");
    1042             : 
    1043             :     /* OK, form the tuple */
    1044        8538 :     tup = (SpGistInnerTuple) palloc0(size);
    1045             : 
    1046        8538 :     tup->nNodes = nNodes;
    1047        8538 :     tup->prefixSize = prefixSize;
    1048        8538 :     tup->size = size;
    1049             : 
    1050        8538 :     if (hasPrefix)
    1051        6544 :         memcpyInnerDatum(SGITDATAPTR(tup), &state->attPrefixType, prefix);
    1052             : 
    1053        8538 :     ptr = (char *) SGITNODEPTR(tup);
    1054             : 
    1055       59308 :     for (i = 0; i < nNodes; i++)
    1056             :     {
    1057       50770 :         SpGistNodeTuple node = nodes[i];
    1058             : 
    1059       50770 :         memcpy(ptr, node, IndexTupleSize(node));
    1060       50770 :         ptr += IndexTupleSize(node);
    1061             :     }
    1062             : 
    1063        8538 :     return tup;
    1064             : }
    1065             : 
    1066             : /*
    1067             :  * Construct a "dead" tuple to replace a tuple being deleted.
    1068             :  *
    1069             :  * The state can be SPGIST_REDIRECT, SPGIST_DEAD, or SPGIST_PLACEHOLDER.
    1070             :  * For a REDIRECT tuple, a pointer (blkno+offset) must be supplied, and
    1071             :  * the xid field is filled in automatically.
    1072             :  *
    1073             :  * This is called in critical sections, so we don't use palloc; the tuple
    1074             :  * is built in preallocated storage.  It should be copied before another
    1075             :  * call with different parameters can occur.
    1076             :  */
    1077             : SpGistDeadTuple
    1078       12868 : spgFormDeadTuple(SpGistState *state, int tupstate,
    1079             :                  BlockNumber blkno, OffsetNumber offnum)
    1080             : {
    1081       12868 :     SpGistDeadTuple tuple = (SpGistDeadTuple) state->deadTupleStorage;
    1082             : 
    1083       12868 :     tuple->tupstate = tupstate;
    1084       12868 :     tuple->size = SGDTSIZE;
    1085       12868 :     SGLT_SET_NEXTOFFSET(tuple, InvalidOffsetNumber);
    1086             : 
    1087       12868 :     if (tupstate == SPGIST_REDIRECT)
    1088             :     {
    1089        2352 :         ItemPointerSet(&tuple->pointer, blkno, offnum);
    1090        2352 :         tuple->xid = state->redirectXid;
    1091             :     }
    1092             :     else
    1093             :     {
    1094       10516 :         ItemPointerSetInvalid(&tuple->pointer);
    1095       10516 :         tuple->xid = InvalidTransactionId;
    1096             :     }
    1097             : 
    1098       12868 :     return tuple;
    1099             : }
    1100             : 
    1101             : /*
    1102             :  * Convert an SPGiST leaf tuple into Datum/isnull arrays.
    1103             :  *
    1104             :  * The caller must allocate sufficient storage for the output arrays.
    1105             :  * (INDEX_MAX_KEYS entries should be enough.)
    1106             :  */
    1107             : void
    1108       62608 : spgDeformLeafTuple(SpGistLeafTuple tup, TupleDesc tupleDescriptor,
    1109             :                    Datum *datums, bool *isnulls, bool keyColumnIsNull)
    1110             : {
    1111       62608 :     bool        hasNullsMask = SGLT_GET_HASNULLMASK(tup);
    1112             :     char       *tp;             /* ptr to tuple data */
    1113             :     bits8      *bp;             /* ptr to null bitmap in tuple */
    1114             : 
    1115       62608 :     if (keyColumnIsNull && tupleDescriptor->natts == 1)
    1116             :     {
    1117             :         /*
    1118             :          * Trivial case: there is only the key attribute and we're in a nulls
    1119             :          * tree.  The hasNullsMask bit in the tuple header should not be set
    1120             :          * (and thus we can't use index_deform_tuple_internal), but
    1121             :          * nonetheless the result is NULL.
    1122             :          *
    1123             :          * Note: currently this is dead code, because noplace calls this when
    1124             :          * there is only the key attribute.  But we should cover the case.
    1125             :          */
    1126             :         Assert(!hasNullsMask);
    1127             : 
    1128           0 :         datums[spgKeyColumn] = (Datum) 0;
    1129           0 :         isnulls[spgKeyColumn] = true;
    1130           0 :         return;
    1131             :     }
    1132             : 
    1133       62608 :     tp = (char *) tup + SGLTHDRSZ(hasNullsMask);
    1134       62608 :     bp = (bits8 *) ((char *) tup + sizeof(SpGistLeafTupleData));
    1135             : 
    1136       62608 :     index_deform_tuple_internal(tupleDescriptor,
    1137             :                                 datums, isnulls,
    1138             :                                 tp, bp, hasNullsMask);
    1139             : 
    1140             :     /*
    1141             :      * Key column isnull value from the tuple should be consistent with
    1142             :      * keyColumnIsNull flag from the caller.
    1143             :      */
    1144             :     Assert(keyColumnIsNull == isnulls[spgKeyColumn]);
    1145             : }
    1146             : 
    1147             : /*
    1148             :  * Extract the label datums of the nodes within innerTuple
    1149             :  *
    1150             :  * Returns NULL if label datums are NULLs
    1151             :  */
    1152             : Datum *
    1153    18680134 : spgExtractNodeLabels(SpGistState *state, SpGistInnerTuple innerTuple)
    1154             : {
    1155             :     Datum      *nodeLabels;
    1156             :     int         i;
    1157             :     SpGistNodeTuple node;
    1158             : 
    1159             :     /* Either all the labels must be NULL, or none. */
    1160    18680134 :     node = SGITNODEPTR(innerTuple);
    1161    18680134 :     if (IndexTupleHasNulls(node))
    1162             :     {
    1163   100684004 :         SGITITERATE(innerTuple, i, node)
    1164             :         {
    1165    82237518 :             if (!IndexTupleHasNulls(node))
    1166           0 :                 elog(ERROR, "some but not all node labels are null in SPGiST inner tuple");
    1167             :         }
    1168             :         /* They're all null, so just return NULL */
    1169    18446486 :         return NULL;
    1170             :     }
    1171             :     else
    1172             :     {
    1173      233648 :         nodeLabels = (Datum *) palloc(sizeof(Datum) * innerTuple->nNodes);
    1174     2678410 :         SGITITERATE(innerTuple, i, node)
    1175             :         {
    1176     2444762 :             if (IndexTupleHasNulls(node))
    1177           0 :                 elog(ERROR, "some but not all node labels are null in SPGiST inner tuple");
    1178     2444762 :             nodeLabels[i] = SGNTDATUM(node, state);
    1179             :         }
    1180      233648 :         return nodeLabels;
    1181             :     }
    1182             : }
    1183             : 
    1184             : /*
    1185             :  * Add a new item to the page, replacing a PLACEHOLDER item if possible.
    1186             :  * Return the location it's inserted at, or InvalidOffsetNumber on failure.
    1187             :  *
    1188             :  * If startOffset isn't NULL, we start searching for placeholders at
    1189             :  * *startOffset, and update that to the next place to search.  This is just
    1190             :  * an optimization for repeated insertions.
    1191             :  *
    1192             :  * If errorOK is false, we throw error when there's not enough room,
    1193             :  * rather than returning InvalidOffsetNumber.
    1194             :  */
    1195             : OffsetNumber
    1196     1618148 : SpGistPageAddNewItem(SpGistState *state, Page page, Item item, Size size,
    1197             :                      OffsetNumber *startOffset, bool errorOK)
    1198             : {
    1199     1618148 :     SpGistPageOpaque opaque = SpGistPageGetOpaque(page);
    1200             :     OffsetNumber i,
    1201             :                 maxoff,
    1202             :                 offnum;
    1203             : 
    1204     1618148 :     if (opaque->nPlaceholder > 0 &&
    1205      462278 :         PageGetExactFreeSpace(page) + SGDTSIZE >= MAXALIGN(size))
    1206             :     {
    1207             :         /* Try to replace a placeholder */
    1208      462278 :         maxoff = PageGetMaxOffsetNumber(page);
    1209      462278 :         offnum = InvalidOffsetNumber;
    1210             : 
    1211             :         for (;;)
    1212             :         {
    1213      462278 :             if (startOffset && *startOffset != InvalidOffsetNumber)
    1214      115026 :                 i = *startOffset;
    1215             :             else
    1216      347252 :                 i = FirstOffsetNumber;
    1217    31712578 :             for (; i <= maxoff; i++)
    1218             :             {
    1219    31712578 :                 SpGistDeadTuple it = (SpGistDeadTuple) PageGetItem(page,
    1220             :                                                                    PageGetItemId(page, i));
    1221             : 
    1222    31712578 :                 if (it->tupstate == SPGIST_PLACEHOLDER)
    1223             :                 {
    1224      462278 :                     offnum = i;
    1225      462278 :                     break;
    1226             :                 }
    1227             :             }
    1228             : 
    1229             :             /* Done if we found a placeholder */
    1230      462278 :             if (offnum != InvalidOffsetNumber)
    1231      462278 :                 break;
    1232             : 
    1233           0 :             if (startOffset && *startOffset != InvalidOffsetNumber)
    1234             :             {
    1235             :                 /* Hint was no good, re-search from beginning */
    1236           0 :                 *startOffset = InvalidOffsetNumber;
    1237           0 :                 continue;
    1238             :             }
    1239             : 
    1240             :             /* Hmm, no placeholder found? */
    1241           0 :             opaque->nPlaceholder = 0;
    1242           0 :             break;
    1243             :         }
    1244             : 
    1245      462278 :         if (offnum != InvalidOffsetNumber)
    1246             :         {
    1247             :             /* Replace the placeholder tuple */
    1248      462278 :             PageIndexTupleDelete(page, offnum);
    1249             : 
    1250      462278 :             offnum = PageAddItem(page, item, size, offnum, false, false);
    1251             : 
    1252             :             /*
    1253             :              * We should not have failed given the size check at the top of
    1254             :              * the function, but test anyway.  If we did fail, we must PANIC
    1255             :              * because we've already deleted the placeholder tuple, and
    1256             :              * there's no other way to keep the damage from getting to disk.
    1257             :              */
    1258      462278 :             if (offnum != InvalidOffsetNumber)
    1259             :             {
    1260             :                 Assert(opaque->nPlaceholder > 0);
    1261      462278 :                 opaque->nPlaceholder--;
    1262      462278 :                 if (startOffset)
    1263      117666 :                     *startOffset = offnum + 1;
    1264             :             }
    1265             :             else
    1266           0 :                 elog(PANIC, "failed to add item of size %zu to SPGiST index page",
    1267             :                      size);
    1268             : 
    1269      462278 :             return offnum;
    1270             :         }
    1271             :     }
    1272             : 
    1273             :     /* No luck in replacing a placeholder, so just add it to the page */
    1274     1155870 :     offnum = PageAddItem(page, item, size,
    1275             :                          InvalidOffsetNumber, false, false);
    1276             : 
    1277     1155870 :     if (offnum == InvalidOffsetNumber && !errorOK)
    1278           0 :         elog(ERROR, "failed to add item of size %zu to SPGiST index page",
    1279             :              size);
    1280             : 
    1281     1155870 :     return offnum;
    1282             : }
    1283             : 
    1284             : /*
    1285             :  *  spgproperty() -- Check boolean properties of indexes.
    1286             :  *
    1287             :  * This is optional for most AMs, but is required for SP-GiST because the core
    1288             :  * property code doesn't support AMPROP_DISTANCE_ORDERABLE.
    1289             :  */
    1290             : bool
    1291         186 : spgproperty(Oid index_oid, int attno,
    1292             :             IndexAMProperty prop, const char *propname,
    1293             :             bool *res, bool *isnull)
    1294             : {
    1295             :     Oid         opclass,
    1296             :                 opfamily,
    1297             :                 opcintype;
    1298             :     CatCList   *catlist;
    1299             :     int         i;
    1300             : 
    1301             :     /* Only answer column-level inquiries */
    1302         186 :     if (attno == 0)
    1303          66 :         return false;
    1304             : 
    1305         120 :     switch (prop)
    1306             :     {
    1307          12 :         case AMPROP_DISTANCE_ORDERABLE:
    1308          12 :             break;
    1309         108 :         default:
    1310         108 :             return false;
    1311             :     }
    1312             : 
    1313             :     /*
    1314             :      * Currently, SP-GiST distance-ordered scans require that there be a
    1315             :      * distance operator in the opclass with the default types. So we assume
    1316             :      * that if such an operator exists, then there's a reason for it.
    1317             :      */
    1318             : 
    1319             :     /* First we need to know the column's opclass. */
    1320          12 :     opclass = get_index_column_opclass(index_oid, attno);
    1321          12 :     if (!OidIsValid(opclass))
    1322             :     {
    1323           0 :         *isnull = true;
    1324           0 :         return true;
    1325             :     }
    1326             : 
    1327             :     /* Now look up the opclass family and input datatype. */
    1328          12 :     if (!get_opclass_opfamily_and_input_type(opclass, &opfamily, &opcintype))
    1329             :     {
    1330           0 :         *isnull = true;
    1331           0 :         return true;
    1332             :     }
    1333             : 
    1334             :     /* And now we can check whether the operator is provided. */
    1335          12 :     catlist = SearchSysCacheList1(AMOPSTRATEGY,
    1336             :                                   ObjectIdGetDatum(opfamily));
    1337             : 
    1338          12 :     *res = false;
    1339             : 
    1340         102 :     for (i = 0; i < catlist->n_members; i++)
    1341             :     {
    1342          96 :         HeapTuple   amoptup = &catlist->members[i]->tuple;
    1343          96 :         Form_pg_amop amopform = (Form_pg_amop) GETSTRUCT(amoptup);
    1344             : 
    1345          96 :         if (amopform->amoppurpose == AMOP_ORDER &&
    1346           6 :             (amopform->amoplefttype == opcintype ||
    1347           6 :              amopform->amoprighttype == opcintype) &&
    1348           6 :             opfamily_can_sort_type(amopform->amopsortfamily,
    1349             :                                    get_op_rettype(amopform->amopopr)))
    1350             :         {
    1351           6 :             *res = true;
    1352           6 :             break;
    1353             :         }
    1354             :     }
    1355             : 
    1356          12 :     ReleaseSysCacheList(catlist);
    1357             : 
    1358          12 :     *isnull = false;
    1359             : 
    1360          12 :     return true;
    1361             : }

Generated by: LCOV version 1.14