-
Notifications
You must be signed in to change notification settings - Fork 705
Expand file tree
/
Copy pathextension_init.cpp
More file actions
1789 lines (1606 loc) · 82.5 KB
/
extension_init.cpp
File metadata and controls
1789 lines (1606 loc) · 82.5 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 libintl.h first to avoid conflicts with PostgreSQL's gettext macro
#include <libintl.h>
#ifdef __cplusplus
#define typeof __typeof__
extern "C" {
#endif
#include <postgres.h>
#include <catalog/namespace.h>
#include <commands/dbcommands.h>
#include <commands/defrem.h>
#include <miscadmin.h>
#include <commands/vacuum.h>
#include <nodes/nodeFuncs.h>
#include <optimizer/planner.h>
#include <parser/parser.h>
#include <postmaster/bgworker.h>
#include <storage/ipc.h>
#include <tcop/utility.h>
#include <utils/jsonb.h>
#ifdef __cplusplus
} /// extern "C"
#endif
#include "column_statistics.hpp"
#include "deeplake_executor.hpp"
#include "dl_catalog.hpp"
#include "pg_deeplake.hpp"
#include "pg_version_compat.h"
#include "sync_worker.hpp"
#include "table_am.hpp"
#include "table_ddl_lock.hpp"
#include "table_scan.hpp"
#include "table_storage.hpp"
#include "table_version.hpp"
#include "memory_tracker.hpp"
#include "reporter.hpp"
#include <algorithm>
#include <climits>
#include <cmath>
#include <cstdint>
#include <map>
#include <memory>
#include <numeric>
#include <set>
#include <vector>
// Define GUC variables (declared as extern in utils.hpp)
namespace pg {
bool use_parallel_workers = false;
bool use_deeplake_executor = true;
bool explain_query_before_execute = false;
bool print_runtime_stats = false;
bool support_json_index = false;
bool is_filter_pushdown_enabled = true;
int32_t max_streamable_column_width = 128;
int32_t max_num_threads_for_global_state = std::thread::hardware_concurrency();
bool treat_numeric_as_double = true; // Treat numeric types as double by default
bool print_progress_during_seq_scan = false;
bool use_shared_mem_for_refresh = false;
bool enable_dataset_logging = false; // Enable dataset operation logging for debugging
bool allow_custom_paths = true; // Allow dataset_path in CREATE TABLE options
bool stateless_enabled = false; // Enable stateless catalog sync across instances
} // namespace pg
namespace {
bool is_count_star(TargetEntry* node)
{
if (node == nullptr || node->expr == nullptr || !IsA(node->expr, Aggref)) {
return false;
}
Aggref* agg = (Aggref*)node->expr;
return ((agg->aggfnoid == F_COUNT_ANY || agg->aggfnoid == F_COUNT_) && (agg->args == NIL || agg->aggstar));
}
void initialize_guc_parameters()
{
DefineCustomBoolVariable("pg_deeplake.treat_numeric_as_double",
"If set to true, numeric values will be treated as double precision.",
nullptr, // optional long description
&pg::treat_numeric_as_double, // linked C variable
true, // default value
PGC_USERSET, // context (USERSET, SUSET, etc.)
0, // flags
nullptr,
nullptr,
nullptr // check_hook, assign_hook, show_hook
);
DefineCustomBoolVariable("pg_deeplake.print_progress_during_seq_scan",
"Print progress during sequential scan.",
nullptr, // optional long description
&pg::print_progress_during_seq_scan, // linked C variable
false, // default value
PGC_USERSET, // context (USERSET, SUSET, etc.)
0, // flags
nullptr,
nullptr,
nullptr // check_hook, assign_hook, show_hook
);
DefineCustomBoolVariable("pg_deeplake.enable_parallel_workers",
"Enable parallel workers for pg_deeplake operations.",
nullptr, // optional long description
&pg::use_parallel_workers, // linked C variable
false, // default value
PGC_USERSET, // context (USERSET, SUSET, etc.)
0, // flags
nullptr,
nullptr,
nullptr // check_hook, assign_hook, show_hook
);
DefineCustomBoolVariable("pg_deeplake.use_deeplake_executor",
"Enable direct execution for pg_deeplake operations.",
nullptr, // optional long description
&pg::use_deeplake_executor, // linked C variable
true, // default value
PGC_USERSET, // context (USERSET, SUSET, etc.)
0, // flags
nullptr,
nullptr,
nullptr // check_hook, assign_hook, show_hook
);
DefineCustomBoolVariable("pg_deeplake.explain_query_before_execute",
"Enable query explanation before execution.",
nullptr, // optional long description
&pg::explain_query_before_execute, // linked C variable
false, // default value
PGC_USERSET, // context (USERSET, SUSET, etc.)
0, // flags
nullptr,
nullptr,
nullptr // check_hook, assign_hook, show_hook
);
DefineCustomBoolVariable("pg_deeplake.print_runtime_stats",
"Enable runtime statistics printing for pg_deeplake operations.",
nullptr, // optional long description
&pg::print_runtime_stats, // linked C variable
false, // default value
PGC_USERSET, // context (USERSET, SUSET, etc.)
0, // flags
nullptr,
nullptr,
nullptr // check_hook, assign_hook, show_hook
);
DefineCustomBoolVariable("pg_deeplake.support_json_index",
"Enable support for JSONB index optimizations.",
nullptr, // optional long description
&pg::support_json_index, // linked C variable
false, // default value
PGC_USERSET, // context (USERSET, SUSET, etc.)
0, // flags
nullptr,
nullptr,
nullptr // check_hook, assign_hook, show_hook
);
DefineCustomBoolVariable("pg_deeplake.is_filter_pushdown_enabled",
"Enable filter pushdown optimizations for pg_deeplake tables.",
nullptr, // optional long description
&pg::is_filter_pushdown_enabled, // linked C variable
true, // default value
PGC_USERSET, // context (USERSET, SUSET, etc.)
0, // flags
nullptr,
nullptr,
nullptr // check_hook, assign_hook, show_hook
);
DefineCustomIntVariable("pg_deeplake.max_streamable_column_width",
"Maximum width (in bytes) for columns to be considered streamable.",
nullptr, // optional long description
&pg::max_streamable_column_width, // linked C variable
128, // default value (128 bytes)
1, // min value
1024, // max value (1 KB)
PGC_USERSET, // context (USERSET, SUSET, etc.)
0, // flags
nullptr,
nullptr,
nullptr // check_hook, assign_hook, show_hook
);
DefineCustomIntVariable("pg_deeplake.max_num_threads_for_global_state",
"Maximum number of threads for global state operations.",
nullptr, // optional long description
&pg::max_num_threads_for_global_state, // linked C variable
base::system_report::cpu_cores(), // default value
1, // min value
base::system_report::cpu_cores(), // max value
PGC_USERSET, // context (USERSET, SUSET, etc.)
0, // flags
nullptr,
nullptr,
nullptr // check_hook, assign_hook, show_hook
);
DefineCustomBoolVariable("pg_deeplake.use_shared_mem_for_refresh",
"Use shared memory to detect whether dataset was refreshed or not.",
"Note: Should have same value across all instances in a cluster. "
"Enabling this option allows the system to use shared memory "
"for detecting dataset refreshes, which can improve performance but may "
"have implications on concurrency. "
"It make sense to disable this for OLTP workloads.",
&pg::use_shared_mem_for_refresh, // linked C variable
true, // default value
PGC_USERSET, // context (USERSET, SUSET, etc.)
0, // flags
nullptr,
nullptr,
nullptr // check_hook, assign_hook, show_hook
);
DefineCustomBoolVariable("deeplake.allow_custom_paths",
"Allow custom dataset paths via USING deeplake WITH (dataset_path=...).",
"If disabled, dataset_path options are rejected and tables must use deeplake.root_path.",
&pg::allow_custom_paths,
true,
PGC_USERSET,
0,
nullptr,
nullptr,
nullptr);
DefineCustomBoolVariable("deeplake.stateless_enabled",
"Enable stateless catalog for multi-instance sync.",
"When enabled, table metadata is written to the shared catalog in storage, "
"allowing multiple PostgreSQL instances to share the same tables. "
"This adds latency for remote storage (S3, GCS) due to catalog sync operations.",
&pg::stateless_enabled,
true,
PGC_POSTMASTER,
0,
nullptr,
nullptr,
nullptr);
DefineCustomBoolVariable("pg_deeplake.enable_dataset_logging",
"Enable operation logging for deeplake datasets.",
"When enabled, all dataset operations (append_row, update_row, delete_row, etc.) "
"are logged to debug_logs/{session_id}/{timestamp}.json files in the dataset storage. "
"This can be useful for debugging and auditing purposes. "
"Note: This may have a performance impact as each operation is logged asynchronously.",
&pg::enable_dataset_logging, // linked C variable
false, // default value
PGC_USERSET, // context (USERSET, SUSET, etc.)
0, // flags
nullptr,
nullptr,
nullptr // check_hook, assign_hook, show_hook
);
// Sync worker GUC variables for stateless multi-instance support
DefineCustomIntVariable("deeplake.sync_interval_ms",
"Interval between catalog sync checks in milliseconds.",
"The background sync worker polls the catalog version at this interval. "
"When the version changes, tables are synced from the shared catalog.",
&deeplake_sync_interval_ms, // linked C variable
2000, // default value (2 seconds)
100, // min value
60000, // max value (1 minute)
PGC_SIGHUP, // context - reloadable
GUC_UNIT_MS, // flags
nullptr,
nullptr,
nullptr // check_hook, assign_hook, show_hook
);
// Initialize PostgreSQL memory tracking
pg::memory_tracker::initialize_guc_parameters();
pg::session_credentials::initialize_guc();
}
/// @name Json path extraction and transformation
/// @description: Helper to extract path from nested -> and ->> operators
/// @note: Under GUC param pg_deeplake.support_json_index (default: false)
/// @{
void extract_jsonb_path(Node* expr, std::vector<std::string>& path, Node** base_col)
{
if (IsA(expr, OpExpr)) {
OpExpr* op = (OpExpr*)expr;
char* opname = get_opname(op->opno);
if (opname && (strcmp(opname, "->") == 0 || strcmp(opname, "->>") == 0)) {
Node* left = (Node*)linitial(op->args);
Node* right = (Node*)lsecond(op->args);
// Recursively extract path from left side
extract_jsonb_path(left, path, base_col);
// Add current key to path
if (IsA(right, Const)) {
Const* kc = (Const*)right;
if (kc->consttype == TEXTOID && !kc->constisnull) {
char* key = text_to_cstring(DatumGetTextPP(kc->constvalue));
path.push_back(std::string(key));
pfree(key);
}
}
} else {
*base_col = expr;
}
if (opname)
pfree(opname);
} else {
*base_col = expr;
}
}
// Build nested JSON from path: ["a", "b", "c"] with value "v" -> {"a": {"b": {"c": "v"}}}
std::string build_nested_json(const std::vector<std::string>& path, const std::string& value)
{
if (path.empty())
return "";
StringInfoData json;
initStringInfo(&json);
// Open braces for each level
for (size_t i = 0; i < path.size(); i++) {
appendStringInfo(&json, "{\"%s\":", path[i].c_str());
}
// Add value
appendStringInfo(&json, "\"%s\"", value.c_str());
// Close braces
for (size_t i = 0; i < path.size(); i++) {
appendStringInfoChar(&json, '}');
}
std::string result(json.data);
pfree(json.data);
return result;
}
// Transform ->> expressions into @> containment for JSONB index usage
void transform_jsonb_arrow_quals(Node** nodeptr)
{
if (!nodeptr || !*nodeptr)
return;
Node* node = *nodeptr;
if (IsA(node, BoolExpr)) {
BoolExpr* b = (BoolExpr*)node;
ListCell* lc = nullptr;
foreach (lc, b->args) {
transform_jsonb_arrow_quals((Node**)&lfirst(lc));
}
} else if (IsA(node, OpExpr)) {
OpExpr* op = (OpExpr*)node;
char* opname = get_opname(op->opno);
// Look for: (data -> 'a' -> 'b' ->> 'c') = 'value' or (data ->> 'key') = 'value'
// Transform to: data @> '{"a": {"b": {"c": "value"}}}'::jsonb
if (opname && strcmp(opname, "=") == 0 && list_length(op->args) == 2) {
Node* left = (Node*)linitial(op->args);
Node* right = (Node*)lsecond(op->args);
// Check if left side has -> or ->> operators and right is a constant
if (IsA(left, OpExpr) && IsA(right, Const)) {
// Extract the full path from nested operators
std::vector<std::string> path;
Node* base_col = nullptr;
extract_jsonb_path(left, path, &base_col);
if (base_col && !path.empty()) {
Oid col_type = exprType(base_col);
Const* val = (Const*)right;
if (col_type == JSONBOID && !val->constisnull && val->consttype == TEXTOID) {
// Build nested JSON
char* vs = text_to_cstring(DatumGetTextPP(val->constvalue));
std::string json_str = build_nested_json(path, vs);
if (!json_str.empty()) {
// Convert to JSONB
Jsonb* jb =
DatumGetJsonbP(DirectFunctionCall1(jsonb_in, CStringGetDatum(json_str.c_str())));
// Create JSONB constant
Const* jc = makeNode(Const);
jc->consttype = JSONBOID;
jc->consttypmod = -1;
jc->constcollid = InvalidOid;
jc->constlen = -1;
jc->constvalue = JsonbPGetDatum(jb);
jc->constisnull = false;
jc->constbyval = false;
jc->location = val->location;
// Look up @> operator
Oid cop = OpernameGetOprid(list_make1(makeString(pstrdup("@>"))), JSONBOID, JSONBOID);
if (OidIsValid(cop)) {
// Create new @> operator expression
OpExpr* newop = makeNode(OpExpr);
newop->opno = cop;
newop->opfuncid = get_opcode(cop);
newop->opresulttype = BOOLOID;
newop->opretset = false;
newop->opcollid = InvalidOid;
newop->inputcollid = InvalidOid;
newop->args = list_make2(copyObject(base_col), jc);
newop->location = op->location;
*nodeptr = (Node*)newop;
base::log_debug(base::log_channel::index,
"Transformed JSONB path (depth {}) to @> containment",
path.size());
}
}
pfree(vs);
}
}
}
}
if (opname)
pfree(opname);
}
}
/// @}
} // namespace
#ifdef __cplusplus
extern "C" {
#endif
PG_MODULE_MAGIC;
PG_FUNCTION_INFO_V1(create_deeplake_table);
PG_FUNCTION_INFO_V1(deeplake_tableam_handler);
static ExecutorStart_hook_type prev_executor_start = nullptr;
static ExecutorRun_hook_type prev_executor_run = nullptr;
static ExecutorEnd_hook_type prev_executor_end = nullptr;
static ProcessUtility_hook_type prev_process_utility_hook = nullptr;
static planner_hook_type prev_planner_hook = nullptr;
typedef void (*set_rel_pathlist_hook_type)(PlannerInfo* root, RelOptInfo* rel, Index rti, RangeTblEntry* rte);
extern PGDLLIMPORT set_rel_pathlist_hook_type set_rel_pathlist_hook;
static set_rel_pathlist_hook_type prev_set_rel_pathlist_hook = nullptr;
static shmem_request_hook_type prev_shmem_request_hook = nullptr;
static shmem_startup_hook_type prev_shmem_startup_hook = nullptr;
/// @name Callbacks for executor hooks
/// @{
static void deeplake_shmem_request()
{
if (prev_shmem_request_hook) {
prev_shmem_request_hook();
}
// Request shared memory for table version tracking
RequestAddinShmemSpace(pg::table_version_tracker::get_shmem_size());
RequestNamedLWLockTranche("deeplake_versions", 1);
// Request shared memory for table DDL lock
RequestAddinShmemSpace(pg::table_ddl_lock::get_shmem_size());
RequestNamedLWLockTranche("deeplake_table_ddl", 1);
// Request shared memory for pending extension install queue
RequestAddinShmemSpace(pg::pending_install_queue::get_shmem_size());
RequestNamedLWLockTranche("deeplake_install_queue", 1);
}
static void deeplake_shmem_startup()
{
if (prev_shmem_startup_hook) {
prev_shmem_startup_hook();
}
pg::table_version_tracker::initialize();
pg::table_ddl_lock::initialize();
pg::pending_install_queue::initialize();
}
static void process_utility(PlannedStmt* pstmt,
const char* queryString,
bool readOnlyTree,
ProcessUtilityContext context,
ParamListInfo params,
QueryEnvironment* queryEnv,
DestReceiver* dest,
QueryCompletion* completionTag)
{
pg::runtime_printer printer("Process Utility Hook");
pg::init_deeplake();
if (nodeTag(pstmt->utilityStmt) == T_DropStmt) {
DropStmt* stmt = (DropStmt*)pstmt->utilityStmt;
if (stmt->removeType == OBJECT_EXTENSION) {
// Extension is being dropped, clean up all tables and indexes
pg::pg_index::clear();
pg::table_storage::instance().clear();
} else if (stmt->removeType == OBJECT_INDEX) {
ListCell* lc = nullptr;
foreach (lc, stmt->objects) {
List* object = (List*)lfirst(lc);
const char* index_name = strVal(linitial(object));
if (!pg::pg_index::has_indexes()) {
pg::load_index_metadata();
}
pg::pg_index::erase_info(index_name);
pg::erase_indexer_data(std::string{}, std::string{}, index_name);
}
} else if (stmt->removeType == OBJECT_TABLE) {
ListCell* lc = nullptr;
foreach (lc, stmt->objects) {
List* table_name_list = (List*)lfirst(lc);
std::string table_name;
if (list_length(table_name_list) == 2) {
auto* sname = strVal(linitial(table_name_list));
auto* tname = strVal(lsecond(table_name_list));
table_name = std::string(sname) + "." + std::string(tname);
} else if (list_length(table_name_list) == 1) {
table_name = std::string("public.") + strVal(linitial(table_name_list));
}
// Handle both index and table cleanup
if (pg::pg_index::has_index_created_on_table(table_name)) {
pg::pg_index::erase_table_info(table_name);
pg::erase_indexer_data(table_name, std::string{}, std::string{});
}
pg::table_storage::instance().drop_table(table_name);
}
} else if (stmt->removeType == OBJECT_VIEW) {
ListCell* lc = nullptr;
foreach (lc, stmt->objects) {
List* view_name_list = (List*)lfirst(lc);
std::string view_name;
if (list_length(view_name_list) == 2) {
auto* sname = strVal(linitial(view_name_list));
auto* vname = strVal(lsecond(view_name_list));
view_name = std::string(sname) + "." + std::string(vname);
} else if (list_length(view_name_list) == 1) {
view_name = std::string(strVal(linitial(view_name_list)));
}
pg::table_storage::instance().erase_view(view_name);
}
} else if (stmt->removeType == OBJECT_SCHEMA) {
ListCell* lc = nullptr;
foreach (lc, stmt->objects) {
String* schema_name_str = (String*)lfirst(lc);
if (schema_name_str == nullptr || !IsA(schema_name_str, String)) {
continue;
}
const char* schema_name = strVal(schema_name_str);
if (schema_name == nullptr) {
continue;
}
const char* query = "SELECT nspname, relname "
"FROM pg_class c "
"JOIN pg_namespace n ON c.relnamespace = n.oid "
"WHERE c.relkind = 'r' AND n.nspname = $1";
pg::utils::spi_connector connector;
Oid argtypes[1] = {TEXTOID};
Datum values[1];
values[0] = CStringGetTextDatum(schema_name);
if (SPI_execute_with_args(query, 1, argtypes, values, nullptr, true, 0) == SPI_OK_SELECT) {
for (auto i = 0; i < SPI_processed; ++i) {
const char* sname = SPI_getvalue(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 1);
const char* tname = SPI_getvalue(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 2);
if (sname != nullptr && tname != nullptr) {
const std::string table_name = (std::string(sname) + "." + std::string(tname));
// Handle both index and table cleanup
if (pg::pg_index::has_index_created_on_table(table_name)) {
pg::pg_index::erase_table_info(table_name);
pg::erase_indexer_data(table_name, std::string{}, std::string{});
}
pg::table_storage::instance().drop_table(table_name);
}
}
}
// Mark schema as "dropping" in the S3 catalog
if (pg::stateless_enabled) {
try {
auto root_path = pg::session_credentials::get_root_path();
if (root_path.empty()) {
root_path = pg::utils::get_deeplake_root_directory();
}
if (!root_path.empty()) {
auto creds = pg::session_credentials::get_credentials();
const char* dbname = get_database_name(MyDatabaseId);
std::string db_name = dbname ? dbname : "postgres";
if (dbname) pfree(const_cast<char*>(dbname));
pg::dl_catalog::ensure_catalog(root_path, creds);
pg::dl_catalog::ensure_db_catalog(root_path, db_name, creds);
pg::dl_catalog::schema_meta s_meta;
s_meta.schema_name = schema_name;
s_meta.state = "dropping";
pg::dl_catalog::upsert_schema(root_path, db_name, creds, s_meta);
pg::dl_catalog::bump_db_catalog_version(root_path, db_name, pg::session_credentials::get_credentials());
pg::dl_catalog::bump_catalog_version(root_path, pg::session_credentials::get_credentials());
}
} catch (const std::exception& e) {
elog(WARNING, "pg_deeplake: failed to mark schema '%s' as dropping in catalog: %s", schema_name, e.what());
}
}
}
} else if (stmt->removeType == OBJECT_DATABASE) {
const char* query = "SELECT nspname, relname "
"FROM pg_class c "
"JOIN pg_namespace n ON c.relnamespace = n.oid "
"WHERE c.relkind = 'r'";
pg::utils::spi_connector connector;
if (SPI_execute(query, true, 0) == SPI_OK_SELECT) {
for (auto i = 0; i < SPI_processed; ++i) {
char* sname = SPI_getvalue(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 1);
char* tname = SPI_getvalue(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 2);
if (sname != nullptr && tname != nullptr) {
const std::string table_name = (std::string(sname) + "." + std::string(tname));
pg::pg_index::erase_table_info(table_name);
pg::erase_indexer_data(table_name, std::string{}, std::string{});
}
}
}
}
}
if (IsA(pstmt->utilityStmt, AlterTableStmt)) {
AlterTableStmt* stmt = (AlterTableStmt*)pstmt->utilityStmt;
/// Extract table name
RangeVar* rel = stmt->relation;
// Get the actual relation OID to resolve the proper schema name (handles custom schemas via search_path)
Oid rel_oid = RangeVarGetRelid(rel, NoLock, false);
Relation temp_rel = RelationIdGetRelation(rel_oid);
std::string table_name;
if (RelationIsValid(temp_rel)) {
Oid nspid = RelationGetNamespace(temp_rel);
char* nspname = get_namespace_name(nspid);
table_name = std::string(nspname ? nspname : "public") + "." + RelationGetRelationName(temp_rel);
if (nspname) {
pfree(nspname);
}
RelationClose(temp_rel);
} else {
// Fallback to RangeVar if relation is invalid (shouldn't happen)
const std::string schema_name = (rel->schemaname != nullptr ? rel->schemaname : "public");
table_name = schema_name + "." + rel->relname;
}
auto* td = pg::table_storage::instance().get_table_data_if_exists(table_name);
if (td != nullptr) {
ListCell* lc = nullptr;
foreach (lc, stmt->cmds) {
AlterTableCmd* cmd = (AlterTableCmd*)lfirst(lc);
if (cmd->subtype == AT_DropColumn) {
std::string column_name = cmd->name;
pg::pg_index::erase_column_info(table_name, column_name);
pg::erase_indexer_data(table_name, column_name, std::string{});
td->get_dataset()->remove_column(column_name);
}
}
td->commit();
// Note: We don't reload table_data here because the TupleDesc hasn't been updated yet.
// The reload will happen in the POST-AlterTable section below after standard_ProcessUtility.
}
}
if (IsA(pstmt->utilityStmt, CreateStmt)) {
CreateStmt* stmt = (CreateStmt*)pstmt->utilityStmt;
elog(DEBUG1, "CreateStmt: %s", stmt->relation->relname);
elog(DEBUG1, "stmt->options: %p", stmt->options);
elog(DEBUG1, "stmt->accessMethod: %s", stmt->accessMethod);
const bool deeplake_table = (stmt->accessMethod != nullptr && std::strcmp(stmt->accessMethod, "deeplake") == 0);
if (deeplake_table && stmt->options != nullptr) {
List* new_options = NIL;
ListCell* lc = nullptr;
foreach (lc, stmt->options) {
DefElem* def = (DefElem*)lfirst(lc);
if (def->arg != nullptr && std::strcmp(def->defname, pg::dataset_path_option_name) == 0) {
const char* ds_path = defGetString(def);
pg::table_options::current().set_dataset_path(ds_path);
elog(DEBUG1, "ds_path: %s", ds_path);
continue;
}
new_options = lappend(new_options, def);
}
stmt->options = new_options;
}
}
std::optional<pg::utils::parallel_workers_switcher> switcher;
if (IsA(pstmt->utilityStmt, IndexStmt)) {
IndexStmt* stmt = (IndexStmt*)pstmt->utilityStmt;
const Oid rel_id = RangeVarGetRelid(stmt->relation, NoLock, false);
if (pg::table_storage::instance().table_exists(rel_id)) {
switcher.emplace();
}
}
// Pre-hook: mark database as "dropping" in S3 catalog before PostgreSQL drops it
if (IsA(pstmt->utilityStmt, DropdbStmt) && pg::stateless_enabled) {
DropdbStmt* dbstmt = (DropdbStmt*)pstmt->utilityStmt;
try {
auto root_path = pg::session_credentials::get_root_path();
if (root_path.empty()) {
root_path = pg::utils::get_deeplake_root_directory();
}
if (!root_path.empty()) {
auto creds = pg::session_credentials::get_credentials();
pg::dl_catalog::ensure_catalog(root_path, creds);
pg::dl_catalog::database_meta db_meta;
db_meta.db_name = dbstmt->dbname;
db_meta.state = "dropping";
pg::dl_catalog::upsert_database(root_path, creds, db_meta);
pg::dl_catalog::bump_catalog_version(root_path, creds);
elog(LOG, "pg_deeplake: marked database '%s' as dropping in catalog", dbstmt->dbname);
}
} catch (const std::exception& e) {
elog(WARNING, "pg_deeplake: failed to mark database '%s' as dropping in catalog: %s", dbstmt->dbname, e.what());
}
}
if (prev_process_utility_hook != nullptr) {
prev_process_utility_hook(pstmt, queryString, readOnlyTree, context, params, queryEnv, dest, completionTag);
} else {
standard_ProcessUtility(pstmt, queryString, readOnlyTree, context, params, queryEnv, dest, completionTag);
}
// Post-hook: record CREATE DATABASE in S3 catalog and install extension
if (IsA(pstmt->utilityStmt, CreatedbStmt)) {
CreatedbStmt* dbstmt = (CreatedbStmt*)pstmt->utilityStmt;
// Queue the database for async extension install by the sync worker.
// The inline PQconnectdb approach fails on PG15+ because CREATE DATABASE
// is WAL-logged/transactional and the pg_database row isn't committed yet.
pg::pending_install_queue::enqueue(dbstmt->dbname);
// Record in S3 catalog if stateless mode is enabled
if (pg::stateless_enabled) {
try {
auto root_path = pg::session_credentials::get_root_path();
if (root_path.empty()) {
root_path = pg::utils::get_deeplake_root_directory();
}
if (!root_path.empty()) {
auto creds = pg::session_credentials::get_credentials();
pg::dl_catalog::ensure_catalog(root_path, creds);
pg::dl_catalog::database_meta db_meta;
db_meta.db_name = dbstmt->dbname;
db_meta.state = "ready";
// Extract options from CREATE DATABASE statement
ListCell* lc = nullptr;
foreach (lc, dbstmt->options) {
DefElem* def = (DefElem*)lfirst(lc);
if (strcmp(def->defname, "owner") == 0) {
db_meta.owner = defGetString(def);
} else if (strcmp(def->defname, "encoding") == 0) {
db_meta.encoding = defGetString(def);
} else if (strcmp(def->defname, "lc_collate") == 0) {
db_meta.lc_collate = defGetString(def);
} else if (strcmp(def->defname, "lc_ctype") == 0) {
db_meta.lc_ctype = defGetString(def);
} else if (strcmp(def->defname, "template") == 0) {
db_meta.template_db = defGetString(def);
}
}
pg::dl_catalog::upsert_database(root_path, creds, db_meta);
pg::dl_catalog::bump_catalog_version(root_path, creds);
elog(DEBUG1, "pg_deeplake: recorded CREATE DATABASE '%s' in catalog", dbstmt->dbname);
}
} catch (const std::exception& e) {
elog(DEBUG1, "pg_deeplake: failed to record CREATE DATABASE '%s' in catalog: %s", dbstmt->dbname, e.what());
}
}
}
// Post-hook: record CREATE SCHEMA in S3 catalog for multi-instance sync
if (IsA(pstmt->utilityStmt, CreateSchemaStmt) && pg::stateless_enabled) {
CreateSchemaStmt* schemastmt = (CreateSchemaStmt*)pstmt->utilityStmt;
try {
auto root_path = pg::session_credentials::get_root_path();
if (root_path.empty()) {
root_path = pg::utils::get_deeplake_root_directory();
}
if (!root_path.empty() && schemastmt->schemaname != nullptr) {
auto creds = pg::session_credentials::get_credentials();
const char* dbname = get_database_name(MyDatabaseId);
std::string db_name = dbname ? dbname : "postgres";
if (dbname) pfree(const_cast<char*>(dbname));
pg::dl_catalog::ensure_catalog(root_path, creds);
pg::dl_catalog::ensure_db_catalog(root_path, db_name, creds);
pg::dl_catalog::schema_meta s_meta;
s_meta.schema_name = schemastmt->schemaname;
s_meta.state = "ready";
if (schemastmt->authrole != nullptr) {
s_meta.owner = schemastmt->authrole->rolename;
}
pg::dl_catalog::upsert_schema(root_path, db_name, creds, s_meta);
pg::dl_catalog::bump_db_catalog_version(root_path, db_name, pg::session_credentials::get_credentials());
pg::dl_catalog::bump_catalog_version(root_path, pg::session_credentials::get_credentials());
elog(DEBUG1, "pg_deeplake: recorded CREATE SCHEMA '%s' in catalog", schemastmt->schemaname);
}
} catch (const std::exception& e) {
elog(DEBUG1, "pg_deeplake: failed to record CREATE SCHEMA in catalog: %s", e.what());
}
}
// Post-process ALTER TABLE ADD COLUMN to add column to deeplake dataset
if (IsA(pstmt->utilityStmt, AlterTableStmt)) {
AlterTableStmt* stmt = (AlterTableStmt*)pstmt->utilityStmt;
RangeVar* rel = stmt->relation;
// Get the actual relation OID to resolve the proper schema name (handles custom schemas via search_path)
Oid rel_oid = RangeVarGetRelid(rel, NoLock, false);
Relation temp_rel = RelationIdGetRelation(rel_oid);
std::string table_name;
if (RelationIsValid(temp_rel)) {
Oid nspid = RelationGetNamespace(temp_rel);
char* nspname = get_namespace_name(nspid);
table_name = std::string(nspname ? nspname : "public") + "." + RelationGetRelationName(temp_rel);
if (nspname) {
pfree(nspname);
}
RelationClose(temp_rel);
} else {
// Fallback to RangeVar if relation is invalid (shouldn't happen)
const std::string schema_name = (rel->schemaname != nullptr ? rel->schemaname : "public");
table_name = schema_name + "." + rel->relname;
}
auto* td = pg::table_storage::instance().get_table_data_if_exists(table_name);
if (td != nullptr) {
ListCell* lc = nullptr;
foreach (lc, stmt->cmds) {
AlterTableCmd* cmd = (AlterTableCmd*)lfirst(lc);
if (cmd->subtype == AT_AddColumn && cmd->def != nullptr) {
// Column has been added to PostgreSQL catalog, now add to deeplake
ColumnDef* coldef = (ColumnDef*)cmd->def;
const char* column_name = coldef->colname;
// Get the relation to query the new column's type from catalog
Relation relation = RelationIdGetRelation(rel_oid);
if (RelationIsValid(relation)) {
TupleDesc tupdesc = RelationGetDescr(relation);
// Find the newly added column in the tuple descriptor
for (int i = 0; i < tupdesc->natts; i++) {
Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
if (strcmp(NameStr(attr->attname), column_name) == 0) {
// Found the new column, add it to deeplake dataset
Oid base_typeid = attr->atttypid;
// Resolve domain types to their base type
HeapTuple type_tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(base_typeid));
if (HeapTupleIsValid(type_tuple)) {
Form_pg_type type_form = (Form_pg_type)GETSTRUCT(type_tuple);
if (type_form->typtype == TYPTYPE_DOMAIN) {
base_typeid = type_form->typbasetype;
}
ReleaseSysCache(type_tuple);
}
try {
auto ds = td->get_dataset();
// Map PostgreSQL type to DeepLake type (same logic as create_table)
switch (base_typeid) {
case BOOLOID:
ds->add_column(column_name, nd::type::scalar(nd::dtype::boolean));
break;
case INT2OID:
ds->add_column(column_name, nd::type::scalar(nd::dtype::int16));
break;
case INT4OID:
case DATEOID:
ds->add_column(column_name, nd::type::scalar(nd::dtype::int32));
break;
case TIMEOID:
case TIMESTAMPOID:
case TIMESTAMPTZOID:
case INT8OID:
ds->add_column(column_name, nd::type::scalar(nd::dtype::int64));
break;
case FLOAT4OID:
ds->add_column(column_name, nd::type::scalar(nd::dtype::float32));
break;
case NUMERICOID: {
const int32_t typmod = attr->atttypmod;
if (typmod >= 0) {
const int32_t precision = ((typmod - VARHDRSZ) >> 16) & 0xFFFF;
if (precision > 15) {
const int32_t scale = (typmod - VARHDRSZ) & 0xFFFF;
elog(WARNING,
"Column '%s' has type NUMERIC(%d, %d), which may lose precision "
"as it is stored as FLOAT64.",
column_name,
precision,
scale);
}
}
}
case FLOAT8OID:
ds->add_column(column_name, nd::type::scalar(nd::dtype::float64));
break;
case CHAROID:
case BPCHAROID:
case VARCHAROID: {
const int32_t typmod = attr->atttypmod;
if (typmod == VARHDRSZ + 1) {
ds->add_column(
column_name,
deeplake_core::type::generic(nd::type::scalar(nd::dtype::int8)));
} else {
ds->add_column(column_name,
deeplake_core::type::text(codecs::compression::null));
}
break;
}
case UUIDOID:
case TEXTOID:
ds->add_column(column_name,
deeplake_core::type::text(codecs::compression::null));
break;
case JSONOID:
case JSONBOID:
ds->add_column(column_name, deeplake_core::type::dict());
break;
case BYTEAOID: {
// Check for special domain types over BYTEA
if (pg::utils::is_file_domain_type(attr->atttypid)) {
// FILE domain -> link of bytes
ds->add_column(
column_name,
deeplake_core::type::link(
deeplake_core::type::generic(nd::type::scalar(nd::dtype::byte))));
break;
}
if (pg::utils::is_image_domain_type(attr->atttypid)) {
// IMAGE domain -> image type
ds->add_column(
column_name,
deeplake_core::type::image(
nd::type::array(nd::dtype::byte, 3), codecs::compression::null));
break;
}
if (pg::utils::is_video_domain_type(attr->atttypid)) {
// VIDEO domain -> video type
ds->add_column(column_name,
deeplake_core::type::video(codecs::compression::mp4));
break;
}
ds->add_column(column_name,
deeplake_core::type::generic(nd::type::scalar(nd::dtype::byte)));
break;
}
case INT2ARRAYOID: {
int32_t ndims = (attr->attndims > 0) ? attr->attndims : 1;
if (ndims > 255) {
elog(ERROR,
"Column '%s' has unsupported type SMALLINT[] with %d dimensions (max "
"255)",
column_name,
ndims);
}
if (ndims == 1) {
ds->add_column(column_name,
deeplake_core::type::embedding(0, nd::dtype::int16));
} else {
ds->add_column(
column_name,
deeplake_core::type::generic(nd::type::array(nd::dtype::int16, ndims)));
}
break;
}
case INT4ARRAYOID: {
int32_t ndims = (attr->attndims > 0) ? attr->attndims : 1;
if (ndims > 255) {
elog(ERROR,