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