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

Generated by: LCOV version 1.14