-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpg_ladybug.c
More file actions
1358 lines (1209 loc) · 50.1 KB
/
Copy pathpg_ladybug.c
File metadata and controls
1358 lines (1209 loc) · 50.1 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
/*
* pg_ladybug.c
*
* PostgreSQL extension: Cypher query support through the embedded
* Ladybug graph engine (liblbug).
*
* Architecture:
* - ladybug_cypher(text) -> SETOF record
* 1. Create in-memory Ladybug database + connection (compile-time linked)
* 2. ATTACH the current Postgres as a foreign catalog (ladybug.pg_connstr)
* 3. EXPLAIN the Cypher in Ladybug
* 4. Extract the pushed-down SQL from the plan text
* 5. Execute that SQL natively via SPI against local Postgres tables
* 6. Stream rows back as a set-returning function
* - ladybug_sql_query(text) -> SETOF record
* Pure native SPI executor (no Ladybug involvement).
* - ladybug_explain(text) -> text
* Return the raw EXPLAIN plan text from Ladybug.
* - ladybug_pushed_sql(text) -> text
* Return the extracted pushed-down SQL string.
*
* Ladybug is used purely as a Cypher -> SQL compiler; the pushed-down SQL
* is executed natively by PostgreSQL itself.
*
* Build-time linking: pg_ladybug links directly to liblbug.so (-llbug)
* rather than using dlopen(). This is best practice for PG extensions
* and ensures the library is loaded by the PG backend's
*/
#include "postgres.h"
#include "fmgr.h"
#include "funcapi.h"
#include "executor/spi.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/typcache.h"
#include "utils/tuplestore.h"
#include "miscadmin.h" /* DataDir */
#include "catalog/pg_type.h"
#include "access/htup_details.h"
#include "commands/trigger.h"
#include "nodes/execnodes.h"
#include "lib/stringinfo.h"
#include <string.h>
PG_MODULE_MAGIC;
/* ------------------------------------------------------------------ */
/* Forward declarations from ladybug_bridge.c */
/* ------------------------------------------------------------------ */
typedef struct LadybugBridge LadybugBridge;
extern LadybugBridge *ladybug_bridge_acquire(const char **err_msg);
extern char *ladybug_bridge_pushed_sql(LadybugBridge *b, const char *cypher,
const char **err_msg);
extern char *ladybug_bridge_explain(LadybugBridge *b, const char *cypher,
const char **err_msg);
extern char *ladybug_bridge_direct_sql(LadybugBridge *b, const char *sql,
const char **err_msg);
extern bool ladybug_bridge_attach_postgres(LadybugBridge *b,
const char *pg_connstr,
const char **err_msg);
extern int ladybug_bridge_execute_collect(LadybugBridge *b,
const char *query,
TupleDesc tupdesc,
HeapTuple **out_tuples,
const char **err_msg);
extern void ladybug_bridge_release(LadybugBridge *b);
/* ------------------------------------------------------------------ */
/* GUCs */
/* ------------------------------------------------------------------ */
static char *ladybug_pg_connstr = "";
static char *ladybug_storage_path = NULL;
/*
* Default storage path, computed in _PG_init from DataDir.
* The Ladybug engine uses this path for persistent storage of
* its catalog (table/schema metadata, not graph data). The
* bridge tries to initialize at this path and falls back to
* in-memory mode if the path is empty or initialization fails.
*
* Format: <DataDir>/storage.lbdb
*/
#define LADYBUG_DEFAULT_STORAGE_PATH_BUFSIZE 1024
static char ladybug_default_storage_path[LADYBUG_DEFAULT_STORAGE_PATH_BUFSIZE];
/* ------------------------------------------------------------------ */
/* SRF execution context for row streaming */
/* ------------------------------------------------------------------ */
typedef struct LadybugSRFContext
{
TupleDesc tupdesc;
int natts;
int current_row; /* current row index while iterating */
int nrows; /* total rows */
HeapTuple *rows; /* dynamically allocated array of HeapTuples */
} LadybugSRFContext;
/* ------------------------------------------------------------------ */
/* Core: run SQL via SPI and return the SPITupleTable for direct use */
/* Returns the number of rows, or -1 on error. */
/* ------------------------------------------------------------------ */
static int
spi_execute_and_capture(const char *sql,
SPITupleTable **out_tuptable, int *out_ncols)
{
int ret;
ret = SPI_connect();
if (ret != SPI_OK_CONNECT)
ereport(ERROR,
(errmsg("ladybug: SPI_connect failed")));
/* read_only=true because we never execute modifying queries */
ret = SPI_execute(sql, true, 0);
if (ret != SPI_OK_SELECT)
{
SPI_finish();
ereport(ERROR,
(errmsg("ladybug: SPI_execute failed"),
errdetail("SPI status: %d", ret),
errhint("The SQL: %s", sql)));
}
*out_tuptable = SPI_tuptable;
if (out_ncols)
*out_ncols = SPI_tuptable ? SPI_tuptable->tupdesc->natts : 0;
return (int) SPI_processed;
}
/* ------------------------------------------------------------------ */
/* Ensure the bridge has ATTACHed this Postgres (once per backend) */
/* ------------------------------------------------------------------ */
static void
ensure_attached(LadybugBridge *b)
{
const char *connstr = ladybug_pg_connstr;
if (b == NULL)
ereport(ERROR,
(errmsg("ladybug: bridge not available")));
if (connstr == NULL || connstr[0] == '\0')
ereport(ERROR,
(errmsg("ladybug: ladybug.pg_connstr is not set"),
errhint("Set ladybug.pg_connstr to a Postgres connection "
"string for the current database, e.g. "
"'host=localhost port=5432 dbname=mydb user=me'.")));
{
const char *e = NULL;
if (!ladybug_bridge_attach_postgres(b, connstr, &e))
{
if (e)
ereport(ERROR,
(errmsg("ladybug: failed to ATTACH local Postgres"),
errdetail("%s", e)));
else
ereport(ERROR,
(errmsg("ladybug: failed to ATTACH local Postgres")));
/* ereport(ERROR) does not return */
}
}
}
/* ------------------------------------------------------------------ */
/* ladybug_cypher(text) -> SETOF record */
/* ------------------------------------------------------------------ */
PG_FUNCTION_INFO_V1(ladybug_cypher);
Datum
ladybug_cypher(PG_FUNCTION_ARGS)
{
FuncCallContext *funcctx;
LadybugSRFContext *srfctx;
TupleDesc expected_tupdesc;
/* Defense-in-depth: should not be reached because SQL declares STRICT */
if (PG_ARGISNULL(0))
ereport(ERROR,
(errmsg("ladybug.cypher(): NULL argument is not allowed")));
if (SRF_IS_FIRSTCALL())
{
MemoryContext oldcontext;
text *cypher_text = PG_GETARG_TEXT_PP(0);
char *cypher_cstr;
const char *err_msg = NULL;
char *sql;
LadybugBridge *b;
int nrows = 0;
int ncols = 0;
SPITupleTable *tuptable;
funcctx = SRF_FIRSTCALL_INIT();
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
/* Determine the caller's expected tuple descriptor */
if (get_call_result_type(fcinfo, NULL, &expected_tupdesc) != TYPEFUNC_COMPOSITE)
ereport(ERROR,
(errmsg("ladybug.cypher() requires a column definition list"),
errhint("Add an \"AS t(col type, ...)\" clause.")));
BlessTupleDesc(expected_tupdesc);
srfctx = (LadybugSRFContext *) palloc0(sizeof(LadybugSRFContext));
srfctx->tupdesc = expected_tupdesc;
srfctx->natts = expected_tupdesc->natts;
srfctx->current_row = 0;
srfctx->nrows = 0;
funcctx->user_fctx = srfctx;
/* Acquire the Ladybug bridge */
b = ladybug_bridge_acquire(&err_msg);
if (b == NULL)
{
MemoryContextSwitchTo(oldcontext);
if (err_msg)
ereport(ERROR,
(errmsg("ladybug: cannot initialize Ladybug engine"),
errdetail("%s", err_msg)));
else
ereport(ERROR,
(errmsg("ladybug: cannot initialize Ladybug engine")));
}
/* ATTACH local Postgres (idempotent) */
ensure_attached(b);
/* Translate Cypher -> pushed-down SQL */
cypher_cstr = text_to_cstring(cypher_text);
err_msg = NULL;
sql = ladybug_bridge_pushed_sql(b, cypher_cstr, &err_msg);
if (sql != NULL)
{
/* ----------------------------------------------------------------
* Pushdown available: execute the SQL via native SPI on this
* Postgres backend.
* ----------------------------------------------------------------
*/
pfree(cypher_cstr);
/* Execute SQL via SPI and copy all row data into multi-call memory context */
nrows = spi_execute_and_capture(sql, &tuptable, &ncols);
pfree(sql);
srfctx->nrows = nrows;
funcctx->max_calls = nrows;
/*
* Build HeapTuples BEFORE SPI_finish, because SPI_getbinval may
* return pointers into SPI memory that would be freed by SPI_finish.
* Store the Datum representation of each HeapTuple in multi-call ctx.
*/
if (nrows > 0 && tuptable != NULL)
{
TupleDesc spi_tupdesc = tuptable->tupdesc;
int natts = expected_tupdesc->natts;
/* Build column name mapping from SPI result columns to expected.
* Strategy:
* 1. Try exact name match first (column aliases match exactly).
* 2. If no exact match, try suffix match: for SPI columns like
* "k_since", strip the table-prefix part (before '_') and match
* the remainder against the expected name. This handles cases
* where the SQL aliases are prefixed (e.g. "k_since") but the
* expected column name is the bare property name (e.g. "since").
* 3. If still no match, try matching just the bare property name
* from the SPI column (everything after the first '_' or '.').
*/
int *col_map = (int *) palloc(natts * sizeof(int));
for (int a = 0; a < natts; a++)
{
const char *exp_name;
col_map[a] = -1;
exp_name = NameStr(TupleDescAttr(expected_tupdesc, a)->attname);
/* Pass 1: exact match */
for (int b = 0; b < ncols; b++)
{
const char *spi_name = NameStr(TupleDescAttr(spi_tupdesc, b)->attname);
if (strcmp(exp_name, spi_name) == 0)
{
col_map[a] = b;
break;
}
}
/* Pass 2: suffix match - spi_name ends with '_' + exp_name */
if (col_map[a] < 0)
{
size_t exp_len = strlen(exp_name);
for (int b = 0; b < ncols; b++)
{
const char *spi_name = NameStr(TupleDescAttr(spi_tupdesc, b)->attname);
size_t spi_len = strlen(spi_name);
if (spi_len > exp_len + 1 &&
spi_name[spi_len - exp_len - 1] == '_' &&
strcmp(spi_name + spi_len - exp_len, exp_name) == 0)
{
col_map[a] = b;
ereport(WARNING,
(errmsg("ladybug: column \"%s\" matched to \"%s\" by suffix",
exp_name, spi_name)));
break;
}
}
}
/* Pass 3: match bare property name from SPI column */
if (col_map[a] < 0)
{
for (int b = 0; b < ncols; b++)
{
const char *spi_name = NameStr(TupleDescAttr(spi_tupdesc, b)->attname);
const char *underscore = strchr(spi_name, '_');
const char *dot = strchr(spi_name, '.');
const char *sep = (underscore && dot) ?
(underscore < dot ? underscore : dot) :
(underscore ? underscore : dot);
if (sep != NULL && strcmp(sep + 1, exp_name) == 0)
{
col_map[a] = b;
ereport(WARNING,
(errmsg("ladybug: column \"%s\" matched to \"%s\" by bare property name",
exp_name, spi_name)));
break;
}
}
}
/* If still no match, leave col_map[a] = -1 (will yield NULL) */
}
srfctx->rows = (HeapTuple *) palloc(nrows * sizeof(HeapTuple));
for (int i = 0; i < nrows; i++)
{
HeapTuple spi_tup;
Datum *vals;
bool *nls;
HeapTuple ht;
spi_tup = tuptable->vals[i];
vals = (Datum *) palloc(natts * sizeof(Datum));
nls = (bool *) palloc(natts * sizeof(bool));
for (int a = 0; a < natts; a++)
{
int spi_idx;
bool isnull;
spi_idx = col_map[a];
isnull = false;
if (spi_idx >= 0 && spi_idx < ncols)
{
Oid spi_type = TupleDescAttr(spi_tupdesc, spi_idx)->atttypid;
Oid exp_type = TupleDescAttr(expected_tupdesc, a)->atttypid;
if (spi_type == exp_type)
{
vals[a] = SPI_getbinval(spi_tup, spi_tupdesc, spi_idx + 1, &isnull);
}
else
{
/* Type mismatch: convert through text representation */
char *str = SPI_getvalue(spi_tup, spi_tupdesc, spi_idx + 1);
if (str)
{
Oid typioparam, typinput;
int32 typmod;
FmgrInfo finfo;
getTypeInputInfo(exp_type, &typinput, &typioparam);
typmod = TupleDescAttr(expected_tupdesc, a)->atttypmod;
fmgr_info(typinput, &finfo);
vals[a] = InputFunctionCall(&finfo, str, typioparam, typmod);
pfree(str);
}
else
isnull = true;
}
}
else
isnull = true;
nls[a] = isnull;
}
/* Build the heap tuple now, while SPI data is still valid */
ht = heap_form_tuple(expected_tupdesc, vals, nls);
srfctx->rows[i] = ht;
pfree(vals);
pfree(nls);
}
pfree(col_map);
}
SPI_finish();
}
else
{
/* ----------------------------------------------------------------
* No pushdown available (e.g., a query like "RETURN 1" that has
* no SQL to push down, or a complex query the planner chose not
* to push down). Fall back to executing the cypher as-is via
* the Ladybug engine and stream the result rows back as if the
* corresponding native SQL had been executed.
*
* Discard the informational err_msg from pushed_sql; the bridge
* sets it whenever the function returns NULL, regardless of
* whether the cause was "no pushdown" or a real error. Any
* real error will surface again from the direct execution below.
* ----------------------------------------------------------------
*/
HeapTuple *tuples = NULL;
int nrows_lbug;
if (err_msg)
{
pfree((char *) err_msg);
err_msg = NULL;
}
err_msg = NULL;
nrows_lbug = ladybug_bridge_execute_collect(
b, cypher_cstr,
expected_tupdesc,
&tuples, &err_msg);
pfree(cypher_cstr);
if (nrows_lbug < 0)
{
MemoryContextSwitchTo(oldcontext);
if (err_msg)
ereport(ERROR,
(errmsg("ladybug: failed to execute cypher via "
"Ladybug engine (no pushdown SQL was "
"available and direct execution failed)"),
errdetail("%s", err_msg),
errhint("Use ladybug.explain() to inspect the "
"plan, or ladybug.pushed_sql() to see "
"what SQL (if any) the planner would "
"have pushed down.")));
else
ereport(ERROR,
(errmsg("ladybug: failed to execute cypher via "
"Ladybug engine (no pushdown SQL was "
"available and direct execution failed)")));
/* ereport(ERROR) does not return */
}
srfctx->nrows = nrows_lbug;
funcctx->max_calls = nrows_lbug;
/*
* Take ownership of the HeapTuples returned by the bridge.
* They are already palloc'd in the multi-call memory context,
* so they survive until the SRF completes.
*/
srfctx->rows = (HeapTuple *) palloc(nrows_lbug * sizeof(HeapTuple));
for (int i = 0; i < nrows_lbug; i++)
srfctx->rows[i] = tuples[i];
if (tuples != NULL)
pfree(tuples);
}
MemoryContextSwitchTo(oldcontext);
}
funcctx = SRF_PERCALL_SETUP();
srfctx = (LadybugSRFContext *) funcctx->user_fctx;
if (srfctx->current_row < srfctx->nrows)
{
int i = srfctx->current_row;
Datum result = HeapTupleGetDatum(srfctx->rows[i]);
srfctx->current_row++;
SRF_RETURN_NEXT(funcctx, result);
}
SRF_RETURN_DONE(funcctx);
}
/* ------------------------------------------------------------------ */
/* ladybug_sql_query(text) -> SETOF record */
/* Pure native SPI executor (no Ladybug). */
/* ------------------------------------------------------------------ */
PG_FUNCTION_INFO_V1(ladybug_sql_query);
Datum
ladybug_sql_query(PG_FUNCTION_ARGS)
{
FuncCallContext *funcctx;
LadybugSRFContext *srfctx;
TupleDesc expected_tupdesc;
text *query_text;
char *query_cstr;
/* Defense-in-depth: should not be reached because SQL declares STRICT */
if (PG_ARGISNULL(0))
ereport(ERROR,
(errmsg("ladybug.sql_query(): NULL argument is not allowed")));
if (SRF_IS_FIRSTCALL())
{
MemoryContext oldcontext;
int nrows = 0;
int ncols = 0;
SPITupleTable *tuptable;
funcctx = SRF_FIRSTCALL_INIT();
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
if (get_call_result_type(fcinfo, NULL, &expected_tupdesc) != TYPEFUNC_COMPOSITE)
ereport(ERROR,
(errmsg("ladybug.sql_query() requires a column definition list"),
errhint("Add an \"AS t(col type, ...)\" clause.")));
BlessTupleDesc(expected_tupdesc);
srfctx = (LadybugSRFContext *) palloc0(sizeof(LadybugSRFContext));
srfctx->tupdesc = expected_tupdesc;
srfctx->natts = expected_tupdesc->natts;
srfctx->current_row = 0;
srfctx->nrows = 0;
funcctx->user_fctx = srfctx;
funcctx->max_calls = 0;
query_text = PG_GETARG_TEXT_PP(0);
query_cstr = text_to_cstring(query_text);
nrows = spi_execute_and_capture(query_cstr, &tuptable, &ncols);
pfree(query_cstr);
srfctx->nrows = nrows;
funcctx->max_calls = nrows;
/*
* Build HeapTuples BEFORE SPI_finish, because SPI_getbinval may
* return pointers into SPI memory that would be freed by SPI_finish.
*/
if (nrows > 0 && tuptable != NULL)
{
TupleDesc spi_tupdesc = tuptable->tupdesc;
int natts = expected_tupdesc->natts;
/* Build column name mapping from SPI result columns to expected.
* Strategy:
* 1. Try exact name match first (column aliases match exactly).
* 2. If no exact match, try suffix match: for SPI columns like
* "k_since", strip the table-prefix part (before '_') and match
* the remainder against the expected name. This handles cases
* where the SQL aliases are prefixed (e.g. "k_since") but the
* expected column name is the bare property name (e.g. "since").
* 3. If still no match, try matching just the bare property name
* from the SPI column (everything after the first '_' or '.').
*/
int *col_map = (int *) palloc(natts * sizeof(int));
for (int a = 0; a < natts; a++)
{
const char *exp_name;
col_map[a] = -1;
exp_name = NameStr(TupleDescAttr(expected_tupdesc, a)->attname);
/* Pass 1: exact match */
for (int b = 0; b < ncols; b++)
{
const char *spi_name = NameStr(TupleDescAttr(spi_tupdesc, b)->attname);
if (strcmp(exp_name, spi_name) == 0)
{
col_map[a] = b;
break;
}
}
/* Pass 2: suffix match - spi_name ends with '_' + exp_name */
if (col_map[a] < 0)
{
size_t exp_len = strlen(exp_name);
for (int b = 0; b < ncols; b++)
{
const char *spi_name = NameStr(TupleDescAttr(spi_tupdesc, b)->attname);
size_t spi_len = strlen(spi_name);
if (spi_len > exp_len + 1 &&
spi_name[spi_len - exp_len - 1] == '_' &&
strcmp(spi_name + spi_len - exp_len, exp_name) == 0)
{
col_map[a] = b;
ereport(WARNING,
(errmsg("ladybug: column \"%s\" matched to \"%s\" by suffix",
exp_name, spi_name)));
break;
}
}
}
/* Pass 3: match bare property name from SPI column */
if (col_map[a] < 0)
{
for (int b = 0; b < ncols; b++)
{
const char *spi_name = NameStr(TupleDescAttr(spi_tupdesc, b)->attname);
const char *underscore = strchr(spi_name, '_');
const char *dot = strchr(spi_name, '.');
const char *sep = (underscore && dot) ?
(underscore < dot ? underscore : dot) :
(underscore ? underscore : dot);
if (sep != NULL && strcmp(sep + 1, exp_name) == 0)
{
col_map[a] = b;
ereport(WARNING,
(errmsg("ladybug: column \"%s\" matched to \"%s\" by bare property name",
exp_name, spi_name)));
break;
}
}
}
/* If still no match, leave col_map[a] = -1 (will yield NULL) */
}
srfctx->rows = (HeapTuple *) palloc(nrows * sizeof(HeapTuple));
for (int i = 0; i < nrows; i++)
{
HeapTuple spi_tup;
Datum *vals;
bool *nls;
HeapTuple ht;
spi_tup = tuptable->vals[i];
vals = (Datum *) palloc(natts * sizeof(Datum));
nls = (bool *) palloc(natts * sizeof(bool));
for (int a = 0; a < natts; a++)
{
int spi_idx;
bool isnull;
spi_idx = col_map[a];
isnull = false;
if (spi_idx >= 0 && spi_idx < ncols)
{
Oid spi_type = TupleDescAttr(spi_tupdesc, spi_idx)->atttypid;
Oid exp_type = TupleDescAttr(expected_tupdesc, a)->atttypid;
if (spi_type == exp_type)
{
vals[a] = SPI_getbinval(spi_tup, spi_tupdesc, spi_idx + 1, &isnull);
}
else
{
/* Type mismatch: convert through text representation */
char *str = SPI_getvalue(spi_tup, spi_tupdesc, spi_idx + 1);
if (str)
{
Oid typioparam, typinput;
int32 typmod;
FmgrInfo finfo;
getTypeInputInfo(exp_type, &typinput, &typioparam);
typmod = TupleDescAttr(expected_tupdesc, a)->atttypmod;
fmgr_info(typinput, &finfo);
vals[a] = InputFunctionCall(&finfo, str, typioparam, typmod);
pfree(str);
}
else
isnull = true;
}
}
else
isnull = true;
nls[a] = isnull;
}
/* Build the heap tuple now, while SPI data is still valid */
ht = heap_form_tuple(expected_tupdesc, vals, nls);
srfctx->rows[i] = ht;
pfree(vals);
pfree(nls);
}
pfree(col_map);
}
SPI_finish();
MemoryContextSwitchTo(oldcontext);
}
funcctx = SRF_PERCALL_SETUP();
srfctx = (LadybugSRFContext *) funcctx->user_fctx;
if (srfctx->current_row < srfctx->nrows)
{
int i = srfctx->current_row;
Datum result = HeapTupleGetDatum(srfctx->rows[i]);
srfctx->current_row++;
SRF_RETURN_NEXT(funcctx, result);
}
SRF_RETURN_DONE(funcctx);
}
/* ------------------------------------------------------------------ */
/* ladybug_explain(text) -> text */
/* Returns the raw Ladybug EXPLAIN plan text. */
/* ------------------------------------------------------------------ */
PG_FUNCTION_INFO_V1(ladybug_explain);
Datum
ladybug_explain(PG_FUNCTION_ARGS)
{
text *cypher_text;
char *cypher_cstr;
const char *err_msg = NULL;
char *plan_text;
text *result;
LadybugBridge *b;
/* Defense-in-depth: should not be reached because SQL declares STRICT */
if (PG_ARGISNULL(0))
PG_RETURN_NULL();
cypher_text = PG_GETARG_TEXT_PP(0);
b = ladybug_bridge_acquire(&err_msg);
if (b == NULL)
{
if (err_msg)
ereport(ERROR,
(errmsg("ladybug: cannot initialize Ladybug engine"),
errdetail("%s", err_msg)));
else
ereport(ERROR,
(errmsg("ladybug: cannot initialize Ladybug engine")));
}
/* Ensure ATTACH has happened so the planner can resolve tables */
ensure_attached(b);
cypher_cstr = text_to_cstring(cypher_text);
plan_text = ladybug_bridge_explain(b, cypher_cstr, &err_msg);
pfree(cypher_cstr);
if (plan_text == NULL)
{
if (err_msg)
ereport(ERROR,
(errmsg("ladybug: EXPLAIN failed"),
errdetail("%s", err_msg)));
else
ereport(ERROR,
(errmsg("ladybug: EXPLAIN failed")));
}
result = cstring_to_text(plan_text);
pfree(plan_text);
PG_RETURN_TEXT_P(result);
}
/* ------------------------------------------------------------------ */
/* ladybug_pushed_sql(text) -> text */
/* Returns the extracted pushed-down SQL string. */
/* ------------------------------------------------------------------ */
PG_FUNCTION_INFO_V1(ladybug_pushed_sql);
Datum
ladybug_pushed_sql(PG_FUNCTION_ARGS)
{
text *cypher_text;
char *cypher_cstr;
const char *err_msg = NULL;
char *sql;
text *result;
LadybugBridge *b;
/* Defense-in-depth: should not be reached because SQL declares STRICT */
if (PG_ARGISNULL(0))
PG_RETURN_NULL();
cypher_text = PG_GETARG_TEXT_PP(0);
b = ladybug_bridge_acquire(&err_msg);
if (b == NULL)
{
if (err_msg)
ereport(ERROR,
(errmsg("ladybug: cannot initialize Ladybug engine"),
errdetail("%s", err_msg)));
else
ereport(ERROR,
(errmsg("ladybug: cannot initialize Ladybug engine")));
}
/* Ensure ATTACH has happened so the planner can resolve tables */
ensure_attached(b);
cypher_cstr = text_to_cstring(cypher_text);
sql = ladybug_bridge_pushed_sql(b, cypher_cstr, &err_msg);
pfree(cypher_cstr);
if (sql == NULL)
{
if (err_msg)
ereport(ERROR,
(errmsg("ladybug: could not extract pushed-down SQL"),
errdetail("%s", err_msg),
errhint("Use ladybug.explain() to see the full plan.")));
else
ereport(ERROR,
(errmsg("ladybug: could not extract pushed-down SQL")));
}
result = cstring_to_text(sql);
pfree(sql);
PG_RETURN_TEXT_P(result);
}
/* ------------------------------------------------------------------ */
/* Replication: convert a SQL row change to a standard Cypher */
/* CREATE / MERGE / DELETE statement. */
/* */
/* The declarative entry point is ladybug.enable_replication(graph), */
/* which creates a Postgres PUBLICATION (conventional name) and an */
/* AFTER INSERT/UPDATE/DELETE row trigger on each registered node/rel */
/* table. This trigger turns the changed row into a standard Cypher */
/* statement and records it in ladybug._replication_log (the change */
/* stream that the ladybug postgres client consumes as its "subscription". */
/* ------------------------------------------------------------------ */
/*
* Render a single Datum as a Cypher literal. Numeric and boolean values
* are emitted bare; every other value is emitted as a single-quoted Cypher
* string with embedded quotes doubled.
*/
static char *
cypher_literal(Oid typid, Datum val)
{
Oid outfunc;
bool isvarlena;
FmgrInfo finfo;
char *raw;
char *copy;
char typcategory;
bool typispreferred;
getTypeOutputInfo(typid, &outfunc, &isvarlena);
fmgr_info(outfunc, &finfo);
raw = OutputFunctionCall(&finfo, val);
/* Determine the type category (PG18: get_type_category_preferred). */
get_type_category_preferred(typid, &typcategory, &typispreferred);
if (typcategory == TYPCATEGORY_NUMERIC ||
typcategory == TYPCATEGORY_BOOLEAN)
{
copy = pstrdup(raw);
pfree(raw);
return copy;
}
else
{
StringInfoData b;
const char *p;
initStringInfo(&b);
appendStringInfoChar(&b, '\'');
for (p = raw; *p; p++)
{
if (*p == '\'')
appendStringInfoChar(&b, '\'');
appendStringInfoChar(&b, *p);
}
appendStringInfoChar(&b, '\'');
copy = b.data;
pfree(raw);
return copy;
}
}
/*
* Fetch the named column of a row as a Cypher literal. Uses SPI_getbinval
* so the SPI connection must be active when this is called. Returns the
* string "null" when the column is NULL or does not exist.
*/
static char *
row_column_literal(HeapTuple row, TupleDesc td, const char *colname, bool *found)
{
int i;
*found = false;
for (i = 0; i < td->natts; i++)
{
if (strcmp(NameStr(TupleDescAttr(td, i)->attname), colname) == 0)
{
bool isnull;
Datum d;
*found = true;
d = SPI_getbinval(row, td, i + 1, &isnull);
if (isnull)
return pstrdup("null");
return cypher_literal(TupleDescAttr(td, i)->atttypid, d);
}
}
return pstrdup("null");
}
/* Append ", col: literal" for every column of the row. */
static void
append_all_props(StringInfo s, HeapTuple row, TupleDesc td)
{
int i;
for (i = 0; i < td->natts; i++)
{
bool isnull;
Datum d;
char *lit;
if (i > 0)
appendStringInfoString(s, ", ");
d = SPI_getbinval(row, td, i + 1, &isnull);
lit = isnull ? pstrdup("null")
: cypher_literal(TupleDescAttr(td, i)->atttypid, d);
appendStringInfo(s, "%s: %s",
NameStr(TupleDescAttr(td, i)->attname), lit);
pfree(lit);
}
}
/* Append "n.col = literal, ..." (SET clause) for every column except id. */
static void
append_set_items(StringInfo s, HeapTuple row, TupleDesc td,
const char *idcol, const char *var)
{
int i;
bool first = true;
for (i = 0; i < td->natts; i++)
{
const char *name = NameStr(TupleDescAttr(td, i)->attname);
bool isnull;
Datum d;
char *lit;
if (idcol && strcmp(name, idcol) == 0)
continue;
d = SPI_getbinval(row, td, i + 1, &isnull);
lit = isnull ? pstrdup("null")
: cypher_literal(TupleDescAttr(td, i)->atttypid, d);
if (!first)
appendStringInfoString(s, ", ");
appendStringInfo(s, "%s.%s = %s", var, name, lit);
first = false;
pfree(lit);
}
}
/*
* Build the standard Cypher statement for a row change.
* INSERT: CREATE (n:Label {cols...})
* UPDATE: MERGE (n:Label {id: ..}) SET n.col = .., ..
* DELETE: MATCH (n:Label {id: ..}) DELETE n
* For edge (rel) tables the endpoints are matched by their id column and
* the relationship is created/merged between them.
*/
static char *
build_replication_cypher(HeapTuple row, TupleDesc td,
const char *kind, const char *label,
const char *idcol, const char *fromcol,
const char *tocol, char op)
{
StringInfoData s;
bool found;
initStringInfo(&s);
if (strcmp(kind, "edge") == 0)
{
char *f = row_column_literal(row, td, fromcol, &found);
char *t = row_column_literal(row, td, tocol, &found);
char *id = row_column_literal(row, td, idcol, &found);
if (op == 'I')
{
appendStringInfoString(&s, "MATCH (a {id: ");
appendStringInfoString(&s, f);
appendStringInfoString(&s, "}), (b {id: ");
appendStringInfoString(&s, t);
appendStringInfoString(&s, "}) CREATE (a)-[r:");
appendStringInfoString(&s, label);
appendStringInfoString(&s, " {id: ");
appendStringInfoString(&s, id);
appendStringInfoString(&s, ", ");
append_all_props(&s, row, td);
appendStringInfoString(&s, "}]->(b)");
}