forked from activeloopai/deeplake
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtable_storage.cpp
More file actions
836 lines (754 loc) · 31.5 KB
/
Copy pathtable_storage.cpp
File metadata and controls
836 lines (754 loc) · 31.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
#include "pg_deeplake.hpp"
#ifdef __cplusplus
extern "C" {
#endif
#include <postgres.h>
#include <access/heapam.h>
#include <access/htup_details.h>
#include <access/parallel.h>
#include <catalog/namespace.h>
#include <catalog/pg_type.h>
#include <executor/spi.h>
#include <miscadmin.h>
#include <utils/builtins.h>
#include <utils/elog.h>
#include <utils/errcodes.h>
#include <utils/guc.h>
#include <utils/lsyscache.h>
#include <utils/rel.h>
#include <utils/syscache.h>
#ifdef __cplusplus
}
#endif
#include "table_storage.hpp"
#include "exceptions.hpp"
#include "logger.hpp"
#include "memory_tracker.hpp"
#include "nd_utils.hpp"
#include "table_ddl_lock.hpp"
#include "table_scan.hpp"
#include "utils.hpp"
#include <icm/json.hpp>
#include <icm/string_map.hpp>
#include <nd/none.hpp>
namespace {
// Helper function to split schema.table_name
std::pair<std::string, std::string> split_table_name(const std::string& full_name)
{
auto dot_pos = full_name.find('.');
if (dot_pos == std::string::npos) {
return {"public", full_name}; // Default to public schema if not specified
}
return {full_name.substr(0, dot_pos), full_name.substr(dot_pos + 1)};
}
void convert_pg_to_nd(const pg::table_data& table_data,
const std::vector<Datum>& values,
const std::vector<uint8_t>& nulls,
int32_t t_len,
icm::string_map<nd::array>& row)
{
TupleDesc tupdesc = table_data.get_tuple_descriptor();
for (auto i = 0; i < table_data.num_columns(); ++i) {
Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
if (attr == nullptr) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("Invalid attribute at position %d", i)));
}
// Skip SERIAL columns as they are auto-generated
if (attr->attidentity == 'a' || attr->attisdropped || attr->attgenerated == ATTRIBUTE_GENERATED_STORED) {
continue;
}
const auto column_name = table_data.get_atttypename(i);
// Skip if column is not in the input tuple
if (i >= t_len || nulls[i] == 1) {
row[column_name] = nd::none(nd::dtype::unknown, 0);
continue;
}
row[column_name] =
pg::utils::datum_to_nd(values[i], table_data.get_base_atttypid(i), table_data.get_atttypmod(i));
}
}
} // unnamed namespace
namespace pg {
// Initialize static members
char* session_credentials::creds_guc_string = nullptr;
char* session_credentials::root_path_guc_string = nullptr;
icm::string_map<> session_credentials::get_credentials()
{
icm::string_map<> creds_map;
if (creds_guc_string != nullptr && std::strlen(creds_guc_string) > 0) {
try {
auto creds_json = icm::json::parse(creds_guc_string);
for (auto it = creds_json.begin(); it != creds_json.end(); ++it) {
std::string key_str(it.key());
if (it.value().is_string()) {
creds_map[key_str] = it.value().get<std::string>();
} else {
elog(WARNING, "Credential value for key '%s' is not a string, skipping", key_str.c_str());
}
}
} catch (const std::exception& e) {
elog(WARNING, "Failed to parse deeplake.creds: %s. Using environment variables.", e.what());
}
}
return creds_map;
}
std::string session_credentials::get_root_path()
{
if (root_path_guc_string != nullptr && std::strlen(root_path_guc_string) > 0) {
return std::string(root_path_guc_string);
}
return "";
}
void session_credentials::initialize_guc()
{
DefineCustomStringVariable(
"deeplake.creds",
"JSON string containing storage credentials for DeepLake datasets",
"Credentials are used for all dataset operations in the current session. "
"Example: SET deeplake.creds = '{\"aws_access_key_id\": \"...\", \"aws_secret_access_key\": \"...\"}';",
&creds_guc_string, // linked C variable
"", // default value (empty)
PGC_USERSET, // context - can be set by any user
0, // flags
nullptr, // check_hook
nullptr, // assign_hook
nullptr // show_hook
);
DefineCustomStringVariable(
"deeplake.root_path",
"Root path for DeepLake datasets",
"Defines the root directory where datasets will be created when no explicit path is provided. "
"Supports local paths and cloud storage (s3://, gcs://, azure://). "
"Example: SET deeplake.root_path = 's3://my-bucket/datasets';",
&root_path_guc_string, // linked C variable
"", // default value (empty)
PGC_USERSET, // context - can be set by any user
0, // flags
nullptr, // check_hook
nullptr, // assign_hook
nullptr // show_hook
);
}
void table_storage::save_table_metadata(const pg::table_data& table_data)
{
const std::string& table_name = table_data.get_table_name();
const std::string ds_path = table_data.get_dataset_path().url();
pg::utils::memory_context_switcher context_switcher;
pg::utils::pg_try([&]() {
StringInfoData buf;
initStringInfo(&buf);
appendStringInfo(&buf,
"INSERT INTO public.pg_deeplake_tables (table_oid, table_name, ds_path) "
"VALUES (%u, %s, %s) "
"ON CONFLICT DO NOTHING",
table_data.get_table_oid(),
quote_literal_cstr(table_name.c_str()),
quote_literal_cstr(ds_path.c_str()));
pg::utils::spi_connector connector;
if (SPI_execute(buf.data, false, 0) != SPI_OK_INSERT) {
throw pg::exception("Failed to save table metadata");
}
return true;
});
}
void table_storage::load_table_metadata()
{
if (tables_loaded_) {
return;
}
/// set this first to avoid reloading metadata
tables_loaded_ = true;
if (!pg::utils::check_table_exists("pg_deeplake_tables")) {
return;
}
const char* query = "SELECT table_oid, table_name, ds_path FROM public.pg_deeplake_tables";
pg::utils::spi_connector connector;
if (SPI_execute(query, true, 0) != SPI_OK_SELECT) {
base::log_warning(base::log_channel::generic, "Failed to query table metadata");
return;
}
const auto proc = SPI_processed;
const bool res = (proc > 0 && SPI_tuptable != nullptr);
if (!res) {
return;
}
TupleDesc tupdesc = SPI_tuptable->tupdesc;
SPITupleTable* tuptable = SPI_tuptable;
// Get credentials from current session
auto creds = session_credentials::get_credentials();
std::vector<Oid> invalid_table_oids;
for (auto i = 0; i < proc; ++i) {
HeapTuple tuple = tuptable->vals[i];
bool is_null = false;
Oid relid = InvalidOid;
Datum relid_datum = SPI_getbinval(tuple, tupdesc, 1, &is_null);
if (!is_null) {
relid = DatumGetUInt32(relid_datum);
}
const char* table_name = SPI_getvalue(tuple, tupdesc, 2);
const char* ds_path = SPI_getvalue(tuple, tupdesc, 3);
if (relid == InvalidOid || table_name == nullptr || ds_path == nullptr || tables_.contains(relid)) {
continue;
}
try {
// Get the relation and its tuple descriptor
Relation rel = try_relation_open(relid, NoLock);
if (rel == nullptr) {
elog(WARNING, "Could not open relation for table %s", table_name);
invalid_table_oids.push_back(relid);
continue;
}
{
pg::utils::memory_context_switcher context_switcher(TopMemoryContext);
table_data td(
relid, table_name, CreateTupleDescCopy(RelationGetDescr(rel)), std::string(ds_path), creds);
auto it2status = tables_.emplace(relid, std::move(td));
up_to_date_ = false;
ASSERT(it2status.second);
}
relation_close(rel, NoLock);
} catch (const base::exception& e) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("%s", e.what())));
}
}
for (Oid invalid_oid : invalid_table_oids) {
auto query = fmt::format("DELETE FROM public.pg_deeplake_tables WHERE table_oid = {}", invalid_oid);
if (SPI_execute(query.c_str(), false, 0) != SPI_OK_DELETE) {
base::log_warning(
base::log_channel::generic, "Failed to delete invalid table metadata for table_oid: {}", invalid_oid);
}
}
load_views();
load_schema_name();
}
void table_storage::load_views()
{
if (!pg::utils::check_table_exists("pg_deeplake_views")) {
return;
}
const char* view_query = "SELECT view_name, query_string FROM public.pg_deeplake_views";
if (SPI_execute(view_query, true, 0) != SPI_OK_SELECT) {
base::log_warning(base::log_channel::generic, "Failed to query view metadata");
return;
}
const auto proc = SPI_processed;
const bool res = (proc > 0 && SPI_tuptable != nullptr);
if (!res) {
return;
}
const auto tupdesc = SPI_tuptable->tupdesc;
const auto tuptable = SPI_tuptable;
for (auto i = 0; i < proc; ++i) {
HeapTuple tuple = tuptable->vals[i];
char* view_name = SPI_getvalue(tuple, tupdesc, 1);
char* view_str = SPI_getvalue(tuple, tupdesc, 2);
if (view_name == nullptr || view_str == nullptr) {
continue;
}
Oid view_oid = RelnameGetRelid(view_name);
if (OidIsValid(view_oid) && !views_.contains(view_oid)) {
views_.emplace(view_oid, std::pair{view_name, view_str});
up_to_date_ = false;
}
}
}
void table_storage::load_schema_name()
{
const char* search_path = GetConfigOption("search_path", false, false);
std::string schema_name = "public";
std::string_view sv(search_path);
// Check if search_path contains 'public'
if (sv.find("public") == std::string_view::npos) {
// If 'public' is not in search_path, take the first schema from comma-separated list
auto comma_pos = sv.find(',');
if (comma_pos != std::string_view::npos) {
sv = sv.substr(0, comma_pos);
}
// Trim leading/trailing whitespace
while (!sv.empty() && std::isspace(sv.front())) {
sv.remove_prefix(1);
}
while (!sv.empty() && std::isspace(sv.back())) {
sv.remove_suffix(1);
}
if (!sv.empty()) {
schema_name = std::string(sv);
}
}
schema_name_ = std::move(schema_name);
}
void table_storage::erase_table_metadata(const std::string& table_name)
{
pg::utils::memory_context_switcher context_switcher;
if (!pg::utils::check_table_exists("pg_deeplake_tables")) {
return;
}
StringInfoData buf;
initStringInfo(&buf);
appendStringInfo(
&buf, "DELETE FROM public.pg_deeplake_tables WHERE table_name = %s", quote_literal_cstr(table_name.c_str()));
pg::utils::spi_connector connector;
if (SPI_execute(buf.data, false, 0) != SPI_OK_DELETE) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("Failed to erase table metadata")));
}
}
void table_storage::create_table(const std::string& table_name, Oid table_id, TupleDesc tupdesc)
{
// Acquire global DDL lock to prevent concurrent CREATE/DROP TABLE operations (also needed for deeplake)
pg::table_ddl_lock_guard ddl_lock;
pg::utils::memory_context_switcher context_switcher(TopMemoryContext);
auto options = pg::table_options::current();
pg::table_options::current().reset();
auto [schema_name, simple_table_name] = split_table_name(table_name);
if (table_exists(table_id) || table_exists(table_name)) {
return;
}
std::string dataset_path;
// Use provided dataset path or construct default path
if (!options.dataset_path().empty()) {
// Explicit path provided via WITH clause
dataset_path = options.dataset_path();
} else {
// Get session root path if set
auto session_root = session_credentials::get_root_path();
std::string root_dir;
if (!session_root.empty()) {
// Use session-level root path from deeplake.root_path GUC
root_dir = session_root;
} else {
// Fall back to DEEPLAKE_ROOT_PATH env var or PostgreSQL data directory
root_dir = pg::utils::get_deeplake_root_directory();
}
// Construct path: root_dir/schema_name/table_name
dataset_path = root_dir + "/" + schema_name + "/" + simple_table_name;
}
// Get credentials from current session
auto creds = session_credentials::get_credentials();
table_data td(table_id, table_name, CreateTupleDescCopy(tupdesc), dataset_path, creds);
PinTupleDesc(td.get_tuple_descriptor());
bool ds_exists = false;
try {
auto creds_for_exists = creds;
ds_exists = deeplake_api::exists(dataset_path, std::move(creds_for_exists)).get_future().get();
} catch (const base::exception& e) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("%s", e.what())));
}
try {
if (ds_exists) {
td.open_dataset(false);
base::log_info(base::log_channel::generic,
"Table dataset exists, url: {}, opening, num_rows: {}",
td.get_dataset_path().url(),
td.num_rows());
/// Validate columns
} else {
td.open_dataset(true);
// Create columns based on TupleDesc
for (auto i = 0; i < td.num_columns(); ++i) {
Form_pg_attribute attr = TupleDescAttr(td.get_tuple_descriptor(), i);
const char* column_name = NameStr(attr->attname);
// Resolve domain types to their base type
Oid base_typeid = td.get_base_atttypid(i);
// Map PostgreSQL types to DeepLake types
switch (base_typeid) {
case BOOLOID:
td.get_dataset()->add_column(column_name, nd::type::scalar(nd::dtype::boolean));
break;
case INT2OID:
td.get_dataset()->add_column(column_name, nd::type::scalar(nd::dtype::int16));
break;
case INT4OID:
case DATEOID:
td.get_dataset()->add_column(column_name, nd::type::scalar(nd::dtype::int32));
break;
case TIMEOID:
case TIMESTAMPOID:
case TIMESTAMPTZOID:
case INT8OID:
td.get_dataset()->add_column(column_name, nd::type::scalar(nd::dtype::int64));
break;
case FLOAT4OID:
td.get_dataset()->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:
td.get_dataset()->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) {
td.get_dataset()->add_column(column_name,
deeplake_core::type::generic(nd::type::scalar(nd::dtype::int8)));
} else {
td.get_dataset()->add_column(column_name, deeplake_core::type::text(codecs::compression::null));
}
break;
}
case UUIDOID:
case TEXTOID:
td.get_dataset()->add_column(column_name, deeplake_core::type::text(codecs::compression::null));
break;
case JSONOID:
case JSONBOID:
td.get_dataset()->add_column(column_name, deeplake_core::type::dict());
break;
case BYTEAOID:
td.get_dataset()->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) {
td.get_dataset()->add_column(column_name, deeplake_core::type::embedding(0, nd::dtype::int16));
} else {
td.get_dataset()->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,
"Column '%s' has unsupported type INT[] with %d dimensions (max 255)",
column_name,
ndims);
}
if (ndims == 1) {
td.get_dataset()->add_column(column_name, deeplake_core::type::embedding(0, nd::dtype::int32));
} else {
td.get_dataset()->add_column(
column_name, deeplake_core::type::generic(nd::type::array(nd::dtype::int32, ndims)));
}
break;
}
case INT8ARRAYOID: {
int32_t ndims = (attr->attndims > 0) ? attr->attndims : 1;
if (ndims > 255) {
elog(ERROR,
"Column '%s' has unsupported type BIGINT[] with %d dimensions (max 255)",
column_name,
ndims);
}
if (ndims == 1) {
td.get_dataset()->add_column(column_name, deeplake_core::type::embedding(0, nd::dtype::int64));
} else {
td.get_dataset()->add_column(
column_name, deeplake_core::type::generic(nd::type::array(nd::dtype::int64, ndims)));
}
break;
}
case FLOAT4ARRAYOID: {
int32_t ndims = (attr->attndims > 0) ? attr->attndims : 1;
if (ndims > 255) {
elog(ERROR,
"Column '%s' has unsupported type REAL[] with %d dimensions (max 255)",
column_name,
ndims);
}
// Store FLOAT4[] as float32 (4 bytes)
if (ndims == 1) {
td.get_dataset()->add_column(column_name,
deeplake_core::type::embedding(0, nd::dtype::float32));
} else {
td.get_dataset()->add_column(
column_name, deeplake_core::type::generic(nd::type::array(nd::dtype::float32, ndims)));
}
break;
}
case FLOAT8ARRAYOID: {
int32_t ndims = (attr->attndims > 0) ? attr->attndims : 1;
if (ndims > 255) {
elog(ERROR,
"Column '%s' has unsupported type DOUBLE PRECISION[] with %d dimensions (max 255)",
column_name,
ndims);
}
if (ndims == 1) {
td.get_dataset()->add_column(column_name,
deeplake_core::type::embedding(0, nd::dtype::float64));
} else {
td.get_dataset()->add_column(
column_name, deeplake_core::type::generic(nd::type::array(nd::dtype::float64, ndims)));
}
break;
}
case BYTEAARRAYOID: {
if (attr->attndims > 1) {
elog(ERROR,
"Column '%s' has unsupported type BYTEA[] with %d dimensions",
column_name,
attr->attndims);
}
td.get_dataset()->add_column(
column_name, deeplake_core::type::generic(nd::type::array(nd::dtype::byte, attr->attndims)));
break;
}
case VARCHARARRAYOID:
case TEXTARRAYOID: {
if (attr->attndims > 1) {
elog(ERROR,
"Column '%s' has unsupported type TEXT[] with %d dimensions",
column_name,
attr->attndims);
}
td.get_dataset()->add_column(
column_name, deeplake_core::type::generic(nd::type::array(nd::dtype::string, attr->attndims)));
break;
}
default: {
auto creds_for_delete = creds;
deeplake_api::delete_dataset(td.get_dataset_path(), std::move(creds_for_delete)).get_future().get();
const char* tname = format_type_with_typemod(attr->atttypid, attr->atttypmod);
elog(ERROR,
"Create Table: Column '%s' has unsupported type '%s' (OID %u, base OID %u)",
column_name,
tname,
attr->atttypid,
base_typeid);
}
}
}
base::log_info(base::log_channel::generic,
"Table dataset initialized with {} columns, url: {}",
td.num_columns(),
td.get_dataset_path().url());
td.commit();
}
save_table_metadata(td);
} catch (const base::exception& e) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("%s", e.what())));
}
if (auto it = primary_keys_.find(simple_table_name); it != primary_keys_.end() && !it->second.empty()) {
try {
td.set_primary_keys(it->second);
} catch (const base::exception& e) {
elog(WARNING, "Failed to set primary keys for table %s: %s", table_name.c_str(), e.what());
}
}
tables_.emplace(table_id, std::move(td));
up_to_date_ = false;
}
void table_storage::drop_table(const std::string& table_name)
{
pg::table_ddl_lock_guard ddl_lock;
if (!table_exists(table_name)) {
force_load_table_metadata();
}
if (table_exists(table_name)) {
auto& table_data = get_table_data(table_name);
auto creds = session_credentials::get_credentials();
try {
table_data.commit(); // Ensure all changes are committed before deletion
table_version_tracker::drop_table(table_data.get_table_oid());
deeplake_api::delete_dataset(table_data.get_dataset_path(), std::move(creds)).get_future().get();
} catch (const base::exception& e) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("Failed to delete dataset: %s", e.what())));
}
erase_table(table_name);
}
/// FreeTupleDesc(table_data.tuple_descriptor_);
erase_table_metadata(table_name);
}
void table_storage::insert_slot(Oid table_id, TupleTableSlot* slot)
{
insert_slots(table_id, 1, &slot);
}
void table_storage::insert_slots(Oid table_id, int32_t nslots, TupleTableSlot** slots)
{
auto& table_data = get_table_data(table_id);
table_data.add_insert_slots(nslots, slots);
if (nslots > 1) {
table_data.reset_streamers();
table_data.flush();
}
}
bool table_storage::delete_tuple(Oid table_id, ItemPointer tid)
{
auto& table_data = get_table_data(table_id);
try {
const auto row_number = utils::tid_to_row_number(tid);
// Verify row exists
if (row_number >= table_data.num_rows()) {
ereport(
ERROR,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("Row number %zu out of range for table %s", row_number, table_data.get_table_name().c_str())));
return false;
}
table_data.add_delete_row(row_number);
return true;
} catch (const base::exception& e) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("Failed to delete tuple: %s", e.what())));
return false;
}
}
bool table_storage::update_tuple(Oid table_id, ItemPointer tid, HeapTuple new_tuple)
{
auto& table_data = get_table_data(table_id);
TupleDesc tupdesc = table_data.get_tuple_descriptor();
try {
const auto row_number = utils::tid_to_row_number(tid);
// Verify row exists
if (row_number >= table_data.num_rows()) {
ereport(
ERROR,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("Row number %zu out of range for table %s", row_number, table_data.get_table_name().c_str())));
return false;
}
// Extract values from HeapTuple
std::vector<Datum> values(tupdesc->natts, 0);
std::vector<uint8_t> nulls(tupdesc->natts, 0);
heap_deform_tuple(new_tuple, tupdesc, values.data(), reinterpret_cast<bool*>(nulls.data()));
icm::string_map<nd::array> row;
::convert_pg_to_nd(table_data, values, nulls, new_tuple->t_len, row);
table_data.add_update_row(row_number, std::move(row));
return true;
} catch (const base::exception& e) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("Failed to update tuple: %s", e.what())));
return false;
}
}
bool table_storage::fetch_tuple(Oid table_id, ItemPointer tid, TupleTableSlot* slot)
{
auto& table_data = get_table_data(table_id);
table_scan tscan(table_id, false, false);
try {
ExecClearTuple(slot);
const auto row_number = utils::tid_to_row_number(tid);
if (row_number >= table_data.num_rows()) {
return false;
}
Datum* values = slot->tts_values;
bool* nulls = slot->tts_isnull;
PG_TRY();
{
tscan.convert_nd_to_pg(row_number, values, nulls);
}
PG_CATCH();
{
PG_RE_THROW();
}
PG_END_TRY();
ExecStoreVirtualTuple(slot);
slot->tts_tid = *tid;
return true;
} catch (const base::exception& e) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("Failed to fetch tuple: %s", e.what())));
}
return false;
}
void table_storage::clear()
{
auto creds = session_credentials::get_credentials();
// Clean up all datasets and metadata
for (auto& [table_id, table_data] : tables_) {
try {
table_data.commit(); // Ensure all changes are committed before deletion
auto creds_for_delete = creds;
deeplake_api::delete_dataset(table_data.get_dataset_path(), std::move(creds_for_delete)).get_future().get();
FreeTupleDesc(table_data.get_tuple_descriptor());
} catch (const base::exception& e) {
// Log error but continue cleaning up other tables
ereport(
WARNING,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("Failed to delete dataset for table %s: %s", table_data.get_table_name().c_str(), e.what())));
}
}
table_version_tracker::clear_all_versions();
tables_.clear();
views_.clear();
up_to_date_ = false;
if (!pg::utils::check_table_exists("pg_deeplake_tables") || !pg::utils::check_table_exists("pg_deeplake_views")) {
return;
}
// Clean up metadata table
pg::utils::memory_context_switcher context_switcher;
pg::utils::spi_connector connector;
if (SPI_execute("DELETE FROM public.pg_deeplake_tables", false, 0) != SPI_OK_DELETE) {
ereport(WARNING, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("Failed to clear metadata table")));
}
if (SPI_execute("DELETE FROM public.pg_deeplake_views", false, 0) != SPI_OK_DELETE) {
ereport(WARNING, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("Failed to clear views metadata table")));
}
}
table_data& table_storage::get_table_data(Oid table_id)
{
if (!tables_.contains(table_id)) {
// If not in memory, try loading from metadata
force_load_table_metadata();
}
return tables_.at(table_id);
}
table_data& table_storage::get_table_data(const std::string& table_name)
{
if (!table_exists(table_name)) {
// If not in memory, try loading from metadata
force_load_table_metadata();
}
for (auto& [_, table] : tables_) {
if (table.get_table_name() == table_name) {
return table;
}
}
return tables_.at(InvalidOid);
}
void table_storage::add_view(Oid view_oid, const std::string& view_name, const std::string& view_str)
{
if (view_exists(view_oid)) {
return;
}
std::string insert_str =
fmt::format("INSERT INTO public.pg_deeplake_views (view_name, query_string) VALUES ('{}', $${}$$) "
"ON CONFLICT (view_name) DO UPDATE SET query_string = EXCLUDED.query_string",
view_name,
view_str);
pg::utils::spi_connector connector;
if (SPI_execute(insert_str.c_str(), false, 0) != SPI_OK_INSERT) {
throw pg::exception("Failed to save view metadata");
}
views_.emplace(view_oid, std::pair{view_name, view_str});
up_to_date_ = false;
}
void table_storage::erase_view(const std::string& view_name)
{
Oid view_oid = RelnameGetRelid(view_name.c_str());
if (views_.erase(view_oid) == 0) {
return;
}
up_to_date_ = false;
pg::utils::memory_context_switcher context_switcher;
if (!pg::utils::check_table_exists("pg_deeplake_views")) {
return;
}
std::string delete_str = fmt::format("DELETE FROM public.pg_deeplake_views WHERE view_name = '{}'", view_name);
pg::utils::spi_connector connector;
if (SPI_execute(delete_str.c_str(), false, 0) != SPI_OK_DELETE) {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("Failed to erase view metadata")));
}
}
} // namespace pg