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

Generated by: LCOV version 1.14