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

Generated by: LCOV version 1.14