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
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;
104 35978 : char *paramModes = NULL;
105 35978 : Oid variadicType = InvalidOid;
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 : */
126 35978 : Assert(PointerIsValid(prosrc));
127 :
128 35978 : parameterCount = parameterTypes->dim1;
129 35978 : if (parameterCount < 0 || parameterCount > FUNC_MAX_ARGS)
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 */
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 : */
146 3765 : ArrayType *allParamArray = (ArrayType *) DatumGetPointer(allParameterTypes);
147 :
148 3765 : allParamCount = ARR_DIMS(allParamArray)[0];
149 3765 : if (ARR_NDIM(allParamArray) != 1 ||
150 3765 : allParamCount <= 0 ||
151 3765 : ARR_HASNULL(allParamArray) ||
152 3765 : ARR_ELEMTYPE(allParamArray) != OIDOID)
153 UBC 0 : elog(ERROR, "allParameterTypes is not a 1-D Oid array");
154 CBC 3765 : allParams = (Oid *) ARR_DATA_PTR(allParamArray);
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 :
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)
177 UBC 0 : elog(ERROR, "parameterModes is not a 1-D char array");
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 : */
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)
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 : */
210 CBC 35939 : if (allParameterTypes != PointerGetDatum(NULL))
211 : {
212 26268 : for (i = 0; i < allParamCount; i++)
213 : {
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 :
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)
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 */
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 : */
246 26214 : for (i = 0; i < allParamCount; i++)
247 : {
248 22473 : switch (paramModes[i])
249 : {
250 8118 : case PROARGMODE_IN:
251 : case PROARGMODE_INOUT:
252 8118 : if (OidIsValid(variadicType))
253 UBC 0 : elog(ERROR, "variadic parameter must be last");
254 CBC 8118 : break;
255 12860 : case PROARGMODE_OUT:
256 12860 : if (OidIsValid(variadicType) && prokind == PROKIND_PROCEDURE)
257 UBC 0 : elog(ERROR, "variadic parameter must be last");
258 CBC 12860 : break;
259 164 : case PROARGMODE_TABLE:
260 : /* okay */
261 164 : break;
262 1331 : case PROARGMODE_VARIADIC:
263 1331 : if (OidIsValid(variadicType))
264 UBC 0 : elog(ERROR, "variadic parameter must be last");
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;
273 11 : case ANYCOMPATIBLEARRAYOID:
274 11 : variadicType = ANYCOMPATIBLEOID;
275 11 : break;
276 1296 : default:
277 1296 : variadicType = get_element_type(allParams[i]);
278 1296 : if (!OidIsValid(variadicType))
279 UBC 0 : elog(ERROR, "variadic parameter is not an array");
280 CBC 1296 : break;
281 : }
282 1331 : break;
283 UBC 0 : default:
284 0 : elog(ERROR, "invalid parameter mode '%c'", paramModes[i]);
285 : break;
286 : }
287 : }
288 : }
289 :
290 : /*
291 : * All seems OK; prepare the data to be inserted into pg_proc.
292 : */
293 :
294 CBC 1113365 : for (i = 0; i < Natts_pg_proc; ++i)
295 : {
296 1077450 : nulls[i] = false;
297 1077450 : values[i] = (Datum) 0;
298 1077450 : replaces[i] = true;
299 : }
300 :
301 35915 : namestrcpy(&procname, procedureName);
302 35915 : values[Anum_pg_proc_proname - 1] = NameGetDatum(&procname);
303 35915 : values[Anum_pg_proc_pronamespace - 1] = ObjectIdGetDatum(procNamespace);
304 35915 : values[Anum_pg_proc_proowner - 1] = ObjectIdGetDatum(proowner);
305 35915 : values[Anum_pg_proc_prolang - 1] = ObjectIdGetDatum(languageObjectId);
306 35915 : values[Anum_pg_proc_procost - 1] = Float4GetDatum(procost);
307 35915 : values[Anum_pg_proc_prorows - 1] = Float4GetDatum(prorows);
308 35915 : values[Anum_pg_proc_provariadic - 1] = ObjectIdGetDatum(variadicType);
309 35915 : values[Anum_pg_proc_prosupport - 1] = ObjectIdGetDatum(prosupport);
310 35915 : values[Anum_pg_proc_prokind - 1] = CharGetDatum(prokind);
311 35915 : values[Anum_pg_proc_prosecdef - 1] = BoolGetDatum(security_definer);
312 35915 : values[Anum_pg_proc_proleakproof - 1] = BoolGetDatum(isLeakProof);
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);
316 35915 : values[Anum_pg_proc_proparallel - 1] = CharGetDatum(parallel);
317 35915 : values[Anum_pg_proc_pronargs - 1] = UInt16GetDatum(parameterCount);
318 35915 : values[Anum_pg_proc_pronargdefaults - 1] = UInt16GetDatum(list_length(parameterDefaults));
319 35915 : values[Anum_pg_proc_prorettype - 1] = ObjectIdGetDatum(returnType);
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
324 32174 : nulls[Anum_pg_proc_proallargtypes - 1] = true;
325 35915 : if (parameterModes != PointerGetDatum(NULL))
326 3741 : values[Anum_pg_proc_proargmodes - 1] = parameterModes;
327 : else
328 32174 : nulls[Anum_pg_proc_proargmodes - 1] = true;
329 35915 : if (parameterNames != PointerGetDatum(NULL))
330 12961 : values[Anum_pg_proc_proargnames - 1] = parameterNames;
331 : else
332 22954 : nulls[Anum_pg_proc_proargnames - 1] = true;
333 35915 : if (parameterDefaults != NIL)
334 10426 : values[Anum_pg_proc_proargdefaults - 1] = CStringGetTextDatum(nodeToString(parameterDefaults));
335 : else
336 25489 : nulls[Anum_pg_proc_proargdefaults - 1] = true;
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;
341 35915 : values[Anum_pg_proc_prosrc - 1] = CStringGetTextDatum(prosrc);
342 35915 : if (probin)
343 3490 : values[Anum_pg_proc_probin - 1] = CStringGetTextDatum(probin);
344 : else
345 32425 : nulls[Anum_pg_proc_probin - 1] = true;
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;
350 35915 : if (proconfig != PointerGetDatum(NULL))
351 28 : values[Anum_pg_proc_proconfig - 1] = proconfig;
352 : else
353 35887 : nulls[Anum_pg_proc_proconfig - 1] = true;
354 : /* proacl will be determined later */
355 :
356 35915 : rel = table_open(ProcedureRelationId, RowExclusiveLock);
357 35915 : tupDesc = RelationGetDescr(rel);
358 :
359 : /* Check for pre-existing definition */
360 35915 : oldtup = SearchSysCache3(PROCNAMEARGSNSP,
361 : PointerGetDatum(procedureName),
362 : PointerGetDatum(parameterTypes),
363 : ObjectIdGetDatum(procNamespace));
364 :
365 35915 : if (HeapTupleIsValid(oldtup))
366 : {
367 : /* There is one; okay to replace it? */
368 24653 : Form_pg_proc oldproc = (Form_pg_proc) GETSTRUCT(oldtup);
369 : Datum proargnames;
370 : bool isnull;
371 : const char *dropcmd;
372 :
373 24653 : if (!replace)
374 UBC 0 : ereport(ERROR,
375 : (errcode(ERRCODE_DUPLICATE_FUNCTION),
376 : errmsg("function \"%s\" already exists with same argument types",
377 : procedureName)));
378 GNC 24653 : if (!object_ownercheck(ProcedureRelationId, oldproc->oid, proowner))
379 UBC 0 : aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_FUNCTION,
380 : procedureName);
381 :
382 : /* Not okay to change routine kind */
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 :
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 : */
409 24644 : if (returnType != oldproc->prorettype ||
410 24638 : returnsSet != oldproc->proretset)
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 : */
429 24638 : if (returnType == RECORDOID)
430 : {
431 : TupleDesc olddesc;
432 : TupleDesc newdesc;
433 :
434 2764 : olddesc = build_function_result_tupdesc_t(oldtup);
435 2764 : newdesc = build_function_result_tupdesc_d(prokind,
436 : allParameterTypes,
437 : parameterModes,
438 : parameterNames);
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))
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 : */
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 :
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);
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 : */
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 :
523 UNC 0 : proargdefaults = SysCacheGetAttrNotNull(PROCNAMEARGSNSP, oldtup,
524 : Anum_pg_proc_proargdefaults);
525 UIC 0 : oldDefaults = castNode(List, stringToNode(TextDatumGetCString(proargdefaults)));
526 0 : Assert(list_length(oldDefaults) == oldproc->pronargdefaults);
527 EUB :
528 : /* new list can have more defaults than old, advance over 'em */
529 UBC 0 : newlc = list_nth_cell(parameterDefaults,
530 UIC 0 : list_length(parameterDefaults) -
531 UBC 0 : oldproc->pronargdefaults);
532 :
533 0 : foreach(oldlc, oldDefaults)
534 EUB : {
535 UIC 0 : Node *oldDef = (Node *) lfirst(oldlc);
536 UBC 0 : Node *newDef = (Node *) lfirst(newlc);
537 EUB :
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.",
544 EUB : dropcmd,
545 : format_procedure(oldproc->oid))));
546 UIC 0 : newlc = lnext(parameterDefaults, newlc);
547 : }
548 : }
549 :
550 : /*
551 : * Do not change existing oid, ownership or permissions, either. Note
552 ECB : * dependency-update code below has to agree with this decision.
553 : */
554 CBC 24626 : replaces[Anum_pg_proc_oid - 1] = false;
555 GIC 24626 : replaces[Anum_pg_proc_proowner - 1] = false;
556 24626 : replaces[Anum_pg_proc_proacl - 1] = false;
557 ECB :
558 : /* Okay, do it... */
559 GIC 24626 : tup = heap_modify_tuple(oldtup, tupDesc, values, nulls, replaces);
560 CBC 24626 : CatalogTupleUpdate(rel, &tup->t_self, tup);
561 ECB :
562 GIC 24626 : ReleaseSysCache(oldtup);
563 24626 : is_update = true;
564 : }
565 : else
566 : {
567 : /* Creating a new procedure */
568 : Oid newOid;
569 ECB :
570 : /* First, get default permissions and set up proacl */
571 CBC 11262 : proacl = get_user_default_acl(OBJECT_FUNCTION, proowner,
572 ECB : procNamespace);
573 GIC 11262 : if (proacl != NULL)
574 CBC 9 : values[Anum_pg_proc_proacl - 1] = PointerGetDatum(proacl);
575 : else
576 11253 : nulls[Anum_pg_proc_proacl - 1] = true;
577 :
578 11262 : newOid = GetNewOidWithIndex(rel, ProcedureOidIndexId,
579 ECB : Anum_pg_proc_oid);
580 CBC 11262 : values[Anum_pg_proc_oid - 1] = ObjectIdGetDatum(newOid);
581 11262 : tup = heap_form_tuple(tupDesc, values, nulls);
582 GIC 11262 : CatalogTupleInsert(rel, tup);
583 11262 : is_update = false;
584 : }
585 ECB :
586 :
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
593 ECB : * shared dependencies do *not* need to change, and we leave them alone.)
594 : */
595 GIC 35888 : if (is_update)
596 CBC 24626 : deleteDependencyRecordsFor(ProcedureRelationId, retval, true);
597 :
598 35888 : addrs = new_object_addresses();
599 :
600 GIC 35888 : ObjectAddressSet(myself, ProcedureRelationId, retval);
601 ECB :
602 : /* dependency on namespace */
603 GIC 35888 : ObjectAddressSet(referenced, NamespaceRelationId, procNamespace);
604 35888 : add_exact_object_address(&referenced, addrs);
605 ECB :
606 : /* dependency on implementation language */
607 GIC 35888 : ObjectAddressSet(referenced, LanguageRelationId, languageObjectId);
608 35888 : add_exact_object_address(&referenced, addrs);
609 ECB :
610 : /* dependency on return type */
611 GIC 35888 : ObjectAddressSet(referenced, TypeRelationId, returnType);
612 35888 : add_exact_object_address(&referenced, addrs);
613 ECB :
614 : /* dependency on transform used by return type, if any */
615 CBC 35888 : if ((trfid = get_transform_oid(returnType, languageObjectId, true)))
616 ECB : {
617 GIC 165 : ObjectAddressSet(referenced, TransformRelationId, trfid);
618 165 : add_exact_object_address(&referenced, addrs);
619 : }
620 ECB :
621 : /* dependency on parameter types */
622 CBC 127400 : for (i = 0; i < allParamCount; i++)
623 ECB : {
624 GIC 91512 : ObjectAddressSet(referenced, TypeRelationId, allParams[i]);
625 91512 : add_exact_object_address(&referenced, addrs);
626 ECB :
627 : /* dependency on transform used by parameter type, if any */
628 CBC 91512 : if ((trfid = get_transform_oid(allParams[i], languageObjectId, true)))
629 ECB : {
630 GIC 355 : ObjectAddressSet(referenced, TransformRelationId, trfid);
631 355 : add_exact_object_address(&referenced, addrs);
632 : }
633 : }
634 ECB :
635 : /* dependency on support function, if any */
636 CBC 35888 : if (OidIsValid(prosupport))
637 ECB : {
638 GIC 6 : ObjectAddressSet(referenced, ProcedureRelationId, prosupport);
639 6 : add_exact_object_address(&referenced, addrs);
640 ECB : }
641 :
642 GIC 35888 : record_object_address_dependencies(&myself, addrs, DEPENDENCY_NORMAL);
643 35888 : free_object_addresses(addrs);
644 ECB :
645 : /* dependency on SQL routine body */
646 GIC 35888 : if (languageObjectId == SQLlanguageId && prosqlbody)
647 17032 : recordDependencyOnExpr(&myself, prosqlbody, NIL, DEPENDENCY_NORMAL);
648 ECB :
649 : /* dependency on parameter default expressions */
650 GIC 35888 : if (parameterDefaults)
651 10420 : recordDependencyOnExpr(&myself, (Node *) parameterDefaults,
652 : NIL, DEPENDENCY_NORMAL);
653 ECB :
654 : /* dependency on owner */
655 GIC 35888 : if (!is_update)
656 11262 : recordDependencyOnOwner(ProcedureRelationId, retval, proowner);
657 ECB :
658 : /* dependency on any roles mentioned in ACL */
659 GIC 35888 : if (!is_update)
660 11262 : recordDependencyOnNewAcl(ProcedureRelationId, retval, 0,
661 : proowner, proacl);
662 ECB :
663 : /* dependency on extension */
664 CBC 35888 : recordDependencyOnCurrentExtension(&myself, is_update);
665 :
666 GIC 35887 : heap_freetuple(tup);
667 ECB :
668 : /* Post creation hook for new function */
669 CBC 35887 : InvokeObjectPostCreateHook(ProcedureRelationId, retval, 0);
670 :
671 GIC 35887 : table_close(rel, RowExclusiveLock);
672 ECB :
673 : /* Verify function body */
674 CBC 35887 : if (OidIsValid(languageValidator))
675 ECB : {
676 GIC 35536 : ArrayType *set_items = NULL;
677 35536 : int save_nestlevel = 0;
678 ECB :
679 : /* Advance command counter so new tuple can be seen by validator */
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
690 ECB : * parameter when check_function_bodies is off.
691 : */
692 CBC 35536 : if (check_function_bodies)
693 ECB : {
694 GIC 32156 : set_items = (ArrayType *) DatumGetPointer(proconfig);
695 CBC 32156 : if (set_items) /* Need a new GUC nesting level */
696 ECB : {
697 GIC 22 : save_nestlevel = NewGUCNestLevel();
698 CBC 22 : ProcessGUCArray(set_items,
699 : NULL,
700 GIC 22 : (superuser() ? PGC_SUSET : PGC_USERSET),
701 : PGC_S_SESSION,
702 : GUC_ACTION_SAVE);
703 : }
704 : }
705 ECB :
706 GIC 35530 : OidFunctionCall1(languageValidator, ObjectIdGetDatum(retval));
707 ECB :
708 CBC 35442 : if (set_items)
709 GIC 16 : AtEOXact_GUC(true, save_nestlevel);
710 : }
711 :
712 ECB : /* ensure that stats are dropped if transaction aborts */
713 CBC 35793 : if (!is_update)
714 GIC 11168 : pgstat_create_function(retval);
715 ECB :
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 : */
727 ECB : Datum
728 GIC 11005 : fmgr_internal_validator(PG_FUNCTION_ARGS)
729 ECB : {
730 GIC 11005 : Oid funcoid = PG_GETARG_OID(0);
731 : HeapTuple tuple;
732 : Datum tmp;
733 ECB : char *prosrc;
734 EUB :
735 GIC 11005 : if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
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.
741 ECB : */
742 :
743 GBC 11005 : tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
744 GIC 11005 : if (!HeapTupleIsValid(tuple))
745 LBC 0 : elog(ERROR, "cache lookup failed for function %u", funcoid);
746 ECB :
747 GNC 11005 : tmp = SysCacheGetAttrNotNull(PROCOID, tuple, Anum_pg_proc_prosrc);
748 GIC 11005 : prosrc = TextDatumGetCString(tmp);
749 :
750 11005 : if (fmgr_internal_function(prosrc) == InvalidOid)
751 3 : ereport(ERROR,
752 ECB : (errcode(ERRCODE_UNDEFINED_FUNCTION),
753 : errmsg("there is no built-in function named \"%s\"",
754 : prosrc)));
755 :
756 GIC 11002 : ReleaseSysCache(tuple);
757 :
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
767 ECB : * the specified link symbol. Also check for a valid function
768 : * information record.
769 : */
770 : Datum
771 GIC 3490 : fmgr_c_validator(PG_FUNCTION_ARGS)
772 : {
773 3490 : Oid funcoid = PG_GETARG_OID(0);
774 : void *libraryhandle;
775 : HeapTuple tuple;
776 EUB : Datum tmp;
777 : char *prosrc;
778 : char *probin;
779 :
780 GIC 3490 : if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
781 UIC 0 : PG_RETURN_VOID();
782 :
783 : /*
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,
786 EUB : * and for pg_dump loading it's much better if we *do* check.
787 : */
788 ECB :
789 CBC 3490 : tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
790 GIC 3490 : if (!HeapTupleIsValid(tuple))
791 LBC 0 : elog(ERROR, "cache lookup failed for function %u", funcoid);
792 ECB :
793 GNC 3490 : tmp = SysCacheGetAttrNotNull(PROCOID, tuple, Anum_pg_proc_prosrc);
794 GIC 3490 : prosrc = TextDatumGetCString(tmp);
795 ECB :
796 GNC 3490 : tmp = SysCacheGetAttrNotNull(PROCOID, tuple, Anum_pg_proc_probin);
797 GIC 3490 : probin = TextDatumGetCString(tmp);
798 :
799 3490 : (void) load_external_function(probin, prosrc, true, &libraryhandle);
800 3484 : (void) fetch_finfo_record(libraryhandle, prosrc);
801 :
802 3484 : ReleaseSysCache(tuple);
803 :
804 3484 : PG_RETURN_VOID();
805 ECB : }
806 :
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
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;
821 ECB : ListCell *lc;
822 EUB : bool isnull;
823 : Datum tmp;
824 ECB : char *prosrc;
825 : parse_error_callback_arg callback_arg;
826 EUB : ErrorContextCallback sqlerrcontext;
827 ECB : bool haspolyarg;
828 : int i;
829 :
830 GIC 18531 : if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
831 LBC 0 : PG_RETURN_VOID();
832 ECB :
833 CBC 18531 : tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
834 18531 : if (!HeapTupleIsValid(tuple))
835 LBC 0 : elog(ERROR, "cache lookup failed for function %u", funcoid);
836 GIC 18531 : proc = (Form_pg_proc) GETSTRUCT(tuple);
837 :
838 : /* Disallow pseudotype result */
839 : /* except for RECORD, VOID, or polymorphic */
840 18531 : if (get_typtype(proc->prorettype) == TYPTYPE_PSEUDO &&
841 1967 : proc->prorettype != RECORDOID &&
842 CBC 904 : proc->prorettype != VOIDOID &&
843 185 : !IsPolymorphicType(proc->prorettype))
844 GIC 3 : ereport(ERROR,
845 ECB : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
846 : errmsg("SQL functions cannot return type %s",
847 : format_type_be(proc->prorettype))));
848 :
849 : /* Disallow pseudotypes in arguments */
850 EUB : /* except for polymorphic */
851 GIC 18528 : haspolyarg = false;
852 55538 : for (i = 0; i < proc->pronargs; i++)
853 : {
854 37010 : if (get_typtype(proc->proargtypes.values[i]) == TYPTYPE_PSEUDO)
855 : {
856 729 : if (IsPolymorphicType(proc->proargtypes.values[i]))
857 729 : haspolyarg = true;
858 ECB : else
859 UIC 0 : ereport(ERROR,
860 ECB : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
861 : errmsg("SQL functions cannot have arguments of type %s",
862 : format_type_be(proc->proargtypes.values[i]))));
863 : }
864 : }
865 :
866 : /* Postpone body checks if !check_function_bodies */
867 CBC 18528 : if (check_function_bodies)
868 : {
869 GNC 18362 : tmp = SysCacheGetAttrNotNull(PROCOID, tuple, Anum_pg_proc_prosrc);
870 GIC 18362 : prosrc = TextDatumGetCString(tmp);
871 :
872 ECB : /*
873 : * Setup error traceback support for ereport().
874 : */
875 GIC 18362 : callback_arg.proname = NameStr(proc->proname);
876 18362 : callback_arg.prosrc = prosrc;
877 :
878 CBC 18362 : sqlerrcontext.callback = sql_function_parse_error_callback;
879 18362 : sqlerrcontext.arg = (void *) &callback_arg;
880 18362 : sqlerrcontext.previous = error_context_stack;
881 GIC 18362 : error_context_stack = &sqlerrcontext;
882 ECB :
883 : /* If we have prosqlbody, pay attention to that not prosrc */
884 CBC 18362 : tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosqlbody, &isnull);
885 18362 : if (!isnull)
886 : {
887 ECB : Node *n;
888 : List *stored_query_list;
889 :
890 GIC 17028 : n = stringToNode(TextDatumGetCString(tmp));
891 17028 : if (IsA(n, List))
892 2154 : stored_query_list = linitial(castNode(List, n));
893 : else
894 14874 : stored_query_list = list_make1(n);
895 :
896 CBC 17028 : querytree_list = NIL;
897 34056 : foreach(lc, stored_query_list)
898 ECB : {
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 : }
912 ECB : }
913 : else
914 : {
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 : */
924 CBC 1334 : raw_parsetree_list = pg_parse_query(prosrc);
925 GIC 1331 : querytree_list = NIL;
926 ECB :
927 GIC 1331 : if (!haspolyarg)
928 ECB : {
929 : /*
930 : * OK to do full precheck: analyze and rewrite the queries,
931 : * then verify the result type.
932 : */
933 : SQLFunctionParseInfoPtr pinfo;
934 :
935 : /* But first, set up parameter information */
936 CBC 774 : pinfo = prepare_sql_fn_parse_info(tuple, NULL, InvalidOid);
937 :
938 GIC 1600 : foreach(lc, raw_parsetree_list)
939 : {
940 832 : RawStmt *parsetree = lfirst_node(RawStmt, lc);
941 : List *querytree_sublist;
942 ECB :
943 GIC 832 : querytree_sublist = pg_analyze_and_rewrite_withcb(parsetree,
944 : prosrc,
945 : (ParserSetupHook) sql_fn_parser_setup,
946 : pinfo,
947 ECB : NULL);
948 GIC 826 : querytree_list = lappend(querytree_list,
949 ECB : querytree_sublist);
950 : }
951 : }
952 : }
953 :
954 GIC 18353 : if (!haspolyarg)
955 : {
956 ECB : Oid rettype;
957 : TupleDesc rettupdesc;
958 :
959 CBC 17796 : check_sql_fn_statements(querytree_list);
960 :
961 17793 : (void) get_func_result_type(funcoid, &rettype, &rettupdesc);
962 :
963 GIC 17793 : (void) check_sql_fn_retval(querytree_list,
964 : rettype, rettupdesc,
965 : false, NULL);
966 : }
967 :
968 CBC 18344 : error_context_stack = sqlerrcontext.previous;
969 : }
970 ECB :
971 GIC 18510 : ReleaseSysCache(tuple);
972 :
973 CBC 18510 : PG_RETURN_VOID();
974 : }
975 :
976 ECB : /*
977 : * Error context callback for handling errors in SQL function definitions
978 : */
979 : static void
980 GIC 18 : sql_function_parse_error_callback(void *arg)
981 : {
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 : }
990 18 : }
991 :
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
1004 CBC 119 : function_parse_error_transpose(const char *prosrc)
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 : *
1013 : * Some PLs may prefer to report the error position as an internal error
1014 : * to begin with, so check that too.
1015 : */
1016 GIC 119 : origerrposition = geterrposition();
1017 119 : if (origerrposition <= 0)
1018 ECB : {
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...) */
1025 101 : if (ActivePortal && ActivePortal->status == PORTAL_ACTIVE)
1026 101 : {
1027 GBC 101 : const char *queryText = ActivePortal->sourceText;
1028 :
1029 : /* Try to locate the prosrc in the original text */
1030 CBC 101 : newerrposition = match_prosrc_to_query(prosrc, queryText,
1031 : origerrposition);
1032 : }
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 : */
1039 UIC 0 : newerrposition = -1;
1040 : }
1041 :
1042 GIC 101 : if (newerrposition > 0)
1043 : {
1044 EUB : /* Successful, so fix error position to reference original query */
1045 GBC 101 : errposition(newerrposition);
1046 EUB : /* Get rid of any report of the error as an "internal query" */
1047 GIC 101 : internalerrposition(0);
1048 101 : internalerrquery(NULL);
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 : */
1056 UIC 0 : errposition(0);
1057 0 : internalerrposition(origerrposition);
1058 0 : internalerrquery(prosrc);
1059 ECB : }
1060 :
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
1068 ECB : * given character index within the literal. If not successful, return 0.
1069 : */
1070 : static int
1071 GIC 101 : match_prosrc_to_query(const char *prosrc, const char *queryText,
1072 : int cursorpos)
1073 : {
1074 ECB : /*
1075 : * Rather than fully parsing the original command, we just scan the
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 : */
1080 GIC 101 : int prosrclen = strlen(prosrc);
1081 101 : int querylen = strlen(queryText);
1082 101 : int matchpos = 0;
1083 : int curpos;
1084 : int newcursorpos;
1085 ECB :
1086 GBC 6983 : for (curpos = 0; curpos < querylen - prosrclen; curpos++)
1087 ECB : {
1088 GIC 6882 : if (queryText[curpos] == '$' &&
1089 190 : strncmp(prosrc, &queryText[curpos + 1], prosrclen) == 0 &&
1090 CBC 95 : queryText[curpos + 1 + prosrclen] == '$')
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 : */
1097 GIC 95 : if (matchpos)
1098 LBC 0 : return 0; /* multiple matches, fail */
1099 GBC 95 : matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
1100 ECB : + cursorpos;
1101 : }
1102 GIC 6793 : else if (queryText[curpos] == '\'' &&
1103 6 : match_prosrc_to_literal(prosrc, &queryText[curpos + 1],
1104 : cursorpos, &newcursorpos))
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 : */
1110 GIC 6 : if (matchpos)
1111 UIC 0 : return 0; /* multiple matches, fail */
1112 GIC 6 : matchpos = pg_mbstrlen_with_len(queryText, curpos + 1)
1113 6 : + newcursorpos;
1114 : }
1115 : }
1116 :
1117 CBC 101 : return matchpos;
1118 : }
1119 :
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
1129 GIC 6 : match_prosrc_to_literal(const char *prosrc, const char *literal,
1130 : int cursorpos, int *newcursorpos)
1131 ECB : {
1132 GIC 6 : int newcp = cursorpos;
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.
1139 : *
1140 : * We do the comparison a character at a time, not a byte at a time, so
1141 EUB : * that we can do the correct cursorpos math.
1142 : */
1143 GBC 72 : while (*prosrc)
1144 : {
1145 CBC 66 : cursorpos--; /* characters left before cursor */
1146 :
1147 EUB : /*
1148 : * Check for backslashes and doubled quotes in the literal; adjust
1149 : * newcp when one is found before the cursor.
1150 : */
1151 GBC 66 : if (*literal == '\\')
1152 : {
1153 LBC 0 : literal++;
1154 0 : if (cursorpos > 0)
1155 UBC 0 : newcp++;
1156 ECB : }
1157 CBC 66 : else if (*literal == '\'')
1158 : {
1159 UIC 0 : if (literal[1] != '\'')
1160 LBC 0 : goto fail;
1161 UIC 0 : literal++;
1162 0 : if (cursorpos > 0)
1163 LBC 0 : newcp++;
1164 ECB : }
1165 GIC 66 : chlen = pg_mblen(prosrc);
1166 66 : if (strncmp(prosrc, literal, chlen) != 0)
1167 UBC 0 : goto fail;
1168 GIC 66 : prosrc += chlen;
1169 GBC 66 : literal += chlen;
1170 EUB : }
1171 :
1172 GIC 6 : if (*literal == '\'' && literal[1] != '\'')
1173 : {
1174 ECB : /* success */
1175 GIC 6 : *newcursorpos = newcp;
1176 CBC 6 : return true;
1177 : }
1178 :
1179 UIC 0 : fail:
1180 ECB : /* Must set *newcursorpos to suppress compiler warning */
1181 UIC 0 : *newcursorpos = newcp;
1182 LBC 0 : return false;
1183 ECB : }
1184 :
1185 : List *
1186 GIC 59 : oid_array_to_list(Datum datum)
1187 : {
1188 59 : ArrayType *array = DatumGetArrayTypeP(datum);
1189 : Datum *values;
1190 : int nelems;
1191 : int i;
1192 59 : List *result = NIL;
1193 :
1194 GNC 59 : deconstruct_array_builtin(array, OIDOID, &values, NULL, &nelems);
1195 GIC 120 : for (i = 0; i < nelems; i++)
1196 61 : result = lappend_oid(result, values[i]);
1197 59 : return result;
1198 : }
|