LCOV - code coverage report
Current view: top level - src/backend/utils/adt - misc.c (source / functions) Hit Total Coverage
Test: PostgreSQL 14devel Lines: 199 285 69.8 %
Date: 2021-01-26 02:06:48 Functions: 17 19 89.5 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * misc.c
       4             :  *
       5             :  *
       6             :  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
       7             :  * Portions Copyright (c) 1994, Regents of the University of California
       8             :  *
       9             :  *
      10             :  * IDENTIFICATION
      11             :  *    src/backend/utils/adt/misc.c
      12             :  *
      13             :  *-------------------------------------------------------------------------
      14             :  */
      15             : #include "postgres.h"
      16             : 
      17             : #include <sys/file.h>
      18             : #include <dirent.h>
      19             : #include <fcntl.h>
      20             : #include <math.h>
      21             : #include <unistd.h>
      22             : 
      23             : #include "access/sysattr.h"
      24             : #include "access/table.h"
      25             : #include "catalog/catalog.h"
      26             : #include "catalog/pg_tablespace.h"
      27             : #include "catalog/pg_type.h"
      28             : #include "commands/dbcommands.h"
      29             : #include "commands/tablespace.h"
      30             : #include "common/keywords.h"
      31             : #include "funcapi.h"
      32             : #include "miscadmin.h"
      33             : #include "parser/scansup.h"
      34             : #include "pgstat.h"
      35             : #include "postmaster/syslogger.h"
      36             : #include "rewrite/rewriteHandler.h"
      37             : #include "storage/fd.h"
      38             : #include "tcop/tcopprot.h"
      39             : #include "utils/builtins.h"
      40             : #include "utils/lsyscache.h"
      41             : #include "utils/ruleutils.h"
      42             : #include "utils/timestamp.h"
      43             : 
      44             : /*
      45             :  * Common subroutine for num_nulls() and num_nonnulls().
      46             :  * Returns true if successful, false if function should return NULL.
      47             :  * If successful, total argument count and number of nulls are
      48             :  * returned into *nargs and *nulls.
      49             :  */
      50             : static bool
      51          80 : count_nulls(FunctionCallInfo fcinfo,
      52             :             int32 *nargs, int32 *nulls)
      53             : {
      54          80 :     int32       count = 0;
      55             :     int         i;
      56             : 
      57             :     /* Did we get a VARIADIC array argument, or separate arguments? */
      58          80 :     if (get_fn_expr_variadic(fcinfo->flinfo))
      59             :     {
      60             :         ArrayType  *arr;
      61             :         int         ndims,
      62             :                     nitems,
      63             :                    *dims;
      64             :         bits8      *bitmap;
      65             : 
      66             :         Assert(PG_NARGS() == 1);
      67             : 
      68             :         /*
      69             :          * If we get a null as VARIADIC array argument, we can't say anything
      70             :          * useful about the number of elements, so return NULL.  This behavior
      71             :          * is consistent with other variadic functions - see concat_internal.
      72             :          */
      73          40 :         if (PG_ARGISNULL(0))
      74           8 :             return false;
      75             : 
      76             :         /*
      77             :          * Non-null argument had better be an array.  We assume that any call
      78             :          * context that could let get_fn_expr_variadic return true will have
      79             :          * checked that a VARIADIC-labeled parameter actually is an array.  So
      80             :          * it should be okay to just Assert that it's an array rather than
      81             :          * doing a full-fledged error check.
      82             :          */
      83             :         Assert(OidIsValid(get_base_element_type(get_fn_expr_argtype(fcinfo->flinfo, 0))));
      84             : 
      85             :         /* OK, safe to fetch the array value */
      86          32 :         arr = PG_GETARG_ARRAYTYPE_P(0);
      87             : 
      88             :         /* Count the array elements */
      89          32 :         ndims = ARR_NDIM(arr);
      90          32 :         dims = ARR_DIMS(arr);
      91          32 :         nitems = ArrayGetNItems(ndims, dims);
      92             : 
      93             :         /* Count those that are NULL */
      94          32 :         bitmap = ARR_NULLBITMAP(arr);
      95          32 :         if (bitmap)
      96             :         {
      97          16 :             int         bitmask = 1;
      98             : 
      99         848 :             for (i = 0; i < nitems; i++)
     100             :             {
     101         832 :                 if ((*bitmap & bitmask) == 0)
     102          16 :                     count++;
     103             : 
     104         832 :                 bitmask <<= 1;
     105         832 :                 if (bitmask == 0x100)
     106             :                 {
     107          96 :                     bitmap++;
     108          96 :                     bitmask = 1;
     109             :                 }
     110             :             }
     111             :         }
     112             : 
     113          32 :         *nargs = nitems;
     114          32 :         *nulls = count;
     115             :     }
     116             :     else
     117             :     {
     118             :         /* Separate arguments, so just count 'em */
     119         136 :         for (i = 0; i < PG_NARGS(); i++)
     120             :         {
     121          96 :             if (PG_ARGISNULL(i))
     122          56 :                 count++;
     123             :         }
     124             : 
     125          40 :         *nargs = PG_NARGS();
     126          40 :         *nulls = count;
     127             :     }
     128             : 
     129          72 :     return true;
     130             : }
     131             : 
     132             : /*
     133             :  * num_nulls()
     134             :  *  Count the number of NULL arguments
     135             :  */
     136             : Datum
     137          40 : pg_num_nulls(PG_FUNCTION_ARGS)
     138             : {
     139             :     int32       nargs,
     140             :                 nulls;
     141             : 
     142          40 :     if (!count_nulls(fcinfo, &nargs, &nulls))
     143           4 :         PG_RETURN_NULL();
     144             : 
     145          36 :     PG_RETURN_INT32(nulls);
     146             : }
     147             : 
     148             : /*
     149             :  * num_nonnulls()
     150             :  *  Count the number of non-NULL arguments
     151             :  */
     152             : Datum
     153          40 : pg_num_nonnulls(PG_FUNCTION_ARGS)
     154             : {
     155             :     int32       nargs,
     156             :                 nulls;
     157             : 
     158          40 :     if (!count_nulls(fcinfo, &nargs, &nulls))
     159           4 :         PG_RETURN_NULL();
     160             : 
     161          36 :     PG_RETURN_INT32(nargs - nulls);
     162             : }
     163             : 
     164             : 
     165             : /*
     166             :  * current_database()
     167             :  *  Expose the current database to the user
     168             :  */
     169             : Datum
     170        2644 : current_database(PG_FUNCTION_ARGS)
     171             : {
     172             :     Name        db;
     173             : 
     174        2644 :     db = (Name) palloc(NAMEDATALEN);
     175             : 
     176        2644 :     namestrcpy(db, get_database_name(MyDatabaseId));
     177        2644 :     PG_RETURN_NAME(db);
     178             : }
     179             : 
     180             : 
     181             : /*
     182             :  * current_query()
     183             :  *  Expose the current query to the user (useful in stored procedures)
     184             :  *  We might want to use ActivePortal->sourceText someday.
     185             :  */
     186             : Datum
     187           0 : current_query(PG_FUNCTION_ARGS)
     188             : {
     189             :     /* there is no easy way to access the more concise 'query_string' */
     190           0 :     if (debug_query_string)
     191           0 :         PG_RETURN_TEXT_P(cstring_to_text(debug_query_string));
     192             :     else
     193           0 :         PG_RETURN_NULL();
     194             : }
     195             : 
     196             : /* Function to find out which databases make use of a tablespace */
     197             : 
     198             : Datum
     199           4 : pg_tablespace_databases(PG_FUNCTION_ARGS)
     200             : {
     201           4 :     Oid         tablespaceOid = PG_GETARG_OID(0);
     202           4 :     ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
     203             :     bool        randomAccess;
     204             :     TupleDesc   tupdesc;
     205             :     Tuplestorestate *tupstore;
     206             :     char       *location;
     207             :     DIR        *dirdesc;
     208             :     struct dirent *de;
     209             :     MemoryContext oldcontext;
     210             : 
     211             :     /* check to see if caller supports us returning a tuplestore */
     212           4 :     if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
     213           0 :         ereport(ERROR,
     214             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     215             :                  errmsg("set-valued function called in context that cannot accept a set")));
     216           4 :     if (!(rsinfo->allowedModes & SFRM_Materialize))
     217           0 :         ereport(ERROR,
     218             :                 (errcode(ERRCODE_SYNTAX_ERROR),
     219             :                  errmsg("materialize mode required, but it is not allowed in this context")));
     220             : 
     221             :     /* The tupdesc and tuplestore must be created in ecxt_per_query_memory */
     222           4 :     oldcontext = MemoryContextSwitchTo(rsinfo->econtext->ecxt_per_query_memory);
     223             : 
     224           4 :     tupdesc = CreateTemplateTupleDesc(1);
     225           4 :     TupleDescInitEntry(tupdesc, (AttrNumber) 1, "pg_tablespace_databases",
     226             :                        OIDOID, -1, 0);
     227             : 
     228           4 :     randomAccess = (rsinfo->allowedModes & SFRM_Materialize_Random) != 0;
     229           4 :     tupstore = tuplestore_begin_heap(randomAccess, false, work_mem);
     230             : 
     231           4 :     rsinfo->returnMode = SFRM_Materialize;
     232           4 :     rsinfo->setResult = tupstore;
     233           4 :     rsinfo->setDesc = tupdesc;
     234             : 
     235           4 :     MemoryContextSwitchTo(oldcontext);
     236             : 
     237           4 :     if (tablespaceOid == GLOBALTABLESPACE_OID)
     238             :     {
     239           0 :         ereport(WARNING,
     240             :                 (errmsg("global tablespace never has databases")));
     241             :         /* return empty tuplestore */
     242           0 :         return (Datum) 0;
     243             :     }
     244             : 
     245           4 :     if (tablespaceOid == DEFAULTTABLESPACE_OID)
     246           4 :         location = psprintf("base");
     247             :     else
     248           0 :         location = psprintf("pg_tblspc/%u/%s", tablespaceOid,
     249             :                             TABLESPACE_VERSION_DIRECTORY);
     250             : 
     251           4 :     dirdesc = AllocateDir(location);
     252             : 
     253           4 :     if (!dirdesc)
     254             :     {
     255             :         /* the only expected error is ENOENT */
     256           0 :         if (errno != ENOENT)
     257           0 :             ereport(ERROR,
     258             :                     (errcode_for_file_access(),
     259             :                      errmsg("could not open directory \"%s\": %m",
     260             :                             location)));
     261           0 :         ereport(WARNING,
     262             :                 (errmsg("%u is not a tablespace OID", tablespaceOid)));
     263             :         /* return empty tuplestore */
     264           0 :         return (Datum) 0;
     265             :     }
     266             : 
     267          38 :     while ((de = ReadDir(dirdesc, location)) != NULL)
     268             :     {
     269          34 :         Oid         datOid = atooid(de->d_name);
     270             :         char       *subdir;
     271             :         bool        isempty;
     272             :         Datum       values[1];
     273             :         bool        nulls[1];
     274             : 
     275             :         /* this test skips . and .., but is awfully weak */
     276          34 :         if (!datOid)
     277          12 :             continue;
     278             : 
     279             :         /* if database subdir is empty, don't report tablespace as used */
     280             : 
     281          22 :         subdir = psprintf("%s/%s", location, de->d_name);
     282          22 :         isempty = directory_is_empty(subdir);
     283          22 :         pfree(subdir);
     284             : 
     285          22 :         if (isempty)
     286           0 :             continue;           /* indeed, nothing in it */
     287             : 
     288          22 :         values[0] = ObjectIdGetDatum(datOid);
     289          22 :         nulls[0] = false;
     290             : 
     291          22 :         tuplestore_putvalues(tupstore, tupdesc, values, nulls);
     292             :     }
     293             : 
     294           4 :     FreeDir(dirdesc);
     295           4 :     return (Datum) 0;
     296             : }
     297             : 
     298             : 
     299             : /*
     300             :  * pg_tablespace_location - get location for a tablespace
     301             :  */
     302             : Datum
     303          28 : pg_tablespace_location(PG_FUNCTION_ARGS)
     304             : {
     305          28 :     Oid         tablespaceOid = PG_GETARG_OID(0);
     306             :     char        sourcepath[MAXPGPATH];
     307             :     char        targetpath[MAXPGPATH];
     308             :     int         rllen;
     309             : 
     310             :     /*
     311             :      * It's useful to apply this function to pg_class.reltablespace, wherein
     312             :      * zero means "the database's default tablespace".  So, rather than
     313             :      * throwing an error for zero, we choose to assume that's what is meant.
     314             :      */
     315          28 :     if (tablespaceOid == InvalidOid)
     316           0 :         tablespaceOid = MyDatabaseTableSpace;
     317             : 
     318             :     /*
     319             :      * Return empty string for the cluster's default tablespaces
     320             :      */
     321          28 :     if (tablespaceOid == DEFAULTTABLESPACE_OID ||
     322             :         tablespaceOid == GLOBALTABLESPACE_OID)
     323          28 :         PG_RETURN_TEXT_P(cstring_to_text(""));
     324             : 
     325             : #if defined(HAVE_READLINK) || defined(WIN32)
     326             : 
     327             :     /*
     328             :      * Find the location of the tablespace by reading the symbolic link that
     329             :      * is in pg_tblspc/<oid>.
     330             :      */
     331           0 :     snprintf(sourcepath, sizeof(sourcepath), "pg_tblspc/%u", tablespaceOid);
     332             : 
     333           0 :     rllen = readlink(sourcepath, targetpath, sizeof(targetpath));
     334           0 :     if (rllen < 0)
     335           0 :         ereport(ERROR,
     336             :                 (errcode_for_file_access(),
     337             :                  errmsg("could not read symbolic link \"%s\": %m",
     338             :                         sourcepath)));
     339           0 :     if (rllen >= sizeof(targetpath))
     340           0 :         ereport(ERROR,
     341             :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
     342             :                  errmsg("symbolic link \"%s\" target is too long",
     343             :                         sourcepath)));
     344           0 :     targetpath[rllen] = '\0';
     345             : 
     346           0 :     PG_RETURN_TEXT_P(cstring_to_text(targetpath));
     347             : #else
     348             :     ereport(ERROR,
     349             :             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     350             :              errmsg("tablespaces are not supported on this platform")));
     351             :     PG_RETURN_NULL();
     352             : #endif
     353             : }
     354             : 
     355             : /*
     356             :  * pg_sleep - delay for N seconds
     357             :  */
     358             : Datum
     359          96 : pg_sleep(PG_FUNCTION_ARGS)
     360             : {
     361          96 :     float8      secs = PG_GETARG_FLOAT8(0);
     362             :     float8      endtime;
     363             : 
     364             :     /*
     365             :      * We sleep using WaitLatch, to ensure that we'll wake up promptly if an
     366             :      * important signal (such as SIGALRM or SIGINT) arrives.  Because
     367             :      * WaitLatch's upper limit of delay is INT_MAX milliseconds, and the user
     368             :      * might ask for more than that, we sleep for at most 10 minutes and then
     369             :      * loop.
     370             :      *
     371             :      * By computing the intended stop time initially, we avoid accumulation of
     372             :      * extra delay across multiple sleeps.  This also ensures we won't delay
     373             :      * less than the specified time when WaitLatch is terminated early by a
     374             :      * non-query-canceling signal such as SIGHUP.
     375             :      */
     376             : #define GetNowFloat()   ((float8) GetCurrentTimestamp() / 1000000.0)
     377             : 
     378          96 :     endtime = GetNowFloat() + secs;
     379             : 
     380             :     for (;;)
     381         102 :     {
     382             :         float8      delay;
     383             :         long        delay_ms;
     384             : 
     385         198 :         CHECK_FOR_INTERRUPTS();
     386             : 
     387         198 :         delay = endtime - GetNowFloat();
     388         198 :         if (delay >= 600.0)
     389           0 :             delay_ms = 600000;
     390         198 :         else if (delay > 0.0)
     391         102 :             delay_ms = (long) ceil(delay * 1000.0);
     392             :         else
     393          96 :             break;
     394             : 
     395         102 :         (void) WaitLatch(MyLatch,
     396             :                          WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
     397             :                          delay_ms,
     398             :                          WAIT_EVENT_PG_SLEEP);
     399         102 :         ResetLatch(MyLatch);
     400             :     }
     401             : 
     402          96 :     PG_RETURN_VOID();
     403             : }
     404             : 
     405             : /* Function to return the list of grammar keywords */
     406             : Datum
     407           0 : pg_get_keywords(PG_FUNCTION_ARGS)
     408             : {
     409             :     FuncCallContext *funcctx;
     410             : 
     411           0 :     if (SRF_IS_FIRSTCALL())
     412             :     {
     413             :         MemoryContext oldcontext;
     414             :         TupleDesc   tupdesc;
     415             : 
     416           0 :         funcctx = SRF_FIRSTCALL_INIT();
     417           0 :         oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
     418             : 
     419           0 :         tupdesc = CreateTemplateTupleDesc(5);
     420           0 :         TupleDescInitEntry(tupdesc, (AttrNumber) 1, "word",
     421             :                            TEXTOID, -1, 0);
     422           0 :         TupleDescInitEntry(tupdesc, (AttrNumber) 2, "catcode",
     423             :                            CHAROID, -1, 0);
     424           0 :         TupleDescInitEntry(tupdesc, (AttrNumber) 3, "barelabel",
     425             :                            BOOLOID, -1, 0);
     426           0 :         TupleDescInitEntry(tupdesc, (AttrNumber) 4, "catdesc",
     427             :                            TEXTOID, -1, 0);
     428           0 :         TupleDescInitEntry(tupdesc, (AttrNumber) 5, "baredesc",
     429             :                            TEXTOID, -1, 0);
     430             : 
     431           0 :         funcctx->attinmeta = TupleDescGetAttInMetadata(tupdesc);
     432             : 
     433           0 :         MemoryContextSwitchTo(oldcontext);
     434             :     }
     435             : 
     436           0 :     funcctx = SRF_PERCALL_SETUP();
     437             : 
     438           0 :     if (funcctx->call_cntr < ScanKeywords.num_keywords)
     439             :     {
     440             :         char       *values[5];
     441             :         HeapTuple   tuple;
     442             : 
     443             :         /* cast-away-const is ugly but alternatives aren't much better */
     444           0 :         values[0] = unconstify(char *,
     445             :                                GetScanKeyword(funcctx->call_cntr,
     446             :                                               &ScanKeywords));
     447             : 
     448           0 :         switch (ScanKeywordCategories[funcctx->call_cntr])
     449             :         {
     450           0 :             case UNRESERVED_KEYWORD:
     451           0 :                 values[1] = "U";
     452           0 :                 values[3] = _("unreserved");
     453           0 :                 break;
     454           0 :             case COL_NAME_KEYWORD:
     455           0 :                 values[1] = "C";
     456           0 :                 values[3] = _("unreserved (cannot be function or type name)");
     457           0 :                 break;
     458           0 :             case TYPE_FUNC_NAME_KEYWORD:
     459           0 :                 values[1] = "T";
     460           0 :                 values[3] = _("reserved (can be function or type name)");
     461           0 :                 break;
     462           0 :             case RESERVED_KEYWORD:
     463           0 :                 values[1] = "R";
     464           0 :                 values[3] = _("reserved");
     465           0 :                 break;
     466           0 :             default:            /* shouldn't be possible */
     467           0 :                 values[1] = NULL;
     468           0 :                 values[3] = NULL;
     469           0 :                 break;
     470             :         }
     471             : 
     472           0 :         if (ScanKeywordBareLabel[funcctx->call_cntr])
     473             :         {
     474           0 :             values[2] = "true";
     475           0 :             values[4] = _("can be bare label");
     476             :         }
     477             :         else
     478             :         {
     479           0 :             values[2] = "false";
     480           0 :             values[4] = _("requires AS");
     481             :         }
     482             : 
     483           0 :         tuple = BuildTupleFromCStrings(funcctx->attinmeta, values);
     484             : 
     485           0 :         SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(tuple));
     486             :     }
     487             : 
     488           0 :     SRF_RETURN_DONE(funcctx);
     489             : }
     490             : 
     491             : 
     492             : /*
     493             :  * Return the type of the argument.
     494             :  */
     495             : Datum
     496        1376 : pg_typeof(PG_FUNCTION_ARGS)
     497             : {
     498        1376 :     PG_RETURN_OID(get_fn_expr_argtype(fcinfo->flinfo, 0));
     499             : }
     500             : 
     501             : 
     502             : /*
     503             :  * Implementation of the COLLATE FOR expression; returns the collation
     504             :  * of the argument.
     505             :  */
     506             : Datum
     507          20 : pg_collation_for(PG_FUNCTION_ARGS)
     508             : {
     509             :     Oid         typeid;
     510             :     Oid         collid;
     511             : 
     512          20 :     typeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
     513          20 :     if (!typeid)
     514           0 :         PG_RETURN_NULL();
     515          20 :     if (!type_is_collatable(typeid) && typeid != UNKNOWNOID)
     516           4 :         ereport(ERROR,
     517             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
     518             :                  errmsg("collations are not supported by type %s",
     519             :                         format_type_be(typeid))));
     520             : 
     521          16 :     collid = PG_GET_COLLATION();
     522          16 :     if (!collid)
     523           4 :         PG_RETURN_NULL();
     524          12 :     PG_RETURN_TEXT_P(cstring_to_text(generate_collation_name(collid)));
     525             : }
     526             : 
     527             : 
     528             : /*
     529             :  * pg_relation_is_updatable - determine which update events the specified
     530             :  * relation supports.
     531             :  *
     532             :  * This relies on relation_is_updatable() in rewriteHandler.c, which see
     533             :  * for additional information.
     534             :  */
     535             : Datum
     536         588 : pg_relation_is_updatable(PG_FUNCTION_ARGS)
     537             : {
     538         588 :     Oid         reloid = PG_GETARG_OID(0);
     539         588 :     bool        include_triggers = PG_GETARG_BOOL(1);
     540             : 
     541         588 :     PG_RETURN_INT32(relation_is_updatable(reloid, NIL, include_triggers, NULL));
     542             : }
     543             : 
     544             : /*
     545             :  * pg_column_is_updatable - determine whether a column is updatable
     546             :  *
     547             :  * This function encapsulates the decision about just what
     548             :  * information_schema.columns.is_updatable actually means.  It's not clear
     549             :  * whether deletability of the column's relation should be required, so
     550             :  * we want that decision in C code where we could change it without initdb.
     551             :  */
     552             : Datum
     553         380 : pg_column_is_updatable(PG_FUNCTION_ARGS)
     554             : {
     555         380 :     Oid         reloid = PG_GETARG_OID(0);
     556         380 :     AttrNumber  attnum = PG_GETARG_INT16(1);
     557         380 :     AttrNumber  col = attnum - FirstLowInvalidHeapAttributeNumber;
     558         380 :     bool        include_triggers = PG_GETARG_BOOL(2);
     559             :     int         events;
     560             : 
     561             :     /* System columns are never updatable */
     562         380 :     if (attnum <= 0)
     563           0 :         PG_RETURN_BOOL(false);
     564             : 
     565         380 :     events = relation_is_updatable(reloid, NIL, include_triggers,
     566             :                                    bms_make_singleton(col));
     567             : 
     568             :     /* We require both updatability and deletability of the relation */
     569             : #define REQ_EVENTS ((1 << CMD_UPDATE) | (1 << CMD_DELETE))
     570             : 
     571         380 :     PG_RETURN_BOOL((events & REQ_EVENTS) == REQ_EVENTS);
     572             : }
     573             : 
     574             : 
     575             : /*
     576             :  * Is character a valid identifier start?
     577             :  * Must match scan.l's {ident_start} character class.
     578             :  */
     579             : static bool
     580        1468 : is_ident_start(unsigned char c)
     581             : {
     582             :     /* Underscores and ASCII letters are OK */
     583        1468 :     if (c == '_')
     584           0 :         return true;
     585        1468 :     if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
     586        1368 :         return true;
     587             :     /* Any high-bit-set character is OK (might be part of a multibyte char) */
     588         100 :     if (IS_HIGHBIT_SET(c))
     589           0 :         return true;
     590         100 :     return false;
     591             : }
     592             : 
     593             : /*
     594             :  * Is character a valid identifier continuation?
     595             :  * Must match scan.l's {ident_cont} character class.
     596             :  */
     597             : static bool
     598        1368 : is_ident_cont(unsigned char c)
     599             : {
     600             :     /* Can be digit or dollar sign ... */
     601        1368 :     if ((c >= '0' && c <= '9') || c == '$')
     602           0 :         return true;
     603             :     /* ... or an identifier start character */
     604        1368 :     return is_ident_start(c);
     605             : }
     606             : 
     607             : /*
     608             :  * parse_ident - parse a SQL qualified identifier into separate identifiers.
     609             :  * When strict mode is active (second parameter), then any chars after
     610             :  * the last identifier are disallowed.
     611             :  */
     612             : Datum
     613          76 : parse_ident(PG_FUNCTION_ARGS)
     614             : {
     615          76 :     text       *qualname = PG_GETARG_TEXT_PP(0);
     616          76 :     bool        strict = PG_GETARG_BOOL(1);
     617          76 :     char       *qualname_str = text_to_cstring(qualname);
     618          76 :     ArrayBuildState *astate = NULL;
     619             :     char       *nextp;
     620          76 :     bool        after_dot = false;
     621             : 
     622             :     /*
     623             :      * The code below scribbles on qualname_str in some cases, so we should
     624             :      * reconvert qualname if we need to show the original string in error
     625             :      * messages.
     626             :      */
     627          76 :     nextp = qualname_str;
     628             : 
     629             :     /* skip leading whitespace */
     630          96 :     while (scanner_isspace(*nextp))
     631          20 :         nextp++;
     632             : 
     633             :     for (;;)
     634          64 :     {
     635             :         char       *curname;
     636         140 :         bool        missing_ident = true;
     637             : 
     638         140 :         if (*nextp == '"')
     639             :         {
     640             :             char       *endp;
     641             : 
     642          40 :             curname = nextp + 1;
     643             :             for (;;)
     644             :             {
     645          40 :                 endp = strchr(nextp + 1, '"');
     646          40 :                 if (endp == NULL)
     647           0 :                     ereport(ERROR,
     648             :                             (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     649             :                              errmsg("string is not a valid identifier: \"%s\"",
     650             :                                     text_to_cstring(qualname)),
     651             :                              errdetail("String has unclosed double quotes.")));
     652          40 :                 if (endp[1] != '"')
     653          40 :                     break;
     654           0 :                 memmove(endp, endp + 1, strlen(endp));
     655           0 :                 nextp = endp;
     656             :             }
     657          40 :             nextp = endp + 1;
     658          40 :             *endp = '\0';
     659             : 
     660          40 :             if (endp - curname == 0)
     661           0 :                 ereport(ERROR,
     662             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     663             :                          errmsg("string is not a valid identifier: \"%s\"",
     664             :                                 text_to_cstring(qualname)),
     665             :                          errdetail("Quoted identifier must not be empty.")));
     666             : 
     667          40 :             astate = accumArrayResult(astate, CStringGetTextDatum(curname),
     668             :                                       false, TEXTOID, CurrentMemoryContext);
     669          40 :             missing_ident = false;
     670             :         }
     671         100 :         else if (is_ident_start((unsigned char) *nextp))
     672             :         {
     673             :             char       *downname;
     674             :             int         len;
     675             :             text       *part;
     676             : 
     677          68 :             curname = nextp++;
     678        1368 :             while (is_ident_cont((unsigned char) *nextp))
     679        1300 :                 nextp++;
     680             : 
     681          68 :             len = nextp - curname;
     682             : 
     683             :             /*
     684             :              * We don't implicitly truncate identifiers. This is useful for
     685             :              * allowing the user to check for specific parts of the identifier
     686             :              * being too long. It's easy enough for the user to get the
     687             :              * truncated names by casting our output to name[].
     688             :              */
     689          68 :             downname = downcase_identifier(curname, len, false, false);
     690          68 :             part = cstring_to_text_with_len(downname, len);
     691          68 :             astate = accumArrayResult(astate, PointerGetDatum(part), false,
     692             :                                       TEXTOID, CurrentMemoryContext);
     693          68 :             missing_ident = false;
     694             :         }
     695             : 
     696         140 :         if (missing_ident)
     697             :         {
     698             :             /* Different error messages based on where we failed. */
     699          32 :             if (*nextp == '.')
     700          12 :                 ereport(ERROR,
     701             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     702             :                          errmsg("string is not a valid identifier: \"%s\"",
     703             :                                 text_to_cstring(qualname)),
     704             :                          errdetail("No valid identifier before \".\".")));
     705          20 :             else if (after_dot)
     706           8 :                 ereport(ERROR,
     707             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     708             :                          errmsg("string is not a valid identifier: \"%s\"",
     709             :                                 text_to_cstring(qualname)),
     710             :                          errdetail("No valid identifier after \".\".")));
     711             :             else
     712          12 :                 ereport(ERROR,
     713             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     714             :                          errmsg("string is not a valid identifier: \"%s\"",
     715             :                                 text_to_cstring(qualname))));
     716             :         }
     717             : 
     718         136 :         while (scanner_isspace(*nextp))
     719          28 :             nextp++;
     720             : 
     721         108 :         if (*nextp == '.')
     722             :         {
     723          64 :             after_dot = true;
     724          64 :             nextp++;
     725          84 :             while (scanner_isspace(*nextp))
     726          20 :                 nextp++;
     727             :         }
     728          44 :         else if (*nextp == '\0')
     729             :         {
     730          24 :             break;
     731             :         }
     732             :         else
     733             :         {
     734          20 :             if (strict)
     735          16 :                 ereport(ERROR,
     736             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     737             :                          errmsg("string is not a valid identifier: \"%s\"",
     738             :                                 text_to_cstring(qualname))));
     739           4 :             break;
     740             :         }
     741             :     }
     742             : 
     743          28 :     PG_RETURN_DATUM(makeArrayResult(astate, CurrentMemoryContext));
     744             : }
     745             : 
     746             : /*
     747             :  * pg_current_logfile
     748             :  *
     749             :  * Report current log file used by log collector by scanning current_logfiles.
     750             :  */
     751             : Datum
     752           2 : pg_current_logfile(PG_FUNCTION_ARGS)
     753             : {
     754             :     FILE       *fd;
     755             :     char        lbuffer[MAXPGPATH];
     756             :     char       *logfmt;
     757             : 
     758             :     /* The log format parameter is optional */
     759           2 :     if (PG_NARGS() == 0 || PG_ARGISNULL(0))
     760           0 :         logfmt = NULL;
     761             :     else
     762             :     {
     763           2 :         logfmt = text_to_cstring(PG_GETARG_TEXT_PP(0));
     764             : 
     765           2 :         if (strcmp(logfmt, "stderr") != 0 && strcmp(logfmt, "csvlog") != 0)
     766           0 :             ereport(ERROR,
     767             :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     768             :                      errmsg("log format \"%s\" is not supported", logfmt),
     769             :                      errhint("The supported log formats are \"stderr\" and \"csvlog\".")));
     770             :     }
     771             : 
     772           2 :     fd = AllocateFile(LOG_METAINFO_DATAFILE, "r");
     773           2 :     if (fd == NULL)
     774             :     {
     775           0 :         if (errno != ENOENT)
     776           0 :             ereport(ERROR,
     777             :                     (errcode_for_file_access(),
     778             :                      errmsg("could not read file \"%s\": %m",
     779             :                             LOG_METAINFO_DATAFILE)));
     780           0 :         PG_RETURN_NULL();
     781             :     }
     782             : 
     783             : #ifdef WIN32
     784             :     /* syslogger.c writes CRLF line endings on Windows */
     785             :     _setmode(_fileno(fd), _O_TEXT);
     786             : #endif
     787             : 
     788             :     /*
     789             :      * Read the file to gather current log filename(s) registered by the
     790             :      * syslogger.
     791             :      */
     792           2 :     while (fgets(lbuffer, sizeof(lbuffer), fd) != NULL)
     793             :     {
     794             :         char       *log_format;
     795             :         char       *log_filepath;
     796             :         char       *nlpos;
     797             : 
     798             :         /* Extract log format and log file path from the line. */
     799           2 :         log_format = lbuffer;
     800           2 :         log_filepath = strchr(lbuffer, ' ');
     801           2 :         if (log_filepath == NULL)
     802             :         {
     803             :             /* Uh oh.  No space found, so file content is corrupted. */
     804           0 :             elog(ERROR,
     805             :                  "missing space character in \"%s\"", LOG_METAINFO_DATAFILE);
     806             :             break;
     807             :         }
     808             : 
     809           2 :         *log_filepath = '\0';
     810           2 :         log_filepath++;
     811           2 :         nlpos = strchr(log_filepath, '\n');
     812           2 :         if (nlpos == NULL)
     813             :         {
     814             :             /* Uh oh.  No newline found, so file content is corrupted. */
     815           0 :             elog(ERROR,
     816             :                  "missing newline character in \"%s\"", LOG_METAINFO_DATAFILE);
     817             :             break;
     818             :         }
     819           2 :         *nlpos = '\0';
     820             : 
     821           2 :         if (logfmt == NULL || strcmp(logfmt, log_format) == 0)
     822             :         {
     823           2 :             FreeFile(fd);
     824           2 :             PG_RETURN_TEXT_P(cstring_to_text(log_filepath));
     825             :         }
     826             :     }
     827             : 
     828             :     /* Close the current log filename file. */
     829           0 :     FreeFile(fd);
     830             : 
     831           0 :     PG_RETURN_NULL();
     832             : }
     833             : 
     834             : /*
     835             :  * Report current log file used by log collector (1 argument version)
     836             :  *
     837             :  * note: this wrapper is necessary to pass the sanity check in opr_sanity,
     838             :  * which checks that all built-in functions that share the implementing C
     839             :  * function take the same number of arguments
     840             :  */
     841             : Datum
     842           2 : pg_current_logfile_1arg(PG_FUNCTION_ARGS)
     843             : {
     844           2 :     return pg_current_logfile(fcinfo);
     845             : }
     846             : 
     847             : /*
     848             :  * SQL wrapper around RelationGetReplicaIndex().
     849             :  */
     850             : Datum
     851         248 : pg_get_replica_identity_index(PG_FUNCTION_ARGS)
     852             : {
     853         248 :     Oid         reloid = PG_GETARG_OID(0);
     854             :     Oid         idxoid;
     855             :     Relation    rel;
     856             : 
     857         248 :     rel = table_open(reloid, AccessShareLock);
     858         248 :     idxoid = RelationGetReplicaIndex(rel);
     859         248 :     table_close(rel, AccessShareLock);
     860             : 
     861         248 :     if (OidIsValid(idxoid))
     862         188 :         PG_RETURN_OID(idxoid);
     863             :     else
     864          60 :         PG_RETURN_NULL();
     865             : }

Generated by: LCOV version 1.13