LCOV - code coverage report
Current view: top level - src/backend/catalog - pg_proc.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13beta1 Lines: 349 400 87.2 %
Date: 2020-05-29 01:06:25 Functions: 9 9 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * pg_proc.c
       4             :  *    routines to support manipulation of the pg_proc relation
       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/catalog/pg_proc.c
      12             :  *
      13             :  *-------------------------------------------------------------------------
      14             :  */
      15             : #include "postgres.h"
      16             : 
      17             : #include "access/htup_details.h"
      18             : #include "access/table.h"
      19             : #include "access/xact.h"
      20             : #include "catalog/catalog.h"
      21             : #include "catalog/dependency.h"
      22             : #include "catalog/indexing.h"
      23             : #include "catalog/objectaccess.h"
      24             : #include "catalog/pg_language.h"
      25             : #include "catalog/pg_namespace.h"
      26             : #include "catalog/pg_proc.h"
      27             : #include "catalog/pg_transform.h"
      28             : #include "catalog/pg_type.h"
      29             : #include "commands/defrem.h"
      30             : #include "executor/functions.h"
      31             : #include "funcapi.h"
      32             : #include "mb/pg_wchar.h"
      33             : #include "miscadmin.h"
      34             : #include "nodes/nodeFuncs.h"
      35             : #include "parser/parse_coerce.h"
      36             : #include "parser/parse_type.h"
      37             : #include "tcop/pquery.h"
      38             : #include "tcop/tcopprot.h"
      39             : #include "utils/acl.h"
      40             : #include "utils/builtins.h"
      41             : #include "utils/lsyscache.h"
      42             : #include "utils/regproc.h"
      43             : #include "utils/rel.h"
      44             : #include "utils/syscache.h"
      45             : 
      46             : 
      47             : typedef struct
      48             : {
      49             :     char       *proname;
      50             :     char       *prosrc;
      51             : } parse_error_callback_arg;
      52             : 
      53             : static void sql_function_parse_error_callback(void *arg);
      54             : static int  match_prosrc_to_query(const char *prosrc, const char *queryText,
      55             :                                   int cursorpos);
      56             : static bool match_prosrc_to_literal(const char *prosrc, const char *literal,
      57             :                                     int cursorpos, int *newcursorpos);
      58             : 
      59             : 
      60             : /* ----------------------------------------------------------------
      61             :  *      ProcedureCreate
      62             :  *
      63             :  * Note: allParameterTypes, parameterModes, parameterNames, trftypes, and proconfig
      64             :  * are either arrays of the proper types or NULL.  We declare them Datum,
      65             :  * not "ArrayType *", to avoid importing array.h into pg_proc.h.
      66             :  * ----------------------------------------------------------------
      67             :  */
      68             : ObjectAddress
      69       25754 : ProcedureCreate(const char *procedureName,
      70             :                 Oid procNamespace,
      71             :                 bool replace,
      72             :                 bool returnsSet,
      73             :                 Oid returnType,
      74             :                 Oid proowner,
      75             :                 Oid languageObjectId,
      76             :                 Oid languageValidator,
      77             :                 const char *prosrc,
      78             :                 const char *probin,
      79             :                 char prokind,
      80             :                 bool security_definer,
      81             :                 bool isLeakProof,
      82             :                 bool isStrict,
      83             :                 char volatility,
      84             :                 char parallel,
      85             :                 oidvector *parameterTypes,
      86             :                 Datum allParameterTypes,
      87             :                 Datum parameterModes,
      88             :                 Datum parameterNames,
      89             :                 List *parameterDefaults,
      90             :                 Datum trftypes,
      91             :                 Datum proconfig,
      92             :                 Oid prosupport,
      93             :                 float4 procost,
      94             :                 float4 prorows)
      95             : {
      96             :     Oid         retval;
      97             :     int         parameterCount;
      98             :     int         allParamCount;
      99             :     Oid        *allParams;
     100       25754 :     char       *paramModes = NULL;
     101       25754 :     Oid         variadicType = InvalidOid;
     102       25754 :     Acl        *proacl = NULL;
     103             :     Relation    rel;
     104             :     HeapTuple   tup;
     105             :     HeapTuple   oldtup;
     106             :     bool        nulls[Natts_pg_proc];
     107             :     Datum       values[Natts_pg_proc];
     108             :     bool        replaces[Natts_pg_proc];
     109             :     NameData    procname;
     110             :     TupleDesc   tupDesc;
     111             :     bool        is_update;
     112             :     ObjectAddress myself,
     113             :                 referenced;
     114             :     char       *detailmsg;
     115             :     int         i;
     116             :     Oid         trfid;
     117             : 
     118             :     /*
     119             :      * sanity checks
     120             :      */
     121             :     Assert(PointerIsValid(prosrc));
     122             : 
     123       25754 :     parameterCount = parameterTypes->dim1;
     124       25754 :     if (parameterCount < 0 || parameterCount > FUNC_MAX_ARGS)
     125           0 :         ereport(ERROR,
     126             :                 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
     127             :                  errmsg_plural("functions cannot have more than %d argument",
     128             :                                "functions cannot have more than %d arguments",
     129             :                                FUNC_MAX_ARGS,
     130             :                                FUNC_MAX_ARGS)));
     131             :     /* note: the above is correct, we do NOT count output arguments */
     132             : 
     133             :     /* Deconstruct array inputs */
     134       25754 :     if (allParameterTypes != PointerGetDatum(NULL))
     135             :     {
     136             :         /*
     137             :          * We expect the array to be a 1-D OID array; verify that. We don't
     138             :          * need to use deconstruct_array() since the array data is just going
     139             :          * to look like a C array of OID values.
     140             :          */
     141        4228 :         ArrayType  *allParamArray = (ArrayType *) DatumGetPointer(allParameterTypes);
     142             : 
     143        4228 :         allParamCount = ARR_DIMS(allParamArray)[0];
     144        4228 :         if (ARR_NDIM(allParamArray) != 1 ||
     145        4228 :             allParamCount <= 0 ||
     146        4228 :             ARR_HASNULL(allParamArray) ||
     147        4228 :             ARR_ELEMTYPE(allParamArray) != OIDOID)
     148           0 :             elog(ERROR, "allParameterTypes is not a 1-D Oid array");
     149        4228 :         allParams = (Oid *) ARR_DATA_PTR(allParamArray);
     150             :         Assert(allParamCount >= parameterCount);
     151             :         /* we assume caller got the contents right */
     152             :     }
     153             :     else
     154             :     {
     155       21526 :         allParamCount = parameterCount;
     156       21526 :         allParams = parameterTypes->values;
     157             :     }
     158             : 
     159       25754 :     if (parameterModes != PointerGetDatum(NULL))
     160             :     {
     161             :         /*
     162             :          * We expect the array to be a 1-D CHAR array; verify that. We don't
     163             :          * need to use deconstruct_array() since the array data is just going
     164             :          * to look like a C array of char values.
     165             :          */
     166        4228 :         ArrayType  *modesArray = (ArrayType *) DatumGetPointer(parameterModes);
     167             : 
     168        4228 :         if (ARR_NDIM(modesArray) != 1 ||
     169        4228 :             ARR_DIMS(modesArray)[0] != allParamCount ||
     170        4228 :             ARR_HASNULL(modesArray) ||
     171        4228 :             ARR_ELEMTYPE(modesArray) != CHAROID)
     172           0 :             elog(ERROR, "parameterModes is not a 1-D char array");
     173        4228 :         paramModes = (char *) ARR_DATA_PTR(modesArray);
     174             :     }
     175             : 
     176             :     /*
     177             :      * Do not allow polymorphic return type unless there is a polymorphic
     178             :      * input argument that we can use to deduce the actual return type.
     179             :      */
     180       25754 :     detailmsg = check_valid_polymorphic_signature(returnType,
     181       25754 :                                                   parameterTypes->values,
     182             :                                                   parameterCount);
     183       25754 :     if (detailmsg)
     184          32 :         ereport(ERROR,
     185             :                 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
     186             :                  errmsg("cannot determine result data type"),
     187             :                  errdetail_internal("%s", detailmsg)));
     188             : 
     189             :     /*
     190             :      * Also, do not allow return type INTERNAL unless at least one input
     191             :      * argument is INTERNAL.
     192             :      */
     193       25722 :     detailmsg = check_valid_internal_signature(returnType,
     194       25722 :                                                parameterTypes->values,
     195             :                                                parameterCount);
     196       25722 :     if (detailmsg)
     197           0 :         ereport(ERROR,
     198             :                 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
     199             :                  errmsg("unsafe use of pseudo-type \"internal\""),
     200             :                  errdetail_internal("%s", detailmsg)));
     201             : 
     202             :     /*
     203             :      * Apply the same tests to any OUT arguments.
     204             :      */
     205       25722 :     if (allParameterTypes != PointerGetDatum(NULL))
     206             :     {
     207       28990 :         for (i = 0; i < allParamCount; i++)
     208             :         {
     209       24782 :             if (paramModes == NULL ||
     210       24782 :                 paramModes[i] == PROARGMODE_IN ||
     211       15574 :                 paramModes[i] == PROARGMODE_VARIADIC)
     212       10712 :                 continue;       /* ignore input-only params */
     213             : 
     214       14070 :             detailmsg = check_valid_polymorphic_signature(allParams[i],
     215       14070 :                                                           parameterTypes->values,
     216             :                                                           parameterCount);
     217       14070 :             if (detailmsg)
     218          20 :                 ereport(ERROR,
     219             :                         (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
     220             :                          errmsg("cannot determine result data type"),
     221             :                          errdetail_internal("%s", detailmsg)));
     222       14050 :             detailmsg = check_valid_internal_signature(allParams[i],
     223       14050 :                                                        parameterTypes->values,
     224             :                                                        parameterCount);
     225       14050 :             if (detailmsg)
     226           0 :                 ereport(ERROR,
     227             :                         (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
     228             :                          errmsg("unsafe use of pseudo-type \"internal\""),
     229             :                          errdetail_internal("%s", detailmsg)));
     230             :         }
     231             :     }
     232             : 
     233             :     /* Identify variadic argument type, if any */
     234       25702 :     if (paramModes != NULL)
     235             :     {
     236             :         /*
     237             :          * Only the last input parameter can be variadic; if it is, save its
     238             :          * element type.  Errors here are just elog since caller should have
     239             :          * checked this already.
     240             :          */
     241       28946 :         for (i = 0; i < allParamCount; i++)
     242             :         {
     243       24738 :             switch (paramModes[i])
     244             :             {
     245        9286 :                 case PROARGMODE_IN:
     246             :                 case PROARGMODE_INOUT:
     247        9286 :                     if (OidIsValid(variadicType))
     248           0 :                         elog(ERROR, "variadic parameter must be last");
     249        9286 :                     break;
     250       13948 :                 case PROARGMODE_OUT:
     251             :                 case PROARGMODE_TABLE:
     252             :                     /* okay */
     253       13948 :                     break;
     254        1504 :                 case PROARGMODE_VARIADIC:
     255        1504 :                     if (OidIsValid(variadicType))
     256           0 :                         elog(ERROR, "variadic parameter must be last");
     257        1504 :                     switch (allParams[i])
     258             :                     {
     259           6 :                         case ANYOID:
     260           6 :                             variadicType = ANYOID;
     261           6 :                             break;
     262          30 :                         case ANYARRAYOID:
     263          30 :                             variadicType = ANYELEMENTOID;
     264          30 :                             break;
     265          16 :                         case ANYCOMPATIBLEARRAYOID:
     266          16 :                             variadicType = ANYCOMPATIBLEOID;
     267          16 :                             break;
     268        1452 :                         default:
     269        1452 :                             variadicType = get_element_type(allParams[i]);
     270        1452 :                             if (!OidIsValid(variadicType))
     271           0 :                                 elog(ERROR, "variadic parameter is not an array");
     272        1452 :                             break;
     273             :                     }
     274        1504 :                     break;
     275           0 :                 default:
     276           0 :                     elog(ERROR, "invalid parameter mode '%c'", paramModes[i]);
     277             :                     break;
     278             :             }
     279             :         }
     280             :     }
     281             : 
     282             :     /*
     283             :      * All seems OK; prepare the data to be inserted into pg_proc.
     284             :      */
     285             : 
     286      771060 :     for (i = 0; i < Natts_pg_proc; ++i)
     287             :     {
     288      745358 :         nulls[i] = false;
     289      745358 :         values[i] = (Datum) 0;
     290      745358 :         replaces[i] = true;
     291             :     }
     292             : 
     293       25702 :     namestrcpy(&procname, procedureName);
     294       25702 :     values[Anum_pg_proc_proname - 1] = NameGetDatum(&procname);
     295       25702 :     values[Anum_pg_proc_pronamespace - 1] = ObjectIdGetDatum(procNamespace);
     296       25702 :     values[Anum_pg_proc_proowner - 1] = ObjectIdGetDatum(proowner);
     297       25702 :     values[Anum_pg_proc_prolang - 1] = ObjectIdGetDatum(languageObjectId);
     298       25702 :     values[Anum_pg_proc_procost - 1] = Float4GetDatum(procost);
     299       25702 :     values[Anum_pg_proc_prorows - 1] = Float4GetDatum(prorows);
     300       25702 :     values[Anum_pg_proc_provariadic - 1] = ObjectIdGetDatum(variadicType);
     301       25702 :     values[Anum_pg_proc_prosupport - 1] = ObjectIdGetDatum(prosupport);
     302       25702 :     values[Anum_pg_proc_prokind - 1] = CharGetDatum(prokind);
     303       25702 :     values[Anum_pg_proc_prosecdef - 1] = BoolGetDatum(security_definer);
     304       25702 :     values[Anum_pg_proc_proleakproof - 1] = BoolGetDatum(isLeakProof);
     305       25702 :     values[Anum_pg_proc_proisstrict - 1] = BoolGetDatum(isStrict);
     306       25702 :     values[Anum_pg_proc_proretset - 1] = BoolGetDatum(returnsSet);
     307       25702 :     values[Anum_pg_proc_provolatile - 1] = CharGetDatum(volatility);
     308       25702 :     values[Anum_pg_proc_proparallel - 1] = CharGetDatum(parallel);
     309       25702 :     values[Anum_pg_proc_pronargs - 1] = UInt16GetDatum(parameterCount);
     310       25702 :     values[Anum_pg_proc_pronargdefaults - 1] = UInt16GetDatum(list_length(parameterDefaults));
     311       25702 :     values[Anum_pg_proc_prorettype - 1] = ObjectIdGetDatum(returnType);
     312       25702 :     values[Anum_pg_proc_proargtypes - 1] = PointerGetDatum(parameterTypes);
     313       25702 :     if (allParameterTypes != PointerGetDatum(NULL))
     314        4208 :         values[Anum_pg_proc_proallargtypes - 1] = allParameterTypes;
     315             :     else
     316       21494 :         nulls[Anum_pg_proc_proallargtypes - 1] = true;
     317       25702 :     if (parameterModes != PointerGetDatum(NULL))
     318        4208 :         values[Anum_pg_proc_proargmodes - 1] = parameterModes;
     319             :     else
     320       21494 :         nulls[Anum_pg_proc_proargmodes - 1] = true;
     321       25702 :     if (parameterNames != PointerGetDatum(NULL))
     322       14530 :         values[Anum_pg_proc_proargnames - 1] = parameterNames;
     323             :     else
     324       11172 :         nulls[Anum_pg_proc_proargnames - 1] = true;
     325       25702 :     if (parameterDefaults != NIL)
     326       10142 :         values[Anum_pg_proc_proargdefaults - 1] = CStringGetTextDatum(nodeToString(parameterDefaults));
     327             :     else
     328       15560 :         nulls[Anum_pg_proc_proargdefaults - 1] = true;
     329       25702 :     if (trftypes != PointerGetDatum(NULL))
     330         116 :         values[Anum_pg_proc_protrftypes - 1] = trftypes;
     331             :     else
     332       25586 :         nulls[Anum_pg_proc_protrftypes - 1] = true;
     333       25702 :     values[Anum_pg_proc_prosrc - 1] = CStringGetTextDatum(prosrc);
     334       25702 :     if (probin)
     335        4890 :         values[Anum_pg_proc_probin - 1] = CStringGetTextDatum(probin);
     336             :     else
     337       20812 :         nulls[Anum_pg_proc_probin - 1] = true;
     338       25702 :     if (proconfig != PointerGetDatum(NULL))
     339          36 :         values[Anum_pg_proc_proconfig - 1] = proconfig;
     340             :     else
     341       25666 :         nulls[Anum_pg_proc_proconfig - 1] = true;
     342             :     /* proacl will be determined later */
     343             : 
     344       25702 :     rel = table_open(ProcedureRelationId, RowExclusiveLock);
     345       25702 :     tupDesc = RelationGetDescr(rel);
     346             : 
     347             :     /* Check for pre-existing definition */
     348       25702 :     oldtup = SearchSysCache3(PROCNAMEARGSNSP,
     349             :                              PointerGetDatum(procedureName),
     350             :                              PointerGetDatum(parameterTypes),
     351             :                              ObjectIdGetDatum(procNamespace));
     352             : 
     353       25702 :     if (HeapTupleIsValid(oldtup))
     354             :     {
     355             :         /* There is one; okay to replace it? */
     356       10576 :         Form_pg_proc oldproc = (Form_pg_proc) GETSTRUCT(oldtup);
     357             :         Datum       proargnames;
     358             :         bool        isnull;
     359             :         const char *dropcmd;
     360             : 
     361       10576 :         if (!replace)
     362           2 :             ereport(ERROR,
     363             :                     (errcode(ERRCODE_DUPLICATE_FUNCTION),
     364             :                      errmsg("function \"%s\" already exists with same argument types",
     365             :                             procedureName)));
     366       10574 :         if (!pg_proc_ownercheck(oldproc->oid, proowner))
     367           0 :             aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_FUNCTION,
     368             :                            procedureName);
     369             : 
     370             :         /* Not okay to change routine kind */
     371       10574 :         if (oldproc->prokind != prokind)
     372          12 :             ereport(ERROR,
     373             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
     374             :                      errmsg("cannot change routine kind"),
     375             :                      (oldproc->prokind == PROKIND_AGGREGATE ?
     376             :                       errdetail("\"%s\" is an aggregate function.", procedureName) :
     377             :                       oldproc->prokind == PROKIND_FUNCTION ?
     378             :                       errdetail("\"%s\" is a function.", procedureName) :
     379             :                       oldproc->prokind == PROKIND_PROCEDURE ?
     380             :                       errdetail("\"%s\" is a procedure.", procedureName) :
     381             :                       oldproc->prokind == PROKIND_WINDOW ?
     382             :                       errdetail("\"%s\" is a window function.", procedureName) :
     383             :                       0)));
     384             : 
     385       10562 :         dropcmd = (prokind == PROKIND_PROCEDURE ? "DROP PROCEDURE" :
     386             :                    prokind == PROKIND_AGGREGATE ? "DROP AGGREGATE" :
     387             :                    "DROP FUNCTION");
     388             : 
     389             :         /*
     390             :          * Not okay to change the return type of the existing proc, since
     391             :          * existing rules, views, etc may depend on the return type.
     392             :          *
     393             :          * In case of a procedure, a changing return type means that whether
     394             :          * the procedure has output parameters was changed.  Since there is no
     395             :          * user visible return type, we produce a more specific error message.
     396             :          */
     397       10562 :         if (returnType != oldproc->prorettype ||
     398       10554 :             returnsSet != oldproc->proretset)
     399           8 :             ereport(ERROR,
     400             :                     (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
     401             :                      prokind == PROKIND_PROCEDURE
     402             :                      ? errmsg("cannot change whether a procedure has output parameters")
     403             :                      : errmsg("cannot change return type of existing function"),
     404             : 
     405             :             /*
     406             :              * translator: first %s is DROP FUNCTION, DROP PROCEDURE, or DROP
     407             :              * AGGREGATE
     408             :              */
     409             :                      errhint("Use %s %s first.",
     410             :                              dropcmd,
     411             :                              format_procedure(oldproc->oid))));
     412             : 
     413             :         /*
     414             :          * If it returns RECORD, check for possible change of record type
     415             :          * implied by OUT parameters
     416             :          */
     417       10554 :         if (returnType == RECORDOID)
     418             :         {
     419             :             TupleDesc   olddesc;
     420             :             TupleDesc   newdesc;
     421             : 
     422        2564 :             olddesc = build_function_result_tupdesc_t(oldtup);
     423        2564 :             newdesc = build_function_result_tupdesc_d(prokind,
     424             :                                                       allParameterTypes,
     425             :                                                       parameterModes,
     426             :                                                       parameterNames);
     427        2564 :             if (olddesc == NULL && newdesc == NULL)
     428             :                  /* ok, both are runtime-defined RECORDs */ ;
     429        2542 :             else if (olddesc == NULL || newdesc == NULL ||
     430        2542 :                      !equalTupleDescs(olddesc, newdesc))
     431           0 :                 ereport(ERROR,
     432             :                         (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
     433             :                          errmsg("cannot change return type of existing function"),
     434             :                          errdetail("Row type defined by OUT parameters is different."),
     435             :                 /* translator: first %s is DROP FUNCTION or DROP PROCEDURE */
     436             :                          errhint("Use %s %s first.",
     437             :                                  dropcmd,
     438             :                                  format_procedure(oldproc->oid))));
     439             :         }
     440             : 
     441             :         /*
     442             :          * If there were any named input parameters, check to make sure the
     443             :          * names have not been changed, as this could break existing calls. We
     444             :          * allow adding names to formerly unnamed parameters, though.
     445             :          */
     446       10554 :         proargnames = SysCacheGetAttr(PROCNAMEARGSNSP, oldtup,
     447             :                                       Anum_pg_proc_proargnames,
     448             :                                       &isnull);
     449       10554 :         if (!isnull)
     450             :         {
     451             :             Datum       proargmodes;
     452             :             char      **old_arg_names;
     453             :             char      **new_arg_names;
     454             :             int         n_old_arg_names;
     455             :             int         n_new_arg_names;
     456             :             int         j;
     457             : 
     458        3642 :             proargmodes = SysCacheGetAttr(PROCNAMEARGSNSP, oldtup,
     459             :                                           Anum_pg_proc_proargmodes,
     460             :                                           &isnull);
     461        3642 :             if (isnull)
     462        1088 :                 proargmodes = PointerGetDatum(NULL);    /* just to be sure */
     463             : 
     464        3642 :             n_old_arg_names = get_func_input_arg_names(proargnames,
     465             :                                                        proargmodes,
     466             :                                                        &old_arg_names);
     467        3642 :             n_new_arg_names = get_func_input_arg_names(parameterNames,
     468             :                                                        parameterModes,
     469             :                                                        &new_arg_names);
     470       16230 :             for (j = 0; j < n_old_arg_names; j++)
     471             :             {
     472       12600 :                 if (old_arg_names[j] == NULL)
     473           4 :                     continue;
     474       12596 :                 if (j >= n_new_arg_names || new_arg_names[j] == NULL ||
     475       12592 :                     strcmp(old_arg_names[j], new_arg_names[j]) != 0)
     476          12 :                     ereport(ERROR,
     477             :                             (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
     478             :                              errmsg("cannot change name of input parameter \"%s\"",
     479             :                                     old_arg_names[j]),
     480             :                     /* translator: first %s is DROP FUNCTION or DROP PROCEDURE */
     481             :                              errhint("Use %s %s first.",
     482             :                                      dropcmd,
     483             :                                      format_procedure(oldproc->oid))));
     484             :             }
     485             :         }
     486             : 
     487             :         /*
     488             :          * If there are existing defaults, check compatibility: redefinition
     489             :          * must not remove any defaults nor change their types.  (Removing a
     490             :          * default might cause a function to fail to satisfy an existing call.
     491             :          * Changing type would only be possible if the associated parameter is
     492             :          * polymorphic, and in such cases a change of default type might alter
     493             :          * the resolved output type of existing calls.)
     494             :          */
     495       10542 :         if (oldproc->pronargdefaults != 0)
     496             :         {
     497             :             Datum       proargdefaults;
     498             :             List       *oldDefaults;
     499             :             ListCell   *oldlc;
     500             :             ListCell   *newlc;
     501             : 
     502           4 :             if (list_length(parameterDefaults) < oldproc->pronargdefaults)
     503           4 :                 ereport(ERROR,
     504             :                         (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
     505             :                          errmsg("cannot remove parameter defaults from existing function"),
     506             :                 /* translator: first %s is DROP FUNCTION or DROP PROCEDURE */
     507             :                          errhint("Use %s %s first.",
     508             :                                  dropcmd,
     509             :                                  format_procedure(oldproc->oid))));
     510             : 
     511           0 :             proargdefaults = SysCacheGetAttr(PROCNAMEARGSNSP, oldtup,
     512             :                                              Anum_pg_proc_proargdefaults,
     513             :                                              &isnull);
     514             :             Assert(!isnull);
     515           0 :             oldDefaults = castNode(List, stringToNode(TextDatumGetCString(proargdefaults)));
     516             :             Assert(list_length(oldDefaults) == oldproc->pronargdefaults);
     517             : 
     518             :             /* new list can have more defaults than old, advance over 'em */
     519           0 :             newlc = list_nth_cell(parameterDefaults,
     520           0 :                                   list_length(parameterDefaults) -
     521           0 :                                   oldproc->pronargdefaults);
     522             : 
     523           0 :             foreach(oldlc, oldDefaults)
     524             :             {
     525           0 :                 Node       *oldDef = (Node *) lfirst(oldlc);
     526           0 :                 Node       *newDef = (Node *) lfirst(newlc);
     527             : 
     528           0 :                 if (exprType(oldDef) != exprType(newDef))
     529           0 :                     ereport(ERROR,
     530             :                             (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
     531             :                              errmsg("cannot change data type of existing parameter default value"),
     532             :                     /* translator: first %s is DROP FUNCTION or DROP PROCEDURE */
     533             :                              errhint("Use %s %s first.",
     534             :                                      dropcmd,
     535             :                                      format_procedure(oldproc->oid))));
     536           0 :                 newlc = lnext(parameterDefaults, newlc);
     537             :             }
     538             :         }
     539             : 
     540             :         /*
     541             :          * Do not change existing oid, ownership or permissions, either.  Note
     542             :          * dependency-update code below has to agree with this decision.
     543             :          */
     544       10538 :         replaces[Anum_pg_proc_oid - 1] = false;
     545       10538 :         replaces[Anum_pg_proc_proowner - 1] = false;
     546       10538 :         replaces[Anum_pg_proc_proacl - 1] = false;
     547             : 
     548             :         /* Okay, do it... */
     549       10538 :         tup = heap_modify_tuple(oldtup, tupDesc, values, nulls, replaces);
     550       10538 :         CatalogTupleUpdate(rel, &tup->t_self, tup);
     551             : 
     552       10538 :         ReleaseSysCache(oldtup);
     553       10538 :         is_update = true;
     554             :     }
     555             :     else
     556             :     {
     557             :         /* Creating a new procedure */
     558             :         Oid         newOid;
     559             : 
     560             :         /* First, get default permissions and set up proacl */
     561       15126 :         proacl = get_user_default_acl(OBJECT_FUNCTION, proowner,
     562             :                                       procNamespace);
     563       15126 :         if (proacl != NULL)
     564          12 :             values[Anum_pg_proc_proacl - 1] = PointerGetDatum(proacl);
     565             :         else
     566       15114 :             nulls[Anum_pg_proc_proacl - 1] = true;
     567             : 
     568       15126 :         newOid = GetNewOidWithIndex(rel, ProcedureOidIndexId,
     569             :                                     Anum_pg_proc_oid);
     570       15126 :         values[Anum_pg_proc_oid - 1] = ObjectIdGetDatum(newOid);
     571       15126 :         tup = heap_form_tuple(tupDesc, values, nulls);
     572       15126 :         CatalogTupleInsert(rel, tup);
     573       15126 :         is_update = false;
     574             :     }
     575             : 
     576             : 
     577       25664 :     retval = ((Form_pg_proc) GETSTRUCT(tup))->oid;
     578             : 
     579             :     /*
     580             :      * Create dependencies for the new function.  If we are updating an
     581             :      * existing function, first delete any existing pg_depend entries.
     582             :      * (However, since we are not changing ownership or permissions, the
     583             :      * shared dependencies do *not* need to change, and we leave them alone.)
     584             :      */
     585       25664 :     if (is_update)
     586       10538 :         deleteDependencyRecordsFor(ProcedureRelationId, retval, true);
     587             : 
     588       25664 :     myself.classId = ProcedureRelationId;
     589       25664 :     myself.objectId = retval;
     590       25664 :     myself.objectSubId = 0;
     591             : 
     592             :     /* dependency on namespace */
     593       25664 :     referenced.classId = NamespaceRelationId;
     594       25664 :     referenced.objectId = procNamespace;
     595       25664 :     referenced.objectSubId = 0;
     596       25664 :     recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
     597             : 
     598             :     /* dependency on implementation language */
     599       25664 :     referenced.classId = LanguageRelationId;
     600       25664 :     referenced.objectId = languageObjectId;
     601       25664 :     referenced.objectSubId = 0;
     602       25664 :     recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
     603             : 
     604             :     /* dependency on return type */
     605       25664 :     referenced.classId = TypeRelationId;
     606       25664 :     referenced.objectId = returnType;
     607       25664 :     referenced.objectSubId = 0;
     608       25664 :     recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
     609             : 
     610             :     /* dependency on transform used by return type, if any */
     611       25664 :     if ((trfid = get_transform_oid(returnType, languageObjectId, true)))
     612             :     {
     613         240 :         referenced.classId = TransformRelationId;
     614         240 :         referenced.objectId = trfid;
     615         240 :         referenced.objectSubId = 0;
     616         240 :         recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
     617             :     }
     618             : 
     619             :     /* dependency on parameter types */
     620       98928 :     for (i = 0; i < allParamCount; i++)
     621             :     {
     622       73264 :         referenced.classId = TypeRelationId;
     623       73264 :         referenced.objectId = allParams[i];
     624       73264 :         referenced.objectSubId = 0;
     625       73264 :         recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
     626             : 
     627             :         /* dependency on transform used by parameter type, if any */
     628       73264 :         if ((trfid = get_transform_oid(allParams[i], languageObjectId, true)))
     629             :         {
     630         408 :             referenced.classId = TransformRelationId;
     631         408 :             referenced.objectId = trfid;
     632         408 :             referenced.objectSubId = 0;
     633         408 :             recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
     634             :         }
     635             :     }
     636             : 
     637             :     /* dependency on parameter default expressions */
     638       25664 :     if (parameterDefaults)
     639       10134 :         recordDependencyOnExpr(&myself, (Node *) parameterDefaults,
     640             :                                NIL, DEPENDENCY_NORMAL);
     641             : 
     642             :     /* dependency on support function, if any */
     643       25664 :     if (OidIsValid(prosupport))
     644             :     {
     645          10 :         referenced.classId = ProcedureRelationId;
     646          10 :         referenced.objectId = prosupport;
     647          10 :         referenced.objectSubId = 0;
     648          10 :         recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
     649             :     }
     650             : 
     651             :     /* dependency on owner */
     652       25664 :     if (!is_update)
     653       15126 :         recordDependencyOnOwner(ProcedureRelationId, retval, proowner);
     654             : 
     655             :     /* dependency on any roles mentioned in ACL */
     656       25664 :     if (!is_update)
     657       15126 :         recordDependencyOnNewAcl(ProcedureRelationId, retval, 0,
     658             :                                  proowner, proacl);
     659             : 
     660             :     /* dependency on extension */
     661       25664 :     recordDependencyOnCurrentExtension(&myself, is_update);
     662             : 
     663       25664 :     heap_freetuple(tup);
     664             : 
     665             :     /* Post creation hook for new function */
     666       25664 :     InvokeObjectPostCreateHook(ProcedureRelationId, retval, 0);
     667             : 
     668       25664 :     table_close(rel, RowExclusiveLock);
     669             : 
     670             :     /* Verify function body */
     671       25664 :     if (OidIsValid(languageValidator))
     672             :     {
     673       25126 :         ArrayType  *set_items = NULL;
     674       25126 :         int         save_nestlevel = 0;
     675             : 
     676             :         /* Advance command counter so new tuple can be seen by validator */
     677       25126 :         CommandCounterIncrement();
     678             : 
     679             :         /*
     680             :          * Set per-function configuration parameters so that the validation is
     681             :          * done with the environment the function expects.  However, if
     682             :          * check_function_bodies is off, we don't do this, because that would
     683             :          * create dump ordering hazards that pg_dump doesn't know how to deal
     684             :          * with.  (For example, a SET clause might refer to a not-yet-created
     685             :          * text search configuration.)  This means that the validator
     686             :          * shouldn't complain about anything that might depend on a GUC
     687             :          * parameter when check_function_bodies is off.
     688             :          */
     689       25126 :         if (check_function_bodies)
     690             :         {
     691       24628 :             set_items = (ArrayType *) DatumGetPointer(proconfig);
     692       24628 :             if (set_items)      /* Need a new GUC nesting level */
     693             :             {
     694          26 :                 save_nestlevel = NewGUCNestLevel();
     695          26 :                 ProcessGUCArray(set_items,
     696          26 :                                 (superuser() ? PGC_SUSET : PGC_USERSET),
     697             :                                 PGC_S_SESSION,
     698             :                                 GUC_ACTION_SAVE);
     699             :             }
     700             :         }
     701             : 
     702       25122 :         OidFunctionCall1(languageValidator, ObjectIdGetDatum(retval));
     703             : 
     704       24996 :         if (set_items)
     705          22 :             AtEOXact_GUC(true, save_nestlevel);
     706             :     }
     707             : 
     708       25534 :     return myself;
     709             : }
     710             : 
     711             : 
     712             : 
     713             : /*
     714             :  * Validator for internal functions
     715             :  *
     716             :  * Check that the given internal function name (the "prosrc" value) is
     717             :  * a known builtin function.
     718             :  */
     719             : Datum
     720       10760 : fmgr_internal_validator(PG_FUNCTION_ARGS)
     721             : {
     722       10760 :     Oid         funcoid = PG_GETARG_OID(0);
     723             :     HeapTuple   tuple;
     724             :     bool        isnull;
     725             :     Datum       tmp;
     726             :     char       *prosrc;
     727             : 
     728       10760 :     if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
     729           0 :         PG_RETURN_VOID();
     730             : 
     731             :     /*
     732             :      * We do not honor check_function_bodies since it's unlikely the function
     733             :      * name will be found later if it isn't there now.
     734             :      */
     735             : 
     736       10760 :     tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
     737       10760 :     if (!HeapTupleIsValid(tuple))
     738           0 :         elog(ERROR, "cache lookup failed for function %u", funcoid);
     739             : 
     740       10760 :     tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
     741       10760 :     if (isnull)
     742           0 :         elog(ERROR, "null prosrc");
     743       10760 :     prosrc = TextDatumGetCString(tmp);
     744             : 
     745       10760 :     if (fmgr_internal_function(prosrc) == InvalidOid)
     746           4 :         ereport(ERROR,
     747             :                 (errcode(ERRCODE_UNDEFINED_FUNCTION),
     748             :                  errmsg("there is no built-in function named \"%s\"",
     749             :                         prosrc)));
     750             : 
     751       10756 :     ReleaseSysCache(tuple);
     752             : 
     753       10756 :     PG_RETURN_VOID();
     754             : }
     755             : 
     756             : 
     757             : 
     758             : /*
     759             :  * Validator for C language functions
     760             :  *
     761             :  * Make sure that the library file exists, is loadable, and contains
     762             :  * the specified link symbol. Also check for a valid function
     763             :  * information record.
     764             :  */
     765             : Datum
     766        4890 : fmgr_c_validator(PG_FUNCTION_ARGS)
     767             : {
     768        4890 :     Oid         funcoid = PG_GETARG_OID(0);
     769             :     void       *libraryhandle;
     770             :     HeapTuple   tuple;
     771             :     bool        isnull;
     772             :     Datum       tmp;
     773             :     char       *prosrc;
     774             :     char       *probin;
     775             : 
     776        4890 :     if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
     777           0 :         PG_RETURN_VOID();
     778             : 
     779             :     /*
     780             :      * It'd be most consistent to skip the check if !check_function_bodies,
     781             :      * but the purpose of that switch is to be helpful for pg_dump loading,
     782             :      * and for pg_dump loading it's much better if we *do* check.
     783             :      */
     784             : 
     785        4890 :     tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
     786        4890 :     if (!HeapTupleIsValid(tuple))
     787           0 :         elog(ERROR, "cache lookup failed for function %u", funcoid);
     788             : 
     789        4890 :     tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
     790        4890 :     if (isnull)
     791           0 :         elog(ERROR, "null prosrc for C function %u", funcoid);
     792        4890 :     prosrc = TextDatumGetCString(tmp);
     793             : 
     794        4890 :     tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_probin, &isnull);
     795        4890 :     if (isnull)
     796           0 :         elog(ERROR, "null probin for C function %u", funcoid);
     797        4890 :     probin = TextDatumGetCString(tmp);
     798             : 
     799        4890 :     (void) load_external_function(probin, prosrc, true, &libraryhandle);
     800        4882 :     (void) fetch_finfo_record(libraryhandle, prosrc);
     801             : 
     802        4882 :     ReleaseSysCache(tuple);
     803             : 
     804        4882 :     PG_RETURN_VOID();
     805             : }
     806             : 
     807             : 
     808             : /*
     809             :  * Validator for SQL language functions
     810             :  *
     811             :  * Parse it here in order to be sure that it contains no syntax errors.
     812             :  */
     813             : Datum
     814        6070 : fmgr_sql_validator(PG_FUNCTION_ARGS)
     815             : {
     816        6070 :     Oid         funcoid = PG_GETARG_OID(0);
     817             :     HeapTuple   tuple;
     818             :     Form_pg_proc proc;
     819             :     List       *raw_parsetree_list;
     820             :     List       *querytree_list;
     821             :     ListCell   *lc;
     822             :     bool        isnull;
     823             :     Datum       tmp;
     824             :     char       *prosrc;
     825             :     parse_error_callback_arg callback_arg;
     826             :     ErrorContextCallback sqlerrcontext;
     827             :     bool        haspolyarg;
     828             :     int         i;
     829             : 
     830        6070 :     if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
     831           0 :         PG_RETURN_VOID();
     832             : 
     833        6070 :     tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
     834        6070 :     if (!HeapTupleIsValid(tuple))
     835           0 :         elog(ERROR, "cache lookup failed for function %u", funcoid);
     836        6070 :     proc = (Form_pg_proc) GETSTRUCT(tuple);
     837             : 
     838             :     /* Disallow pseudotype result */
     839             :     /* except for RECORD, VOID, or polymorphic */
     840        6070 :     if (get_typtype(proc->prorettype) == TYPTYPE_PSEUDO &&
     841        1514 :         proc->prorettype != RECORDOID &&
     842         304 :         proc->prorettype != VOIDOID &&
     843         176 :         !IsPolymorphicType(proc->prorettype))
     844           4 :         ereport(ERROR,
     845             :                 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
     846             :                  errmsg("SQL functions cannot return type %s",
     847             :                         format_type_be(proc->prorettype))));
     848             : 
     849             :     /* Disallow pseudotypes in arguments */
     850             :     /* except for polymorphic */
     851        6066 :     haspolyarg = false;
     852       16442 :     for (i = 0; i < proc->pronargs; i++)
     853             :     {
     854       10376 :         if (get_typtype(proc->proargtypes.values[i]) == TYPTYPE_PSEUDO)
     855             :         {
     856         780 :             if (IsPolymorphicType(proc->proargtypes.values[i]))
     857         780 :                 haspolyarg = true;
     858             :             else
     859           0 :                 ereport(ERROR,
     860             :                         (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
     861             :                          errmsg("SQL functions cannot have arguments of type %s",
     862             :                                 format_type_be(proc->proargtypes.values[i]))));
     863             :         }
     864             :     }
     865             : 
     866             :     /* Postpone body checks if !check_function_bodies */
     867        6066 :     if (check_function_bodies)
     868             :     {
     869        5916 :         tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull);
     870        5916 :         if (isnull)
     871           0 :             elog(ERROR, "null prosrc");
     872             : 
     873        5916 :         prosrc = TextDatumGetCString(tmp);
     874             : 
     875             :         /*
     876             :          * Setup error traceback support for ereport().
     877             :          */
     878        5916 :         callback_arg.proname = NameStr(proc->proname);
     879        5916 :         callback_arg.prosrc = prosrc;
     880             : 
     881        5916 :         sqlerrcontext.callback = sql_function_parse_error_callback;
     882        5916 :         sqlerrcontext.arg = (void *) &callback_arg;
     883        5916 :         sqlerrcontext.previous = error_context_stack;
     884        5916 :         error_context_stack = &sqlerrcontext;
     885             : 
     886             :         /*
     887             :          * We can't do full prechecking of the function definition if there
     888             :          * are any polymorphic input types, because actual datatypes of
     889             :          * expression results will be unresolvable.  The check will be done at
     890             :          * runtime instead.
     891             :          *
     892             :          * We can run the text through the raw parser though; this will at
     893             :          * least catch silly syntactic errors.
     894             :          */
     895        5916 :         raw_parsetree_list = pg_parse_query(prosrc);
     896             : 
     897        5912 :         if (!haspolyarg)
     898             :         {
     899             :             /*
     900             :              * OK to do full precheck: analyze and rewrite the queries, then
     901             :              * verify the result type.
     902             :              */
     903             :             SQLFunctionParseInfoPtr pinfo;
     904             :             Oid         rettype;
     905             :             TupleDesc   rettupdesc;
     906             : 
     907             :             /* But first, set up parameter information */
     908        5318 :             pinfo = prepare_sql_fn_parse_info(tuple, NULL, InvalidOid);
     909             : 
     910        5318 :             querytree_list = NIL;
     911       10722 :             foreach(lc, raw_parsetree_list)
     912             :             {
     913        5412 :                 RawStmt    *parsetree = lfirst_node(RawStmt, lc);
     914             :                 List       *querytree_sublist;
     915             : 
     916        5412 :                 querytree_sublist = pg_analyze_and_rewrite_params(parsetree,
     917             :                                                                   prosrc,
     918             :                                                                   (ParserSetupHook) sql_fn_parser_setup,
     919             :                                                                   pinfo,
     920             :                                                                   NULL);
     921        5404 :                 querytree_list = list_concat(querytree_list,
     922             :                                              querytree_sublist);
     923             :             }
     924             : 
     925        5310 :             check_sql_fn_statements(querytree_list);
     926             : 
     927        5306 :             (void) get_func_result_type(funcoid, &rettype, &rettupdesc);
     928             : 
     929        5306 :             (void) check_sql_fn_retval(querytree_list,
     930             :                                        rettype, rettupdesc,
     931             :                                        false, NULL);
     932             :         }
     933             : 
     934        5892 :         error_context_stack = sqlerrcontext.previous;
     935             :     }
     936             : 
     937        6042 :     ReleaseSysCache(tuple);
     938             : 
     939        6042 :     PG_RETURN_VOID();
     940             : }
     941             : 
     942             : /*
     943             :  * Error context callback for handling errors in SQL function definitions
     944             :  */
     945             : static void
     946          24 : sql_function_parse_error_callback(void *arg)
     947             : {
     948          24 :     parse_error_callback_arg *callback_arg = (parse_error_callback_arg *) arg;
     949             : 
     950             :     /* See if it's a syntax error; if so, transpose to CREATE FUNCTION */
     951          24 :     if (!function_parse_error_transpose(callback_arg->prosrc))
     952             :     {
     953             :         /* If it's not a syntax error, push info onto context stack */
     954          12 :         errcontext("SQL function \"%s\"", callback_arg->proname);
     955             :     }
     956          24 : }
     957             : 
     958             : /*
     959             :  * Adjust a syntax error occurring inside the function body of a CREATE
     960             :  * FUNCTION or DO command.  This can be used by any function validator or
     961             :  * anonymous-block handler, not only for SQL-language functions.
     962             :  * It is assumed that the syntax error position is initially relative to the
     963             :  * function body string (as passed in).  If possible, we adjust the position
     964             :  * to reference the original command text; if we can't manage that, we set
     965             :  * up an "internal query" syntax error instead.
     966             :  *
     967             :  * Returns true if a syntax error was processed, false if not.
     968             :  */
     969             : bool
     970         168 : function_parse_error_transpose(const char *prosrc)
     971             : {
     972             :     int         origerrposition;
     973             :     int         newerrposition;
     974             :     const char *queryText;
     975             : 
     976             :     /*
     977             :      * Nothing to do unless we are dealing with a syntax error that has a
     978             :      * cursor position.
     979             :      *
     980             :      * Some PLs may prefer to report the error position as an internal error
     981             :      * to begin with, so check that too.
     982             :      */
     983         168 :     origerrposition = geterrposition();
     984         168 :     if (origerrposition <= 0)
     985             :     {
     986         148 :         origerrposition = getinternalerrposition();
     987         148 :         if (origerrposition <= 0)
     988          24 :             return false;
     989             :     }
     990             : 
     991             :     /* We can get the original query text from the active portal (hack...) */
     992             :     Assert(ActivePortal && ActivePortal->status == PORTAL_ACTIVE);
     993         144 :     queryText = ActivePortal->sourceText;
     994             : 
     995             :     /* Try to locate the prosrc in the original text */
     996         144 :     newerrposition = match_prosrc_to_query(prosrc, queryText, origerrposition);
     997             : 
     998         144 :     if (newerrposition > 0)
     999             :     {
    1000             :         /* Successful, so fix error position to reference original query */
    1001         144 :         errposition(newerrposition);
    1002             :         /* Get rid of any report of the error as an "internal query" */
    1003         144 :         internalerrposition(0);
    1004         144 :         internalerrquery(NULL);
    1005             :     }
    1006             :     else
    1007             :     {
    1008             :         /*
    1009             :          * If unsuccessful, convert the position to an internal position
    1010             :          * marker and give the function text as the internal query.
    1011             :          */
    1012           0 :         errposition(0);
    1013           0 :         internalerrposition(origerrposition);
    1014           0 :         internalerrquery(prosrc);
    1015             :     }
    1016             : 
    1017         144 :     return true;
    1018             : }
    1019             : 
    1020             : /*
    1021             :  * Try to locate the string literal containing the function body in the
    1022             :  * given text of the CREATE FUNCTION or DO command.  If successful, return
    1023             :  * the character (not byte) index within the command corresponding to the
    1024             :  * given character index within the literal.  If not successful, return 0.
    1025             :  */
    1026             : static int
    1027         144 : match_prosrc_to_query(const char *prosrc, const char *queryText,
    1028             :                       int cursorpos)
    1029             : {
    1030             :     /*
    1031             :      * Rather than fully parsing the original command, we just scan the
    1032             :      * command looking for $prosrc$ or 'prosrc'.  This could be fooled (though
    1033             :      * not in any very probable scenarios), so fail if we find more than one
    1034             :      * match.
    1035             :      */
    1036         144 :     int         prosrclen = strlen(prosrc);
    1037         144 :     int         querylen = strlen(queryText);
    1038         144 :     int         matchpos = 0;
    1039             :     int         curpos;
    1040             :     int         newcursorpos;
    1041             : 
    1042        9752 :     for (curpos = 0; curpos < querylen - prosrclen; curpos++)
    1043             :     {
    1044        9608 :         if (queryText[curpos] == '$' &&
    1045         272 :             strncmp(prosrc, &queryText[curpos + 1], prosrclen) == 0 &&
    1046         136 :             queryText[curpos + 1 + prosrclen] == '$')
    1047             :         {
    1048             :             /*
    1049             :              * Found a $foo$ match.  Since there are no embedded quoting
    1050             :              * characters in a dollar-quoted literal, we don't have to do any
    1051             :              * fancy arithmetic; just offset by the starting position.
    1052             :              */
    1053         136 :             if (matchpos)
    1054           0 :                 return 0;       /* multiple matches, fail */
    1055         136 :             matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
    1056             :                 + cursorpos;
    1057             :         }
    1058        9480 :         else if (queryText[curpos] == '\'' &&
    1059           8 :                  match_prosrc_to_literal(prosrc, &queryText[curpos + 1],
    1060             :                                          cursorpos, &newcursorpos))
    1061             :         {
    1062             :             /*
    1063             :              * Found a 'foo' match.  match_prosrc_to_literal() has adjusted
    1064             :              * for any quotes or backslashes embedded in the literal.
    1065             :              */
    1066           8 :             if (matchpos)
    1067           0 :                 return 0;       /* multiple matches, fail */
    1068           8 :             matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
    1069           8 :                 + newcursorpos;
    1070             :         }
    1071             :     }
    1072             : 
    1073         144 :     return matchpos;
    1074             : }
    1075             : 
    1076             : /*
    1077             :  * Try to match the given source text to a single-quoted literal.
    1078             :  * If successful, adjust newcursorpos to correspond to the character
    1079             :  * (not byte) index corresponding to cursorpos in the source text.
    1080             :  *
    1081             :  * At entry, literal points just past a ' character.  We must check for the
    1082             :  * trailing quote.
    1083             :  */
    1084             : static bool
    1085           8 : match_prosrc_to_literal(const char *prosrc, const char *literal,
    1086             :                         int cursorpos, int *newcursorpos)
    1087             : {
    1088           8 :     int         newcp = cursorpos;
    1089             :     int         chlen;
    1090             : 
    1091             :     /*
    1092             :      * This implementation handles backslashes and doubled quotes in the
    1093             :      * string literal.  It does not handle the SQL syntax for literals
    1094             :      * continued across line boundaries.
    1095             :      *
    1096             :      * We do the comparison a character at a time, not a byte at a time, so
    1097             :      * that we can do the correct cursorpos math.
    1098             :      */
    1099          96 :     while (*prosrc)
    1100             :     {
    1101          88 :         cursorpos--;            /* characters left before cursor */
    1102             : 
    1103             :         /*
    1104             :          * Check for backslashes and doubled quotes in the literal; adjust
    1105             :          * newcp when one is found before the cursor.
    1106             :          */
    1107          88 :         if (*literal == '\\')
    1108             :         {
    1109           0 :             literal++;
    1110           0 :             if (cursorpos > 0)
    1111           0 :                 newcp++;
    1112             :         }
    1113          88 :         else if (*literal == '\'')
    1114             :         {
    1115           0 :             if (literal[1] != '\'')
    1116           0 :                 goto fail;
    1117           0 :             literal++;
    1118           0 :             if (cursorpos > 0)
    1119           0 :                 newcp++;
    1120             :         }
    1121          88 :         chlen = pg_mblen(prosrc);
    1122          88 :         if (strncmp(prosrc, literal, chlen) != 0)
    1123           0 :             goto fail;
    1124          88 :         prosrc += chlen;
    1125          88 :         literal += chlen;
    1126             :     }
    1127             : 
    1128           8 :     if (*literal == '\'' && literal[1] != '\'')
    1129             :     {
    1130             :         /* success */
    1131           8 :         *newcursorpos = newcp;
    1132           8 :         return true;
    1133             :     }
    1134             : 
    1135           0 : fail:
    1136             :     /* Must set *newcursorpos to suppress compiler warning */
    1137           0 :     *newcursorpos = newcp;
    1138           0 :     return false;
    1139             : }
    1140             : 
    1141             : List *
    1142         118 : oid_array_to_list(Datum datum)
    1143             : {
    1144         118 :     ArrayType  *array = DatumGetArrayTypeP(datum);
    1145             :     Datum      *values;
    1146             :     int         nelems;
    1147             :     int         i;
    1148         118 :     List       *result = NIL;
    1149             : 
    1150         118 :     deconstruct_array(array,
    1151             :                       OIDOID,
    1152             :                       sizeof(Oid), true, TYPALIGN_INT,
    1153             :                       &values, NULL, &nelems);
    1154         236 :     for (i = 0; i < nelems; i++)
    1155         118 :         result = lappend_oid(result, values[i]);
    1156         118 :     return result;
    1157             : }

Generated by: LCOV version 1.13