-
Notifications
You must be signed in to change notification settings - Fork 180
Expand file tree
/
Copy pathpgduckdb_background_worker.cpp
More file actions
1360 lines (1176 loc) · 44.4 KB
/
pgduckdb_background_worker.cpp
File metadata and controls
1360 lines (1176 loc) · 44.4 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
#include "duckdb.hpp"
#include "duckdb/catalog/catalog_entry/schema_catalog_entry.hpp"
#include "duckdb/parser/keyword_helper.hpp"
#include "duckdb/parser/parsed_data/create_info.hpp"
#include "duckdb/common/unordered_set.hpp"
#include "duckdb/parser/column_definition.hpp"
#include "duckdb/parser/constraint.hpp"
#include "duckdb/parser/statement/select_statement.hpp"
#include "duckdb/catalog/catalog_entry/column_dependency_manager.hpp"
#include "duckdb/parser/column_list.hpp"
#include "duckdb/parser/parsed_data/create_table_info.hpp"
#include "duckdb/parser/parsed_data/create_view_info.hpp"
#include "duckdb/catalog/catalog_entry/table_catalog_entry.hpp"
#include "duckdb/catalog/catalog_entry/view_catalog_entry.hpp"
#include "duckdb/storage/table_storage_info.hpp"
#include "duckdb/main/attached_database.hpp"
#include "pgduckdb/pgduckdb_ddl.hpp"
#include "pgduckdb/pgduckdb_fdw.hpp"
#include "pgduckdb/pgduckdb_types.hpp"
#include "pgduckdb/pgduckdb_utils.hpp"
#include "pgduckdb/pg/relations.hpp"
#include "pgduckdb/utility/cpp_wrapper.hpp"
#include "pgduckdb/pg/string_utils.hpp"
#include <string>
#include <unordered_map>
#include <sys/file.h>
#include <fcntl.h>
extern "C" {
#include "postgres.h"
#include "access/xact.h"
#include "catalog/dependency.h"
#include "catalog/namespace.h"
#include "catalog/objectaddress.h"
#include "catalog/pg_authid.h"
#include "catalog/pg_class.h"
#include "catalog/pg_extension.h"
#include "catalog/pg_foreign_server.h"
#include "catalog/pg_namespace.h"
#include "commands/dbcommands.h"
#include "common/file_utils.h"
#include "executor/spi.h"
#include "fmgr.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "postmaster/bgworker.h"
#include "postmaster/interrupt.h"
#include "storage/ipc.h"
#include "storage/latch.h"
#include "storage/proc.h"
#include "storage/shmem.h"
#include "tcop/tcopprot.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/palloc.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
}
#include "pgduckdb/pgduckdb.h"
#include "pgduckdb/pgduckdb_guc.hpp"
#include "pgduckdb/pgduckdb_duckdb.hpp"
#include "pgduckdb/pgduckdb_background_worker.hpp"
#include "pgduckdb/pgduckdb_metadata_cache.hpp"
#include "pgduckdb/pgduckdb_userdata_cache.hpp"
static std::unordered_map<std::string, std::string> last_known_motherduck_catalog_versions;
static duckdb::unique_ptr<duckdb::Connection> ddb_connection = nullptr;
static uint64_t initial_cache_version = 0;
namespace pgduckdb {
bool is_background_worker = false;
/*
* This stores a UUIDv4 that's generated on Postgres statrup. This cannot be a
* hardcoded token otherwise you could get contention on the matching
* MotherDuck read-instance if multiple pg_duckdb instances connect to the same
* MotherDuck account.
*
* The length is 37, because a UUID has 36 characters and we need to add a NULL
* byte.
*/
static char bgw_session_hint[37];
/* Did this backend reuse the session hint of the background worker? */
static bool reused_bgw_session_hint = false;
/*
* For some reason we cannot configure the before_shmem_exit hook in _PG_init,
* nor in shmem_startup_hook. So instead we configure it lazily for a backend
* whenever it is needed. We need to make sure we only do that at most once for
* each backend though. So this boolean keeps track of that.
*/
static bool set_up_unclaim_session_hint_hook = false;
void SyncMotherDuckCatalogsWithPg(bool drop_with_cascade, duckdb::ClientContext &context);
void SyncMotherDuckCatalogsWithPg_Cpp(bool drop_with_cascade, duckdb::ClientContext &context);
typedef struct BgwStatePerDB {
Oid database_oid;
int64 activity_count; /* the number of times activity was triggered by other backends */
bool bgw_session_hint_is_reused;
Latch *latch;
} BgwStatePerDB;
typedef struct BackgroundWorkerShmemStruct {
slock_t lock; /* protects all the fields below */
HTAB *statePerDB; /* Map of Database Oid -> {Latch, activity count, etc.} */
} BackgroundWorkerShmemStruct;
static BackgroundWorkerShmemStruct *BgwShmemStruct;
/*
MUST be called under a lock
Get the BGW state for the current database (MyDatabaseId)
*/
static BgwStatePerDB *
FindState() {
bool found = false;
auto state = (BgwStatePerDB *)hash_search(BgwShmemStruct->statePerDB, &MyDatabaseId, HASH_FIND, &found);
return found ? state : nullptr;
}
static BgwStatePerDB *
GetState() {
Assert(is_background_worker);
auto state = FindState();
if (!state) {
SpinLockRelease(&BgwShmemStruct->lock);
elog(ERROR, "pg_duckdb background worker: could not find state for database %u", MyDatabaseId);
}
return state;
}
static void
BackgroundWorkerCheck(duckdb::Connection &connection, int64_t &last_activity_count) {
SpinLockAcquire(&BgwShmemStruct->lock);
int64_t new_activity_count = GetState()->activity_count;
SpinLockRelease(&BgwShmemStruct->lock);
if (last_activity_count != new_activity_count) {
last_activity_count = new_activity_count;
/* Trigger some activity to restart the syncing */
pgduckdb::DuckDBQueryOrThrow(connection, "FROM duckdb_tables() limit 0");
}
/*
* If the extension is not registerid this loop is a no-op, which
* means we essentially keep polling until the extension is
* installed
*/
pgduckdb::SyncMotherDuckCatalogsWithPg_Cpp(false, *connection.context);
}
bool CanTakeBgwLockForDatabase(Oid database_oid);
static bool
RunOneCheck(int64_t &last_activity_count) {
// No need to run if MD is not enabled.
if (!IsMotherDuckEnabled()) {
elog(LOG, "pg_duckdb background worker: MotherDuck is not enabled, will exit.");
return true; // should exit
}
if (!IsExtensionRegistered()) {
return false; // XXX: shouldn't we exit actually?
}
if (!ddb_connection) {
try {
ddb_connection = DuckDBManager::CreateConnection();
} catch (std::exception &ex) {
elog(LOG, "pg_duckdb background worker: failed to create connection: %s", ex.what());
return true; // should exit
}
}
InvokeCPPFunc(pgduckdb::BackgroundWorkerCheck, *ddb_connection, last_activity_count);
return false;
}
static void
SetBackgroundWorkerState(Oid database_oid) {
auto state = (BgwStatePerDB *)hash_search(BgwShmemStruct->statePerDB, &database_oid, HASH_ENTER, NULL);
state->latch = MyLatch;
state->activity_count = 0;
state->bgw_session_hint_is_reused = false;
}
static void
BgwMainLoop() {
elog(LOG, "pg_duckdb background worker: starting");
char *db_name = nullptr;
{
StartTransactionCommand();
db_name = strdup(get_database_name(MyDatabaseId));
CommitTransactionCommand();
elog(LOG, "pg_duckdb background worker: started for database '%s' (%u)", db_name, MyDatabaseId);
}
doing_motherduck_sync = true;
is_background_worker = true;
int64_t last_activity_count = -1; // force a check on the first iteration
while (true) {
// Initialize SPI (Server Programming Interface) and connect to the database
SetCurrentStatementStartTimestamp();
StartTransactionCommand();
SPI_connect();
PushActiveSnapshot(GetTransactionSnapshot());
const bool should_exit = RunOneCheck(last_activity_count);
// Commit the transaction
PopActiveSnapshot();
SPI_finish();
CommitTransactionCommand();
if (should_exit) {
break;
}
pgstat_report_stat(false);
pgstat_report_activity(STATE_IDLE, NULL);
// Wait for a second or until the latch is set
WaitLatch(MyLatch, WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH, 1000L, PG_WAIT_EXTENSION);
CHECK_FOR_INTERRUPTS();
ResetLatch(MyLatch);
}
ddb_connection.reset();
DuckDBManager::Reset();
elog(LOG, "pg_duckdb background worker for database '%s' (%u) has now terminated.", db_name, MyDatabaseId);
}
} // namespace pgduckdb
extern "C" {
PGDLLEXPORT void pgduckdb_background_worker_main(Datum main_arg);
PGDLLEXPORT void
pgduckdb_background_worker_main(Datum main_arg) {
Oid database_oid = DatumGetObjectId(main_arg);
if (!pgduckdb::CanTakeBgwLockForDatabase(database_oid)) {
elog(LOG, "pg_duckdb background worker: could not take lock for database %u. Will exit.", database_oid);
return;
}
// Set up a signal handler for SIGTERM
pqsignal(SIGTERM, die);
BackgroundWorkerUnblockSignals();
BackgroundWorkerInitializeConnectionByOid(database_oid, InvalidOid, 0);
SpinLockAcquire(&pgduckdb::BgwShmemStruct->lock);
pgduckdb::SetBackgroundWorkerState(database_oid);
SpinLockRelease(&pgduckdb::BgwShmemStruct->lock);
PG_TRY();
{
pgduckdb::BgwMainLoop();
}
PG_FINALLY();
{
// Remove state entry.
SpinLockAcquire(&pgduckdb::BgwShmemStruct->lock);
hash_search(pgduckdb::BgwShmemStruct->statePerDB, &MyDatabaseId, HASH_REMOVE, NULL);
SpinLockRelease(&pgduckdb::BgwShmemStruct->lock);
}
PG_END_TRY();
}
PG_FUNCTION_INFO_V1(force_motherduck_sync);
Datum
force_motherduck_sync(PG_FUNCTION_ARGS) {
Datum drop_with_cascade = PG_GETARG_BOOL(0);
/* clear the cache of known catalog versions to force a full sync */
last_known_motherduck_catalog_versions.clear();
/*
* We don't use GetConnection, because we want to be able to precisely
* control the transaction lifecycle. We commit Postgres connections
* throughout this function, and the GetConnect its cached connection its
* lifecycle would be linked to those postgres transactions, which we
* don't want.
*/
auto connection = pgduckdb::DuckDBManager::Get().CreateConnection();
SPI_connect_ext(SPI_OPT_NONATOMIC);
PG_TRY();
{
pgduckdb::doing_motherduck_sync = true;
pgduckdb::SyncMotherDuckCatalogsWithPg(drop_with_cascade, *connection->context);
}
PG_FINALLY();
{
pgduckdb::doing_motherduck_sync = false;
}
PG_END_TRY();
SPI_finish();
PG_RETURN_VOID();
}
}
namespace pgduckdb {
#if PG_VERSION_NUM >= 150000
static shmem_request_hook_type prev_shmem_request_hook = NULL;
#endif
static shmem_startup_hook_type prev_shmem_startup_hook = NULL;
/*
* shmem_request hook: request additional shared resources. We'll allocate or
* attach to the shared resources in pgss_shmem_startup().
*/
static void
ShmemRequest(void) {
#if PG_VERSION_NUM >= 150000
if (prev_shmem_request_hook)
prev_shmem_request_hook();
#endif
RequestAddinShmemSpace(sizeof(BackgroundWorkerShmemStruct));
}
/*
* CheckpointerShmemInit
* Allocate and initialize checkpointer-related shared memory
*/
static void
ShmemStartup(void) {
if (prev_shmem_startup_hook) {
prev_shmem_startup_hook();
}
Size size = sizeof(BackgroundWorkerShmemStruct);
bool found;
/*
* Create or attach to the shared memory state, including hash table
*/
LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
BgwShmemStruct = (BackgroundWorkerShmemStruct *)ShmemInitStruct("DuckdbBackgroundWorker Data", size, &found);
if (!found) {
/*
* First time through, so initialize. Note that we zero the whole
* requests array; this is so that CompactCheckpointerRequestQueue can
* assume that any pad bytes in the request structs are zeroes.
*/
MemSet(BgwShmemStruct, 0, size);
SpinLockInit(&BgwShmemStruct->lock);
HASHCTL info;
info.keysize = sizeof(Oid);
info.entrysize = sizeof(BgwStatePerDB);
BgwShmemStruct->statePerDB =
ShmemInitHash("ProcBgwStatePerDB", 1, max_worker_processes, &info, HASH_ELEM | HASH_BLOBS);
}
LWLockRelease(AddinShmemInitLock);
}
constexpr const char *PGDUCKDB_SYNC_WORKER_NAME = "pg_duckdb sync worker";
static bool
HasBgwRunningForMyDatabase() {
const auto num_backends = pgstat_fetch_stat_numbackends();
for (int backend_idx = 1; backend_idx <= num_backends; ++backend_idx) {
#if PG_VERSION_NUM >= 140000 && PG_VERSION_NUM < 160000
PgBackendStatus *beentry = pgstat_fetch_stat_beentry(backend_idx);
#else
LocalPgBackendStatus *local_beentry = pgstat_get_local_beentry_by_index(backend_idx);
PgBackendStatus *beentry = &local_beentry->backendStatus;
#endif
if (beentry->st_databaseid == InvalidOid) {
continue; // backend is not connected to a database
}
auto datid = ObjectIdGetDatum(beentry->st_databaseid);
if (datid != MyDatabaseId) {
continue; // backend is connected to a different database
}
auto backend_type = GetBackgroundWorkerTypeByPid(beentry->st_procpid);
if (!backend_type || strcmp(backend_type, PGDUCKDB_SYNC_WORKER_NAME) != 0) {
continue; // backend is not a pg_duckdb sync worker
}
return true;
}
return false;
}
/*
Attempts to take a lock on a file named 'pgduckdb_worker_<database_oid>.lock'
If the lock is taken, the function returns true. If the lock is not taken, the function returns false.
*/
bool
CanTakeBgwLockForDatabase(Oid database_oid) {
char lock_file_name[MAXPGPATH];
snprintf(lock_file_name, MAXPGPATH, "%s/%s.pgduckdb_worker.%d", DataDir, PG_TEMP_FILE_PREFIX, database_oid);
auto fd = open(lock_file_name, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
if (fd < 0) {
elog(ERROR, "Could not open file '%s': %m", lock_file_name);
}
// Take exclusive lock on the file
auto ret = flock(fd, LOCK_EX | LOCK_NB);
if (ret != 0) {
if (errno == EWOULDBLOCK || errno == EAGAIN) {
return false;
}
elog(ERROR, "Could not take lock on file '%s': %m", lock_file_name);
}
return true;
}
void
UnclaimBgwSessionHint(int /*code*/, Datum /*arg*/) {
if (!reused_bgw_session_hint) {
return;
}
SpinLockAcquire(&BgwShmemStruct->lock);
auto *state = FindState();
if (state) {
state->bgw_session_hint_is_reused = false;
}
SpinLockRelease(&BgwShmemStruct->lock);
reused_bgw_session_hint = false;
}
void
InitBackgroundWorkersShmem(void) {
/* Set up the shared memory hooks */
#if PG_VERSION_NUM >= 150000
prev_shmem_request_hook = shmem_request_hook;
shmem_request_hook = ShmemRequest;
#else
ShmemRequest();
#endif
prev_shmem_startup_hook = shmem_startup_hook;
shmem_startup_hook = ShmemStartup;
Datum random_uuid = DirectFunctionCall1(gen_random_uuid, 0);
Datum uuid_datum = DirectFunctionCall1(uuid_out, random_uuid);
char *uuid_cstr = DatumGetCString(uuid_datum);
strcpy(bgw_session_hint, uuid_cstr);
}
/*
Will start the background worker if:
- MotherDuck is enabled (TODO: should be database-specific)
- it is not already running for the current PG database
*/
void
StartBackgroundWorkerIfNeeded(void) {
if (!pgduckdb::IsMotherDuckEnabled()) {
elog(DEBUG3, "pg_duckdb background worker not started because MotherDuck is not enabled");
return;
}
if (HasBgwRunningForMyDatabase()) {
elog(DEBUG3, "pg_duckdb background worker already running for database %u", MyDatabaseId);
return;
}
BackgroundWorker worker;
// Set up the worker struct
MemSet(&worker, 0, sizeof(BackgroundWorker));
worker.bgw_flags = BGWORKER_SHMEM_ACCESS | BGWORKER_BACKEND_DATABASE_CONNECTION;
worker.bgw_start_time = BgWorkerStart_RecoveryFinished;
snprintf(worker.bgw_library_name, BGW_MAXLEN, "pg_duckdb");
snprintf(worker.bgw_function_name, BGW_MAXLEN, "pgduckdb_background_worker_main");
snprintf(worker.bgw_name, BGW_MAXLEN, PGDUCKDB_SYNC_WORKER_NAME);
worker.bgw_restart_time = 1;
worker.bgw_main_arg = ObjectIdGetDatum(MyDatabaseId);
// Register the worker
RegisterDynamicBackgroundWorker(&worker, NULL);
}
void
TriggerActivity(void) {
if (!IsMotherDuckEnabled()) {
return;
}
SpinLockAcquire(&BgwShmemStruct->lock);
auto state = FindState();
if (state) {
state->activity_count++;
SetLatch(state->latch);
}
SpinLockRelease(&BgwShmemStruct->lock);
}
/*
* When motherduck read scaling is used we don't want to have the background
* worker use a dedicated read-scaling instance. Instead we want to have it
* share an instance with the backend that's doing the actual query. We do this
* having a single normal backend use the same session_hint as the background
* worker. This function decides if that's necessary and returns the
* session_hint that the background uses.
*
* If it's not necessary this returns the empty string.
*/
const char *
PossiblyReuseBgwSessionHint(void) {
if (is_background_worker || reused_bgw_session_hint) {
return bgw_session_hint;
}
const char *result = "";
SpinLockAcquire(&BgwShmemStruct->lock);
auto state = FindState();
if (state && !state->bgw_session_hint_is_reused) {
result = bgw_session_hint;
state->bgw_session_hint_is_reused = true;
reused_bgw_session_hint = true;
}
SpinLockRelease(&BgwShmemStruct->lock);
if (reused_bgw_session_hint && !set_up_unclaim_session_hint_hook) {
before_shmem_exit(UnclaimBgwSessionHint, 0);
}
return result;
}
/* Global variables that are used to communicate with our event triggers so
* they handle DDL of syncing differently than user-initiated DDL */
bool doing_motherduck_sync;
char *current_motherduck_catalog_version;
static std::string
PgSchemaName(const std::string &db_name, const std::string &schema_name, bool is_default_db) {
if (is_default_db) {
/*
* We map the "main" DuckDB schema of the default database to the
* "public" Postgres schema, because they are pretty much equivalent
* from a user perspective even though they are named differently.
*/
return schema_name == "main" ? "public" : schema_name;
}
std::ostringstream oss;
oss << "ddb$" << duckdb::KeywordHelper::EscapeQuotes(db_name, '$');
if (schema_name != "main") {
oss << "$" << duckdb::KeywordHelper::EscapeQuotes(schema_name, '$');
}
return oss.str();
}
static std::string
DropPgRelationString(const char *postgres_schema_name, const char *relation_name, char relation_kind,
bool with_cascade) {
std::ostringstream oss;
oss << "DROP ";
if (relation_kind == RELKIND_VIEW) {
oss << "VIEW ";
} else {
oss << "TABLE ";
}
oss << duckdb::KeywordHelper::WriteQuoted(postgres_schema_name, '"');
oss << ".";
oss << duckdb::KeywordHelper::WriteQuoted(relation_name, '"');
if (with_cascade) {
oss << " CASCADE";
}
oss << "; ";
return oss.str();
}
static std::string
CreatePgViewString(duckdb::CreateViewInfo &info, bool is_default_db) {
std::ostringstream oss;
oss << "CREATE VIEW ";
std::string schema_name = PgSchemaName(info.catalog, info.schema, is_default_db);
oss << duckdb::KeywordHelper::WriteQuoted(schema_name, '"');
oss << ".";
oss << duckdb::KeywordHelper::WriteQuoted(info.view_name, '"');
if (!info.aliases.empty()) {
oss << " (";
oss << duckdb::StringUtil::Join(info.aliases, info.aliases.size(), ", ", [](const std::string &name) {
return duckdb::KeywordHelper::WriteQuoted(name, '"');
});
oss << ")";
}
oss << " AS SELECT ";
auto it_names = info.names.begin();
auto it_types = info.types.begin();
bool first = true;
for (; it_names != info.names.end() && it_types != info.types.end(); it_names++, it_types++) {
Oid postgres_type = GetPostgresDuckDBType(*it_types);
if (postgres_type == InvalidOid) {
elog(WARNING, "Skipping column %s in table %s.%s.%s due to unsupported type", it_names->c_str(),
info.catalog.c_str(), info.schema.c_str(), info.view_name.c_str());
continue;
}
if (!first) {
oss << ", ";
} else {
first = false;
}
oss << "r[" << duckdb::KeywordHelper::WriteQuoted(*it_names, '\'') << "]::";
int32_t typemod = GetPostgresDuckDBTypemod(*it_types);
oss << format_type_with_typemod(postgres_type, typemod);
oss << " AS " << duckdb::KeywordHelper::WriteQuoted(*it_names, '"');
}
if (first) {
elog(WARNING, "Skipping view %s.%s.%s because none of its columns had supported types", info.catalog.c_str(),
info.schema.c_str(), info.view_name.c_str());
return "";
}
oss << " FROM duckdb.view(";
oss << duckdb::KeywordHelper::WriteQuoted(info.catalog) << ", ";
oss << duckdb::KeywordHelper::WriteQuoted(info.schema) << ", ";
oss << duckdb::KeywordHelper::WriteQuoted(info.view_name) << ", ";
oss << duckdb::KeywordHelper::WriteQuoted(info.query->ToString(), '\'');
oss << ") r;";
return oss.str();
}
static std::string
CreatePgTableString(duckdb::CreateTableInfo &info, bool is_default_db) {
std::ostringstream oss;
oss << "CREATE TABLE ";
std::string schema_name = PgSchemaName(info.catalog, info.schema, is_default_db);
oss << duckdb::KeywordHelper::WriteQuoted(schema_name, '"');
oss << ".";
oss << duckdb::KeywordHelper::WriteQuoted(info.table, '"');
oss << "(";
bool first = true;
for (auto &column : info.columns.Logical()) {
Oid postgres_type = GetPostgresDuckDBType(column.Type());
if (postgres_type == InvalidOid) {
continue;
}
if (first) {
first = false;
} else {
oss << ", ";
}
oss << duckdb::KeywordHelper::WriteQuoted(column.Name(), '"');
oss << " ";
int32_t typemod = GetPostgresDuckDBTypemod(column.Type());
oss << format_type_with_typemod(postgres_type, typemod);
}
if (first) {
elog(WARNING, "Skipping table %s.%s.%s because non of its columns had supported types", info.catalog.c_str(),
info.schema.c_str(), info.table.c_str());
return "";
}
oss << ") USING duckdb;";
return oss.str();
}
static std::string
CreatePgSchemaString(std::string postgres_schema_name) {
return "CREATE SCHEMA " + duckdb::KeywordHelper::WriteQuoted(postgres_schema_name, '"') + ";";
}
/*
* This function is a workaround for the fact that SPI_commit() does not work
* well in background workers. You get weird errors like:
* ERROR: portal snapshots (0) did not account for all active snapshots (1)
*
* Luckily we don't really care, all we really care about is that we quickly
* release the heavy locks we hold on tables after dropping/creating them. And
* this can easily be done by simply finishing the transaction and opening a
* new one.
*
* This workaround is only necessary in background workers, in normal sessions
* where people call force_motherduck_sync wo still want to use SPI_commit().
*
* See the following thread for details:
* https://www.postgresql.org/message-id/flat/CAFcNs%2Bp%2BfD5HEXEiZMZC1COnXkJCMnUK0%3Dr4agmZP%3D9Hi%2BYcJA%40mail.gmail.com
*/
static void
SPI_commit_that_works_in_bgworker() {
if (is_background_worker) {
SPI_finish();
PopActiveSnapshot();
CommitTransactionCommand();
StartTransactionCommand();
SPI_connect();
PushActiveSnapshot(GetTransactionSnapshot());
} else {
SPI_commit();
}
if (initial_cache_version != pgduckdb::CacheVersion()) {
if (is_background_worker) {
elog(ERROR, "DuckDB cache version changed during sync, aborting sync, background worker will restart "
"automatically");
} else {
elog(ERROR, "DuckDB cache version changed during sync, aborting sync, please try again");
}
}
}
/*
* This function runs a utility command in the current SPI context. Instead of
* throwing an ERROR on failure this will throw a WARNING and return false. It
* does so in a way that preserves the current transaction state, so that other
* commands can still be run.
*/
static bool
SPI_run_utility_command(const char *query) {
MemoryContext old_context = CurrentMemoryContext;
int ret;
/*
* We create a subtransaction to be able to cleanly roll back in case of
* any errors.
*/
BeginInternalSubTransaction(NULL);
PG_TRY();
{
ret = SPI_exec(query, 0);
}
PG_CATCH();
{
MemoryContextSwitchTo(old_context);
ErrorData *edata = CopyErrorData();
edata->elevel = WARNING;
ThrowErrorData(edata);
FreeErrorData(edata);
FlushErrorState();
RollbackAndReleaseCurrentSubTransaction();
return false;
}
PG_END_TRY();
if (ret != SPI_OK_UTILITY) {
elog(WARNING, "SPI_execute failed: error code %d", ret);
RollbackAndReleaseCurrentSubTransaction();
return false;
}
/* Success, so we commit the subtransaction */
ReleaseCurrentSubTransaction();
return true;
}
static bool
CreateView(const char *postgres_schema_name, const char *view_name, const char *create_view_query,
bool drop_with_cascade) {
/* -1 is for the NULL terminator */
if (strlen(view_name) > NAMEDATALEN - 1) {
ereport(WARNING, (errmsg("Skipping sync of MotherDuck view '%s' because its name is too long", view_name),
errhint("The maximum length of a view name is %d characters", NAMEDATALEN - 1)));
return false;
}
/*
* We need to fetch this over-and-over again, because we commit the
* transaction and thus release locks. So in theory the schema could be
* deleted/renamed etc.
*/
Oid schema_oid = get_namespace_oid(postgres_schema_name, false);
HeapTuple tuple = SearchSysCache2(RELNAMENSP, CStringGetDatum(view_name), ObjectIdGetDatum(schema_oid));
bool did_delete_table = false;
if (HeapTupleIsValid(tuple)) {
Form_pg_class postgres_relation = (Form_pg_class)GETSTRUCT(tuple);
/* The table already exists in Postgres, so we cannot simply create it. */
if (!IsMotherDuckTable(postgres_relation) && !IsMotherDuckView(postgres_relation)) {
/*
* Oops, we have a conflict. Let's notify the user, and
* not do anything else
*/
elog(WARNING,
"Skipping sync of MotherDuck view %s.%s because its name conflicts with an "
"already existing table/view/index in Postgres",
postgres_schema_name, view_name);
ReleaseSysCache(tuple);
return false;
}
char relation_kind = postgres_relation->relkind;
ReleaseSysCache(tuple);
/*
* It's an old version of this DuckDB table, we can safely
* drop it and recreate it.
*/
std::string drop_table_query =
DropPgRelationString(postgres_schema_name, view_name, relation_kind, drop_with_cascade);
/* We use this to roll back the drop if the CREATE after fails */
BeginInternalSubTransaction(NULL);
/* Revert back to original privileges */
if (!SPI_run_utility_command(drop_table_query.c_str())) {
ereport(WARNING, (errmsg("Failed to sync MotherDuck view %s.%s", postgres_schema_name, view_name),
errdetail("While executing command: %s", create_view_query),
errhint("See previous WARNING for details")));
/*
* Rollback the subtransaction to clean up the subtransaction
* state. Even though there's nothing actually in it. So we could
* we could just as well commit it, but rolling back seems more
* sensible.
*/
RollbackAndReleaseCurrentSubTransaction();
return false;
}
did_delete_table = true;
}
Oid saved_userid;
int sec_context;
GetUserIdAndSecContext(&saved_userid, &sec_context);
SetUserIdAndSecContext(MotherDuckPostgresUserOid(), sec_context | SECURITY_LOCAL_USERID_CHANGE);
bool create_table_succeeded = SPI_run_utility_command(create_view_query);
SetUserIdAndSecContext(saved_userid, sec_context);
/* Revert back to original privileges */
if (!create_table_succeeded) {
ereport(WARNING, (errmsg("Failed to sync MotherDuck view %s.%s", postgres_schema_name, view_name),
errdetail("While executing command: %s", create_view_query),
errhint("See previous WARNING for details")));
if (did_delete_table) {
/* Rollback the drop that succeeded */
RollbackAndReleaseCurrentSubTransaction();
}
return false;
}
if (did_delete_table) {
/*
* Commit the subtransaction that contains both the drop and the create that
* contains the actual table creation.
*/
ReleaseCurrentSubTransaction();
}
/* And then we also commit the actual transaction to release any locks that
* were necessary to execute it. */
SPI_commit_that_works_in_bgworker();
return true;
}
static bool
CreateTable(const char *postgres_schema_name, const char *table_name, const char *create_table_query,
bool drop_with_cascade) {
/* -1 is for the NULL terminator */
if (strlen(table_name) > NAMEDATALEN - 1) {
ereport(WARNING, (errmsg("Skipping sync of MotherDuck table '%s' because its name is too long", table_name),
errhint("The maximum length of a table name is %d characters", NAMEDATALEN - 1)));
return false;
}
/*
* We need to fetch this over-and-over again, because we commit the
* transaction and thus release locks. So in theory the schema could be
* deleted/renamed etc.
*/
Oid schema_oid = get_namespace_oid(postgres_schema_name, false);
HeapTuple tuple = SearchSysCache2(RELNAMENSP, CStringGetDatum(table_name), ObjectIdGetDatum(schema_oid));
bool did_delete_table = false;
if (HeapTupleIsValid(tuple)) {
Form_pg_class postgres_relation = (Form_pg_class)GETSTRUCT(tuple);
/* The table already exists in Postgres, so we cannot simply create it. */
if (!IsMotherDuckTable(postgres_relation) && !IsMotherDuckView(postgres_relation)) {
/*
* Oops, we have a conflict. Let's notify the user, and
* not do anything else
*/
elog(WARNING,
"Skipping sync of MotherDuck table %s.%s because its name conflicts with an "
"already existing table/view/index in Postgres",
postgres_schema_name, table_name);
ReleaseSysCache(tuple);
return false;
}
char relation_kind = postgres_relation->relkind;
ReleaseSysCache(tuple);
/*
* It's an old version of this DuckDB table, we can safely
* drop it and recreate it.
*/
std::string drop_table_query =
DropPgRelationString(postgres_schema_name, table_name, relation_kind, drop_with_cascade);
/* We use this to roll back the drop if the CREATE after fails */
BeginInternalSubTransaction(NULL);
/* Revert back to original privileges */
if (!SPI_run_utility_command(drop_table_query.c_str())) {
ereport(WARNING, (errmsg("Failed to sync MotherDuck table %s.%s", postgres_schema_name, table_name),
errdetail("While executing command: %s", create_table_query),
errhint("See previous WARNING for details")));
/*
* Rollback the subtransaction to clean up the subtransaction
* state. Even though there's nothing actually in it. So we could
* we could just as well commit it, but rolling back seems more
* sensible.
*/
RollbackAndReleaseCurrentSubTransaction();
return false;
}
did_delete_table = true;
}
Oid saved_userid;
int sec_context;
GetUserIdAndSecContext(&saved_userid, &sec_context);
SetUserIdAndSecContext(MotherDuckPostgresUserOid(), sec_context | SECURITY_LOCAL_USERID_CHANGE);
bool create_table_succeeded = SPI_run_utility_command(create_table_query);
SetUserIdAndSecContext(saved_userid, sec_context);
/* Revert back to original privileges */
if (!create_table_succeeded) {
ereport(WARNING, (errmsg("Failed to sync MotherDuck table %s.%s", postgres_schema_name, table_name),
errdetail("While executing command: %s", create_table_query),
errhint("See previous WARNING for details")));
if (did_delete_table) {
/* Rollback the drop that succeeded */
RollbackAndReleaseCurrentSubTransaction();
}
return false;
}
if (did_delete_table) {
/*
* Commit the subtransaction that contains both the drop and the create that
* contains the actual table creation.
*/
ReleaseCurrentSubTransaction();
}
/* And then we also commit the actual transaction to release any locks that
* were necessary to execute it. */
SPI_commit_that_works_in_bgworker();
return true;
}
static bool
DropRelation(const char *fully_qualified_table, char relation_kind, bool drop_with_cascade) {
const char *relkind_string = "TABLE";
if (relation_kind == RELKIND_VIEW) {
relkind_string = "VIEW";
}
const char *query =
psprintf("DROP %s %s%s", relkind_string, fully_qualified_table, drop_with_cascade ? " CASCADE" : "");
if (!SPI_run_utility_command(query)) {
ereport(WARNING,
(errmsg("Failed to drop deleted MotherDuck table %s", fully_qualified_table),
errdetail("While executing command: %s", query), errhint("See previous WARNING for details")));
return false;
}
/*
* We explicitly don't call SPI_commit_that_works_in_background_worker
* here, because that makes transactional considerations easier. And when
* deleting tables, it doesn't matter how long we keep locks on them,
* because they are already deleted upstream so there can be no queries on