forked from knu/postgresql-plruby
-
Notifications
You must be signed in to change notification settings - Fork 4
/
plpl.c
1514 lines (1394 loc) · 43.1 KB
/
plpl.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
#include "plruby.h"
static VALUE pl_ePLruby, pl_mPLtemp;
static VALUE pl_mPL, pl_cPLPlan, pl_eCatch;
static ID id_thr;
static VALUE pl_SPI_exec _((int, VALUE *, VALUE));
#ifndef HAVE_RB_HASH_DELETE
static ID id_delete;
#define rb_hash_delete(a, b) rb_funcall((a), id_delete, 1, (b))
#endif
static char *names =
"SELECT a.attname FROM pg_class c, pg_attribute a, pg_namespace n"
" WHERE c.relname = '%s' AND a.attnum > 0 AND NOT a.attisdropped AND a.attrelid = c.oid"
" AND c.relnamespace = n.oid AND n.nspname = '%s'"
" ORDER BY a.attnum";
static VALUE
pl_column_name(VALUE obj, VALUE table)
{
VALUE *query, res;
char *tmp;
char *nsp, *tbl, *c;
if (TYPE(table) != T_STRING || !RSTRING_PTR(table)) {
rb_raise(pl_ePLruby, "expected a String");
}
tmp = ALLOCA_N(char, strlen(names) + RSTRING_LEN(table) + 1);
nsp = ALLOCA_N(char, RSTRING_LEN(table) + 1);
tbl = ALLOCA_N(char, RSTRING_LEN(table) + 1);
strcpy(nsp, RSTRING_PTR(table));
if ((c = strchr(nsp, '.')) != NULL) {
*c = 0;
strcpy(tbl, c + 1);
}
else {
strcpy(tbl, nsp);
strcpy(nsp, "public");
}
sprintf(tmp, names, tbl, nsp);
query = ALLOCA_N(VALUE, 3);
MEMZERO(query, VALUE, 3);
query[0] = rb_str_new2(tmp);
query[1] = Qnil;
query[2] = rb_str_new2("value");
res = pl_SPI_exec(3, query, pl_mPL);
rb_funcall2(res, rb_intern("flatten!"), 0, 0);
return res;
}
static char *types =
"SELECT t.typname FROM pg_class c, pg_attribute a, pg_type t, pg_namespace n"
" WHERE c.relname = '%s' and a.attnum > 0 AND NOT a.attisdropped"
" AND a.attrelid = c.oid and a.atttypid = t.oid"
" AND c.relnamespace = n.oid AND n.nspname = '%s'"
" ORDER BY a.attnum";
static VALUE
pl_column_type(VALUE obj, VALUE table)
{
VALUE *query, res;
char *tmp;
char *nsp, *tbl, *c;
if (TYPE(table) != T_STRING || !RSTRING_PTR(table)) {
rb_raise(pl_ePLruby, "expected a String");
}
tmp = ALLOCA_N(char, strlen(types) + RSTRING_LEN(table) + 1);
nsp = ALLOCA_N(char, RSTRING_LEN(table) + 1);
tbl = ALLOCA_N(char, RSTRING_LEN(table) + 1);
strcpy(nsp, RSTRING_PTR(table));
if ((c = strchr(nsp, '.')) != NULL) {
*c = 0;
strcpy(tbl, c + 1);
}
else {
strcpy(tbl, nsp);
strcpy(nsp, "public");
}
sprintf(tmp, types, tbl, nsp);
query = ALLOCA_N(VALUE, 3);
MEMZERO(query, VALUE, 3);
query[0] = rb_str_new2(tmp);
query[1] = Qnil;
query[2] = rb_str_new2("value");
res = pl_SPI_exec(3, query, pl_mPL);
rb_funcall2(res, rb_intern("flatten!"), 0, 0);
return res;
}
struct pl_tuple {
MemoryContext cxt;
AttInMetadata *att;
pl_proc_desc *pro;
TupleDesc dsc;
Tuplestorestate *out;
PG_FUNCTION_ARGS;
};
extern int work_mem;
static void pl_thr_mark(struct pl_tuple *tpl) {}
#define GetTuple(tmp_, tpl_) do { \
if (TYPE(tmp_) != T_DATA || \
RDATA(tmp_)->dmark != (RUBY_DATA_FUNC)pl_thr_mark) { \
rb_raise(pl_ePLruby, "invalid thread local variable"); \
} \
Data_Get_Struct(tmp_, struct pl_tuple, tpl_); \
} while(0)
static VALUE
pl_query_name(VALUE obj)
{
VALUE res, tmp;
struct pl_tuple *tpl;
char * attname;
int i;
tmp = rb_thread_local_aref(rb_thread_current(), id_thr);
if (NIL_P(tmp)) {
return Qnil;
}
GetTuple(tmp, tpl);
if (!tpl->dsc) {
return Qnil;
}
res = rb_ary_new2(tpl->dsc->natts);
for (i = 0; i < tpl->dsc->natts; i++) {
Form_pg_attribute attr = TupleDescAttr(tpl->dsc, i);
if (attr->attisdropped) {
attname = "";
}
else {
attname = NameStr(attr->attname);
}
rb_ary_push(res, rb_tainted_str_new2(attname));
}
return res;
}
static VALUE
pl_query_type(VALUE obj)
{
struct pl_tuple *tpl;
VALUE res, tmp;
char * attname;
HeapTuple typeTup;
Form_pg_type fpgt;
int i;
tmp = rb_thread_local_aref(rb_thread_current(), id_thr);
if (NIL_P(tmp)) {
return Qnil;
}
GetTuple(tmp, tpl);
if (!tpl->dsc) {
PLRUBY_BEGIN(1);
typeTup = SearchSysCache(TYPEOID, OidGD(tpl->pro->result_oid),0,0,0);
PLRUBY_END;
if (!HeapTupleIsValid(typeTup)) {
rb_raise(pl_ePLruby, "Cache lookup for result type %d failed",
tpl->pro->result_oid);
}
fpgt = (Form_pg_type) GETSTRUCT(typeTup);
res = rb_tainted_str_new2(NameStr(fpgt->typname));
ReleaseSysCache(typeTup);
return res;
}
res = rb_ary_new2(tpl->dsc->natts);
for (i = 0; i < tpl->dsc->natts; i++) {
Form_pg_attribute attr = TupleDescAttr(tpl->dsc, i);
if (attr->attisdropped)
continue;
PLRUBY_BEGIN(1);
attname = NameStr(attr->attname);
typeTup = SearchSysCache(TYPEOID, OidGD(attr->atttypid),
0, 0, 0);
PLRUBY_END;
if (!HeapTupleIsValid(typeTup)) {
rb_raise(pl_ePLruby, "Cache lookup for attribute '%s' type %ld failed",
attname, OidGD(attr->atttypid));
}
fpgt = (Form_pg_type) GETSTRUCT(typeTup);
rb_ary_push(res, rb_tainted_str_new2(NameStr(fpgt->typname)));
ReleaseSysCache(typeTup);
}
return res;
}
static VALUE
pl_query_description(VALUE obj)
{
VALUE name, types, res;
VALUE tt_virg, tt_blc;
int i;
tt_virg = rb_str_new2(", ");
tt_blc = rb_str_new2(" ");
name = pl_query_name(obj);
if (NIL_P(name)) {
return Qnil;
}
types = pl_query_type(obj);
if (TYPE(name) != T_ARRAY || TYPE(types) != T_ARRAY ||
RARRAY_LEN(name) != RARRAY_LEN(types)) {
rb_raise(pl_ePLruby, "unknown error");
}
res = rb_tainted_str_new2("");
for (i = 0; i < RARRAY_LEN(name); ++i) {
rb_str_concat(res, RARRAY_PTR(name)[i]);
rb_str_concat(res, tt_blc);
rb_str_concat(res, RARRAY_PTR(types)[i]);
if (i != (RARRAY_LEN(name) - 1)) {
rb_str_concat(res, tt_virg);
}
}
return res;
}
static VALUE
pl_query_lgth(VALUE obj)
{
VALUE tmp;
struct pl_tuple *tpl;
tmp = rb_thread_local_aref(rb_thread_current(), id_thr);
if (NIL_P(tmp)) {
return Qnil;
}
GetTuple(tmp, tpl);
if (!tpl->dsc) {
return Qnil;
}
return INT2NUM(tpl->dsc->natts);
}
static VALUE
pl_args_type(VALUE obj)
{
struct pl_tuple *tpl;
VALUE res, tmp;
HeapTuple typeTup;
Form_pg_type fpgt;
int i;
tmp = rb_thread_local_aref(rb_thread_current(), id_thr);
if (NIL_P(tmp)) {
return Qnil;
}
GetTuple(tmp, tpl);
res = rb_ary_new2(tpl->pro->nargs);
for (i = 0; i < tpl->pro->nargs; i++) {
PLRUBY_BEGIN(1);
typeTup = SearchSysCache(TYPEOID, OidGD(tpl->pro->arg_type[i]),0,0,0);
PLRUBY_END;
if (!HeapTupleIsValid(typeTup)) {
rb_raise(pl_ePLruby, "Cache lookup for type %ld failed",
OidGD(tpl->pro->arg_type[i]));
}
fpgt = (Form_pg_type) GETSTRUCT(typeTup);
rb_ary_push(res, rb_tainted_str_new2(NameStr(fpgt->typname)));
ReleaseSysCache(typeTup);
}
return res;
}
static VALUE PLcontext;
struct PL_node
{
NodeTag type;
VALUE value;
};
static VALUE
pl_context_get(VALUE obj)
{
struct pl_tuple *tpl;
VALUE tmp;
tmp = rb_thread_local_aref(rb_thread_current(), id_thr);
if (NIL_P(tmp)) {
return Qnil;
}
GetTuple(tmp, tpl);
if (!tpl->fcinfo || !tpl->fcinfo->context ||
!IsA(tpl->fcinfo->context, Invalid)) {
return Qnil;
}
return ((struct PL_node *)tpl->fcinfo->context)->value;
}
static VALUE
pl_context_set(VALUE obj, VALUE a)
{
struct pl_tuple *tpl;
VALUE tmp;
tmp = rb_thread_local_aref(rb_thread_current(), id_thr);
GetTuple(tmp, tpl);
if (tpl->fcinfo && tpl->fcinfo->context) {
if (!IsA(tpl->fcinfo->context, Invalid)) {
rb_raise(pl_ePLruby, "trying to change a valid context");
}
rb_hash_delete(PLcontext, ((struct PL_node *)tpl->fcinfo->context)->value);
}
else {
if (!tpl->fcinfo) {
rb_raise(pl_ePLruby, "no function info");
}
tpl->fcinfo->context = newNode(sizeof(struct PL_node), T_Invalid);
}
((struct PL_node *)tpl->fcinfo->context)->value = a;
rb_hash_aset(PLcontext, a, Qnil);
return a;
}
static void
pl_context_remove()
{
struct pl_tuple *tpl;
VALUE tmp;
tmp = rb_thread_local_aref(rb_thread_current(), id_thr);
GetTuple(tmp, tpl);
if (tpl->fcinfo && tpl->fcinfo->context) {
rb_hash_delete(PLcontext, ((struct PL_node *)tpl->fcinfo->context)->value);
pfree(tpl->fcinfo->context);
}
}
static VALUE
pl_tuple_s_new(PG_FUNCTION_ARGS, pl_proc_desc *prodesc)
{
VALUE res;
ReturnSetInfo *rsi;
struct pl_tuple *tpl;
if (!fcinfo || !fcinfo->resultinfo) {
rb_raise(pl_ePLruby, "no description given");
}
rsi = (ReturnSetInfo *)fcinfo->resultinfo;
if ((rsi->allowedModes & SFRM_Materialize) == 0 || !rsi->expectedDesc) {
rb_raise(pl_ePLruby, "context don't accept set");
}
res = rb_thread_local_aref(rb_thread_current(), id_thr);
if (NIL_P(res)) {
res = Data_Make_Struct(rb_cData, struct pl_tuple, pl_thr_mark, free, tpl);
}
GetTuple(res, tpl);
tpl->cxt = rsi->econtext->ecxt_per_query_memory;
tpl->dsc = rsi->expectedDesc;
tpl->att = TupleDescGetAttInMetadata(rsi->expectedDesc);
tpl->pro = prodesc;
rb_thread_local_aset(rb_thread_current(), id_thr, res);
return res;
}
#ifdef PLRUBY_ENABLE_CONVERSION
static ID id_from_datum;
static ID id_to_datum;
struct datum_value {
Datum d;
Oid typoid;
int typlen;
};
static void pl_conv_mark() {}
Oid plruby_datum_oid(VALUE obj, int *typlen)
{
struct datum_value *dv;
if (TYPE(obj) != T_DATA ||
RDATA(obj)->dmark != (RUBY_DATA_FUNC)pl_conv_mark) {
rb_raise(pl_ePLruby, "invalid Datum value");
}
Data_Get_Struct(obj, struct datum_value, dv);
if (typlen) *typlen = dv->typlen;
return dv->typoid;
}
VALUE plruby_datum_set(VALUE obj, Datum d)
{
struct datum_value *dv;
if (TYPE(obj) != T_DATA ||
RDATA(obj)->dmark != (RUBY_DATA_FUNC)pl_conv_mark) {
rb_raise(pl_ePLruby, "invalid Datum value");
}
Data_Get_Struct(obj, struct datum_value, dv);
dv->d = d;
return obj;
}
Datum plruby_datum_get(VALUE obj, Oid *typoid)
{
struct datum_value *dv;
if (TYPE(obj) != T_DATA ||
RDATA(obj)->dmark != (RUBY_DATA_FUNC)pl_conv_mark) {
rb_raise(pl_ePLruby, "invalid Datum value");
}
Data_Get_Struct(obj, struct datum_value, dv);
if (typoid) *typoid = dv->typoid;
return dv->d;
}
#endif
Datum
plruby_to_datum(VALUE obj, FmgrInfo *finfo, Oid typoid,
Oid typelem, int typlen)
{
Datum d;
VALUE tmp;
tmp = rb_attr_get(obj, rb_intern("plruby_tuple"));
if (TYPE(tmp) == T_DATA) {
return (Datum)DATA_PTR(tmp);
}
if (typoid == BOOLOID) {
return BoolGD(RTEST(obj));
}
#ifdef PLRUBY_ENABLE_CONVERSION
if (rb_respond_to(obj, id_to_datum)) {
struct datum_value *dv;
VALUE res;
res = Data_Make_Struct(rb_cData, struct datum_value, pl_conv_mark, free, dv);
dv->typoid = typoid;
dv->typlen = typlen;
res = rb_funcall(obj, id_to_datum, 1, res);
if (TYPE(res) == T_DATA &&
RDATA(res)->dmark == (RUBY_DATA_FUNC)pl_conv_mark) {
Data_Get_Struct(res, struct datum_value, dv);
if (dv->typoid == typoid && dv->typlen == typlen && dv->d) {
return dv->d;
}
}
}
#endif
obj = plruby_to_s(obj);
PLRUBY_BEGIN_PROTECT(1);
d = FunctionCall3(finfo, PointerGD(RSTRING_PTR(obj)),
OidGD(typelem), IntGD(typlen));
PLRUBY_END_PROTECT;
return d;
}
Datum
plruby_return_array(VALUE ary, pl_proc_desc *p)
{
VALUE tmp;
int i, total, ndim, *dim, *lbs;
Datum *values;
ArrayType *array;
tmp = rb_Array(ary);
total = 1;
dim = ALLOCA_N(int, MAXDIM);
MEMZERO(dim, int, MAXDIM);
lbs = ALLOCA_N(int, MAXDIM);
MEMZERO(lbs, int, MAXDIM);
i = 0;
while (TYPE(tmp) == T_ARRAY) {
lbs[i] = 1;
dim[i++] = RARRAY_LEN(tmp);
if (i == MAXDIM) {
rb_raise(pl_ePLruby, "too many dimensions -- max %d", MAXDIM);
}
if (RARRAY_LEN(tmp)) {
total *= RARRAY_LEN(tmp);
}
tmp = RARRAY_PTR(tmp)[0];
}
ndim = i;
ary = rb_funcall2(ary, rb_intern("flatten"), 0, 0);
if (RARRAY_LEN(ary) != total) {
#ifdef WARNING
elog(WARNING, "not a regular array");
#else
elog(NOTICE, "not a regular array");
#endif
}
values = (Datum *)palloc(RARRAY_LEN(ary) * sizeof(Datum));
for (i = 0; i < RARRAY_LEN(ary); ++i) {
values[i] = plruby_to_datum(RARRAY_PTR(ary)[i],
&p->result_func,
p->result_oid, p->result_elem,
-1);
}
PLRUBY_BEGIN_PROTECT(1);
array = construct_md_array(values, NULL, ndim, dim, lbs,
p->result_elem, p->result_len,
p->result_val, p->result_align);
PLRUBY_END_PROTECT;
return PointerGD(array);
}
static Datum
return_base_type(VALUE c, pl_proc_desc *prodesc)
{
Datum retval;
if (prodesc->result_is_array) {
retval = plruby_return_array(c, prodesc);
}
else {
retval = plruby_to_datum(c, &prodesc->result_func,
prodesc->result_oid,
prodesc->result_elem,
-1);
}
return retval;
}
struct each_st {
VALUE res;
TupleDesc tup;
};
static HeapTuple
pl_tuple_heap(VALUE c, VALUE tuple)
{
HeapTuple retval;
struct pl_tuple *tpl;
TupleDesc tupdesc = 0;
Datum *dvalues;
Oid typid;
bool *nulls;
int i;
GetTuple(tuple, tpl);
if (tpl->att) {
tupdesc = tpl->att->tupdesc;
}
if (!tupdesc) {
rb_raise(pl_ePLruby, "Invalid descriptor");
}
if (TYPE(c) != T_ARRAY) {
if (NIL_P(c) || (TYPE(c) == T_STRING && !RSTRING_LEN(c))) {
c = rb_ary_new2(1);
rb_ary_push(c, rb_str_new2(""));
}
else {
c = rb_Array(c);
}
}
if (TYPE(c) != T_ARRAY || !RARRAY_PTR(c)) {
rb_raise(pl_ePLruby, "expected an Array");
}
if (tupdesc->natts != RARRAY_LEN(c)) {
rb_raise(pl_ePLruby, "Invalid number of columns (got %ld, expected %d)",
RARRAY_LEN(c), tupdesc->natts);
}
dvalues = ALLOCA_N(Datum, RARRAY_LEN(c));
MEMZERO(dvalues, Datum, RARRAY_LEN(c));
nulls = ALLOCA_N(bool, RARRAY_LEN(c));
MEMZERO(nulls, bool, RARRAY_LEN(c));
for (i = 0; i < RARRAY_LEN(c); i++) {
Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
if (NIL_P(RARRAY_PTR(c)[i]) ||
attr->attisdropped) {
dvalues[i] = (Datum)0;
nulls[i] = true;
}
else {
nulls[i] = false;
typid = attr->atttypid;
if (attr->attndims != 0 ||
tpl->att->attinfuncs[i].fn_addr == (PGFunction)array_in) {
pl_proc_desc prodesc;
FmgrInfo func;
HeapTuple hp;
Form_pg_type fpg;
MEMZERO(&prodesc, pl_proc_desc, 1);
PLRUBY_BEGIN(1);
hp = SearchSysCache(TYPEOID, OidGD(typid), 0, 0, 0);
if (!HeapTupleIsValid(hp)) {
rb_raise(pl_ePLruby, "cache lookup failed for type %u",
typid);
}
fpg = (Form_pg_type) GETSTRUCT(hp);
typid = getTypeIOParam(hp);
ReleaseSysCache(hp);
hp = SearchSysCache(TYPEOID, OidGD(typid), 0, 0, 0);
PLRUBY_END;
if (!HeapTupleIsValid(hp)) {
rb_raise(pl_ePLruby, "cache lookup failed for type %u",
typid);
}
fpg = (Form_pg_type) GETSTRUCT(hp);
fmgr_info(fpg->typinput, &func);
prodesc.result_func = func;
prodesc.result_oid = typid;
prodesc.result_elem = typid;
prodesc.result_val = fpg->typbyval;
prodesc.result_len = fpg->typlen;
prodesc.result_align = fpg->typalign;
ReleaseSysCache(hp);
dvalues[i] = plruby_return_array(RARRAY_PTR(c)[i], &prodesc);
}
else {
dvalues[i] = plruby_to_datum(RARRAY_PTR(c)[i],
&tpl->att->attinfuncs[i],
typid,
tpl->att->attioparams[i],
tpl->att->atttypmods[i]);
}
}
}
PLRUBY_BEGIN_PROTECT(1);
retval = heap_form_tuple(tupdesc, dvalues, nulls);
PLRUBY_END_PROTECT;
return retval;
}
static VALUE
pl_tuple_put(VALUE c, VALUE tuple)
{
HeapTuple retval;
MemoryContext oldcxt;
struct pl_tuple *tpl;
GetTuple(tuple, tpl);
retval = pl_tuple_heap(c, tuple);
PLRUBY_BEGIN_PROTECT(1);
oldcxt = MemoryContextSwitchTo(tpl->cxt);
if (!tpl->out) {
tpl->out = tuplestore_begin_heap(true, false, work_mem);
}
tuplestore_puttuple(tpl->out, retval);
MemoryContextSwitchTo(oldcxt);
PLRUBY_END_PROTECT;
return Qnil;
}
static Datum
pl_tuple_datum(VALUE c, VALUE tuple)
{
Datum retval;
HeapTuple tmp;
tmp = pl_tuple_heap(c, tuple);
PLRUBY_BEGIN_PROTECT(1);
retval = TupleGD(tmp);
PLRUBY_END_PROTECT;
return retval;
}
struct pl_arg {
ID id;
int named;
VALUE ary;
};
static void
pl_arg_mark(struct pl_arg *args)
{
rb_gc_mark(args->ary);
}
static VALUE
pl_func(VALUE arg)
{
#if HAVE_RB_BLOCK_CALL
return Qtrue;
#else
struct pl_arg *args;
Data_Get_Struct(arg, struct pl_arg, args);
if (args->named) {
return rb_funcall2(pl_mPLtemp, args->id, RARRAY_LEN(args->ary),
RARRAY_PTR(args->ary));
}
return rb_funcall(pl_mPLtemp, args->id, 1, args->ary);
#endif
}
static VALUE
pl_string(VALUE arg)
{
struct pl_arg *args;
VALUE tmp[2], plan;
Data_Get_Struct(arg, struct pl_arg, args);
tmp[0] = args->ary;
tmp[1] = rb_hash_new();
rb_hash_aset(tmp[1], rb_str_new2("block"), INT2NUM(50));
rb_hash_aset(tmp[1], rb_str_new2("output"), rb_str_new2("value"));
plan = plruby_s_new(2, tmp, pl_cPLPlan);
#if HAVE_RB_BLOCK_CALL
return plan;
#else
rb_funcall2(plan, rb_intern("each"), 0, 0);
return Qnil;
#endif
}
static VALUE
pl_warn(argc, argv, obj)
int argc;
VALUE *argv;
VALUE obj;
{
int level, indice;
VALUE res;
level = NOTICE;
indice = 0;
switch (argc) {
case 2:
indice = 1;
switch (level = NUM2INT(argv[0])) {
#ifdef DEBUG
case DEBUG:
#endif
#ifdef DEBUG1
case DEBUG1:
#endif
#ifdef DEBUG2
case DEBUG2:
#endif
#ifdef DEBUG3
case DEBUG3:
#endif
#ifdef DEBUG4
case DEBUG4:
#endif
#ifdef DEBUG5
case DEBUG5:
#endif
#ifdef NOTICE
case NOTICE:
#endif
#ifdef LOG
#if !defined(DEBUG) || LOG != DEBUG
case LOG:
#endif
#endif
#ifdef NOIND
case NOIND:
#endif
#ifdef WARNING
case WARNING:
#endif
#ifdef WARN
case WARN:
#endif
#ifdef ERROR
case ERROR:
#endif
#ifdef FATAL
case FATAL:
#endif
break;
default:
rb_raise(pl_ePLruby, "invalid level %d", level);
}
case 1:
res = argv[indice];
if (NIL_P(res)) {
return Qnil;
}
res = plruby_to_s(res);
break;
default:
rb_raise(pl_ePLruby, "invalid syntax");
}
PLRUBY_BEGIN_PROTECT(1);
elog(level, "%s", RSTRING_PTR(res));
PLRUBY_END_PROTECT;
return Qnil;
}
static VALUE
pl_quote(obj, mes)
VALUE obj, mes;
{
char *tmp, *cp1, *cp2;
if (TYPE(mes) != T_STRING || !RSTRING_PTR(mes)) {
rb_raise(pl_ePLruby, "quote: string expected");
}
tmp = ALLOCA_N(char, RSTRING_LEN(mes) * 2 + 1);
cp1 = RSTRING_PTR(mes);
cp2 = tmp;
while (*cp1) {
if (*cp1 == '\'')
*cp2++ = '\'';
else {
if (*cp1 == '\\')
*cp2++ = '\\';
}
*cp2++ = *cp1++;
}
*cp2 = '\0';
return rb_tainted_str_new2(tmp);
}
void
plruby_exec_output(VALUE option, int compose, int *result)
{
if (TYPE(option) != T_STRING || RSTRING_PTR(option) == 0 || !result) {
rb_raise(pl_ePLruby, "string expected for optional output");
}
if (strcmp(RSTRING_PTR(option), "array") == 0) {
*result = compose|RET_DESC_ARR;
}
else if (strcmp(RSTRING_PTR(option), "hash") == 0) {
*result = compose|RET_DESC;
}
else if (strcmp(RSTRING_PTR(option), "value") == 0) {
*result = RET_ARRAY;
}
}
static VALUE
pl_SPI_exec(argc, argv, obj)
int argc;
VALUE *argv;
VALUE obj;
{
int spi_rc, count, array;
int i, comp, ntuples;
struct portal_options po;
VALUE a, b, c, result;
HeapTuple *tuples;
TupleDesc tupdesc = NULL;
count = 0;
array = comp = RET_HASH;
if (argc && TYPE(argv[argc - 1]) == T_HASH) {
MEMZERO(&po, struct portal_options, 1);
rb_iterate(rb_each, argv[argc - 1], plruby_i_each, (VALUE)&po);
comp = po.output;
count = po.count;
argc--;
}
switch (rb_scan_args(argc, argv, "12", &a, &b, &c)) {
case 3:
plruby_exec_output(c, RET_HASH, &comp);
/* ... */
case 2:
if (!NIL_P(b)) {
count = NUM2INT(b);
}
}
if (TYPE(a) != T_STRING) {
rb_raise(pl_ePLruby, "exec: first argument must be a string");
}
array = comp;
PLRUBY_BEGIN_PROTECT(1);
spi_rc = SPI_exec(RSTRING_PTR(a), count);
PLRUBY_END_PROTECT;
switch (spi_rc) {
case SPI_OK_UTILITY:
if (SPI_tuptable == NULL) {
SPI_freetuptable(SPI_tuptable);
return Qtrue;
}
break;
case SPI_OK_SELINTO:
case SPI_OK_INSERT:
case SPI_OK_DELETE:
case SPI_OK_UPDATE:
SPI_freetuptable(SPI_tuptable);
return INT2NUM(SPI_processed);
case SPI_OK_SELECT:
#ifdef SPI_OK_INSERT_RETURNING
case SPI_OK_INSERT_RETURNING:
case SPI_OK_DELETE_RETURNING:
case SPI_OK_UPDATE_RETURNING:
#endif
break;
case SPI_ERROR_ARGUMENT:
rb_raise(pl_ePLruby, "SPI_exec() failed - SPI_ERROR_ARGUMENT");
case SPI_ERROR_UNCONNECTED:
rb_raise(pl_ePLruby, "SPI_exec() failed - SPI_ERROR_UNCONNECTED");
case SPI_ERROR_COPY:
rb_raise(pl_ePLruby, "SPI_exec() failed - SPI_ERROR_COPY");
case SPI_ERROR_CURSOR:
rb_raise(pl_ePLruby, "SPI_exec() failed - SPI_ERROR_CURSOR");
case SPI_ERROR_TRANSACTION:
rb_raise(pl_ePLruby, "SPI_exec() failed - SPI_ERROR_TRANSACTION");
case SPI_ERROR_OPUNKNOWN:
rb_raise(pl_ePLruby, "SPI_exec() failed - SPI_ERROR_OPUNKNOWN");
default:
rb_raise(pl_ePLruby, "SPI_exec() failed - unknown RC %d", spi_rc);
}
ntuples = SPI_processed;
if (ntuples <= 0) {
SPI_freetuptable(SPI_tuptable);
if (rb_block_given_p() || count == 1)
return Qfalse;
else
return rb_ary_new2(0);
}
tuples = SPI_tuptable->vals;
tupdesc = SPI_tuptable->tupdesc;
if (rb_block_given_p()) {
if (count == 1) {
if (!(array & RET_DESC)) {
array |= RET_BASIC;
}
plruby_build_tuple(tuples[0], tupdesc, array);
}
else {
for (i = 0; i < ntuples; i++) {
rb_yield(plruby_build_tuple(tuples[i], tupdesc, array));
}
}
result = Qtrue;
}
else {
if (count == 1) {
result = plruby_build_tuple(tuples[0], tupdesc, array);
}
else {
result = rb_ary_new2(ntuples);
for (i = 0; i < ntuples; i++) {
rb_ary_push(result, plruby_build_tuple(tuples[i], tupdesc, array));
}
}
}
SPI_freetuptable(SPI_tuptable);
return result;
}
static VALUE
pl_convert_arg(Datum value, Oid typoid, FmgrInfo *finfo, Oid typelem,
int attlen)
{
VALUE result;
char *outstr;
if (typoid == BOOLOID) {
return DatumGetBool(value)?Qtrue:Qfalse;
}
#ifdef PLRUBY_ENABLE_CONVERSION
{
VALUE vid, klass;
vid = INT2NUM(typoid);
klass = rb_hash_aref(plruby_classes, vid);
if (NIL_P(klass)) {
klass = rb_hash_aref(plruby_conversions, vid);
if (NIL_P(klass)) {
st_insert(RHASH_TBL(plruby_classes), vid, Qfalse);
}
else {
klass = rb_const_get(rb_cObject, NUM2INT(klass));
st_insert(RHASH_TBL(plruby_classes), vid, klass);
}
}
if (RTEST(klass)) {
struct datum_value *dv;
VALUE res;
res = Data_Make_Struct(rb_cData, struct datum_value,
pl_conv_mark, free, dv);
dv->d = value;
dv->typoid = typoid;
dv->typlen = attlen;
res = rb_funcall(klass, id_from_datum, 1, res);
return res;
}
}
#endif
PLRUBY_BEGIN_PROTECT(1);
outstr = DatumGetCString(FunctionCall3(finfo, value, OidGD(typelem),
IntGD(attlen)));
result = rb_tainted_str_new2(outstr);
pfree(outstr);
PLRUBY_END_PROTECT;
return result;
}
static VALUE
create_array(index, ndim, dim, p, prodesc, curr, typoid)
int index, ndim, *dim, curr;
Oid typoid;
char **p;
pl_proc_desc *prodesc;
{
VALUE res, tmp;