forked from sqliteai/sqlite-sync
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase_postgresql.c
More file actions
2780 lines (2317 loc) · 95.2 KB
/
database_postgresql.c
File metadata and controls
2780 lines (2317 loc) · 95.2 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
//
// database_postgresql.c
// cloudsync
//
// Created by Marco Bambini on 03/12/25.
//
// PostgreSQL requires postgres.h to be included FIRST
// It sets up the entire environment including platform compatibility
#include "postgres.h"
#include <inttypes.h>
#include <stdlib.h>
#include <string.h>
#include "../cloudsync.h"
#include "../database.h"
#include "../dbutils.h"
#include "../sql.h"
#include "../utils.h"
// PostgreSQL SPI and other headers
#include "access/xact.h"
#include "catalog/pg_type.h"
#include "executor/spi.h"
#include "funcapi.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/snapmgr.h"
#include "pgvalue.h"
// ============================================================================
// SPI CONNECTION REQUIREMENTS
// ============================================================================
//
// IMPORTANT: This implementation requires an active SPI connection to function.
// The Extension Function that calls these functions MUST:
//
// 1. Call SPI_connect() before using any database functions
// 2. Call SPI_finish() before returning from the extension function
//
// ============================================================================
// MARK: - PREPARED STATEMENTS -
// PostgreSQL SPI handles require knowing parameter count and types upfront.
// Solution: Defer actual SPI_prepare until first step(), after all bindings are set.
#define MAX_PARAMS 32
typedef struct {
// Prepared plan
SPIPlanPtr plan;
bool plan_is_prepared;
// Cursor execution
Portal portal; // owned by statement
bool portal_open;
// Current fetched batch (we fetch 1 row at a time, but SPI still returns a tuptable)
SPITupleTable *last_tuptable; // must SPI_freetuptable() before next fetch
HeapTuple current_tuple;
TupleDesc current_tupdesc;
// Params
int nparams;
Oid types[MAX_PARAMS];
Datum values[MAX_PARAMS];
char nulls[MAX_PARAMS];
bool executed_nonselect; // non-select executed already
// Memory
MemoryContext stmt_mcxt; // lifetime = pg_stmt_t
MemoryContext bind_mcxt; // resettable region for parameters (cleared on clear_bindings/reset)
MemoryContext row_mcxt; // per-row scratch (cleared each step after consumer copies)
// Context
const char *sql;
cloudsync_context *data;
} pg_stmt_t;
static int database_refresh_snapshot (void);
// MARK: - SQL -
static char *sql_escape_character (const char *name, char *buffer, size_t bsize, char c) {
if (!name || !buffer || bsize < 1) {
if (buffer && bsize > 0) buffer[0] = '\0';
return NULL;
}
size_t i = 0, j = 0;
while (name[i]) {
if (name[i] == c) {
// Need space for 2 chars (escaped c) + null
if (j >= bsize - 2) {
elog(WARNING, "Identifier name too long for buffer, truncated: %s", name);
break;
}
buffer[j++] = c;
buffer[j++] = c;
} else {
// Need space for 1 char + null
if (j >= bsize - 1) {
elog(WARNING, "Identifier name too long for buffer, truncated: %s", name);
break;
}
buffer[j++] = name[i];
}
i++;
}
buffer[j] = '\0';
return buffer;
}
static char *sql_escape_identifier (const char *name, char *buffer, size_t bsize) {
// PostgreSQL identifier escaping: double any embedded double quotes
// Does NOT add surrounding quotes (caller's responsibility)
// Similar to SQLite's %q behavior for escaping
return sql_escape_character(name, buffer, bsize, '"');
}
static char *sql_escape_literal (const char *name, char *buffer, size_t bsize) {
// Escapes single quotes for use inside SQL string literals: ' → ''
// Does NOT add surrounding quotes (caller's responsibility)
return sql_escape_character(name, buffer, bsize, '\'');
}
char *sql_build_drop_table (const char *table_name, char *buffer, int bsize, bool is_meta) {
// Escape the table name (doubles any embedded quotes)
char escaped[512];
sql_escape_identifier(table_name, escaped, sizeof(escaped));
// Add the surrounding quotes in the format string
if (is_meta) {
snprintf(buffer, bsize, "DROP TABLE IF EXISTS \"%s_cloudsync\";", escaped);
} else {
snprintf(buffer, bsize, "DROP TABLE IF EXISTS \"%s\";", escaped);
}
return buffer;
}
char *sql_build_select_nonpk_by_pk (cloudsync_context *data, const char *table_name, const char *schema) {
UNUSED_PARAMETER(data);
char *qualified = database_build_base_ref(schema, table_name);
if (!qualified) return NULL;
char *sql = cloudsync_memory_mprintf(SQL_BUILD_SELECT_NONPK_COLS_BY_PK, qualified);
cloudsync_memory_free(qualified);
if (!sql) return NULL;
char *query = NULL;
int rc = database_select_text(data, sql, &query);
cloudsync_memory_free(sql);
return (rc == DBRES_OK) ? query : NULL;
}
char *sql_build_delete_by_pk (cloudsync_context *data, const char *table_name, const char *schema) {
UNUSED_PARAMETER(data);
char *qualified = database_build_base_ref(schema, table_name);
if (!qualified) return NULL;
char *sql = cloudsync_memory_mprintf(SQL_BUILD_DELETE_ROW_BY_PK, qualified);
cloudsync_memory_free(qualified);
if (!sql) return NULL;
char *query = NULL;
int rc = database_select_text(data, sql, &query);
cloudsync_memory_free(sql);
return (rc == DBRES_OK) ? query : NULL;
}
char *sql_build_insert_pk_ignore (cloudsync_context *data, const char *table_name, const char *schema) {
UNUSED_PARAMETER(data);
char *qualified = database_build_base_ref(schema, table_name);
if (!qualified) return NULL;
char *sql = cloudsync_memory_mprintf(SQL_BUILD_INSERT_PK_IGNORE, qualified);
cloudsync_memory_free(qualified);
if (!sql) return NULL;
char *query = NULL;
int rc = database_select_text(data, sql, &query);
cloudsync_memory_free(sql);
return (rc == DBRES_OK) ? query : NULL;
}
char *sql_build_upsert_pk_and_col (cloudsync_context *data, const char *table_name, const char *colname, const char *schema) {
UNUSED_PARAMETER(data);
char *qualified = database_build_base_ref(schema, table_name);
if (!qualified) return NULL;
char *sql = cloudsync_memory_mprintf(SQL_BUILD_UPSERT_PK_AND_COL, qualified, colname);
cloudsync_memory_free(qualified);
if (!sql) return NULL;
char *query = NULL;
int rc = database_select_text(data, sql, &query);
cloudsync_memory_free(sql);
return (rc == DBRES_OK) ? query : NULL;
}
char *sql_build_select_cols_by_pk (cloudsync_context *data, const char *table_name, const char *colname, const char *schema) {
UNUSED_PARAMETER(data);
char *qualified = database_build_base_ref(schema, table_name);
if (!qualified) return NULL;
char *sql = cloudsync_memory_mprintf(SQL_BUILD_SELECT_COLS_BY_PK_FMT, qualified, colname);
cloudsync_memory_free(qualified);
if (!sql) return NULL;
char *query = NULL;
int rc = database_select_text(data, sql, &query);
cloudsync_memory_free(sql);
return (rc == DBRES_OK) ? query : NULL;
}
char *sql_build_rekey_pk_and_reset_version_except_col (cloudsync_context *data, const char *table_name, const char *except_col) {
char *meta_ref = database_build_meta_ref(cloudsync_schema(data), table_name);
if (!meta_ref) return NULL;
char *result = cloudsync_memory_mprintf(SQL_CLOUDSYNC_REKEY_PK_AND_RESET_VERSION_EXCEPT_COL, meta_ref, except_col, meta_ref, meta_ref, except_col);
cloudsync_memory_free(meta_ref);
return result;
}
char *database_table_schema (const char *table_name) {
if (!table_name) return NULL;
// Build metadata table name
char meta_table[256];
snprintf(meta_table, sizeof(meta_table), "%s_cloudsync", table_name);
// Query system catalogs to find the schema of the metadata table.
// Rationale: The metadata table is created in the same schema as the base table,
// so finding its location tells us which schema the table belongs to.
const char *query =
"SELECT n.nspname "
"FROM pg_class c "
"JOIN pg_namespace n ON c.relnamespace = n.oid "
"WHERE c.relname = $1 "
"AND c.relkind = 'r'"; // 'r' = ordinary table
char *schema = NULL;
if (SPI_connect() != SPI_OK_CONNECT) {
return NULL;
}
Oid argtypes[1] = {TEXTOID};
Datum values[1] = {CStringGetTextDatum(meta_table)};
char nulls[1] = {' '};
int rc = SPI_execute_with_args(query, 1, argtypes, values, nulls, true, 1);
if (rc == SPI_OK_SELECT && SPI_processed > 0) {
TupleDesc tupdesc = SPI_tuptable->tupdesc;
HeapTuple tuple = SPI_tuptable->vals[0];
bool isnull;
Datum datum = SPI_getbinval(tuple, tupdesc, 1, &isnull);
if (!isnull) {
// pg_namespace.nspname is type 'name', not 'text'
Name nspname = DatumGetName(datum);
schema = cloudsync_string_dup(NameStr(*nspname));
}
}
if (SPI_tuptable) {
SPI_freetuptable(SPI_tuptable);
}
pfree(DatumGetPointer(values[0]));
SPI_finish();
// Returns NULL if metadata table doesn't exist yet (during initialization).
// Caller should fall back to cloudsync_schema() in this case.
return schema;
}
char *database_build_meta_ref (const char *schema, const char *table_name) {
char escaped_table[512];
sql_escape_identifier(table_name, escaped_table, sizeof(escaped_table));
if (schema) {
char escaped_schema[512];
sql_escape_identifier(schema, escaped_schema, sizeof(escaped_schema));
return cloudsync_memory_mprintf("\"%s\".\"%s_cloudsync\"", escaped_schema, escaped_table);
}
return cloudsync_memory_mprintf("\"%s_cloudsync\"", escaped_table);
}
char *database_build_base_ref (const char *schema, const char *table_name) {
char escaped_table[512];
sql_escape_identifier(table_name, escaped_table, sizeof(escaped_table));
if (schema) {
char escaped_schema[512];
sql_escape_identifier(schema, escaped_schema, sizeof(escaped_schema));
return cloudsync_memory_mprintf("\"%s\".\"%s\"", escaped_schema, escaped_table);
}
return cloudsync_memory_mprintf("\"%s\"", escaped_table);
}
// Schema-aware SQL builder for PostgreSQL: deletes columns not in schema or pkcol.
// Schema parameter: pass empty string to fall back to current_schema() via SQL.
char *sql_build_delete_cols_not_in_schema_query (const char *schema, const char *table_name, const char *meta_ref, const char *pkcol) {
const char *schema_param = schema ? schema : "";
char esc_table[1024], esc_schema[1024];
sql_escape_literal(table_name, esc_table, sizeof(esc_table));
sql_escape_literal(schema_param, esc_schema, sizeof(esc_schema));
return cloudsync_memory_mprintf(
"DELETE FROM %s WHERE col_name NOT IN ("
"SELECT column_name FROM information_schema.columns WHERE table_name = '%s' "
"AND table_schema = COALESCE(NULLIF('%s', ''), current_schema()) "
"UNION SELECT '%s'"
");",
meta_ref, esc_table, esc_schema, pkcol
);
}
// Builds query to get comma-separated list of primary key column names.
char *sql_build_pk_collist_query (const char *schema, const char *table_name) {
const char *schema_param = schema ? schema : "";
char esc_table[1024], esc_schema[1024];
sql_escape_literal(table_name, esc_table, sizeof(esc_table));
sql_escape_literal(schema_param, esc_schema, sizeof(esc_schema));
return cloudsync_memory_mprintf(
"SELECT string_agg(quote_ident(column_name), ',') "
"FROM information_schema.key_column_usage "
"WHERE table_name = '%s' AND table_schema = COALESCE(NULLIF('%s', ''), current_schema()) "
"AND constraint_name LIKE '%%_pkey';",
esc_table, esc_schema
);
}
// Builds query to get SELECT list of decoded primary key columns.
char *sql_build_pk_decode_selectlist_query (const char *schema, const char *table_name) {
const char *schema_param = schema ? schema : "";
char esc_table[1024], esc_schema[1024];
sql_escape_literal(table_name, esc_table, sizeof(esc_table));
sql_escape_literal(schema_param, esc_schema, sizeof(esc_schema));
return cloudsync_memory_mprintf(
"SELECT string_agg("
"'cloudsync_pk_decode(pk, ' || ordinal_position || ') AS ' || quote_ident(column_name), ',' ORDER BY ordinal_position"
") "
"FROM information_schema.key_column_usage "
"WHERE table_name = '%s' AND table_schema = COALESCE(NULLIF('%s', ''), current_schema()) "
"AND constraint_name LIKE '%%_pkey';",
esc_table, esc_schema
);
}
// Builds query to get qualified (schema.table.column) primary key column list.
char *sql_build_pk_qualified_collist_query (const char *schema, const char *table_name) {
const char *schema_param = schema ? schema : "";
char esc_table[1024], esc_schema[1024];
sql_escape_literal(table_name, esc_table, sizeof(esc_table));
sql_escape_literal(schema_param, esc_schema, sizeof(esc_schema));
return cloudsync_memory_mprintf(
"SELECT string_agg(quote_ident(column_name), ',' ORDER BY ordinal_position) "
"FROM information_schema.key_column_usage "
"WHERE table_name = '%s' AND table_schema = COALESCE(NULLIF('%s', ''), current_schema()) "
"AND constraint_name LIKE '%%_pkey';", esc_table, esc_schema
);
}
char *sql_build_insert_missing_pks_query(const char *schema, const char *table_name,
const char *pkvalues_identifiers,
const char *base_ref, const char *meta_ref) {
UNUSED_PARAMETER(schema);
char esc_table[1024];
sql_escape_literal(table_name, esc_table, sizeof(esc_table));
// PostgreSQL: Use NOT EXISTS with cloudsync_pk_encode to avoid EXCEPT type mismatch.
//
// CRITICAL: Pass PK columns directly to VARIADIC functions (NOT wrapped in ARRAY[]).
// This preserves each column's actual type (TEXT, INTEGER, etc.) for correct pk_encode.
// Using ARRAY[] would require all elements to be the same type, causing errors with
// mixed-type composite PKs (e.g., TEXT + INTEGER).
//
// Example: cloudsync_insert('table', col1, col2) where col1=TEXT, col2=INTEGER
// PostgreSQL's VARIADIC handling preserves each type and matches SQLite's encoding.
return cloudsync_memory_mprintf(
"SELECT cloudsync_insert('%s', %s) "
"FROM %s b "
"WHERE NOT EXISTS ("
" SELECT 1 FROM %s m WHERE m.pk = cloudsync_pk_encode(%s)"
");",
esc_table, pkvalues_identifiers, base_ref, meta_ref, pkvalues_identifiers
);
}
// MARK: - HELPER FUNCTIONS -
// Map SPI result codes to DBRES
static int map_spi_result (int rc) {
switch (rc) {
case SPI_OK_SELECT:
case SPI_OK_INSERT:
case SPI_OK_UPDATE:
case SPI_OK_DELETE:
case SPI_OK_UTILITY:
return DBRES_OK;
case SPI_OK_INSERT_RETURNING:
case SPI_OK_UPDATE_RETURNING:
case SPI_OK_DELETE_RETURNING:
return DBRES_ROW;
default:
return DBRES_ERROR;
}
}
static void clear_fetch_batch (pg_stmt_t *stmt) {
if (!stmt) return;
if (stmt->last_tuptable) {
SPI_freetuptable(stmt->last_tuptable);
stmt->last_tuptable = NULL;
}
stmt->current_tuple = NULL;
stmt->current_tupdesc = NULL;
if (stmt->row_mcxt) MemoryContextReset(stmt->row_mcxt);
}
static void close_portal (pg_stmt_t *stmt) {
if (!stmt) return;
// Always clear portal_open first to maintain consistent state
stmt->portal_open = false;
if (!stmt->portal) return;
PG_TRY();
{
SPI_cursor_close(stmt->portal);
}
PG_CATCH();
{
// Log but don't throw - we're cleaning up
FlushErrorState();
}
PG_END_TRY();
stmt->portal = NULL;
}
static inline Datum get_datum (pg_stmt_t *stmt, int col /* 0-based */, bool *isnull, Oid *type) {
if (!stmt || !stmt->current_tuple || !stmt->current_tupdesc) {
if (isnull) *isnull = true;
if (type) *type = 0;
return (Datum) 0;
}
if (type) *type = SPI_gettypeid(stmt->current_tupdesc, col + 1);
return SPI_getbinval(stmt->current_tuple, stmt->current_tupdesc, col + 1, isnull);
}
// MARK: - PRIVATE -
int database_select1_value (cloudsync_context *data, const char *sql, char **ptr_value, int64_t *int_value, DBTYPE expected_type) {
cloudsync_reset_error(data);
// init values and sanity check expected_type
if (ptr_value) *ptr_value = NULL;
if (int_value) *int_value = 0;
if (expected_type != DBTYPE_INTEGER && expected_type != DBTYPE_TEXT && expected_type != DBTYPE_BLOB) {
return cloudsync_set_error(data, "Invalid expected_type", DBRES_MISUSE);
}
int rc = SPI_execute(sql, true, 0);
if (rc < 0) {
rc = cloudsync_set_error(data, "SPI_execute failed in database_select1_value", DBRES_ERROR);
goto cleanup;
}
// ensure at least one column
if (!SPI_tuptable || !SPI_tuptable->tupdesc) {
rc = cloudsync_set_error(data, "No result table", DBRES_ERROR);
goto cleanup;
}
if (SPI_tuptable->tupdesc->natts < 1) {
rc = cloudsync_set_error(data, "No columns in result", DBRES_ERROR);
goto cleanup;
}
// no rows OK
if (SPI_processed == 0) {
rc = DBRES_OK;
goto cleanup;
}
HeapTuple tuple = SPI_tuptable->vals[0];
bool isnull;
Datum datum = SPI_getbinval(tuple, SPI_tuptable->tupdesc, 1, &isnull);
// NULL value is OK
if (isnull) {
rc = DBRES_OK;
goto cleanup;
}
// Get type info
Oid typeid = SPI_gettypeid(SPI_tuptable->tupdesc, 1);
if (expected_type == DBTYPE_INTEGER) {
switch (typeid) {
case INT2OID:
*int_value = (int64_t)DatumGetInt16(datum);
break;
case INT4OID:
*int_value = (int64_t)DatumGetInt32(datum);
break;
case INT8OID:
*int_value = DatumGetInt64(datum);
break;
default:
rc = cloudsync_set_error(data, "Type mismatch: expected integer", DBRES_ERROR);
goto cleanup;
}
} else if (expected_type == DBTYPE_TEXT) {
char *val = SPI_getvalue(tuple, SPI_tuptable->tupdesc, 1);
if (val) {
size_t len = strlen(val);
char *ptr = cloudsync_memory_alloc(len + 1);
if (!ptr) {
pfree(val);
rc = cloudsync_set_error(data, "Memory allocation failed", DBRES_NOMEM);
goto cleanup;
}
memcpy(ptr, val, len);
ptr[len] = '\0';
if (ptr_value) *ptr_value = ptr;
if (int_value) *int_value = (int64_t)len;
pfree(val);
}
} else if (expected_type == DBTYPE_BLOB) {
bytea *ba = DatumGetByteaP(datum);
int len = VARSIZE(ba) - VARHDRSZ;
if (len > 0) {
char *ptr = cloudsync_memory_alloc(len);
if (!ptr) {
rc = cloudsync_set_error(data, "Memory allocation failed", DBRES_NOMEM);
goto cleanup;
}
memcpy(ptr, VARDATA(ba), len);
if (ptr_value) *ptr_value = ptr;
if (int_value) *int_value = len;
}
}
rc = DBRES_OK;
cleanup:
if (SPI_tuptable) SPI_freetuptable(SPI_tuptable);
return rc;
}
int database_select3_values (cloudsync_context *data, const char *sql, char **value, int64_t *len, int64_t *value2, int64_t *value3) {
cloudsync_reset_error(data);
// init values
*value = NULL;
*value2 = 0;
*value3 = 0;
*len = 0;
int rc = SPI_execute(sql, true, 0);
if (rc < 0) {
rc = cloudsync_set_error(data, "SPI_execute failed in database_select3_values", DBRES_ERROR);
goto cleanup;
}
if (!SPI_tuptable || !SPI_tuptable->tupdesc) {
rc = cloudsync_set_error(data, "No result table in database_select3_values", DBRES_ERROR);
goto cleanup;
}
if (SPI_tuptable->tupdesc->natts < 3) {
rc = cloudsync_set_error(data, "Result has fewer than 3 columns in database_select3_values", DBRES_ERROR);
goto cleanup;
}
if (SPI_processed == 0) {
rc = DBRES_OK;
goto cleanup;
}
HeapTuple tuple = SPI_tuptable->vals[0];
bool isnull;
// First column - text/blob
Datum datum1 = SPI_getbinval(tuple, SPI_tuptable->tupdesc, 1, &isnull);
if (!isnull) {
Oid typeid = SPI_gettypeid(SPI_tuptable->tupdesc, 1);
if (typeid == BYTEAOID) {
bytea *ba = DatumGetByteaP(datum1);
int blob_len = VARSIZE(ba) - VARHDRSZ;
if (blob_len > 0) {
char *ptr = cloudsync_memory_alloc(blob_len);
if (!ptr) {
rc = DBRES_NOMEM;
goto cleanup;
}
memcpy(ptr, VARDATA(ba), blob_len);
*value = ptr;
*len = blob_len;
}
} else {
text *txt = DatumGetTextP(datum1);
int text_len = VARSIZE(txt) - VARHDRSZ;
if (text_len > 0) {
char *ptr = cloudsync_memory_alloc(text_len + 1);
if (!ptr) {
rc = DBRES_NOMEM;
goto cleanup;
}
memcpy(ptr, VARDATA(txt), text_len);
ptr[text_len] = '\0';
*value = ptr;
*len = text_len;
}
}
}
// Second column - int
Datum datum2 = SPI_getbinval(tuple, SPI_tuptable->tupdesc, 2, &isnull);
if (!isnull) {
Oid typeid = SPI_gettypeid(SPI_tuptable->tupdesc, 2);
if (typeid == INT8OID) {
*value2 = DatumGetInt64(datum2);
} else if (typeid == INT4OID) {
*value2 = (int64_t)DatumGetInt32(datum2);
}
}
// Third column - int
Datum datum3 = SPI_getbinval(tuple, SPI_tuptable->tupdesc, 3, &isnull);
if (!isnull) {
Oid typeid = SPI_gettypeid(SPI_tuptable->tupdesc, 3);
if (typeid == INT8OID) {
*value3 = DatumGetInt64(datum3);
} else if (typeid == INT4OID) {
*value3 = (int64_t)DatumGetInt32(datum3);
}
}
rc = DBRES_OK;
cleanup:
if (SPI_tuptable) SPI_freetuptable(SPI_tuptable);
return rc;
}
static bool database_system_exists (cloudsync_context *data, const char *name, const char *type, bool force_public, const char *schema) {
if (!name || !type) return false;
cloudsync_reset_error(data);
bool exists = false;
const char *query;
// Schema parameter: pass empty string to fall back to current_schema() via SQL
const char *schema_param = (schema && schema[0]) ? schema : "";
if (strcmp(type, "table") == 0) {
if (force_public) {
query = "SELECT 1 FROM pg_tables WHERE schemaname = 'public' AND tablename = $1";
} else {
query = "SELECT 1 FROM pg_tables WHERE schemaname = COALESCE(NULLIF($2, ''), current_schema()) AND tablename = $1";
}
} else if (strcmp(type, "trigger") == 0) {
query = "SELECT 1 FROM pg_trigger WHERE tgname = $1";
} else {
return false;
}
bool need_schema_param = !force_public && strcmp(type, "trigger") != 0;
Datum datum_name = CStringGetTextDatum(name);
Datum datum_schema = need_schema_param ? CStringGetTextDatum(schema_param) : (Datum)0;
MemoryContext oldcontext = CurrentMemoryContext;
PG_TRY();
{
if (!need_schema_param) {
// force_public or trigger: only need table/trigger name parameter
Oid argtypes[1] = {TEXTOID};
Datum values[1] = {datum_name};
char nulls[1] = {' '};
int rc = SPI_execute_with_args(query, 1, argtypes, values, nulls, true, 0);
exists = (rc >= 0 && SPI_processed > 0);
if (SPI_tuptable) SPI_freetuptable(SPI_tuptable);
} else {
// table with schema parameter
Oid argtypes[2] = {TEXTOID, TEXTOID};
Datum values[2] = {datum_name, datum_schema};
char nulls[2] = {' ', ' '};
int rc = SPI_execute_with_args(query, 2, argtypes, values, nulls, true, 0);
exists = (rc >= 0 && SPI_processed > 0);
if (SPI_tuptable) SPI_freetuptable(SPI_tuptable);
}
}
PG_CATCH();
{
MemoryContextSwitchTo(oldcontext);
ErrorData *edata = CopyErrorData();
cloudsync_set_error(data, edata->message, DBRES_ERROR);
FreeErrorData(edata);
FlushErrorState();
exists = false;
}
PG_END_TRY();
pfree(DatumGetPointer(datum_name));
if (need_schema_param) pfree(DatumGetPointer(datum_schema));
elog(DEBUG1, "database_system_exists %s: %d", name, exists);
return exists;
}
// MARK: - GENERAL -
int database_exec (cloudsync_context *data, const char *sql) {
if (!sql) return cloudsync_set_error(data, "SQL statement is NULL", DBRES_ERROR);
cloudsync_reset_error(data);
int rc;
bool is_error = false;
MemoryContext oldcontext = CurrentMemoryContext;
PG_TRY();
{
rc = SPI_execute(sql, false, 0);
if (SPI_tuptable) {
SPI_freetuptable(SPI_tuptable);
}
}
PG_CATCH();
{
MemoryContextSwitchTo(oldcontext);
ErrorData *edata = CopyErrorData();
rc = cloudsync_set_error(data, edata->message, DBRES_ERROR);
FreeErrorData(edata);
FlushErrorState();
if (SPI_tuptable) {
SPI_freetuptable(SPI_tuptable);
}
is_error = true;
}
PG_END_TRY();
if (is_error) return rc;
// Increment command counter to make changes visible
if (rc >= 0) {
database_refresh_snapshot();
return map_spi_result(rc);
}
return cloudsync_set_error(data, "SPI_execute failed", DBRES_ERROR);
}
int database_exec_callback (cloudsync_context *data, const char *sql, int (*callback)(void *xdata, int argc, char **values, char **names), void *xdata) {
if (!sql) return cloudsync_set_error(data, "SQL statement is NULL", DBRES_ERROR);
cloudsync_reset_error(data);
int rc;
bool is_error = false;
MemoryContext oldcontext = CurrentMemoryContext;
PG_TRY();
{
rc = SPI_execute(sql, true, 0);
}
PG_CATCH();
{
MemoryContextSwitchTo(oldcontext);
ErrorData *edata = CopyErrorData();
rc = cloudsync_set_error(data, edata->message, DBRES_ERROR);
FreeErrorData(edata);
FlushErrorState();
is_error = true;
}
PG_END_TRY();
if (is_error) return rc;
if (rc < 0) return cloudsync_set_error(data, "SPI_execute failed", DBRES_ERROR);
// Call callback for each row if provided
if (callback && SPI_tuptable) {
TupleDesc tupdesc = SPI_tuptable->tupdesc;
if (!tupdesc) {
SPI_freetuptable(SPI_tuptable);
return cloudsync_set_error(data, "Invalid tuple descriptor", DBRES_ERROR);
}
int ncols = tupdesc->natts;
if (ncols <= 0) {
SPI_freetuptable(SPI_tuptable);
return DBRES_OK;
}
// IMPORTANT: Save SPI state before any callback can modify it.
// Callbacks may execute SPI queries which overwrite global SPI_tuptable.
// We must copy all data we need BEFORE calling any callbacks.
uint64 nrows = SPI_processed;
SPITupleTable *saved_tuptable = SPI_tuptable;
// No rows to process - free tuptable and return success
if (nrows == 0) {
SPI_freetuptable(saved_tuptable);
return DBRES_OK;
}
// Allocate array for column names (shared across all rows)
char **names = cloudsync_memory_alloc(ncols * sizeof(char*));
if (!names) {
SPI_freetuptable(saved_tuptable);
return DBRES_NOMEM;
}
// Get column names - make copies to avoid pointing to internal memory
for (int i = 0; i < ncols; i++) {
Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
if (attr) {
names[i] = cloudsync_string_dup(NameStr(attr->attname));
} else {
names[i] = NULL;
}
}
// Pre-extract ALL row values before calling any callbacks.
// This prevents SPI state corruption when callbacks run queries.
char ***all_values = cloudsync_memory_alloc(nrows * sizeof(char**));
if (!all_values) {
for (int i = 0; i < ncols; i++) {
if (names[i]) cloudsync_memory_free(names[i]);
}
cloudsync_memory_free(names);
SPI_freetuptable(saved_tuptable);
return DBRES_NOMEM;
}
// Extract values from all tuples
for (uint64 row = 0; row < nrows; row++) {
HeapTuple tuple = saved_tuptable->vals[row];
all_values[row] = cloudsync_memory_alloc(ncols * sizeof(char*));
if (!all_values[row]) {
// Cleanup already allocated rows
for (uint64 r = 0; r < row; r++) {
for (int c = 0; c < ncols; c++) {
if (all_values[r][c]) pfree(all_values[r][c]);
}
cloudsync_memory_free(all_values[r]);
}
cloudsync_memory_free(all_values);
for (int i = 0; i < ncols; i++) {
if (names[i]) cloudsync_memory_free(names[i]);
}
cloudsync_memory_free(names);
SPI_freetuptable(saved_tuptable);
return DBRES_NOMEM;
}
if (!tuple) {
for (int i = 0; i < ncols; i++) all_values[row][i] = NULL;
continue;
}
for (int i = 0; i < ncols; i++) {
bool isnull;
SPI_getbinval(tuple, tupdesc, i + 1, &isnull);
all_values[row][i] = (isnull) ? NULL : SPI_getvalue(tuple, tupdesc, i + 1);
}
}
// Free SPI_tuptable BEFORE calling callbacks - we have all data we need
SPI_freetuptable(saved_tuptable);
SPI_tuptable = NULL;
// Now process each row - callbacks can safely run SPI queries
int result = DBRES_OK;
for (uint64 row = 0; row < nrows; row++) {
int cb_rc = callback(xdata, ncols, all_values[row], names);
if (cb_rc != 0) {
char errmsg[1024];
snprintf(errmsg, sizeof(errmsg), "database_exec_callback aborted %d", cb_rc);
result = cloudsync_set_error(data, errmsg, DBRES_ABORT);
break;
}
}
// Cleanup all extracted values
for (uint64 row = 0; row < nrows; row++) {
for (int i = 0; i < ncols; i++) {
if (all_values[row][i]) pfree(all_values[row][i]);
}
cloudsync_memory_free(all_values[row]);
}
cloudsync_memory_free(all_values);
// Free column names
for (int i = 0; i < ncols; i++) {
if (names[i]) cloudsync_memory_free(names[i]);
}
cloudsync_memory_free(names);
return result;
}
if (SPI_tuptable) SPI_freetuptable(SPI_tuptable);
return DBRES_OK;
}
int database_write (cloudsync_context *data, const char *sql, const char **bind_values, DBTYPE bind_types[], int bind_lens[], int bind_count) {
if (!sql) return cloudsync_set_error(data, "Invalid parameters to database_write", DBRES_ERROR);
cloudsync_reset_error(data);
// Prepare statement
dbvm_t *stmt;
int rc = databasevm_prepare(data, sql, &stmt, 0);
if (rc != DBRES_OK) return rc;
// Bind parameters
for (int i = 0; i < bind_count; i++) {
int param_idx = i + 1;
switch (bind_types[i]) {
case DBTYPE_NULL:
rc = databasevm_bind_null(stmt, param_idx);
break;
case DBTYPE_INTEGER: {
int64_t val = strtoll(bind_values[i], NULL, 0);
rc = databasevm_bind_int(stmt, param_idx, val);
break;
}
case DBTYPE_FLOAT: {
double val = strtod(bind_values[i], NULL);
rc = databasevm_bind_double(stmt, param_idx, val);
break;
}
case DBTYPE_TEXT:
rc = databasevm_bind_text(stmt, param_idx, bind_values[i], bind_lens[i]);
break;
case DBTYPE_BLOB:
rc = databasevm_bind_blob(stmt, param_idx, bind_values[i], bind_lens[i]);
break;
default:
rc = DBRES_ERROR;
break;
}
if (rc != DBRES_OK) {
databasevm_finalize(stmt);
return rc;
}
}
// Execute
rc = databasevm_step(stmt);
databasevm_finalize(stmt);
return (rc == DBRES_DONE) ? DBRES_OK : rc;
}
int database_select_int (cloudsync_context *data, const char *sql, int64_t *value) {
return database_select1_value(data, sql, NULL, value, DBTYPE_INTEGER);
}
int database_select_text (cloudsync_context *data, const char *sql, char **value) {
int64_t len = 0;
return database_select1_value(data, sql, value, &len, DBTYPE_TEXT);
}
int database_select_blob (cloudsync_context *data, const char *sql, char **value, int64_t *len) {
return database_select1_value(data, sql, value, len, DBTYPE_BLOB);
}
int database_select_blob_2int (cloudsync_context *data, const char *sql, char **value, int64_t *len, int64_t *value2, int64_t *value3) {
return database_select3_values(data, sql, value, len, value2, value3);
}
int database_cleanup (cloudsync_context *data) {
// NOOP
return DBRES_OK;
}
// MARK: - STATUS -
int database_errcode (cloudsync_context *data) {