forked from taehoonkoo/plr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plr.c
1896 lines (1641 loc) · 48.9 KB
/
plr.c
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/R - PostgreSQL support for R as a
* procedural language (PL)
*
* Copyright (c) 2003-2015 by Joseph E. Conway
* ALL RIGHTS RESERVED
*
* Joe Conway <[email protected]>
*
* Based on pltcl by Jan Wieck
* and inspired by REmbeddedPostgres by
* Duncan Temple Lang <[email protected]>
* http://www.omegahat.org/RSPostgres/
*
* License: GPL version 2 or newer. http://www.gnu.org/copyleft/gpl.html
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* plr.c - Language handler and support functions
*/
#include "plr.h"
PG_MODULE_MAGIC;
/*
* Global data
*/
MemoryContext plr_caller_context;
MemoryContext plr_SPI_context = NULL;
HTAB *plr_HashTable = (HTAB *) NULL;
char *last_R_error_msg = NULL;
static bool plr_pm_init_done = false;
static bool plr_be_init_done = false;
/* namespace OID for the PL/R language handler function */
static Oid plr_nspOid = InvalidOid;
int R_SignalHandlers = 1; /* Exposed in R_interface.h */
/*
* defines
*/
/* real max is 3 (for "PLR") plus number of characters in an Oid */
#define MAX_PRONAME_LEN NAMEDATALEN
#define OPTIONS_NULL_CMD "options(error = expression(NULL))"
#define THROWRERROR_CMD \
"pg.throwrerror <-function(msg) " \
"{" \
" msglen <- nchar(msg);" \
" if (substr(msg, msglen, msglen + 1) == \"\\n\")" \
" msg <- substr(msg, 1, msglen - 1);" \
" .C(\"throw_r_error\", as.character(msg));" \
"}"
#define OPTIONS_THROWRERROR_CMD \
"options(error = expression(pg.throwrerror(geterrmessage())))"
#define THROWNOTICE_CMD \
"pg.thrownotice <-function(msg) " \
"{.C(\"throw_pg_notice\", as.character(msg))}"
#define THROWERROR_CMD \
"pg.throwerror <-function(msg) " \
"{stop(msg, call. = FALSE)}"
#define OPTIONS_THROWWARN_CMD \
"options(warning.expression = expression(pg.thrownotice(last.warning)))"
#define QUOTE_LITERAL_CMD \
"pg.quoteliteral <-function(sql) " \
"{.Call(\"plr_quote_literal\", sql)}"
#define QUOTE_IDENT_CMD \
"pg.quoteident <-function(sql) " \
"{.Call(\"plr_quote_ident\", sql)}"
#define SPI_EXEC_CMD \
"pg.spi.exec <-function(sql) {.Call(\"plr_SPI_exec\", sql)}"
#define SPI_PREPARE_CMD \
"pg.spi.prepare <-function(sql, argtypes = NA) " \
"{.Call(\"plr_SPI_prepare\", sql, argtypes)}"
#define SPI_EXECP_CMD \
"pg.spi.execp <-function(sql, argvalues = NA) " \
"{.Call(\"plr_SPI_execp\", sql, argvalues)}"
#define SPI_CURSOR_OPEN_CMD \
"pg.spi.cursor_open<-function(cursor_name,plan,argvalues=NA) " \
"{.Call(\"plr_SPI_cursor_open\",cursor_name,plan,argvalues)}"
#define SPI_CURSOR_FETCH_CMD \
"pg.spi.cursor_fetch<-function(cursor,forward,rows) " \
"{.Call(\"plr_SPI_cursor_fetch\",cursor,forward,rows)}"
#define SPI_CURSOR_MOVE_CMD \
"pg.spi.cursor_move<-function(cursor,forward,rows) " \
"{.Call(\"plr_SPI_cursor_move\",cursor,forward,rows)}"
#define SPI_CURSOR_CLOSE_CMD \
"pg.spi.cursor_close<-function(cursor) " \
"{.Call(\"plr_SPI_cursor_close\",cursor)}"
#define SPI_LASTOID_CMD \
"pg.spi.lastoid <-function() " \
"{.Call(\"plr_SPI_lastoid\")}"
#define SPI_DBDRIVER_CMD \
"dbDriver <-function(db_name)\n" \
"{return(NA)}"
#define SPI_DBCONN_CMD \
"dbConnect <- function(drv,user=\"\",password=\"\",host=\"\",dbname=\"\",port=\"\",tty =\"\",options=\"\")\n" \
"{return(NA)}"
#define SPI_DBSENDQUERY_CMD \
"dbSendQuery <- function(conn, sql) {\n" \
"plan <- pg.spi.prepare(sql)\n" \
"cursor_obj <- pg.spi.cursor_open(\"plr_cursor\",plan)\n" \
"return(cursor_obj)\n" \
"}"
#define SPI_DBFETCH_CMD \
"fetch <- function(rs,n) {\n" \
"data <- pg.spi.cursor_fetch(rs, TRUE, as.integer(n))\n" \
"return(data)\n" \
"}"
#define SPI_DBCLEARRESULT_CMD \
"dbClearResult <- function(rs) {\n" \
"pg.spi.cursor_close(rs)\n" \
"}"
#define SPI_DBGETQUERY_CMD \
"dbGetQuery <-function(conn, sql) {\n" \
"data <- pg.spi.exec(sql)\n" \
"return(data)\n" \
"}"
#define SPI_DBREADTABLE_CMD \
"dbReadTable <- function(con, name, row.names = \"row_names\", check.names = TRUE) {\n" \
"data <- dbGetQuery(con, paste(\"SELECT * from\", name))\n" \
"return(data)\n" \
"}"
#define SPI_DBDISCONN_CMD \
"dbDisconnect <- function(con)\n" \
"{return(NA)}"
#define SPI_DBUNLOADDRIVER_CMD \
"dbUnloadDriver <-function(drv)\n" \
"{return(NA)}"
#define SPI_FACTOR_CMD \
"pg.spi.factor <- function(arg1) {\n" \
" for (col in 1:ncol(arg1)) {\n" \
" if (!is.numeric(arg1[,col])) {\n" \
" arg1[,col] <- factor(arg1[,col])\n" \
" }\n" \
" }\n" \
" return(arg1)\n" \
"}"
#define REVAL \
"pg.reval <- function(arg1) {eval(parse(text = arg1))}"
#define PG_STATE_FIRSTPASS \
"pg.state.firstpass <- TRUE"
#define CurrentTriggerData ((TriggerData *) fcinfo->context)
/*
* static declarations
*/
static void plr_atexit(void);
static void plr_load_builtins(Oid funcid);
static void plr_init_all(Oid funcid);
static Datum plr_trigger_handler(PG_FUNCTION_ARGS);
static Datum plr_func_handler(PG_FUNCTION_ARGS);
static plr_function *compile_plr_function(FunctionCallInfo fcinfo);
static plr_function *do_compile(FunctionCallInfo fcinfo,
HeapTuple procTup,
plr_func_hashkey *hashkey);
static SEXP plr_parse_func_body(const char *body);
static SEXP plr_convertargs(plr_function *function, Datum *arg, bool *argnull, FunctionCallInfo fcinfo);
static void plr_error_callback(void *arg);
static Oid getNamespaceOidFromFunctionOid(Oid fnOid);
static bool haveModulesTable(Oid nspOid);
static char *getModulesSql(Oid nspOid);
#ifdef HAVE_WINDOW_FUNCTIONS
static void WinGetFrameData(WindowObject winobj, int argno, Datum *dvalues, bool *isnull, int *numels, bool *has_nulls);
#endif
static void plr_resolve_polymorphic_argtypes(int numargs,
Oid *argtypes, char *argmodes,
Node *call_expr, bool forValidator,
const char *proname);
/*
* plr_call_handler - This is the only visible function
* of the PL interpreter. The PostgreSQL
* function manager and trigger manager
* call this function for execution of
* PL/R procedures.
*/
PG_FUNCTION_INFO_V1(plr_call_handler);
Datum
plr_call_handler(PG_FUNCTION_ARGS)
{
Datum retval;
/* save caller's context */
plr_caller_context = CurrentMemoryContext;
if (SPI_connect() != SPI_OK_CONNECT)
elog(ERROR, "SPI_connect failed");
plr_SPI_context = CurrentMemoryContext;
MemoryContextSwitchTo(plr_caller_context);
/* initialize R if needed */
plr_init_all(fcinfo->flinfo->fn_oid);
if (CALLED_AS_TRIGGER(fcinfo))
retval = plr_trigger_handler(fcinfo);
else
retval = plr_func_handler(fcinfo);
return retval;
}
void
load_r_cmd(const char *cmd)
{
SEXP cmdSexp,
cmdexpr;
int i,
status;
/*
* Init if not already done. This can happen when PL/R is not preloaded
* and reload_plr_modules() or install_rcmd() is called by the user prior
* to any PL/R functions.
*/
if (!plr_pm_init_done)
plr_init();
PROTECT(cmdSexp = NEW_CHARACTER(1));
SET_STRING_ELT(cmdSexp, 0, COPY_TO_USER_STRING(cmd));
PROTECT(cmdexpr = R_PARSEVECTOR(cmdSexp, -1, &status));
if (status != PARSE_OK) {
UNPROTECT(2);
if (last_R_error_msg)
ereport(ERROR,
(errcode(ERRCODE_DATA_EXCEPTION),
errmsg("R interpreter parse error"),
errdetail("%s", last_R_error_msg)));
else
ereport(ERROR,
(errcode(ERRCODE_DATA_EXCEPTION),
errmsg("R interpreter parse error"),
errdetail("R parse error caught in \"%s\".", cmd)));
}
/* Loop is needed here as EXPSEXP may be of length > 1 */
for(i = 0; i < length(cmdexpr); i++)
{
R_tryEval(VECTOR_ELT(cmdexpr, i), R_GlobalEnv, &status);
if(status != 0)
{
if (last_R_error_msg)
ereport(ERROR,
(errcode(ERRCODE_DATA_EXCEPTION),
errmsg("R interpreter expression evaluation error"),
errdetail("%s", last_R_error_msg)));
else
ereport(ERROR,
(errcode(ERRCODE_DATA_EXCEPTION),
errmsg("R interpreter expression evaluation error"),
errdetail("R expression evaluation error caught " \
"in \"%s\".", cmd)));
}
}
UNPROTECT(2);
}
/*
* plr_cleanup() - Let the embedded interpreter clean up after itself
*
* DO NOT make this static --- it has to be registered as an on_proc_exit()
* callback
*/
void
PLR_CLEANUP
{
char *buf;
char *tmpdir = getenv("R_SESSION_TMPDIR");
R_dot_Last();
R_RunExitFinalizers();
KillAllDevices();
if(tmpdir)
{
int rv;
/*
* length needed = 'rm -rf ""' == 9
* plus 1 for NULL terminator
* plus length of dir string
*/
buf = (char *) palloc(9 + 1 + strlen(tmpdir));
sprintf(buf, "rm -rf \"%s\"", tmpdir);
/* ignoring return value */
rv = system(buf);
if (rv != 0)
; /* do nothing */
}
}
static void
plr_atexit(void)
{
/* only react during plr startup */
if (plr_pm_init_done)
return;
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("the R interpreter did not initialize"),
errhint("R_HOME must be correct in the environment " \
"of the user that starts the postmaster process.")));
}
/*
* plr_init() - Initialize all that's safe to do in the postmaster
*
* DO NOT make this static --- it has to be callable by preload
*/
void
plr_init(void)
{
char *r_home;
int rargc;
char *rargv[] = {"PL/R", "--slave", "--silent", "--no-save", "--no-restore"};
/* refuse to init more than once */
if (plr_pm_init_done)
return;
/* refuse to start if R_HOME is not defined */
r_home = getenv("R_HOME");
if (r_home == NULL)
{
size_t rh_len = strlen(R_HOME_DEFAULT);
/* see if there is a compiled in default R_HOME */
if (rh_len)
{
char *rhenv;
MemoryContext oldcontext;
/* Needs to live until/unless we explicitly delete it */
oldcontext = MemoryContextSwitchTo(TopMemoryContext);
rhenv = palloc(8 + rh_len);
MemoryContextSwitchTo(oldcontext);
sprintf(rhenv, "R_HOME=%s", R_HOME_DEFAULT);
putenv(rhenv);
}
else
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("environment variable R_HOME not defined"),
errhint("R_HOME must be defined in the environment " \
"of the user that starts the postmaster process.")));
}
rargc = sizeof(rargv)/sizeof(rargv[0]);
/*
* register an exit callback to handle the case where R does not initialize
* and just exits with R_suicide()
*/
atexit(plr_atexit);
/*
* Stop R using its own signal handlers
*/
R_SignalHandlers = 0;
/*
* When initialization fails, R currently exits. Check the return
* value anyway in case this ever gets fixed
*/
if (!Rf_initEmbeddedR(rargc, rargv))
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("the R interpreter did not initialize"),
errhint("R_HOME must be correct in the environment " \
"of the user that starts the postmaster process.")));
/* arrange for automatic cleanup at proc_exit */
on_proc_exit(plr_cleanup, 0);
#ifndef WIN32
/*
* Force non-interactive mode since R may not do so.
* See comment in Rembedded.c just after R_Interactive = TRUE:
* "Rf_initialize_R set this based on isatty"
* If Postgres still has the tty attached, R_Interactive remains TRUE
*/
R_Interactive = false;
#endif
plr_pm_init_done = true;
}
/*
* plr_load_builtins() - load "builtin" PL/R functions into R interpreter
*/
static void
plr_load_builtins(Oid funcid)
{
int j;
char *cmd;
char *cmds[] =
{
/* first turn off error handling by R */
OPTIONS_NULL_CMD,
/* set up the postgres error handler in R */
THROWRERROR_CMD,
OPTIONS_THROWRERROR_CMD,
THROWNOTICE_CMD,
THROWERROR_CMD,
OPTIONS_THROWWARN_CMD,
/* install the commands for SPI support in the interpreter */
QUOTE_LITERAL_CMD,
QUOTE_IDENT_CMD,
SPI_EXEC_CMD,
SPI_PREPARE_CMD,
SPI_EXECP_CMD,
SPI_CURSOR_OPEN_CMD,
SPI_CURSOR_FETCH_CMD,
SPI_CURSOR_MOVE_CMD,
SPI_CURSOR_CLOSE_CMD,
SPI_LASTOID_CMD,
SPI_DBDRIVER_CMD,
SPI_DBCONN_CMD,
SPI_DBSENDQUERY_CMD,
SPI_DBFETCH_CMD,
SPI_DBCLEARRESULT_CMD,
SPI_DBGETQUERY_CMD,
SPI_DBREADTABLE_CMD,
SPI_DBDISCONN_CMD,
SPI_DBUNLOADDRIVER_CMD,
SPI_FACTOR_CMD,
/* handy predefined R functions */
REVAL,
/* terminate */
NULL
};
/*
* temporarily turn off R error reporting -- it will be turned back on
* once the custom R error handler is installed from the plr library
*/
load_r_cmd(cmds[0]);
/* next load the plr library into R */
load_r_cmd(get_load_self_ref_cmd(funcid));
/*
* run the rest of the R bootstrap commands, being careful to start
* at cmds[1] since we already executed cmds[0]
*/
for (j = 1; (cmd = cmds[j]); j++)
load_r_cmd(cmds[j]);
}
/*
* plr_load_modules() - Load procedures from
* table plr_modules (if it exists)
*
* The caller is responsible to ensure SPI has already been connected
* DO NOT make this static --- it has to be callable by reload_plr_modules()
*/
void
plr_load_modules(void)
{
int spi_rc;
char *cmd;
int i;
int fno;
MemoryContext oldcontext;
char *modulesSql;
/* switch to SPI memory context */
SWITCHTO_PLR_SPI_CONTEXT(oldcontext);
/*
* Check if table plr_modules exists
*/
if (!haveModulesTable(plr_nspOid))
{
/* clean up if SPI was used, and regardless restore caller's context */
CLEANUP_PLR_SPI_CONTEXT(oldcontext);
return;
}
/* plr_modules table exists -- get SQL code extract table's contents */
modulesSql = getModulesSql(plr_nspOid);
/* Read all the row's from it in the order of modseq */
spi_rc = SPI_exec(modulesSql, 0);
/* modulesSql no longer needed -- cleanup */
pfree(modulesSql);
if (spi_rc != SPI_OK_SELECT)
/* internal error */
elog(ERROR, "plr_init_load_modules: select from plr_modules failed");
/* If there's nothing, no modules exist */
if (SPI_processed == 0)
{
SPI_freetuptable(SPI_tuptable);
/* clean up if SPI was used, and regardless restore caller's context */
CLEANUP_PLR_SPI_CONTEXT(oldcontext);
return;
}
/*
* There is at least on module to load. Get the
* source from the modsrc load it in the R interpreter
*/
fno = SPI_fnumber(SPI_tuptable->tupdesc, "modsrc");
for (i = 0; i < SPI_processed; i++)
{
cmd = SPI_getvalue(SPI_tuptable->vals[i],
SPI_tuptable->tupdesc, fno);
if (cmd != NULL)
{
load_r_cmd(cmd);
pfree(cmd);
}
}
SPI_freetuptable(SPI_tuptable);
/* clean up if SPI was used, and regardless restore caller's context */
CLEANUP_PLR_SPI_CONTEXT(oldcontext);
}
static void
plr_init_all(Oid funcid)
{
MemoryContext oldcontext;
/* everything initialized needs to live until/unless we explicitly delete it */
oldcontext = MemoryContextSwitchTo(TopMemoryContext);
/* execute postmaster-startup safe initialization */
if (!plr_pm_init_done)
plr_init();
/*
* Any other initialization that must be done each time a new
* backend starts:
*/
if (!plr_be_init_done)
{
/* load "builtin" R functions */
plr_load_builtins(funcid);
/* obtain & store namespace OID of PL/R language handler */
plr_nspOid = getNamespaceOidFromFunctionOid(funcid);
/* try to load procedures from plr_modules */
plr_load_modules();
plr_be_init_done = true;
}
/* switch back to caller's context */
MemoryContextSwitchTo(oldcontext);
}
static Datum
plr_trigger_handler(PG_FUNCTION_ARGS)
{
plr_function *function;
SEXP fun;
SEXP rargs;
SEXP rvalue;
Datum retval;
Datum arg[FUNC_MAX_ARGS];
bool argnull[FUNC_MAX_ARGS];
TriggerData *trigdata = (TriggerData *) fcinfo->context;
TupleDesc tupdesc = trigdata->tg_relation->rd_att;
Datum *dvalues;
ArrayType *array;
#define FIXED_NUM_DIMS 1
int ndims = FIXED_NUM_DIMS;
int dims[FIXED_NUM_DIMS];
int lbs[FIXED_NUM_DIMS];
#undef FIXED_NUM_DIMS
TRIGGERTUPLEVARS;
ERRORCONTEXTCALLBACK;
int i;
if (trigdata->tg_trigger->tgnargs > 0)
dvalues = palloc(trigdata->tg_trigger->tgnargs * sizeof(Datum));
else
dvalues = NULL;
/* Find or compile the function */
function = compile_plr_function(fcinfo);
/* set up error context */
PUSH_PLERRCONTEXT(plr_error_callback, function->proname);
/*
* Build up arguments for the trigger function. The data types
* are mostly hardwired in advance
*/
/* first is trigger name */
arg[0] = DirectFunctionCall1(textin,
CStringGetDatum(trigdata->tg_trigger->tgname));
argnull[0] = false;
/* second is trigger relation oid */
arg[1] = ObjectIdGetDatum(trigdata->tg_relation->rd_id);
argnull[1] = false;
/* third is trigger relation name */
arg[2] = DirectFunctionCall1(textin,
CStringGetDatum(get_rel_name(trigdata->tg_relation->rd_id)));
argnull[2] = false;
/* fourth is when trigger fired, i.e. BEFORE or AFTER */
if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
arg[3] = DirectFunctionCall1(textin,
CStringGetDatum("BEFORE"));
else if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
arg[3] = DirectFunctionCall1(textin,
CStringGetDatum("AFTER"));
else
/* internal error */
elog(ERROR, "unrecognized tg_event");
argnull[3] = false;
/*
* fifth is level trigger fired, i.e. ROW or STATEMENT
* sixth is operation that fired trigger, i.e. INSERT, UPDATE, or DELETE
* seventh is NEW, eigth is OLD
*/
if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
{
arg[4] = DirectFunctionCall1(textin,
CStringGetDatum("STATEMENT"));
if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
arg[5] = DirectFunctionCall1(textin, CStringGetDatum("INSERT"));
else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
arg[5] = DirectFunctionCall1(textin, CStringGetDatum("DELETE"));
else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
arg[5] = DirectFunctionCall1(textin, CStringGetDatum("UPDATE"));
else
/* internal error */
elog(ERROR, "unrecognized tg_event");
arg[6] = (Datum) 0;
argnull[6] = true;
arg[7] = (Datum) 0;
argnull[7] = true;
}
else if (TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
{
arg[4] = DirectFunctionCall1(textin,
CStringGetDatum("ROW"));
if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
SET_INSERT_ARGS_567;
else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
SET_DELETE_ARGS_567;
else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
SET_UPDATE_ARGS_567;
else
/* internal error */
elog(ERROR, "unrecognized tg_event");
}
else
/* internal error */
elog(ERROR, "unrecognized tg_event");
argnull[4] = false;
argnull[5] = false;
/*
* finally, ninth argument is a text array of trigger arguments
*/
for (i = 0; i < trigdata->tg_trigger->tgnargs; i++)
dvalues[i] = DirectFunctionCall1(textin,
CStringGetDatum(trigdata->tg_trigger->tgargs[i]));
dims[0] = trigdata->tg_trigger->tgnargs;
lbs[0] = 1;
array = construct_md_array(dvalues, NULL, ndims, dims, lbs,
TEXTOID, -1, false, 'i');
arg[8] = PointerGetDatum(array);
argnull[8] = false;
/*
* All done building args; from this point it is just like
* calling a non-trigger function, except we need to be careful
* that the return value tuple is the same tupdesc as the trigger tuple.
*/
PROTECT(fun = function->fun);
/* Convert all call arguments */
PROTECT(rargs = plr_convertargs(function, arg, argnull, fcinfo));
/* Call the R function */
PROTECT(rvalue = call_r_func(fun, rargs));
/*
* Convert the return value from an R object to a Datum.
* We expect r_get_pg to do the right thing with missing or empty results.
*/
if (SPI_finish() != SPI_OK_FINISH)
elog(ERROR, "SPI_finish failed");
retval = r_get_pg(rvalue, function, fcinfo);
POP_PLERRCONTEXT;
UNPROTECT(3);
return retval;
}
static Datum
plr_func_handler(PG_FUNCTION_ARGS)
{
plr_function *function;
SEXP fun;
SEXP rargs;
SEXP rvalue;
Datum retval;
ERRORCONTEXTCALLBACK;
/* Find or compile the function */
function = compile_plr_function(fcinfo);
/* set up error context */
PUSH_PLERRCONTEXT(plr_error_callback, function->proname);
PROTECT(fun = function->fun);
/* Convert all call arguments */
PROTECT(rargs = plr_convertargs(function, fcinfo->arg, fcinfo->argnull, fcinfo));
/* Call the R function */
PROTECT(rvalue = call_r_func(fun, rargs));
/*
* Convert the return value from an R object to a Datum.
* We expect r_get_pg to do the right thing with missing or empty results.
*/
if (SPI_finish() != SPI_OK_FINISH)
elog(ERROR, "SPI_finish failed");
retval = r_get_pg(rvalue, function, fcinfo);
POP_PLERRCONTEXT;
UNPROTECT(3);
return retval;
}
/* ----------
* compile_plr_function
*
* Note: it's important for this to fall through quickly if the function
* has already been compiled.
* ----------
*/
plr_function *
compile_plr_function(FunctionCallInfo fcinfo)
{
Oid funcOid = fcinfo->flinfo->fn_oid;
HeapTuple procTup;
Form_pg_proc procStruct;
plr_function *function;
plr_func_hashkey hashkey;
bool hashkey_valid = false;
ERRORCONTEXTCALLBACK;
/*
* Lookup the pg_proc tuple by Oid; we'll need it in any case
*/
procTup = SearchSysCache(PROCOID,
ObjectIdGetDatum(funcOid),
0, 0, 0);
if (!HeapTupleIsValid(procTup))
/* internal error */
elog(ERROR, "cache lookup failed for proc %u", funcOid);
procStruct = (Form_pg_proc) GETSTRUCT(procTup);
/* set up error context */
PUSH_PLERRCONTEXT(plr_error_callback, NameStr(procStruct->proname));
/*
* See if there's already a cache entry for the current FmgrInfo.
* If not, try to find one in the hash table.
*/
function = (plr_function *) fcinfo->flinfo->fn_extra;
if (!function)
{
/* First time through in this backend? If so, init hashtable */
if (!plr_HashTable)
plr_HashTableInit();
/* Compute hashkey using function signature and actual arg types */
compute_function_hashkey(fcinfo, procStruct, &hashkey);
hashkey_valid = true;
/* And do the lookup */
function = plr_HashTableLookup(&hashkey);
/*
* first time through for this statement, set
* firstpass to TRUE
*/
load_r_cmd(PG_STATE_FIRSTPASS);
}
if (function)
{
bool function_valid;
/* We have a compiled function, but is it still valid? */
if (function->fn_xmin == HeapTupleHeaderGetXmin(procTup->t_data) &&
ItemPointerEquals(&function->fn_tid, &procTup->t_self))
function_valid = true;
else
function_valid = false;
if (!function_valid)
{
/*
* Nope, drop the hashtable entry. XXX someday, free all the
* subsidiary storage as well.
*/
plr_HashTableDelete(function);
/* free some of the subsidiary storage */
xpfree(function->proname);
R_ReleaseObject(function->fun);
xpfree(function);
function = NULL;
}
}
/*
* If the function wasn't found or was out-of-date, we have to compile it
*/
if (!function)
{
/*
* Calculate hashkey if we didn't already; we'll need it to store
* the completed function.
*/
if (!hashkey_valid)
compute_function_hashkey(fcinfo, procStruct, &hashkey);
/*
* Do the hard part.
*/
function = do_compile(fcinfo, procTup, &hashkey);
}
ReleaseSysCache(procTup);
/*
* Save pointer in FmgrInfo to avoid search on subsequent calls
*/
fcinfo->flinfo->fn_extra = (void *) function;
POP_PLERRCONTEXT;
/*
* Finally return the compiled function
*/
return function;
}
/*
* This is the slow part of compile_plr_function().
*/
static plr_function *
do_compile(FunctionCallInfo fcinfo,
HeapTuple procTup,
plr_func_hashkey *hashkey)
{
Form_pg_proc procStruct = (Form_pg_proc) GETSTRUCT(procTup);
Datum prosrcdatum;
bool isnull;
bool is_trigger = CALLED_AS_TRIGGER(fcinfo) ? true : false;
plr_function *function = NULL;
Oid fn_oid = fcinfo->flinfo->fn_oid;
char internal_proname[MAX_PRONAME_LEN];
char *proname;
Oid result_typid;
HeapTuple langTup;
HeapTuple typeTup;
Form_pg_language langStruct;
Form_pg_type typeStruct;
StringInfo proc_internal_def = makeStringInfo();
StringInfo proc_internal_args = makeStringInfo();
char *proc_source;
MemoryContext oldcontext;
char *p;
/* grab the function name */
proname = NameStr(procStruct->proname);
/* Build our internal proc name from the functions Oid */
sprintf(internal_proname, "PLR%u", fn_oid);
/*
* analyze the functions arguments and returntype and store
* the in-/out-functions in the function block and create
* a new hashtable entry for it.
*
* Then load the procedure into the R interpreter.
*/
/* the function structure needs to live until we explicitly delete it */
oldcontext = MemoryContextSwitchTo(TopMemoryContext);
/* Allocate a new procedure description block */
function = (plr_function *) palloc(sizeof(plr_function));
if (function == NULL)
ereport(ERROR,
(errcode(ERRCODE_OUT_OF_MEMORY),
errmsg("out of memory")));
MemSet(function, 0, sizeof(plr_function));
function->proname = pstrdup(proname);
function->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);
function->fn_tid = procTup->t_self;
#ifdef HAVE_WINDOW_FUNCTIONS
/* Flag for window functions */
function->iswindow = procStruct->proiswindow;
#endif
/* Lookup the pg_language tuple by Oid*/
langTup = SearchSysCache(LANGOID,
ObjectIdGetDatum(procStruct->prolang),
0, 0, 0);
if (!HeapTupleIsValid(langTup))
{
xpfree(function->proname);
xpfree(function);
/* internal error */
elog(ERROR, "cache lookup failed for language %u",
procStruct->prolang);
}
langStruct = (Form_pg_language) GETSTRUCT(langTup);
function->lanpltrusted = langStruct->lanpltrusted;
ReleaseSysCache(langTup);
/* get the functions return type */
if (procStruct->prorettype == ANYARRAYOID ||
procStruct->prorettype == ANYELEMENTOID)
{
result_typid = get_fn_expr_rettype(fcinfo->flinfo);
if (result_typid == InvalidOid)
result_typid = procStruct->prorettype;
}
else
result_typid = procStruct->prorettype;
/*
* Get the required information for input conversion of the
* return value.
*/
if (!is_trigger)
{
function->result_typid = result_typid;
typeTup = SearchSysCache(TYPEOID,
ObjectIdGetDatum(function->result_typid),
0, 0, 0);
if (!HeapTupleIsValid(typeTup))