-
Notifications
You must be signed in to change notification settings - Fork 99
Expand file tree
/
Copy pathwrite_data.c
More file actions
801 lines (655 loc) · 22.3 KB
/
write_data.c
File metadata and controls
801 lines (655 loc) · 22.3 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
/*
* 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.
*/
/*
* Functions for generating query for writing data via pgduck server.
*/
#include "postgres.h"
#include "access/tupdesc.h"
#include "commands/defrem.h"
#include "common/string.h"
#include "pg_lake/csv/csv_options.h"
#include "pg_lake/copy/copy_format.h"
#include "pg_lake/data_file/data_file_stats.h"
#include "pg_lake/extensions/postgis.h"
#include "pg_lake/parquet/field.h"
#include "pg_lake/parquet/geoparquet.h"
#include "pg_lake/pgduck/numeric.h"
#include "pg_lake/pgduck/read_data.h"
#include "pg_lake/pgduck/type.h"
#include "pg_lake/pgduck/iceberg_query_validation.h"
#include "pg_lake/pgduck/write_data.h"
#include "pg_lake/util/numeric.h"
#include "nodes/pg_list.h"
#include "utils/builtins.h"
#include "pg_lake/pgduck/parse_struct.h"
#include "utils/lsyscache.h"
static DuckDBTypeInfo ChooseDuckDBEngineTypeForWrite(PGType postgresType,
CopyDataFormat destinationFormat);
static void AppendFieldIdValue(StringInfo map, Field * field, int fieldId);
static const char *ParquetVersionToString(ParquetVersion version);
static DuckDBTypeInfo VARCHAR_TYPE =
{
DUCKDB_TYPE_VARCHAR, false, "VARCHAR",
};
int TargetRowGroupSizeMB = DEFAULT_TARGET_ROW_GROUP_SIZE_MB;
int DefaultParquetVersion = PARQUET_VERSION_V1;
/*
* ConvertCSVFileTo copies and converts a CSV file at source path to
* the destinationPath.
*
* The CSV was generated using COPY ... TO '<csvFilePath>'
*/
StatsCollector *
ConvertCSVFileTo(char *csvFilePath, TupleDesc csvTupleDesc, int maxLineSize,
char *destinationPath,
CopyDataFormat destinationFormat,
CopyDataCompression destinationCompression,
List *formatOptions,
DataFileSchema * schema,
List *leafFields)
{
StringInfoData command;
initStringInfo(&command);
/* project columns into target format */
appendStringInfo(&command, "SELECT %s FROM ",
TupleDescToProjectionListForWrite(csvTupleDesc, destinationFormat));
/* build the read_csv(...) clause */
char *columnsMap = NULL;
if (csvTupleDesc != NULL && csvTupleDesc->natts > 0)
columnsMap = TupleDescToColumnMapForWrite(csvTupleDesc, destinationFormat);
bool includeHeader = true;
AppendReadCSVClause(&command, csvFilePath, maxLineSize, columnsMap,
InternalCSVOptions(includeHeader));
bool queryHasRowIds = false;
/*
* CSV data is already clamped by WriteInsertRecord and converted to
* struct for Iceberg
*/
return WriteQueryResultTo(command.data,
destinationPath,
destinationFormat,
destinationCompression,
formatOptions,
queryHasRowIds,
schema,
csvTupleDesc,
leafFields,
ICEBERG_OOR_NONE,
false /* wrapNativeIntervals */ ,
NIL /* partitionByExprs */ );
}
/*
* WriteQueryResultTo takes the result of a query and writes to
* destinationPath. There may be multiple files if file_size_bytes
* is specified in formatOptions.
*/
StatsCollector *
WriteQueryResultTo(char *query,
char *destinationPath,
CopyDataFormat destinationFormat,
CopyDataCompression destinationCompression,
List *formatOptions,
bool queryHasRowId,
DataFileSchema * schema,
TupleDesc queryTupleDesc,
List *leafFields,
IcebergOutOfRangePolicy outOfRangePolicy,
bool wrapNativeIntervals,
List *partitionByExprs)
{
if (outOfRangePolicy != ICEBERG_OOR_NONE)
{
query = IcebergWrapQueryWithErrorOrClampChecks(query, queryTupleDesc,
outOfRangePolicy,
queryHasRowId);
}
if (wrapNativeIntervals && destinationFormat == DATA_FORMAT_ICEBERG)
{
query = IcebergWrapQueryWithIntervalConversion(query, queryTupleDesc,
queryHasRowId);
}
/*
* If partition expressions are given, wrap the (already validated) query
* with synthetic partition columns. This must happen AFTER the validation
* and interval wrappers, because those reconstruct the SELECT list from
* queryTupleDesc and would drop any extra columns added earlier.
*/
if (partitionByExprs != NIL)
{
StringInfoData wrapped;
initStringInfo(&wrapped);
appendStringInfoString(&wrapped, "SELECT *");
int partIndex = 0;
ListCell *exprCell = NULL;
foreach(exprCell, partitionByExprs)
{
char *expr = strVal(lfirst(exprCell));
appendStringInfo(&wrapped, ", %s AS " PARTITION_COLUMN_PREFIX "%d", expr, partIndex);
partIndex++;
}
appendStringInfo(&wrapped, " FROM (%s) __partitioned_source", query);
query = wrapped.data;
}
StringInfoData command;
initStringInfo(&command);
appendStringInfo(&command, "COPY (%s) TO %s",
query,
quote_literal_cstr(destinationPath));
/* start WITH options */
appendStringInfoString(&command, " WITH (");
/*
* Iceberg data files are Parquet, so use "parquet" as the DuckDB format
* name for both DATA_FORMAT_PARQUET and DATA_FORMAT_ICEBERG.
*/
const char *formatName = (destinationFormat == DATA_FORMAT_ICEBERG) ?
"parquet" : CopyDataFormatToName(destinationFormat);
appendStringInfo(&command, "format %s",
quote_literal_cstr(formatName));
switch (destinationFormat)
{
case DATA_FORMAT_ICEBERG:
case DATA_FORMAT_PARQUET:
{
if (destinationCompression == DATA_COMPRESSION_NONE)
{
/* Parquet format uses uncompressed instead of none */
appendStringInfo(&command, ", compression 'uncompressed'");
break;
}
else
{
const char *compressionName =
CopyDataCompressionToName(destinationCompression);
appendStringInfo(&command, ", compression %s",
quote_literal_cstr(compressionName));
}
ListCell *optionCell = NULL;
foreach(optionCell, formatOptions)
{
DefElem *option = lfirst(optionCell);
if (strcmp(option->defname, "file_size_bytes") == 0)
{
char *fileSizeStr = defGetString(option);
appendStringInfo(&command, ", file_size_bytes %s",
quote_literal_cstr(fileSizeStr));
}
}
if (schema != NULL)
{
appendStringInfoString(&command, ", field_ids {");
AppendFields(&command, schema);
if (queryHasRowId)
appendStringInfo(&command, ", '_row_id' : %d", ICEBERG_ROWID_FIELD_ID);
appendStringInfoString(&command, "}");
}
if (queryTupleDesc != NULL)
{
char *geoParquetMeta =
GetGeoParquetMetadataForTupleDesc(queryTupleDesc);
if (geoParquetMeta != NULL)
{
appendStringInfo(&command, ", kv_metadata { geo: %s }",
quote_literal_cstr(geoParquetMeta));
}
}
if (TargetRowGroupSizeMB > 0)
{
/*
* When writing Parquet files, a single row group per
* thread must fit in memory uncompressed. Hence, set
* row_group_size_bytes to 128MB.
* https://github.com/duckdb/duckdb/issues/16078#issuecomment-2644985411
*
* duckdb also uses row_group_size which is set to 122880
* rows by default. If row_group_size hits the limit
* before row_group_size_bytes, it will be used instead.
*
* row_group_size_bytes also requires
* preserve_insertion_order=false.
*/
appendStringInfo(&command, ", row_group_size_bytes '%dMB'", TargetRowGroupSizeMB);
}
appendStringInfo(&command, ", parquet_version '%s'",
ParquetVersionToString(DefaultParquetVersion));
appendStringInfo(&command, ", return_stats");
break;
}
case DATA_FORMAT_JSON:
{
if (destinationCompression == DATA_COMPRESSION_SNAPPY)
{
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("pg_lake_copy: snappy compression is not "
"supported for JSON format")));
}
const char *compressionName =
CopyDataCompressionToName(destinationCompression);
appendStringInfo(&command, ", compression %s",
quote_literal_cstr(compressionName));
break;
}
case DATA_FORMAT_CSV:
{
if (destinationCompression == DATA_COMPRESSION_SNAPPY)
{
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("pg_lake_copy: snappy compression is not "
"supported for CSV format")));
}
const char *compressionName =
CopyDataCompressionToName(destinationCompression);
appendStringInfo(&command, ", compression %s",
quote_literal_cstr(compressionName));
/*
* We normalize the list of options to include default values
* for all options, unless auto_detect is on, in which case we
* only include the explicitly defined ones.
*/
List *csvOptions = NormalizedExternalCSVOptions(formatOptions);
ListCell *optionCell = NULL;
foreach(optionCell, csvOptions)
{
DefElem *option = lfirst(optionCell);
if (strcmp(option->defname, "header") == 0)
{
CopyHeaderChoice choice =
GetCopyHeaderChoice(option, true);
appendStringInfo(&command, ", header %s",
choice == COPY_HEADER_FALSE ? "false" : "true");
}
else if (strcmp(option->defname, "delimiter") == 0)
{
char *delimiter = defGetString(option);
appendStringInfo(&command, ", delim %s",
quote_literal_cstr(delimiter));
}
else if (strcmp(option->defname, "quote") == 0)
{
char *quote = defGetString(option);
appendStringInfo(&command, ", quote %s",
quote_literal_cstr(quote));
}
else if (strcmp(option->defname, "escape") == 0)
{
char *escape = defGetString(option);
appendStringInfo(&command, ", escape %s",
quote_literal_cstr(escape));
}
else if (strcmp(option->defname, "null") == 0)
{
char *null = defGetString(option);
appendStringInfo(&command, ", nullstr %s",
quote_literal_cstr(null));
}
else if (strcmp(option->defname, "force_quote") == 0)
{
if (option->arg && IsA(option->arg, A_Star))
{
appendStringInfoString(&command, ", force_quote *");
}
else if (option->arg && IsA(option->arg, List))
{
appendStringInfoString(&command, ", force_quote (");
List *columnNameList = castNode(List, option->arg);;
ListCell *columnNameCell = NULL;
int columnIndex = 0;
foreach(columnNameCell, columnNameList)
{
char *columnName = strVal(lfirst(columnNameCell));
/* add comma after first column */
appendStringInfo(&command, "%s%s",
columnIndex > 0 ? ", " : "",
quote_identifier(columnName));
columnIndex++;
}
appendStringInfoString(&command, ")");
}
}
}
break;
}
default:
elog(ERROR, "unexpected format: %s", formatName);
}
/* add PARTITION_BY if partitioning expressions were specified */
if (partitionByExprs != NIL)
{
appendStringInfoString(&command, ", PARTITION_BY (");
int numExprs = list_length(partitionByExprs);
for (int i = 0; i < numExprs; i++)
{
if (i > 0)
appendStringInfoString(&command, ", ");
appendStringInfo(&command, PARTITION_COLUMN_PREFIX "%d", i);
}
appendStringInfoString(&command, ")");
/*
* Disable Hive-style directory naming (col=val/) since we extract
* partition values from the partition_keys MAP, not from file paths.
* This avoids issues with long text values causing HTTP 400 errors
* and percent-encoding in directory names.
*/
appendStringInfoString(&command, ", WRITE_PARTITION_COLUMNS false"
", HIVE_FILE_PATTERN false");
}
/* end WITH options */
appendStringInfoString(&command, ")");
return ExecuteCopyToCommandOnPGDuckConnection(command.data,
leafFields,
schema,
destinationPath,
destinationFormat);
}
/*
* TupleDescToProjectionList converts a PostgreSQL tuple descriptor to
* projection list in string form that can be used for writes.
*/
char *
TupleDescToProjectionListForWrite(TupleDesc tupleDesc, CopyDataFormat destinationFormat)
{
Assert(tupleDesc != NULL);
StringInfoData projection;
initStringInfo(&projection);
bool hasColumns = false;
for (int attnum = 1; attnum <= tupleDesc->natts; attnum++)
{
Form_pg_attribute column = TupleDescAttr(tupleDesc, attnum - 1);
if (column->attisdropped)
continue;
char *columnName = NameStr(column->attname);
Oid columnTypeId = column->atttypid;
if (hasColumns)
appendStringInfoString(&projection, ", ");
/*
* TimeTZ is stored as TIME (UTC-normalized) in Iceberg. We convert to
* UTC in PGDuckSerialize, so DuckDB should parse as TIME.
*/
if (columnTypeId == TIMETZOID && destinationFormat == DATA_FORMAT_ICEBERG)
appendStringInfo(&projection, "CAST(%s AS TIME) AS ",
quote_identifier(columnName));
/*
* In case of geometry, we write WKT in csv_writer.c and parse it as
* GEOMETRY via read_csv. Just before writing to the destination, we
* convert to a form that makes sense for the destination format,
* namely WKB blob in Parquet and GeoJSON in JSON.
*
* In case of CSV we preserve the WKT as written by csv_writer.c
*/
if (IsGeometryTypeId(columnTypeId))
{
if (destinationFormat == DATA_FORMAT_PARQUET ||
destinationFormat == DATA_FORMAT_ICEBERG)
appendStringInfo(&projection, "ST_AsWKB(%s) AS ",
quote_identifier(columnName));
else if (destinationFormat == DATA_FORMAT_JSON)
appendStringInfo(&projection, "ST_AsGeoJSON(%s) AS ",
quote_identifier(columnName));
}
appendStringInfo(&projection, "%s",
quote_identifier(columnName));
hasColumns = true;
}
if (!hasColumns)
/* no columns, fall back to SELECT * */
return "*";
return projection.data;
}
/*
* TupleDescToColumnMapForWrite converts a PostgreSQL tuple descriptor to
* a DuckDB columns map in string form.
*/
char *
TupleDescToColumnMapForWrite(TupleDesc tupleDesc, CopyDataFormat destinationFormat)
{
StringInfoData map;
initStringInfo(&map);
bool hasColumns = false;
appendStringInfoString(&map, "{");
for (int attnum = 1; attnum <= tupleDesc->natts; attnum++)
{
Form_pg_attribute column = TupleDescAttr(tupleDesc, attnum - 1);
if (column->attisdropped)
continue;
char *columnName = NameStr(column->attname);
Oid columnTypeId = column->atttypid;
int columnTypeMod = column->atttypmod;
DuckDBTypeInfo duckdbType = ChooseDuckDBEngineTypeForWrite(
MakePGType(columnTypeId, columnTypeMod),
destinationFormat);
appendStringInfo(&map, "%s%s:%s",
hasColumns ? "," : "",
quote_literal_cstr(columnName),
quote_literal_cstr(duckdbType.typeName));
hasColumns = true;
}
appendStringInfoString(&map, "}");
return map.data;
}
/*
* AppendFields appends comma-separated mappings from
* a field name to a field ID to a DuckDB map in string form.
*/
void
AppendFields(StringInfo map, DataFileSchema * schema)
{
bool addComma = false;
for (size_t fieldIdx = 0; fieldIdx < schema->nfields; fieldIdx++)
{
DataFileSchemaField *field = &schema->fields[fieldIdx];
const char *fieldName = field->name;
appendStringInfo(map, "%s%s: ",
addComma ? ", " : "",
quote_literal_cstr(fieldName));
AppendFieldIdValue(map, field->type, field->id);
addComma = true;
}
}
/*
* AppendFieldIdValue appends a field ID to a DuckDB map in string form.
* The field ID is either a number or another map containing the field
* ID for the current field and the subfields.
*
* https://duckdb.org/docs/sql/statements/copy
*/
static void
AppendFieldIdValue(StringInfo fieldIdsStr, Field * field, int fieldId)
{
#define CURRENT_FIELD_ID "__duckdb_field_id"
switch (field->type)
{
case FIELD_TYPE_SCALAR:
appendStringInfo(fieldIdsStr, "%d", fieldId);
break;
case FIELD_TYPE_LIST:
appendStringInfo(fieldIdsStr, "{" CURRENT_FIELD_ID ": %d", fieldId);
FieldList *listField = &field->field.list;
appendStringInfoString(fieldIdsStr, ", element: ");
AppendFieldIdValue(fieldIdsStr, listField->element, listField->elementId);
appendStringInfoString(fieldIdsStr, "}");
break;
case FIELD_TYPE_MAP:
appendStringInfo(fieldIdsStr, "{" CURRENT_FIELD_ID ": %d", fieldId);
FieldMap *mapField = &field->field.map;
appendStringInfoString(fieldIdsStr, ", key: ");
AppendFieldIdValue(fieldIdsStr, mapField->key, mapField->keyId);
appendStringInfoString(fieldIdsStr, ", value: ");
AppendFieldIdValue(fieldIdsStr, mapField->value, mapField->valueId);
appendStringInfoString(fieldIdsStr, "}");
break;
case FIELD_TYPE_STRUCT:
appendStringInfo(fieldIdsStr, "{" CURRENT_FIELD_ID ": %d", fieldId);
DataFileSchema *structField = &field->field.structType;
appendStringInfoString(fieldIdsStr, ", ");
AppendFields(fieldIdsStr, structField);
appendStringInfoString(fieldIdsStr, "}");
break;
}
}
/*
* ParquetVersionToString converts a ParquetVersion to a string.
*/
static const char *
ParquetVersionToString(ParquetVersion version)
{
switch (version)
{
case PARQUET_VERSION_V1:
return "V1";
case PARQUET_VERSION_V2:
return "V2";
default:
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("unexpected parquet version: %d", version)));
}
return NULL;
}
/*
* ChooseDuckDBEngineTypeForWrite obtains a DuckDB type name for a given postgres
* type, and codifies some of our limitations around arrays and decimals.
*
* NOTE: This function should stay in sync with ShouldUseDuckSerialization where
* we decide how to write the values to the intermediate CSV. Here we decide how
* DuckDB should parse those values. In particular, the format emitted by csv_writer.c
* should be parseable by read_csv() when using the type decided by this function.
*/
static DuckDBTypeInfo
ChooseDuckDBEngineTypeForWrite(PGType postgresType,
CopyDataFormat destinationFormat)
{
/*
* We prefer to treat all fields as text when writing CSV to preserve
* PostgreSQL serialization format.
*/
if (destinationFormat == DATA_FORMAT_CSV)
return VARCHAR_TYPE;
int32 postgresTypeMod = postgresType.postgresTypeMod;
Oid elementTypeId = get_element_type(postgresType.postgresTypeOid);
bool isArrayType = OidIsValid(elementTypeId);
char *typeModifier = "";
/*
* We can handle an array by treating the element type like the type that
* was passed in from here on out an add [] to the type name in the end.
*/
if (isArrayType)
postgresType.postgresTypeOid = elementTypeId;
DuckDBType duckTypeId = GetDuckDBTypeForPGType(postgresType);
if (duckTypeId == DUCKDB_TYPE_INVALID)
{
/*
* Treat any type that does not have a DuckDB equivalent as text.
*/
duckTypeId = DUCKDB_TYPE_VARCHAR;
}
else if (duckTypeId == DUCKDB_TYPE_DECIMAL)
{
/*
* PostgreSQL supports up to 1000 digits in numeric fields, while
* DuckDB supports up to 38.
*
* To make sure we do not break the limit, emit large numeric as text.
* Other systems might not understand that as numeric, but PostgreSQL
* can still parse it.
*
* https://duckdb.org/docs/sql/data_types/overview
* https://www.postgresql.org/docs/current/datatype-numeric.html#DATATYPE-NUMERIC-DECIMAL
*/
int precision = -1;
int scale = -1;
GetDuckdbAdjustedPrecisionAndScaleFromNumericTypeMod(postgresTypeMod, &precision, &scale);
if (CanPushdownNumericToDuckdb(precision, scale))
{
/*
* happy case: we can map to DECIMAL(precision, scale)
*/
typeModifier = psprintf("(%d,%d)", precision, scale);
duckTypeId = DUCKDB_TYPE_DECIMAL;
}
else
{
/* explicit precision which is too big for us */
duckTypeId = DUCKDB_TYPE_VARCHAR;
}
}
else if (duckTypeId == DUCKDB_TYPE_TIME_TZ && destinationFormat == DATA_FORMAT_ICEBERG)
{
/*
* Iceberg only has a "time" type (no timezone). We convert timetz
* values to UTC in PGDuckSerialize, so DuckDB should parse as TIME.
*/
duckTypeId = DUCKDB_TYPE_TIME;
}
else if (duckTypeId == DUCKDB_TYPE_BLOB && destinationFormat == DATA_FORMAT_JSON)
{
/*
* We map bytea to text in JSON, because DuckDB's bytea text format is
* subtly different from PostgreSQL. It needs a separate \x for every
* 2 hex characters, otherwise it interprets the characters as ASCII
* bytes, so something like \xabab would be interpreted differently
* between PG and DuckDB
*
* This corresponds to ShouldUseDuckSerialization in csv_writer.c
*/
duckTypeId = DUCKDB_TYPE_VARCHAR;
isArrayType = false;
}
else if (duckTypeId == DUCKDB_TYPE_INTERVAL && destinationFormat == DATA_FORMAT_ICEBERG)
{
/*
* Iceberg does not have a native interval type. We store intervals as
* struct(months BIGINT, days BIGINT, microseconds BIGINT) in both the
* Iceberg metadata and Parquet data files. For plain Parquet files,
* DuckDB uses its native INTERVAL type.
*/
char *intervalTypeName =
psprintf("STRUCT(months BIGINT, days BIGINT, microseconds BIGINT)%s",
isArrayType ? "[]" : "");
DuckDBTypeInfo typeInfo = {
.typeId = DUCKDB_TYPE_STRUCT,
.typeName = intervalTypeName,
.isArrayType = isArrayType,
};
return typeInfo;
}
/*
* In case of both JSON and Parquet, composites/arrays/maps are serialized
* in a DuckDB- compatible format by csv_writer.c and parsed into the
* native DuckDB struct/list/map types by read_csv(). When writing to JSON
* they become JSON objects/array, and when writing to Parquet they are
* converted to native Parquet structures. That behaviour seems desirable
* for us as well, so we do not do any special processing other than
* emitting the appropriate type name/definition.
*/
char *typeName;
if (duckTypeId == DUCKDB_TYPE_STRUCT || duckTypeId == DUCKDB_TYPE_MAP)
{
/* generate field names for struct/map */
const char *structDef =
GetFullDuckDBTypeNameForPGType(postgresType, destinationFormat);
typeName = psprintf("%s%s", structDef, isArrayType ? "[]" : "");
}
else
typeName = psprintf("%s%s%s",
GetDuckDBTypeName(duckTypeId),
typeModifier,
isArrayType ? "[]" : "");
DuckDBTypeInfo typeInfo = {
.typeId = duckTypeId,
.typeName = typeName,
.isArrayType = isArrayType
};
return typeInfo;
}