forked from okbob/plpgsql_check
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplpgsql_check.c
More file actions
5329 lines (4455 loc) · 137 KB
/
plpgsql_check.c
File metadata and controls
5329 lines (4455 loc) · 137 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
/*-------------------------------------------------------------------------
*
* plpgsql_check.c
*
* enhanced checks for plpgsql functions
*
* by Pavel Stehule 2013-2016
*
*-------------------------------------------------------------------------
*
* Notes:
*
* 1) Secondary hash table for function signature is necessary due holding is_checked
* attribute - this protection against unwanted repeated check.
*
* 2) Reusing some plpgsql_xxx functions requires full run-time environment. It is
* emulated by fake expression context and fake fceinfo (these are created when
* active checking is used) - see: setup_fake_fcinfo, setup_cstate.
*
* 3) The environment is referenced by stored execution plans. The actual plan should
* not be linked with fake environment. All expressions created in checking time
* should be relased by release_exprs(cstate.exprs) function.
*
*/
#include "postgres.h"
#include "plpgsql.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "plpgsql_check_builtins.h"
#if PG_VERSION_NUM >= 100000
#define PLPGSQL_STMT_TYPES
#else
#define PLPGSQL_STMT_TYPES (enum PLpgSQL_stmt_types)
#endif
#if PG_VERSION_NUM >= 100000
#include "utils/regproc.h"
#endif
#if PG_VERSION_NUM >= 90300
#include "access/htup_details.h"
#else
/* Older version doesn't support event triggers */
#ifdef _MSC_VER
typedef struct {char nothing[0];} EventTriggerData;
#else
typedef struct {} EventTriggerData;
#endif
typedef enum PLpgSQL_trigtype
{
PLPGSQL_DML_TRIGGER,
PLPGSQL_EVENT_TRIGGER,
PLPGSQL_NOT_TRIGGER
} PLpgSQL_trigtype;
#endif
#include "access/tupconvert.h"
#include "access/tupdesc.h"
#ifndef TupleDescAttr
#define TupleDescAttr(tupdesc, i) ((tupdesc)->attrs[(i)])
#endif
#include "catalog/pg_language.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "executor/spi_priv.h"
#include "nodes/nodeFuncs.h"
#include "parser/parse_coerce.h"
#include "tcop/utility.h"
#include "tsearch/ts_locale.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
#include "utils/rel.h"
#include "utils/json.h"
#include "utils/reltrigger.h"
#include "utils/xml.h"
#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif
/*
* columns of plpgsql_check_function_table result
*
*/
#define Natts_result 11
#define Anum_result_functionid 0
#define Anum_result_lineno 1
#define Anum_result_statement 2
#define Anum_result_sqlstate 3
#define Anum_result_message 4
#define Anum_result_detail 5
#define Anum_result_hint 6
#define Anum_result_level 7
#define Anum_result_position 8
#define Anum_result_query 9
#define Anum_result_context 10
enum
{
PLPGSQL_CHECK_ERROR,
PLPGSQL_CHECK_WARNING_OTHERS,
PLPGSQL_CHECK_WARNING_EXTRA, /* check shadowed variables */
PLPGSQL_CHECK_WARNING_PERFORMANCE
};
enum
{
PLPGSQL_CHECK_FORMAT_ELOG,
PLPGSQL_CHECK_FORMAT_TEXT,
PLPGSQL_CHECK_FORMAT_TABULAR,
PLPGSQL_CHECK_FORMAT_XML,
PLPGSQL_CHECK_FORMAT_JSON
};
enum
{
PLPGSQL_CHECK_CLOSED,
PLPGSQL_CHECK_CLOSED_BY_EXCEPTIONS,
PLPGSQL_CHECK_POSSIBLY_CLOSED,
PLPGSQL_CHECK_UNCLOSED,
PLPGSQL_CHECK_UNKNOWN
};
enum
{
PLPGSQL_CHECK_MODE_DISABLED, /* all functionality is disabled */
PLPGSQL_CHECK_MODE_BY_FUNCTION, /* checking is allowed via CHECK function only (default) */
PLPGSQL_CHECK_MODE_FRESH_START, /* check only when function is called first time */
PLPGSQL_CHECK_MODE_EVERY_START /* check on every start */
};
typedef struct PLpgSQL_stmt_stack_item
{
PLpgSQL_stmt *stmt;
char *label;
struct PLpgSQL_stmt_stack_item *outer;
} PLpgSQL_stmt_stack_item;
typedef struct PLpgSQL_checkstate
{
Oid fn_oid; /* oid of checked function */
List *argnames; /* function arg names */
PLpgSQL_execstate *estate; /* check state is estate extension */
Tuplestorestate *tuple_store; /* result target */
TupleDesc tupdesc; /* result description */
bool fatal_errors; /* stop on first error */
bool performance_warnings; /* show performace warnings */
bool other_warnings; /* show other warnings */
bool extra_warnings; /* show extra warnings */
int format; /* output format */
StringInfo sinfo; /* aux. stringInfo used for result string concat */
MemoryContext check_cxt;
List *exprs; /* list of all expression created by checker */
bool is_active_mode; /* true, when checking is started by plpgsql_check_function */
Bitmapset *used_variables; /* track which variables have been used; bit per varno */
Bitmapset *modif_variables; /* track which variables had been changed; bit per varno */
PLpgSQL_stmt_stack_item *top_stmt_stack; /* list of known labels + related command */
bool found_return_query; /* true, when code contains RETURN query */
} PLpgSQL_checkstate;
static void assign_tupdesc_dno(PLpgSQL_checkstate *cstate, int varno, TupleDesc tupdesc, bool isnull);
static void assign_tupdesc_row_or_rec(PLpgSQL_checkstate *cstate,
PLpgSQL_row *row, PLpgSQL_rec *rec,
TupleDesc tupdesc, bool isnull);
static void check_assignment(PLpgSQL_checkstate *cstate, PLpgSQL_expr *expr,
PLpgSQL_rec *targetrec, PLpgSQL_row *targetrow,
int targetdno);
static void check_assignment_with_possible_slices(PLpgSQL_checkstate *cstate, PLpgSQL_expr *expr,
PLpgSQL_rec *targetrec, PLpgSQL_row *targetrow,
int targetdno, bool use_element_type);
static void check_expr(PLpgSQL_checkstate *cstate, PLpgSQL_expr *expr);
static void check_expr_with_expected_scalar_type(PLpgSQL_checkstate *cstate,
PLpgSQL_expr *expr,
Oid expected_typoid,
bool required);
static void check_expr_as_rvalue(PLpgSQL_checkstate *cstate, PLpgSQL_expr *expr,
PLpgSQL_rec *targetrec, PLpgSQL_row *targetrow,
int targetdno, bool use_element_type, bool is_expression);
static void check_returned_expr(PLpgSQL_checkstate *cstate, PLpgSQL_expr *expr, bool is_expression);
static void check_expr_as_sqlstmt_nodata(PLpgSQL_checkstate *cstate, PLpgSQL_expr *expr);
static void check_assign_to_target_type(PLpgSQL_checkstate *cstate,
Oid target_typoid, int32 target_typmod,
Oid value_typoid,
bool isnull);
static void check_function_epilog(PLpgSQL_checkstate *cstate);
static void check_function_prolog(PLpgSQL_checkstate *cstate);
static void check_on_func_beg(PLpgSQL_execstate * estate, PLpgSQL_function * func);
static void check_plpgsql_function(HeapTuple procTuple, Oid relid, PLpgSQL_trigtype trigtype,
TupleDesc tupdesc,
Tuplestorestate *tupstore,
int format,
bool fatal_errors,
bool other_warnings,
bool performance_warnings,
bool extra_warnings);
static void check_row_or_rec(PLpgSQL_checkstate *cstate, PLpgSQL_row *row, PLpgSQL_rec *rec);
static void check_stmt(PLpgSQL_checkstate *cstate, PLpgSQL_stmt *stmt, int *closing, List **exceptions);
static void check_stmts(PLpgSQL_checkstate *cstate, List *stmts, int *closing, List **exceptions);
static void check_target(PLpgSQL_checkstate *cstate, int varno, Oid *expected_typoid, int *expected_typmod);
static PLpgSQL_datum *copy_plpgsql_datum(PLpgSQL_datum *datum);
static char *datum_get_refname(PLpgSQL_datum *d);
static TupleDesc expr_get_desc(PLpgSQL_checkstate *cstate,
PLpgSQL_expr *query,
bool use_element_type,
bool expand_record,
bool is_expression,
Oid *first_level_typoid);
static void format_error_xml(StringInfo str,
PLpgSQL_execstate *estate,
int sqlerrcode, int lineno,
const char *message, const char *detail, const char *hint,
int level, int position,
const char *query,
const char *context);
static void format_error_json(StringInfo str,
PLpgSQL_execstate *estate,
int sqlerrcode, int lineno,
const char *message, const char *detail, const char *hint,
int level, int position,
const char *query,
const char *context);
static void function_check(PLpgSQL_function *func, FunctionCallInfo fcinfo,
PLpgSQL_execstate *estate, PLpgSQL_checkstate *cstate);
static PLpgSQL_trigtype get_trigtype(HeapTuple procTuple);
static void init_datum_dno(PLpgSQL_checkstate *cstate, int varno);
static bool is_checked(PLpgSQL_function *func);
static int load_configuration(HeapTuple procTuple, bool *reload_config);
static void mark_as_checked(PLpgSQL_function *func);
static void plpgsql_check_HashTableInit(void);
static void prohibit_write_plan(PLpgSQL_checkstate *cstate, PLpgSQL_expr *query);
static void put_error(PLpgSQL_checkstate *cstate,
int sqlerrcode, int lineno,
const char *message, const char *detail, const char *hint,
int level, int position,
const char *query, const char *context);
static void put_error_edata(PLpgSQL_checkstate *cstate, ErrorData *edata);
static void precheck_conditions(HeapTuple procTuple, PLpgSQL_trigtype trigtype, Oid relid);
static void prepare_expr(PLpgSQL_checkstate *cstate, PLpgSQL_expr *expr, int cursorOptions);
static void release_exprs(List *exprs);
static void setup_cstate(PLpgSQL_checkstate *cstate,
Oid fn_oid, TupleDesc tupdesc, Tuplestorestate *tupstore,
bool fatal_errors,
bool other_warnings, bool perform_warnings, bool extra_warnings,
int format,
bool is_active_mode);
static void setup_fake_fcinfo(HeapTuple procTuple,
FmgrInfo *flinfo,
FunctionCallInfoData *fcinfo,
ReturnSetInfo *rsinfo,
TriggerData *trigdata,
Oid relid,
EventTriggerData *etrigdata,
Oid funcoid,
PLpgSQL_trigtype trigtype,
Trigger *tg_trigger);
static void setup_plpgsql_estate(PLpgSQL_execstate *estate,
PLpgSQL_function *func, ReturnSetInfo *rsi);
static void trigger_check(PLpgSQL_function *func,
Node *trigdata,
PLpgSQL_execstate *estate, PLpgSQL_checkstate *cstate);
static void tuplestore_put_error_text(Tuplestorestate *tuple_store, TupleDesc tupdesc,
PLpgSQL_execstate *estate, Oid fn_oid,
int sqlerrcode, int lineno,
const char *message, const char *detail, const char *hint,
int level, int position,
const char *query, const char *context);
static void tuplestore_put_error_tabular(Tuplestorestate *tuple_store, TupleDesc tupdesc,
PLpgSQL_execstate *estate, Oid fn_oid,
int sqlerrcode, int lineno,
const char *message, const char *detail, const char *hint,
int level, int position,
const char *query, const char *context);
static void tuplestore_put_text_line(Tuplestorestate *tuple_store, TupleDesc tupdesc,
const char *message, int len);
static void report_unused_variables(PLpgSQL_checkstate *cstate);
static void record_variable_usage(PLpgSQL_checkstate *cstate, int dno, bool write);
static bool datum_is_used(PLpgSQL_checkstate *cstate, int dno, bool write);
static bool is_const_null_expr(PLpgSQL_expr *query);
static void prohibit_transaction_stmt(PLpgSQL_checkstate *cstate, PLpgSQL_expr *query);
static int merge_closing(int c, int c_local, List **exceptions, List *exceptions_local, int err_code);
static int possibly_closed(int c);
static char *ExprGetString(PLpgSQL_expr *query, bool *IsConst);
static bool exception_matches_conditions(int err_code, PLpgSQL_condition *cond);
static bool plpgsql_check_other_warnings = false;
static bool plpgsql_check_extra_warnings = false;
static bool plpgsql_check_performance_warnings = false;
static bool plpgsql_check_fatal_errors = true;
static int plpgsql_check_mode = PLPGSQL_CHECK_MODE_BY_FUNCTION;
static PLpgSQL_plugin plugin_funcs = { NULL, check_on_func_beg, NULL, NULL, NULL};
static const struct config_enum_entry plpgsql_check_mode_options[] = {
{"disabled", PLPGSQL_CHECK_MODE_DISABLED, false},
{"by_function", PLPGSQL_CHECK_MODE_BY_FUNCTION, false},
{"fresh_start", PLPGSQL_CHECK_MODE_FRESH_START, false},
{"every_start", PLPGSQL_CHECK_MODE_EVERY_START, false},
{NULL, 0, false}
};
/* ----------
* Hash table for checked functions
* ----------
*/
static HTAB *plpgsql_check_HashTable = NULL;
typedef struct plpgsql_hashent
{
PLpgSQL_func_hashkey key;
TransactionId fn_xmin;
ItemPointerData fn_tid;
bool is_checked;
} plpgsql_check_HashEnt;
#define FUNCS_PER_USER 128 /* initial table size */
PG_FUNCTION_INFO_V1(plpgsql_check_function);
PG_FUNCTION_INFO_V1(plpgsql_check_function_tb);
/*
* Module initialization
*
* join to PLpgSQL executor
*
*/
void
_PG_init(void)
{
PLpgSQL_plugin ** var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable( "PLpgSQL_plugin" );
/* Be sure we do initialization only once (should be redundant now) */
static bool inited = false;
if (inited)
return;
*var_ptr = &plugin_funcs;
DefineCustomEnumVariable("plpgsql_check.mode",
"choose a mode for enhanced checking",
NULL,
&plpgsql_check_mode,
PLPGSQL_CHECK_MODE_BY_FUNCTION,
plpgsql_check_mode_options,
PGC_SUSET, 0,
NULL, NULL, NULL);
DefineCustomBoolVariable("plpgsql_check.show_nonperformance_extra_warnings",
"when is true, then extra warning (except performance warnings) are showed",
NULL,
&plpgsql_check_extra_warnings,
false,
PGC_SUSET, 0,
NULL, NULL, NULL);
DefineCustomBoolVariable("plpgsql_check.show_nonperformance_warnings",
"when is true, then warning (except performance warnings) are showed",
NULL,
&plpgsql_check_other_warnings,
false,
PGC_SUSET, 0,
NULL, NULL, NULL);
DefineCustomBoolVariable("plpgsql_check.show_performance_warnings",
"when is true, then performance warnings are showed",
NULL,
&plpgsql_check_performance_warnings,
false,
PGC_SUSET, 0,
NULL, NULL, NULL);
DefineCustomBoolVariable("plpgsql_check.fatal_errors",
"when is true, then plpgsql check stops execution on detected error",
NULL,
&plpgsql_check_fatal_errors,
true,
PGC_SUSET, 0,
NULL, NULL, NULL);
plpgsql_check_HashTableInit();
inited = true;
}
/*
* plpgsql_check_func_beg
*
* callback function - called by plgsql executor, when function is started
* and local variables are initialized.
*
*/
static void
check_on_func_beg(PLpgSQL_execstate * estate, PLpgSQL_function * func)
{
const char *err_text = estate->err_text;
int closing;
List *exceptions;
if (plpgsql_check_mode == PLPGSQL_CHECK_MODE_FRESH_START ||
plpgsql_check_mode == PLPGSQL_CHECK_MODE_EVERY_START)
{
int i;
PLpgSQL_rec *saved_records;
PLpgSQL_var *saved_vars;
MemoryContext oldcontext,
old_cxt;
ResourceOwner oldowner;
PLpgSQL_checkstate cstate;
/*
* don't allow repeated execution on checked function
* when it is not requsted.
*/
if (plpgsql_check_mode == PLPGSQL_CHECK_MODE_FRESH_START &&
is_checked(func))
{
elog(NOTICE, "function \"%s\" was checked already",
func->fn_signature);
return;
}
mark_as_checked(func);
setup_cstate(&cstate, func->fn_oid, NULL, NULL,
plpgsql_check_fatal_errors,
plpgsql_check_other_warnings,
plpgsql_check_performance_warnings,
plpgsql_check_extra_warnings,
PLPGSQL_CHECK_FORMAT_ELOG,
false);
/* use real estate */
cstate.estate = estate;
old_cxt = MemoryContextSwitchTo(cstate.check_cxt);
/*
* During the check stage a rec and vars variables are modified, so we should
* to save their content
*/
saved_records = palloc(sizeof(PLpgSQL_rec) * estate->ndatums);
saved_vars = palloc(sizeof(PLpgSQL_var) * estate->ndatums);
for (i = 0; i < estate->ndatums; i++)
{
if (estate->datums[i]->dtype == PLPGSQL_DTYPE_REC)
{
PLpgSQL_rec *rec = (PLpgSQL_rec *) estate->datums[i];
saved_records[i].tup = rec->tup;
saved_records[i].tupdesc = rec->tupdesc;
saved_records[i].freetup = rec->freetup;
saved_records[i].freetupdesc = rec->freetupdesc;
/* don't release a original tupdesc and original tup */
rec->freetup = false;
rec->freetupdesc = false;
}
else if (estate->datums[i]->dtype == PLPGSQL_DTYPE_VAR)
{
PLpgSQL_var *var = (PLpgSQL_var *) estate->datums[i];
saved_vars[i].value = var->value;
saved_vars[i].isnull = var->isnull;
saved_vars[i].freeval = var->freeval;
var->freeval = false;
}
}
estate->err_text = NULL;
/*
* Raised exception should be trapped in outer functtion. Protection
* against outer trap is QUERY_CANCELED exception.
*/
oldcontext = CurrentMemoryContext;
oldowner = CurrentResourceOwner;
PG_TRY();
{
/*
* Now check the toplevel block of statements
*/
check_stmt(&cstate, (PLpgSQL_stmt *) func->action, &closing, &exceptions);
estate->err_stmt = NULL;
if (closing != PLPGSQL_CHECK_CLOSED && closing != PLPGSQL_CHECK_CLOSED_BY_EXCEPTIONS)
put_error(&cstate,
ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT, 0,
"control reached end of function without RETURN",
NULL,
NULL,
closing == PLPGSQL_CHECK_UNCLOSED ?
PLPGSQL_CHECK_ERROR : PLPGSQL_CHECK_WARNING_EXTRA,
0, NULL, NULL);
report_unused_variables(&cstate);
}
PG_CATCH();
{
ErrorData *edata;
/* Save error info */
MemoryContextSwitchTo(oldcontext);
edata = CopyErrorData();
FlushErrorState();
CurrentResourceOwner = oldowner;
release_exprs(cstate.exprs);
edata->sqlerrcode = ERRCODE_QUERY_CANCELED;
ReThrowError(edata);
}
PG_END_TRY();
estate->err_text = err_text;
estate->err_stmt = NULL;
/* return back a original rec variables */
for (i = 0; i < estate->ndatums; i++)
{
if (estate->datums[i]->dtype == PLPGSQL_DTYPE_REC)
{
PLpgSQL_rec *rec = (PLpgSQL_rec *) estate->datums[i];
if (rec->freetupdesc)
FreeTupleDesc(rec->tupdesc);
rec->tup = saved_records[i].tup;
rec->tupdesc = saved_records[i].tupdesc;
rec->freetup = saved_records[i].freetup;
rec->freetupdesc = saved_records[i].freetupdesc;
}
else if (estate->datums[i]->dtype == PLPGSQL_DTYPE_VAR)
{
PLpgSQL_var *var = (PLpgSQL_var *) estate->datums[i];
var->value = saved_vars[i].value;
var->isnull = saved_vars[i].isnull;
var->freeval = saved_vars[i].freeval;
}
}
MemoryContextSwitchTo(old_cxt);
MemoryContextDelete(cstate.check_cxt);
}
}
/*
* plpgsql_check_function
*
* Extended check with formatted text output
*
*/
Datum
plpgsql_check_function(PG_FUNCTION_ARGS)
{
Oid funcoid = PG_GETARG_OID(0);
Oid relid = PG_GETARG_OID(1);
char *format_str = text_to_cstring(PG_GETARG_TEXT_PP(2));
bool fatal_errors = PG_GETARG_BOOL(3);
bool other_warnings = PG_GETARG_BOOL(4);
bool performance_warnings = PG_GETARG_BOOL(5);
bool extra_warnings;
TupleDesc tupdesc;
HeapTuple procTuple;
Tuplestorestate *tupstore;
MemoryContext per_query_ctx;
MemoryContext oldcontext;
ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
PLpgSQL_trigtype trigtype;
char *format_lower_str;
int format = PLPGSQL_CHECK_FORMAT_TEXT;
ErrorContextCallback *prev_errorcontext;
if (PG_NARGS() != 7)
elog(ERROR, "unexpected number of parameters, you should to update extension");
extra_warnings = PG_GETARG_BOOL(6);
format_lower_str = lowerstr(format_str);
if (strcmp(format_lower_str, "text") == 0)
format = PLPGSQL_CHECK_FORMAT_TEXT;
else if (strcmp(format_lower_str, "xml") == 0)
format = PLPGSQL_CHECK_FORMAT_XML;
else if (strcmp(format_lower_str, "json") == 0)
format = PLPGSQL_CHECK_FORMAT_JSON;
else
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("unrecognize format: \"%s\"",
format_lower_str),
errhint("Only \"text\", \"xml\" and \"json\" formats are supported.")));
/* check to see if caller supports us returning a tuplestore */
if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("set-valued function called in context that cannot accept a set")));
if (!(rsinfo->allowedModes & SFRM_Materialize))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("materialize mode required, but it is not allowed in this context")));
procTuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
if (!HeapTupleIsValid(procTuple))
elog(ERROR, "cache lookup failed for function %u", funcoid);
trigtype = get_trigtype(procTuple);
precheck_conditions(procTuple, trigtype, relid);
/* need to build tuplestore in query context */
per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
oldcontext = MemoryContextSwitchTo(per_query_ctx);
tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
tupstore = tuplestore_begin_heap(false, false, work_mem);
MemoryContextSwitchTo(oldcontext);
prev_errorcontext = error_context_stack;
error_context_stack = NULL;
check_plpgsql_function(procTuple, relid, trigtype,
tupdesc, tupstore,
format,
fatal_errors,
other_warnings, performance_warnings, extra_warnings);
error_context_stack = prev_errorcontext;
ReleaseSysCache(procTuple);
/* clean up and return the tuplestore */
tuplestore_donestoring(tupstore);
rsinfo->returnMode = SFRM_Materialize;
rsinfo->setResult = tupstore;
rsinfo->setDesc = tupdesc;
return (Datum) 0;
}
/*
* plpgsql_check_function_tb
*
* It ensure a detailed validation and returns result as multicolumn table
*
*/
Datum
plpgsql_check_function_tb(PG_FUNCTION_ARGS)
{
Oid funcoid = PG_GETARG_OID(0);
Oid relid = PG_GETARG_OID(1);
bool fatal_errors = PG_GETARG_BOOL(2);
bool other_warnings = PG_GETARG_BOOL(3);
bool performance_warnings = PG_GETARG_BOOL(4);
bool extra_warnings;
TupleDesc tupdesc;
HeapTuple procTuple;
Tuplestorestate *tupstore;
MemoryContext per_query_ctx;
MemoryContext oldcontext;
ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
PLpgSQL_trigtype trigtype;
ErrorContextCallback *prev_errorcontext;
if (PG_NARGS() != 6)
elog(ERROR, "unexpected number of parameters, you should to update extension");
extra_warnings = PG_GETARG_BOOL(5);
/* check to see if caller supports us returning a tuplestore */
if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("set-valued function called in context that cannot accept a set")));
if (!(rsinfo->allowedModes & SFRM_Materialize))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("materialize mode required, but it is not allowed in this context")));
procTuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
if (!HeapTupleIsValid(procTuple))
elog(ERROR, "cache lookup failed for function %u", funcoid);
trigtype = get_trigtype(procTuple);
precheck_conditions(procTuple, trigtype, relid);
/* need to build tuplestore in query context */
per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
oldcontext = MemoryContextSwitchTo(per_query_ctx);
tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
tupstore = tuplestore_begin_heap(false, false, work_mem);
MemoryContextSwitchTo(oldcontext);
prev_errorcontext = error_context_stack;
/* Envelope outer plpgsql function is not interesting */
error_context_stack = NULL;
check_plpgsql_function(procTuple, relid, trigtype,
tupdesc, tupstore,
PLPGSQL_CHECK_FORMAT_TABULAR,
fatal_errors,
other_warnings, performance_warnings, extra_warnings);
error_context_stack = prev_errorcontext;
ReleaseSysCache(procTuple);
/* clean up and return the tuplestore */
tuplestore_donestoring(tupstore);
rsinfo->returnMode = SFRM_Materialize;
rsinfo->setResult = tupstore;
rsinfo->setDesc = tupdesc;
return (Datum) 0;
}
/*
* Add label to stack of labels
*/
static PLpgSQL_stmt_stack_item *
push_stmt_to_stmt_stack(PLpgSQL_checkstate *cstate)
{
PLpgSQL_stmt *stmt = cstate->estate->err_stmt;
PLpgSQL_stmt_stack_item *stmt_stack_item;
PLpgSQL_stmt_stack_item *current = cstate->top_stmt_stack;
stmt_stack_item = (PLpgSQL_stmt_stack_item *) palloc(sizeof(PLpgSQL_stmt_stack_item));
stmt_stack_item->stmt = stmt;
switch (PLPGSQL_STMT_TYPES stmt->cmd_type)
{
case PLPGSQL_STMT_BLOCK:
stmt_stack_item->label = ((PLpgSQL_stmt_block *) stmt)->label;
break;
case PLPGSQL_STMT_EXIT:
stmt_stack_item->label = ((PLpgSQL_stmt_exit *) stmt)->label;
break;
case PLPGSQL_STMT_LOOP:
stmt_stack_item->label = ((PLpgSQL_stmt_loop *) stmt)->label;
break;
case PLPGSQL_STMT_WHILE:
stmt_stack_item->label = ((PLpgSQL_stmt_while *) stmt)->label;
break;
case PLPGSQL_STMT_FORI:
stmt_stack_item->label = ((PLpgSQL_stmt_fori *) stmt)->label;
break;
case PLPGSQL_STMT_FORS:
stmt_stack_item->label = ((PLpgSQL_stmt_fors *) stmt)->label;
break;
case PLPGSQL_STMT_FORC:
stmt_stack_item->label = ((PLpgSQL_stmt_forc *) stmt)->label;
break;
case PLPGSQL_STMT_DYNFORS:
stmt_stack_item->label = ((PLpgSQL_stmt_dynfors *) stmt)->label;
break;
case PLPGSQL_STMT_FOREACH_A:
stmt_stack_item->label = ((PLpgSQL_stmt_foreach_a *) stmt)->label;
break;
default:
stmt_stack_item->label = NULL;
}
stmt_stack_item->outer = current;
cstate->top_stmt_stack = stmt_stack_item;
return current;
}
static void
pop_stmt_from_stmt_stack(PLpgSQL_checkstate *cstate)
{
PLpgSQL_stmt_stack_item *current = cstate->top_stmt_stack;
Assert(cstate->top_stmt_stack != NULL);
cstate->top_stmt_stack = current->outer;
pfree(current);
}
/*
* Returns true, when stmt is any loop statement
*/
static bool
is_any_loop_stmt(PLpgSQL_stmt *stmt)
{
switch (PLPGSQL_STMT_TYPES stmt->cmd_type)
{
case PLPGSQL_STMT_LOOP:
case PLPGSQL_STMT_WHILE:
case PLPGSQL_STMT_FORI:
case PLPGSQL_STMT_FORS:
case PLPGSQL_STMT_FORC:
case PLPGSQL_STMT_DYNFORS:
case PLPGSQL_STMT_FOREACH_A:
return true;
default:
return false;
}
}
/*
* Searching a any statement related to CONTINUE/EXIT statement.
* label cannot be NULL.
*/
static PLpgSQL_stmt *
find_stmt_with_label(char *label, PLpgSQL_stmt_stack_item *current)
{
while (current != NULL)
{
if (current->label != NULL
&& strcmp(current->label, label) == 0)
return current->stmt;
current = current->outer;
}
return NULL;
}
static PLpgSQL_stmt *
find_nearest_loop(PLpgSQL_stmt_stack_item *current)
{
while (current != NULL)
{
if (is_any_loop_stmt(current->stmt))
return current->stmt;
current = current->outer;
}
return NULL;
}
/*
* returns false, when a variable doesn't shadows any other variable
*/
static bool
found_shadowed_variable(char *varname, PLpgSQL_stmt_stack_item *current, PLpgSQL_checkstate *cstate)
{
while (current != NULL)
{
if (current->stmt->cmd_type == PLPGSQL_STMT_BLOCK)
{
PLpgSQL_stmt_block *stmt_block = (PLpgSQL_stmt_block *) current->stmt;
int i;
PLpgSQL_datum *d;
for (i = 0; i < stmt_block->n_initvars; i++)
{
char *refname;
d = cstate->estate->func->datums[stmt_block->initvarnos[i]];
refname = datum_get_refname(d);
if (refname != NULL && strcmp(refname, varname) == 0)
return true;
}
}
current = current->outer;
}
return false;
}
/*
* Returns PLpgSQL_trigtype based on prorettype
*/
static PLpgSQL_trigtype
get_trigtype(HeapTuple procTuple)
{
Form_pg_proc proc;
char functyptype;
proc = (Form_pg_proc) GETSTRUCT(procTuple);
functyptype = get_typtype(proc->prorettype);
/*
* Disallow pseudotype result except for TRIGGER, RECORD, VOID, or
* polymorphic
*/
if (functyptype == TYPTYPE_PSEUDO)
{
/* we assume OPAQUE with no arguments means a trigger */
if (proc->prorettype == TRIGGEROID ||
(proc->prorettype == OPAQUEOID && proc->pronargs == 0))
return PLPGSQL_DML_TRIGGER;
#if PG_VERSION_NUM >= 90300
else if (proc->prorettype == EVTTRIGGEROID)
return PLPGSQL_EVENT_TRIGGER;
#endif
else if (proc->prorettype != RECORDOID &&
proc->prorettype != VOIDOID &&
!IsPolymorphicType(proc->prorettype))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("PL/pgSQL functions cannot return type %s",
format_type_be(proc->prorettype))));
}
return PLPGSQL_NOT_TRIGGER;
}
/*
* Process necessary checking before code checking
* a) disallow other than plpgsql check function,
* b) when function is trigger function, then reloid must be defined
*/
static void
precheck_conditions(HeapTuple procTuple, PLpgSQL_trigtype trigtype, Oid relid)
{
Form_pg_proc proc;
Form_pg_language languageStruct;
HeapTuple languageTuple;
char *funcname;
proc = (Form_pg_proc) GETSTRUCT(procTuple);
funcname = format_procedure(HeapTupleGetOid(procTuple));
/* used language must be plpgsql */
languageTuple = SearchSysCache1(LANGOID, ObjectIdGetDatum(proc->prolang));
Assert(HeapTupleIsValid(languageTuple));
languageStruct = (Form_pg_language) GETSTRUCT(languageTuple);
if (strcmp(NameStr(languageStruct->lanname), "plpgsql") != 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("%s is not a plpgsql function", funcname)));
ReleaseSysCache(languageTuple);
/* dml trigger needs valid relid, others not */
if (trigtype == PLPGSQL_DML_TRIGGER)
{
if (!OidIsValid(relid))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("missing trigger relation"),
errhint("Trigger relation oid must be valid")));
}
else
{
if (OidIsValid(relid))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("function is not trigger"),
errhint("Trigger relation oid must not be valid for non dml trigger function.")));
}
pfree(funcname);
}
/*
* own implementation