forked from sqliteai/sqlite-sync
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcloudsync_postgresql.c
More file actions
2489 lines (2091 loc) · 87.6 KB
/
cloudsync_postgresql.c
File metadata and controls
2489 lines (2091 loc) · 87.6 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
//
// cloudsync_postgresql.c
// cloudsync
//
// Created by Claude Code on 18/12/25.
//
// Define POSIX feature test macros before any includes
#define _POSIX_C_SOURCE 200809L
// PostgreSQL requires postgres.h to be included FIRST
#include "postgres.h"
#include "utils/datum.h"
#include "access/xact.h"
#include "catalog/pg_type.h"
#include "catalog/namespace.h"
#include "executor/spi.h"
#include "utils/lsyscache.h"
#include "utils/array.h"
#include "fmgr.h"
#include "funcapi.h"
#include "pgvalue.h"
#include "storage/ipc.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/hsearch.h"
#include "utils/memutils.h"
#include "utils/uuid.h"
#include "nodes/nodeFuncs.h" // exprTypmod, exprCollation
#include "nodes/pg_list.h" // linitial
#include "nodes/primnodes.h" // FuncExpr
// CloudSync headers (after PostgreSQL headers)
#include "../cloudsync.h"
#include "../database.h"
#include "../dbutils.h"
#include "../pk.h"
#include "../utils.h"
// Note: network.h is not needed for PostgreSQL implementation
PG_MODULE_MAGIC;
// Note: PG_FUNCTION_INFO_V1 macros are declared before each function implementation below
// They should NOT be duplicated here to avoid redefinition errors
#ifndef UNUSED_PARAMETER
#define UNUSED_PARAMETER(X) (void)(X)
#endif
#define CLOUDSYNC_RLS_RESTRICTED_VALUE_BYTEA "E'\\\\x0b095f5f5b524c535d5f5f'::bytea"
#define CLOUDSYNC_NULL_VALUE_BYTEA "E'\\\\x05'::bytea"
// External declaration
Datum database_column_datum (dbvm_t *vm, int index);
// MARK: - Context Management -
// Global context stored per backend
static cloudsync_context *pg_cloudsync_context = NULL;
static void cloudsync_pg_context_init (cloudsync_context *data) {
int spi_rc = SPI_connect();
if (spi_rc != SPI_OK_CONNECT) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed: %d", spi_rc)));
}
PG_TRY();
{
if (cloudsync_config_exists(data)) {
if (cloudsync_context_init(data) == NULL) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("An error occurred while trying to initialize context")));
}
// make sure to update internal version to current version
dbutils_settings_set_key_value(data, CLOUDSYNC_KEY_LIBVERSION, CLOUDSYNC_VERSION);
}
if (SPI_tuptable) {
SPI_freetuptable(SPI_tuptable);
SPI_tuptable = NULL;
}
SPI_finish();
}
PG_CATCH();
{
SPI_finish();
PG_RE_THROW();
}
PG_END_TRY();
}
// Get or create the CloudSync context for this backend
static cloudsync_context *get_cloudsync_context(void) {
if (pg_cloudsync_context == NULL) {
// Create context - db_t is not used in PostgreSQL mode
MemoryContext old = MemoryContextSwitchTo(TopMemoryContext);
cloudsync_context *data = cloudsync_context_create(NULL);
MemoryContextSwitchTo(old);
if (!data) {
ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("Not enough memory to create a database context")));
}
// Set early to prevent infinite recursion: during init, SQL queries may call
// cloudsync_schema() which calls get_cloudsync_context(). Without early assignment,
// each nested call sees NULL and tries to reinitialize, causing stack overflow.
pg_cloudsync_context = data;
PG_TRY();
{
cloudsync_pg_context_init(data);
}
PG_CATCH();
{
pg_cloudsync_context = NULL;
cloudsync_context_free(data);
PG_RE_THROW();
}
PG_END_TRY();
}
return pg_cloudsync_context;
}
// MARK: - Extension Entry Points -
void _PG_init (void) {
// Extension initialization
// SPI will be connected per-function call
elog(DEBUG1, "CloudSync extension loading");
// Initialize memory debugger (NOOP in production)
cloudsync_memory_init(1);
}
void _PG_fini (void) {
// Extension cleanup
elog(DEBUG1, "CloudSync extension unloading");
// Free global context if it exists
if (pg_cloudsync_context) {
cloudsync_context_free(pg_cloudsync_context);
pg_cloudsync_context = NULL;
}
}
// MARK: - Public SQL Functions -
// cloudsync_version() - Returns extension version
PG_FUNCTION_INFO_V1(cloudsync_version);
Datum cloudsync_version (PG_FUNCTION_ARGS) {
UNUSED_PARAMETER(fcinfo);
PG_RETURN_TEXT_P(cstring_to_text(CLOUDSYNC_VERSION));
}
// cloudsync_siteid() - Get site identifier (UUID)
PG_FUNCTION_INFO_V1(pg_cloudsync_siteid);
Datum pg_cloudsync_siteid (PG_FUNCTION_ARGS) {
UNUSED_PARAMETER(fcinfo);
cloudsync_context *data = get_cloudsync_context();
const void *siteid = cloudsync_siteid(data);
if (!siteid) {
PG_RETURN_NULL();
}
// Return as bytea (binary UUID)
bytea *result = (bytea *)palloc(VARHDRSZ + UUID_LEN);
SET_VARSIZE(result, VARHDRSZ + UUID_LEN);
memcpy(VARDATA(result), siteid, UUID_LEN);
PG_RETURN_BYTEA_P(result);
}
// cloudsync_uuid() - Generate a new UUID
PG_FUNCTION_INFO_V1(cloudsync_uuid);
Datum cloudsync_uuid (PG_FUNCTION_ARGS) {
UNUSED_PARAMETER(fcinfo);
uint8_t uuid_bytes[UUID_LEN];
cloudsync_uuid_v7(uuid_bytes);
// Format as text with dashes (matches SQLite implementation)
char uuid_str[UUID_STR_MAXLEN];
cloudsync_uuid_v7_stringify(uuid_bytes, uuid_str, true);
// Parse into PostgreSQL UUID type
Datum uuid_datum = DirectFunctionCall1(uuid_in, CStringGetDatum(uuid_str));
PG_RETURN_DATUM(uuid_datum);
}
// cloudsync_db_version() - Get current database version
PG_FUNCTION_INFO_V1(cloudsync_db_version);
Datum cloudsync_db_version (PG_FUNCTION_ARGS) {
UNUSED_PARAMETER(fcinfo);
cloudsync_context *data = get_cloudsync_context();
int64_t version = 0;
bool spi_connected = false;
// Connect SPI for database operations
int spi_rc = SPI_connect();
if (spi_rc != SPI_OK_CONNECT) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed: %d", spi_rc)));
}
spi_connected = true;
PG_TRY();
{
int rc = cloudsync_dbversion_check_uptodate(data);
if (rc != DBRES_OK) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("Unable to retrieve db_version (%s)", database_errmsg(data))));
}
version = cloudsync_dbversion(data);
}
PG_CATCH();
{
if (spi_connected) SPI_finish();
PG_RE_THROW();
}
PG_END_TRY();
if (spi_connected) SPI_finish();
PG_RETURN_INT64(version);
}
// cloudsync_db_version_next([merging_version]) - Get next database version
PG_FUNCTION_INFO_V1(cloudsync_db_version_next);
Datum cloudsync_db_version_next (PG_FUNCTION_ARGS) {
cloudsync_context *data = get_cloudsync_context();
int64_t next_version = 0;
bool spi_connected = false;
int64_t merging_version = CLOUDSYNC_VALUE_NOTSET;
if (PG_NARGS() == 1 && !PG_ARGISNULL(0)) {
merging_version = PG_GETARG_INT64(0);
}
// Connect SPI for database operations
int spi_rc = SPI_connect();
if (spi_rc != SPI_OK_CONNECT) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed: %d", spi_rc)));
}
spi_connected = true;
PG_TRY();
{
next_version = cloudsync_dbversion_next(data, merging_version);
}
PG_CATCH();
{
if (spi_connected) SPI_finish();
PG_RE_THROW();
}
PG_END_TRY();
if (spi_connected) SPI_finish();
PG_RETURN_INT64(next_version);
}
// MARK: - Table Initialization -
// Internal helper for cloudsync_init - replicates dbsync_init logic from SQLite
// Returns site_id as bytea on success, raises error on failure
static bytea *cloudsync_init_internal (cloudsync_context *data, const char *table, const char *algo, bool skip_int_pk_check) {
bytea *result = NULL;
// Connect SPI for database operations
int spi_rc = SPI_connect();
if (spi_rc != SPI_OK_CONNECT) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed: %d", spi_rc)));
}
PG_TRY();
{
// Begin savepoint for transactional init
int rc = database_begin_savepoint(data, "cloudsync_init");
if (rc != DBRES_OK) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("Unable to create cloudsync_init savepoint: %s", database_errmsg(data))));
}
// Initialize table for sync
rc = cloudsync_init_table(data, table, algo, skip_int_pk_check);
ereport(DEBUG1, (errmsg("cloudsync_init_internal cloudsync_init_table %d", rc)));
if (rc == DBRES_OK) {
rc = database_commit_savepoint(data, "cloudsync_init");
if (rc != DBRES_OK) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("Unable to release cloudsync_init savepoint: %s", database_errmsg(data))));
}
// Persist schema to settings now that the settings table exists
const char *cur_schema = cloudsync_schema(data);
if (cur_schema) {
dbutils_settings_set_key_value(data, "schema", cur_schema);
}
} else {
// In case of error, rollback transaction
char err[1024];
snprintf(err, sizeof(err), "%s", cloudsync_errmsg(data));
database_rollback_savepoint(data, "cloudsync_init");
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("%s", err)));
}
cloudsync_update_schema_hash(data);
// Build site_id as bytea to return
// Use SPI_palloc so the allocation survives SPI_finish
result = (bytea *)SPI_palloc(UUID_LEN + VARHDRSZ);
SET_VARSIZE(result, UUID_LEN + VARHDRSZ);
memcpy(VARDATA(result), cloudsync_siteid(data), UUID_LEN);
SPI_finish();
}
PG_CATCH();
{
SPI_finish();
PG_RE_THROW();
}
PG_END_TRY();
return result;
}
// cloudsync_init(table_name, [algo], [skip_int_pk_check]) - Initialize table for sync
// Supports 1-3 arguments with defaults: algo=NULL, skip_int_pk_check=false
PG_FUNCTION_INFO_V1(cloudsync_init);
Datum cloudsync_init (PG_FUNCTION_ARGS) {
if (PG_ARGISNULL(0)) {
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("table_name cannot be NULL")));
}
const char *table = text_to_cstring(PG_GETARG_TEXT_PP(0));
// Default values
const char *algo = NULL;
bool skip_int_pk_check = false;
// Handle optional arguments
int nargs = PG_NARGS();
if (nargs >= 2 && !PG_ARGISNULL(1)) {
algo = text_to_cstring(PG_GETARG_TEXT_PP(1));
}
if (nargs >= 3 && !PG_ARGISNULL(2)) {
skip_int_pk_check = PG_GETARG_BOOL(2);
}
cloudsync_context *data = get_cloudsync_context();
// Call internal helper and return site_id as bytea
bytea *result = cloudsync_init_internal(data, table, algo, skip_int_pk_check);
PG_RETURN_BYTEA_P(result);
}
// MARK: - Table Enable/Disable Functions -
// Internal helper for enable/disable
static void cloudsync_enable_disable (const char *table_name, bool value) {
cloudsync_context *data = get_cloudsync_context();
cloudsync_table_context *table = table_lookup(data, table_name);
if (table) table_set_enabled(table, value);
}
// cloudsync_enable - Enable sync for a table
PG_FUNCTION_INFO_V1(cloudsync_enable);
Datum cloudsync_enable (PG_FUNCTION_ARGS) {
if (PG_ARGISNULL(0)) {
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("table_name cannot be NULL")));
}
const char *table = text_to_cstring(PG_GETARG_TEXT_PP(0));
cloudsync_enable_disable(table, true);
PG_RETURN_BOOL(true);
}
// cloudsync_disable - Disable sync for a table
PG_FUNCTION_INFO_V1(cloudsync_disable);
Datum cloudsync_disable (PG_FUNCTION_ARGS) {
if (PG_ARGISNULL(0)) {
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("table_name cannot be NULL")));
}
const char *table = text_to_cstring(PG_GETARG_TEXT_PP(0));
cloudsync_enable_disable(table, false);
PG_RETURN_BOOL(true);
}
// cloudsync_is_enabled - Check if table is sync-enabled
PG_FUNCTION_INFO_V1(cloudsync_is_enabled);
Datum cloudsync_is_enabled (PG_FUNCTION_ARGS) {
if (PG_ARGISNULL(0)) {
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("table_name cannot be NULL")));
}
cloudsync_context *data = get_cloudsync_context();
const char *table_name = text_to_cstring(PG_GETARG_TEXT_PP(0));
cloudsync_table_context *table = table_lookup(data, table_name);
bool result = (table && table_enabled(table));
PG_RETURN_BOOL(result);
}
// MARK: - Cleanup and Termination -
// cloudsync_cleanup - Cleanup orphaned metadata for a table
PG_FUNCTION_INFO_V1(pg_cloudsync_cleanup);
Datum pg_cloudsync_cleanup (PG_FUNCTION_ARGS) {
if (PG_ARGISNULL(0)) {
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("table_name cannot be NULL")));
}
const char *table = text_to_cstring(PG_GETARG_TEXT_PP(0));
cloudsync_context *data = get_cloudsync_context();
int rc = DBRES_OK;
bool spi_connected = false;
int spi_rc = SPI_connect();
if (spi_rc != SPI_OK_CONNECT) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed: %d", spi_rc)));
}
spi_connected = true;
PG_TRY();
{
rc = cloudsync_cleanup(data, table);
}
PG_CATCH();
{
if (spi_connected) SPI_finish();
PG_RE_THROW();
}
PG_END_TRY();
if (SPI_tuptable) {
SPI_freetuptable(SPI_tuptable);
SPI_tuptable = NULL;
}
if (spi_connected) SPI_finish();
if (rc != DBRES_OK) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("%s", cloudsync_errmsg(data))));
}
PG_RETURN_BOOL(true);
}
// cloudsync_terminate - Terminate CloudSync
PG_FUNCTION_INFO_V1(pg_cloudsync_terminate);
Datum pg_cloudsync_terminate (PG_FUNCTION_ARGS) {
UNUSED_PARAMETER(fcinfo);
cloudsync_context *data = get_cloudsync_context();
int rc = DBRES_OK;
bool spi_connected = false;
int spi_rc = SPI_connect();
if (spi_rc != SPI_OK_CONNECT) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed: %d", spi_rc)));
}
spi_connected = true;
PG_TRY();
{
rc = cloudsync_terminate(data);
}
PG_CATCH();
{
if (spi_connected) SPI_finish();
PG_RE_THROW();
}
PG_END_TRY();
if (spi_connected) SPI_finish();
PG_RETURN_INT32(rc);
}
// MARK: - Settings Functions -
// cloudsync_set - Set global configuration
PG_FUNCTION_INFO_V1(cloudsync_set);
Datum cloudsync_set (PG_FUNCTION_ARGS) {
const char *key = NULL;
const char *value = NULL;
if (!PG_ARGISNULL(0)) {
key = text_to_cstring(PG_GETARG_TEXT_PP(0));
}
if (!PG_ARGISNULL(1)) {
value = text_to_cstring(PG_GETARG_TEXT_PP(1));
}
// Silently fail if key is NULL (matches SQLite behavior)
if (key == NULL) {
PG_RETURN_BOOL(true);
}
cloudsync_context *data = get_cloudsync_context();
bool spi_connected = false;
int spi_rc = SPI_connect();
if (spi_rc != SPI_OK_CONNECT) {
ereport(ERROR,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("SPI_connect failed: %d", spi_rc)));
}
spi_connected = true;
PG_TRY();
{
dbutils_settings_set_key_value(data, key, value);
}
PG_CATCH();
{
if (spi_connected) SPI_finish();
PG_RE_THROW();
}
PG_END_TRY();
if (spi_connected) SPI_finish();
PG_RETURN_BOOL(true);
}
// cloudsync_set_table - Set table-level configuration
PG_FUNCTION_INFO_V1(cloudsync_set_table);
Datum cloudsync_set_table (PG_FUNCTION_ARGS) {
const char *tbl = NULL;
const char *key = NULL;
const char *value = NULL;
if (!PG_ARGISNULL(0)) {
tbl = text_to_cstring(PG_GETARG_TEXT_PP(0));
}
if (!PG_ARGISNULL(1)) {
key = text_to_cstring(PG_GETARG_TEXT_PP(1));
}
if (!PG_ARGISNULL(2)) {
value = text_to_cstring(PG_GETARG_TEXT_PP(2));
}
cloudsync_context *data = get_cloudsync_context();
bool spi_connected = false;
int spi_rc = SPI_connect();
if (spi_rc != SPI_OK_CONNECT) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed: %d", spi_rc)));
}
spi_connected = true;
PG_TRY();
{
dbutils_table_settings_set_key_value(data, tbl, "*", key, value);
}
PG_CATCH();
{
if (spi_connected) SPI_finish();
PG_RE_THROW();
}
PG_END_TRY();
if (spi_connected) SPI_finish();
PG_RETURN_BOOL(true);
}
// cloudsync_set_column - Set column-level configuration
PG_FUNCTION_INFO_V1(cloudsync_set_column);
Datum cloudsync_set_column (PG_FUNCTION_ARGS) {
const char *tbl = NULL;
const char *col = NULL;
const char *key = NULL;
const char *value = NULL;
if (!PG_ARGISNULL(0)) {
tbl = text_to_cstring(PG_GETARG_TEXT_PP(0));
}
if (!PG_ARGISNULL(1)) {
col = text_to_cstring(PG_GETARG_TEXT_PP(1));
}
if (!PG_ARGISNULL(2)) {
key = text_to_cstring(PG_GETARG_TEXT_PP(2));
}
if (!PG_ARGISNULL(3)) {
value = text_to_cstring(PG_GETARG_TEXT_PP(3));
}
cloudsync_context *data = get_cloudsync_context();
bool spi_connected = false;
int spi_rc = SPI_connect();
if (spi_rc != SPI_OK_CONNECT) {
ereport(ERROR,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("SPI_connect failed: %d", spi_rc)));
}
spi_connected = true;
PG_TRY();
{
dbutils_table_settings_set_key_value(data, tbl, col, key, value);
}
PG_CATCH();
{
if (spi_connected) SPI_finish();
PG_RE_THROW();
}
PG_END_TRY();
if (spi_connected) SPI_finish();
PG_RETURN_BOOL(true);
}
// MARK: - Row Filter -
// cloudsync_set_filter - Set a row-level filter for conditional sync
PG_FUNCTION_INFO_V1(cloudsync_set_filter);
Datum cloudsync_set_filter (PG_FUNCTION_ARGS) {
if (PG_ARGISNULL(0) || PG_ARGISNULL(1)) {
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("cloudsync_set_filter: table and filter expression required")));
}
const char *tbl = text_to_cstring(PG_GETARG_TEXT_PP(0));
const char *filter_expr = text_to_cstring(PG_GETARG_TEXT_PP(1));
cloudsync_context *data = get_cloudsync_context();
bool spi_connected = false;
int spi_rc = SPI_connect();
if (spi_rc != SPI_OK_CONNECT) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed: %d", spi_rc)));
}
spi_connected = true;
PG_TRY();
{
// Store filter in table settings
dbutils_table_settings_set_key_value(data, tbl, "*", "filter", filter_expr);
// Read current algo
table_algo algo = dbutils_table_settings_get_algo(data, tbl);
if (algo == table_algo_none) algo = table_algo_crdt_cls;
// Drop triggers
database_delete_triggers(data, tbl);
// Reconnect SPI so that the catalog changes from DROP are visible
SPI_finish();
spi_connected = false;
spi_rc = SPI_connect();
if (spi_rc != SPI_OK_CONNECT) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed: %d", spi_rc)));
}
spi_connected = true;
// Recreate triggers with filter
int rc = database_create_triggers(data, tbl, algo, filter_expr);
if (rc != DBRES_OK) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR),
errmsg("cloudsync_set_filter: error recreating triggers")));
}
}
PG_CATCH();
{
if (spi_connected) SPI_finish();
PG_RE_THROW();
}
PG_END_TRY();
if (spi_connected) SPI_finish();
PG_RETURN_BOOL(true);
}
// cloudsync_clear_filter - Remove the row-level filter for a table
PG_FUNCTION_INFO_V1(cloudsync_clear_filter);
Datum cloudsync_clear_filter (PG_FUNCTION_ARGS) {
if (PG_ARGISNULL(0)) {
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("cloudsync_clear_filter: table name required")));
}
const char *tbl = text_to_cstring(PG_GETARG_TEXT_PP(0));
cloudsync_context *data = get_cloudsync_context();
bool spi_connected = false;
int spi_rc = SPI_connect();
if (spi_rc != SPI_OK_CONNECT) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed: %d", spi_rc)));
}
spi_connected = true;
PG_TRY();
{
// Remove filter from settings
dbutils_table_settings_set_key_value(data, tbl, "*", "filter", NULL);
// Read current algo
table_algo algo = dbutils_table_settings_get_algo(data, tbl);
if (algo == table_algo_none) algo = table_algo_crdt_cls;
// Drop triggers
database_delete_triggers(data, tbl);
// Reconnect SPI so that the catalog changes from DROP are visible
SPI_finish();
spi_connected = false;
spi_rc = SPI_connect();
if (spi_rc != SPI_OK_CONNECT) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed: %d", spi_rc)));
}
spi_connected = true;
// Recreate triggers without filter
int rc = database_create_triggers(data, tbl, algo, NULL);
if (rc != DBRES_OK) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR),
errmsg("cloudsync_clear_filter: error recreating triggers")));
}
}
PG_CATCH();
{
if (spi_connected) SPI_finish();
PG_RE_THROW();
}
PG_END_TRY();
if (spi_connected) SPI_finish();
PG_RETURN_BOOL(true);
}
// MARK: - Schema Alteration -
// cloudsync_begin_alter - Begin schema alteration
PG_FUNCTION_INFO_V1(pg_cloudsync_begin_alter);
Datum pg_cloudsync_begin_alter (PG_FUNCTION_ARGS) {
if (PG_ARGISNULL(0)) {
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("table_name cannot be NULL")));
}
const char *table_name = text_to_cstring(PG_GETARG_TEXT_PP(0));
cloudsync_context *data = get_cloudsync_context();
int rc = DBRES_OK;
bool spi_connected = false;
int spi_rc = SPI_connect();
if (spi_rc != SPI_OK_CONNECT) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed: %d", spi_rc)));
}
spi_connected = true;
PG_TRY();
{
rc = cloudsync_begin_alter(data, table_name);
}
PG_CATCH();
{
if (spi_connected) SPI_finish();
PG_RE_THROW();
}
PG_END_TRY();
if (spi_connected) SPI_finish();
if (rc != DBRES_OK) {
ereport(ERROR,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("%s", cloudsync_errmsg(data))));
}
PG_RETURN_BOOL(true);
}
// cloudsync_commit_alter - Commit schema alteration
PG_FUNCTION_INFO_V1(pg_cloudsync_commit_alter);
Datum pg_cloudsync_commit_alter (PG_FUNCTION_ARGS) {
if (PG_ARGISNULL(0)) {
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("table_name cannot be NULL")));
}
const char *table_name = text_to_cstring(PG_GETARG_TEXT_PP(0));
cloudsync_context *data = get_cloudsync_context();
int rc = DBRES_OK;
bool spi_connected = false;
int spi_rc = SPI_connect();
if (spi_rc != SPI_OK_CONNECT) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed: %d", spi_rc)));
}
spi_connected = true;
PG_TRY();
{
rc = cloudsync_commit_alter(data, table_name);
}
PG_CATCH();
{
if (spi_connected) SPI_finish();
PG_RE_THROW();
}
PG_END_TRY();
if (spi_connected) SPI_finish();
if (rc != DBRES_OK) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("%s", cloudsync_errmsg(data))));
}
PG_RETURN_BOOL(true);
}
// MARK: - Payload Functions -
// Aggregate function: cloudsync_payload_encode transition function
PG_FUNCTION_INFO_V1(cloudsync_payload_encode_transfn);
Datum cloudsync_payload_encode_transfn (PG_FUNCTION_ARGS) {
MemoryContext aggContext;
cloudsync_payload_context *payload = NULL;
if (!AggCheckCallContext(fcinfo, &aggContext)) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("cloudsync_payload_encode_transfn called in non-aggregate context")));
}
// Get or allocate aggregate state
if (PG_ARGISNULL(0)) {
MemoryContext oldContext = MemoryContextSwitchTo(aggContext);
payload = (cloudsync_payload_context *)cloudsync_memory_alloc(cloudsync_payload_context_size(NULL));
memset(payload, 0, cloudsync_payload_context_size(NULL));
MemoryContextSwitchTo(oldContext);
} else {
payload = (cloudsync_payload_context *)PG_GETARG_POINTER(0);
}
int argc = 0;
cloudsync_context *data = get_cloudsync_context();
pgvalue_t **argv = pgvalues_from_args(fcinfo, 1, &argc);
// Wrap variadic args into pgvalue_t so pk/payload helpers can read types safely.
if (argc > 0) {
int rc = cloudsync_payload_encode_step(payload, data, argc, (dbvalue_t **)argv);
if (rc != DBRES_OK) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("%s", cloudsync_errmsg(data))));
}
}
// payload_encode_step does not retain pgvalue_t*, free transient wrappers now
for (int i = 0; i < argc; i++) {
pgvalue_free(argv[i]);
}
if (argv) cloudsync_memory_free(argv);
PG_RETURN_POINTER(payload);
}
// Aggregate function: cloudsync_payload_encode finalize function
PG_FUNCTION_INFO_V1(cloudsync_payload_encode_finalfn);
Datum cloudsync_payload_encode_finalfn (PG_FUNCTION_ARGS) {
if (PG_ARGISNULL(0)) {
PG_RETURN_NULL();
}
cloudsync_payload_context *payload = (cloudsync_payload_context *)PG_GETARG_POINTER(0);
cloudsync_context *data = get_cloudsync_context();
int rc = cloudsync_payload_encode_final(payload, data);
if (rc != DBRES_OK) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("%s", cloudsync_errmsg(data))));
}
int64_t blob_size = 0;
char *blob = cloudsync_payload_blob(payload, &blob_size, NULL);
if (!blob) {
PG_RETURN_NULL();
}
bytea *result = (bytea *)palloc(VARHDRSZ + blob_size);
SET_VARSIZE(result, VARHDRSZ + blob_size);
memcpy(VARDATA(result), blob, blob_size);
cloudsync_memory_free(blob);
PG_RETURN_BYTEA_P(result);
}
// Payload decode - Apply changes from payload
PG_FUNCTION_INFO_V1(cloudsync_payload_decode);
Datum cloudsync_payload_decode (PG_FUNCTION_ARGS) {
if (PG_ARGISNULL(0)) {
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("payload cannot be NULL")));
}
bytea *payload_data = PG_GETARG_BYTEA_P(0);
int blen = VARSIZE(payload_data) - VARHDRSZ;
// Sanity check payload size
size_t header_size = 0;
cloudsync_payload_context_size(&header_size);
if (blen < (int)header_size) {
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("Invalid payload size")));
}
const char *payload = VARDATA(payload_data);
cloudsync_context *data = get_cloudsync_context();
int rc = DBRES_OK;
int nrows = 0;
bool spi_connected = false;
int spi_rc = SPI_connect();
if (spi_rc != SPI_OK_CONNECT) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("SPI_connect failed: %d", spi_rc)));
}
spi_connected = true;
PG_TRY();
{
rc = cloudsync_payload_apply(data, payload, blen, &nrows);
}
PG_CATCH();
{
if (spi_connected) SPI_finish();
PG_RE_THROW();
}
PG_END_TRY();
if (spi_connected) SPI_finish();
if (rc != DBRES_OK) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("%s", cloudsync_errmsg(data))));
}
PG_RETURN_INT32(nrows);
}
// Alias for payload_decode
PG_FUNCTION_INFO_V1(pg_cloudsync_payload_apply);
Datum pg_cloudsync_payload_apply (PG_FUNCTION_ARGS) {
return cloudsync_payload_decode(fcinfo);
}
// MARK: - Private/Internal Functions -
typedef struct cloudsync_pg_cleanup_state {
char *pk;
char pk_buffer[1024];
pgvalue_t **argv;
int argc;
bool spi_connected;
} cloudsync_pg_cleanup_state;
static void cloudsync_pg_cleanup(int code, Datum arg) {
cloudsync_pg_cleanup_state *state = (cloudsync_pg_cleanup_state *)DatumGetPointer(arg);
if (!state) return;
UNUSED_PARAMETER(code);
if (state->pk && state->pk != state->pk_buffer) {
cloudsync_memory_free(state->pk);
}
state->pk = NULL;
for (int i = 0; i < state->argc; i++) {
pgvalue_free(state->argv[i]);
}
if (state->argv) cloudsync_memory_free(state->argv);
state->argv = NULL;
state->argc = 0;
if (state->spi_connected) {
SPI_finish();
state->spi_connected = false;
}
}
// cloudsync_is_sync - Check if table has sync metadata
PG_FUNCTION_INFO_V1(cloudsync_is_sync);
Datum cloudsync_is_sync (PG_FUNCTION_ARGS) {
cloudsync_context *data = get_cloudsync_context();
if (cloudsync_insync(data)) {
PG_RETURN_BOOL(true);
}
if (PG_ARGISNULL(0)) {
PG_RETURN_BOOL(false);
}
const char *table_name = text_to_cstring(PG_GETARG_TEXT_PP(0));
cloudsync_table_context *table = table_lookup(data, table_name);
bool result = (table && (table_enabled(table) == 0));
PG_RETURN_BOOL(result);
}
typedef struct cloudsync_update_payload {
pgvalue_t *table_name;
pgvalue_t **new_values;
pgvalue_t **old_values;
int count;
int capacity;
MemoryContext mcxt;
// Context-owned callback info for early-exit cleanup.
// We null the payload pointer on normal finalization to avoid double-free.
struct cloudsync_mcxt_cb_info *mcxt_cb_info;
} cloudsync_update_payload;
static void cloudsync_update_payload_free (cloudsync_update_payload *payload);