This repository was archived by the owner on Jun 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathrcall.c
1287 lines (1045 loc) · 31.4 KB
/
rcall.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
/*------------------------------------------------------------------------------
*
* Copyright (c) 2016-Present Pivotal Software, Inc
*
*------------------------------------------------------------------------------
*/
/* Global header files */
#include <assert.h>
#include <errno.h>
#include <netinet/ip.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <signal.h>
#include <limits.h>
#include <unistd.h>
/* R header files */
#include <R.h>
#include <Rversion.h>
#include <Rembedded.h>
#include <Rinternals.h>
#include <R_ext/Parse.h>
#include <Rdefines.h>
/* PL/Container header files */
#include "common/comm_channel.h"
#include "common/messages/messages.h"
#include "common/comm_utils.h"
#include "common/comm_connectivity.h"
#include "common/comm_server.h"
#include "rcall.h"
#include "rconversions.h"
#include "rlogging.h"
#define ERR_MSG_LENGTH 512
#if (R_VERSION >= 132352) /* R_VERSION >= 2.5.0 */
#define R_PARSEVECTOR(a_, b_, c_) R_ParseVector(a_, b_, (ParseStatus *) c_, R_NilValue)
#else /* R_VERSION < 2.5.0 */
#define R_PARSEVECTOR(a_, b_, c_) R_ParseVector(a_, b_, (ParseStatus *) c_)
#endif /* R_VERSION >= 2.5.0 */
#ifndef PATH_MAX
#define PATH_MAX 2048
#endif
#define TYPE_ID_LENGTH 12
#define OPTIONS_NULL_CMD "options(error = expression(NULL))"
/* install the error handler to call our throw_r_error */
#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())))"
/* install the notice handler to call our throw_r_notice */
#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 SPI_EXEC_CMD \
"pg.spi.exec <-function(sql) {.Call(\"plr_SPI_exec\", sql)}"
#define SPI_DBGETQUERY_CMD \
"dbGetQuery <-function(sql) {\n" \
"data <- pg.spi.exec(sql)\n" \
"return(data)\n" \
"}"
#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 PG_LOG_DEBUG_CMD \
"plr.debug <- function(msg) {.Call(\"plr_debug\",msg)}"
#define PG_LOG_LOG_CMD \
"plr.log <- function(msg) {.Call(\"plr_log\",msg)}"
#define PG_LOG_INFO_CMD \
"plr.info <- function(msg) {.Call(\"plr_info\",msg)}"
#define PG_LOG_NOTICE_CMD \
"plr.notice <- function(msg) {.Call(\"plr_notice\",msg)}"
#define PG_LOG_WARNING_CMD \
"plr.warning <- function(msg) {.Call(\"plr_warning\",msg)}"
#define PG_LOG_ERROR_CMD \
"plr.error <- function(msg) {.Call(\"plr_error\",msg)}"
#define PG_LOG_FATAL_CMD \
"plr.fatal <- function(msg) {.Call(\"plr_fatal\",msg)}"
// init variable
plcConn *plcconn_global;
int plc_is_execution_terminated;
/* R interface */
void throw_pg_notice(const char **msg);
void throw_r_error(const char **msg);
SEXP plr_SPI_exec(SEXP rsql);
SEXP plr_SPI_prepare(SEXP rsql, SEXP rargtypes);
SEXP plr_SPI_execp(SEXP rsaved_plan, SEXP rargvalues);
/* Function definitions */
static char *get_load_self_ref_cmd(void);
static int load_r_cmd(const char *cmd);
static void send_error(plcConn *conn, char *msg);
static SEXP parse_r_code(const char *code, plcConn *conn, int *errorOccurred);
static char *create_r_func(plcMsgCallreq *req);
static int handle_matrix_set(SEXP retval, plcRFunction *r_func, plcMsgResult *res);
static int handle_retset(SEXP retval, plcRFunction *r_func, plcMsgResult *res);
static int process_call_results(plcConn *conn, SEXP retval, plcRFunction *r_func);
static SEXP arguments_to_r(plcRFunction *r_func);
static void pg_get_one_r(char *value, plcDatatype column_type, SEXP *obj, int elnum);
static SEXP process_SPI_results();
/* Globals */
/* Exposed in R_interface.h */
int R_SignalHandlers = 1;
/* set by hook throw_r_error */
static char *last_R_error_msg,
*last_R_notice;
/* Global PL/Container connection */
plcConn *plcconn_global;
plcMsgError *plcLastErrMessage = NULL;
/* R objects */
typedef struct r_saved_plan {
void *pplan; /* Store the pointer to plan on the QE side. */
plcDatatype *argtypes;
int nargs;
} r_saved_plan;
int r_init(void) {
char *rargv[] = {"rclient", "--slave", "--silent", "--no-save", "--no-restore"};
char *buf;
char *r_home;
int rargc;
int status;
int i;
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 */
SPI_EXEC_CMD,
SPI_PREPARE_CMD,
SPI_EXECP_CMD,
SPI_DBGETQUERY_CMD,
/* setup debug log to greenplum db */
PG_LOG_DEBUG_CMD,
PG_LOG_LOG_CMD,
PG_LOG_INFO_CMD,
PG_LOG_NOTICE_CMD,
PG_LOG_WARNING_CMD,
PG_LOG_ERROR_CMD,
PG_LOG_FATAL_CMD,
SPI_DBGETQUERY_CMD,
/* terminate */
NULL
};
r_home = getenv("R_HOME");
/*
* Stop R using its own signal handlers Otherwise, R will prompt the user for what to do and
will hang in the container
*/
R_SignalHandlers = 0;
if (r_home == NULL) {
plc_elog(ERROR, "R_HOME is not set, please check and set the R_HOME");
return -1;
}
rargc = sizeof(rargv) / sizeof(rargv[0]);
if (!Rf_initEmbeddedR(rargc, rargv)) {
//TODO: return an error
plc_elog(ERROR, "can not start Embedded R");
}
/*
* temporarily turn off R error reporting -- it will be turned back on
* once the custom R error handler is installed from the plr library
*/
status = load_r_cmd(cmds[0]);
if (status < 0) {
return -1;
}
status = load_r_cmd(buf = get_load_self_ref_cmd());
pfree(buf);
if (status < 0) {
return -1;
}
for (i = 1; (cmd = cmds[i]); i++) {
status = load_r_cmd(cmds[i]);
if (status < 0) {
return -1;
}
}
return 0;
}
static char *get_load_self_ref_cmd() {
char *buf = (char *) pmalloc(PATH_MAX);
#ifdef __linux__
char path[PATH_MAX];
char *p = NULL;
int size;
/* next load the plr library into R */
size = readlink("/proc/self/exe", path, PATH_MAX);
if (size == -1) {
plc_elog(ERROR, "can not read execute path");
} else {
path[size] = '\0';
}
plc_elog(DEBUG1, "Current R client path is %s", path);
p = strrchr(path, '/');
if(p) {
*(p+1) = '\0';
} else {
plc_elog(ERROR, "can not read execute directory %s", path);
}
plc_elog(DEBUG1, "Split path by '/'. Get the path: %s", path);
snprintf(buf, PATH_MAX, "dyn.load(\"%s/%s\")", path, "librcall.so");
#else
snprintf(buf, PATH_MAX, "dyn.load(\"%s\")", "librcall.so");
#endif
return buf;
}
static int load_r_cmd(const char *cmd) {
SEXP cmdSexp,
cmdexpr;
int i,
status = 0;
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) {
goto error;
}
/* 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) {
goto error;
}
}
UNPROTECT(2);
return 0;
error:
UNPROTECT(2);
raise_execution_error("Error evaluating function %s", cmd);
return -1;
}
void handle_call(plcMsgCallreq *req, plcConn *conn) {
SEXP r,
strres,
call,
rargs;
int errorOccurred;
char *func,
*errmsg;
client_log_level = req->logLevel;
plc_elog(DEBUG1, "R client receives a call");
/*
* Keep our connection for future calls from R back to us.
*/
plcconn_global = conn;
/* wrap the input in a function and evaluate the result */
func = create_r_func(req);
plcRFunction *r_func = plc_R_init_function(req);
PROTECT(r = parse_r_code(func, conn, &errorOccurred));
pfree(func);
if (errorOccurred) {
//TODO send real error message
/* run_r_code will send an error back */
UNPROTECT(1); //r
return;
}
if (req->nargs > 0) {
rargs = arguments_to_r(r_func);
PROTECT(call = lcons(r, rargs));
} else {
PROTECT(call = lcons(r, R_NilValue));
}
/* call the function */
plc_is_execution_terminated = 0;
PROTECT(strres = R_tryEval(call, R_GlobalEnv, &errorOccurred));
if (errorOccurred) {
UNPROTECT(3); //r, strres, call
//TODO send real error message
if (last_R_error_msg) {
errmsg = strdup(last_R_error_msg);
} else {
errmsg = strdup("Error executing\n");
errmsg = realloc(errmsg, strlen(errmsg) + strlen(req->proc.src));
errmsg = strcat(errmsg, req->proc.src);
}
send_error(conn, errmsg);
free(errmsg);
plc_r_free_function(r_func);
return;
}
if (plc_is_execution_terminated == 0) {
process_call_results(conn, strres, r_func);
}
plc_r_free_function(r_func);
UNPROTECT(3); //r, strres, call
plc_elog(DEBUG1, "R client finished processing this call");
return;
}
static void send_error(plcConn *conn, char *msg) {
/* an exception was thrown */
plcMsgError *err;
err = pmalloc(sizeof(plcMsgError));
err->msgtype = MT_EXCEPTION;
err->message = msg;
err->stacktrace = NULL;
/* send the result back */
plcontainer_channel_send(conn, (plcMessage *) err);
/* free the objects */
free(err);
}
static SEXP parse_r_code(const char *code, plcConn *conn, int *errorOccurred) {
/* int hadError; */
ParseStatus status;
char *errmsg;
SEXP tmp,
rbody,
fun;
PROTECT(rbody = mkString(code));
/*
limit the number of expressions to be parsed to 2:
- the definition of the function, i.e. f <- function() {...}
- the call to the function f()
kind of useful to prevent injection, but pointless since we are
running in a container. I think -1 is equivalent to no limit.
*/
PROTECT(tmp = R_PARSEVECTOR(rbody, -1, &status));
if (tmp != R_NilValue) {
PROTECT(fun = VECTOR_ELT(tmp, 0));
} else {
PROTECT(fun = R_NilValue);
}
if (status != PARSE_OK) {
if (last_R_error_msg != NULL) {
errmsg = strdup(last_R_error_msg);
} else {
errmsg = strdup("Parse Error\n");
errmsg = realloc(errmsg, strlen(errmsg) + strlen(code) + 1);
errmsg = strcat(errmsg, code);
}
goto error;
}
UNPROTECT(3);
*errorOccurred = 0;
return fun;
error:
UNPROTECT(3);
/*
* set the global error flag
*/
*errorOccurred = 1;
send_error(conn, errmsg);
free(errmsg);
return NULL;
}
static char *create_r_func(plcMsgCallreq *req) {
int plen;
char *mrc;
size_t mlen = 0;
int i;
/* calculate space required for args */
mlen = 5; // for args,
for (i = 0; i < req->nargs; i++) {
/* +4 for , and space */
if (req->args[i].name != NULL) {
mlen += strlen(req->args[i].name) + 4;
}
}
/*
* room for function source and function call
*/
mlen += strlen(req->proc.src) + strlen(req->proc.name) + 40 + strlen("gpdb.");
mrc = pmalloc(mlen);
/* create the first part of the function name and add the args array */
plen = snprintf(mrc, mlen, "gpdb.%s <- function(args", req->proc.name);
for (i = 0; i < req->nargs; i++) {
if (req->args[i].name != NULL) {
/*
* add a comma, note if there are no args this will not be added
* and if there are some it will be added before the arg
*/
strcat(mrc, ", ");
plen += 2;
strcat(mrc, req->args[i].name);
/* keep track of where we are copying */
plen += strlen(req->args[i].name);
}
}
/* finish the function definition from where we left off */
plen = snprintf(mrc + plen, mlen, ") {%s}", req->proc.src);
assert(plen >= 0 && ((size_t) plen) < mlen);
return mrc;
}
static int handle_frame(SEXP df, plcRFunction *r_func, plcMsgResult *res) {
uint32 row, col, cols;
/* a data frame is an array of columns, the length of which is the number of columns */
res->cols = 1;
cols = length(df);
SEXP dfcol = VECTOR_ELT(df, 0);
res->rows = length(dfcol);
res->data = pmalloc(res->rows * sizeof(rawdata *));
plc_r_copy_type(&res->types[0], &r_func->res);
res->names[0] = strdup(r_func->res.argName);
for (row = 0; row < res->rows; row++) {
plcUDT *udt;
// allocate space for the data
res->data[row] = pmalloc(sizeof(rawdata));
// allocate space for the UDT
udt = pmalloc(sizeof(plcUDT));
// allocate space for the columns of the UDT
udt->data = pmalloc(cols * sizeof(rawdata));
for (col = 0; col < cols; col++) {
PROTECT(dfcol = VECTOR_ELT(df, col));
/*
* R stores characters in factors for efficiency...
*/
if (isFactor(dfcol)) {
/*
* a factor is a special type of integer
* but must check for NA value first
*/
if (INTEGER(dfcol)[row] != NA_INTEGER) {
SEXP c;
PROTECT(c = Rf_asCharacterFactor(dfcol));
rawdata *datum = plc_r_vector_element_rawdata(c, row, &r_func->res.subTypes[col]);
udt->data[col].isnull = datum->isnull;
udt->data[col].value = datum->value;
UNPROTECT(1);
free(datum);
} else {
udt->data[col].isnull = TRUE;
udt->data[col].value = NULL;
}
} else {
rawdata *datum = plc_r_vector_element_rawdata(dfcol, row, &r_func->res.subTypes[col]);
udt->data[col].isnull = datum->isnull;
udt->data[col].value = datum->value;
free(datum);
}
UNPROTECT(1);
}
res->data[row]->value = (char *) udt;
res->data[row]->isnull = FALSE;
}
return 0;
}
static int handle_matrix_set(SEXP retval, plcRFunction *r_func, plcMsgResult *res) {
int cols, start = 0;
uint32 i;
SEXP rdims;
PROTECT(rdims = getAttrib(retval, R_DimSymbol));
// get the number of rows
if (rdims != R_NilValue) {
res->rows = INTEGER(rdims)[0];
cols = INTEGER(rdims)[1];
} else {
UNPROTECT(1);
return -1;
}
UNPROTECT(1);
// this is a matrix of vectors but we only handle one column in set of right now
res->cols = 1;
res->data = malloc(res->rows * sizeof(rawdata *));
for (i = 0; i < res->rows; i++) {
res->data[i] = malloc(cols * sizeof(rawdata));
}
plc_r_copy_type(&res->types[0], &r_func->res);
res->names[0] = strdup(r_func->res.argName);
start = 0;
for (i = 0; i < res->rows; i++) {
res->data[i][0].isnull = 0;
if (plc_r_matrix_as_setof(retval, start, cols, &res->data[i][0].value, &r_func->res) != 0) {
free_result(res, true);
return -1;
}
start = start + cols;
}
return 0;
}
static int handle_retset(SEXP retval, plcRFunction *r_func, plcMsgResult *res) {
uint32 i = 0;
rawdata *raw;
/*
* we check for the dims here to find arrays of text
* a simple one dimensional array of text will be handled below
* an n dimensional array of text will be handle in handle_matrix_set
* having a dimension should guarantee that it is an array of text
*/
if (isMatrix(retval) || (IS_CHARACTER(retval) && getAttrib(retval, R_DimSymbol) != R_NilValue)) {
handle_matrix_set(retval, r_func, res);
} else if (isFrame(retval)) {
handle_frame(retval, r_func, res);
} else {
res->rows = length(retval);
res->cols = 1;
res->data = malloc(res->rows * sizeof(rawdata *));
for (i = 0; i < res->rows; i++) {
res->data[i] = NULL;
}
plc_r_copy_type(&res->types[0], &r_func->res);
res->names[0] = strdup(r_func->res.argName);
for (i = 0; i < res->rows; i++) {
if (r_func->res.conv.outputfunc == NULL) {
raise_execution_error("Type %d is not yet supported by R container",
(int) res->types[0].type);
free_result(res, true);
return -1;
}
raw = plc_r_vector_element_rawdata(retval, i, &r_func->res);
if (raw == NULL) {
free_result(res, true);
return -1;
} else {
res->data[i] = raw;
}
}
}
return 0;
}
static int process_call_results(plcConn *conn, SEXP retval, plcRFunction *r_func) {
plcMsgResult *res;
uint32 i = 0;
int ret = 0;
/* allocate a result */
res = malloc(sizeof(plcMsgResult));
res->msgtype = MT_RESULT;
res->names = malloc(1 * sizeof(char *));
res->types = malloc(1 * sizeof(plcType));
res->exception_callback = NULL;
if (r_func->retset != 0) {
if (handle_retset(retval, r_func, res) != 0) {
free_result(res, true);
return -1;
}
} else {
res->rows = 1;
res->cols = 1;
res->data = malloc(res->rows * sizeof(rawdata *));
for (i = 0; i < res->rows; i++) {
res->data[i] = malloc(res->cols * sizeof(rawdata));
}
plc_r_copy_type(&res->types[0], &r_func->res);
res->names[0] = strdup(r_func->res.argName);
if (retval == R_NilValue) {
res->data[0][0].isnull = 1;
res->data[0][0].value = NULL;
} else {
for (i = 0; i < res->rows; i++) {
res->data[i][0].isnull = 0;
if (r_func->res.conv.outputfunc == NULL) {
raise_execution_error("Type %d is not yet supported by R container",
(int) res->types[0].type);
free_result(res, true);
return -1;
}
ret = r_func->res.conv.outputfunc(retval, &res->data[i][0].value, &r_func->res);
if (ret != 0) {
raise_execution_error("Exception raised converting function output to function output type %d",
(int) res->types[0].type);
free_result(res, true);
return -1;
}
}
}
}
/* send the result back */
plcontainer_channel_send(conn, (plcMessage *) res);
free_result(res, true);
return 0;
}
static SEXP arguments_to_r(plcRFunction *r_func) {
SEXP r_args, r_curarg, allargs, element;
int i, notnull = 0;
/* number of arguments that have names and should make it to the input tuple */
for (i = 0; i < r_func->nargs; i++) {
if (r_func->call->args[i].name != NULL) {
notnull += 1;
}
}
/* create the argument list plus 1 for the unnamed args list */
PROTECT(r_args = r_curarg = allocList(notnull + 1));
PROTECT(allargs = allocList(r_func->nargs));
/* all argument vector is the 1st argument */
SETCAR(r_curarg, allargs);
r_curarg = CDR(r_curarg);
for (i = 0; i < r_func->nargs; i++) {
if (r_func->call->args[i].data.isnull) {
PROTECT(element = R_NilValue);
} else {
if (r_func->args[i].conv.inputfunc == NULL) {
raise_execution_error("Parameter '%s' type %d is not supported",
r_func->args[i].argName,
r_func->args[i].type);
UNPROTECT(2);
return NULL;
}
// this is returned protected by the input function
element = r_func->args[i].conv.inputfunc(r_func->call->args[i].data.value, &r_func->args[i]);
}
if (element == NULL) {
raise_execution_error("Converting parameter '%s' to R type failed",
r_func->args[i].argName);
/* we've made it to the i'th argument */
UNPROTECT(2 + i - 1);
return NULL;
}
if (r_func->call->args[i].name != NULL) {
SETCAR(r_curarg, element);
r_curarg = CDR(r_curarg);
}
/* all arguments named or otherwise go in here */
SETCAR(allargs, element);
allargs = CDR(allargs);
}
/* the input function above returns args protected */
UNPROTECT(r_func->nargs + 2);
return r_args;
}
/*
* given a single non-array pg value, convert to its R value representation
*/
static void pg_get_one_r(char *value, plcDatatype column_type, SEXP *obj, int elnum) {
int bsize;
switch (column_type) {
/* 2 and 4 byte integer pgsql datatype => use R INTEGER */
case PLC_DATA_INT2:
INTEGER_DATA(*obj)[elnum] = *((int16 *) value);
break;
case PLC_DATA_INT4:
INTEGER_DATA(*obj)[elnum] = *((int32 *) value);
break;
/*
* Other numeric types => use R REAL
* Note pgsql int8 is mapped to R REAL
* because R INTEGER is only 4 byte
*/
case PLC_DATA_INT8:
NUMERIC_DATA(*obj)[elnum] = (int64) (*((float8 *) value));
break;
case PLC_DATA_FLOAT4:
NUMERIC_DATA(*obj)[elnum] = *((float4 *) value);
break;
case PLC_DATA_FLOAT8:
NUMERIC_DATA(*obj)[elnum] = *((float8 *) value);
break;
case PLC_DATA_INT1:
LOGICAL_DATA(*obj)[elnum] = *((int8 *) value);
break;
case PLC_DATA_UDT:
case PLC_DATA_INVALID:
case PLC_DATA_ARRAY:
raise_execution_error("unhandled type %s [%d]",
plc_get_type_name(column_type), column_type);
break;
case PLC_DATA_BYTEA:
/*
* for bytea type, we first get its size then do copy
* based on upstream, we trade it as TEXT, so '\0' is
* not accepted in bytea type
*/
if (value[0] != '\0') {
bsize = *((int *) value);
SET_STRING_ELT(*obj, elnum, mkCharLen(value + 4, bsize));
break;
}
// fallthrough
case PLC_DATA_TEXT:
default:
/* Everything else is defaulted to string */
if (value) {
SET_STRING_ELT(*obj, elnum, COPY_TO_USER_STRING(value));
} else {
SET_STRING_ELT(*obj, elnum, NA_STRING);
}
}
}
/*
* common function for SPI exec and SPI execp to extract returned results
*/
static SEXP process_SPI_results() {
plcMsgResult *result;
plcMessage *resp;
SEXP r_result = NULL,
names,
row_names,
fldvec;
uint32 i, j;
int res = 0;
char buf[256];
receive:
res = plcontainer_channel_receive(plcconn_global, &resp, MT_PING_BIT | MT_CALLREQ_BIT | MT_RESULT_BIT| MT_EXCEPTION_BIT);
if (res < 0) {
raise_execution_error("Error receiving data from the backend, %d", res);
return NULL;
}
switch (resp->msgtype) {
case MT_CALLREQ:
handle_call((plcMsgCallreq *) resp, plcconn_global);
free_callreq((plcMsgCallreq *) resp, false, false);
goto receive;
case MT_PING:
plcontainer_channel_send(plcconn_global, resp);
goto receive;
case MT_EXCEPTION:
if (((plcMsgError *) resp)->message != NULL) {
raise_execution_error("SPI process_SPI_results failed due to %s", ((plcMsgError *) resp)->message);
} else {
raise_execution_error("SPI process_SPI_results failed.");
}
break;
case MT_RESULT:
break;
default:
raise_execution_error("didn't receive result back %c", resp->msgtype);
return NULL;
}
result = (plcMsgResult *) resp;
/*
* If result->cols=0, it should be the INSERT, UPDATE or DELETE statment
*/
if (result->cols == 0) {
char buffer[64];
PROTECT(r_result = NEW_CHARACTER(1));
snprintf(buf, sizeof(buffer), "%d", result->rows);
SET_STRING_ELT(r_result, 0, COPY_TO_USER_STRING(buf));
UNPROTECT(1);
free_result(result, false);
return r_result;
} else if (result->rows == 0) {
free_result(result, false);
return R_NilValue;
}
/*
* r_result is a list of columns
*/
PROTECT(r_result = NEW_LIST(result->cols));
/*
* names for each column
*/
PROTECT(names = NEW_CHARACTER(result->cols));
/*
* we store everything in columns because vectors can only have one type
* normally we get tuples back in rows with each column possibly a different type,
* instead we store each column in a single vector
*/
for (j = 0; j < result->cols; j++) {
/*
* set the names of the column
*/
SET_STRING_ELT(names, j, Rf_mkChar(result->names[j]));
/*
* create a vector of the type that is rows long
* For type BYTEA, we process it as TEXT
*/
if (result->types[j].type == PLC_DATA_BYTEA) {
PROTECT(fldvec = get_r_vector(PLC_DATA_TEXT, result->rows));
} else {
PROTECT(fldvec = get_r_vector(result->types[j].type, result->rows));
}
for (i = 0; i < result->rows; i++) {
/*
* store the value
*/
pg_get_one_r(result->data[i][j].value, result->types[j].type, &fldvec, i);
}
UNPROTECT(1);
SET_VECTOR_ELT(r_result, j, fldvec);
}
/* attach the column names */
setAttrib(r_result, R_NamesSymbol, names);
/* attach row names - basically just the row number, zero based */
PROTECT(row_names = allocVector(STRSXP, result->rows));
for (i = 0; i < result->rows; i++) {
sprintf(buf, "%d", i + 1);
SET_STRING_ELT(row_names, i, COPY_TO_USER_STRING(buf));
}
setAttrib(r_result, R_RowNamesSymbol, row_names);
/* finally, tell R we are a data.frame */
setAttrib(r_result, R_ClassSymbol, mkString("data.frame"));
/*
* result has an attribute names which is a vector of names
* a vector of vectors num columns long by num rows
*/
free_result(result, false);
UNPROTECT(3);
return r_result;
}
/*
* plr_SPI_exec - The builtin SPI_exec command for the R interpreter
*/
SEXP plr_SPI_exec(SEXP rsql) {
const char *sql;
plcMsgSQL *msg;
PROTECT(rsql = AS_CHARACTER(rsql));
sql = CHAR(STRING_ELT(rsql, 0));
UNPROTECT(1);
if (sql == NULL) {
raise_execution_error("R client cannot execute empty query");
return NULL;
}
/* If the execution was terminated we don't need to proceed with SPI */
if (plc_is_execution_terminated != 0) {
return NULL;
}
msg = pmalloc(sizeof(plcMsgSQL));
msg->msgtype = MT_SQL;
msg->sqltype = SQL_TYPE_STATEMENT;
msg->limit = 0; /* No limit for R. */