forked from RhodiumToad/pllua-ng
-
Notifications
You must be signed in to change notification settings - Fork 14
/
spi.c
1572 lines (1346 loc) · 37 KB
/
spi.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
/* spi.c */
#include "pllua.h"
#include "access/htup_details.h"
#if PG_VERSION_NUM >= 110000
#include "access/xact.h"
#endif
#include "commands/trigger.h"
#include "catalog/pg_type.h"
#include "executor/spi.h"
#include "parser/analyze.h"
#include "parser/parse_param.h"
#if PG_VERSION_NUM >= 110000
#define PortalGetHeapMemory(portal) ((portal)->portalContext)
#endif
/*
* plpgsql uses 10. We have a bit more overhead per queue fill since we
* start/stop SPI and do a bunch of data copies, so a larger value seems good.
* However, above 50 the returns are very small and the potential for memory
* problems increases.
*
* The fetch count can be set per-statement.
*/
#define DEFAULT_FETCH_COUNT 50
typedef struct pllua_spi_statement {
SPIPlanPtr plan;
bool kept;
bool cursor_plan;
int fetch_count; /* only used for private cursors */
int nparams;
int param_types_len;
Oid *param_types;
MemoryContext mcxt;
} pllua_spi_statement;
/*
* This is an object not a refobject since it references no memory other than
* the Portal, which has its own memory context already.
*
* But, we have to allow for the possibility that the portal will be ripped out
* from under us, e.g. by transaction end, explicit CLOSE, or whatever. So we
* use the same trick as for activations (with the slight variation that we use
* a weak table for tracking, since unlike with activations we expect to shed
* references to no-longer-needed cursors).
*
* We also track whether the cursor is considered "private" to us (meaning that
* it hasn't been exposed anywhere that the user would see, e.g. we're keeping it
* in a closure for a rows() iterator). Since the position of such a cursor isn't
* visible to others, we can prefetch.
*/
typedef struct pllua_spi_cursor {
Portal portal; /* or null if closed or dead */
MemoryContextCallback *cb; /* allocated in PortalContext */
lua_State *L; /* needed by callback */
int fetch_count; /* only used for private cursors */
bool is_ours; /* we created (and will close) it? */
bool is_private; /* nobody else should be touching it */
bool is_live; /* cleared by callback */
} pllua_spi_cursor;
static pllua_spi_cursor *pllua_newcursor(lua_State *L);
static void pllua_cursor_setportal(lua_State *L, int nd,
pllua_spi_cursor *curs,
Portal portal, bool is_ours);
/*
* Pushes up to four entries on the stack - beware!
*/
static void pllua_spi_alloc_argspace(lua_State *L,
int nargs,
Datum **values,
bool **isnull,
Oid **argtypes,
pllua_typeinfo ***typeinfos)
{
if (values)
*values = lua_newuserdata(L, nargs * sizeof(Datum));
if (isnull)
*isnull = lua_newuserdata(L, nargs * sizeof(bool));
if (argtypes)
*argtypes = lua_newuserdata(L, nargs * sizeof(Oid));
if (typeinfos)
*typeinfos = lua_newuserdata(L, nargs * sizeof(pllua_typeinfo *));
}
static bool pllua_spi_enter(lua_State *L)
{
bool readonly = pllua_get_cur_act_readonly(L);
ASSERT_PG_CONTEXT;
SPI_connect();
#if PG_VERSION_NUM >= 100000
{
pllua_activation_record *pact = &(pllua_getinterpreter(L)->cur_activation);
if (pact->fcinfo && CALLED_AS_TRIGGER(pact->fcinfo))
SPI_register_trigger_data((TriggerData *) pact->fcinfo->context);
}
#endif
return readonly;
}
static int pllua_spi_is_readonly(lua_State *L)
{
bool readonly = pllua_get_cur_act_readonly(L);
lua_pushboolean(L, readonly);
return 1;
}
static void pllua_spi_exit(lua_State *L)
{
SPI_finish();
}
/*
* This creates the result but does not copy the data into the proper memory
* context; see pllua_spi_save_result for that.
*
* args: light[tuptab] nrows [table baseidx]
* returns: typeinfo table baseidx
*/
int pllua_spi_prepare_result(lua_State *L)
{
SPITupleTable *tuptab = lua_touserdata(L, 1);
lua_Integer nrows = lua_tointeger(L, 2);
TupleDesc tupdesc = tuptab->tupdesc;
lua_Integer base = 1;
lua_Integer i;
if (!lua_istable(L, 3))
{
lua_settop(L, 3);
lua_createtable(L, nrows, 0);
lua_replace(L, 3);
}
else
base = 1 + lua_tointeger(L, 4);
if (tupdesc->tdtypeid == RECORDOID && tupdesc->tdtypmod < 0)
pllua_newtypeinfo_raw(L, tupdesc->tdtypeid, tupdesc->tdtypmod, tupdesc);
else
{
lua_pushcfunction(L, pllua_typeinfo_lookup);
lua_pushinteger(L, (lua_Integer) tupdesc->tdtypeid);
lua_pushinteger(L, (lua_Integer) tupdesc->tdtypmod);
lua_call(L, 2, 1);
}
for (i = 0; i < nrows; ++i)
{
HeapTuple htup = tuptab->vals[i];
HeapTupleHeader h = htup->t_data;
pllua_datum *d;
/* htup might be in on-disk format or datum format. Force datum format. */
HeapTupleHeaderSetDatumLength(h, htup->t_len);
HeapTupleHeaderSetTypeId(h, tupdesc->tdtypeid);
HeapTupleHeaderSetTypMod(h, tupdesc->tdtypmod);
d = pllua_newdatum(L, -1, (Datum)0);
/* we intentionally do not detoast anything here, see savedatum */
d->value = PointerGetDatum(h);
lua_rawseti(L, 3, i+base);
}
lua_pushvalue(L, 3);
lua_pushinteger(L, base+nrows-1);
lua_setfield(L, -2, "n");
lua_pushinteger(L, base);
return 3;
}
/*
* stack: ... typeinfo table base
*/
static void pllua_spi_save_result(lua_State *L, lua_Integer nrows)
{
MemoryContext oldcontext = MemoryContextSwitchTo(pllua_get_memory_cxt(L));
pllua_typeinfo *t = *(void **)lua_touserdata(L, -3);
lua_Integer base = lua_tointeger(L, -1);
lua_Integer i;
/* we rely on the fact that rawgeti won't throw */
for (i = 0; i < nrows; ++i)
{
pllua_datum *d;
lua_rawgeti(L, -2, i+base);
d = lua_touserdata(L, -1);
pllua_savedatum(L, d, t);
lua_pop(L,1);
}
MemoryContextSwitchTo(oldcontext);
}
static int pllua_cursor_options(lua_State *L, int nd, int *fetch_count)
{
int n = 0;
int isint = 0;
int flag = 0;
if (lua_isnoneornil(L, nd))
return 0;
luaL_checktype(L, nd, LUA_TTABLE);
lua_getfield(L, nd, "scroll");
/*
* support scroll = false as if it were no_scroll = true, because not doing
* so is too confusing. But note that specifying neither has a different
* effect.
*/
if (!lua_isnil(L, -1))
{
if (lua_toboolean(L, -1))
flag |= CURSOR_OPT_SCROLL;
else
flag |= CURSOR_OPT_NO_SCROLL;
}
lua_pop(L, 1);
lua_getfield(L, nd, "no_scroll");
flag |= (lua_toboolean(L, -1)) ? CURSOR_OPT_NO_SCROLL : 0;
lua_pop(L, 1);
lua_getfield(L, nd, "hold");
flag |= (lua_toboolean(L, -1)) ? CURSOR_OPT_HOLD : 0;
lua_pop(L, 1);
lua_getfield(L, nd, "fast_start");
flag |= (lua_toboolean(L, -1)) ? CURSOR_OPT_FAST_PLAN : 0;
lua_pop(L, 1);
lua_getfield(L, nd, "custom_plan");
flag |= (lua_toboolean(L, -1)) ? CURSOR_OPT_CUSTOM_PLAN : 0;
lua_pop(L, 1);
lua_getfield(L, nd, "generic_plan");
flag |= (lua_toboolean(L, -1)) ? CURSOR_OPT_GENERIC_PLAN : 0;
lua_pop(L, 1);
lua_getfield(L, nd, "fetch_count");
n = lua_tointegerx(L, -1, &isint);
if (isint && n >= 1 && n < 10000000)
*fetch_count = n;
lua_pop(L, 1);
return flag;
}
static int pllua_spi_prepare_recursion = -1;
static post_parse_analyze_hook_type pllua_spi_prev_parse_hook = NULL;
#if PG_VERSION_NUM >= 140000
static void pllua_spi_prepare_checkparam_hook(ParseState *pstate,
Query *query,
JumbleState *jstate)
{
if (pllua_spi_prepare_recursion == 1)
check_variable_parameters(pstate, query);
if (pllua_spi_prev_parse_hook)
pllua_spi_prev_parse_hook(pstate, query, jstate);
}
#else
static void pllua_spi_prepare_checkparam_hook(ParseState *pstate,
Query *query)
{
if (pllua_spi_prepare_recursion == 1)
check_variable_parameters(pstate, query);
if (pllua_spi_prev_parse_hook)
pllua_spi_prev_parse_hook(pstate, query);
}
#endif
static void pllua_spi_prepare_parser_setup_hook(ParseState *pstate, void *arg)
{
pllua_spi_statement *stmt = arg;
#if PG_VERSION_NUM >= 150000
setup_parse_variable_parameters(pstate, &stmt->param_types, &stmt->param_types_len);
#else
parse_variable_parameters(pstate, &stmt->param_types, &stmt->param_types_len);
#endif
}
static pllua_spi_statement *pllua_spi_make_statement(lua_State *L,
const char *str,
int nargs_known,
Oid *argtypes,
int opts)
{
MemoryContext mcxt = AllocSetContextCreate(CurrentMemoryContext,
"PL/Lua SPI statement object",
ALLOCSET_SMALL_SIZES);
MemoryContext oldcontext = MemoryContextSwitchTo(mcxt);
pllua_spi_statement *stmt = palloc0(sizeof(pllua_spi_statement));
int i;
ASSERT_PG_CONTEXT;
stmt->mcxt = mcxt;
stmt->nparams = 0;
stmt->fetch_count = 0;
if (nargs_known > 0)
{
stmt->param_types_len = nargs_known;
stmt->param_types = palloc(nargs_known * sizeof(Oid));
memcpy(stmt->param_types, argtypes, nargs_known * sizeof(Oid));
}
else
{
/* we have to preallocate this to get it in the right context */
stmt->param_types_len = 16; /* wholly arbitrary */
stmt->param_types = palloc0(16 * sizeof(Oid));
}
/*
* GAH. To do parameter type checking properly, we have to arrange to
* enable our own global post-parse hook transiently.
*/
if (pllua_spi_prepare_recursion != 0)
elog(ERROR, "pllua: recursive entry into prepare!"); /* paranoia */
PG_TRY();
{
++pllua_spi_prepare_recursion;
stmt->plan = SPI_prepare_params(str,
pllua_spi_prepare_parser_setup_hook,
stmt,
opts);
--pllua_spi_prepare_recursion;
}
PG_CATCH();
{
--pllua_spi_prepare_recursion;
PG_RE_THROW();
}
PG_END_TRY();
if (!stmt->plan)
elog(ERROR, "spi error: %s", SPI_result_code_string(SPI_result));
for (i = stmt->param_types_len; i > 0; --i)
{
if (stmt->param_types[i - 1] != 0)
{
stmt->nparams = i;
break;
}
}
stmt->cursor_plan = SPI_is_cursor_plan(stmt->plan);
MemoryContextSwitchTo(oldcontext);
return stmt;
}
/*
* prepare(cmd,[{argtypes}, [{flag=true,...,fetch_count=n}])
*
* argtypes are given as text or typeinfo.
* flags: "scroll","no_scroll","fast_start","custom_plan","generic_plan"
*/
static int pllua_spi_prepare(lua_State *L)
{
const char *str = lua_tostring(L, 1);
int fetch_count = 0;
int opts = pllua_cursor_options(L, 3, &fetch_count);
void **volatile p;
int i;
int nargs = 0;
Oid d_argtypes[100];
Oid *argtypes = d_argtypes;
if (pllua_ending)
luaL_error(L, "cannot call SPI during shutdown");
if (nargs > 99)
pllua_spi_alloc_argspace(L, nargs, NULL, NULL, &argtypes, NULL);
lua_settop(L, 2);
/* make the plan object - index 3 */
p = pllua_newrefobject(L, PLLUA_SPI_STMT_OBJECT, NULL, true);
nargs = 0;
if (!lua_isnoneornil(L, 2))
{
for(i = 1; ; ++i)
{
pllua_typeinfo *t;
if (lua_geti(L, 2, i) == LUA_TNIL)
break;
if (lua_isstring(L, -1))
{
lua_pushcfunction(L, pllua_typeinfo_parsetype);
lua_pushvalue(L, -2);
lua_call(L, 1, 1);
if (lua_isnil(L, -1))
luaL_error(L, "unknown type '%s'", lua_tostring(L, -2));
lua_remove(L, -2);
}
t = pllua_totypeinfo(L, -1);
if (!t)
luaL_error(L, "unexpected object type in argtypes list");
argtypes[nargs++] = t->typeoid;
}
}
PLLUA_TRY();
{
pllua_spi_statement *stmt;
pllua_spi_enter(L);
stmt = pllua_spi_make_statement(L, str, nargs, argtypes, opts);
/* reparent everything */
SPI_keepplan(stmt->plan);
stmt->kept = true;
stmt->fetch_count = fetch_count;
MemoryContextSetParent(stmt->mcxt, pllua_get_memory_cxt(L));
*p = stmt;
pllua_spi_exit(L);
}
PLLUA_CATCH_RETHROW();
lua_getuservalue(L, 3);
{
pllua_spi_statement *stmt = *p;
for(i = 0; i < stmt->nparams; ++i)
{
pllua_typeinfo *t;
/* unused params will have InvalidOid here */
if (OidIsValid(stmt->param_types[i]))
{
lua_pushcfunction(L, pllua_typeinfo_lookup);
lua_pushinteger(L, (lua_Integer) stmt->param_types[i]);
lua_call(L, 1, 1);
t = pllua_totypeinfo(L, -1);
if (!t)
luaL_error(L, "unexpected type in paramtypes list: %d", (lua_Integer) stmt->param_types[i]);
lua_rawseti(L, -2, i+1);
}
}
}
lua_pushvalue(L, 3);
return 1;
}
/*
* args: light[values] light[isnull] light[argtypes] argtable arg...
*
* argtypes are as determined by the parser, may not match the actual type of
* arg.
*/
int pllua_spi_convert_args(lua_State *L)
{
Datum *values = lua_touserdata(L, 1);
bool *isnull = lua_touserdata(L, 2);
Oid *argtypes = lua_touserdata(L, 3);
int nargs = lua_gettop(L) - 4;
int argbase = 5;
int i;
for (i = 0; i < nargs; ++i)
{
if (!lua_isnil(L, argbase+i) && OidIsValid(argtypes[i]))
{
pllua_typeinfo *dt;
pllua_datum *d;
lua_pushvalue(L, argbase+i);
d = pllua_toanydatum(L, -1, &dt);
/* not already an unexploded datum of correct type? */
if (!d ||
dt->typeoid != argtypes[i] ||
dt->obsolete || dt->modified ||
d->modified)
{
if (d)
lua_pop(L, 1); /* discard typeinfo */
lua_pushcfunction(L, pllua_typeinfo_lookup);
lua_pushinteger(L, (lua_Integer) argtypes[i]);
lua_call(L, 1, 1);
lua_insert(L, -2);
lua_call(L, 1, 1);
d = pllua_toanydatum(L, -1, &dt);
}
/* it better be the right type now */
if (!d || dt->typeoid != argtypes[i])
luaL_error(L, "inconsistent value type in SPI parameter list");
lua_pop(L, 1); /* discard typeinfo */
/*
* holding a reference here means that d remains valid even though
* it's no longer on the stack
*/
lua_rawseti(L, 4, i+1);
values[i] = d->value;
isnull[i] = false;
}
else
{
values[i] = (Datum)0;
isnull[i] = true;
}
}
return 0;
}
static ParamListInfo
pllua_spi_init_paramlist(int nargs, Datum *values, bool *isnull, Oid *types)
{
ParamListInfo paramLI;
int i;
ASSERT_PG_CONTEXT;
paramLI = (ParamListInfo) palloc0(offsetof(ParamListInfoData, params) +
nargs * sizeof(ParamExternData));
/* we have static list of params, so no hooks needed */
paramLI->paramFetch = NULL;
paramLI->paramFetchArg = NULL;
#if PG_VERSION_NUM >= 110000
paramLI->paramCompile = NULL;
paramLI->paramCompileArg = NULL;
#endif
paramLI->parserSetup = NULL;
paramLI->parserSetupArg = NULL;
paramLI->numParams = nargs;
#if PG_VERSION_NUM >= 90600 && PG_VERSION_NUM < 110000
paramLI->paramMask = NULL;
#endif
for (i = 0; i < nargs; i++)
{
ParamExternData *prm = ¶mLI->params[i];
prm->value = values[i];
prm->isnull = isnull[i];
prm->pflags = PARAM_FLAG_CONST;
prm->ptype = types[i];
}
return paramLI;
}
/*
* spi.execute_count(cmd, count, arg...) returns {rows...}
* also stmt:execute_count(count, arg...)
*
*/
static int pllua_spi_execute_count(lua_State *L)
{
void **p = pllua_torefobject(L, 1, PLLUA_SPI_STMT_OBJECT);
const char *str = lua_tostring(L, 1);
int nargs = lua_gettop(L) - 2;
int argbase = 3;
Datum d_values[100];
bool d_isnull[100];
Oid d_argtypes[100];
Datum *values = d_values;
bool *isnull = d_isnull;
Oid *argtypes = d_argtypes;
lua_Integer count_param = luaL_optinteger(L, 2, 0);
long count;
volatile lua_Integer nrows = -1;
int i;
if (!str && !p)
luaL_error(L, "incorrect argument type for execute, string or statement expected");
if (count_param == 0)
count = (long) Min(LUA_MAXINTEGER-1, LONG_MAX-1);
else if (count_param < 0 || count_param > LUA_MAXINTEGER-1 || count_param > LONG_MAX-1)
luaL_error(L, "requested number of rows is out of range");
else
count = (long) count_param;
if (pllua_ending)
luaL_error(L, "cannot call SPI during shutdown");
if (nargs > 99)
pllua_spi_alloc_argspace(L, nargs, &values, &isnull, &argtypes, NULL);
/* check encoding of query string */
if (str)
pllua_verify_encoding(L, str);
/*
* If we don't have a prepared stmt, then extract argtypes where we have
* definite info (i.e. only when the parameter is actually a datum).
*/
if (!p)
{
for (i = 0; i < nargs; ++i)
{
argtypes[i] = 0;
if (lua_type(L, argbase+i) == LUA_TUSERDATA)
{
pllua_typeinfo *dt;
pllua_datum *d = pllua_toanydatum(L, argbase+i, &dt);
if (d)
{
argtypes[i] = dt->typeoid;
lua_pop(L, 1);
}
}
}
}
/* we're going to re-push all the args, better have space */
luaL_checkstack(L, 40+nargs, NULL);
lua_createtable(L, nargs, 0); /* table to hold refs to arg datums */
PLLUA_TRY();
{
bool readonly = pllua_spi_enter(L);
pllua_spi_statement *stmt = p ? *p : NULL;
ParamListInfo paramLI = NULL;
int rc;
if (!stmt)
stmt = pllua_spi_make_statement(L, str, nargs, argtypes, 0);
if (stmt->nparams != nargs)
elog(ERROR, "pllua: wrong number of arguments to SPI query: expected %d got %d", stmt->nparams, nargs);
pllua_pushcfunction(L, pllua_spi_convert_args);
lua_pushlightuserdata(L, values);
lua_pushlightuserdata(L, isnull);
lua_pushlightuserdata(L, stmt->param_types);
lua_pushvalue(L, -5);
for (i = 0; i < nargs; ++i)
{
lua_pushvalue(L, argbase+i);
}
pllua_pcall(L, 4+nargs, 0, 0);
if (nargs > 0)
paramLI = pllua_spi_init_paramlist(nargs, values, isnull, stmt->param_types);
rc = SPI_execute_plan_with_paramlist(stmt->plan, paramLI, readonly, count);
if (rc >= 0)
{
nrows = SPI_processed;
if (SPI_tuptable)
{
/*
* Blessing the tupdesc of the result turns out to be a bad
* idea if we can avoid it; in a long-running backend the
* tupdescs can really pile up.
*/
pllua_pushcfunction(L, pllua_spi_prepare_result);
lua_pushlightuserdata(L, SPI_tuptable);
lua_pushinteger(L, nrows);
pllua_pcall(L, 2, 3, 0);
pllua_spi_save_result(L, nrows);
lua_pop(L, 1);
}
else
lua_pushinteger(L, nrows);
}
else
elog(ERROR, "spi error: %s", SPI_result_code_string(rc));
/*
* If we made our own statement, we didn't save it so it goes away here
*/
pllua_spi_exit(L);
}
PLLUA_CATCH_RETHROW();
return 1;
}
/*
* spi.execute(cmd, arg...) returns {rows...}
* also stmt:execute(arg...)
*
* simple shim to insert the count arg
*/
static int pllua_spi_execute(lua_State *L)
{
luaL_checkany(L, 1);
lua_pushcfunction(L, pllua_spi_execute_count);
lua_insert(L, 1);
lua_pushnil(L);
lua_insert(L, 3);
lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
return lua_gettop(L);
}
/*
* c:open(cmd, arg...)
* c:open(stmt, arg...)
*
*/
static int pllua_spi_cursor_open(lua_State *L)
{
pllua_spi_cursor *curs = pllua_checkobject(L, 1, PLLUA_SPI_CURSOR_OBJECT);
void **p = pllua_torefobject(L, 2, PLLUA_SPI_STMT_OBJECT);
pllua_spi_statement *stmt = p ? *p : NULL;
const char *str = lua_tostring(L, 2);
const char *name = NULL;
int nargs = lua_gettop(L) - 2;
int argbase = 3;
Datum d_values[100];
bool d_isnull[100];
Oid d_argtypes[100];
Datum *values = d_values;
bool *isnull = d_isnull;
Oid *argtypes = d_argtypes;
volatile Portal portal;
int i;
if (!str && !p)
luaL_error(L, "incorrect argument type for cursor open, string or statement expected");
if (curs->portal)
luaL_error(L, "cursor is already open");
if (pllua_ending)
luaL_error(L, "cannot call SPI during shutdown");
if (stmt && !stmt->cursor_plan)
luaL_error(L, "invalid statement for cursor");
if (nargs > 99)
pllua_spi_alloc_argspace(L, nargs, &values, &isnull, &argtypes, NULL);
/* check encoding of query string */
if (str)
pllua_verify_encoding(L, str);
lua_getuservalue(L, 1);
lua_getfield(L, -1, "name");
name = lua_tostring(L, -1);
lua_pop(L, 1);
/*
* If we don't have a prepared stmt, then extract argtypes where we have
* definite info (i.e. only when the parameter is actually a datum).
*/
if (!stmt)
{
for (i = 0; i < nargs; ++i)
{
argtypes[i] = 0;
if (lua_type(L, argbase+i) == LUA_TUSERDATA)
{
pllua_typeinfo *dt;
pllua_datum *d = pllua_toanydatum(L, argbase+i, &dt);
if (d)
{
argtypes[i] = dt->typeoid;
lua_pop(L, 1);
}
}
}
}
/* we're going to re-push all the args, better have space */
luaL_checkstack(L, 40+nargs, NULL);
lua_createtable(L, nargs, 0);
PLLUA_TRY();
{
bool readonly = pllua_spi_enter(L);
ParamListInfo paramLI = NULL;
if (!stmt)
{
stmt = pllua_spi_make_statement(L, str, nargs, argtypes, 0);
if (!stmt->cursor_plan)
elog(ERROR, "pllua: invalid query for cursor");
}
if (stmt->nparams != nargs)
elog(ERROR, "pllua: wrong number of arguments to SPI query: expected %d got %d", stmt->nparams, nargs);
pllua_pushcfunction(L, pllua_spi_convert_args);
lua_pushlightuserdata(L, values);
lua_pushlightuserdata(L, isnull);
lua_pushlightuserdata(L, stmt->param_types);
lua_pushvalue(L, -5);
for (i = 0; i < nargs; ++i)
{
lua_pushvalue(L, argbase+i);
}
pllua_pcall(L, 4+nargs, 0, 0);
if (nargs > 0)
paramLI = pllua_spi_init_paramlist(nargs, values, isnull, stmt->param_types);
portal = SPI_cursor_open_with_paramlist(name, stmt->plan, paramLI, readonly);
/*
* If we made our own statement, we didn't save it so it goes away here
* The portal does _not_ go away - it's not tied to SPI.
*/
pllua_spi_exit(L);
}
PLLUA_CATCH_RETHROW();
/*
* Treat the new cursor as ours until told otherwise, but not private
* (caller does that if appropriate)
*/
pllua_cursor_setportal(L, 1, curs, portal, true);
lua_pushvalue(L, 1);
return 1;
}
/*
* s:getcursor(args) returns cursor
*
* Doesn't allow setting the name.
*
* = return spi.newcursor():open(self,args)
*/
static int pllua_spi_stmt_getcursor(lua_State *L)
{
pllua_newcursor(L);
lua_insert(L, 1);
lua_pushcfunction(L, pllua_spi_cursor_open);
lua_insert(L, 1);
lua_call(L, lua_gettop(L) - 1, 1);
return 1;
}
/*
* c:fetch(n [,dir]) -- returns rows
*
* dir = 'forward', 'backward', 'absolute', 'relative'
*/
static FetchDirection pllua_spi_cursor_direction(lua_State *L, int nd)
{
const char *str = luaL_optstring(L, nd, "forward");
switch (*str)
{
case 'f': if (strcmp(str, "forward") == 0) return FETCH_FORWARD; else break;
case 'b': if (strcmp(str, "backward") == 0) return FETCH_BACKWARD; else break;
case 'a': if (strcmp(str, "absolute") == 0) return FETCH_ABSOLUTE; else break;
case 'r': if (strcmp(str, "relative") == 0) return FETCH_RELATIVE; else break;
case 'p': if (strcmp(str, "prior") == 0) return FETCH_BACKWARD; else break;
case 'n': if (strcmp(str, "next") == 0) return FETCH_FORWARD; else break;
}
luaL_error(L, "unknown fetch direction '%s'", str);
}
static int pllua_spi_cursor_fetch(lua_State *L)
{
pllua_spi_cursor *curs = pllua_checkobject(L, 1, PLLUA_SPI_CURSOR_OBJECT);
int64 count = luaL_optinteger(L, 2, 1);
FetchDirection dir = pllua_spi_cursor_direction(L, 3);
if (pllua_ending)
luaL_error(L, "cannot call SPI during shutdown");
if (!curs->portal || !curs->is_live)
luaL_error(L, "attempting to fetch from a closed cursor");
PLLUA_TRY();
{
int64 nrows;
pllua_spi_enter(L);
SPI_scroll_cursor_fetch(curs->portal, dir, count);
nrows = SPI_processed;
if (SPI_tuptable)
{
pllua_pushcfunction(L, pllua_spi_prepare_result);
lua_pushlightuserdata(L, SPI_tuptable);
lua_pushinteger(L, nrows);
pllua_pcall(L, 2, 3, 0);
pllua_spi_save_result(L, nrows);
lua_pop(L, 1);
}
else
lua_pushinteger(L, nrows);
pllua_spi_exit(L);
}
PLLUA_CATCH_RETHROW();
return 1;
}
static int pllua_spi_cursor_move(lua_State *L)
{
pllua_spi_cursor *curs = pllua_checkobject(L, 1, PLLUA_SPI_CURSOR_OBJECT);
int64 count = luaL_optinteger(L, 2, 1);
FetchDirection dir = pllua_spi_cursor_direction(L, 3);
if (pllua_ending)
luaL_error(L, "cannot call SPI during shutdown");
if (!curs->portal || !curs->is_live)
luaL_error(L, "attempting to fetch from a closed cursor");
PLLUA_TRY();
{
int64 nrows;
pllua_spi_enter(L);
SPI_scroll_cursor_move(curs->portal, dir, count);
nrows = SPI_processed;
lua_pushinteger(L, nrows);
pllua_spi_exit(L);
}
PLLUA_CATCH_RETHROW();
return 1;
}
static int pllua_stmt_cursor_ok(lua_State *L)
{
pllua_spi_statement *stmt = *pllua_checkrefobject(L, 1, PLLUA_SPI_STMT_OBJECT);
lua_pushboolean(L, stmt->cursor_plan);
return 1;
}
static int pllua_stmt_numargs(lua_State *L)
{
pllua_spi_statement *stmt = *pllua_checkrefobject(L, 1, PLLUA_SPI_STMT_OBJECT);
lua_pushinteger(L, stmt->nparams);
return 1;
}
static int pllua_stmt_argtype(lua_State *L)
{
pllua_spi_statement *stmt = *pllua_checkrefobject(L, 1, PLLUA_SPI_STMT_OBJECT);
int i = luaL_checkinteger(L, 2);
int nparams = stmt->nparams;
if (i < 1 || i > nparams)
luaL_error(L, "parameter %d out of range", i);
lua_getuservalue(L, 1);
lua_rawgeti(L, -1, i);
return 1;
}
static int pllua_stmt_gc(lua_State *L)
{
void **p = pllua_torefobject(L, 1, PLLUA_SPI_STMT_OBJECT);
pllua_spi_statement *stmt = p ? *p : NULL;
ASSERT_LUA_CONTEXT;
if (!p)
return 0;
*p = NULL;
if (!stmt)
return 0;
PLLUA_TRY();
{
if (stmt->kept && stmt->plan)
SPI_freeplan(stmt->plan);
MemoryContextDelete(stmt->mcxt);
}
PLLUA_CATCH_RETHROW();
return 0;
}
int pllua_cursor_cleanup_portal(lua_State *L)
{
Portal portal = lua_touserdata(L, 1);
lua_rawgetp(L, LUA_REGISTRYINDEX, PLLUA_PORTALS);
lua_pushnil(L);
lua_rawsetp(L, -2, portal);
lua_pop(L, 1);
return 0;
}
static void pllua_cursor_cb(void *arg)
{
pllua_spi_cursor *curs = arg;