-
Notifications
You must be signed in to change notification settings - Fork 15
/
pg_conversion.c
2025 lines (1777 loc) · 46.3 KB
/
pg_conversion.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
*
* pg_conversion.c - functions for converting arguments from pg types to
* R types, and for converting return values from R types
* to pg types
*/
#include "plr.h"
static void pg_get_one_r(char *value, Oid arg_out_fn_oid, SEXP *obj,
int elnum);
static SEXP get_r_vector(Oid typtype, int numels);
static Datum get_trigger_tuple(SEXP rval, plr_function *function,
FunctionCallInfo fcinfo, bool *isnull);
static Datum get_tuplestore(SEXP rval, plr_function *function,
FunctionCallInfo fcinfo, bool *isnull);
static Datum get_simple_array_datum(SEXP rval, Oid typelem, bool *isnull);
static Datum get_array_datum(SEXP rval, plr_function *function, int col, bool *isnull);
static Datum get_frame_array_datum(SEXP rval, plr_function *function, int col,
bool *isnull);
static Datum get_md_array_datum(SEXP rval, int ndims, plr_function *function, int col,
bool *isnull);
static Datum get_generic_array_datum(SEXP rval, plr_function *function, int col,
bool *isnull);
static Tuplestorestate *get_frame_tuplestore(SEXP rval,
plr_function *function,
AttInMetadata *attinmeta,
MemoryContext per_query_ctx,
bool retset);
static Tuplestorestate *get_matrix_tuplestore(SEXP rval,
plr_function *function,
AttInMetadata *attinmeta,
MemoryContext per_query_ctx,
bool retset);
static Tuplestorestate *get_generic_tuplestore(SEXP rval,
plr_function *function,
AttInMetadata *attinmeta,
MemoryContext per_query_ctx,
bool retset);
static SEXP coerce_to_char(SEXP rval);
extern char *last_R_error_msg;
/*
* given a scalar pg value, convert to a one row R vector
*/
SEXP
pg_scalar_get_r(Datum dvalue, Oid arg_typid, FmgrInfo arg_out_func)
{
SEXP result;
/* add our value to it */
if (arg_typid != BYTEAOID)
{
char *value;
value = DatumGetCString(FunctionCall3(&arg_out_func,
dvalue,
(Datum) 0,
Int32GetDatum(-1)));
/* get new vector of the appropriate type, length 1 */
PROTECT(result = get_r_vector(arg_typid, 1));
pg_get_one_r(value, arg_typid, &result, 0);
UNPROTECT(1);
}
else
{
SEXP s, t, obj;
int status;
Datum dt_dvalue = PointerGetDatum(PG_DETOAST_DATUM(dvalue));
int bsize = VARSIZE((bytea *) dt_dvalue);
PROTECT(obj = get_r_vector(arg_typid, bsize));
memcpy((char *) RAW(obj),
VARDATA((bytea *) dt_dvalue),
bsize);
/*
* Need to construct a call to
* unserialize(rval)
*/
PROTECT(t = s = allocList(2));
SET_TYPEOF(s, LANGSXP);
SETCAR(t, install("unserialize"));
t = CDR(t);
SETCAR(t, obj);
PROTECT(result = R_tryEval(s, 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 \"unserialize\".")));
}
UNPROTECT(3);
}
return result;
}
/*
* Given an array pg value, convert to a multi-row R vector.
*/
SEXP
pg_array_get_r(Datum dvalue, FmgrInfo out_func, int typlen, bool typbyval, char typalign)
{
/*
* Loop through and convert each scalar value.
* Use the converted values to build an R vector.
*/
SEXP result;
ArrayType *v;
Oid element_type;
int i, j, k,
nitems,
nr = 1,
nc = 1,
nz = 1,
ndim,
*dim;
int elem_idx = 0;
Datum *elem_values;
bool *elem_nulls;
bool fast_track_type;
/* short-circuit for NULL datums */
if (dvalue == (Datum) NULL)
return R_NilValue;
v = DatumGetArrayTypeP(dvalue);
ndim = ARR_NDIM(v);
element_type = ARR_ELEMTYPE(v);
dim = ARR_DIMS(v);
nitems = ArrayGetNItems(ARR_NDIM(v), ARR_DIMS(v));
switch (element_type)
{
case INT4OID:
case FLOAT8OID:
fast_track_type = true;
break;
default:
fast_track_type = false;
}
/*
* Special case for pass-by-value data types, if the following conditions are met:
* designated fast_track_type
* no NULL elements
* 1 dimensional array only
* at least one element
*/
if (fast_track_type &&
typbyval &&
!ARR_HASNULL(v) &&
(ndim == 1) &&
(nitems > 0))
{
char *p = ARR_DATA_PTR(v);
/* get new vector of the appropriate type and length */
PROTECT(result = get_r_vector(element_type, nitems));
/* keep this in sync with switch above -- fast_track_type only */
switch (element_type)
{
case INT4OID:
Assert(sizeof(int) == 4);
memcpy(INTEGER_DATA(result), p, nitems * sizeof(int));
break;
case FLOAT8OID:
Assert(sizeof(double) == 8);
memcpy(NUMERIC_DATA(result), p, nitems * sizeof(double));
break;
default:
/* Everything else is error */
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("direct array passthrough attempted for unsupported type")));
}
if (ndim > 1)
{
SEXP matrix_dims;
/* attach dimensions */
PROTECT(matrix_dims = allocVector(INTSXP, ndim));
for (i = 0; i < ndim; i++)
INTEGER_DATA(matrix_dims)[i] = dim[i];
setAttrib(result, R_DimSymbol, matrix_dims);
UNPROTECT(1);
}
UNPROTECT(1); /* result */
}
else
{
deconstruct_array(v, element_type,
typlen, typbyval, typalign,
&elem_values, &elem_nulls, &nitems);
/* array is empty */
if (nitems == 0)
{
PROTECT(result = get_r_vector(element_type, nitems));
UNPROTECT(1);
return result;
}
if (ndim == 1)
nr = nitems;
else if (ndim == 2)
{
nr = dim[0];
nc = dim[1];
}
else if (ndim == 3)
{
nr = dim[0];
nc = dim[1];
nz = dim[2];
}
else
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("greater than 3-dimensional arrays are not yet supported")));
/* get new vector of the appropriate type and length */
PROTECT(result = get_r_vector(element_type, nitems));
/* Convert all values to their R form and build the vector */
for (i = 0; i < nr; i++)
{
for (j = 0; j < nc; j++)
{
for (k = 0; k < nz; k++)
{
char *value;
Datum itemvalue;
bool isnull;
int idx = (k * nr * nc) + (j * nr) + i;
isnull = elem_nulls[elem_idx];
itemvalue = elem_values[elem_idx++];
if (!isnull)
{
value = DatumGetCString(FunctionCall3(&out_func,
itemvalue,
(Datum) 0,
Int32GetDatum(-1)));
}
else
value = NULL;
/*
* Note that pg_get_one_r() replaces NULL values with
* the NA value appropriate for the data type.
*/
pg_get_one_r(value, element_type, &result, idx);
if (value != NULL)
pfree(value);
}
}
}
pfree(elem_values);
pfree(elem_nulls);
if (ndim > 1)
{
SEXP matrix_dims;
/* attach dimensions */
PROTECT(matrix_dims = allocVector(INTSXP, ndim));
for (i = 0; i < ndim; i++)
INTEGER_DATA(matrix_dims)[i] = dim[i];
setAttrib(result, R_DimSymbol, matrix_dims);
UNPROTECT(1);
}
UNPROTECT(1); /* result */
}
return result;
}
/*
* Given an array pg datums, convert to a multi-row R vector.
*/
SEXP
pg_datum_array_get_r(Datum *elem_values, bool *elem_nulls, int numels, bool has_nulls,
Oid element_type, FmgrInfo out_func, bool typbyval)
{
/*
* Loop through and convert each scalar value.
* Use the converted values to build an R vector.
*/
SEXP result;
int i;
bool fast_track_type;
switch (element_type)
{
case INT4OID:
case FLOAT8OID:
fast_track_type = true;
break;
default:
fast_track_type = false;
}
/*
* Special case for pass-by-value data types, if the following conditions are met:
* designated fast_track_type
* no NULL elements
* 1 dimensional array only
* at least one element
*/
if (fast_track_type &&
typbyval &&
!has_nulls &&
(numels > 0))
{
SEXP matrix_dims;
/* get new vector of the appropriate type and length */
PROTECT(result = get_r_vector(element_type, numels));
/* keep this in sync with switch above -- fast_track_type only */
switch (element_type)
{
case INT4OID:
Assert(sizeof(int) == 4);
memcpy(INTEGER_DATA(result), elem_values, numels * sizeof(int));
break;
case FLOAT8OID:
Assert(sizeof(double) == 8);
memcpy(NUMERIC_DATA(result), elem_values, numels * sizeof(double));
break;
default:
/* Everything else is error */
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("direct array passthrough attempted for unsupported type")));
}
/* attach dimensions */
PROTECT(matrix_dims = allocVector(INTSXP, 1));
INTEGER_DATA(matrix_dims)[0] = numels;
setAttrib(result, R_DimSymbol, matrix_dims);
UNPROTECT(1);
UNPROTECT(1); /* result */
}
else
{
SEXP matrix_dims;
/* array is empty */
if (numels == 0)
{
PROTECT(result = get_r_vector(element_type, 0));
UNPROTECT(1);
return result;
}
/* get new vector of the appropriate type and length */
PROTECT(result = get_r_vector(element_type, numels));
/* Convert all values to their R form and build the vector */
for (i = 0; i < numels; i++)
{
char *value;
Datum itemvalue;
bool isnull;
isnull = elem_nulls[i];
itemvalue = elem_values[i];
if (!isnull)
{
value = DatumGetCString(FunctionCall3(&out_func,
itemvalue,
(Datum) 0,
Int32GetDatum(-1)));
}
else
value = NULL;
/*
* Note that pg_get_one_r() replaces NULL values with
* the NA value appropriate for the data type.
*/
pg_get_one_r(value, element_type, &result, i);
if (value != NULL)
pfree(value);
}
/* attach dimensions */
PROTECT(matrix_dims = allocVector(INTSXP, 1));
INTEGER_DATA(matrix_dims)[0] = numels;
setAttrib(result, R_DimSymbol, matrix_dims);
UNPROTECT(1);
UNPROTECT(1); /* result */
}
return result;
}
/*
* Given an array of pg tuples, convert to an R list
* the created object is not quite actually a data.frame
*/
SEXP
pg_tuple_get_r_frame(int ntuples, HeapTuple *tuples, TupleDesc tupdesc)
{
int nr = ntuples;
int nc = tupdesc->natts;
int nc_non_dropped = 0;
int df_colnum = 0;
int i = 0;
int j = 0;
Oid element_type;
Oid typelem;
SEXP names;
SEXP row_names;
char buf[256];
SEXP result;
SEXP fldvec;
if (tuples == NULL || ntuples < 1)
return R_NilValue;
/* Count non-dropped attributes so we can later ignore the dropped ones */
for (j = 0; j < nc; j++)
{
if (!tupdesc->attrs[j]->attisdropped)
nc_non_dropped++;
}
/*
* Allocate the data.frame initially as a list,
* and also allocate a names vector for the column names
*/
PROTECT(result = NEW_LIST(nc_non_dropped));
PROTECT(names = NEW_CHARACTER(nc_non_dropped));
/*
* Loop by columns
*/
for (j = 0; j < nc; j++)
{
int16 typlen;
bool typbyval;
char typdelim;
Oid typoutput,
typioparam;
FmgrInfo outputproc;
char typalign;
/* ignore dropped attributes */
if (tupdesc->attrs[j]->attisdropped)
continue;
/* set column name */
SET_COLUMN_NAMES;
/* get column datatype oid */
element_type = SPI_gettypeid(tupdesc, j + 1);
/*
* Check to see if it is an array type. get_element_type will return
* InvalidOid instead of actual element type if the type is not a
* varlena array.
*/
typelem = get_element_type(element_type);
/* get new vector of the appropriate type and length */
if (typelem == InvalidOid)
PROTECT(fldvec = get_r_vector(element_type, nr));
else
{
PROTECT(fldvec = NEW_LIST(nr));
get_type_io_data(typelem, IOFunc_output, &typlen, &typbyval,
&typalign, &typdelim, &typioparam, &typoutput);
fmgr_info(typoutput, &outputproc);
}
/* loop rows for this column */
for (i = 0; i < nr; i++)
{
if (typelem == InvalidOid)
{
/* not an array type */
char *value;
value = SPI_getvalue(tuples[i], tupdesc, j + 1);
pg_get_one_r(value, element_type, &fldvec, i);
}
else
{
/* array type */
Datum dvalue;
bool isnull;
SEXP fldvec_elem;
dvalue = SPI_getbinval(tuples[i], tupdesc, j + 1, &isnull);
if (!isnull)
PROTECT(fldvec_elem = pg_array_get_r(dvalue, outputproc, typlen, typbyval, typalign));
else
PROTECT(fldvec_elem = R_NilValue);
SET_VECTOR_ELT(fldvec, i, fldvec_elem);
UNPROTECT(1);
}
}
SET_VECTOR_ELT(result, df_colnum, fldvec);
UNPROTECT(1);
df_colnum++;
}
/* attach the column names */
setAttrib(result, R_NamesSymbol, names);
/* attach row names - basically just the row number, zero based */
PROTECT(row_names = allocVector(STRSXP, nr));
for (i=0; i<nr; i++)
{
sprintf(buf, "%d", i+1);
SET_STRING_ELT(row_names, i, COPY_TO_USER_STRING(buf));
}
setAttrib(result, R_RowNamesSymbol, row_names);
/* finally, tell R we are a data.frame */
setAttrib(result, R_ClassSymbol, mkString("data.frame"));
UNPROTECT(3);
return result;
}
/*
* create an R vector of a given type and size based on pg output function oid
*/
static SEXP
get_r_vector(Oid typtype, int numels)
{
SEXP result;
switch (typtype)
{
case OIDOID:
case INT2OID:
case INT4OID:
/* 2 and 4 byte integer pgsql datatype => use R INTEGER */
PROTECT(result = NEW_INTEGER(numels));
break;
case INT8OID:
case FLOAT4OID:
case FLOAT8OID:
case CASHOID:
case NUMERICOID:
/*
* Other numeric types => use R REAL
* Note pgsql int8 is mapped to R REAL
* because R INTEGER is only 4 byte
*/
PROTECT(result = NEW_NUMERIC(numels));
break;
case BOOLOID:
PROTECT(result = NEW_LOGICAL(numels));
break;
case BYTEAOID:
PROTECT(result = NEW_RAW(numels));
break;
default:
/* Everything else is defaulted to string */
PROTECT(result = NEW_CHARACTER(numels));
}
UNPROTECT(1);
return result;
}
/*
* given a single non-array pg value, convert to its R value representation
*/
static void
pg_get_one_r(char *value, Oid typtype, SEXP *obj, int elnum)
{
switch (typtype)
{
case OIDOID:
case INT2OID:
case INT4OID:
/* 2 and 4 byte integer pgsql datatype => use R INTEGER */
if (value)
INTEGER_DATA(*obj)[elnum] = atoi(value);
else
INTEGER_DATA(*obj)[elnum] = NA_INTEGER;
break;
case INT8OID:
case FLOAT4OID:
case FLOAT8OID:
case CASHOID:
case NUMERICOID:
/*
* Other numeric types => use R REAL
* Note pgsql int8 is mapped to R REAL
* because R INTEGER is only 4 byte
*/
if (value)
NUMERIC_DATA(*obj)[elnum] = atof(value);
else
NUMERIC_DATA(*obj)[elnum] = NA_REAL;
break;
case BOOLOID:
if (value)
LOGICAL_DATA(*obj)[elnum] = ((*value == 't') ? 1 : 0);
else
LOGICAL_DATA(*obj)[elnum] = NA_LOGICAL;
break;
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);
}
}
/*
* given an R value, convert to its pg representation
*/
Datum
r_get_pg(SEXP rval, plr_function *function, FunctionCallInfo fcinfo)
{
bool isnull = false;
Datum result;
if (function->result_typid != BYTEAOID &&
(TYPEOF(rval) == CLOSXP ||
TYPEOF(rval) == PROMSXP ||
TYPEOF(rval) == LANGSXP ||
TYPEOF(rval) == ENVSXP))
ereport(ERROR,
(errcode(ERRCODE_DATA_EXCEPTION),
errmsg("incorrect function return type"),
errdetail("R return value type cannot be mapped to PostgreSQL return type."),
errhint("Try BYTEA as the PostgreSQL return type.")));
if (CALLED_AS_TRIGGER(fcinfo))
result = get_trigger_tuple(rval, function, fcinfo, &isnull);
else if (function->result_istuple || fcinfo->flinfo->fn_retset)
result = get_tuplestore(rval, function, fcinfo, &isnull);
else
{
/* short circuit if return value is Null */
if (rval == R_NilValue || isNull(rval)) /* probably redundant */
{
fcinfo->isnull = true;
return (Datum) 0;
}
if (function->result_elem == 0)
result = get_scalar_datum(rval, function->result_typid, function->result_in_func, &isnull);
else
result = get_array_datum(rval, function, 0, &isnull);
}
if (isnull)
fcinfo->isnull = true;
return result;
}
/*
* Similar to r_get_pg, given an R value, convert to its pg representation
* Other than scalar, currently only prepared to be used with simple 1D vector
*/
Datum
get_datum(SEXP rval, Oid typid, Oid typelem, FmgrInfo in_func, bool *isnull)
{
Datum result;
/* short circuit if return value is Null */
if (rval == R_NilValue || isNull(rval)) /* probably redundant */
{
*isnull = true;
return (Datum) 0;
}
if (typelem == InvalidOid)
result = get_scalar_datum(rval, typid, in_func, isnull);
else
result = get_simple_array_datum(rval, typelem, isnull);
return result;
}
static Datum
get_trigger_tuple(SEXP rval, plr_function *function, FunctionCallInfo fcinfo, bool *isnull)
{
TriggerData *trigdata = (TriggerData *) fcinfo->context;
TupleDesc tupdesc = trigdata->tg_relation->rd_att;
AttInMetadata *attinmeta;
MemoryContext fn_mcxt;
MemoryContext oldcontext;
int nc;
int nr;
char **values;
HeapTuple tuple = NULL;
int i, j;
int nc_dropped = 0;
int df_colnum = 0;
SEXP result;
SEXP dfcol;
/* short circuit statement level trigger which always returns NULL */
if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
{
/* special for triggers, don't set isnull flag */
*isnull = false;
return (Datum) 0;
}
/* short circuit if return value is Null */
if (rval == R_NilValue || isNull(rval)) /* probably redundant */
{
/* special for triggers, don't set isnull flag */
*isnull = false;
return (Datum) 0;
}
if (isFrame(rval))
nc = length(rval);
else if (isMatrix(rval))
nc = ncols(rval);
else
nc = 1;
PROTECT(dfcol = VECTOR_ELT(rval, 0));
nr = length(dfcol);
UNPROTECT(1);
if (nr != 1)
ereport(ERROR,
(errcode(ERRCODE_DATA_EXCEPTION),
errmsg("incorrect function return type"),
errdetail("function return value cannot have more " \
"than one row")));
/*
* Count number of dropped attributes so we can add them back to
* the return tuple
*/
for (j = 0; j < nc; j++)
{
if (tupdesc->attrs[j]->attisdropped)
nc_dropped++;
}
/*
* Check to make sure we have the same number of columns
* to return as there are attributes in the return tuple.
* Note that we have to account for the number of dropped
* columns.
*
* Note we will attempt to coerce the R values into whatever
* the return attribute type is and depend on the "in"
* function to complain if needed.
*/
if (nc + nc_dropped != tupdesc->natts)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("returned tuple structure does not match table " \
"of trigger event")));
fn_mcxt = fcinfo->flinfo->fn_mcxt;
oldcontext = MemoryContextSwitchTo(fn_mcxt);
attinmeta = TupleDescGetAttInMetadata(tupdesc);
/* coerce columns to character in advance */
PROTECT(result = NEW_LIST(nc));
for (j = 0; j < nc; j++)
{
PROTECT(dfcol = VECTOR_ELT(rval, j));
if(!isFactor(dfcol))
{
SEXP obj;
PROTECT(obj = coerce_to_char(dfcol));
SET_VECTOR_ELT(result, j, obj);
UNPROTECT(1);
}
else
{
SEXP t;
for (t = ATTRIB(dfcol); t != R_NilValue; t = CDR(t))
{
if(TAG(t) == R_LevelsSymbol)
{
PROTECT(SETCAR(t, coerce_to_char(CAR(t))));
UNPROTECT(1);
break;
}
}
SET_VECTOR_ELT(result, j, dfcol);
}
UNPROTECT(1);
}
values = (char **) palloc((nc + nc_dropped) * sizeof(char *));
for(i = 0; i < nr; i++)
{
for (j = 0; j < nc + nc_dropped; j++)
{
/* insert NULL for dropped attributes */
if (tupdesc->attrs[j]->attisdropped)
values[j] = NULL;
else
{
PROTECT(dfcol = VECTOR_ELT(result, df_colnum));
if(isFactor(dfcol))
{
SEXP t;
for (t = ATTRIB(dfcol); t != R_NilValue; t = CDR(t))
{
if(TAG(t) == R_LevelsSymbol)
{
SEXP obj;
int idx = INTEGER(dfcol)[i] - 1;
PROTECT(obj = CAR(t));
values[j] = pstrdup(CHAR(STRING_ELT(obj, idx)));
UNPROTECT(1);
break;
}
}
}
else
{
if (STRING_ELT(dfcol, 0) != NA_STRING)
values[j] = pstrdup(CHAR(STRING_ELT(dfcol, i)));
else
values[j] = NULL;
}
UNPROTECT(1);
df_colnum++;
}
}
/* construct the tuple */
tuple = BuildTupleFromCStrings(attinmeta, values);
for (j = 0; j < nc; j++)
if (values[j] != NULL)
pfree(values[j]);
}
UNPROTECT(1);
MemoryContextSwitchTo(oldcontext);
if (tuple)
{
*isnull = false;
return PointerGetDatum(tuple);
}
else
{
/* special for triggers, don't set isnull flag */
*isnull = false;
return (Datum) 0;
}
}
static Datum
get_tuplestore(SEXP rval, plr_function *function, FunctionCallInfo fcinfo, bool *isnull)
{
bool retset = fcinfo->flinfo->fn_retset;
ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
TupleDesc tupdesc;
AttInMetadata *attinmeta;
MemoryContext per_query_ctx;
MemoryContext oldcontext;
int nc;
/* check to see if caller supports us returning a tuplestore */
if (!rsinfo || !(rsinfo->allowedModes & SFRM_Materialize))
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("materialize mode required, but it is not "
"allowed in this context")));
if (isFrame(rval))
nc = length(rval);
else if (isList(rval) || isNewList(rval))
nc = length(rval);
else if (isMatrix(rval))
nc = ncols(rval);
else
nc = 1;
per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
oldcontext = MemoryContextSwitchTo(per_query_ctx);
/* get the requested return tuple description */
tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
/*
* Check to make sure we have the same number of columns
* to return as there are attributes in the return tuple.
*
* Note we will attempt to coerce the R values into whatever
* the return attribute type is and depend on the "in"
* function to complain if needed.
*/
if (nc != tupdesc->natts)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("query-specified return tuple and "
"function returned data.frame are not compatible")));
attinmeta = TupleDescGetAttInMetadata(tupdesc);
/* OK, go to work */
rsinfo->returnMode = SFRM_Materialize;
if (isFrame(rval))
rsinfo->setResult = get_frame_tuplestore(rval, function, attinmeta, per_query_ctx, retset);
else if (isList(rval) || isNewList(rval))
rsinfo->setResult = get_frame_tuplestore(rval, function, attinmeta, per_query_ctx, retset);
else if (isMatrix(rval))
rsinfo->setResult = get_matrix_tuplestore(rval, function, attinmeta, per_query_ctx, retset);
else
rsinfo->setResult = get_generic_tuplestore(rval, function, attinmeta, per_query_ctx, retset);
/*
* SFRM_Materialize mode expects us to return a NULL Datum. The actual
* tuples are in our tuplestore and passed back through
* rsinfo->setResult. rsinfo->setDesc is set to the tuple description
* that we actually used to build our tuples with, so the caller can
* verify we did what it was expecting.
*/
rsinfo->setDesc = tupdesc;
MemoryContextSwitchTo(oldcontext);
*isnull = true;
return (Datum) 0;
}