forked from nextgres/uplpgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupl_runtime.c
More file actions
1799 lines (1583 loc) · 55.9 KB
/
Copy pathupl_runtime.c
File metadata and controls
1799 lines (1583 loc) · 55.9 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
/*-------------------------------------------------------------------------
*
* uplpgsql_runtime.c
* C runtime helper functions called from JIT'd code.
*
* These functions bridge the gap between LLVM-generated native code
* and PostgreSQL's C runtime. They are called from JIT'd functions
* when an operation requires PostgreSQL infrastructure that cannot
* be expressed in LLVM IR (SPI calls, memory management, error
* handling, etc.).
*
* Symbol visibility:
* All functions are marked UPLPGSQL_RT_EXPORT which expands to
* __attribute__((visibility("default"))). This is necessary
* because the extension builds with -fvisibility=hidden. OrcJIT's
* process symbol search generator finds these symbols at link time.
*
* Function patterns:
* Most helpers follow a consistent pattern:
* 1. Receive UPLpgSQL_exec_state *estate as first argument
* 2. Extract plstate = estate->uplpgsql_estate
* 3. Call the corresponding exec_* function from upl_exec.c
* 4. Copy return values (retval, retisnull) back to JIT estate
*
* Some thin wrappers (e.g. exec_stmt_perform, exec_stmt_raise)
* are bypassed entirely by the compiler — uplpgsql_compile.c
* embeds the exec_* function pointer directly. The runtime
* helpers remain for:
* - Functions that need result value transfer (exec_return)
* - Functions with non-trivial bridging logic (eval_expr copies)
* - Cursor management (open/fetch/close portal lifecycle)
* - Exception handling (subtransaction management steps)
*
* Categories:
* - Expression evaluation: eval_expr, eval_bool, eval_int
* - Variable management: assign_expr, assign_int, assign_null,
* init_var, set_found, assign_var_datum, copy_assign_var_datum,
* get_recfield
* - Statement execution: exec_return, exec_perform, exec_sql, etc.
* - Cursor management: open_query_cursor, fetch_cursor_row,
* close_portal, open_forc_cursor, open_dynfors_cursor
* - Exception handling: exception_push_frame, exception_arm,
* exception_try_exit, exception_catch, exception_set_handler_vars,
* exception_handler_done, exception_rethrow
* - Error helpers: int_overflow, div_zero (in uplpgsql_expr.c)
*
*
* Copyright (c) 2003-2014, Jonah H. Harris <[email protected]>
* Copyright (c) 2014-2026, NEXTGRES, LLC. <[email protected]>
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain a
* copy of the License in LICENSE or at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
*-------------------------------------------------------------------------
*/
#include "upl_common.h"
#include "access/xact.h"
#include "catalog/pg_type_d.h"
#include "utils/array.h"
#include "utils/expandeddatum.h"
#include "utils/expandedrecord.h"
#include "utils/datum.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/portal.h"
/*
* Per-cursor context for batch prefetching in FOR-query loops.
*
* Allocated by open_query_cursor, freed by close_portal. Each nested
* FOR-query loop gets its own context, so batch state doesn't bleed
* between nesting levels.
*/
typedef struct UPLpgSQL_cursor_ctx
{
Portal portal;
SPITupleTable *batch_tuptab; /* current batch of fetched rows */
uint64 batch_count; /* number of rows in current batch */
uint64 batch_idx; /* index of next row to process */
uint64 batch_tupdesc_id; /* previous tupdesc id for fast assign */
bool batch_tupdescs_match; /* can use expanded_record_set_tuple? */
} UPLpgSQL_cursor_ctx;
/*
* uplpgsql_rt_exec_block_protected - Execute a block with exception handling.
*
* Delegates the entire block (including its exception handlers) to the
* interpreter's exec_stmt_block, which manages subtransactions via
* PG_TRY/PG_CATCH. This cannot be compiled to LLVM IR because longjmp
* is incompatible with LLVM's control flow model.
*/
UPLPGSQL_RT_EXPORT int32
uplpgsql_rt_exec_block_protected(UPLpgSQL_exec_state *estate,
UPLpgSQL_stmt_block *stmt)
{
UPLpgSQL_execstate *plstate = estate->uplpgsql_estate;
int32 rc;
rc = exec_stmt_block(plstate, stmt);
/*
* If the block returned via RETURN, copy retval/retisnull back to
* JIT state so the caller can see the result.
*/
if (rc == UPLPGSQL_RC_RETURN)
{
estate->retval = plstate->retval;
estate->retisnull = plstate->retisnull;
}
return rc;
}
/*
* uplpgsql_rt_eval_expr - Evaluate a UPLpgSQL_expr and return its Datum value.
*
* Wraps exec_eval_expr with datum copy for safety, since exec_eval_expr
* returns values that may live in the eval_tuptable.
*/
UPLPGSQL_RT_EXPORT Datum
uplpgsql_rt_eval_expr(UPLpgSQL_exec_state *estate,
UPLpgSQL_expr *expr, bool *isNull)
{
UPLpgSQL_execstate *plstate = estate->uplpgsql_estate;
Datum result;
Oid rettype;
int32 rettypmod;
result = exec_eval_expr(plstate, expr, isNull, &rettype, &rettypmod);
/*
* exec_eval_expr returns a value that may be in the eval_tuptable
* and could be freed on the next call. Copy pass-by-reference values.
*/
if (!*isNull)
{
int16 typlen;
bool typbyval;
get_typlenbyval(rettype, &typlen, &typbyval);
if (!typbyval)
result = datumCopy(result, typbyval, typlen);
}
exec_eval_cleanup(plstate);
return result;
}
/*
* uplpgsql_rt_eval_bool - Evaluate expression and coerce to bool.
* NULL is treated as false.
*/
UPLPGSQL_RT_EXPORT bool
uplpgsql_rt_eval_bool(UPLpgSQL_exec_state *estate, UPLpgSQL_expr *expr)
{
UPLpgSQL_execstate *plstate = estate->uplpgsql_estate;
bool isnull;
bool result;
result = exec_eval_boolean(plstate, expr, &isnull);
exec_eval_cleanup(plstate);
if (isnull)
return false;
return result;
}
/*
* uplpgsql_rt_eval_int - Evaluate expression and coerce to int32.
*/
UPLPGSQL_RT_EXPORT int32
uplpgsql_rt_eval_int(UPLpgSQL_exec_state *estate, UPLpgSQL_expr *expr)
{
UPLpgSQL_execstate *plstate = estate->uplpgsql_estate;
bool isnull;
int32 result;
result = exec_eval_integer(plstate, expr, &isnull);
exec_eval_cleanup(plstate);
if (isnull)
ereport(ERROR,
(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
errmsg("NULL value not allowed for integer expression")));
return result;
}
/*
* uplpgsql_rt_assign_expr - Evaluate expression and assign to variable.
*/
UPLPGSQL_RT_EXPORT void
uplpgsql_rt_assign_expr(UPLpgSQL_exec_state *estate,
int target_dno, UPLpgSQL_expr *expr)
{
UPLpgSQL_execstate *plstate = estate->uplpgsql_estate;
exec_assign_expr(plstate, plstate->datums[target_dno], expr);
}
/*
* uplpgsql_rt_case_assign_test - Evaluate a simple CASE's test expression into
* its temporary variable, retyping the variable to the expression's real type.
*
* The parser cannot know what type "CASE <expr> WHEN ..." tests, so it builds
* the temporary as an INT4 placeholder and leaves a note that the runtime will
* "fix this at runtime if needed" (upl_gram.y). exec_stmt_case() does the
* fixing. The JIT used to call exec_assign_expr() directly, which skips it and
* coerces the value to int4 instead:
*
* DECLARE a text := 'x';
* CASE a WHEN 'x' THEN ... END CASE;
* ERROR: invalid input syntax for type integer: "x"
*
* so a simple CASE worked only when the test expression really was an integer.
* Mirror exec_stmt_case().
*/
UPLPGSQL_RT_EXPORT void
uplpgsql_rt_case_assign_test(UPLpgSQL_exec_state *estate, int t_varno,
UPLpgSQL_expr *t_expr)
{
UPLpgSQL_execstate *plstate = estate->uplpgsql_estate;
UPLpgSQL_var *t_var;
Datum t_val;
bool isnull;
Oid t_typoid;
int32 t_typmod;
t_val = exec_eval_expr(plstate, t_expr, &isnull, &t_typoid, &t_typmod);
t_var = (UPLpgSQL_var *) plstate->datums[t_varno];
/*
* When the expected datatype differs from the real one, change it. This
* modifies an execution copy of the datum, so it does not affect the
* stored parse tree.
*/
if (t_var->datatype->typoid != t_typoid ||
t_var->datatype->atttypmod != t_typmod)
t_var->datatype = uplpgsql_build_datatype(t_typoid,
t_typmod,
plstate->func->fn_input_collation,
NULL);
exec_assign_value(plstate, (UPLpgSQL_datum *) t_var, t_val, isnull,
t_typoid, t_typmod);
exec_eval_cleanup(plstate);
}
/*
* uplpgsql_rt_init_var - Initialize a variable with its default value.
*
* Must match exec_stmt_block()'s variable initialization logic exactly,
* including domain constraint checking and error context setup.
*/
UPLPGSQL_RT_EXPORT void
uplpgsql_rt_init_var(UPLpgSQL_exec_state *estate, int dno)
{
UPLpgSQL_execstate *plstate = estate->uplpgsql_estate;
UPLpgSQL_datum *datum = plstate->datums[dno];
/*
* Set error context so that constraint violations during init report
* "during statement block local variable initialization" just like
* the interpreter does in exec_stmt_block().
*/
plstate->err_text = gettext_noop("during statement block local variable initialization");
plstate->err_var = (UPLpgSQL_variable *) datum;
switch (datum->dtype)
{
case UPLPGSQL_DTYPE_VAR:
{
UPLpgSQL_var *var = (UPLpgSQL_var *) datum;
/*
* Free any old value, in case re-entering block, and
* initialize to NULL.
*/
assign_simple_var(plstate, var, (Datum) 0, true, false);
if (var->default_val == NULL)
{
/*
* If needed, give the datatype a chance to reject NULLs,
* by assigning a NULL to the variable. We claim the value
* is of type UNKNOWN, not the var's datatype, else
* coercion will be skipped.
*/
if (var->datatype->typtype == TYPTYPE_DOMAIN)
exec_assign_value(plstate,
(UPLpgSQL_datum *) var,
(Datum) 0,
true,
UNKNOWNOID,
-1);
/* parser should have rejected NOT NULL */
Assert(!var->notnull);
}
else
{
exec_assign_expr(plstate, (UPLpgSQL_datum *) var,
var->default_val);
}
}
break;
case UPLPGSQL_DTYPE_REC:
{
UPLpgSQL_rec *rec = (UPLpgSQL_rec *) datum;
if (rec->default_val == NULL)
{
/*
* If needed, give the datatype a chance to reject NULLs,
* by assigning a NULL to the variable.
*/
exec_move_row(plstate, (UPLpgSQL_variable *) rec,
NULL, NULL);
/* parser should have rejected NOT NULL */
Assert(!rec->notnull);
}
else
{
exec_assign_expr(plstate, (UPLpgSQL_datum *) rec,
rec->default_val);
}
}
break;
default:
elog(ERROR, "unrecognized dtype: %d", datum->dtype);
}
plstate->err_text = NULL;
plstate->err_var = NULL;
}
/*
* uplpgsql_rt_set_found - Set the FOUND variable.
*/
UPLPGSQL_RT_EXPORT void
uplpgsql_rt_set_found(UPLpgSQL_exec_state *estate, bool value)
{
exec_set_found(estate->uplpgsql_estate, value);
}
/*
* uplpgsql_rt_exec_return - Execute a RETURN statement.
*
* Delegates to exec_stmt_return which handles all edge cases:
* retvarno, expression, VOID hack, composite types, etc.
* The return value, type, and null flag are stored directly into
* the PL/pgSQL estate by exec_stmt_return.
*/
UPLPGSQL_RT_EXPORT int32
uplpgsql_rt_exec_return(UPLpgSQL_exec_state *estate, UPLpgSQL_stmt_return *stmt)
{
UPLpgSQL_execstate *plstate = estate->uplpgsql_estate;
int rc;
rc = exec_stmt_return(plstate, stmt);
/* Copy back to JIT state so the caller can see the result */
estate->retval = plstate->retval;
estate->retisnull = plstate->retisnull;
return rc;
}
/*
* uplpgsql_rt_assign_int - Assign an int32 value to a variable by dno.
*
* Lightweight assignment for loop counters: the value is pass-by-value,
* never null, never freeable. Bypasses the full assign_simple_var path.
*/
UPLPGSQL_RT_EXPORT void
uplpgsql_rt_assign_int(UPLpgSQL_exec_state *estate, int dno, int32 value)
{
UPLpgSQL_execstate *plstate = estate->uplpgsql_estate;
UPLpgSQL_var *var = (UPLpgSQL_var *) plstate->datums[dno];
/*
* As in uplpgsql_rt_assign_null: release the old value through
* assign_simple_var so a read/write expanded object is deleted rather than
* pfree'd header-first. Only reached for pass-by-value int targets today
* (loop counters), where the old value cannot be expanded — but the raw
* free was latent breakage waiting for a caller with a wider target, and
* the detoast branch is inert here anyway (typlen != -1).
*/
assign_simple_var(plstate, var, Int32GetDatum(value), false, false);
}
/*
* uplpgsql_rt_exec_perform - Execute a PERFORM statement.
*/
UPLPGSQL_RT_EXPORT int32
uplpgsql_rt_exec_perform(UPLpgSQL_exec_state *estate, UPLpgSQL_stmt_perform *stmt)
{
return exec_stmt_perform(estate->uplpgsql_estate, stmt);
}
/*
* uplpgsql_rt_exec_sql - Execute a static SQL statement.
*/
UPLPGSQL_RT_EXPORT int32
uplpgsql_rt_exec_sql(UPLpgSQL_exec_state *estate, UPLpgSQL_stmt_execsql *stmt)
{
return exec_stmt_execsql(estate->uplpgsql_estate, stmt);
}
/*
* uplpgsql_rt_exec_raise - Execute a RAISE statement.
*/
UPLPGSQL_RT_EXPORT void
uplpgsql_rt_exec_raise(UPLpgSQL_exec_state *estate, UPLpgSQL_stmt_raise *stmt)
{
exec_stmt_raise(estate->uplpgsql_estate, stmt);
}
/*
* uplpgsql_rt_assign_null - Set a variable to NULL.
*
* Used by CASE to clear the temporary search expression variable
* after a match is found or at the end of the statement.
*/
UPLPGSQL_RT_EXPORT void
uplpgsql_rt_assign_null(UPLpgSQL_exec_state *estate, int dno)
{
UPLpgSQL_execstate *plstate = estate->uplpgsql_estate;
UPLpgSQL_var *var = (UPLpgSQL_var *) plstate->datums[dno];
/*
* Go through assign_simple_var rather than pfree'ing var->value directly.
*
* A read/write expanded object (an expanded array or record) must be
* released with DeleteExpandedObject: a bare pfree frees only the
* ExpandedObjectHeader chunk, leaking the object's private context and
* corrupting the allocator. This is reachable — CASE clears its temporary
* search variable through here, and that variable can hold an expanded
* value. assign_simple_var also cancels any promise on the variable,
* which the open-coded version skipped.
*/
assign_simple_var(plstate, var, (Datum) 0, true, false);
}
/*
* uplpgsql_rt_case_error - Raise "case not found" error.
*
* Called when no WHEN clause matches and there is no ELSE clause.
* SQL2003 mandates this error.
*/
UPLPGSQL_RT_EXPORT void
uplpgsql_rt_case_error(UPLpgSQL_exec_state *estate, int lineno)
{
ereport(ERROR,
(errcode(ERRCODE_CASE_NOT_FOUND),
errmsg("case not found"),
errhint("CASE statement is missing ELSE part.")));
}
/*
* uplpgsql_rt_assert_fail - Handle a failed ASSERT.
*
* Called from JIT'd code when the ASSERT condition evaluated to false/NULL.
* Evaluates the optional message expression and raises ERROR.
* Also checks uplpgsql_check_asserts GUC — if asserts are disabled,
* this is a no-op (the JIT'd code evaluates the condition but we
* swallow the failure).
*/
/*
* uplpgsql_rt_exec_assert - Execute an ASSERT statement.
*
* Delegates to exec_stmt_assert which handles the GUC check,
* condition evaluation, message evaluation, and error raising.
*/
UPLPGSQL_RT_EXPORT void
uplpgsql_rt_exec_assert(UPLpgSQL_exec_state *estate, UPLpgSQL_stmt_assert *stmt)
{
exec_stmt_assert(estate->uplpgsql_estate, stmt);
}
/*
* uplpgsql_rt_exec_open - Open a cursor.
*
* Handles all three OPEN variants (static query, dynamic query, explicit
* cursor) via exec_stmt_open. The path selection is based on AST fields
* known at compile time, but the SPI infrastructure (plan preparation,
* parameter binding, portal creation) requires runtime C code.
*/
UPLPGSQL_RT_EXPORT int32
uplpgsql_rt_exec_open(UPLpgSQL_exec_state *estate, UPLpgSQL_stmt_open *stmt)
{
return exec_stmt_open(estate->uplpgsql_estate, stmt);
}
/*
* uplpgsql_rt_exec_fetch - Fetch from a cursor or move cursor position.
*
* Handles FETCH INTO target and MOVE variants. Sets FOUND and
* eval_processed (ROW_COUNT) in the estate.
*/
UPLPGSQL_RT_EXPORT int32
uplpgsql_rt_exec_fetch(UPLpgSQL_exec_state *estate, UPLpgSQL_stmt_fetch *stmt)
{
return exec_stmt_fetch(estate->uplpgsql_estate, stmt);
}
/*
* uplpgsql_rt_exec_close - Close a cursor.
*/
UPLPGSQL_RT_EXPORT int32
uplpgsql_rt_exec_close(UPLpgSQL_exec_state *estate, UPLpgSQL_stmt_close *stmt)
{
return exec_stmt_close(estate->uplpgsql_estate, stmt);
}
/*
* uplpgsql_rt_open_query_cursor - Open a portal for a SELECT query.
*
* Used by FOR-query (FORS) loops. Prepares the plan if needed,
* opens a cursor via SPI, and returns a cursor context that includes
* batch prefetching state. Each nested FOR-query loop gets its own
* context, so batch state doesn't bleed between nesting levels.
*/
UPLPGSQL_RT_EXPORT void *
uplpgsql_rt_open_query_cursor(UPLpgSQL_exec_state *estate,
UPLpgSQL_expr *query)
{
UPLpgSQL_execstate *plstate = estate->uplpgsql_estate;
UPLpgSQL_cursor_ctx *cctx;
Portal portal;
exec_run_select(plstate, query, 0, &portal);
PinPortal(portal);
cctx = (UPLpgSQL_cursor_ctx *) palloc0(sizeof(UPLpgSQL_cursor_ctx));
cctx->portal = portal;
return (void *) cctx;
}
/*
* uplpgsql_rt_fetch_cursor_row - Fetch the next row from a cursor into
* the target variable.
*
* Returns true if a row was fetched, false if no more rows.
* Used by FOR-query loop condition: fetch → branch on result.
*
* Implements batch prefetching (matching PL/pgSQL's exec_for_query):
* first fetch grabs 10 rows, subsequent fetches grab 50. This reduces
* SPI cursor overhead by ~50x for large result sets.
*
* For RECORD-type targets, after the first row we use the fast
* expanded_record_set_tuple() path instead of exec_move_row(), which
* avoids tuple deconstruction overhead on subsequent rows.
*/
UPLPGSQL_RT_EXPORT bool
uplpgsql_rt_fetch_cursor_row(UPLpgSQL_exec_state *estate,
void *portal_ptr, int target_dno)
{
UPLpgSQL_execstate *plstate = estate->uplpgsql_estate;
UPLpgSQL_cursor_ctx *cctx = (UPLpgSQL_cursor_ctx *) portal_ptr;
UPLpgSQL_variable *target;
target = (UPLpgSQL_variable *) plstate->datums[target_dno];
/*
* If we have rows remaining in the current batch, assign the next one.
*/
if (cctx->batch_idx < cctx->batch_count)
{
SPITupleTable *tuptab = cctx->batch_tuptab;
uint64 idx = cctx->batch_idx++;
/*
* Fast path for RECORD targets: use expanded_record_set_tuple()
* when the tupdesc hasn't changed since the first row. This is
* the same optimization PL/pgSQL uses in exec_for_query.
*/
if (target->dtype == UPLPGSQL_DTYPE_REC)
{
UPLpgSQL_rec *rec = (UPLpgSQL_rec *) target;
if (rec->erh &&
rec->erh->er_tupdesc_id == cctx->batch_tupdesc_id &&
cctx->batch_tupdescs_match)
{
expanded_record_set_tuple(rec->erh, tuptab->vals[idx],
true, !plstate->atomic);
return true;
}
}
exec_move_row(plstate, target, tuptab->vals[idx], tuptab->tupdesc);
exec_eval_cleanup(plstate);
/* Check if fast path is usable for subsequent rows */
if (target->dtype == UPLPGSQL_DTYPE_REC)
{
UPLpgSQL_rec *rec = (UPLpgSQL_rec *) target;
if (rec->erh)
{
if (cctx->batch_tupdescs_match)
{
cctx->batch_tupdescs_match =
(rec->rectypeid == RECORDOID ||
rec->rectypeid == tuptab->tupdesc->tdtypeid);
}
cctx->batch_tupdesc_id = rec->erh->er_tupdesc_id;
}
}
return true;
}
/*
* Current batch is exhausted. Free it and fetch a new one.
*/
if (cctx->batch_tuptab)
{
SPI_freetuptable(cctx->batch_tuptab);
cctx->batch_tuptab = NULL;
}
/*
* Fetch next batch: 10 rows for first fetch (to minimize startup
* overhead), 50 rows for subsequent fetches (matching PL/pgSQL).
*
* Like PL/pgSQL, in non-atomic contexts we don't prefetch to avoid
* dangling toast references if the user commits mid-loop.
*/
{
long fetch_count;
if (!plstate->atomic)
fetch_count = 1;
else if (cctx->batch_count == 0)
fetch_count = 10; /* first fetch */
else
fetch_count = 50; /* subsequent fetches */
SPI_cursor_fetch(cctx->portal, true, fetch_count);
}
cctx->batch_tuptab = SPI_tuptable;
cctx->batch_count = SPI_processed;
cctx->batch_idx = 0;
if (cctx->batch_count == 0)
{
/* No more rows — set target to NULL */
exec_move_row(plstate, target, NULL,
cctx->batch_tuptab->tupdesc);
exec_eval_cleanup(plstate);
SPI_freetuptable(cctx->batch_tuptab);
cctx->batch_tuptab = NULL;
return false;
}
/* Assign first row of new batch */
{
SPITupleTable *tuptab = cctx->batch_tuptab;
cctx->batch_idx = 1;
exec_move_row(plstate, target, tuptab->vals[0], tuptab->tupdesc);
exec_eval_cleanup(plstate);
/* Initialize fast-path state for subsequent rows */
if (target->dtype == UPLPGSQL_DTYPE_REC)
{
UPLpgSQL_rec *rec = (UPLpgSQL_rec *) target;
if (rec->erh)
{
cctx->batch_tupdescs_match =
(rec->rectypeid == RECORDOID ||
rec->rectypeid == tuptab->tupdesc->tdtypeid);
cctx->batch_tupdesc_id = rec->erh->er_tupdesc_id;
}
}
}
return true;
}
/*
* uplpgsql_rt_close_portal - Close and unpin a portal.
*
* Used at the end of FOR-query loops. Frees any remaining batch
* and the cursor context itself.
*/
UPLPGSQL_RT_EXPORT void
uplpgsql_rt_close_portal(UPLpgSQL_exec_state *estate, void *portal_ptr)
{
UPLpgSQL_cursor_ctx *cctx = (UPLpgSQL_cursor_ctx *) portal_ptr;
/* Free any remaining batch from prefetch */
if (cctx->batch_tuptab)
{
SPI_freetuptable(cctx->batch_tuptab);
cctx->batch_tuptab = NULL;
}
UnpinPortal(cctx->portal);
SPI_cursor_close(cctx->portal);
pfree(cctx);
}
/*
* uplpgsql_rt_open_forc_cursor - Open the cursor for a FOR-cursor loop.
*
* Handles argument evaluation, plan preparation, SPI portal opening,
* and cursor variable assignment. Returns a cursor context wrapping
* a pinned Portal.
*/
UPLPGSQL_RT_EXPORT void *
uplpgsql_rt_open_forc_cursor(UPLpgSQL_exec_state *estate,
UPLpgSQL_stmt_forc *stmt)
{
UPLpgSQL_cursor_ctx *cctx;
Portal portal;
portal = exec_open_forc_cursor(estate->uplpgsql_estate, stmt);
cctx = (UPLpgSQL_cursor_ctx *) palloc0(sizeof(UPLpgSQL_cursor_ctx));
cctx->portal = portal;
return (void *) cctx;
}
/*
* uplpgsql_rt_close_forc_cursor - Close the cursor for a FOR-cursor loop.
*
* Unpins and closes the portal, resets cursor variable if needed.
* Frees any remaining batch and the cursor context.
*/
UPLPGSQL_RT_EXPORT void
uplpgsql_rt_close_forc_cursor(UPLpgSQL_exec_state *estate,
UPLpgSQL_stmt_forc *stmt,
void *portal_ptr)
{
UPLpgSQL_cursor_ctx *cctx = (UPLpgSQL_cursor_ctx *) portal_ptr;
/* Free any remaining batch from prefetch */
if (cctx->batch_tuptab)
{
SPI_freetuptable(cctx->batch_tuptab);
cctx->batch_tuptab = NULL;
}
exec_close_forc_cursor(estate->uplpgsql_estate, stmt, cctx->portal);
pfree(cctx);
}
/*
* uplpgsql_rt_exec_dynexecute - Execute a dynamic SQL statement.
*/
UPLPGSQL_RT_EXPORT int32
uplpgsql_rt_exec_dynexecute(UPLpgSQL_exec_state *estate,
UPLpgSQL_stmt_dynexecute *stmt)
{
return exec_stmt_dynexecute(estate->uplpgsql_estate, stmt);
}
/*
* uplpgsql_rt_exec_call - Execute a CALL statement.
*/
UPLPGSQL_RT_EXPORT int32
uplpgsql_rt_exec_call(UPLpgSQL_exec_state *estate, UPLpgSQL_stmt_call *stmt)
{
return exec_stmt_call(estate->uplpgsql_estate, stmt);
}
/*
* uplpgsql_rt_exec_getdiag - Execute a GET DIAGNOSTICS statement.
*/
UPLPGSQL_RT_EXPORT void
uplpgsql_rt_exec_getdiag(UPLpgSQL_exec_state *estate,
UPLpgSQL_stmt_getdiag *stmt)
{
exec_stmt_getdiag(estate->uplpgsql_estate, stmt);
}
/*
* uplpgsql_rt_exec_return_next - Execute RETURN NEXT.
*/
UPLPGSQL_RT_EXPORT int32
uplpgsql_rt_exec_return_next(UPLpgSQL_exec_state *estate,
UPLpgSQL_stmt_return_next *stmt)
{
return exec_stmt_return_next(estate->uplpgsql_estate, stmt);
}
/*
* uplpgsql_rt_exec_return_query - Execute RETURN QUERY.
*/
UPLPGSQL_RT_EXPORT int32
uplpgsql_rt_exec_return_query(UPLpgSQL_exec_state *estate,
UPLpgSQL_stmt_return_query *stmt)
{
return exec_stmt_return_query(estate->uplpgsql_estate, stmt);
}
/*
* uplpgsql_rt_exec_commit - Execute COMMIT.
*/
UPLPGSQL_RT_EXPORT void
uplpgsql_rt_exec_commit(UPLpgSQL_exec_state *estate,
UPLpgSQL_stmt_commit *stmt)
{
exec_stmt_commit(estate->uplpgsql_estate, stmt);
}
/*
* uplpgsql_rt_exec_rollback - Execute ROLLBACK.
*/
UPLPGSQL_RT_EXPORT void
uplpgsql_rt_exec_rollback(UPLpgSQL_exec_state *estate,
UPLpgSQL_stmt_rollback *stmt)
{
exec_stmt_rollback(estate->uplpgsql_estate, stmt);
}
/*
* uplpgsql_rt_exec_foreach_a - Execute a FOREACH array loop.
*
* For now, delegate the entire loop to the interpreter since the
* array slicing/element extraction logic is deeply tied to executor
* internals. The loop control flow stays in C.
*/
UPLPGSQL_RT_EXPORT int32
uplpgsql_rt_exec_foreach_a(UPLpgSQL_exec_state *estate,
UPLpgSQL_stmt_foreach_a *stmt)
{
return exec_stmt_foreach_a(estate->uplpgsql_estate, stmt);
}
/*
* uplpgsql_rt_array_get_element - Read a single element from an array variable.
*
* Bypasses SPI expression evaluation for arr[i] reads. The JIT'd code
* compiles the subscript index to native IR and passes it directly as
* an integer. This function loads the array Datum from the variable and
* calls array_get_element() — skipping exec_eval_expr, ExprState setup,
* and the Param callback chain.
*
* Parameters:
* estate - JIT execution state (plstate lives inside)
* array_dno - datum number of the array variable
* subscript - 1-based array index (already evaluated by JIT'd code)
* isNull_out - output: whether the element is NULL
*
* Returns the element Datum (pass-by-value or pointer to palloc'd copy).
*/
UPLPGSQL_RT_EXPORT Datum
uplpgsql_rt_array_get_element(UPLpgSQL_exec_state *estate,
int array_dno, int subscript,
int typlen, int16 elmlen,
bool elmbyval, char elmalign,
bool *isNull_out)
{
UPLpgSQL_execstate *plstate = estate->uplpgsql_estate;
UPLpgSQL_var *arrayvar;
Datum result;
arrayvar = (UPLpgSQL_var *) plstate->datums[array_dno];
/* NULL array → NULL element */
if (arrayvar->isnull)
{
*isNull_out = true;
return (Datum) 0;
}
result = array_get_element(arrayvar->value,
1, &subscript,
typlen,
elmlen, elmbyval, elmalign,
isNull_out);
/* Copy pass-by-ref result so it survives beyond transient contexts */
if (!*isNull_out && !elmbyval)
result = datumCopy(result, elmbyval, elmlen);
return result;
}
/*
* uplpgsql_rt_array_set_element - Write a single element into an array variable.
*
* Bypasses SPI expression evaluation for arr[i] := val writes. The JIT'd
* code compiles both the subscript index and the value to native IR and
* passes them directly. This function calls array_set_element() and
* stores the modified array back into the variable.
*
* Handles:
* - NULL array (creates empty array first)
* - Expanded array promotion (R/W form for efficient subsequent access)
* - freeval cleanup via assign_simple_var
*
* Parameters:
* estate - JIT execution state
* array_dno - datum number of the array variable
* subscript - 1-based array index (already evaluated by JIT'd code)
* newvalue - Datum value to store
* valisnull - whether the value is NULL
*/
UPLPGSQL_RT_EXPORT void
uplpgsql_rt_array_set_element(UPLpgSQL_exec_state *estate,
int array_dno, int subscript,
Datum newvalue, bool valisnull,
int typlen, Oid elemtype,
int16 elmlen, bool elmbyval,
char elmalign)
{
UPLpgSQL_execstate *plstate = estate->uplpgsql_estate;
UPLpgSQL_var *arrayvar;
Datum arraydatum;
arrayvar = (UPLpgSQL_var *) plstate->datums[array_dno];
/* NULL array → start with empty array */
if (arrayvar->isnull)
arraydatum = PointerGetDatum(construct_empty_array(elemtype));
else
arraydatum = arrayvar->value;
{
Datum olddatum = arraydatum;
arraydatum = array_set_element(arraydatum,
1, &subscript,
newvalue, valisnull,
typlen,
elmlen, elmbyval, elmalign);
if (arraydatum == olddatum)
{
/*
* array_set_element modified the expanded array in-place and
* returned the same pointer. Nothing more to do — the variable
* already points to the updated expanded object.
*/
}
else
{
/*
* Got a new flat array back. Promote to R/W expanded form so
* subsequent subscript ops can modify in-place.
*/
arraydatum = expand_array(arraydatum,
plstate->datum_context, NULL);
assign_simple_var(plstate, arrayvar, arraydatum, false, true);
}
}
}
/*
* uplpgsql_rt_open_dynfors_cursor - Open a portal for a dynamic FOR query.
*
* Evaluates the dynamic query string with USING parameters and returns
* a pinned Portal for the JIT'd loop to iterate over.
*/
UPLPGSQL_RT_EXPORT void *
uplpgsql_rt_open_dynfors_cursor(UPLpgSQL_exec_state *estate,
UPLpgSQL_stmt_dynfors *stmt)
{
UPLpgSQL_execstate *plstate = estate->uplpgsql_estate;
UPLpgSQL_cursor_ctx *cctx;
Portal portal;
portal = exec_dynquery_with_params(plstate, stmt->query, stmt->params,
NULL, CURSOR_OPT_NO_SCROLL);
PinPortal(portal);
cctx = (UPLpgSQL_cursor_ctx *) palloc0(sizeof(UPLpgSQL_cursor_ctx));
cctx->portal = portal;
return (void *) cctx;
}