-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplruby.c
More file actions
1864 lines (1620 loc) · 53.7 KB
/
Copy pathplruby.c
File metadata and controls
1864 lines (1620 loc) · 53.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**********************************************************************
* plruby.c - Ruby as a procedural language for PostgreSQL
*
* PL/Ruby embeds a Ruby (MRI) interpreter in the PostgreSQL backend and
* runs function/trigger/procedure bodies written in Ruby. Its structure
* follows the sibling PL/php handler; the Zend/PHP embed API is replaced
* with Ruby's C API.
*
* Copyright (c) 2026 ChronicallyJD. Distributed under the MIT License;
* see the LICENSE file at the root of the source tree.
**********************************************************************/
#include "postgres.h"
#include "access/htup_details.h"
#include "access/transam.h"
#include "catalog/pg_language.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "commands/event_trigger.h"
#include "commands/trigger.h"
#include "fmgr.h"
#include "funcapi.h"
#include "lib/stringinfo.h"
#include "nodes/parsenodes.h"
#include "parser/parse_coerce.h"
#if PG_VERSION_NUM >= 130000
#include "tcop/cmdtag.h"
#endif
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
#include "plruby.h"
#include "plruby_io.h"
#include "plruby_spi.h"
PG_MODULE_MAGIC;
/*
* FunctionCallInfo argument access; PG 12 replaced arg[]/argnull[] with a
* NullableDatum args[] array.
*/
#if PG_VERSION_NUM >= 120000
#define PLRUBY_ARG_ISNULL(fcinfo, n) ((fcinfo)->args[n].isnull)
#define PLRUBY_ARG_VALUE(fcinfo, n) ((fcinfo)->args[n].value)
#else
#define PLRUBY_ARG_ISNULL(fcinfo, n) ((fcinfo)->argnull[n])
#define PLRUBY_ARG_VALUE(fcinfo, n) ((fcinfo)->arg[n])
#endif
#define IS_ARGMODE_OUT(mode) ((mode) == PROARGMODE_OUT || \
(mode) == PROARGMODE_TABLE)
typedef enum pl_type
{
PL_TUPLE = 1 << 0,
PL_ARRAY = 1 << 1,
PL_PSEUDO = 1 << 2
} pl_type;
typedef struct plruby_proc_desc
{
char *proname; /* internal (OID-derived) method name */
TransactionId fn_xmin;
CommandId fn_cmin;
pl_type ret_type;
Oid ret_oid;
bool retset;
FmgrInfo result_in_func;
Oid result_typioparam;
int n_total_args;
int n_out_args;
int n_mixed_args;
Oid arg_type[FUNC_MAX_ARGS];
char arg_typtype[FUNC_MAX_ARGS];
char arg_argmode[FUNC_MAX_ARGS];
FmgrInfo arg_out_func[FUNC_MAX_ARGS];
/*
* TRANSFORM FOR TYPE support: the FromSQL function for each argument and
* the ToSQL function for the return value (InvalidOid when the function
* declares no transform for that type). A FromSQL function returns the
* Ruby VALUE as a Datum; a ToSQL function accepts one. The full
* resolved list (transforms/n_transforms, malloc'd) also backs nested
* conversions: composite fields, array elements, and SRF rows.
*/
Oid arg_transform[FUNC_MAX_ARGS];
Oid ret_transform;
plruby_transform_info *transforms;
int n_transforms;
} plruby_proc_desc;
/* Interpreter-wide Ruby objects (see plruby.h) */
VALUE rb_mPLRuby;
VALUE rb_ePLRubyError;
VALUE plruby_recv;
VALUE plruby_proc_cache;
/* Global state */
static bool plruby_first_call = true;
static bool plruby_vm_inited = false;
static char *plruby_start_proc = NULL;
static char *plruby_on_init = NULL;
static bool plruby_session_inited = false;
/*
* Per-function static storage. Maps a function's internal proc name (see
* plruby_compile_function) to a Hash that is exposed to the body as $_SD and
* persists across calls to that function within the session. Counterpart of
* PL/Python's SD; $_SHARED is the session-global GD. Entries are dropped when
* a function is recompiled, so $_SD resets on CREATE OR REPLACE.
*/
static VALUE plruby_sd_table;
/* Forward declarations */
void _PG_init(void);
void plruby_init(void);
static void plruby_init_all(void);
static void plruby_session_init(void);
static void plruby_load_modules(void);
PG_FUNCTION_INFO_V1(plruby_call_handler);
PG_FUNCTION_INFO_V1(plruby_validator);
PG_FUNCTION_INFO_V1(plruby_inline_handler);
static Datum plruby_func_handler(FunctionCallInfo fcinfo, plruby_proc_desc *desc);
static Datum plruby_srf_handler(FunctionCallInfo fcinfo, plruby_proc_desc *desc);
static Datum plruby_trigger_handler(FunctionCallInfo fcinfo, plruby_proc_desc *desc);
static Datum plruby_event_trigger_handler(FunctionCallInfo fcinfo, plruby_proc_desc *desc);
static plruby_proc_desc *plruby_compile_function(Oid fnoid, bool is_trigger,
bool is_event_trigger);
static VALUE plruby_func_build_args(plruby_proc_desc *desc, FunctionCallInfo fcinfo);
static bool is_valid_ruby_identifier(const char *name);
/* ---------------------------------------------------------------------
* Error bridge: Ruby exceptions <-> PostgreSQL errors
* ------------------------------------------------------------------- */
static VALUE
msg_to_s_tramp(VALUE err)
{
return rb_funcall(err, rb_intern("message"), 0);
}
char *
plruby_pop_exception_message(void)
{
VALUE err = rb_errinfo();
char *msg;
int state = 0;
VALUE m;
if (NIL_P(err))
return NULL;
m = rb_protect(msg_to_s_tramp, err, &state);
if (!state && RB_TYPE_P(m, T_STRING))
msg = pnstrdup(RSTRING_PTR(m), RSTRING_LEN(m));
else
msg = pstrdup("unknown Ruby error");
rb_set_errinfo(Qnil);
return msg;
}
/*
* A string-valued instance variable of the pending exception, as a palloc'd
* C string, or NULL. rb_ivar_get cannot raise for a missing ivar.
*/
static char *
plruby_exception_field(VALUE err, const char *ivar)
{
VALUE v = rb_ivar_get(err, rb_intern(ivar));
if (!RB_TYPE_P(v, T_STRING))
return NULL;
return pnstrdup(RSTRING_PTR(v), RSTRING_LEN(v));
}
void
plruby_report_exception(void)
{
VALUE err = rb_errinfo();
char *detail = NULL;
char *hint = NULL;
char *sqlstate = NULL;
char *msg;
if (!NIL_P(err))
{
detail = plruby_exception_field(err, "@detail");
hint = plruby_exception_field(err, "@hint");
sqlstate = plruby_exception_field(err, "@sqlstate");
if (sqlstate != NULL && strlen(sqlstate) != 5)
sqlstate = NULL;
}
msg = plruby_pop_exception_message();
if (msg == NULL)
msg = pstrdup("plruby: unknown error");
ereport(ERROR,
(sqlstate ? errcode(MAKE_SQLSTATE(sqlstate[0], sqlstate[1],
sqlstate[2], sqlstate[3],
sqlstate[4])) : 0,
errmsg("%s", msg),
detail ? errdetail("%s", detail) : 0,
hint ? errhint("%s", hint) : 0));
}
void
plruby_eval_string(const char *source, const char *errctx)
{
int state = 0;
rb_eval_string_protect(source, &state);
if (state)
{
char *msg = plruby_pop_exception_message();
if (msg != NULL)
elog(ERROR, "%s: %s", errctx, msg);
else
elog(ERROR, "%s", errctx);
}
}
struct pcall
{
VALUE recv;
ID mid;
int argc;
VALUE *argv;
};
static VALUE
pcall_tramp(VALUE p)
{
struct pcall *c = (struct pcall *) p;
return rb_funcallv(c->recv, c->mid, c->argc, c->argv);
}
VALUE
plruby_protected_call(VALUE recv, ID mid, int argc, VALUE *argv)
{
int state = 0;
struct pcall c;
VALUE r;
c.recv = recv;
c.mid = mid;
c.argc = argc;
c.argv = argv;
r = rb_protect(pcall_tramp, (VALUE) &c, &state);
if (state)
plruby_report_exception(); /* does not return */
return r;
}
/* Remove a top-level method previously defined for a temp/inline body. */
static void
plruby_remove_method(const char *name)
{
char buf[192];
int state = 0;
snprintf(buf, sizeof(buf),
"PLRuby::PROCS.delete('%s'); "
"Object.send(:remove_method, :%s) rescue nil", name, name);
rb_eval_string_protect(buf, &state);
if (state)
rb_set_errinfo(Qnil);
}
/* ---------------------------------------------------------------------
* Module init and interpreter startup
* ------------------------------------------------------------------- */
void
_PG_init(void)
{
DefineCustomStringVariable("plruby.on_init",
"Ruby source to evaluate when the interpreter "
"is first initialized in a session.",
"Runs before plruby_modules and plruby.start_proc, "
"at the top level. The counterpart of "
"plperl.on_init.",
&plruby_on_init,
NULL,
PGC_SUSET, 0,
NULL, NULL, NULL);
DefineCustomStringVariable("plruby.start_proc",
"PL/Ruby function to call when the interpreter "
"is first initialized in a session.",
NULL,
&plruby_start_proc,
NULL,
PGC_SUSET, 0,
NULL, NULL, NULL);
#if PG_VERSION_NUM >= 150000
MarkGUCPrefixReserved("plruby");
#else
EmitWarningsOnPlaceholders("plruby");
#endif
}
static void
plruby_init_all(void)
{
if (plruby_first_call)
plruby_init();
}
void
plruby_init(void)
{
if (!plruby_first_call)
return;
if (!plruby_vm_inited)
{
/*
* ruby_init() alone leaves the interpreter only partially set up: the
* builtin prelude (RUBY_DESCRIPTION and Ruby-level core methods such as
* Integer#odd?, Kernel#class, require, ...) is loaded by the normal
* startup path, ruby_options(). We run it with a no-op "-e ;" program
* (which is parsed but never executed, since we do not call
* ruby_run_node).
*
* RubyGems stays enabled: on Ruby 3.4+ much of the traditional
* standard library (csv, bigdecimal, base64, ...) ships as bundled
* gems that plain require cannot see without it. did_you_mean and
* error_highlight are disabled so error messages stay deterministic
* (no suggestion lines appended to NameError/NoMethodError).
*/
static char *ruby_argv[] = {
(char *) "plruby",
(char *) "--disable=did_you_mean,error_highlight",
(char *) "-e", (char *) ";"
};
int ruby_argc = lengthof(ruby_argv);
char **argv_p = ruby_argv;
ruby_sysinit(&ruby_argc, &argv_p);
{
RUBY_INIT_STACK;
ruby_init();
ruby_options(ruby_argc, argv_p);
}
plruby_vm_inited = true;
}
plruby_eval_string("module PLRuby; PROCS = {};"
" class Error < StandardError;"
" attr_reader :sqlstate, :detail, :hint; end; end",
"plruby: interpreter init");
rb_mPLRuby = rb_const_get(rb_cObject, rb_intern("PLRuby"));
rb_ePLRubyError = rb_const_get(rb_mPLRuby, rb_intern("Error"));
rb_gc_register_address(&rb_mPLRuby);
rb_gc_register_address(&rb_ePLRubyError);
/*
* Use the top-level "main" object as the receiver for compiled methods
* (which are private methods on Object). Besides being the natural self
* for top-level code, its #inspect is the stable string "main", so
* NoMethodError/NameError messages are deterministic rather than embedding
* a per-backend object address.
*/
plruby_recv = rb_eval_string("self");
rb_gc_register_address(&plruby_recv);
plruby_proc_cache = rb_hash_new();
rb_gc_register_address(&plruby_proc_cache);
plruby_sd_table = rb_hash_new();
rb_gc_register_address(&plruby_sd_table);
rb_gv_set("$_SD", rb_hash_new()); /* placeholder until a body binds one */
rb_gc_register_address(¤t_srf_binding);
plruby_spi_init();
plruby_first_call = false;
}
/* ---------------------------------------------------------------------
* Session initialization: modules + start_proc
* ------------------------------------------------------------------- */
/*
* plruby_load_modules
* If a visible table named plruby_modules(modname, modseq, modsrc) exists,
* evaluate each row's Ruby source at the top level (ordered by
* modname, modseq) so any methods/classes it defines become available to
* every PL/Ruby function in the session. Must run with SPI connected.
*/
static void
plruby_load_modules(void)
{
uint64 i;
int ret;
ret = SPI_execute("SELECT 1 FROM pg_class "
"WHERE relname = 'plruby_modules' "
"AND relkind IN ('r', 'p') "
"AND pg_table_is_visible(oid)", true, 1);
if (ret != SPI_OK_SELECT || SPI_processed == 0)
return;
ret = SPI_execute("SELECT modsrc FROM plruby_modules "
"ORDER BY modname, modseq", true, 0);
if (ret != SPI_OK_SELECT)
return;
for (i = 0; i < SPI_processed; i++)
{
char *modsrc = SPI_getvalue(SPI_tuptable->vals[i],
SPI_tuptable->tupdesc, 1);
int state = 0;
if (modsrc == NULL)
continue;
rb_eval_string_protect(modsrc, &state);
pfree(modsrc);
if (state)
{
char *msg = plruby_pop_exception_message();
if (msg != NULL)
elog(ERROR, "plruby: failed to load module: %s", msg);
else
elog(ERROR, "plruby: failed to load module");
}
}
}
static void
plruby_session_init(void)
{
if (plruby_session_inited)
return;
plruby_session_inited = true;
/*
* plruby.on_init runs first: arbitrary top-level Ruby (requires, helper
* definitions, ...) evaluated once, before modules and start_proc. The
* counterpart of plperl.on_init.
*/
if (plruby_on_init != NULL && plruby_on_init[0] != '\0')
{
int state = 0;
rb_eval_string_protect(plruby_on_init, &state);
if (state)
{
char *msg = plruby_pop_exception_message();
if (msg != NULL)
elog(ERROR, "plruby.on_init failed: %s", msg);
else
elog(ERROR, "plruby.on_init failed");
}
}
plruby_load_modules();
if (plruby_start_proc != NULL && plruby_start_proc[0] != '\0')
{
StringInfoData buf;
int ret;
initStringInfo(&buf);
appendStringInfo(&buf, "SELECT %s()", plruby_start_proc);
ret = SPI_execute(buf.data, false, 0);
if (ret < 0)
elog(ERROR, "plruby: start_proc \"%s\" failed: %s",
plruby_start_proc, SPI_result_code_string(ret));
pfree(buf.data);
}
}
/* ---------------------------------------------------------------------
* Error context: name the running code in the server's CONTEXT line, like
* every other procedural language.
* ------------------------------------------------------------------- */
typedef struct plruby_error_ctx
{
const char *proname; /* real function name, or NULL */
bool inline_block; /* true for a DO block */
} plruby_error_ctx;
static void
plruby_error_callback(void *arg)
{
plruby_error_ctx *ctx = (plruby_error_ctx *) arg;
if (ctx->inline_block)
errcontext("PL/Ruby anonymous code block");
else if (ctx->proname != NULL)
errcontext("PL/Ruby function \"%s\"", ctx->proname);
}
/* ---------------------------------------------------------------------
* Call handler
* ------------------------------------------------------------------- */
/*
* Bind $_SD to this function's private, session-persistent Hash and return the
* previous $_SD so the caller can restore it (needed when a body re-enters
* PL/Ruby via SPI). The hash is keyed by the internal proc name, so it is
* distinct for every function -- and for a function's trigger vs plain form --
* and is dropped when the function is recompiled.
*/
static VALUE
plruby_bind_sd(plruby_proc_desc *desc)
{
VALUE prev = rb_gv_get("$_SD");
VALUE key = rb_str_new_cstr(desc->proname);
VALUE sd = rb_hash_aref(plruby_sd_table, key);
if (NIL_P(sd))
{
sd = rb_hash_new();
rb_hash_aset(plruby_sd_table, key, sd);
}
rb_gv_set("$_SD", sd);
return prev;
}
Datum
plruby_call_handler(PG_FUNCTION_ARGS)
{
Datum retval = (Datum) 0;
bool nonatomic = false;
plruby_proc_desc *desc;
plruby_init_all();
if (fcinfo->context && IsA(fcinfo->context, CallContext))
nonatomic = !((CallContext *) fcinfo->context)->atomic;
if (SPI_connect_ext(nonatomic ? SPI_OPT_NONATOMIC : 0) != SPI_OK_CONNECT)
ereport(ERROR,
(errcode(ERRCODE_CONNECTION_FAILURE),
errmsg("could not connect to SPI manager")));
/* Reset SRF state for this call */
current_fcinfo = NULL;
plruby_session_init();
{
/*
* Scope the function's TRANSFORM FOR TYPE list to this call,
* saving/restoring for nested calls -- including when a nested
* call's error is caught and rescued by the outer body, hence the
* PG_CATCH. Triggers and event triggers do not use transforms.
*/
plruby_transform_info *save_call_trf = plruby_call_transforms;
int save_call_ntrf = plruby_call_ntransforms;
plruby_transform_info *save_arg_trf = plruby_arg_transforms;
int save_arg_ntrf = plruby_arg_ntransforms;
VALUE save_sd = rb_gv_get("$_SD");
ErrorContextCallback ecb;
plruby_error_ctx errctx;
/*
* Add a "CONTEXT: PL/Ruby function ..." line to any error raised while
* this function compiles or runs. The name is resolved now (cheap
* syscache lookup) so it is stable across nested calls.
*/
errctx.proname = get_func_name(fcinfo->flinfo->fn_oid);
errctx.inline_block = false;
ecb.callback = plruby_error_callback;
ecb.arg = (void *) &errctx;
ecb.previous = error_context_stack;
error_context_stack = &ecb;
PG_TRY();
{
if (CALLED_AS_TRIGGER(fcinfo))
{
/*
* A trigger function that declares TRANSFORM FOR TYPE gets
* transformed $_TD rows and 'MODIFY' conversion; without the
* clause the list is empty and nothing changes.
*/
desc = plruby_compile_function(fcinfo->flinfo->fn_oid, true, false);
plruby_call_transforms = desc->transforms;
plruby_call_ntransforms = desc->n_transforms;
plruby_bind_sd(desc);
retval = plruby_trigger_handler(fcinfo, desc);
}
else if (CALLED_AS_EVENT_TRIGGER(fcinfo))
{
desc = plruby_compile_function(fcinfo->flinfo->fn_oid, false, true);
plruby_call_transforms = NULL;
plruby_call_ntransforms = 0;
plruby_bind_sd(desc);
retval = plruby_event_trigger_handler(fcinfo, desc);
}
else
{
desc = plruby_compile_function(fcinfo->flinfo->fn_oid, false, false);
plruby_call_transforms = desc->transforms;
plruby_call_ntransforms = desc->n_transforms;
plruby_bind_sd(desc);
if (desc->retset)
retval = plruby_srf_handler(fcinfo, desc);
else
retval = plruby_func_handler(fcinfo, desc);
}
}
PG_CATCH();
{
error_context_stack = ecb.previous;
plruby_call_transforms = save_call_trf;
plruby_call_ntransforms = save_call_ntrf;
plruby_arg_transforms = save_arg_trf;
plruby_arg_ntransforms = save_arg_ntrf;
rb_gv_set("$_SD", save_sd);
PG_RE_THROW();
}
PG_END_TRY();
error_context_stack = ecb.previous;
plruby_call_transforms = save_call_trf;
plruby_call_ntransforms = save_call_ntrf;
plruby_arg_transforms = save_arg_trf;
plruby_arg_ntransforms = save_arg_ntrf;
rb_gv_set("$_SD", save_sd);
}
return retval;
}
/* ---------------------------------------------------------------------
* Regular function handler
* ------------------------------------------------------------------- */
static Datum
plruby_func_handler(FunctionCallInfo fcinfo, plruby_proc_desc *desc)
{
VALUE args;
VALUE result;
VALUE params[2];
Datum retval = (Datum) 0;
char *retvalbuffer = NULL;
Assert(!desc->retset);
args = plruby_func_build_args(desc, fcinfo);
params[0] = args;
params[1] = INT2NUM(desc->n_total_args);
result = plruby_protected_call(plruby_recv, rb_intern(desc->proname),
2, params);
/* Basic datatype checks */
if ((desc->ret_type & PL_ARRAY) && !RB_TYPE_P(result, T_ARRAY))
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("function declared to return array must return an array")));
if ((desc->ret_type & PL_TUPLE) &&
!RB_TYPE_P(result, T_ARRAY) && !RB_TYPE_P(result, T_HASH))
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("function declared to return tuple must return an array or hash")));
if (SPI_finish() != SPI_OK_FINISH)
ereport(ERROR,
(errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
errmsg("could not disconnect from SPI manager")));
/* Refresh I/O info for pseudo return types resolved at call time */
if (desc->ret_type & PL_PSEUDO)
{
HeapTuple retTypeTup;
Form_pg_type retTypeStruct;
retTypeTup = SearchSysCache1(TYPEOID,
ObjectIdGetDatum(get_fn_expr_rettype(fcinfo->flinfo)));
retTypeStruct = (Form_pg_type) GETSTRUCT(retTypeTup);
fmgr_info_cxt(retTypeStruct->typinput, &(desc->result_in_func),
TopMemoryContext);
desc->result_typioparam = retTypeStruct->typelem;
ReleaseSysCache(retTypeTup);
}
/* VOID (and procedures called via CALL) ignore the body's value */
if (desc->ret_oid == VOIDOID)
{
fcinfo->isnull = true;
return (Datum) 0;
}
/* A TRANSFORM FOR TYPE return value converts through its ToSQL function */
if (OidIsValid(desc->ret_transform) && !NIL_P(result))
{
fcinfo->isnull = false;
return OidFunctionCall1(desc->ret_transform, (Datum) result);
}
switch (TYPE(result))
{
case T_NIL:
fcinfo->isnull = true;
break;
case T_TRUE:
case T_FALSE:
case T_FIXNUM:
case T_BIGNUM:
case T_FLOAT:
retvalbuffer = plruby_value_to_cstring(result, false, false);
break;
case T_STRING:
/*
* bytea takes the String's raw bytes (NUL-safe) via the datum
* path; every other scalar keeps the text-input path below.
*/
if (desc->ret_oid == BYTEAOID)
{
bool isnull;
Datum d = plruby_datum_from_value(result, desc->ret_oid,
(int32) -1, &isnull);
if (isnull)
{
fcinfo->isnull = true;
return (Datum) 0;
}
return d;
}
retvalbuffer = plruby_value_to_cstring(result, false, false);
break;
case T_ARRAY:
if (desc->ret_type & PL_ARRAY)
{
Oid elemtype = get_element_type(desc->ret_oid);
/*
* Array of composite (or of a transformed type, e.g. jsonb[],
* or of bytea, whose elements are raw bytes): build the array
* datum directly so each element is assembled recursively /
* through its ToSQL function. Scalar arrays keep the
* (multidimensional-capable) text path below.
*/
if (OidIsValid(elemtype) &&
(type_is_rowtype(elemtype) ||
elemtype == BYTEAOID ||
OidIsValid(plruby_transform_tosql(elemtype))))
{
bool isnull;
Datum d = plruby_datum_from_value(result, desc->ret_oid,
(int32) -1, &isnull);
if (isnull)
{
fcinfo->isnull = true;
return (Datum) 0;
}
return d;
}
retvalbuffer = plruby_array_to_pg(result);
}
else if (desc->ret_type & PL_TUPLE)
{
TupleDesc td;
HeapTuple tup;
if (desc->ret_oid == RECORDOID)
{
ReturnSetInfo *rs = (ReturnSetInfo *) fcinfo->resultinfo;
if (!rs || !IsA(rs, ReturnSetInfo) || rs->expectedDesc == NULL)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("function returning record called in context "
"that cannot accept type record")));
td = rs->expectedDesc;
tup = plruby_htup_from_value(result, td);
}
else
{
td = lookup_rowtype_tupdesc(desc->ret_oid, (int32) -1);
tup = plruby_htup_from_value(result, td);
ReleaseTupleDesc(td);
}
return HeapTupleGetDatum(tup);
}
else
elog(ERROR, "this plruby function cannot return arrays");
break;
case T_HASH:
if (desc->ret_type & PL_TUPLE)
{
TupleDesc td;
HeapTuple tup;
if (desc->ret_oid == RECORDOID)
{
ReturnSetInfo *rs = (ReturnSetInfo *) fcinfo->resultinfo;
if (!rs || !IsA(rs, ReturnSetInfo) || rs->expectedDesc == NULL)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("function returning record called in context "
"that cannot accept type record")));
td = rs->expectedDesc;
tup = plruby_htup_from_value(result, td);
}
else
{
td = lookup_rowtype_tupdesc(desc->ret_oid, (int32) -1);
tup = plruby_htup_from_value(result, td);
ReleaseTupleDesc(td);
}
return HeapTupleGetDatum(tup);
}
else
elog(ERROR, "this plruby function cannot return a hash");
break;
default:
elog(WARNING, "plruby functions cannot return this Ruby type");
fcinfo->isnull = true;
break;
}
if (!fcinfo->isnull && retvalbuffer != NULL)
{
retval = InputFunctionCall(&desc->result_in_func, retvalbuffer,
desc->result_typioparam, -1);
pfree(retvalbuffer);
}
return retval;
}
/* ---------------------------------------------------------------------
* Handlers to be implemented in later tasks
* ------------------------------------------------------------------- */
static Datum
plruby_srf_handler(FunctionCallInfo fcinfo, plruby_proc_desc *desc)
{
ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
TupleDesc tupdesc;
MemoryContext oldcxt;
VALUE args;
VALUE params[2];
/* Save SRF state so nested set-returning calls compose correctly */
FunctionCallInfo save_fcinfo = current_fcinfo;
TupleDesc save_tupledesc = current_tupledesc;
AttInMetadata *save_attinmeta = current_attinmeta;
MemoryContext save_memcxt = current_memcxt;
Tuplestorestate *save_tuplestore = current_tuplestore;
VALUE save_binding = current_srf_binding;
Assert(desc->retset);
if (!rsi || !IsA(rsi, ReturnSetInfo) ||
(rsi->allowedModes & SFRM_Materialize) == 0 ||
rsi->expectedDesc == NULL)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("set-valued function called in context that "
"cannot accept a set")));
get_call_result_type(fcinfo, NULL, &tupdesc);
if (tupdesc == NULL)
tupdesc = rsi->expectedDesc;
if (tupdesc == NULL)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot determine result tuple type for PL/Ruby set function")));
current_fcinfo = fcinfo;
current_tuplestore = NULL;
current_srf_binding = Qnil;
oldcxt = MemoryContextSwitchTo(rsi->econtext->ecxt_per_query_memory);
current_memcxt = AllocSetContextCreate(CurTransactionContext,
"PL/Ruby SRF context",
ALLOCSET_DEFAULT_SIZES);
current_tupledesc = CreateTupleDescCopy(tupdesc);
current_attinmeta = TupleDescGetAttInMetadata(current_tupledesc);
/* The body must call return_next to populate the tuplestore. */
args = plruby_func_build_args(desc, fcinfo);
params[0] = args;
params[1] = INT2NUM(desc->n_total_args);
plruby_protected_call(plruby_recv, rb_intern(desc->proname), 2, params);
if (SPI_finish() != SPI_OK_FINISH)
ereport(ERROR,
(errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
errmsg("could not disconnect from SPI manager")));
rsi->returnMode = SFRM_Materialize;
if (current_tuplestore)
{
rsi->setResult = current_tuplestore;
rsi->setDesc = current_tupledesc;
}
MemoryContextDelete(current_memcxt);
MemoryContextSwitchTo(oldcxt);
/* Restore prior SRF state */
current_fcinfo = save_fcinfo;
current_tupledesc = save_tupledesc;
current_attinmeta = save_attinmeta;
current_memcxt = save_memcxt;
current_tuplestore = save_tuplestore;
current_srf_binding = save_binding;
return (Datum) 0;
}
/*
* Build the $_TD Hash for a data-modification trigger.
*/
static VALUE
plruby_trig_build_args(FunctionCallInfo fcinfo)
{
TriggerData *tdata = (TriggerData *) fcinfo->context;
TupleDesc tupdesc = tdata->tg_relation->rd_att;
VALUE td = rb_hash_new();
char *relname = SPI_getrelname(tdata->tg_relation);
char *nspname = SPI_getnspname(tdata->tg_relation);
int i;
rb_hash_aset(td, rb_str_new_cstr("name"),
rb_str_new_cstr(tdata->tg_trigger->tgname));
rb_hash_aset(td, rb_str_new_cstr("relid"),
ULL2NUM(tdata->tg_relation->rd_id));
rb_hash_aset(td, rb_str_new_cstr("relname"), rb_str_new_cstr(relname));
rb_hash_aset(td, rb_str_new_cstr("schemaname"), rb_str_new_cstr(nspname));
if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
rb_hash_aset(td, rb_str_new_cstr("event"), rb_str_new_cstr("INSERT"));
else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
rb_hash_aset(td, rb_str_new_cstr("event"), rb_str_new_cstr("DELETE"));
else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
rb_hash_aset(td, rb_str_new_cstr("event"), rb_str_new_cstr("UPDATE"));
else if (TRIGGER_FIRED_BY_TRUNCATE(tdata->tg_event))
rb_hash_aset(td, rb_str_new_cstr("event"), rb_str_new_cstr("TRUNCATE"));
else
elog(ERROR, "unknown firing event for trigger function");
if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
{
if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
rb_hash_aset(td, rb_str_new_cstr("new"),
plruby_hash_from_tuple(tdata->tg_trigtuple, tupdesc));
else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
rb_hash_aset(td, rb_str_new_cstr("old"),
plruby_hash_from_tuple(tdata->tg_trigtuple, tupdesc));
else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
{
rb_hash_aset(td, rb_str_new_cstr("new"),
plruby_hash_from_tuple(tdata->tg_newtuple, tupdesc));
rb_hash_aset(td, rb_str_new_cstr("old"),
plruby_hash_from_tuple(tdata->tg_trigtuple, tupdesc));
}
}
rb_hash_aset(td, rb_str_new_cstr("argc"),
INT2NUM(tdata->tg_trigger->tgnargs));
if (tdata->tg_trigger->tgnargs > 0)
{
VALUE tgargs = rb_ary_new();
for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
rb_ary_push(tgargs, rb_str_new_cstr(tdata->tg_trigger->tgargs[i]));
rb_hash_aset(td, rb_str_new_cstr("args"), tgargs);
}
if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
rb_hash_aset(td, rb_str_new_cstr("when"), rb_str_new_cstr("BEFORE"));
else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
rb_hash_aset(td, rb_str_new_cstr("when"), rb_str_new_cstr("AFTER"));
else if (TRIGGER_FIRED_INSTEAD(tdata->tg_event))
rb_hash_aset(td, rb_str_new_cstr("when"), rb_str_new_cstr("INSTEAD OF"));
else