| 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 |
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 |
char *paramModes = NULL; |
| 132 |
Oid variadicType = InvalidOid; |
| 133 |
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 |
parameterCount = parameterTypes->dim1; |
| 155 |
if (parameterCount < 0 || parameterCount > FUNC_MAX_ARGS) |
| 156 |
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 |
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 |
ArrayType *allParamArray = (ArrayType *) DatumGetPointer(allParameterTypes); |
| 173 |
|
| 174 |
allParamCount = ARR_DIMS(allParamArray)[0]; |
| 175 |
if (ARR_NDIM(allParamArray) != 1 || |
| 176 |
allParamCount <= 0 || |
| 177 |
ARR_HASNULL(allParamArray) || |
| 178 |
ARR_ELEMTYPE(allParamArray) != OIDOID) |
| 179 |
elog(ERROR, "allParameterTypes is not a 1-D Oid array"); |
| 180 |
allParams = (Oid *) ARR_DATA_PTR(allParamArray); |
| 181 |
Assert(allParamCount >= parameterCount); |
| 182 |
/* we assume caller got the contents right */ |
| 183 |
} |
| 184 |
else |
| 185 |
{ |
| 186 |
allParamCount = parameterCount; |
| 187 |
allParams = parameterTypes->values; |
| 188 |
} |
| 189 |
|
| 190 |
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 |
ArrayType *modesArray = (ArrayType *) DatumGetPointer(parameterModes); |
| 198 |
|
| 199 |
if (ARR_NDIM(modesArray) != 1 || |
| 200 |
ARR_DIMS(modesArray)[0] != allParamCount || |
| 201 |
ARR_HASNULL(modesArray) || |
| 202 |
ARR_ELEMTYPE(modesArray) != CHAROID) |
| 203 |
elog(ERROR, "parameterModes is not a 1-D char array"); |
| 204 |
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 |
detailmsg = check_valid_polymorphic_signature(returnType, |
| 212 |
parameterTypes->values, |
| 213 |
parameterCount); |
| 214 |
if (detailmsg) |
| 215 |
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 |
detailmsg = check_valid_internal_signature(returnType, |
| 225 |
parameterTypes->values, |
| 226 |
parameterCount); |
| 227 |
if (detailmsg) |
| 228 |
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 |
if (allParameterTypes != PointerGetDatum(NULL)) |
| 237 |
{ |
| 238 |
for (i = 0; i < allParamCount; i++) |
| 239 |
{ |
| 240 |
if (paramModes == NULL || |
| 241 |
paramModes[i] == PROARGMODE_IN || |
| 242 |
paramModes[i] == PROARGMODE_VARIADIC) |
| 243 |
continue; /* ignore input-only params */ |
| 244 |
|
| 245 |
detailmsg = check_valid_polymorphic_signature(allParams[i], |
| 246 |
parameterTypes->values, |
| 247 |
parameterCount); |
| 248 |
if (detailmsg) |
| 249 |
ereport(ERROR, |
| 250 |
(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION), |
| 251 |
errmsg("cannot determine result data type"), |
| 252 |
errdetail_internal("%s", detailmsg))); |
| 253 |
detailmsg = check_valid_internal_signature(allParams[i], |
| 254 |
parameterTypes->values, |
| 255 |
parameterCount); |
| 256 |
if (detailmsg) |
| 257 |
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 |
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 |
for (i = 0; i < allParamCount; i++) |
| 273 |
{ |
| 274 |
switch (paramModes[i]) |
| 275 |
{ |
| 276 |
case PROARGMODE_IN: |
| 277 |
case PROARGMODE_INOUT: |
| 278 |
if (OidIsValid(variadicType)) |
| 279 |
elog(ERROR, "variadic parameter must be last"); |
| 280 |
break; |
| 281 |
case PROARGMODE_OUT: |
| 282 |
if (OidIsValid(variadicType) && prokind == PROKIND_PROCEDURE) |
| 283 |
elog(ERROR, "variadic parameter must be last"); |
| 284 |
break; |
| 285 |
case PROARGMODE_TABLE: |
| 286 |
/* okay */ |
| 287 |
break; |
| 288 |
case PROARGMODE_VARIADIC: |
| 289 |
if (OidIsValid(variadicType)) |
| 290 |
elog(ERROR, "variadic parameter must be last"); |
| 291 |
switch (allParams[i]) |
| 292 |
{ |
| 293 |
case ANYOID: |
| 294 |
variadicType = ANYOID; |
| 295 |
break; |
| 296 |
case ANYARRAYOID: |
| 297 |
variadicType = ANYELEMENTOID; |
| 298 |
break; |
| 299 |
case ANYCOMPATIBLEARRAYOID: |
| 300 |
variadicType = ANYCOMPATIBLEOID; |
| 301 |
break; |
| 302 |
default: |
| 303 |
variadicType = get_element_type(allParams[i]); |
| 304 |
if (!OidIsValid(variadicType)) |
| 305 |
elog(ERROR, "variadic parameter is not an array"); |
| 306 |
break; |
| 307 |
} |
| 308 |
break; |
| 309 |
default: |
| 310 |
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 |
for (i = 0; i < Natts_pg_proc; ++i) |
| 321 |
{ |
| 322 |
nulls[i] = false; |
| 323 |
values[i] = (Datum) 0; |
| 324 |
replaces[i] = true; |
| 325 |
} |
| 326 |
|
| 327 |
namestrcpy(&procname, procedureName); |
| 328 |
values[Anum_pg_proc_proname - 1] = NameGetDatum(&procname); |
| 329 |
values[Anum_pg_proc_pronamespace - 1] = ObjectIdGetDatum(procNamespace); |
| 330 |
values[Anum_pg_proc_proowner - 1] = ObjectIdGetDatum(proowner); |
| 331 |
values[Anum_pg_proc_prolang - 1] = ObjectIdGetDatum(languageObjectId); |
| 332 |
values[Anum_pg_proc_procost - 1] = Float4GetDatum(procost); |
| 333 |
values[Anum_pg_proc_prorows - 1] = Float4GetDatum(prorows); |
| 334 |
values[Anum_pg_proc_provariadic - 1] = ObjectIdGetDatum(variadicType); |
| 335 |
values[Anum_pg_proc_prosupport - 1] = ObjectIdGetDatum(prosupport); |
| 336 |
values[Anum_pg_proc_prokind - 1] = CharGetDatum(prokind); |
| 337 |
values[Anum_pg_proc_prosecdef - 1] = BoolGetDatum(security_definer); |
| 338 |
values[Anum_pg_proc_proleakproof - 1] = BoolGetDatum(isLeakProof); |
| 339 |
values[Anum_pg_proc_proisstrict - 1] = BoolGetDatum(isStrict); |
| 340 |
values[Anum_pg_proc_proretset - 1] = BoolGetDatum(returnsSet); |
| 341 |
values[Anum_pg_proc_provolatile - 1] = CharGetDatum(volatility); |
| 342 |
values[Anum_pg_proc_proparallel - 1] = CharGetDatum(parallel); |
| 343 |
values[Anum_pg_proc_pronargs - 1] = UInt16GetDatum(parameterCount); |
| 344 |
values[Anum_pg_proc_pronargdefaults - 1] = UInt16GetDatum(list_length(parameterDefaults)); |
| 345 |
values[Anum_pg_proc_prorettype - 1] = ObjectIdGetDatum(returnType); |
| 346 |
values[Anum_pg_proc_proargtypes - 1] = PointerGetDatum(parameterTypes); |
| 347 |
if (allParameterTypes != PointerGetDatum(NULL)) |
| 348 |
values[Anum_pg_proc_proallargtypes - 1] = allParameterTypes; |
| 349 |
else |
| 350 |
nulls[Anum_pg_proc_proallargtypes - 1] = true; |
| 351 |
if (parameterModes != PointerGetDatum(NULL)) |
| 352 |
values[Anum_pg_proc_proargmodes - 1] = parameterModes; |
| 353 |
else |
| 354 |
nulls[Anum_pg_proc_proargmodes - 1] = true; |
| 355 |
if (parameterNames != PointerGetDatum(NULL)) |
| 356 |
values[Anum_pg_proc_proargnames - 1] = parameterNames; |
| 357 |
else |
| 358 |
nulls[Anum_pg_proc_proargnames - 1] = true; |
| 359 |
if (parameterDefaults != NIL) |
| 360 |
values[Anum_pg_proc_proargdefaults - 1] = CStringGetTextDatum(nodeToString(parameterDefaults)); |
| 361 |
else |
| 362 |
nulls[Anum_pg_proc_proargdefaults - 1] = true; |
| 363 |
if (trftypes != PointerGetDatum(NULL)) |
| 364 |
values[Anum_pg_proc_protrftypes - 1] = trftypes; |
| 365 |
else |
| 366 |
nulls[Anum_pg_proc_protrftypes - 1] = true; |
| 367 |
values[Anum_pg_proc_prosrc - 1] = CStringGetTextDatum(prosrc); |
| 368 |
if (probin) |
| 369 |
values[Anum_pg_proc_probin - 1] = CStringGetTextDatum(probin); |
| 370 |
else |
| 371 |
nulls[Anum_pg_proc_probin - 1] = true; |
| 372 |
if (prosqlbody) |
| 373 |
values[Anum_pg_proc_prosqlbody - 1] = CStringGetTextDatum(nodeToString(prosqlbody)); |
| 374 |
else |
| 375 |
nulls[Anum_pg_proc_prosqlbody - 1] = true; |
| 376 |
if (proconfig != PointerGetDatum(NULL)) |
| 377 |
values[Anum_pg_proc_proconfig - 1] = proconfig; |
| 378 |
else |
| 379 |
nulls[Anum_pg_proc_proconfig - 1] = true; |
| 380 |
/* proacl will be determined later */ |
| 381 |
|
| 382 |
rel = table_open(ProcedureRelationId, RowExclusiveLock); |
| 383 |
tupDesc = RelationGetDescr(rel); |
| 384 |
|
| 385 |
/* Check for pre-existing definition */ |
| 386 |
oldtup = SearchSysCache3(PROCNAMEARGSNSP, |
| 387 |
PointerGetDatum(procedureName), |
| 388 |
PointerGetDatum(parameterTypes), |
| 389 |
ObjectIdGetDatum(procNamespace)); |
| 390 |
|
| 391 |
if (HeapTupleIsValid(oldtup)) |
| 392 |
{ |
| 393 |
/* There is one; okay to replace it? */ |
| 394 |
Form_pg_proc oldproc = (Form_pg_proc) GETSTRUCT(oldtup); |
| 395 |
Datum proargnames; |
| 396 |
bool isnull; |
| 397 |
const char *dropcmd; |
| 398 |
|
| 399 |
if (!replace) |
| 400 |
ereport(ERROR, |
| 401 |
(errcode(ERRCODE_DUPLICATE_FUNCTION), |
| 402 |
errmsg("function \"%s\" already exists with same argument types", |
| 403 |
procedureName))); |
| 404 |
if (!object_ownercheck(ProcedureRelationId, oldproc->oid, proowner)) |
| 405 |
aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_FUNCTION, |
| 406 |
procedureName); |
| 407 |
|
| 408 |
/* Not okay to change routine kind */ |
| 409 |
if (oldproc->prokind != prokind) |
| 410 |
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 |
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 |
if (returnType != oldproc->prorettype || |
| 436 |
returnsSet != oldproc->proretset) |
| 437 |
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 |
if (returnType == RECORDOID) |
| 456 |
{ |
| 457 |
TupleDesc olddesc; |
| 458 |
TupleDesc newdesc; |
| 459 |
|
| 460 |
olddesc = build_function_result_tupdesc_t(oldtup); |
| 461 |
newdesc = build_function_result_tupdesc_d(prokind, |
| 462 |
allParameterTypes, |
| 463 |
parameterModes, |
| 464 |
parameterNames); |
| 465 |
if (olddesc == NULL && newdesc == NULL) |
| 466 |
/* ok, both are runtime-defined RECORDs */ ; |
| 467 |
else if (olddesc == NULL || newdesc == NULL || |
| 468 |
!equalRowTypes(olddesc, newdesc)) |
| 469 |
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 |
proargnames = SysCacheGetAttr(PROCNAMEARGSNSP, oldtup, |
| 485 |
Anum_pg_proc_proargnames, |
| 486 |
&isnull); |
| 487 |
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 |
proargmodes = SysCacheGetAttr(PROCNAMEARGSNSP, oldtup, |
| 497 |
Anum_pg_proc_proargmodes, |
| 498 |
&isnull); |
| 499 |
if (isnull) |
| 500 |
proargmodes = PointerGetDatum(NULL); /* just to be sure */ |
| 501 |
|
| 502 |
n_old_arg_names = get_func_input_arg_names(proargnames, |
| 503 |
proargmodes, |
| 504 |
&old_arg_names); |
| 505 |
n_new_arg_names = get_func_input_arg_names(parameterNames, |
| 506 |
parameterModes, |
| 507 |
&new_arg_names); |
| 508 |
for (j = 0; j < n_old_arg_names; j++) |
| 509 |
{ |
| 510 |
if (old_arg_names[j] == NULL) |
| 511 |
continue; |
| 512 |
if (j >= n_new_arg_names || new_arg_names[j] == NULL || |
| 513 |
strcmp(old_arg_names[j], new_arg_names[j]) != 0) |
| 514 |
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 |
if (oldproc->pronargdefaults != 0) |
| 534 |
{ |
| 535 |
Datum proargdefaults; |
| 536 |
List *oldDefaults; |
| 537 |
ListCell *oldlc; |
| 538 |
ListCell *newlc; |
| 539 |
|
| 540 |
if (list_length(parameterDefaults) < oldproc->pronargdefaults) |
| 541 |
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 |
proargdefaults = SysCacheGetAttrNotNull(PROCNAMEARGSNSP, oldtup, |
| 550 |
Anum_pg_proc_proargdefaults); |
| 551 |
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 |
newlc = list_nth_cell(parameterDefaults, |
| 556 |
list_length(parameterDefaults) - |
| 557 |
oldproc->pronargdefaults); |
| 558 |
|
| 559 |
foreach(oldlc, oldDefaults) |
| 560 |
{ |
| 561 |
Node *oldDef = (Node *) lfirst(oldlc); |
| 562 |
Node *newDef = (Node *) lfirst(newlc); |
| 563 |
|
| 564 |
if (exprType(oldDef) != exprType(newDef)) |
| 565 |
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 |
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 |
replaces[Anum_pg_proc_oid - 1] = false; |
| 581 |
replaces[Anum_pg_proc_proowner - 1] = false; |
| 582 |
replaces[Anum_pg_proc_proacl - 1] = false; |
| 583 |
|
| 584 |
/* Okay, do it... */ |
| 585 |
tup = heap_modify_tuple(oldtup, tupDesc, values, nulls, replaces); |
| 586 |
CatalogTupleUpdate(rel, &tup->t_self, tup); |
| 587 |
|
| 588 |
ReleaseSysCache(oldtup); |
| 589 |
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 |
proacl = get_user_default_acl(OBJECT_FUNCTION, proowner, |
| 598 |
procNamespace); |
| 599 |
if (proacl != NULL) |
| 600 |
values[Anum_pg_proc_proacl - 1] = PointerGetDatum(proacl); |
| 601 |
else |
| 602 |
nulls[Anum_pg_proc_proacl - 1] = true; |
| 603 |
|
| 604 |
newOid = GetNewOidWithIndex(rel, ProcedureOidIndexId, |
| 605 |
Anum_pg_proc_oid); |
| 606 |
values[Anum_pg_proc_oid - 1] = ObjectIdGetDatum(newOid); |
| 607 |
tup = heap_form_tuple(tupDesc, values, nulls); |
| 608 |
CatalogTupleInsert(rel, tup); |
| 609 |
is_update = false; |
| 610 |
} |
| 611 |
|
| 612 |
|
| 613 |
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 |
if (is_update) |
| 622 |
deleteDependencyRecordsFor(ProcedureRelationId, retval, true); |
| 623 |
|
| 624 |
addrs = new_object_addresses(); |
| 625 |
|
| 626 |
ObjectAddressSet(myself, ProcedureRelationId, retval); |
| 627 |
|
| 628 |
/* dependency on namespace */ |
| 629 |
ObjectAddressSet(referenced, NamespaceRelationId, procNamespace); |
| 630 |
add_exact_object_address(&referenced, addrs); |
| 631 |
|
| 632 |
/* dependency on implementation language */ |
| 633 |
ObjectAddressSet(referenced, LanguageRelationId, languageObjectId); |
| 634 |
add_exact_object_address(&referenced, addrs); |
| 635 |
|
| 636 |
/* dependency on return type */ |
| 637 |
ObjectAddressSet(referenced, TypeRelationId, returnType); |
| 638 |
add_exact_object_address(&referenced, addrs); |
| 639 |
|
| 640 |
/* dependency on parameter types */ |
| 641 |
for (i = 0; i < allParamCount; i++) |
| 642 |
{ |
| 643 |
ObjectAddressSet(referenced, TypeRelationId, allParams[i]); |
| 644 |
add_exact_object_address(&referenced, addrs); |
| 645 |
} |
| 646 |
|
| 647 |
/* dependency on transforms, if any */ |
| 648 |
foreach_oid(transformid, trfoids) |
| 649 |
{ |
| 650 |
ObjectAddressSet(referenced, TransformRelationId, transformid); |
| 651 |
add_exact_object_address(&referenced, addrs); |
| 652 |
} |
| 653 |
|
| 654 |
/* dependency on support function, if any */ |
| 655 |
if (OidIsValid(prosupport)) |
| 656 |
{ |
| 657 |
ObjectAddressSet(referenced, ProcedureRelationId, prosupport); |
| 658 |
add_exact_object_address(&referenced, addrs); |
| 659 |
} |
| 660 |
|
| 661 |
record_object_address_dependencies(&myself, addrs, DEPENDENCY_NORMAL); |
| 662 |
free_object_addresses(addrs); |
| 663 |
|
| 664 |
/* dependency on SQL routine body */ |
| 665 |
if (languageObjectId == SQLlanguageId && prosqlbody) |
| 666 |
{ |
| 667 |
CheckUsageOnTypesInExpr(prosqlbody, NIL, GetUserId()); |
| 668 |
recordDependencyOnExpr(&myself, prosqlbody, NIL, DEPENDENCY_NORMAL); |
| 669 |
} |
| 670 |
|
| 671 |
/* dependency on parameter default expressions */ |
| 672 |
if (parameterDefaults) |
| 673 |
{ |
| 674 |
CheckUsageOnTypesInExpr((Node *) parameterDefaults, NIL, GetUserId()); |
| 675 |
recordDependencyOnExpr(&myself, (Node *) parameterDefaults, |
| 676 |
NIL, DEPENDENCY_NORMAL); |
| 677 |
} |
| 678 |
|
| 679 |
/* dependency on owner */ |
| 680 |
if (!is_update) |
| 681 |
recordDependencyOnOwner(ProcedureRelationId, retval, proowner); |
| 682 |
|
| 683 |
/* dependency on any roles mentioned in ACL */ |
| 684 |
if (!is_update) |
| 685 |
recordDependencyOnNewAcl(ProcedureRelationId, retval, 0, |
| 686 |
proowner, proacl); |
| 687 |
|
| 688 |
/* dependency on extension */ |
| 689 |
recordDependencyOnCurrentExtension(&myself, is_update); |
| 690 |
|
| 691 |
heap_freetuple(tup); |
| 692 |
|
| 693 |
/* Post creation hook for new function */ |
| 694 |
InvokeObjectPostCreateHook(ProcedureRelationId, retval, 0); |
| 695 |
|
| 696 |
table_close(rel, RowExclusiveLock); |
| 697 |
|
| 698 |
/* Verify function body */ |
| 699 |
if (OidIsValid(languageValidator)) |
| 700 |
{ |
| 701 |
ArrayType *set_items = NULL; |
| 702 |
int save_nestlevel = 0; |
| 703 |
|
| 704 |
/* Advance command counter so new tuple can be seen by validator */ |
| 705 |
CommandCounterIncrement(); |
| 706 |
|
| 707 |
/* |
| 708 |
* Set per-function configuration parameters so that the validation is |
| 709 |
* done with the environment the function expects. However, if |
| 710 |
* check_function_bodies is off, we don't do this, because that would |
| 711 |
* create dump ordering hazards that pg_dump doesn't know how to deal |
| 712 |
* with. (For example, a SET clause might refer to a not-yet-created |
| 713 |
* text search configuration.) This means that the validator |
| 714 |
* shouldn't complain about anything that might depend on a GUC |
| 715 |
* parameter when check_function_bodies is off. |
| 716 |
*/ |
| 717 |
if (check_function_bodies) |
| 718 |
{ |
| 719 |
set_items = (ArrayType *) DatumGetPointer(proconfig); |
| 720 |
if (set_items) /* Need a new GUC nesting level */ |
| 721 |
{ |
| 722 |
save_nestlevel = NewGUCNestLevel(); |
| 723 |
ProcessGUCArray(set_items, |
| 724 |
(superuser() ? PGC_SUSET : PGC_USERSET), |
| 725 |
PGC_S_SESSION, |
| 726 |
GUC_ACTION_SAVE); |
| 727 |
} |
| 728 |
} |
| 729 |
|
| 730 |
OidFunctionCall1(languageValidator, ObjectIdGetDatum(retval)); |
| 731 |
|
| 732 |
if (set_items) |
| 733 |
AtEOXact_GUC(true, save_nestlevel); |
| 734 |
} |
| 735 |
|
| 736 |
/* ensure that stats are dropped if transaction aborts */ |
| 737 |
if (!is_update) |
| 738 |
pgstat_create_function(retval); |
| 739 |
|
| 740 |
return myself; |
| 741 |
} |
| 742 |
|
| 743 |
|
| 744 |
|
| 745 |
/* |
| 746 |
* Validator for internal functions |
| 747 |
* |
| 748 |
* Check that the given internal function name (the "prosrc" value) is |
| 749 |
* a known builtin function. |
| 750 |
*/ |
| 751 |
Datum |
| 752 |
fmgr_internal_validator(PG_FUNCTION_ARGS) |
| 753 |
{ |
| 754 |
Oid funcoid = PG_GETARG_OID(0); |
| 755 |
HeapTuple tuple; |
| 756 |
Datum tmp; |
| 757 |
char *prosrc; |
| 758 |
|
| 759 |
if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid)) |
| 760 |
PG_RETURN_VOID(); |
| 761 |
|
| 762 |
/* |
| 763 |
* We do not honor check_function_bodies since it's unlikely the function |
| 764 |
* name will be found later if it isn't there now. |
| 765 |
*/ |
| 766 |
|
| 767 |
tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid)); |
| 768 |
if (!HeapTupleIsValid(tuple)) |
| 769 |
elog(ERROR, "cache lookup failed for function %u", funcoid); |
| 770 |
|
| 771 |
tmp = SysCacheGetAttrNotNull(PROCOID, tuple, Anum_pg_proc_prosrc); |
| 772 |
prosrc = TextDatumGetCString(tmp); |
| 773 |
|
| 774 |
if (fmgr_internal_function(prosrc) == InvalidOid) |
| 775 |
ereport(ERROR, |
| 776 |
(errcode(ERRCODE_UNDEFINED_FUNCTION), |
| 777 |
errmsg("there is no built-in function named \"%s\"", |
| 778 |
prosrc))); |
| 779 |
|
| 780 |
ReleaseSysCache(tuple); |
| 781 |
|
| 782 |
PG_RETURN_VOID(); |
| 783 |
} |
| 784 |
|
| 785 |
|
| 786 |
|
| 787 |
/* |
| 788 |
* Validator for C language functions |
| 789 |
* |
| 790 |
* Make sure that the library file exists, is loadable, and contains |
| 791 |
* the specified link symbol. Also check for a valid function |
| 792 |
* information record. |
| 793 |
*/ |
| 794 |
Datum |
| 795 |
fmgr_c_validator(PG_FUNCTION_ARGS) |
| 796 |
{ |
| 797 |
Oid funcoid = PG_GETARG_OID(0); |
| 798 |
void *libraryhandle; |
| 799 |
HeapTuple tuple; |
| 800 |
Datum tmp; |
| 801 |
char *prosrc; |
| 802 |
char *probin; |
| 803 |
|
| 804 |
if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid)) |
| 805 |
PG_RETURN_VOID(); |
| 806 |
|
| 807 |
/* |
| 808 |
* It'd be most consistent to skip the check if !check_function_bodies, |
| 809 |
* but the purpose of that switch is to be helpful for pg_dump loading, |
| 810 |
* and for pg_dump loading it's much better if we *do* check. |
| 811 |
*/ |
| 812 |
|
| 813 |
tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid)); |
| 814 |
if (!HeapTupleIsValid(tuple)) |
| 815 |
elog(ERROR, "cache lookup failed for function %u", funcoid); |
| 816 |
|
| 817 |
tmp = SysCacheGetAttrNotNull(PROCOID, tuple, Anum_pg_proc_prosrc); |
| 818 |
prosrc = TextDatumGetCString(tmp); |
| 819 |
|
| 820 |
tmp = SysCacheGetAttrNotNull(PROCOID, tuple, Anum_pg_proc_probin); |
| 821 |
probin = TextDatumGetCString(tmp); |
| 822 |
|
| 823 |
(void) load_external_function(probin, prosrc, true, &libraryhandle); |
| 824 |
(void) fetch_finfo_record(libraryhandle, prosrc); |
| 825 |
|
| 826 |
ReleaseSysCache(tuple); |
| 827 |
|
| 828 |
PG_RETURN_VOID(); |
| 829 |
} |
| 830 |
|
| 831 |
|
| 832 |
/* |
| 833 |
* Validator for SQL language functions |
| 834 |
* |
| 835 |
* Parse it here in order to be sure that it contains no syntax errors. |
| 836 |
*/ |
| 837 |
Datum |
| 838 |
fmgr_sql_validator(PG_FUNCTION_ARGS) |
| 839 |
{ |
| 840 |
Oid funcoid = PG_GETARG_OID(0); |
| 841 |
HeapTuple tuple; |
| 842 |
Form_pg_proc proc; |
| 843 |
List *raw_parsetree_list; |
| 844 |
List *querytree_list; |
| 845 |
ListCell *lc; |
| 846 |
bool isnull; |
| 847 |
Datum tmp; |
| 848 |
char *prosrc; |
| 849 |
parse_error_callback_arg callback_arg; |
| 850 |
ErrorContextCallback sqlerrcontext; |
| 851 |
bool haspolyarg; |
| 852 |
int i; |
| 853 |
|
| 854 |
if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid)) |
| 855 |
PG_RETURN_VOID(); |
| 856 |
|
| 857 |
tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid)); |
| 858 |
if (!HeapTupleIsValid(tuple)) |
| 859 |
elog(ERROR, "cache lookup failed for function %u", funcoid); |
| 860 |
proc = (Form_pg_proc) GETSTRUCT(tuple); |
| 861 |
|
| 862 |
/* Disallow pseudotype result */ |
| 863 |
/* except for RECORD, VOID, or polymorphic */ |
| 864 |
if (get_typtype(proc->prorettype) == TYPTYPE_PSEUDO && |
| 865 |
proc->prorettype != RECORDOID && |
| 866 |
proc->prorettype != VOIDOID && |
| 867 |
!IsPolymorphicType(proc->prorettype)) |
| 868 |
ereport(ERROR, |
| 869 |
(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION), |
| 870 |
errmsg("SQL functions cannot return type %s", |
| 871 |
format_type_be(proc->prorettype)))); |
| 872 |
|
| 873 |
/* Disallow pseudotypes in arguments */ |
| 874 |
/* except for polymorphic */ |
| 875 |
haspolyarg = false; |
| 876 |
for (i = 0; i < proc->pronargs; i++) |
| 877 |
{ |
| 878 |
if (get_typtype(proc->proargtypes.values[i]) == TYPTYPE_PSEUDO) |
| 879 |
{ |
| 880 |
if (IsPolymorphicType(proc->proargtypes.values[i])) |
| 881 |
haspolyarg = true; |
| 882 |
else |
| 883 |
ereport(ERROR, |
| 884 |
(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION), |
| 885 |
errmsg("SQL functions cannot have arguments of type %s", |
| 886 |
format_type_be(proc->proargtypes.values[i])))); |
| 887 |
} |
| 888 |
} |
| 889 |
|
| 890 |
/* Postpone body checks if !check_function_bodies */ |
| 891 |
if (check_function_bodies) |
| 892 |
{ |
| 893 |
tmp = SysCacheGetAttrNotNull(PROCOID, tuple, Anum_pg_proc_prosrc); |
| 894 |
prosrc = TextDatumGetCString(tmp); |
| 895 |
|
| 896 |
/* |
| 897 |
* Setup error traceback support for ereport(). |
| 898 |
*/ |
| 899 |
callback_arg.proname = NameStr(proc->proname); |
| 900 |
callback_arg.prosrc = prosrc; |
| 901 |
|
| 902 |
sqlerrcontext.callback = sql_function_parse_error_callback; |
| 903 |
sqlerrcontext.arg = &callback_arg; |
| 904 |
sqlerrcontext.previous = error_context_stack; |
| 905 |
error_context_stack = &sqlerrcontext; |
| 906 |
|
| 907 |
/* If we have prosqlbody, pay attention to that not prosrc */ |
| 908 |
tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosqlbody, &isnull); |
| 909 |
if (!isnull) |
| 910 |
{ |
| 911 |
Node *n; |
| 912 |
List *stored_query_list; |
| 913 |
|
| 914 |
n = stringToNode(TextDatumGetCString(tmp)); |
| 915 |
if (IsA(n, List)) |
| 916 |
stored_query_list = linitial(castNode(List, n)); |
| 917 |
else |
| 918 |
stored_query_list = list_make1(n); |
| 919 |
|
| 920 |
querytree_list = NIL; |
| 921 |
foreach(lc, stored_query_list) |
| 922 |
{ |
| 923 |
Query *parsetree = lfirst_node(Query, lc); |
| 924 |
List *querytree_sublist; |
| 925 |
|
| 926 |
/* |
| 927 |
* Typically, we'd have acquired locks already while parsing |
| 928 |
* the body of the CREATE FUNCTION command. However, a |
| 929 |
* validator function cannot assume that it's only called in |
| 930 |
* that context. |
| 931 |
*/ |
| 932 |
AcquireRewriteLocks(parsetree, true, false); |
| 933 |
querytree_sublist = pg_rewrite_query(parsetree); |
| 934 |
querytree_list = lappend(querytree_list, querytree_sublist); |
| 935 |
} |
| 936 |
} |
| 937 |
else |
| 938 |
{ |
| 939 |
/* |
| 940 |
* We can't do full prechecking of the function definition if |
| 941 |
* there are any polymorphic input types, because actual datatypes |
| 942 |
* of expression results will be unresolvable. The check will be |
| 943 |
* done at runtime instead. |
| 944 |
* |
| 945 |
* We can run the text through the raw parser though; this will at |
| 946 |
* least catch silly syntactic errors. |
| 947 |
*/ |
| 948 |
raw_parsetree_list = pg_parse_query(prosrc); |
| 949 |
querytree_list = NIL; |
| 950 |
|
| 951 |
if (!haspolyarg) |
| 952 |
{ |
| 953 |
/* |
| 954 |
* OK to do full precheck: analyze and rewrite the queries, |
| 955 |
* then verify the result type. |
| 956 |
*/ |
| 957 |
SQLFunctionParseInfoPtr pinfo; |
| 958 |
|
| 959 |
/* But first, set up parameter information */ |
| 960 |
pinfo = prepare_sql_fn_parse_info(tuple, NULL, InvalidOid); |
| 961 |
|
| 962 |
foreach(lc, raw_parsetree_list) |
| 963 |
{ |
| 964 |
RawStmt *parsetree = lfirst_node(RawStmt, lc); |
| 965 |
List *querytree_sublist; |
| 966 |
|
| 967 |
querytree_sublist = pg_analyze_and_rewrite_withcb(parsetree, |
| 968 |
prosrc, |
| 969 |
(ParserSetupHook) sql_fn_parser_setup, |
| 970 |
pinfo, |
| 971 |
NULL); |
| 972 |
querytree_list = lappend(querytree_list, |
| 973 |
querytree_sublist); |
| 974 |
} |
| 975 |
} |
| 976 |
} |
| 977 |
|
| 978 |
if (!haspolyarg) |
| 979 |
{ |
| 980 |
Oid rettype; |
| 981 |
TupleDesc rettupdesc; |
| 982 |
|
| 983 |
check_sql_fn_statements(querytree_list); |
| 984 |
|
| 985 |
(void) get_func_result_type(funcoid, &rettype, &rettupdesc); |
| 986 |
|
| 987 |
(void) check_sql_fn_retval(querytree_list, |
| 988 |
rettype, rettupdesc, |
| 989 |
proc->prokind, |
| 990 |
false); |
| 991 |
} |
| 992 |
|
| 993 |
error_context_stack = sqlerrcontext.previous; |
| 994 |
} |
| 995 |
|
| 996 |
ReleaseSysCache(tuple); |
| 997 |
|
| 998 |
PG_RETURN_VOID(); |
| 999 |
} |
| 1000 |
|
| 1001 |
/* |
| 1002 |
* Error context callback for handling errors in SQL function definitions |
| 1003 |
*/ |
| 1004 |
static void |
| 1005 |
sql_function_parse_error_callback(void *arg) |
| 1006 |
{ |
| 1007 |
parse_error_callback_arg *callback_arg = (parse_error_callback_arg *) arg; |
| 1008 |
|
| 1009 |
/* See if it's a syntax error; if so, transpose to CREATE FUNCTION */ |
| 1010 |
if (!function_parse_error_transpose(callback_arg->prosrc)) |
| 1011 |
{ |
| 1012 |
/* If it's not a syntax error, push info onto context stack */ |
| 1013 |
errcontext("SQL function \"%s\"", callback_arg->proname); |
| 1014 |
} |
| 1015 |
} |
| 1016 |
|
| 1017 |
/* |
| 1018 |
* Adjust a syntax error occurring inside the function body of a CREATE |
| 1019 |
* FUNCTION or DO command. This can be used by any function validator or |
| 1020 |
* anonymous-block handler, not only for SQL-language functions. |
| 1021 |
* It is assumed that the syntax error position is initially relative to the |
| 1022 |
* function body string (as passed in). If possible, we adjust the position |
| 1023 |
* to reference the original command text; if we can't manage that, we set |
| 1024 |
* up an "internal query" syntax error instead. |
| 1025 |
* |
| 1026 |
* Returns true if a syntax error was processed, false if not. |
| 1027 |
*/ |
| 1028 |
bool |
| 1029 |
function_parse_error_transpose(const char *prosrc) |
| 1030 |
{ |
| 1031 |
int origerrposition; |
| 1032 |
int newerrposition; |
| 1033 |
|
| 1034 |
/* |
| 1035 |
* Nothing to do unless we are dealing with a syntax error that has a |
| 1036 |
* cursor position. |
| 1037 |
* |
| 1038 |
* Some PLs may prefer to report the error position as an internal error |
| 1039 |
* to begin with, so check that too. |
| 1040 |
*/ |
| 1041 |
origerrposition = geterrposition(); |
| 1042 |
if (origerrposition <= 0) |
| 1043 |
{ |
| 1044 |
origerrposition = getinternalerrposition(); |
| 1045 |
if (origerrposition <= 0) |
| 1046 |
return false; |
| 1047 |
} |
| 1048 |
|
| 1049 |
/* We can get the original query text from the active portal (hack...) */ |
| 1050 |
if (ActivePortal && ActivePortal->status == PORTAL_ACTIVE) |
| 1051 |
{ |
| 1052 |
const char *queryText = ActivePortal->sourceText; |
| 1053 |
|
| 1054 |
/* Try to locate the prosrc in the original text */ |
| 1055 |
newerrposition = match_prosrc_to_query(prosrc, queryText, |
| 1056 |
origerrposition); |
| 1057 |
} |
| 1058 |
else |
| 1059 |
{ |
| 1060 |
/* |
| 1061 |
* Quietly give up if no ActivePortal. This is an unusual situation |
| 1062 |
* but it can happen in, e.g., logical replication workers. |
| 1063 |
*/ |
| 1064 |
newerrposition = -1; |
| 1065 |
} |
| 1066 |
|
| 1067 |
if (newerrposition > 0) |
| 1068 |
{ |
| 1069 |
/* Successful, so fix error position to reference original query */ |
| 1070 |
errposition(newerrposition); |
| 1071 |
/* Get rid of any report of the error as an "internal query" */ |
| 1072 |
internalerrposition(0); |
| 1073 |
internalerrquery(NULL); |
| 1074 |
} |
| 1075 |
else |
| 1076 |
{ |
| 1077 |
/* |
| 1078 |
* If unsuccessful, convert the position to an internal position |
| 1079 |
* marker and give the function text as the internal query. |
| 1080 |
*/ |
| 1081 |
errposition(0); |
| 1082 |
internalerrposition(origerrposition); |
| 1083 |
internalerrquery(prosrc); |
| 1084 |
} |
| 1085 |
|
| 1086 |
return true; |
| 1087 |
} |
| 1088 |
|
| 1089 |
/* |
| 1090 |
* Try to locate the string literal containing the function body in the |
| 1091 |
* given text of the CREATE FUNCTION or DO command. If successful, return |
| 1092 |
* the character (not byte) index within the command corresponding to the |
| 1093 |
* given character index within the literal. If not successful, return 0. |
| 1094 |
*/ |
| 1095 |
static int |
| 1096 |
match_prosrc_to_query(const char *prosrc, const char *queryText, |
| 1097 |
int cursorpos) |
| 1098 |
{ |
| 1099 |
/* |
| 1100 |
* Rather than fully parsing the original command, we just scan the |
| 1101 |
* command looking for $prosrc$ or 'prosrc'. This could be fooled (though |
| 1102 |
* not in any very probable scenarios), so fail if we find more than one |
| 1103 |
* match. |
| 1104 |
*/ |
| 1105 |
int prosrclen = strlen(prosrc); |
| 1106 |
int querylen = strlen(queryText); |
| 1107 |
int matchpos = 0; |
| 1108 |
int curpos; |
| 1109 |
int newcursorpos; |
| 1110 |
|
| 1111 |
for (curpos = 0; curpos < querylen - prosrclen; curpos++) |
| 1112 |
{ |
| 1113 |
if (queryText[curpos] == '$' && |
| 1114 |
strncmp(prosrc, &queryText[curpos + 1], prosrclen) == 0 && |
| 1115 |
queryText[curpos + 1 + prosrclen] == '$') |
| 1116 |
{ |
| 1117 |
/* |
| 1118 |
* Found a $foo$ match. Since there are no embedded quoting |
| 1119 |
* characters in a dollar-quoted literal, we don't have to do any |
| 1120 |
* fancy arithmetic; just offset by the starting position. |
| 1121 |
*/ |
| 1122 |
if (matchpos) |
| 1123 |
return 0; /* multiple matches, fail */ |
| 1124 |
matchpos = pg_mbstrlen_with_len(queryText, curpos + 1) |
| 1125 |
+ cursorpos; |
| 1126 |
} |
| 1127 |
else if (queryText[curpos] == '\'' && |
| 1128 |
match_prosrc_to_literal(prosrc, &queryText[curpos + 1], |
| 1129 |
cursorpos, &newcursorpos)) |
| 1130 |
{ |
| 1131 |
/* |
| 1132 |
* Found a 'foo' match. match_prosrc_to_literal() has adjusted |
| 1133 |
* for any quotes or backslashes embedded in the literal. |
| 1134 |
*/ |
| 1135 |
if (matchpos) |
| 1136 |
return 0; /* multiple matches, fail */ |
| 1137 |
matchpos = pg_mbstrlen_with_len(queryText, curpos + 1) |
| 1138 |
+ newcursorpos; |
| 1139 |
} |
| 1140 |
} |
| 1141 |
|
| 1142 |
return matchpos; |
| 1143 |
} |
| 1144 |
|
| 1145 |
/* |
| 1146 |
* Try to match the given source text to a single-quoted literal. |
| 1147 |
* If successful, adjust newcursorpos to correspond to the character |
| 1148 |
* (not byte) index corresponding to cursorpos in the source text. |
| 1149 |
* |
| 1150 |
* At entry, literal points just past a ' character. We must check for the |
| 1151 |
* trailing quote. |
| 1152 |
*/ |
| 1153 |
static bool |
| 1154 |
match_prosrc_to_literal(const char *prosrc, const char *literal, |
| 1155 |
int cursorpos, int *newcursorpos) |
| 1156 |
{ |
| 1157 |
int newcp = cursorpos; |
| 1158 |
int chlen; |
| 1159 |
|
| 1160 |
/* |
| 1161 |
* This implementation handles backslashes and doubled quotes in the |
| 1162 |
* string literal. It does not handle the SQL syntax for literals |
| 1163 |
* continued across line boundaries. |
| 1164 |
* |
| 1165 |
* We do the comparison a character at a time, not a byte at a time, so |
| 1166 |
* that we can do the correct cursorpos math. |
| 1167 |
*/ |
| 1168 |
while (*prosrc) |
| 1169 |
{ |
| 1170 |
cursorpos--; /* characters left before cursor */ |
| 1171 |
|
| 1172 |
/* |
| 1173 |
* Check for backslashes and doubled quotes in the literal; adjust |
| 1174 |
* newcp when one is found before the cursor. |
| 1175 |
*/ |
| 1176 |
if (*literal == '\\') |
| 1177 |
{ |
| 1178 |
literal++; |
| 1179 |
if (cursorpos > 0) |
| 1180 |
newcp++; |
| 1181 |
} |
| 1182 |
else if (*literal == '\'') |
| 1183 |
{ |
| 1184 |
if (literal[1] != '\'') |
| 1185 |
goto fail; |
| 1186 |
literal++; |
| 1187 |
if (cursorpos > 0) |
| 1188 |
newcp++; |
| 1189 |
} |
| 1190 |
chlen = pg_mblen_cstr(prosrc); |
| 1191 |
if (strncmp(prosrc, literal, chlen) != 0) |
| 1192 |
goto fail; |
| 1193 |
prosrc += chlen; |
| 1194 |
literal += chlen; |
| 1195 |
} |
| 1196 |
|
| 1197 |
if (*literal == '\'' && literal[1] != '\'') |
| 1198 |
{ |
| 1199 |
/* success */ |
| 1200 |
*newcursorpos = newcp; |
| 1201 |
return true; |
| 1202 |
} |
| 1203 |
|
| 1204 |
fail: |
| 1205 |
/* Must set *newcursorpos to suppress compiler warning */ |
| 1206 |
*newcursorpos = newcp; |
| 1207 |
return false; |
| 1208 |
} |
| 1209 |
|
| 1210 |
List * |
| 1211 |
oid_array_to_list(Datum datum) |
| 1212 |
{ |
| 1213 |
ArrayType *array = DatumGetArrayTypeP(datum); |
| 1214 |
Datum *values; |
| 1215 |
int nelems; |
| 1216 |
int i; |
| 1217 |
List *result = NIL; |
| 1218 |
|
| 1219 |
deconstruct_array_builtin(array, OIDOID, &values, NULL, &nelems); |
| 1220 |
for (i = 0; i < nelems; i++) |
| 1221 |
result = lappend_oid(result, values[i]); |
| 1222 |
return result; |
| 1223 |
} |