-
Notifications
You must be signed in to change notification settings - Fork 99
/
Copy pathpgduckdb_options.cpp
738 lines (622 loc) · 25.6 KB
/
pgduckdb_options.cpp
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
#include "duckdb.hpp"
#include <filesystem>
#include <fstream>
#include "pgduckdb/pgduckdb_types.hpp"
#include "pgduckdb/pgduckdb_utils.hpp"
#include "pgduckdb/pgduckdb_background_worker.hpp"
extern "C" {
#include "postgres.h"
#include "miscadmin.h"
#include "funcapi.h"
#include "access/genam.h"
#include "access/relation.h"
#include "access/table.h"
#include "access/xact.h"
#include "executor/spi.h"
#include "executor/execExpr.h"
#include "foreign/foreign.h"
#include "catalog/indexing.h"
#include "parser/parse_coerce.h"
#include "parser/parse_node.h"
#include "parser/parse_expr.h"
#include "nodes/subscripting.h"
#include "nodes/nodeFuncs.h"
#include "catalog/namespace.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/rel.h"
#include "utils/snapmgr.h"
#include "nodes/print.h"
#include "pgduckdb/vendor/pg_list.hpp"
}
#include "pgduckdb/pgduckdb_options.hpp"
#include "pgduckdb/pgduckdb_duckdb.hpp"
#include "pgduckdb/pgduckdb_xact.hpp"
#include "pgduckdb/pgduckdb_metadata_cache.hpp"
#include "pgduckdb/pgduckdb_userdata_cache.hpp"
#include "pgduckdb/utility/cpp_wrapper.hpp"
namespace pgduckdb {
static Oid
GetDuckdbNamespace(void) {
return get_namespace_oid("duckdb", false);
}
static Oid
ExtensionsTableRelationId(void) {
return get_relname_relid("extensions", GetDuckdbNamespace());
}
static std::string
DatumToString(Datum datum) {
return std::string(text_to_cstring(DatumGetTextPP(datum)));
}
std::vector<DuckdbExtension>
ReadDuckdbExtensions() {
HeapTuple tuple = NULL;
Oid duckdb_extension_table_relation_id = ExtensionsTableRelationId();
Relation duckdb_extension_relation = table_open(duckdb_extension_table_relation_id, AccessShareLock);
SysScanDescData *scan =
systable_beginscan(duckdb_extension_relation, InvalidOid, false, GetActiveSnapshot(), 0, NULL);
std::vector<DuckdbExtension> duckdb_extensions;
while (HeapTupleIsValid(tuple = systable_getnext(scan))) {
Datum datum_array[Natts_duckdb_extension];
bool is_null_array[Natts_duckdb_extension];
heap_deform_tuple(tuple, RelationGetDescr(duckdb_extension_relation), datum_array, is_null_array);
DuckdbExtension secret;
secret.name = DatumToString(datum_array[Anum_duckdb_extension_name - 1]);
secret.enabled = DatumGetBool(datum_array[Anum_duckdb_extension_enable - 1]);
duckdb_extensions.push_back(secret);
}
systable_endscan(scan);
table_close(duckdb_extension_relation, NoLock);
return duckdb_extensions;
}
static void
DuckdbInstallExtension(const std::string &extension_name, const std::string &repository) {
auto install_extension_command = "INSTALL " + duckdb::KeywordHelper::WriteQuoted(extension_name) + " FROM ";
if (repository == "core" || repository == "core_nightly" || repository == "community" ||
repository == "local_build_debug" || repository == "local_build_release") {
install_extension_command += repository;
} else {
install_extension_command += duckdb::KeywordHelper::WriteQuoted(repository);
}
/*
* Temporily allow all filesystems for this query, because INSTALL needs
* local filesystem access. Since this setting cannot be changed inside
* DuckDB after it's set to LocalFileSystem this temporary configuration
* change only really has effect duckdb.install_extension is called as the
* first DuckDB query for this session. Since we cannot change it back.
*
* While that's suboptimal it's also not a huge problem. Users only need to
* install an extension once on a server. So doing that on a new connection
* or after calling duckdb.recycle_ddb() should not be a big deal.
*
* NOTE: Because each backend has its own DuckDB instance, this setting
* does not impact other backends and thus cannot cause a security issue
* due to a race condition.
*/
auto save_nestlevel = NewGUCNestLevel();
SetConfigOption("duckdb.disabled_filesystems", "", PGC_SUSET, PGC_S_SESSION);
pgduckdb::DuckDBQueryOrThrow(install_extension_command);
AtEOXact_GUC(false, save_nestlevel);
Datum extension_name_datum = CStringGetTextDatum(extension_name.c_str());
Oid arg_types[] = {TEXTOID};
Datum values[] = {extension_name_datum};
SPI_connect();
auto ret = SPI_execute_with_args(R"(
INSERT INTO duckdb.extensions (name, enabled)
VALUES ($1, true)
ON CONFLICT (name) DO UPDATE SET enabled = true
)",
lengthof(arg_types), arg_types, values, NULL, false, 0);
if (ret != SPI_OK_INSERT)
elog(ERROR, "SPI_exec failed: error code %s", SPI_result_code_string(ret));
SPI_finish();
}
// Find a unique name for the server, based on the given prefix.
// The name is generated by appending an incrementing number to the prefix
// until a unique name is found. For example, if the prefix is "my_server",
// the function will try "my_server_1", "my_server_2", etc. until it finds
// a name that does not exist in the database.
//
// Technically we should do this under a lock to make sure no other connection
// process is creating the same server, though this is unlikely to happen.
std::string
FindServerName(const char *server_prefix) {
auto oid = get_foreign_server_oid(server_prefix, true);
if (oid == InvalidOid) {
return server_prefix;
}
uint32_t i = 0;
std::ostringstream oss;
oss << server_prefix << "_";
const auto len = oss.str().length();
while (true) {
oss.seekp(len);
oss << ++i;
auto server_name = oss.str();
if (get_foreign_server_oid(server_name.c_str(), true) == InvalidOid) {
return server_name;
}
}
}
namespace pg {
std::string
GetArgString(PG_FUNCTION_ARGS, int argno) {
if (PG_NARGS() <= argno) {
throw duckdb::InvalidInputException("argument %d is required", argno);
}
if (PG_ARGISNULL(argno)) {
throw duckdb::InvalidInputException("argument %d cannot be NULL", argno);
}
return DatumToString(PG_GETARG_DATUM(argno));
}
std::string
ReadOptions(FunctionCallInfo fcinfo, int start, const std::vector<std::string> &names) {
std::ostringstream oss;
int opt_idx = start;
for (const auto &name : names) {
auto value = GetArgString(fcinfo, opt_idx++);
if (value.empty()) {
continue;
}
if (!oss.str().empty()) {
oss << ", ";
}
oss << name << " " << duckdb::KeywordHelper::WriteQuoted(value);
}
return oss.str();
}
} // namespace pg
} // namespace pgduckdb
extern "C" {
DECLARE_PG_FUNCTION(install_extension) {
std::string extension_name = pgduckdb::pg::GetArgString(fcinfo, 0);
std::string repository = pgduckdb::pg::GetArgString(fcinfo, 1);
pgduckdb::DuckdbInstallExtension(extension_name, repository);
PG_RETURN_VOID();
}
DECLARE_PG_FUNCTION(pgduckdb_raw_query) {
const char *query = text_to_cstring(PG_GETARG_TEXT_PP(0));
auto result = pgduckdb::DuckDBQueryOrThrow(query);
elog(NOTICE, "result: %s", result->ToString().c_str());
PG_RETURN_BOOL(true);
}
DECLARE_PG_FUNCTION(pgduckdb_is_motherduck_enabled) {
PG_RETURN_BOOL(pgduckdb::IsMotherDuckEnabled());
}
DECLARE_PG_FUNCTION(pgduckdb_enable_motherduck) {
pgduckdb::pg::PreventInTransactionBlock("duckdb.enable_motherduck()");
if (pgduckdb::IsMotherDuckEnabled()) {
elog(NOTICE, "MotherDuck is already enabled");
PG_RETURN_BOOL(false);
}
auto token = pgduckdb::pg::GetArgString(fcinfo, 0);
auto default_database = pgduckdb::pg::GetArgString(fcinfo, 1);
// If no token provided, check that token exists in the environment
if (token == "::FROM_ENV::" && getenv("MOTHERDUCK_TOKEN") == nullptr && getenv("motherduck_token") == nullptr) {
elog(ERROR, "No token was provided and `motherduck_token` environment variable was not set");
}
SPI_connect_ext(SPI_OPT_NONATOMIC);
if (pgduckdb::GetMotherduckForeignServerOid() == InvalidOid) {
std::string query = "CREATE SERVER motherduck TYPE 'motherduck' FOREIGN DATA WRAPPER duckdb";
if (default_database.empty()) {
query += ";";
} else {
query += " OPTIONS (default_database " + duckdb::KeywordHelper::WriteQuoted(default_database) + ");";
}
auto ret = SPI_exec(query.c_str(), 0);
if (ret != SPI_OK_UTILITY) {
elog(ERROR, "Could not create 'motherduck' SERVER: %s", SPI_result_code_string(ret));
}
} else if (!default_database.empty()) {
// TODO: check if it was set to the same value and update it or only error in that case
elog(ERROR, "Cannot provide a default_database: because the server already exists");
}
{
// Create mapping for current user
auto query = "CREATE USER MAPPING FOR CURRENT_USER SERVER motherduck OPTIONS (token " +
duckdb::KeywordHelper::WriteQuoted(token) + ");";
auto ret = SPI_exec(query.c_str(), 0);
if (ret != SPI_OK_UTILITY) {
elog(ERROR, "Could not create USER MAPPING for current user: %s", SPI_result_code_string(ret));
}
}
/*
* New we need to start the background worker, so that the table sync
* starts. We need to first commit though, otherwise if the background
* worker starts quick enough, it will not see that we enabled motherduck
* (i.e. it does not see the motherduck SERVER).
*/
SPI_commit();
SPI_finish();
pgduckdb::StartBackgroundWorkerIfNeeded();
PG_RETURN_VOID();
}
DECLARE_PG_FUNCTION(pgduckdb_create_simple_secret) {
auto type = pgduckdb::pg::GetArgString(fcinfo, 0);
auto lc_type = duckdb::StringUtil::Lower(type);
if (lc_type != "r2" && lc_type != "s3" && lc_type != "gcs") {
elog(ERROR,
"Invalid type '%s': this helper only supports 's3', 'gcs' or 'r2'. Please refer to the documentation to "
"create advanced secrets.",
type.c_str());
}
auto key = pgduckdb::pg::GetArgString(fcinfo, 1);
auto secret = pgduckdb::pg::GetArgString(fcinfo, 2);
auto session_token = pgduckdb::pg::GetArgString(fcinfo, 3);
auto secret_name = "simple_" + lc_type + "_secret";
SPI_connect();
auto server_name = pgduckdb::FindServerName(secret_name.c_str());
{
std::ostringstream create_server_query;
create_server_query << "CREATE SERVER " << server_name << " TYPE '" << type << "' FOREIGN DATA WRAPPER duckdb";
auto options = pgduckdb::pg::ReadOptions(fcinfo, 4, {"region", "url_style", "provider", "endpoint"});
if (!options.empty()) {
create_server_query << " OPTIONS (" << options << ")";
}
auto ret = SPI_exec(create_server_query.str().c_str(), 0);
if (ret != SPI_OK_UTILITY) {
elog(ERROR, "Could not create '%s' SERVER: %s", type.c_str(), SPI_result_code_string(ret));
}
}
{
std::ostringstream create_mapping_query;
create_mapping_query << "CREATE USER MAPPING FOR CURRENT_USER SERVER " << server_name << " OPTIONS (KEY_ID "
<< duckdb::KeywordHelper::WriteQuoted(key) << ", SECRET "
<< duckdb::KeywordHelper::WriteQuoted(secret);
if (!session_token.empty()) {
create_mapping_query << ", session_token " << duckdb::KeywordHelper::WriteQuoted(session_token);
}
create_mapping_query << ");";
auto ret = SPI_exec(create_mapping_query.str().c_str(), 0);
if (ret != SPI_OK_UTILITY) {
elog(ERROR, "Could not create '%s' USER MAPPING: %s", type.c_str(), SPI_result_code_string(ret));
}
}
SPI_finish();
auto result = cstring_to_text(server_name.c_str());
PG_RETURN_TEXT_P(result);
}
DECLARE_PG_FUNCTION(pgduckdb_create_azure_secret) {
// XXX: Should this install `azure` if not already installed? Or fail if not?
auto connection_string = pgduckdb::pg::GetArgString(fcinfo, 0);
SPI_connect();
auto server_name = pgduckdb::FindServerName("azure_secret");
{
auto create_server_query = "CREATE SERVER " + server_name + " TYPE 'azure' FOREIGN DATA WRAPPER duckdb";
auto ret = SPI_exec(create_server_query.c_str(), 0);
if (ret != SPI_OK_UTILITY) {
elog(ERROR, "Could not create 'azure' SERVER: %s", SPI_result_code_string(ret));
}
}
auto query = "CREATE USER MAPPING FOR CURRENT_USER SERVER " + server_name + " OPTIONS (connection_string " +
duckdb::KeywordHelper::WriteQuoted(connection_string) + ");";
auto ret = SPI_exec(query.c_str(), 0);
if (ret != SPI_OK_UTILITY) {
elog(ERROR, "Could not create 'azure' USER MAPPING: %s", SPI_result_code_string(ret));
}
SPI_finish();
auto result = cstring_to_text(server_name.c_str());
PG_RETURN_TEXT_P(result);
}
/*
* We need these dummy cache functions so that people are able to load the
* new pg_duckdb.so file with an old SQL version (where these functions still
* exist). People should then upgrade the SQL part of the extension using the
* command described in the error message. Once we believe no-one is on these old
* version anymore we can remove these dummy functions.
*/
DECLARE_PG_FUNCTION(cache) {
elog(ERROR, "duckdb.cache is not supported anymore, please run 'ALTER EXTENSION pg_duckdb UPDATE'");
}
DECLARE_PG_FUNCTION(cache_info) {
elog(ERROR, "duckdb.cache_info is not supported anymore, please run 'ALTER EXTENSION pg_duckdb UPDATE'");
}
DECLARE_PG_FUNCTION(cache_delete) {
elog(ERROR, "duckdb.cache_delete is not supported anymore, please run 'ALTER EXTENSION pg_duckdb UPDATE'");
}
DECLARE_PG_FUNCTION(pgduckdb_recycle_ddb) {
pgduckdb::RequireDuckdbExecution();
/*
* We cannot safely run this in a transaction block, because a DuckDB
* transaction might have already started. Recycling the database will
* violate our assumptions about DuckDB its transaction lifecycle
*/
pgduckdb::pg::PreventInTransactionBlock("duckdb.recycle_ddb()");
pgduckdb::DuckDBManager::Get().Reset();
PG_RETURN_BOOL(true);
}
Node *
CoerceSubscriptToText(struct ParseState *pstate, A_Indices *subscript, const char *type_name) {
if (!subscript->uidx) {
elog(ERROR, "Creating a slice out of %s is not supported", type_name);
}
Node *subscript_expr = transformExpr(pstate, subscript->uidx, pstate->p_expr_kind);
int expr_location = exprLocation(subscript->uidx);
Oid subscript_expr_type = exprType(subscript_expr);
if (subscript->lidx) {
elog(ERROR, "Creating a slice out of %s is not supported", type_name);
}
Node *coerced_expr = coerce_to_target_type(pstate, subscript_expr, subscript_expr_type, TEXTOID, -1,
COERCION_IMPLICIT, COERCE_IMPLICIT_CAST, expr_location);
if (!coerced_expr) {
ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), errmsg("%s subscript must have text type", type_name),
parser_errposition(pstate, expr_location)));
}
if (!IsA(subscript_expr, Const)) {
ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), errmsg("%s subscript must be a constant", type_name),
parser_errposition(pstate, expr_location)));
}
Const *subscript_const = castNode(Const, subscript_expr);
if (subscript_const->constisnull) {
ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("%s subscript cannot be NULL", type_name),
parser_errposition(pstate, expr_location)));
}
return coerced_expr;
}
Node *
CoerceRowSubscriptToText(struct ParseState *pstate, A_Indices *subscript) {
return CoerceSubscriptToText(pstate, subscript, "duckdb.row");
}
// Cloned implementation from CoerceRowSubscriptToText
Node *
CoerceStructSubscriptToText(struct ParseState *pstate, A_Indices *subscript) {
return CoerceSubscriptToText(pstate, subscript, "duckdb.struct");
}
/*
* In Postgres all index operations in a row ar all slices or all plain
* index operations. If you mix them, all are converted to slices.
* There's no difference in representation possible between
* "col[1:2][1]" and "col[1:2][1:]". If you want this seperation you
* need to use parenthesis to seperate: "(col[1:2])[1]"
* This might seem like fairly strange behaviour, but Postgres uses
* this to be able to slice in multi-dimensional arrays and thtis
* behaviour is documented here:
* https://www.postgresql.org/docs/current/arrays.html#ARRAYS-ACCESSING
*
* This is different from DuckDB, but there's not much we can do about
* that. So we'll have this same behaviour by, which means we need to always
* add the lower subscript to the slice. The lower subscript will be NULL in
* that case.
*
* See also comments on SubscriptingRef in nodes/subscripting.h
*/
void
AddSubscriptExpressions(SubscriptingRef *sbsref, struct ParseState *pstate, A_Indices *subscript, bool isSlice) {
Assert(isSlice || subscript->uidx);
Node *upper_subscript_expr = NULL;
if (subscript->uidx) {
upper_subscript_expr = transformExpr(pstate, subscript->uidx, pstate->p_expr_kind);
}
sbsref->refupperindexpr = lappend(sbsref->refupperindexpr, upper_subscript_expr);
if (isSlice) {
Node *lower_subscript_expr = NULL;
if (subscript->uidx) {
lower_subscript_expr = transformExpr(pstate, subscript->lidx, pstate->p_expr_kind);
}
sbsref->reflowerindexpr = lappend(sbsref->reflowerindexpr, lower_subscript_expr);
}
}
/*
* DuckdbSubscriptTransform is called by the parser when a subscripting
* operation is performed on a duckdb.row. It has two main puprposes:
* 1. Ensure that the row is being indexed using a string literal
* 2. Ensure that the return type of this index operation is duckdb.unresolved_type
*/
void
DuckdbSubscriptTransform(SubscriptingRef *sbsref, List *indirection, struct ParseState *pstate, bool isSlice,
bool isAssignment, const char *type_name) {
/*
* We need to populate our cache for some of the code below. Normally this
* cache is populated at the start of our planner hook, but this function
* is being called from the parser.
*/
if (!pgduckdb::IsExtensionRegistered()) {
elog(ERROR, "BUG: Using %s but the pg_duckdb extension is not installed", type_name);
}
if (isAssignment) {
elog(ERROR, "Assignment to %s is not supported", type_name);
}
if (indirection == NIL) {
elog(ERROR, "Subscripting %s with an empty subscript is not supported", type_name);
}
bool first = true;
// Transform each subscript expression
foreach_node(A_Indices, subscript, indirection) {
/* The first subscript needs to be a TEXT constant, since it should be
* a column reference. But the subscripts after that can be anything,
* DuckDB should interpret those. */
if (first) {
sbsref->refupperindexpr = lappend(sbsref->refupperindexpr, CoerceRowSubscriptToText(pstate, subscript));
if (isSlice) {
sbsref->reflowerindexpr = lappend(sbsref->reflowerindexpr, NULL);
}
first = false;
continue;
}
AddSubscriptExpressions(sbsref, pstate, subscript, isSlice);
}
// Set the result type of the subscripting operation
sbsref->refrestype = pgduckdb::DuckdbUnresolvedTypeOid();
sbsref->reftypmod = -1;
}
void
DuckdbRowSubscriptTransform(SubscriptingRef *sbsref, List *indirection, struct ParseState *pstate, bool isSlice,
bool isAssignment) {
DuckdbSubscriptTransform(sbsref, indirection, pstate, isSlice, isAssignment, "duckdb.row");
}
void
DuckdbStructSubscriptTransform(SubscriptingRef *sbsref, List *indirection, struct ParseState *pstate, bool isSlice,
bool isAssignment) {
DuckdbSubscriptTransform(sbsref, indirection, pstate, isSlice, isAssignment, "duckdb.struct");
}
static bool
DuckdbSubscriptCheckSubscripts(ExprState * /*state*/, ExprEvalStep *op, ExprContext * /*econtext*/) {
SubscriptingRefState *sbsrefstate = op->d.sbsref_subscript.state;
char *type_name = strVal(sbsrefstate->workspace);
elog(ERROR, "Subscripting %s is not supported in the Postgres Executor", type_name);
}
static void
DuckdbSubscriptFetch(ExprState * /*state*/, ExprEvalStep *op, ExprContext * /*econtext*/) {
SubscriptingRefState *sbsrefstate = op->d.sbsref_subscript.state;
char *type_name = strVal(sbsrefstate->workspace);
elog(ERROR, "Subscripting %s is not supported in the Postgres Executor", type_name);
}
static void
DuckdbSubscriptAssign(ExprState * /*state*/, ExprEvalStep *op, ExprContext * /*econtext*/) {
SubscriptingRefState *sbsrefstate = op->d.sbsref_subscript.state;
char *type_name = strVal(sbsrefstate->workspace);
elog(ERROR, "Subscripting %s is not supported in the Postgres Executor", type_name);
}
static void
DuckdbSubscriptFetchOld(ExprState * /*state*/, ExprEvalStep *op, ExprContext * /*econtext*/) {
SubscriptingRefState *sbsrefstate = op->d.sbsref_subscript.state;
char *type_name = strVal(sbsrefstate->workspace);
elog(ERROR, "Subscripting %s is not supported in the Postgres Executor", type_name);
}
/*
* DuckdbSubscriptExecSetup stores a bunch of functions in the methods
* structure. These functions are called by the Postgres executor when a
* subscripting is executed. We need to implement this function, because it is
* called for materialized CTEs. Even in that case the actual functions that
* are stored in methods are never supposed to be called, because pg_duckdb
* shouldn't force usage of DuckDB execution when duckdb types are present in
* the query. So these methods are just stubs that throw an error when called.
*/
void
DuckdbSubscriptExecSetup(const SubscriptingRef * /*sbsref*/, SubscriptingRefState *sbsrefstate,
SubscriptExecSteps *methods, const char *type_name) {
sbsrefstate->workspace = makeString(pstrdup(type_name));
methods->sbs_check_subscripts = DuckdbSubscriptCheckSubscripts;
methods->sbs_fetch = DuckdbSubscriptFetch;
methods->sbs_assign = DuckdbSubscriptAssign;
methods->sbs_fetch_old = DuckdbSubscriptFetchOld;
}
void
DuckdbRowSubscriptExecSetup(const SubscriptingRef *sbsref, SubscriptingRefState *sbsrefstate,
SubscriptExecSteps *methods) {
DuckdbSubscriptExecSetup(sbsref, sbsrefstate, methods, "duckdb.row");
}
void
DuckdbStructSubscriptExecSetup(const SubscriptingRef *sbsref, SubscriptingRefState *sbsrefstate,
SubscriptExecSteps *methods) {
DuckdbSubscriptExecSetup(sbsref, sbsrefstate, methods, "duckdb.struct");
}
static SubscriptRoutines duckdb_row_subscript_routines = {
.transform = DuckdbRowSubscriptTransform,
.exec_setup = DuckdbRowSubscriptExecSetup,
.fetch_strict = false,
.fetch_leakproof = true,
.store_leakproof = true,
};
DECLARE_PG_FUNCTION(duckdb_row_subscript) {
PG_RETURN_POINTER(&duckdb_row_subscript_routines);
}
static SubscriptRoutines duckdb_struct_subscript_routines = {
.transform = DuckdbStructSubscriptTransform,
.exec_setup = DuckdbStructSubscriptExecSetup,
.fetch_strict = false,
.fetch_leakproof = true,
.store_leakproof = true,
};
DECLARE_PG_FUNCTION(duckdb_struct_subscript) {
PG_RETURN_POINTER(&duckdb_struct_subscript_routines);
}
/*
* DuckdbUnresolvedTypeSubscriptTransform is called by the parser when a
* subscripting operation is performed on a duckdb.unresolved_type. All this
* does is parse ensre that any subscript on duckdb.unresolved_type returns an
* unrsolved type again.
*/
void
DuckdbUnresolvedTypeSubscriptTransform(SubscriptingRef *sbsref, List *indirection, struct ParseState *pstate,
bool isSlice, bool isAssignment) {
/*
* We need to populate our cache for some of the code below. Normally this
* cache is populated at the start of our planner hook, but this function
* is being called from the parser.
*/
if (!pgduckdb::IsExtensionRegistered()) {
elog(ERROR, "BUG: Using duckdb.unresolved_type but the pg_duckdb extension is not installed");
}
if (isAssignment) {
elog(ERROR, "Assignment to duckdb.unresolved_type is not supported");
}
if (indirection == NIL) {
elog(ERROR, "Subscripting duckdb.row with an empty subscript is not supported");
}
// Transform each subscript expression
foreach_node(A_Indices, subscript, indirection) {
AddSubscriptExpressions(sbsref, pstate, subscript, isSlice);
}
// Set the result type of the subscripting operation
sbsref->refrestype = pgduckdb::DuckdbUnresolvedTypeOid();
sbsref->reftypmod = -1;
}
/*
* DuckdbUnresolvedTypeSubscriptExecSetup is called by the executor when a
* subscripting operation is performed on a duckdb.unresolved_type. This should
* never happen, because any query that contains a duckdb.unresolved_type should
* automatically be use DuckDB execution.
*/
void
DuckdbUnresolvedTypeSubscriptExecSetup(const SubscriptingRef * /*sbsref*/, SubscriptingRefState * /*sbsrefstate*/,
SubscriptExecSteps * /*exprstate*/) {
elog(ERROR, "Subscripting duckdb.unresolved_type is not supported in the Postgres Executor");
}
static SubscriptRoutines duckdb_unresolved_type_subscript_routines = {
.transform = DuckdbUnresolvedTypeSubscriptTransform,
.exec_setup = DuckdbUnresolvedTypeSubscriptExecSetup,
.fetch_strict = false,
.fetch_leakproof = true,
.store_leakproof = true,
};
DECLARE_PG_FUNCTION(duckdb_unresolved_type_subscript) {
PG_RETURN_POINTER(&duckdb_unresolved_type_subscript_routines);
}
DECLARE_PG_FUNCTION(duckdb_row_in) {
elog(ERROR, "Creating the duckdb.row type is not supported");
}
DECLARE_PG_FUNCTION(duckdb_row_out) {
elog(ERROR, "Converting a duckdb.row to a string is not supported");
}
DECLARE_PG_FUNCTION(duckdb_struct_in) {
elog(ERROR, "Creating the duckdb.struct type is not supported");
}
DECLARE_PG_FUNCTION(duckdb_struct_out) {
return textout(fcinfo);
}
DECLARE_PG_FUNCTION(duckdb_unresolved_type_in) {
return textin(fcinfo);
}
DECLARE_PG_FUNCTION(duckdb_unresolved_type_out) {
return textout(fcinfo);
}
DECLARE_PG_FUNCTION(duckdb_unresolved_type_operator) {
elog(ERROR, "Unresolved duckdb types cannot be used by the Postgres executor");
}
DECLARE_PG_FUNCTION(duckdb_only_function) {
char *function_name = DatumGetCString(DirectFunctionCall1(regprocout, fcinfo->flinfo->fn_oid));
elog(ERROR, "Function '%s' only works with DuckDB execution", function_name);
}
DECLARE_PG_FUNCTION(duckdb_union_in) {
elog(ERROR, "Creating the duckdb.union type is not supported");
}
DECLARE_PG_FUNCTION(duckdb_union_out) {
return textout(fcinfo);
}
DECLARE_PG_FUNCTION(duckdb_map_in) {
elog(ERROR, "Creating the duckdb.map type is not supported");
}
DECLARE_PG_FUNCTION(duckdb_map_out) {
return textout(fcinfo);
}
DECLARE_PG_FUNCTION(pgduckdb_test_escape_uri) {
auto input = pgduckdb::pg::GetArgString(fcinfo, 0);
std::ostringstream oss;
pgduckdb::AppendEscapedUri(oss, input.c_str());
auto result = oss.str();
auto text_result = cstring_to_text(result.c_str());
PG_RETURN_TEXT_P(text_result);
}
} // extern "C"