LCOV - code coverage report
Current view: top level - src/backend/utils/adt - misc.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13beta1 Lines: 179 278 64.4 %
Date: 2020-06-03 10:06:28 Functions: 15 19 78.9 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13