forked from nextgres/uplpgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupl_comp.c
More file actions
2375 lines (2091 loc) · 67.2 KB
/
Copy pathupl_comp.c
File metadata and controls
2375 lines (2091 loc) · 67.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-------------------------------------------------------------------------
*
* pl_comp.c - Compiler part of the PL/pgSQL
* procedural language
*
* Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
* Portions Copyright (c) 2003-2014, Jonah H. Harris <[email protected]>
* Portions Copyright (c) 2014-2026, NEXTGRES, LLC. <[email protected]>
*
* Derived from PostgreSQL src/pl/plpgsql/src/pl_comp.c; modifications are
* licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain a
* copy of the License in LICENSE or at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0 AND PostgreSQL
*
*
* IDENTIFICATION
* src/pl/plpgsql/src/pl_comp.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <ctype.h>
#include "access/htup_details.h"
#include "catalog/namespace.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "funcapi.h"
#include "nodes/makefuncs.h"
#include "parser/parse_node.h"
#include "upl_plpgsql.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/regproc.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
/* ----------
* Our own local and global variables
* ----------
*/
static int datums_alloc;
int uplpgsql_nDatums;
UPLpgSQL_datum **uplpgsql_Datums;
static int datums_last;
char *uplpgsql_error_funcname;
bool uplpgsql_DumpExecTree = false;
bool uplpgsql_check_syntax = false;
UPLpgSQL_function *uplpgsql_curr_compile;
/* A context appropriate for short-term allocs during compilation */
MemoryContext uplpgsql_compile_tmp_cxt;
/* ----------
* Lookup table for EXCEPTION condition names
* ----------
*/
typedef struct
{
const char *label;
int sqlerrstate;
} ExceptionLabelMap;
static const ExceptionLabelMap exception_label_map[] = {
#include "upl_errcodes.h"
{NULL, 0}
};
/* ----------
* static prototypes
* ----------
*/
static void uplpgsql_compile_callback(FunctionCallInfo fcinfo,
HeapTuple procTup,
const CachedFunctionHashKey *hashkey,
CachedFunction *cfunc,
bool forValidator);
static void uplpgsql_compile_error_callback(void *arg);
static void add_parameter_name(UPLpgSQL_nsitem_type itemtype, int itemno, const char *name);
static void add_dummy_return(UPLpgSQL_function *function);
static Node *uplpgsql_pre_column_ref(ParseState *pstate, ColumnRef *cref);
static Node *uplpgsql_post_column_ref(ParseState *pstate, ColumnRef *cref, Node *var);
static Node *uplpgsql_param_ref(ParseState *pstate, ParamRef *pref);
static Node *resolve_column_ref(ParseState *pstate, UPLpgSQL_expr *expr,
ColumnRef *cref, bool error_if_no_field);
static Node *make_datum_param(UPLpgSQL_expr *expr, int dno, int location);
static UPLpgSQL_row *build_row_from_vars(UPLpgSQL_variable **vars, int numvars);
static UPLpgSQL_type *build_datatype(HeapTuple typeTup, int32 typmod,
Oid collation, TypeName *origtypname);
static void uplpgsql_start_datums(void);
static void uplpgsql_finish_datums(UPLpgSQL_function *function);
/* ----------
* uplpgsql_compile Make an execution tree for a PL/pgSQL function.
*
* If forValidator is true, we're only compiling for validation purposes,
* and so some checks are skipped.
*
* Note: it's important for this to fall through quickly if the function
* has already been compiled.
* ----------
*/
UPLpgSQL_function *
uplpgsql_compile(FunctionCallInfo fcinfo, bool forValidator)
{
UPLpgSQL_function *function;
/*
* funccache.c manages re-use of existing UPLpgSQL_function caches.
*
* In PL/pgSQL we use fn_extra directly as the pointer to the long-lived
* function cache entry; we have no need for any query-lifespan cache.
* Also, we don't need to make the cache key depend on composite result
* type (at least for now).
*/
function = (UPLpgSQL_function *)
cached_function_compile(fcinfo,
fcinfo->flinfo->fn_extra,
uplpgsql_compile_callback,
uplpgsql_delete_callback,
sizeof(UPLpgSQL_function),
false,
forValidator);
/*
* Save pointer in FmgrInfo to avoid search on subsequent calls
*/
fcinfo->flinfo->fn_extra = function;
/*
* Finally return the compiled function
*/
return function;
}
struct compile_error_callback_arg
{
const char *proc_source;
yyscan_t yyscanner;
};
/*
* This is the slow part of uplpgsql_compile().
*
* The passed-in "cfunc" struct is expected to be zeroes, except
* for the CachedFunction fields, which we don't touch here.
*
* While compiling a function, the CurrentMemoryContext is the
* per-function memory context of the function we are compiling. That
* means a palloc() will allocate storage with the same lifetime as
* the function itself.
*
* Because palloc()'d storage will not be immediately freed, temporary
* allocations should either be performed in a short-lived memory
* context or explicitly pfree'd. Since not all backend functions are
* careful about pfree'ing their allocations, it is also wise to
* switch into a short-term context before calling into the
* backend. An appropriate context for performing short-term
* allocations is the uplpgsql_compile_tmp_cxt.
*
* NB: this code is not re-entrant. We assume that nothing we do here could
* result in the invocation of another plpgsql function.
*/
static void
uplpgsql_compile_callback(FunctionCallInfo fcinfo,
HeapTuple procTup,
const CachedFunctionHashKey *hashkey,
CachedFunction *cfunc,
bool forValidator)
{
UPLpgSQL_function *function = (UPLpgSQL_function *) cfunc;
Form_pg_proc procStruct = (Form_pg_proc) GETSTRUCT(procTup);
bool is_dml_trigger = CALLED_AS_TRIGGER(fcinfo);
bool is_event_trigger = CALLED_AS_EVENT_TRIGGER(fcinfo);
yyscan_t scanner;
Datum prosrcdatum;
char *proc_source;
char *proc_signature;
HeapTuple typeTup;
Form_pg_type typeStruct;
UPLpgSQL_variable *var;
UPLpgSQL_rec *rec;
int i;
struct compile_error_callback_arg cbarg;
ErrorContextCallback plerrcontext;
int parse_rc;
Oid rettypeid;
int numargs;
int num_in_args = 0;
int num_out_args = 0;
Oid *argtypes;
char **argnames;
char *argmodes;
int *in_arg_varnos = NULL;
UPLpgSQL_variable **out_arg_variables;
MemoryContext func_cxt;
/*
* Setup the scanner input and error info.
*/
prosrcdatum = SysCacheGetAttrNotNull(PROCOID, procTup, Anum_pg_proc_prosrc);
proc_source = TextDatumGetCString(prosrcdatum);
scanner = uplpgsql_scanner_init(proc_source);
uplpgsql_error_funcname = pstrdup(NameStr(procStruct->proname));
/*
* Setup error traceback support for ereport()
*/
cbarg.proc_source = forValidator ? proc_source : NULL;
cbarg.yyscanner = scanner;
plerrcontext.callback = uplpgsql_compile_error_callback;
plerrcontext.arg = &cbarg;
plerrcontext.previous = error_context_stack;
error_context_stack = &plerrcontext;
/*
* Do extra syntax checks when validating the function definition. We skip
* this when actually compiling functions for execution, for performance
* reasons.
*/
uplpgsql_check_syntax = forValidator;
uplpgsql_curr_compile = function;
/* format_procedure leaks memory, so run it in temp context */
proc_signature = format_procedure(fcinfo->flinfo->fn_oid);
/*
* All the permanent output of compilation (e.g. parse tree) is kept in a
* per-function memory context, so it can be reclaimed easily.
*
* While the func_cxt needs to be long-lived, we initially make it a child
* of the assumed-short-lived caller's context, and reparent it under
* CacheMemoryContext only upon success. This arrangement avoids memory
* leakage during compilation of a faulty function.
*/
func_cxt = AllocSetContextCreate(CurrentMemoryContext,
"PL/pgSQL function",
ALLOCSET_DEFAULT_SIZES);
uplpgsql_compile_tmp_cxt = MemoryContextSwitchTo(func_cxt);
function->fn_signature = pstrdup(proc_signature);
MemoryContextSetIdentifier(func_cxt, function->fn_signature);
function->fn_oid = fcinfo->flinfo->fn_oid;
function->fn_input_collation = fcinfo->fncollation;
function->fn_cxt = func_cxt;
function->out_param_varno = -1; /* set up for no OUT param */
function->resolve_option = uplpgsql_variable_conflict;
function->print_strict_params = uplpgsql_print_strict_params;
/* only promote extra warnings and errors at CREATE FUNCTION time */
function->extra_warnings = forValidator ? uplpgsql_extra_warnings : 0;
function->extra_errors = forValidator ? uplpgsql_extra_errors : 0;
if (is_dml_trigger)
function->fn_is_trigger = UPLPGSQL_DML_TRIGGER;
else if (is_event_trigger)
function->fn_is_trigger = UPLPGSQL_EVENT_TRIGGER;
else
function->fn_is_trigger = UPLPGSQL_NOT_TRIGGER;
function->fn_prokind = procStruct->prokind;
function->nstatements = 0;
function->requires_procedure_resowner = false;
function->has_exception_block = false;
/*
* Initialize the compiler, particularly the namespace stack. The
* outermost namespace contains function parameters and other special
* variables (such as FOUND), and is named after the function itself.
*/
uplpgsql_ns_init();
uplpgsql_ns_push(NameStr(procStruct->proname), UPLPGSQL_LABEL_BLOCK);
uplpgsql_DumpExecTree = false;
uplpgsql_start_datums();
switch (function->fn_is_trigger)
{
case UPLPGSQL_NOT_TRIGGER:
/*
* Fetch info about the procedure's parameters. Allocations aren't
* needed permanently, so make them in tmp cxt.
*
* We also need to resolve any polymorphic input or output
* argument types. In validation mode we won't be able to, so we
* arbitrarily assume we are dealing with integers.
*/
MemoryContextSwitchTo(uplpgsql_compile_tmp_cxt);
numargs = get_func_arg_info(procTup,
&argtypes, &argnames, &argmodes);
cfunc_resolve_polymorphic_argtypes(numargs, argtypes, argmodes,
fcinfo->flinfo->fn_expr,
forValidator,
uplpgsql_error_funcname);
in_arg_varnos = palloc_array(int, numargs);
out_arg_variables = palloc_array(UPLpgSQL_variable *, numargs);
MemoryContextSwitchTo(func_cxt);
/*
* Create the variables for the procedure's parameters.
*/
for (i = 0; i < numargs; i++)
{
char buf[32];
Oid argtypeid = argtypes[i];
char argmode = argmodes ? argmodes[i] : PROARGMODE_IN;
UPLpgSQL_type *argdtype;
UPLpgSQL_variable *argvariable;
UPLpgSQL_nsitem_type argitemtype;
/* Create $n name for variable */
snprintf(buf, sizeof(buf), "$%d", i + 1);
/* Create datatype info */
argdtype = uplpgsql_build_datatype(argtypeid,
-1,
function->fn_input_collation,
NULL);
/* Disallow pseudotype argument */
/* (note we already replaced polymorphic types) */
/* (build_variable would do this, but wrong message) */
if (argdtype->ttype == UPLPGSQL_TTYPE_PSEUDO)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("PL/pgSQL functions cannot accept type %s",
format_type_be(argtypeid))));
/*
* Build variable and add to datum list. If there's a name
* for the argument, use that as refname, else use $n name.
*/
argvariable = uplpgsql_build_variable((argnames &&
argnames[i][0] != '\0') ?
argnames[i] : buf,
0, argdtype, false);
if (argvariable->dtype == UPLPGSQL_DTYPE_VAR)
{
argitemtype = UPLPGSQL_NSTYPE_VAR;
}
else
{
Assert(argvariable->dtype == UPLPGSQL_DTYPE_REC);
argitemtype = UPLPGSQL_NSTYPE_REC;
}
/* Remember arguments in appropriate arrays */
if (argmode == PROARGMODE_IN ||
argmode == PROARGMODE_INOUT ||
argmode == PROARGMODE_VARIADIC)
in_arg_varnos[num_in_args++] = argvariable->dno;
if (argmode == PROARGMODE_OUT ||
argmode == PROARGMODE_INOUT ||
argmode == PROARGMODE_TABLE)
out_arg_variables[num_out_args++] = argvariable;
/* Add to namespace under the $n name */
add_parameter_name(argitemtype, argvariable->dno, buf);
/* If there's a name for the argument, make an alias */
if (argnames && argnames[i][0] != '\0')
add_parameter_name(argitemtype, argvariable->dno,
argnames[i]);
}
/*
* If there's just one OUT parameter, out_param_varno points
* directly to it. If there's more than one, build a row that
* holds all of them. Procedures return a row even for one OUT
* parameter.
*/
if (num_out_args > 1 ||
(num_out_args == 1 && function->fn_prokind == PROKIND_PROCEDURE))
{
UPLpgSQL_row *row = build_row_from_vars(out_arg_variables,
num_out_args);
uplpgsql_adddatum((UPLpgSQL_datum *) row);
function->out_param_varno = row->dno;
}
else if (num_out_args == 1)
function->out_param_varno = out_arg_variables[0]->dno;
/*
* Check for a polymorphic returntype. If found, use the actual
* returntype type from the caller's FuncExpr node, if we have
* one. (In validation mode we arbitrarily assume we are dealing
* with integers.)
*
* Note: errcode is FEATURE_NOT_SUPPORTED because it should always
* work; if it doesn't we're in some context that fails to make
* the info available.
*/
rettypeid = procStruct->prorettype;
if (IsPolymorphicType(rettypeid))
{
if (forValidator)
{
if (rettypeid == ANYARRAYOID ||
rettypeid == ANYCOMPATIBLEARRAYOID)
rettypeid = INT4ARRAYOID;
else if (rettypeid == ANYRANGEOID ||
rettypeid == ANYCOMPATIBLERANGEOID)
rettypeid = INT4RANGEOID;
else if (rettypeid == ANYMULTIRANGEOID)
rettypeid = INT4MULTIRANGEOID;
else /* ANYELEMENT or ANYNONARRAY or ANYCOMPATIBLE */
rettypeid = INT4OID;
/* XXX what could we use for ANYENUM? */
}
else
{
rettypeid = get_fn_expr_rettype(fcinfo->flinfo);
if (!OidIsValid(rettypeid))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("could not determine actual return type "
"for polymorphic function \"%s\"",
uplpgsql_error_funcname)));
}
}
/*
* Normal function has a defined returntype
*/
function->fn_rettype = rettypeid;
function->fn_retset = procStruct->proretset;
/*
* Lookup the function's return type
*/
typeTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(rettypeid));
if (!HeapTupleIsValid(typeTup))
elog(ERROR, "cache lookup failed for type %u", rettypeid);
typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
/* Disallow pseudotype result, except VOID or RECORD */
/* (note we already replaced polymorphic types) */
if (typeStruct->typtype == TYPTYPE_PSEUDO)
{
if (rettypeid == VOIDOID ||
rettypeid == RECORDOID)
/* okay */ ;
else if (rettypeid == TRIGGEROID || rettypeid == EVENT_TRIGGEROID)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("trigger functions can only be called as triggers")));
else
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("PL/pgSQL functions cannot return type %s",
format_type_be(rettypeid))));
}
function->fn_retistuple = type_is_rowtype(rettypeid);
function->fn_retisdomain = (typeStruct->typtype == TYPTYPE_DOMAIN);
function->fn_retbyval = typeStruct->typbyval;
function->fn_rettyplen = typeStruct->typlen;
/*
* install $0 reference, but only for polymorphic return types,
* and not when the return is specified through an output
* parameter.
*/
if (IsPolymorphicType(procStruct->prorettype) &&
num_out_args == 0)
{
(void) uplpgsql_build_variable("$0", 0,
build_datatype(typeTup,
-1,
function->fn_input_collation,
NULL),
true);
}
ReleaseSysCache(typeTup);
break;
case UPLPGSQL_DML_TRIGGER:
/* Trigger procedure's return type is unknown yet */
function->fn_rettype = InvalidOid;
function->fn_retbyval = false;
function->fn_retistuple = true;
function->fn_retisdomain = false;
function->fn_retset = false;
/* shouldn't be any declared arguments */
if (procStruct->pronargs != 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
errmsg("trigger functions cannot have declared arguments"),
errhint("The arguments of the trigger can be accessed through TG_NARGS and TG_ARGV instead.")));
/* Add the record for referencing NEW ROW */
rec = uplpgsql_build_record("new", 0, NULL, RECORDOID, true);
function->new_varno = rec->dno;
/* Add the record for referencing OLD ROW */
rec = uplpgsql_build_record("old", 0, NULL, RECORDOID, true);
function->old_varno = rec->dno;
/* Add the variable tg_name */
var = uplpgsql_build_variable("tg_name", 0,
uplpgsql_build_datatype(NAMEOID,
-1,
function->fn_input_collation,
NULL),
true);
Assert(var->dtype == UPLPGSQL_DTYPE_VAR);
var->dtype = UPLPGSQL_DTYPE_PROMISE;
((UPLpgSQL_var *) var)->promise = UPLPGSQL_PROMISE_TG_NAME;
/* Add the variable tg_when */
var = uplpgsql_build_variable("tg_when", 0,
uplpgsql_build_datatype(TEXTOID,
-1,
function->fn_input_collation,
NULL),
true);
Assert(var->dtype == UPLPGSQL_DTYPE_VAR);
var->dtype = UPLPGSQL_DTYPE_PROMISE;
((UPLpgSQL_var *) var)->promise = UPLPGSQL_PROMISE_TG_WHEN;
/* Add the variable tg_level */
var = uplpgsql_build_variable("tg_level", 0,
uplpgsql_build_datatype(TEXTOID,
-1,
function->fn_input_collation,
NULL),
true);
Assert(var->dtype == UPLPGSQL_DTYPE_VAR);
var->dtype = UPLPGSQL_DTYPE_PROMISE;
((UPLpgSQL_var *) var)->promise = UPLPGSQL_PROMISE_TG_LEVEL;
/* Add the variable tg_op */
var = uplpgsql_build_variable("tg_op", 0,
uplpgsql_build_datatype(TEXTOID,
-1,
function->fn_input_collation,
NULL),
true);
Assert(var->dtype == UPLPGSQL_DTYPE_VAR);
var->dtype = UPLPGSQL_DTYPE_PROMISE;
((UPLpgSQL_var *) var)->promise = UPLPGSQL_PROMISE_TG_OP;
/* Add the variable tg_relid */
var = uplpgsql_build_variable("tg_relid", 0,
uplpgsql_build_datatype(OIDOID,
-1,
InvalidOid,
NULL),
true);
Assert(var->dtype == UPLPGSQL_DTYPE_VAR);
var->dtype = UPLPGSQL_DTYPE_PROMISE;
((UPLpgSQL_var *) var)->promise = UPLPGSQL_PROMISE_TG_RELID;
/* Add the variable tg_relname */
var = uplpgsql_build_variable("tg_relname", 0,
uplpgsql_build_datatype(NAMEOID,
-1,
function->fn_input_collation,
NULL),
true);
Assert(var->dtype == UPLPGSQL_DTYPE_VAR);
var->dtype = UPLPGSQL_DTYPE_PROMISE;
((UPLpgSQL_var *) var)->promise = UPLPGSQL_PROMISE_TG_TABLE_NAME;
/* tg_table_name is now preferred to tg_relname */
var = uplpgsql_build_variable("tg_table_name", 0,
uplpgsql_build_datatype(NAMEOID,
-1,
function->fn_input_collation,
NULL),
true);
Assert(var->dtype == UPLPGSQL_DTYPE_VAR);
var->dtype = UPLPGSQL_DTYPE_PROMISE;
((UPLpgSQL_var *) var)->promise = UPLPGSQL_PROMISE_TG_TABLE_NAME;
/* add the variable tg_table_schema */
var = uplpgsql_build_variable("tg_table_schema", 0,
uplpgsql_build_datatype(NAMEOID,
-1,
function->fn_input_collation,
NULL),
true);
Assert(var->dtype == UPLPGSQL_DTYPE_VAR);
var->dtype = UPLPGSQL_DTYPE_PROMISE;
((UPLpgSQL_var *) var)->promise = UPLPGSQL_PROMISE_TG_TABLE_SCHEMA;
/* Add the variable tg_nargs */
var = uplpgsql_build_variable("tg_nargs", 0,
uplpgsql_build_datatype(INT4OID,
-1,
InvalidOid,
NULL),
true);
Assert(var->dtype == UPLPGSQL_DTYPE_VAR);
var->dtype = UPLPGSQL_DTYPE_PROMISE;
((UPLpgSQL_var *) var)->promise = UPLPGSQL_PROMISE_TG_NARGS;
/* Add the variable tg_argv */
var = uplpgsql_build_variable("tg_argv", 0,
uplpgsql_build_datatype(TEXTARRAYOID,
-1,
function->fn_input_collation,
NULL),
true);
Assert(var->dtype == UPLPGSQL_DTYPE_VAR);
var->dtype = UPLPGSQL_DTYPE_PROMISE;
((UPLpgSQL_var *) var)->promise = UPLPGSQL_PROMISE_TG_ARGV;
break;
case UPLPGSQL_EVENT_TRIGGER:
function->fn_rettype = VOIDOID;
function->fn_retbyval = false;
function->fn_retistuple = true;
function->fn_retisdomain = false;
function->fn_retset = false;
/* shouldn't be any declared arguments */
if (procStruct->pronargs != 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
errmsg("event trigger functions cannot have declared arguments")));
/* Add the variable tg_event */
var = uplpgsql_build_variable("tg_event", 0,
uplpgsql_build_datatype(TEXTOID,
-1,
function->fn_input_collation,
NULL),
true);
Assert(var->dtype == UPLPGSQL_DTYPE_VAR);
var->dtype = UPLPGSQL_DTYPE_PROMISE;
((UPLpgSQL_var *) var)->promise = UPLPGSQL_PROMISE_TG_EVENT;
/* Add the variable tg_tag */
var = uplpgsql_build_variable("tg_tag", 0,
uplpgsql_build_datatype(TEXTOID,
-1,
function->fn_input_collation,
NULL),
true);
Assert(var->dtype == UPLPGSQL_DTYPE_VAR);
var->dtype = UPLPGSQL_DTYPE_PROMISE;
((UPLpgSQL_var *) var)->promise = UPLPGSQL_PROMISE_TG_TAG;
break;
default:
elog(ERROR, "unrecognized function typecode: %d",
(int) function->fn_is_trigger);
break;
}
/* Remember if function is STABLE/IMMUTABLE */
function->fn_readonly = (procStruct->provolatile != PROVOLATILE_VOLATILE);
/*
* Create the magic FOUND variable.
*/
var = uplpgsql_build_variable("found", 0,
uplpgsql_build_datatype(BOOLOID,
-1,
InvalidOid,
NULL),
true);
function->found_varno = var->dno;
/*
* Now parse the function's text
*/
parse_rc = uplpgsql_yyparse(&function->action, scanner);
if (parse_rc != 0)
elog(ERROR, "plpgsql parser returned %d", parse_rc);
uplpgsql_scanner_finish(scanner);
pfree(proc_source);
/*
* If it has OUT parameters or returns VOID or returns a set, we allow
* control to fall off the end without an explicit RETURN statement. The
* easiest way to implement this is to add a RETURN statement to the end
* of the statement list during parsing.
*/
if (num_out_args > 0 || function->fn_rettype == VOIDOID ||
function->fn_retset)
add_dummy_return(function);
/*
* Complete the function's info
*/
function->fn_nargs = procStruct->pronargs;
for (i = 0; i < function->fn_nargs; i++)
function->fn_argvarnos[i] = in_arg_varnos[i];
uplpgsql_finish_datums(function);
if (function->has_exception_block)
uplpgsql_mark_local_assignment_targets(function);
/* Debug dump for completed functions */
if (uplpgsql_DumpExecTree)
uplpgsql_dumptree(function);
/*
* All is well, so make the func_cxt long-lived
*/
MemoryContextSetParent(func_cxt, CacheMemoryContext);
/*
* Pop the error context stack
*/
error_context_stack = plerrcontext.previous;
uplpgsql_error_funcname = NULL;
uplpgsql_check_syntax = false;
MemoryContextSwitchTo(uplpgsql_compile_tmp_cxt);
uplpgsql_compile_tmp_cxt = NULL;
}
/* ----------
* uplpgsql_compile_inline Make an execution tree for an anonymous code block.
*
* Note: this is generally parallel to uplpgsql_compile_callback(); is it worth
* trying to merge the two?
*
* Note: we assume the block will be thrown away so there is no need to build
* persistent data structures.
* ----------
*/
UPLpgSQL_function *
uplpgsql_compile_inline(char *proc_source)
{
yyscan_t scanner;
char *func_name = "inline_code_block";
UPLpgSQL_function *function;
struct compile_error_callback_arg cbarg;
ErrorContextCallback plerrcontext;
UPLpgSQL_variable *var;
int parse_rc;
MemoryContext func_cxt;
/*
* Setup the scanner input and error info.
*/
scanner = uplpgsql_scanner_init(proc_source);
uplpgsql_error_funcname = func_name;
/*
* Setup error traceback support for ereport()
*/
cbarg.proc_source = proc_source;
cbarg.yyscanner = scanner;
plerrcontext.callback = uplpgsql_compile_error_callback;
plerrcontext.arg = &cbarg;
plerrcontext.previous = error_context_stack;
error_context_stack = &plerrcontext;
/* Do extra syntax checking if check_function_bodies is on */
uplpgsql_check_syntax = check_function_bodies;
/* Function struct does not live past current statement */
function = palloc0_object(UPLpgSQL_function);
uplpgsql_curr_compile = function;
/*
* All the rest of the compile-time storage (e.g. parse tree) is kept in
* its own memory context, so it can be reclaimed easily.
*/
func_cxt = AllocSetContextCreate(CurrentMemoryContext,
"PL/pgSQL inline code context",
ALLOCSET_DEFAULT_SIZES);
uplpgsql_compile_tmp_cxt = MemoryContextSwitchTo(func_cxt);
function->fn_signature = pstrdup(func_name);
function->fn_is_trigger = UPLPGSQL_NOT_TRIGGER;
function->fn_input_collation = InvalidOid;
function->fn_cxt = func_cxt;
function->out_param_varno = -1; /* set up for no OUT param */
function->resolve_option = uplpgsql_variable_conflict;
function->print_strict_params = uplpgsql_print_strict_params;
/*
* don't do extra validation for inline code as we don't want to add spam
* at runtime
*/
function->extra_warnings = 0;
function->extra_errors = 0;
function->nstatements = 0;
function->requires_procedure_resowner = false;
function->has_exception_block = false;
uplpgsql_ns_init();
uplpgsql_ns_push(func_name, UPLPGSQL_LABEL_BLOCK);
uplpgsql_DumpExecTree = false;
uplpgsql_start_datums();
/* Set up as though in a function returning VOID */
function->fn_rettype = VOIDOID;
function->fn_retset = false;
function->fn_retistuple = false;
function->fn_retisdomain = false;
function->fn_prokind = PROKIND_FUNCTION;
/* a bit of hardwired knowledge about type VOID here */
function->fn_retbyval = true;
function->fn_rettyplen = sizeof(int32);
/*
* Remember if function is STABLE/IMMUTABLE. XXX would it be better to
* set this true inside a read-only transaction? Not clear.
*/
function->fn_readonly = false;
/*
* Create the magic FOUND variable.
*/
var = uplpgsql_build_variable("found", 0,
uplpgsql_build_datatype(BOOLOID,
-1,
InvalidOid,
NULL),
true);
function->found_varno = var->dno;
/*
* Now parse the function's text
*/
parse_rc = uplpgsql_yyparse(&function->action, scanner);
if (parse_rc != 0)
elog(ERROR, "plpgsql parser returned %d", parse_rc);
uplpgsql_scanner_finish(scanner);
/*
* If it returns VOID (always true at the moment), we allow control to
* fall off the end without an explicit RETURN statement.
*/
if (function->fn_rettype == VOIDOID)
add_dummy_return(function);
/*
* Complete the function's info
*/
function->fn_nargs = 0;
uplpgsql_finish_datums(function);
if (function->has_exception_block)
uplpgsql_mark_local_assignment_targets(function);
/* Debug dump for completed functions */
if (uplpgsql_DumpExecTree)
uplpgsql_dumptree(function);
/*
* Pop the error context stack
*/
error_context_stack = plerrcontext.previous;
uplpgsql_error_funcname = NULL;
uplpgsql_check_syntax = false;
MemoryContextSwitchTo(uplpgsql_compile_tmp_cxt);
uplpgsql_compile_tmp_cxt = NULL;
return function;
}
/*
* error context callback to let us supply a call-stack traceback.
* If we are validating or executing an anonymous code block, the function
* source text is passed as an argument.
*/
static void
uplpgsql_compile_error_callback(void *arg)
{
struct compile_error_callback_arg *cbarg = (struct compile_error_callback_arg *) arg;
yyscan_t yyscanner = cbarg->yyscanner;
if (cbarg->proc_source)
{
/*
* Try to convert syntax error position to reference text of original
* CREATE FUNCTION or DO command.
*/
if (function_parse_error_transpose(cbarg->proc_source))
return;
/*
* Done if a syntax error position was reported; otherwise we have to
* fall back to a "near line N" report.
*/
}
if (uplpgsql_error_funcname)
errcontext("compilation of PL/pgSQL function \"%s\" near line %d",
uplpgsql_error_funcname, uplpgsql_latest_lineno(yyscanner));
}
/*
* Add a name for a function parameter to the function's namespace
*/
static void
add_parameter_name(UPLpgSQL_nsitem_type itemtype, int itemno, const char *name)
{
/*
* Before adding the name, check for duplicates. We need this even though
* functioncmds.c has a similar check, because that code explicitly
* doesn't complain about conflicting IN and OUT parameter names. In
* plpgsql, such names are in the same namespace, so there is no way to
* disambiguate.
*/
if (uplpgsql_ns_lookup(uplpgsql_ns_top(), true,
name, NULL, NULL,
NULL) != NULL)
ereport(ERROR,
(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
errmsg("parameter name \"%s\" used more than once",
name)));
/* OK, add the name */
uplpgsql_ns_additem(itemtype, itemno, name);
}
/*
* Add a dummy RETURN statement to the given function's body
*/
static void
add_dummy_return(UPLpgSQL_function *function)
{
/*
* If the outer block has an EXCEPTION clause, we need to make a new outer
* block, since the added RETURN shouldn't act like it is inside the
* EXCEPTION clause. Likewise, if it has a label, wrap it in a new outer
* block so that EXIT doesn't skip the RETURN.
*/
if (function->action->exceptions != NULL ||
function->action->label != NULL)
{
UPLpgSQL_stmt_block *new;
new = palloc0_object(UPLpgSQL_stmt_block);
new->cmd_type = UPLPGSQL_STMT_BLOCK;
new->stmtid = ++function->nstatements;
new->body = list_make1(function->action);
new->sqlstate_varno = -1;
function->action = new;
}
if (function->action->body == NIL ||
((UPLpgSQL_stmt *) llast(function->action->body))->cmd_type != UPLPGSQL_STMT_RETURN)
{
UPLpgSQL_stmt_return *new;
new = palloc0_object(UPLpgSQL_stmt_return);
new->cmd_type = UPLPGSQL_STMT_RETURN;
new->stmtid = ++function->nstatements;
new->expr = NULL;
new->retvarno = function->out_param_varno;
function->action->body = lappend(function->action->body, new);
}
}
/*
* uplpgsql_parser_setup set up parser hooks for dynamic parameters
*