LCOV - differential code coverage report
Current view: top level - src/backend/access/gin - ginutil.c (source / functions) Coverage Total Hit UBC GNC CBC DCB
Current: 0e5ff9b9b45a657aea12440478dc002e9b01f138 vs 0123ce131fca454009439dfa3b2266d1d40737d7 Lines: 88.2 % 221 195 26 7 188 67
Current Date: 2026-03-14 14:10:32 -0400 Functions: 92.9 % 14 13 1 3 10 2
Baseline: lcov-20260315-024220-baseline Branches: 68.9 % 103 71 32 71 10
Baseline Date: 2026-03-14 15:27:56 +0100 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 100.0 % 1 1 1
(30,360] days: 100.0 % 6 6 6
(360..) days: 87.9 % 214 188 26 188
Function coverage date bins:
(360..) days: 92.9 % 14 13 1 3 10
Branch coverage date bins:
(360..) days: 68.9 % 103 71 32 71

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  *
                                  3                 :                :  * ginutil.c
                                  4                 :                :  *    Utility routines for the Postgres inverted index access method.
                                  5                 :                :  *
                                  6                 :                :  *
                                  7                 :                :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
                                  8                 :                :  * Portions Copyright (c) 1994, Regents of the University of California
                                  9                 :                :  *
                                 10                 :                :  * IDENTIFICATION
                                 11                 :                :  *          src/backend/access/gin/ginutil.c
                                 12                 :                :  *-------------------------------------------------------------------------
                                 13                 :                :  */
                                 14                 :                : 
                                 15                 :                : #include "postgres.h"
                                 16                 :                : 
                                 17                 :                : #include "access/gin_private.h"
                                 18                 :                : #include "access/ginxlog.h"
                                 19                 :                : #include "access/reloptions.h"
                                 20                 :                : #include "access/xloginsert.h"
                                 21                 :                : #include "catalog/pg_collation.h"
                                 22                 :                : #include "catalog/pg_type.h"
                                 23                 :                : #include "commands/progress.h"
                                 24                 :                : #include "commands/vacuum.h"
                                 25                 :                : #include "miscadmin.h"
                                 26                 :                : #include "storage/indexfsm.h"
                                 27                 :                : #include "utils/builtins.h"
                                 28                 :                : #include "utils/index_selfuncs.h"
                                 29                 :                : #include "utils/rel.h"
                                 30                 :                : #include "utils/typcache.h"
                                 31                 :                : 
                                 32                 :                : 
                                 33                 :                : /*
                                 34                 :                :  * GIN handler function: return IndexAmRoutine with access method parameters
                                 35                 :                :  * and callbacks.
                                 36                 :                :  */
                                 37                 :                : Datum
 3710 tgl@sss.pgh.pa.us          38                 :CBC        2101 : ginhandler(PG_FUNCTION_ARGS)
                                 39                 :                : {
                                 40                 :                :     static const IndexAmRoutine amroutine = {
                                 41                 :                :         .type = T_IndexAmRoutine,
                                 42                 :                :         .amstrategies = 0,
                                 43                 :                :         .amsupport = GINNProcs,
                                 44                 :                :         .amoptsprocnum = GIN_OPTIONS_PROC,
                                 45                 :                :         .amcanorder = false,
                                 46                 :                :         .amcanorderbyop = false,
                                 47                 :                :         .amcanhash = false,
                                 48                 :                :         .amconsistentequality = false,
                                 49                 :                :         .amconsistentordering = false,
                                 50                 :                :         .amcanbackward = false,
                                 51                 :                :         .amcanunique = false,
                                 52                 :                :         .amcanmulticol = true,
                                 53                 :                :         .amoptionalkey = true,
                                 54                 :                :         .amsearcharray = false,
                                 55                 :                :         .amsearchnulls = false,
                                 56                 :                :         .amstorage = true,
                                 57                 :                :         .amclusterable = false,
                                 58                 :                :         .ampredlocks = true,
                                 59                 :                :         .amcanparallel = false,
                                 60                 :                :         .amcanbuildparallel = true,
                                 61                 :                :         .amcaninclude = false,
                                 62                 :                :         .amusemaintenanceworkmem = true,
                                 63                 :                :         .amsummarizing = false,
                                 64                 :                :         .amparallelvacuumoptions =
                                 65                 :                :         VACUUM_OPTION_PARALLEL_BULKDEL | VACUUM_OPTION_PARALLEL_CLEANUP,
                                 66                 :                :         .amkeytype = InvalidOid,
                                 67                 :                : 
                                 68                 :                :         .ambuild = ginbuild,
                                 69                 :                :         .ambuildempty = ginbuildempty,
                                 70                 :                :         .aminsert = gininsert,
                                 71                 :                :         .aminsertcleanup = NULL,
                                 72                 :                :         .ambulkdelete = ginbulkdelete,
                                 73                 :                :         .amvacuumcleanup = ginvacuumcleanup,
                                 74                 :                :         .amcanreturn = NULL,
                                 75                 :                :         .amcostestimate = gincostestimate,
                                 76                 :                :         .amgettreeheight = NULL,
                                 77                 :                :         .amoptions = ginoptions,
                                 78                 :                :         .amproperty = NULL,
                                 79                 :                :         .ambuildphasename = ginbuildphasename,
                                 80                 :                :         .amvalidate = ginvalidate,
                                 81                 :                :         .amadjustmembers = ginadjustmembers,
                                 82                 :                :         .ambeginscan = ginbeginscan,
                                 83                 :                :         .amrescan = ginrescan,
                                 84                 :                :         .amgettuple = NULL,
                                 85                 :                :         .amgetbitmap = gingetbitmap,
                                 86                 :                :         .amendscan = ginendscan,
                                 87                 :                :         .ammarkpos = NULL,
                                 88                 :                :         .amrestrpos = NULL,
                                 89                 :                :         .amestimateparallelscan = NULL,
                                 90                 :                :         .aminitparallelscan = NULL,
                                 91                 :                :         .amparallelrescan = NULL,
                                 92                 :                :     };
                                 93                 :                : 
   75 tgl@sss.pgh.pa.us          94                 :GNC        2101 :     PG_RETURN_POINTER(&amroutine);
                                 95                 :                : }
                                 96                 :                : 
                                 97                 :                : /*
                                 98                 :                :  * initGinState: fill in an empty GinState struct to describe the index
                                 99                 :                :  *
                                100                 :                :  * Note: assorted subsidiary data is allocated in the CurrentMemoryContext.
                                101                 :                :  */
                                102                 :                : void
 7102 bruce@momjian.us          103                 :CBC        2748 : initGinState(GinState *state, Relation index)
                                104                 :                : {
 5546 tgl@sss.pgh.pa.us         105                 :           2748 :     TupleDesc   origTupdesc = RelationGetDescr(index);
                                106                 :                :     int         i;
                                107                 :                : 
                                108   [ +  -  +  -  :           2748 :     MemSet(state, 0, sizeof(GinState));
                                     +  -  -  +  -  
                                                 - ]
                                109                 :                : 
                                110                 :           2748 :     state->index = index;
 1649 michael@paquier.xyz       111                 :           2748 :     state->oneCol = (origTupdesc->natts == 1);
 5546 tgl@sss.pgh.pa.us         112                 :           2748 :     state->origTupdesc = origTupdesc;
                                113                 :                : 
                                114         [ +  + ]:           5642 :     for (i = 0; i < origTupdesc->natts; i++)
                                115                 :                :     {
 3129 andres@anarazel.de        116                 :           2894 :         Form_pg_attribute attr = TupleDescAttr(origTupdesc, i);
                                117                 :                : 
 5546 tgl@sss.pgh.pa.us         118         [ +  + ]:           2894 :         if (state->oneCol)
                                119                 :           2602 :             state->tupdesc[i] = state->origTupdesc;
                                120                 :                :         else
                                121                 :                :         {
 2672 andres@anarazel.de        122                 :            292 :             state->tupdesc[i] = CreateTemplateTupleDesc(2);
                                123                 :                : 
 5546 tgl@sss.pgh.pa.us         124                 :            292 :             TupleDescInitEntry(state->tupdesc[i], (AttrNumber) 1, NULL,
                                125                 :                :                                INT2OID, -1, 0);
                                126                 :            292 :             TupleDescInitEntry(state->tupdesc[i], (AttrNumber) 2, NULL,
                                127                 :                :                                attr->atttypid,
                                128                 :                :                                attr->atttypmod,
 3129 andres@anarazel.de        129                 :            292 :                                attr->attndims);
 5468 tgl@sss.pgh.pa.us         130                 :            292 :             TupleDescInitEntryCollation(state->tupdesc[i], (AttrNumber) 2,
                                131                 :                :                                         attr->attcollation);
                                132                 :                :         }
                                133                 :                : 
                                134                 :                :         /*
                                135                 :                :          * If the compare proc isn't specified in the opclass definition, look
                                136                 :                :          * up the index key type's default btree comparator.
                                137                 :                :          */
 3457                           138         [ +  + ]:           2894 :         if (index_getprocid(index, i + 1, GIN_COMPARE_PROC) != InvalidOid)
                                139                 :                :         {
                                140                 :           1371 :             fmgr_info_copy(&(state->compareFn[i]),
                                141                 :           1371 :                            index_getprocinfo(index, i + 1, GIN_COMPARE_PROC),
                                142                 :                :                            CurrentMemoryContext);
                                143                 :                :         }
                                144                 :                :         else
                                145                 :                :         {
                                146                 :                :             TypeCacheEntry *typentry;
                                147                 :                : 
 3129 andres@anarazel.de        148                 :           1523 :             typentry = lookup_type_cache(attr->atttypid,
                                149                 :                :                                          TYPECACHE_CMP_PROC_FINFO);
 3457 tgl@sss.pgh.pa.us         150         [ -  + ]:           1523 :             if (!OidIsValid(typentry->cmp_proc_finfo.fn_oid))
 3457 tgl@sss.pgh.pa.us         151         [ #  # ]:UBC           0 :                 ereport(ERROR,
                                152                 :                :                         (errcode(ERRCODE_UNDEFINED_FUNCTION),
                                153                 :                :                          errmsg("could not identify a comparison function for type %s",
                                154                 :                :                                 format_type_be(attr->atttypid))));
 3457 tgl@sss.pgh.pa.us         155                 :CBC        1523 :             fmgr_info_copy(&(state->compareFn[i]),
                                156                 :                :                            &(typentry->cmp_proc_finfo),
                                157                 :                :                            CurrentMemoryContext);
                                158                 :                :         }
                                159                 :                : 
                                160                 :                :         /* Opclass must always provide extract procs */
 6456                           161                 :           2894 :         fmgr_info_copy(&(state->extractValueFn[i]),
 6121 bruce@momjian.us          162                 :           2894 :                        index_getprocinfo(index, i + 1, GIN_EXTRACTVALUE_PROC),
                                163                 :                :                        CurrentMemoryContext);
 6456 tgl@sss.pgh.pa.us         164                 :           2894 :         fmgr_info_copy(&(state->extractQueryFn[i]),
 6121 bruce@momjian.us          165                 :           2894 :                        index_getprocinfo(index, i + 1, GIN_EXTRACTQUERY_PROC),
                                166                 :                :                        CurrentMemoryContext);
                                167                 :                : 
                                168                 :                :         /*
                                169                 :                :          * Check opclass capability to do tri-state or binary logic consistent
                                170                 :                :          * check.
                                171                 :                :          */
 4386 heikki.linnakangas@i      172         [ +  + ]:           2894 :         if (index_getprocid(index, i + 1, GIN_TRICONSISTENT_PROC) != InvalidOid)
                                173                 :                :         {
                                174                 :           2507 :             fmgr_info_copy(&(state->triConsistentFn[i]),
 3189 tgl@sss.pgh.pa.us         175                 :           2507 :                            index_getprocinfo(index, i + 1, GIN_TRICONSISTENT_PROC),
                                176                 :                :                            CurrentMemoryContext);
                                177                 :                :         }
                                178                 :                : 
 4386 heikki.linnakangas@i      179         [ +  - ]:           2894 :         if (index_getprocid(index, i + 1, GIN_CONSISTENT_PROC) != InvalidOid)
                                180                 :                :         {
                                181                 :           2894 :             fmgr_info_copy(&(state->consistentFn[i]),
 3189 tgl@sss.pgh.pa.us         182                 :           2894 :                            index_getprocinfo(index, i + 1, GIN_CONSISTENT_PROC),
                                183                 :                :                            CurrentMemoryContext);
                                184                 :                :         }
                                185                 :                : 
 4386 heikki.linnakangas@i      186         [ -  + ]:           2894 :         if (state->consistentFn[i].fn_oid == InvalidOid &&
 4386 heikki.linnakangas@i      187         [ #  # ]:UBC           0 :             state->triConsistentFn[i].fn_oid == InvalidOid)
                                188                 :                :         {
                                189         [ #  # ]:              0 :             elog(ERROR, "missing GIN support function (%d or %d) for attribute %d of index \"%s\"",
                                190                 :                :                  GIN_CONSISTENT_PROC, GIN_TRICONSISTENT_PROC,
                                191                 :                :                  i + 1, RelationGetRelationName(index));
                                192                 :                :         }
                                193                 :                : 
                                194                 :                :         /*
                                195                 :                :          * Check opclass capability to do partial match.
                                196                 :                :          */
 6121 bruce@momjian.us          197         [ +  + ]:CBC        2894 :         if (index_getprocid(index, i + 1, GIN_COMPARE_PARTIAL_PROC) != InvalidOid)
                                198                 :                :         {
 6456 tgl@sss.pgh.pa.us         199                 :            495 :             fmgr_info_copy(&(state->comparePartialFn[i]),
 3189                           200                 :            495 :                            index_getprocinfo(index, i + 1, GIN_COMPARE_PARTIAL_PROC),
                                201                 :                :                            CurrentMemoryContext);
 6456                           202                 :            495 :             state->canPartialMatch[i] = true;
                                203                 :                :         }
                                204                 :                :         else
                                205                 :                :         {
                                206                 :           2399 :             state->canPartialMatch[i] = false;
                                207                 :                :         }
                                208                 :                : 
                                209                 :                :         /*
                                210                 :                :          * If the index column has a specified collation, we should honor that
                                211                 :                :          * while doing comparisons.  However, we may have a collatable storage
                                212                 :                :          * type for a noncollatable indexed data type (for instance, hstore
                                213                 :                :          * uses text index entries).  If there's no index collation then
                                214                 :                :          * specify default collation in case the support functions need
                                215                 :                :          * collation.  This is harmless if the support functions don't care
                                216                 :                :          * about collation, so we just do it unconditionally.  (We could
                                217                 :                :          * alternatively call get_typcollation, but that seems like expensive
                                218                 :                :          * overkill --- there aren't going to be any cases where a GIN storage
                                219                 :                :          * type has a nondefault collation.)
                                220                 :                :          */
 5451                           221         [ +  + ]:           2894 :         if (OidIsValid(index->rd_indcollation[i]))
 5441                           222                 :            204 :             state->supportCollation[i] = index->rd_indcollation[i];
                                223                 :                :         else
                                224                 :           2690 :             state->supportCollation[i] = DEFAULT_COLLATION_OID;
                                225                 :                :     }
 6456                           226                 :           2748 : }
                                227                 :                : 
                                228                 :                : /*
                                229                 :                :  * Extract attribute (column) number of stored entry from GIN tuple
                                230                 :                :  */
                                231                 :                : OffsetNumber
                                232                 :        8614439 : gintuple_get_attrnum(GinState *ginstate, IndexTuple tuple)
                                233                 :                : {
                                234                 :                :     OffsetNumber colN;
                                235                 :                : 
 5546                           236         [ +  + ]:        8614439 :     if (ginstate->oneCol)
                                237                 :                :     {
                                238                 :                :         /* column number is not stored explicitly */
                                239                 :        4284934 :         colN = FirstOffsetNumber;
                                240                 :                :     }
                                241                 :                :     else
                                242                 :                :     {
                                243                 :                :         Datum       res;
                                244                 :                :         bool        isnull;
                                245                 :                : 
                                246                 :                :         /*
                                247                 :                :          * First attribute is always int16, so we can safely use any tuple
                                248                 :                :          * descriptor to obtain first attribute of tuple
                                249                 :                :          */
 6456                           250                 :        4329505 :         res = index_getattr(tuple, FirstOffsetNumber, ginstate->tupdesc[0],
                                251                 :                :                             &isnull);
                                252         [ -  + ]:        4329505 :         Assert(!isnull);
                                253                 :                : 
                                254                 :        4329505 :         colN = DatumGetUInt16(res);
 6121 bruce@momjian.us          255   [ +  -  -  + ]:        4329505 :         Assert(colN >= FirstOffsetNumber && colN <= ginstate->origTupdesc->natts);
                                256                 :                :     }
                                257                 :                : 
 6456 tgl@sss.pgh.pa.us         258                 :        8614439 :     return colN;
                                259                 :                : }
                                260                 :                : 
                                261                 :                : /*
                                262                 :                :  * Extract stored datum (and possible null category) from GIN tuple
                                263                 :                :  */
                                264                 :                : Datum
 5546                           265                 :        6450899 : gintuple_get_key(GinState *ginstate, IndexTuple tuple,
                                266                 :                :                  GinNullCategory *category)
                                267                 :                : {
                                268                 :                :     Datum       res;
                                269                 :                :     bool        isnull;
                                270                 :                : 
 6121 bruce@momjian.us          271         [ +  + ]:        6450899 :     if (ginstate->oneCol)
                                272                 :                :     {
                                273                 :                :         /*
                                274                 :                :          * Single column index doesn't store attribute numbers in tuples
                                275                 :                :          */
 6456 tgl@sss.pgh.pa.us         276                 :        4286508 :         res = index_getattr(tuple, FirstOffsetNumber, ginstate->origTupdesc,
                                277                 :                :                             &isnull);
                                278                 :                :     }
                                279                 :                :     else
                                280                 :                :     {
                                281                 :                :         /*
                                282                 :                :          * Since the datum type depends on which index column it's from, we
                                283                 :                :          * must be careful to use the right tuple descriptor here.
                                284                 :                :          */
                                285                 :        2164391 :         OffsetNumber colN = gintuple_get_attrnum(ginstate, tuple);
                                286                 :                : 
                                287                 :        2164391 :         res = index_getattr(tuple, OffsetNumberNext(FirstOffsetNumber),
                                288                 :        2164391 :                             ginstate->tupdesc[colN - 1],
                                289                 :                :                             &isnull);
                                290                 :                :     }
                                291                 :                : 
 5546                           292         [ +  + ]:        6450899 :     if (isnull)
                                293         [ +  + ]:            900 :         *category = GinGetNullCategory(tuple, ginstate);
                                294                 :                :     else
                                295                 :        6449999 :         *category = GIN_CAT_NORM_KEY;
                                296                 :                : 
 6456                           297                 :        6450899 :     return res;
                                298                 :                : }
                                299                 :                : 
                                300                 :                : /*
                                301                 :                :  * Allocate a new page (either by recycling, or by extending the index file)
                                302                 :                :  * The returned buffer is already pinned and exclusive-locked
                                303                 :                :  * Caller is responsible for initializing the page by calling GinInitBuffer
                                304                 :                :  */
                                305                 :                : Buffer
 7102 bruce@momjian.us          306                 :           4653 : GinNewBuffer(Relation index)
                                307                 :                : {
                                308                 :                :     Buffer      buffer;
                                309                 :                : 
                                310                 :                :     /* First, try to get a page from FSM */
                                311                 :                :     for (;;)
 7102 bruce@momjian.us          312                 :UBC           0 :     {
 6375 heikki.linnakangas@i      313                 :CBC        4653 :         BlockNumber blkno = GetFreeIndexPage(index);
                                314                 :                : 
 7257 teodor@sigaev.ru          315         [ +  + ]:           4653 :         if (blkno == InvalidBlockNumber)
                                316                 :           4600 :             break;
                                317                 :                : 
                                318                 :             53 :         buffer = ReadBuffer(index, blkno);
                                319                 :                : 
                                320                 :                :         /*
                                321                 :                :          * We have to guard against the possibility that someone else already
                                322                 :                :          * recycled this page; the buffer may be locked if so.
                                323                 :                :          */
 7102 bruce@momjian.us          324         [ +  - ]:             53 :         if (ConditionalLockBuffer(buffer))
                                325                 :                :         {
 2649 akorotkov@postgresql      326         [ +  - ]:             53 :             if (GinPageIsRecyclable(BufferGetPage(buffer)))
 7102 bruce@momjian.us          327                 :             53 :                 return buffer;  /* OK to use */
                                328                 :                : 
 7257 teodor@sigaev.ru          329                 :UBC           0 :             LockBuffer(buffer, GIN_UNLOCK);
                                330                 :                :         }
                                331                 :                : 
                                332                 :                :         /* Can't use it, so release buffer and try again */
                                333                 :              0 :         ReleaseBuffer(buffer);
                                334                 :                :     }
                                335                 :                : 
                                336                 :                :     /* Must extend the file */
  935 tmunro@postgresql.or      337                 :CBC        4600 :     buffer = ExtendBufferedRel(BMR_REL(index), MAIN_FORKNUM, NULL,
                                338                 :                :                                EB_LOCK_FIRST);
                                339                 :                : 
 7257 teodor@sigaev.ru          340                 :           4600 :     return buffer;
                                341                 :                : }
                                342                 :                : 
                                343                 :                : void
 7102 bruce@momjian.us          344                 :          31560 : GinInitPage(Page page, uint32 f, Size pageSize)
                                345                 :                : {
                                346                 :                :     GinPageOpaque opaque;
                                347                 :                : 
 7257 teodor@sigaev.ru          348                 :          31560 :     PageInit(page, pageSize, sizeof(GinPageOpaqueData));
                                349                 :                : 
                                350                 :          31560 :     opaque = GinPageGetOpaque(page);
 7102 bruce@momjian.us          351                 :          31560 :     opaque->flags = f;
 7257 teodor@sigaev.ru          352                 :          31560 :     opaque->rightlink = InvalidBlockNumber;
                                353                 :          31560 : }
                                354                 :                : 
                                355                 :                : void
 7102 bruce@momjian.us          356                 :           2045 : GinInitBuffer(Buffer b, uint32 f)
                                357                 :                : {
 3616 kgrittn@postgresql.o      358                 :           2045 :     GinInitPage(BufferGetPage(b), f, BufferGetPageSize(b));
 7257 teodor@sigaev.ru          359                 :           2045 : }
                                360                 :                : 
                                361                 :                : void
 6200 tgl@sss.pgh.pa.us         362                 :          24165 : GinInitMetabuffer(Buffer b)
                                363                 :                : {
                                364                 :                :     GinMetaPageData *metadata;
 3616 kgrittn@postgresql.o      365                 :          24165 :     Page        page = BufferGetPage(b);
                                366                 :                : 
 6200 tgl@sss.pgh.pa.us         367                 :          24165 :     GinInitPage(page, GIN_META, BufferGetPageSize(b));
                                368                 :                : 
                                369                 :          24165 :     metadata = GinPageGetMeta(page);
                                370                 :                : 
                                371                 :          24165 :     metadata->head = metadata->tail = InvalidBlockNumber;
                                372                 :          24165 :     metadata->tailFreeSize = 0;
                                373                 :          24165 :     metadata->nPendingPages = 0;
                                374                 :          24165 :     metadata->nPendingHeapTuples = 0;
 5628                           375                 :          24165 :     metadata->nTotalPages = 0;
                                376                 :          24165 :     metadata->nEntryPages = 0;
                                377                 :          24165 :     metadata->nDataPages = 0;
                                378                 :          24165 :     metadata->nEntries = 0;
 5546                           379                 :          24165 :     metadata->ginVersion = GIN_CURRENT_VERSION;
                                380                 :                : 
                                381                 :                :     /*
                                382                 :                :      * Set pd_lower just past the end of the metadata.  This is essential,
                                383                 :                :      * because without doing so, metadata will be lost if xlog.c compresses
                                384                 :                :      * the page.
                                385                 :                :      */
 3055                           386                 :          24165 :     ((PageHeader) page)->pd_lower =
                                387                 :          24165 :         ((char *) metadata + sizeof(GinMetaPageData)) - (char *) page;
 6200                           388                 :          24165 : }
                                389                 :                : 
                                390                 :                : /*
                                391                 :                :  * Support for sorting key datums in ginExtractEntries
                                392                 :                :  *
                                393                 :                :  * Note: we only have to worry about null and not-null keys here;
                                394                 :                :  * ginExtractEntries never generates more than one placeholder null,
                                395                 :                :  * so it doesn't have to sort those.
                                396                 :                :  */
                                397                 :                : typedef struct
                                398                 :                : {
                                399                 :                :     Datum       datum;
                                400                 :                :     bool        isnull;
                                401                 :                : } keyEntryData;
                                402                 :                : 
                                403                 :                : typedef struct
                                404                 :                : {
                                405                 :                :     FmgrInfo   *cmpDatumFunc;
                                406                 :                :     Oid         collation;
                                407                 :                :     bool        haveDups;
                                408                 :                : } cmpEntriesArg;
                                409                 :                : 
                                410                 :                : static int
 5546                           411                 :        2071278 : cmpEntries(const void *a, const void *b, void *arg)
                                412                 :                : {
                                413                 :        2071278 :     const keyEntryData *aa = (const keyEntryData *) a;
                                414                 :        2071278 :     const keyEntryData *bb = (const keyEntryData *) b;
                                415                 :        2071278 :     cmpEntriesArg *data = (cmpEntriesArg *) arg;
                                416                 :                :     int         res;
                                417                 :                : 
                                418         [ -  + ]:        2071278 :     if (aa->isnull)
                                419                 :                :     {
 5546 tgl@sss.pgh.pa.us         420         [ #  # ]:UBC           0 :         if (bb->isnull)
                                421                 :              0 :             res = 0;            /* NULL "=" NULL */
                                422                 :                :         else
                                423                 :              0 :             res = 1;            /* NULL ">" not-NULL */
                                424                 :                :     }
 5546 tgl@sss.pgh.pa.us         425         [ -  + ]:CBC     2071278 :     else if (bb->isnull)
 5546 tgl@sss.pgh.pa.us         426                 :UBC           0 :         res = -1;               /* not-NULL "<" NULL */
                                427                 :                :     else
 5451 tgl@sss.pgh.pa.us         428                 :CBC     2071278 :         res = DatumGetInt32(FunctionCall2Coll(data->cmpDatumFunc,
                                429                 :                :                                               data->collation,
                                430                 :        2071278 :                                               aa->datum, bb->datum));
                                431                 :                : 
                                432                 :                :     /*
                                433                 :                :      * Detect if we have any duplicates.  If there are equal keys, qsort must
                                434                 :                :      * compare them at some point, else it wouldn't know whether one should go
                                435                 :                :      * before or after the other.
                                436                 :                :      */
 7102 bruce@momjian.us          437         [ +  + ]:        2071278 :     if (res == 0)
 5546 tgl@sss.pgh.pa.us         438                 :          34310 :         data->haveDups = true;
                                439                 :                : 
 7257 teodor@sigaev.ru          440                 :        2071278 :     return res;
                                441                 :                : }
                                442                 :                : 
                                443                 :                : 
                                444                 :                : /*
                                445                 :                :  * Extract the index key values from an indexable item
                                446                 :                :  *
                                447                 :                :  * The resulting key values are sorted, and any duplicates are removed.
                                448                 :                :  * This avoids generating redundant index entries.
                                449                 :                :  */
                                450                 :                : Datum *
 5546 tgl@sss.pgh.pa.us         451                 :         690810 : ginExtractEntries(GinState *ginstate, OffsetNumber attnum,
                                452                 :                :                   Datum value, bool isNull,
                                453                 :                :                   int32 *nentries, GinNullCategory **categories)
                                454                 :                : {
                                455                 :                :     Datum      *entries;
                                456                 :                :     bool       *nullFlags;
                                457                 :                :     int32       i;
                                458                 :                : 
                                459                 :                :     /*
                                460                 :                :      * We don't call the extractValueFn on a null item.  Instead generate a
                                461                 :                :      * placeholder.
                                462                 :                :      */
                                463         [ +  + ]:         690810 :     if (isNull)
                                464                 :                :     {
                                465                 :           3311 :         *nentries = 1;
   95 michael@paquier.xyz       466                 :GNC        3311 :         entries = palloc_object(Datum);
 5546 tgl@sss.pgh.pa.us         467                 :CBC        3311 :         entries[0] = (Datum) 0;
   95 michael@paquier.xyz       468                 :GNC        3311 :         *categories = palloc_object(GinNullCategory);
 5546 tgl@sss.pgh.pa.us         469                 :CBC        3311 :         (*categories)[0] = GIN_CAT_NULL_ITEM;
                                470                 :           3311 :         return entries;
                                471                 :                :     }
                                472                 :                : 
                                473                 :                :     /* OK, call the opclass's extractValueFn */
                                474                 :         687499 :     nullFlags = NULL;           /* in case extractValue doesn't set it */
                                475                 :                :     entries = (Datum *)
 5441                           476                 :        1374998 :         DatumGetPointer(FunctionCall3Coll(&ginstate->extractValueFn[attnum - 1],
 3189                           477                 :         687499 :                                           ginstate->supportCollation[attnum - 1],
                                478                 :                :                                           value,
                                479                 :                :                                           PointerGetDatum(nentries),
                                480                 :                :                                           PointerGetDatum(&nullFlags)));
                                481                 :                : 
                                482                 :                :     /*
                                483                 :                :      * Generate a placeholder if the item contained no keys.
                                484                 :                :      */
 5546                           485   [ +  +  +  + ]:         687499 :     if (entries == NULL || *nentries <= 0)
                                486                 :                :     {
                                487                 :            888 :         *nentries = 1;
   95 michael@paquier.xyz       488                 :GNC         888 :         entries = palloc_object(Datum);
 5546 tgl@sss.pgh.pa.us         489                 :CBC         888 :         entries[0] = (Datum) 0;
   95 michael@paquier.xyz       490                 :GNC         888 :         *categories = palloc_object(GinNullCategory);
 5546 tgl@sss.pgh.pa.us         491                 :CBC         888 :         (*categories)[0] = GIN_CAT_EMPTY_ITEM;
                                492                 :            888 :         return entries;
                                493                 :                :     }
                                494                 :                : 
                                495                 :                :     /*
                                496                 :                :      * If the extractValueFn didn't create a nullFlags array, create one,
                                497                 :                :      * assuming that everything's non-null.
                                498                 :                :      */
                                499         [ +  + ]:         686611 :     if (nullFlags == NULL)
                                500                 :         117323 :         nullFlags = (bool *) palloc0(*nentries * sizeof(bool));
                                501                 :                : 
                                502                 :                :     /*
                                503                 :                :      * If there's more than one key, sort and unique-ify.
                                504                 :                :      *
                                505                 :                :      * XXX Using qsort here is notationally painful, and the overhead is
                                506                 :                :      * pretty bad too.  For small numbers of keys it'd likely be better to use
                                507                 :                :      * a simple insertion sort.
                                508                 :                :      */
                                509         [ +  + ]:         686611 :     if (*nentries > 1)
                                510                 :                :     {
                                511                 :                :         keyEntryData *keydata;
                                512                 :                :         cmpEntriesArg arg;
                                513                 :                : 
   95 michael@paquier.xyz       514                 :GNC      294882 :         keydata = palloc_array(keyEntryData, *nentries);
 5546 tgl@sss.pgh.pa.us         515         [ +  + ]:CBC     1644500 :         for (i = 0; i < *nentries; i++)
                                516                 :                :         {
                                517                 :        1349618 :             keydata[i].datum = entries[i];
                                518                 :        1349618 :             keydata[i].isnull = nullFlags[i];
                                519                 :                :         }
                                520                 :                : 
                                521                 :         294882 :         arg.cmpDatumFunc = &ginstate->compareFn[attnum - 1];
 5441                           522                 :         294882 :         arg.collation = ginstate->supportCollation[attnum - 1];
 5546                           523                 :         294882 :         arg.haveDups = false;
                                524                 :         294882 :         qsort_arg(keydata, *nentries, sizeof(keyEntryData),
                                525                 :                :                   cmpEntries, &arg);
                                526                 :                : 
                                527         [ +  + ]:         294882 :         if (arg.haveDups)
                                528                 :                :         {
                                529                 :                :             /* there are duplicates, must get rid of 'em */
                                530                 :                :             int32       j;
                                531                 :                : 
                                532                 :          13445 :             entries[0] = keydata[0].datum;
                                533                 :          13445 :             nullFlags[0] = keydata[0].isnull;
                                534                 :          13445 :             j = 1;
                                535         [ +  + ]:         101039 :             for (i = 1; i < *nentries; i++)
                                536                 :                :             {
 5453 bruce@momjian.us          537         [ +  + ]:          87594 :                 if (cmpEntries(&keydata[i - 1], &keydata[i], &arg) != 0)
                                538                 :                :                 {
 5546 tgl@sss.pgh.pa.us         539                 :          70948 :                     entries[j] = keydata[i].datum;
                                540                 :          70948 :                     nullFlags[j] = keydata[i].isnull;
                                541                 :          70948 :                     j++;
                                542                 :                :                 }
                                543                 :                :             }
                                544                 :          13445 :             *nentries = j;
                                545                 :                :         }
                                546                 :                :         else
                                547                 :                :         {
                                548                 :                :             /* easy, no duplicates */
                                549         [ +  + ]:        1530016 :             for (i = 0; i < *nentries; i++)
                                550                 :                :             {
                                551                 :        1248579 :                 entries[i] = keydata[i].datum;
                                552                 :        1248579 :                 nullFlags[i] = keydata[i].isnull;
                                553                 :                :             }
                                554                 :                :         }
                                555                 :                : 
                                556                 :         294882 :         pfree(keydata);
                                557                 :                :     }
                                558                 :                : 
                                559                 :                :     /*
                                560                 :                :      * Create GinNullCategory representation from nullFlags.
                                561                 :                :      */
 3001 peter_e@gmx.net           562                 :         686611 :     *categories = (GinNullCategory *) palloc0(*nentries * sizeof(GinNullCategory));
                                563         [ +  + ]:        2411312 :     for (i = 0; i < *nentries; i++)
                                564                 :        1724701 :         (*categories)[i] = (nullFlags[i] ? GIN_CAT_NULL_KEY : GIN_CAT_NORM_KEY);
                                565                 :                : 
 7257 teodor@sigaev.ru          566                 :         686611 :     return entries;
                                567                 :                : }
                                568                 :                : 
                                569                 :                : bytea *
 3710 tgl@sss.pgh.pa.us         570                 :            311 : ginoptions(Datum reloptions, bool validate)
                                571                 :                : {
                                572                 :                :     static const relopt_parse_elt tab[] = {
                                573                 :                :         {"fastupdate", RELOPT_TYPE_BOOL, offsetof(GinOptions, useFastUpdate)},
                                574                 :                :         {"gin_pending_list_limit", RELOPT_TYPE_INT, offsetof(GinOptions,
                                575                 :                :                                                              pendingListCleanupSize)}
                                576                 :                :     };
                                577                 :                : 
 2322 michael@paquier.xyz       578                 :            311 :     return (bytea *) build_reloptions(reloptions, validate,
                                579                 :                :                                       RELOPT_KIND_GIN,
                                580                 :                :                                       sizeof(GinOptions),
                                581                 :                :                                       tab, lengthof(tab));
                                582                 :                : }
                                583                 :                : 
                                584                 :                : /*
                                585                 :                :  * Fetch index's statistical data into *stats
                                586                 :                :  *
                                587                 :                :  * Note: in the result, nPendingPages can be trusted to be up-to-date,
                                588                 :                :  * as can ginVersion; but the other fields are as of the last VACUUM.
                                589                 :                :  */
                                590                 :                : void
 5628 tgl@sss.pgh.pa.us         591                 :           1296 : ginGetStats(Relation index, GinStatsData *stats)
                                592                 :                : {
                                593                 :                :     Buffer      metabuffer;
                                594                 :                :     Page        metapage;
                                595                 :                :     GinMetaPageData *metadata;
                                596                 :                : 
                                597                 :           1296 :     metabuffer = ReadBuffer(index, GIN_METAPAGE_BLKNO);
                                598                 :           1296 :     LockBuffer(metabuffer, GIN_SHARE);
 3616 kgrittn@postgresql.o      599                 :           1296 :     metapage = BufferGetPage(metabuffer);
 5628 tgl@sss.pgh.pa.us         600                 :           1296 :     metadata = GinPageGetMeta(metapage);
                                601                 :                : 
                                602                 :           1296 :     stats->nPendingPages = metadata->nPendingPages;
                                603                 :           1296 :     stats->nTotalPages = metadata->nTotalPages;
                                604                 :           1296 :     stats->nEntryPages = metadata->nEntryPages;
                                605                 :           1296 :     stats->nDataPages = metadata->nDataPages;
                                606                 :           1296 :     stats->nEntries = metadata->nEntries;
 5546                           607                 :           1296 :     stats->ginVersion = metadata->ginVersion;
                                608                 :                : 
 5628                           609                 :           1296 :     UnlockReleaseBuffer(metabuffer);
                                610                 :           1296 : }
                                611                 :                : 
                                612                 :                : /*
                                613                 :                :  * Write the given statistics to the index's metapage
                                614                 :                :  *
                                615                 :                :  * Note: nPendingPages and ginVersion are *not* copied over
                                616                 :                :  */
                                617                 :                : void
 2538 heikki.linnakangas@i      618                 :            233 : ginUpdateStats(Relation index, const GinStatsData *stats, bool is_build)
                                619                 :                : {
                                620                 :                :     Buffer      metabuffer;
                                621                 :                :     Page        metapage;
                                622                 :                :     GinMetaPageData *metadata;
                                623                 :                : 
 5628 tgl@sss.pgh.pa.us         624                 :            233 :     metabuffer = ReadBuffer(index, GIN_METAPAGE_BLKNO);
                                625                 :            233 :     LockBuffer(metabuffer, GIN_EXCLUSIVE);
 3616 kgrittn@postgresql.o      626                 :            233 :     metapage = BufferGetPage(metabuffer);
 5628 tgl@sss.pgh.pa.us         627                 :            233 :     metadata = GinPageGetMeta(metapage);
                                628                 :                : 
                                629                 :            233 :     START_CRIT_SECTION();
                                630                 :                : 
                                631                 :            233 :     metadata->nTotalPages = stats->nTotalPages;
                                632                 :            233 :     metadata->nEntryPages = stats->nEntryPages;
                                633                 :            233 :     metadata->nDataPages = stats->nDataPages;
                                634                 :            233 :     metadata->nEntries = stats->nEntries;
                                635                 :                : 
                                636                 :                :     /*
                                637                 :                :      * Set pd_lower just past the end of the metadata.  This is essential,
                                638                 :                :      * because without doing so, metadata will be lost if xlog.c compresses
                                639                 :                :      * the page.  (We must do this here because pre-v11 versions of PG did not
                                640                 :                :      * set the metapage's pd_lower correctly, so a pg_upgraded index might
                                641                 :                :      * contain the wrong value.)
                                642                 :                :      */
 3055                           643                 :            233 :     ((PageHeader) metapage)->pd_lower =
                                644                 :            233 :         ((char *) metadata + sizeof(GinMetaPageData)) - (char *) metapage;
                                645                 :                : 
 5628                           646                 :            233 :     MarkBufferDirty(metabuffer);
                                647                 :                : 
 2538 heikki.linnakangas@i      648   [ +  +  +  +  :            233 :     if (RelationNeedsWAL(index) && !is_build)
                                     +  +  +  +  +  
                                                 + ]
                                649                 :                :     {
                                650                 :                :         XLogRecPtr  recptr;
                                651                 :                :         ginxlogUpdateMeta data;
                                652                 :                : 
 1348 rhaas@postgresql.org      653                 :             25 :         data.locator = index->rd_locator;
 5628 tgl@sss.pgh.pa.us         654                 :             25 :         data.ntuples = 0;
                                655                 :             25 :         data.newRightlink = data.prevTail = InvalidBlockNumber;
                                656                 :             25 :         memcpy(&data.metadata, metadata, sizeof(GinMetaPageData));
                                657                 :                : 
 4133 heikki.linnakangas@i      658                 :             25 :         XLogBeginInsert();
  397 peter@eisentraut.org      659                 :             25 :         XLogRegisterData(&data, sizeof(ginxlogUpdateMeta));
 3055 tgl@sss.pgh.pa.us         660                 :             25 :         XLogRegisterBuffer(0, metabuffer, REGBUF_WILL_INIT | REGBUF_STANDARD);
                                661                 :                : 
 4133 heikki.linnakangas@i      662                 :             25 :         recptr = XLogInsert(RM_GIN_ID, XLOG_GIN_UPDATE_META_PAGE);
 5628 tgl@sss.pgh.pa.us         663                 :             25 :         PageSetLSN(metapage, recptr);
                                664                 :                :     }
                                665                 :                : 
                                666         [ -  + ]:            233 :     END_CRIT_SECTION();
                                667                 :                : 
   24 michael@paquier.xyz       668                 :GNC         233 :     UnlockReleaseBuffer(metabuffer);
 5628 tgl@sss.pgh.pa.us         669                 :CBC         233 : }
                                670                 :                : 
                                671                 :                : /*
                                672                 :                :  *  ginbuildphasename() -- Return name of index build phase.
                                673                 :                :  */
                                674                 :                : char *
  377 tomas.vondra@postgre      675                 :UBC           0 : ginbuildphasename(int64 phasenum)
                                676                 :                : {
                                677   [ #  #  #  #  :              0 :     switch (phasenum)
                                           #  #  # ]
                                678                 :                :     {
                                679                 :              0 :         case PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE:
                                680                 :              0 :             return "initializing";
                                681                 :              0 :         case PROGRESS_GIN_PHASE_INDEXBUILD_TABLESCAN:
                                682                 :              0 :             return "scanning table";
                                683                 :              0 :         case PROGRESS_GIN_PHASE_PERFORMSORT_1:
                                684                 :              0 :             return "sorting tuples (workers)";
                                685                 :              0 :         case PROGRESS_GIN_PHASE_MERGE_1:
                                686                 :              0 :             return "merging tuples (workers)";
                                687                 :              0 :         case PROGRESS_GIN_PHASE_PERFORMSORT_2:
                                688                 :              0 :             return "sorting tuples";
                                689                 :              0 :         case PROGRESS_GIN_PHASE_MERGE_2:
                                690                 :              0 :             return "merging tuples";
                                691                 :              0 :         default:
                                692                 :              0 :             return NULL;
                                693                 :                :     }
                                694                 :                : }
        

Generated by: LCOV version 2.4-beta