-
Notifications
You must be signed in to change notification settings - Fork 99
Expand file tree
/
Copy pathcreate_table.c
More file actions
1827 lines (1514 loc) · 56.1 KB
/
create_table.c
File metadata and controls
1827 lines (1514 loc) · 56.1 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
/*
* Copyright 2025 Snowflake Inc.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "postgres.h"
#include "miscadmin.h"
#include "access/table.h"
#include "access/tableam.h"
#include "access/relation.h"
#include "catalog/namespace.h"
#include "catalog/pg_attribute.h"
#include "catalog/pg_class.h"
#include "commands/dbcommands.h"
#include "commands/defrem.h"
#include "commands/extension.h"
#include "commands/tablecmds.h"
#include "common/string.h"
#include "foreign/foreign.h"
#include "nodes/makefuncs.h"
#include "nodes/nodes.h"
#include "nodes/value.h"
#include "parser/parse_type.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
#include "utils/inval.h"
#include "pg_lake/access_method/access_method.h"
#include "pg_lake/copy/copy_format.h"
#include "pg_lake/ddl/alter_table.h"
#include "pg_lake/ddl/ddl_changes.h"
#include "pg_lake/ddl/create_table.h"
#include "pg_lake/ddl/utility_hook.h"
#include "pg_lake/describe/describe.h"
#include "pg_lake/extensions/pg_lake_iceberg.h"
#include "pg_lake/extensions/pg_lake_table.h"
#include "pg_lake/extensions/pg_lake_spatial.h"
#include "pg_lake/extensions/postgis.h"
#include "pg_lake/fdw/pg_lake_table.h"
#include "pg_lake/partitioning/partition_by_parser.h"
#include "pg_lake/fdw/row_ids.h"
#include "pg_lake/fdw/schema_operations/field_id_mapping_catalog.h"
#include "pg_lake/fdw/schema_operations/register_field_ids.h"
#include "pg_lake/iceberg/api.h"
#include "pg_lake/iceberg/catalog.h"
#include "pg_lake/util/numeric.h"
#include "pg_lake/util/rel_utils.h"
#include "pg_lake/util/url_encode.h"
#include "pg_lake/parsetree/options.h"
#include "pg_lake/partitioning/partition_spec_catalog.h"
#include "pg_lake/pgduck/client.h"
#include "pg_lake/pgduck/map.h"
#include "pg_lake/pgduck/numeric.h"
#include "pg_lake/pgduck/read_data.h"
#include "pg_lake/pgduck/region.h"
#include "pg_lake/pgduck/remote_storage.h"
#include "pg_lake/pgduck/type.h"
#include "pg_lake/planner/dbt.h"
#include "pg_lake/query/execute.h"
#include "pg_lake/object_store_catalog/object_store_catalog.h"
#include "pg_lake/transaction/track_iceberg_metadata_changes.h"
#include "pg_lake/rest_catalog/rest_catalog.h"
/* reserved column hook */
PgLakeIsReservedColumnNameHookType PgLakeIsReservedColumnNameHook = NULL;
static bool IsCreateLakeTable(CreateForeignTableStmt *createStmt);
static void AddLakeTableColumnDefinitions(CreateForeignTableStmt *createStmt);
static bool IsJsonOrCSVBackedTable(PgLakeTableType tableType, List *options);
static void ErrorIfUnsupportedColumnTypeForJsonOrCSVTables(List *columnDefList);
static void ErrorIfUsingGeometryWithoutSpatialAnalytics(List *columnDefList);
static void ErrorIfUnsupportedLakeTable(CreateForeignTableStmt *createStmt);
static void ErrorIfWritableTableWithReservedColumnName(List *columnDefList, PgLakeTableType tableType);
static void ErrorIfInvalidFilenameColumn(List *columnDefList);
static bool IsConflictingColumnNameForReadParquet(const char *columnName);
static CreateForeignTableStmt *GetCreateIcebergForeignTableStmtFromCreateStmt(CreateStmt *createStmt);
static void EnsureCreateIcebergTableColumnOptions(CreateStmt *createStmt);
static void EnsureCreateIcebergTableSupported(CreateStmt *createStmt);
static List *ExpandTableElements(List *tableElements);
static List *ExpandTableLikeClause(TableLikeClause *table_like_clause);
static bool ProcessCreateLakeTable(ProcessUtilityParams * params);
static bool ProcessCreateIcebergTableFromForeignTableStmt(ProcessUtilityParams * params);
static bool ProcessCreateIcebergTableFromCreateStmt(ProcessUtilityParams * params);
static void ErrorIfNotInManagedStorageRegion(char *location);
static void ErrorIfTypeUnsupportedForIcebergTablesInternal(Oid typeOid, int32 typmod, int level, char *columnName);
static void ErrorIfLocationIsNotEmpty(const char *location);
static void EnsureSupportedIcebergTableColumnDefinitions(List *columnDefList);
#if PG_VERSION_NUM >= 180000
static void ErrorIfTableContainsVirtualColumns(List *columnDefList);
#endif
static void ErrorIfTableContainsUnsupportedTypes(List *columnDefList);
static char *SetIcebergTableLocationOptionFromDefaultPrefix(Oid relationId,
const char *defaultLocationPrefix,
char *databaseName,
char *schemaName, char *tableName);
/*
* CreatePgLakeTableCheckUnsupportedFeaturesPostProcess is a utility statement handler
* for checking unsupported features in CREATE FOREIGN TABLE statements that have to be called
* after the table has been created.
*
* We currently check for unsupported column types in CSV backed tables. It is much simpler
* to check for these features after the table has been created, such that Postgres has
* already done the heavy lifting of parsing the column definitions (e.g., bigserial is already
* converted to int8, etc.)
*/
void
CreatePgLakeTableCheckUnsupportedFeaturesPostProcess(ProcessUtilityParams * params, void *arg)
{
PlannedStmt *plannedStmt = params->plannedStmt;
if (!IsA(plannedStmt->utilityStmt, CreateForeignTableStmt))
{
/* not a foreign table */
return;
}
CreateForeignTableStmt *createStmt =
(CreateForeignTableStmt *) plannedStmt->utilityStmt;
if (!IsCreateLakeTable(createStmt))
{
/* not a lake table */
return;
}
PgLakeTableType tableType =
GetPgLakeTableTypeViaServerName(createStmt->servername);
List *options = createStmt->options;
/* Parquet and JSON/CSV have different rules */
if (IsJsonOrCSVBackedTable(tableType, options))
{
ErrorIfUnsupportedColumnTypeForJsonOrCSVTables(createStmt->base.tableElts);
}
/* cannot use geometry without pg_lake_spatial */
ErrorIfUsingGeometryWithoutSpatialAnalytics(createStmt->base.tableElts);
}
/*
* IsJsonOrCSVBackedTable returns whether the given table is backed by a JSON
* or CSV file. It supports both the regular pg_lake tables
* and the writable pg_lake tables.
*/
static bool
IsJsonOrCSVBackedTable(PgLakeTableType tableType, List *options)
{
DefElem *pathOption = GetOption(options, "path");
char *path = NULL;
if (pathOption != NULL)
{
path = defGetString(pathOption);
}
CopyDataFormat format = DATA_FORMAT_INVALID;
CopyDataCompression compression = DATA_COMPRESSION_INVALID;
FindDataFormatAndCompression(tableType, path, options, &format, &compression);
return (format == DATA_FORMAT_CSV || format == DATA_FORMAT_JSON);
}
/*
* ErrorIfUnsupportedColumnTypeForJsonOrCSVTables checks whether the given column
* definitions are supported for JSON/CSV backed pg_lake tables.
*/
static void
ErrorIfUnsupportedColumnTypeForJsonOrCSVTables(List *columnDefList)
{
ListCell *columnDefCell;
List *restrictedColumnDefList =
GetRestrictedColumnDefList(columnDefList);
foreach(columnDefCell, restrictedColumnDefList)
{
ColumnDef *columnDef = (ColumnDef *) lfirst(columnDefCell);
int32 typmod = 0;
Oid typeOid = InvalidOid;
typenameTypeIdAndMod(NULL, columnDef->typeName, &typeOid, &typmod);
/*
* We prevent arrays, bytea, and structs because we perform pushdown
* operations on them. This breaks in CSV/JSON as we can't yet parse
* PostgreSQL array/composite/bytea syntax from DuckDB. Other types
* are either not pushed down or are treated as text.
*/
if (type_is_array(typeOid))
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("array types are not "
"supported for JSON/CSV backed pg_lake tables")));
if (get_typtype(typeOid) == TYPTYPE_COMPOSITE)
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("composite types are not "
"supported for JSON/CSV backed pg_lake tables")));
if (typeOid == BYTEAOID)
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("bytea type is not "
"supported for JSON/CSV backed pg_lake tables")));
}
}
/*
* GetRestrictedColumnDefList returns a list of column definitions that are not
* pseudo-serial columns, LIKE or Constraint clauses.
*
* These are the column definitions that shows up in pre-utility hooks.
* However, due to a bug in other extension (e.g., Citus), we might see
* these pseudo-serial columns in the column definitions. See #863 for the
* details.
*
* So, we filter out these pseudo-serial columns, LIKE and Constraint clauses
* to get the actual column definitions.
*/
List *
GetRestrictedColumnDefList(List *columnDefList)
{
List *restrictedColumnDefList = NIL;
ListCell *columnDefCell;
foreach(columnDefCell, columnDefList)
{
if (!IsA(lfirst(columnDefCell), ColumnDef))
{
/* could be LIKE clause or constraint clause */
continue;
}
ColumnDef *columnDef = (ColumnDef *) lfirst(columnDefCell);
/*
* might be null for partitions when specified constraint for parent
* column. e.g. CREATE TABLE child_table PARTITION OF parent_table (a
* unique) FOR VALUES FROM (0) TO (10);
*/
if (columnDef->typeName == NULL)
{
continue;
}
if (ColumnDefIsPseudoSerial(columnDef))
{
/*
* serial etc. is supported for iceberg tables, but
* typenameTypeIdAndMod() cannot resolve the type for these
* pseudo-types. We skip these.
*/
continue;
}
restrictedColumnDefList = lappend(restrictedColumnDefList, columnDef);
}
return restrictedColumnDefList;
}
/*
* ErrorIfUsingGeometryWithoutSpatialAnalytics throws an error if there is
* a geometry column, but pg_lake_spatial does not exist.
*
* We rely on pg_lake_spatial to push down certain PostGIS functions.
* Users will get errors for queries that involve those function at some point,
* perhaps in future releases, so we prefer to error out aggressively at
* CREATE TABLE time.
*/
static void
ErrorIfUsingGeometryWithoutSpatialAnalytics(List *columnDefList)
{
ListCell *columnDefCell;
List *restrictedColumnDefList =
GetRestrictedColumnDefList(columnDefList);
foreach(columnDefCell, restrictedColumnDefList)
{
ColumnDef *columnDef = (ColumnDef *) lfirst(columnDefCell);
int32 typmod = 0;
Oid typeOid = InvalidOid;
typenameTypeIdAndMod(NULL, columnDef->typeName, &typeOid, &typmod);
if (IsGeometryTypeId(typeOid))
ErrorIfPgLakeSpatialNotEnabled();
}
}
/*
* ErrorUnsupportedCreatePgLakeTableHandler is a utility statement handler for handling
* CREATE FOREIGN TABLE statements that are pg_lake tables.
*
* We check for unsupported features in the table definition, such as unsupported URLs or unsupported
* combinations such as writable tables without column definitions.
*/
bool
ErrorUnsupportedCreatePgLakeTableHandler(ProcessUtilityParams * params, void *arg)
{
PlannedStmt *plannedStmt = params->plannedStmt;
if (!IsA(plannedStmt->utilityStmt, CreateForeignTableStmt))
{
/* not a foreign table */
return false;
}
CreateForeignTableStmt *createStmt =
(CreateForeignTableStmt *) plannedStmt->utilityStmt;
if (!IsCreateLakeTable(createStmt))
{
/* not a lake table */
return false;
}
ErrorIfUnsupportedLakeTable(createStmt);
return false;
}
/*
* ErrorIfUnsupportedLakeTable is a helper function for checking unsupported features
* in CREATE FOREIGN TABLE statements that are pg_lake tables.
*/
static void
ErrorIfUnsupportedLakeTable(CreateForeignTableStmt *createStmt)
{
List *options = createStmt->options;
DefElem *pathOption = GetOption(options, "path");
char *path = pathOption != NULL ? ResolveStageURL(defGetString(pathOption)) : "";
DefElem *locationOption = GetOption(options, "location");
char *location = locationOption != NULL ? defGetString(locationOption) : "";
bool isWritable = GetBoolOption(createStmt->options, "writable", false);
if (isWritable && createStmt->base.tableElts == NIL &&
createStmt->base.partbound == NULL)
ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR),
errmsg("column list cannot be empty for writable "
"pg_lake tables")));
if (!isWritable && pathOption == NULL)
ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR),
errmsg("\"path\" option is required for regular "
"pg_lake tables")));
if (!isWritable && !IsSupportedURL(path))
{
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("pg_lake_table: only s3://, gs://, az://, azure://, abfss://, hf://, and r2:// URLs are "
"currently supported")));
}
else if (isWritable && !IsSupportedURL(location))
{
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("pg_lake_table: only s3://, gs://, az://, azure://, abfss://, hf://, and r2:// URLs are "
"currently supported")));
}
if (isWritable)
ErrorIfWritableTableWithReservedColumnName(createStmt->base.tableElts, PG_LAKE_TABLE_TYPE);
#if PG_VERSION_NUM >= 180000
ErrorIfTableContainsVirtualColumns(createStmt->base.tableElts);
#endif
}
/*
* ErrorIfWritableTableWithReservedColumnName errors if column list contains a column
* with a reserved column name, which is also returned by duckdb's "read_parquet"
* function.
*/
static void
ErrorIfWritableTableWithReservedColumnName(List *columnDefList, PgLakeTableType tableType)
{
ListCell *columnDefCell = NULL;
foreach(columnDefCell, columnDefList)
{
/* could be LIKE clause or constraint clause */
if (!IsA(lfirst(columnDefCell), ColumnDef))
{
continue;
}
ColumnDef *columnDef = (ColumnDef *) lfirst(columnDefCell);
if (IsConflictingColumnNameForReadParquet(columnDef->colname))
{
const char *tableTypeStr = PgLakeTableTypeToName(tableType);
ereport(ERROR, (errcode(ERRCODE_RESERVED_NAME),
errmsg("pg_lake_table: column name \"%s\" is reserved for "
"%s tables", columnDef->colname, tableTypeStr),
errhint("Please use a different column name.")));
}
}
}
/*
* ErrorIfInvalidFilenameColumn errors if the _filename column is not in the last place.
*/
static void
ErrorIfInvalidFilenameColumn(List *columnDefList)
{
ListCell *columnDefCell = NULL;
bool hasFilenameColumn = false;
foreach(columnDefCell, columnDefList)
{
/* could be LIKE clause or constraint clause */
if (!IsA(lfirst(columnDefCell), ColumnDef))
continue;
ColumnDef *columnDef = (ColumnDef *) lfirst(columnDefCell);
if (strcmp(columnDef->colname, "_filename") != 0)
continue;
int32 typmod = 0;
Oid typeOid = InvalidOid;
bool missingOK = true;
Type typeTuple = LookupTypeName(NULL, columnDef->typeName, &typmod, missingOK);
if (typeTuple != NULL)
{
typeOid = typeTypeId(typeTuple);
ReleaseSysCache(typeTuple);
}
if (typeOid != TEXTOID)
{
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("_filename column must have type text")));
}
hasFilenameColumn = true;
}
if (!hasFilenameColumn)
{
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("no _filename column found"),
errdetail("When using the filename option, the last column "
"must be _filename text")));
}
}
/*
* IsConflictingColumnNameForReadParquet returns true if given column name
* is a column name which is also returned by duckdb's "read_parquet" calls.
*
* We rely on Duckdb's file_row_number and filename columns during
* read_parquet calls.
*/
bool
IsConflictingColumnNameForReadParquet(const char *columnName)
{
const char *reservedColumnNames[] = {"file_row_number", INTERNAL_FILENAME_COLUMN_NAME};
const int numReservedColumnNames = sizeof(reservedColumnNames) / sizeof(reservedColumnNames[0]);
for (int reservedNameIndex = 0; reservedNameIndex < numReservedColumnNames; reservedNameIndex++)
{
if (pg_strcasecmp(columnName, reservedColumnNames[reservedNameIndex]) == 0)
{
return true;
}
}
/* if we have a hook to check additional columns, call it now */
if (PgLakeIsReservedColumnNameHook)
return PgLakeIsReservedColumnNameHook(columnName);
return false;
}
/*
* ProcessPgLakeTable is a utility statement handler for handling
* statements for creating pg_lake tables.
*
* Currently this code implements:
* 1. Adding columns definitions to lake tables:
* - CREATE FOREIGN TABLE name () SERVER pg_lake OPTIONS (path 's3://...')
*
* 2. CREATE TABLE USING syntax for iceberg tables:
* - CREATE TABLE name (<col_defs>) USING pg_lake_iceberg WITH (location = <>)
*/
bool
ProcessCreatePgLakeTable(ProcessUtilityParams * params, void *arg)
{
PlannedStmt *plannedStmt = params->plannedStmt;
if (IsA(plannedStmt->utilityStmt, CreateForeignTableStmt))
{
CreateForeignTableStmt *createStmt =
(CreateForeignTableStmt *) plannedStmt->utilityStmt;
if (IsPgLakeIcebergServerName(createStmt->servername))
{
return ProcessCreateIcebergTableFromForeignTableStmt(params);
}
else if (IsPgLakeServerName(createStmt->servername))
{
return ProcessCreateLakeTable(params);
}
}
else if (IsA(plannedStmt->utilityStmt, CreateStmt))
{
return ProcessCreateIcebergTableFromCreateStmt(params);
}
return false;
}
/*
* ProcessCreateLakeTable handles CREATE FOREIGN TABLE statements
* that creates pg_lake tables.
*/
static bool
ProcessCreateLakeTable(ProcessUtilityParams * params)
{
Assert(IsA(params->plannedStmt->utilityStmt, CreateForeignTableStmt));
CreateForeignTableStmt *createStmt =
(CreateForeignTableStmt *) params->plannedStmt->utilityStmt;
if (!IsPgLakeServerName(createStmt->servername))
{
/* not a lake table */
return false;
}
/* when creating a partition we always inherit columns from parent */
if (createStmt->base.partbound != NULL)
return false;
/* get a writable copy of the parse tree */
if (params->readOnlyTree)
createStmt = (CreateForeignTableStmt *) CopyUtilityStmt(params);
/*
* Resolve @STAGE/ prefix in the path option so the full URL is stored in
* the foreign table metadata rather than the @STAGE/ shorthand.
*/
DefElem *pathOption = GetOption(createStmt->options, "path");
if (pathOption != NULL)
{
char *path = defGetString(pathOption);
char *resolvedPath = ResolveStageURL(path);
if (resolvedPath != path)
pathOption->arg = (Node *) makeString(resolvedPath);
}
/*
* If the column list is empty, we automatically fill it in.
*/
if (createStmt->base.tableElts == NIL)
{
AddLakeTableColumnDefinitions(createStmt);
/*
* Rerun all DDL handlers. We will not re-enter this path since the
* tableElts is no longer NIL.
*/
PgLakeCommonProcessUtility(params);
return true;
}
/*
* If there is a filename option, check whether the _filename column is in
* the right place.
*/
bool hasFilename = GetBoolOption(createStmt->options, "filename", false);
if (hasFilename)
{
bool isWritable = GetBoolOption(createStmt->options, "writable", false);
if (isWritable)
/* filename option is never allowed for writable tables */
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("\"filename\" option is not allowed for writable pg_lake tables")));
ErrorIfInvalidFilenameColumn(createStmt->base.tableElts);
}
return false;
}
/*
* ProcessCreateIcebergTableFromForeignTableStmt handles CREATE FOREIGN TABLE
* statements that are pg_lake_iceberg tables.
*/
static bool
ProcessCreateIcebergTableFromForeignTableStmt(ProcessUtilityParams * params)
{
Assert(IsA(params->plannedStmt->utilityStmt, CreateForeignTableStmt));
CreateForeignTableStmt *createStmt =
(CreateForeignTableStmt *) params->plannedStmt->utilityStmt;
if (!IsPgLakeIcebergServerName(createStmt->servername))
{
/* not an iceberg table */
return false;
}
/* we might adjust the parse tree */
if (params->readOnlyTree)
createStmt = (CreateForeignTableStmt *) CopyUtilityStmt(params);
DefElem *catalogOption = GetOption(createStmt->options, "catalog");
if (catalogOption == NULL)
{
DefElem *defaultCatalog = makeDefElem("catalog", (Node *) makeString(IcebergDefaultCatalog), -1);
createStmt->options = lappend(createStmt->options, defaultCatalog);
}
bool hasRestCatalogOption = HasRestCatalogTableOption(createStmt->options);
bool hasObjectStoreCatalogOption = HasObjectStoreCatalogTableOption(createStmt->options);
if (hasObjectStoreCatalogOption || hasRestCatalogOption)
{
Oid namespaceId = RangeVarGetAndCheckCreationNamespace(createStmt->base.relation, NoLock, NULL);
/*
* Read-only external catalog tables are a special case of Iceberg
* tables. They are recognized as Iceberg tables, but are not
* registered in any internal catalogs (e.g., lake_iceberg.tables).
* Instead, the table is created only in PostgreSQL’s system
* catalogs. When the table is queried, its metadata is fetched on
* demand from the external catalog.
*/
bool hasExternalCatalogReadOnlyOption = HasReadOnlyOption(createStmt->options);
char *metadataLocation = NULL;
char *catalogNamespace = NULL;
char *catalogTableName = NULL;
char *catalogName = NULL;
char *catalogNamespaceProvided = GetStringOption(createStmt->options, "catalog_namespace", false);
/*
* Always provide catalog_namespace and catalog_table_name options for
* REST catalog iceberg tables. If not provided by user, we set them
* to default values. The default values are the table's schema name
* and table name.
*/
if (catalogNamespaceProvided == NULL && hasExternalCatalogReadOnlyOption)
{
catalogNamespace = get_namespace_name(namespaceId);
/* add catalog_namespace table options */
createStmt->options =
lappend(createStmt->options,
makeDefElem("catalog_namespace", (Node *) makeString(catalogNamespace), -1));
}
else
{
catalogNamespace = catalogNamespaceProvided;
}
char *catalogTableNameProvided = GetStringOption(createStmt->options, "catalog_table_name", false);
if (catalogTableNameProvided == NULL && hasExternalCatalogReadOnlyOption)
{
catalogTableName = pstrdup(createStmt->base.relation->relname);
createStmt->options =
lappend(createStmt->options,
makeDefElem("catalog_table_name", (Node *) makeString(catalogTableName), -1));
}
else
{
catalogTableName = catalogTableNameProvided;
}
char *catalogNameProvided = GetStringOption(createStmt->options, "catalog_name", false);
if (catalogNameProvided == NULL && hasExternalCatalogReadOnlyOption)
{
catalogName = get_database_name(MyDatabaseId);
createStmt->options =
lappend(createStmt->options,
makeDefElem("catalog_name", (Node *) makeString(catalogName), -1));
}
else
{
catalogName = catalogNameProvided;
}
if (hasRestCatalogOption && hasExternalCatalogReadOnlyOption)
{
ErrorIfRestNamespaceDoesNotExist(catalogName, catalogNamespace);
metadataLocation =
GetMetadataLocationFromRestCatalog(catalogName, catalogNamespace, catalogTableName);
}
else if (hasObjectStoreCatalogOption && hasExternalCatalogReadOnlyOption)
{
ErrorIfExternalObjectStoreCatalogDoesNotExist(catalogName);
metadataLocation =
GetTableMetadataLocationFromExternalObjectStoreCatalog(catalogName,
catalogNamespace,
catalogTableName);
}
if (!hasExternalCatalogReadOnlyOption)
{
/*
* For writable object store catalog tables, we need to continue
* with the regular iceberg table creation process. We only fill
* in the catalog options here. Other than that, we simply check
* if user provided any catalog options. That's not allowed,
* writable tables only inherit from the database name, schema
* name, and table name.
*/
if (catalogNamespaceProvided != NULL ||
catalogTableNameProvided != NULL ||
catalogNameProvided != NULL)
{
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("writable %s catalog iceberg tables do not "
"allow explicit catalog options", hasObjectStoreCatalogOption ? OBJECT_STORE_CATALOG_NAME : REST_CATALOG_NAME)));
}
}
else if (createStmt->base.tableElts == NIL && hasExternalCatalogReadOnlyOption)
{
List *dataFileColumns =
DescribeColumnsFromIcebergMetadataURI(metadataLocation, false);
createStmt->base.tableElts = dataFileColumns;
MaybeConvertUnsupportedNumericColumnsToDouble(createStmt->base.tableElts);
EnsureSupportedIcebergTableColumnDefinitions(createStmt->base.tableElts);
/*
* Rerun all DDL handlers. We will not re-enter this path since
* the tableElts is no longer NIL.
*/
PgLakeCommonProcessUtility(params);
return true;
}
else
{
MaybeConvertUnsupportedNumericColumnsToDouble(createStmt->base.tableElts);
EnsureSupportedIcebergTableColumnDefinitions(createStmt->base.tableElts);
PgLakeCommonParentProcessUtility(params);
return true;
}
}
MaybeConvertUnsupportedNumericColumnsToDouble(createStmt->base.tableElts);
EnsureSupportedIcebergTableColumnDefinitions(createStmt->base.tableElts);
Oid namespaceId =
RangeVarGetAndCheckCreationNamespace(createStmt->base.relation, NoLock, NULL);
createStmt->base.tableElts = ExpandTableElements(createStmt->base.tableElts);
if (createStmt->base.relation->schemaname == NULL)
{
/*
* Fix the schema name to be robust to search_path changes, since we
* rely on the schema name in PostProcessCreateIcebergTable.
*/
createStmt->base.relation->schemaname = get_namespace_name(namespaceId);
}
DefElem *locationOption = GetOption(createStmt->options, "location");
char *defaultLocationPrefix = GetIcebergDefaultLocationPrefix();
if (hasObjectStoreCatalogOption)
{
const char *objectStoreCatalogLocationPrefix = GetObjectStoreDefaultLocationPrefix();
if (objectStoreCatalogLocationPrefix == NULL)
{
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg(OBJECT_STORE_CATALOG_NAME " catalog iceberg tables require "
"pg_lake_iceberg.object_store_catalog_location_prefix "
"to be set")));
}
if (InternalObjectStorePrefix == NULL)
{
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg(OBJECT_STORE_CATALOG_NAME " catalog iceberg tables require "
"pg_lake_iceberg.internal_iceberg_storage_prefix "
"to be set")));
}
/* here we only deal with writable tables */
Assert(!HasReadOnlyOption(createStmt->options));
/*
* For hasObjectStoreCatalogOption, we also append
* InternalObjectStorePrefix/tables to the location
*/
defaultLocationPrefix = psprintf("%s/%s/%s",
defaultLocationPrefix,
InternalObjectStorePrefix,
"tables");
}
/*
* We will set the location by using the default location prefix when user
* does not specify the location but already set default locatipn prefix.
* We append the "database_name/schema_name/table_name/relation_id" to the
* default location prefix. Since the relation_id is available only after
* table is created at post hook, we set the location as a placeholder for
* now. We will replace the placeholder with the actual location at post
* hook.
*/
if (locationOption == NULL && defaultLocationPrefix != NULL)
{
DefElem *defaultPlaceholder = makeDefElem("location", (Node *) makeString(DEFAULT_ICEBERG_LOCATION_PLACEHOLDER), -1);
createStmt->options = lappend(createStmt->options, defaultPlaceholder);
}
/*
* Our CREATE FOREIGN TABLE statement is fully ready for execution, so we
* go to the parent ProcessUtility.
*/
PgLakeCommonParentProcessUtility(params);
/*
* Repeat the type checks for CREATE FOREIGN TABLE .. PARTITION OF .. now
* that the column list is populated.
*/
if (createStmt->base.partbound != NULL)
{
MaybeConvertUnsupportedNumericColumnsToDouble(createStmt->base.tableElts);
ErrorIfTableContainsUnsupportedTypes(createStmt->base.tableElts);
}
/* the table is now created, get its OID */
Oid relationId = RangeVarGetRelid(createStmt->base.relation, NoLock, false);
char *location;
if (locationOption != NULL)
{
/*
* We use GetWritableTableLocation rather than looking at the option
* directly because it cleans up the separator.
*/
char *queryArguments = "";
location = GetWritableTableLocation(relationId, &queryArguments);
}
else
{
/*
* replace default placeholder uri with the actual default uri for the
* table
*/
Assert(defaultLocationPrefix != NULL);
char *databaseName = get_database_name(MyDatabaseId);
char *tableName = createStmt->base.relation->relname;
char *schemaName = createStmt->base.relation->schemaname;
location = SetIcebergTableLocationOptionFromDefaultPrefix(relationId,
defaultLocationPrefix,
databaseName,
schemaName, tableName);
}
/* we do not allow non-empty locations */
ErrorIfLocationIsNotEmpty(location);
/* we currently only allow Iceberg tables in the managed storage region */
ErrorIfNotInManagedStorageRegion(location);
if (hasRestCatalogOption)
{
/* here we only deal with writable rest catalog iceberg tables */
Assert(!HasReadOnlyOption(createStmt->options));
/*
* For writable rest catalog iceberg tables, we register the namespace
* in the rest catalog. We do that later in the command processing so
* that any previous errors (e.g., table creation failures) prevents
* us from registering the namespace.
*
* Note that registering a namespace is not a transactional operation
* from pg_lake's perspective. If the subsequent table creation fails,
* the namespace registration will remain. We accept that tradeoff for
* simplicity as re-registering an existing namespace is a no-op. For
* a writable rest catalog iceberg table, the namespace is always the
* table's schema name. Similarly, the catalog name is always the
* database name. We normally encode that in GetRestCatalogName()
* etc., but here we need to do it early before the table is created.
*/
RegisterNamespaceToRestCatalog(get_database_name(MyDatabaseId),
get_namespace_name(namespaceId));
}
bool hasRowIds = GetBoolOption(createStmt->options, "row_ids", false);
/* when a table has row_ids, we need to create a sequence */
if (hasRowIds)
CreateRelationRowIdSequence(relationId);
List *columnDefList = createStmt->base.tableElts;
/*
* This function should run after StandardProcessUtility, such that the
* columnDefList is already the restricted list.
*/
Assert(list_length(GetRestrictedColumnDefList(columnDefList)) == list_length(columnDefList));
if (hasRestCatalogOption)
{
/* this code-path only deals with writable rest catalog tables */
Assert(!HasReadOnlyOption(createStmt->options));
/*
* We have to start staging create table for writable rest catalog
* tables here, because initial staging allows us to get the vended
* credentials for this transaction. For example, if the rest catalog
* table is created via CTAS, the CTAS command may need to read/write
* data to S3 using the vended credentials. Also note that staging
* consists of two steps: 1.
* StartStagingCreateRestCatalogIcebergTable: which creates the table
* in the rest catalog with a "staging" status. 2.
* FinalizeStagingCreateRestCatalogIcebergTable: which finalizes the
* table creation in the rest catalog after the local table creation
* is successful in post-commit.
*/
StartStageRestCatalogIcebergTableCreate(relationId);
/*
* Record the create table operation in the rest catalog. Note that
* this is not the final registration of the table in the tx, we'll
* update this record in
* FinalizeStagingCreateRestCatalogIcebergTableCreate. We prefer to
* record it here such if table is dropped before commit, we can track
* the creation of the table properly.
*/
RecordRestCatalogRequestInTx(relationId, REST_CATALOG_CREATE_TABLE, "");
}
List *ddlOps = NIL;
IcebergDDLOperation *createDDLOp = palloc0(sizeof(IcebergDDLOperation));
createDDLOp->type = DDL_TABLE_CREATE;