-
Notifications
You must be signed in to change notification settings - Fork 99
Expand file tree
/
Copy pathmetadata_operations.c
More file actions
1317 lines (1096 loc) · 39.5 KB
/
metadata_operations.c
File metadata and controls
1317 lines (1096 loc) · 39.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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 "fmgr.h"
#include "access/xact.h"
#include "common/hashfn.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "pg_lake/cleanup/deletion_queue.h"
#include "pg_lake/cleanup/in_progress_files.h"
#include "pg_lake/data_file/data_files.h"
#include "pg_lake/extensions/pg_lake_iceberg.h"
#include "pg_lake/iceberg/api.h"
#include "pg_lake/iceberg/api/table_metadata.h"
#include "pg_lake/iceberg/api/partitioning.h"
#include "pg_lake/iceberg/catalog.h"
#include "pg_lake/iceberg/data_file_stats.h"
#include "pg_lake/iceberg/metadata_operations.h"
#include "pg_lake/iceberg/operations/find_referenced_files.h"
#include "pg_lake/iceberg/operations/manifest_merge.h"
#include "pg_lake/iceberg/partitioning/partition.h"
#include "pg_lake/iceberg/partitioning/spec_generation.h"
#include "pg_lake/iceberg/utils.h"
#include "pg_lake/object_store_catalog/object_store_catalog.h"
#include "pg_lake/rest_catalog/rest_catalog.h"
#include "pg_lake/parquet/field.h"
#include "pg_lake/permissions/roles.h"
#include "pg_lake/pgduck/remote_storage.h"
#include "pg_lake/storage/local_storage.h"
#include "pg_lake/util/string_utils.h"
#include "pg_lake/util/s3_writer_utils.h"
#include "access/htup_details.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_enum.h"
#include "catalog/pg_type.h"
#include "utils/memutils.h"
#include "utils/lsyscache.h"
#include "utils/syscache.h"
#include "utils/inval.h"
/*
* IcebergSnapshotBuilder is used to create a new snapshot from a base
* snapshot via a series of metadata operations.
*/
typedef struct IcebergSnapshotBuilder
{
/* snapshot which we're modifying */
IcebergSnapshot *baseSnapshot;
/* new snapshot that we're building (generated upfront to obtain new IDs) */
IcebergSnapshot *newSnapshot;
/* data files added to the snapshot */
HTAB *dataEntries;
/* positional delete files */
HTAB *positionalDeleteEntries;
/* data or delete files to be removed */
List *removedEntries;
/* remove all data files (truncate) */
bool removeAllEntries;
/* whether to apply manifest compaction */
bool applyManifestCompaction;
/* a DDL has changed the iceberg schema or set to an existing schema */
bool regenerateSchema;
/* a DDL has changed partition specs */
bool regeneratePartitionSpec;
List *partitionSpecs;
int32_t defaultSpecId;
/* table is a new one */
bool createTable;
/* whether to expire old snapshots */
bool expireOldSnapshots;
/* new schema */
DataFileSchema *schema;
/* a DDL has set to an existing schema */
int32_t schemaId;
/* snapshot operation */
SnapshotOperation operation;
} IcebergSnapshotBuilder;
/*
* PartitionSpecManifestsEntries is hash entry to group manifest entries
* by partition spec id.
*/
typedef struct PartitionSpecManifestsEntries
{
int32_t partitionSpecId;
List *manifestEntries;
} PartitionSpecManifestsEntries;
static IcebergSnapshotBuilder * CreateIcebergSnapshotBuilder(IcebergTableMetadata * metadata, List *metadataOperations);
static void SetSnapshotOperation(IcebergSnapshot * snapshot, SnapshotOperation operation);
static SnapshotOperation SnapshotOperationSummary(List *metadataOperations);
static void ProcessIcebergMetadataOperations(Oid relationId, List *metadataOperations,
IcebergSnapshotBuilder * builder);
static IcebergManifestEntry * CreateIcebergManifestEntryFromMetadataOperation(TableMetadataOperation * operation,
int64_t newSnapshotId,
int64_t sequenceNumber);
static IcebergSnapshot * FinalizeNewSnapshot(IcebergSnapshotBuilder * builder,
Oid relationId,
const char *metadataLocation,
int32_t currentSchemaId,
List *allTransforms,
bool isVerbose);
static List *CreateNewManifestsForDeletedEntries(List *allManifestEntries, List *deletedManifestEntries,
IcebergSnapshot * newSnapshot, const char *metadataLocation,
const char *snapshotUUID, int *manifestIndex,
int partitionSpecId, List *partitionTransforms,
IcebergManifestContentType contentType);
static IcebergSnapshot * CopyIcebergSnapshot(IcebergSnapshot * src);
static Property * CopyPropertiesArray(Property * src, int length);
static HTAB *MakePartitionManifestEntryHash(void);
static void AddManifestEntryToHash(HTAB *hash, int32 partitionSpecId,
IcebergManifestEntry * entry);
static bool HasCreateTableOperation(List *metadataOperations);
static void DeleteInProgressManifests(Oid relationId, List *manifests);
/*
* ApplyIcebergMetadataChanges applies the given metadata operations to the
* iceberg metadata for the given relation.
*/
List *
ApplyIcebergMetadataChanges(Oid relationId, List *metadataOperations, List *allTransforms,
int maxSnapshotAgeInSecs, bool isVerbose,
char **deletionQueueMetadataPath)
{
List *restCatalogRequests = NIL;
if (deletionQueueMetadataPath)
*deletionQueueMetadataPath = NULL;
Assert(metadataOperations != NIL);
#ifdef USE_ASSERT_CHECKING
/* we already made sure we should apply the changes at tracking them */
List *metadataOperationTypes = GetMetadataOperationTypes(metadataOperations);
Assert(!ShouldSkipMetadataChangeToIceberg(metadataOperationTypes));
#endif
IcebergCatalogType catalogType = GetIcebergCatalogType(relationId);
bool writableRestCatalogTable = catalogType == REST_CATALOG_READ_WRITE;
int64_t prevLastUpdatedMs = 0;
/* read the iceberg metadata for the table */
bool forUpdate = true;
char *metadataPath = NULL;
bool createNewTable = HasCreateTableOperation(metadataOperations);
IcebergTableMetadata *metadata = NULL;
if (createNewTable)
{
/*
* For new tables, except for the writable rest catalog tables, we had
* already generated the initial metadata and have the metadata path
* inserted to the catalog. For writable rest catalog tables, the
* metadata path is managed by the rest catalog itself and has not
* been set yet. We still set metadata for writable rest catalog
* tables, to keep the code simple, even though it won't be used for
* actual metadata purposes, but only simple bookkeeping such as
* last_sequence_number.
*/
metadataPath =
!writableRestCatalogTable ? GetIcebergMetadataLocation(relationId, forUpdate) : NULL;
metadata = GenerateInitialIcebergTableMetadata(relationId);
/* Polaris expects the sequence number start from 1 */
metadata->last_sequence_number = !writableRestCatalogTable ? 0 : 1;
metadata->last_updated_ms = PostgresTimestampToIcebergTimestampMs();
}
else
{
metadataPath = GetIcebergMetadataLocation(relationId, forUpdate);
/*
* metadata for writable rest catalog is intended to be read-only in
* the remaining of the function, given the authoritative source is
* the rest catalog.
*/
metadata = ReadIcebergTableMetadata(metadataPath);
/*
* for writable rest catalog tables, the metadata state is on the REST
* catalog itself, we should not modify the in-memory metadata here.
*/
if (!writableRestCatalogTable)
{
prevLastUpdatedMs = metadata->last_updated_ms;
metadata->last_sequence_number = metadata->last_sequence_number + 1;
metadata->last_updated_ms = PostgresTimestampToIcebergTimestampMs();
}
}
IcebergSnapshotBuilder *builder = CreateIcebergSnapshotBuilder(metadata, metadataOperations);
ProcessIcebergMetadataOperations(relationId, metadataOperations, builder);
if (builder->createTable || builder->regenerateSchema)
{
if (!writableRestCatalogTable)
{
if (builder->schema != NULL)
{
AppendCurrentPostgresSchema(relationId, metadata, builder->schema);
}
else if (builder->schemaId >= 0)
{
metadata->current_schema_id = builder->schemaId;
}
else
pg_unreachable();
}
else if (builder->regenerateSchema)
{
if (builder->schema != NULL)
{
RestCatalogRequest *request = GetAddSchemaCatalogRequest(relationId, builder->schema);
restCatalogRequests = lappend(restCatalogRequests, request);
}
else if (builder->schemaId >= 0)
{
RestCatalogRequest *request = GetSetCurrentSchemaCatalogRequest(relationId, builder->schemaId);
restCatalogRequests = lappend(restCatalogRequests, request);
}
else
pg_unreachable();
}
}
if (builder->createTable || builder->regeneratePartitionSpec)
{
metadata->default_spec_id = builder->defaultSpecId;
ListCell *newSpecCell = NULL;
foreach(newSpecCell, builder->partitionSpecs)
{
IcebergPartitionSpec *newSpec = lfirst(newSpecCell);
if (!writableRestCatalogTable)
AppendPartitionSpec(metadata, newSpec);
else if (builder->regeneratePartitionSpec)
{
RestCatalogRequest *request =
GetAddPartitionCatalogRequest(relationId, list_make1(newSpec));
restCatalogRequests = lappend(restCatalogRequests, request);
}
}
if (writableRestCatalogTable && builder->regeneratePartitionSpec)
{
RestCatalogRequest *request =
GetSetPartitionDefaultIdCatalogRequest(relationId, builder->defaultSpecId);
restCatalogRequests = lappend(restCatalogRequests, request);
}
}
/* whether to create a new version of the Iceberg table */
bool createNewSnapshot = false;
IcebergSnapshot *newSnapshot = FinalizeNewSnapshot(builder,
relationId,
metadata->location,
metadata->current_schema_id,
allTransforms,
isVerbose);
if (newSnapshot != NULL)
{
createNewSnapshot = true;
/* update metadata's snapshot */
if (!writableRestCatalogTable)
UpdateLatestSnapshot(metadata, newSnapshot);
else
{
newSnapshot->sequence_number = metadata->last_sequence_number + 1;
RestCatalogRequest *request =
GetAddSnapshotCatalogRequest(newSnapshot, relationId);
restCatalogRequests = lappend(restCatalogRequests, request);
}
}
/* if we need to expire old snapshots, we do it here */
if (builder->expireOldSnapshots)
{
List *expiredSnapshotIds =
RemoveOldSnapshotsFromMetadata(relationId, metadata, maxSnapshotAgeInSecs, isVerbose);
if (expiredSnapshotIds != NIL)
{
createNewSnapshot = true;
if (writableRestCatalogTable)
{
RestCatalogRequest *request =
GetRemoveSnapshotCatalogRequest(expiredSnapshotIds, relationId);
restCatalogRequests = lappend(restCatalogRequests, request);
}
}
}
/* if there were no changes to the Iceberg table, we are done */
if (!createNewSnapshot && !createNewTable)
{
Assert(restCatalogRequests == NIL);
return restCatalogRequests;
}
if (writableRestCatalogTable)
{
if (metadataPath)
{
InsertDeletionQueueRecord(metadataPath, relationId, GetCurrentTransactionStartTimestamp());
/*
* Report the path we inserted so the caller can undo it if
* the REST catalog commit fails later.
*/
if (deletionQueueMetadataPath)
*deletionQueueMetadataPath = metadataPath;
}
/*
* We are done, writable rest catalog iceberg tables have their
* metadata updated in the catalog itself.
*/
return restCatalogRequests;
}
/* add the new snapshot to the snapshot log */
GenerateSnapshotLogEntries(metadata);
/*
* append the current metadata log before uploading new one. There is no
* metadata log for new tables.
*/
if (!createNewTable)
{
Assert(prevLastUpdatedMs != 0);
AdjustAndRetainMetadataLogs(metadata, metadataPath, metadata->snapshots_length, prevLastUpdatedMs);
}
int version = metadata->last_sequence_number;
/*
* For newly created iceberg tables, we have generated the metadata path
* and already inserted into iceberg tables. Here, we skip re-generating
* another path, simply use the path from the catalog.
*/
char *newMetadataPath = (createNewTable) ? metadataPath : GenerateRemoteMetadataFilePath(version, metadata->location, "");
char *previousMetadataPath =
GetIcebergCatalogPreviousMetadataLocation(relationId, forUpdate);
/* finally, update the table metadata and catalog */
UploadTableMetadataToURI(metadata, newMetadataPath);
UpdateInternalCatalogMetadataLocation(relationId, newMetadataPath, (createNewTable) ? NULL : metadataPath);
if (previousMetadataPath)
{
TimestampTz orphanedAt = GetCurrentTransactionStartTimestamp();
/*
* There is (currently) no value in retaining the old metadata.json
* files.
*/
InsertDeletionQueueRecord(previousMetadataPath, relationId, orphanedAt);
}
TriggerCatalogExportIfObjectStoreTable(relationId);
/*
* for a non-writable rest table, we should not have any rest catalog
* requests
*/
Assert(restCatalogRequests == NIL);
return restCatalogRequests;
}
/*
* CreateIcebergSnapshotBuilder prepares a snapshot builder that keeps track
* of all the changes to the current snapshot.
*/
static IcebergSnapshotBuilder *
CreateIcebergSnapshotBuilder(IcebergTableMetadata * metadata, List *metadataOperations)
{
IcebergSnapshotBuilder *builder = palloc0(sizeof(IcebergSnapshotBuilder));
/*
* Get the current snapshot, and also prepare new snapshot for adding
* files. We take a copy of the current snapshot because there is no
* guarantee that we will retain the current snapshot in the metadata.
*/
builder->baseSnapshot = CopyIcebergSnapshot(GetCurrentSnapshot(metadata, true));
builder->newSnapshot = CreateNewIcebergSnapshot(metadata);
builder->dataEntries = MakePartitionManifestEntryHash();
builder->positionalDeleteEntries = MakePartitionManifestEntryHash();
builder->operation = SnapshotOperationSummary(metadataOperations);
return builder;
}
/*
* MakePartitionManifestEntryHash creates a hash table for the partition
* manifest entries. The hash table is used to keep track of partitionSpecId <->asm
* manifest entries.
*/
static HTAB *
MakePartitionManifestEntryHash(void)
{
HASHCTL hashInfo;
hashInfo.keysize = sizeof(int32_t);
hashInfo.entrysize = sizeof(PartitionSpecManifestsEntries);
hashInfo.hash = uint32_hash;
hashInfo.hcxt = CurrentMemoryContext;
uint32 hashFlags = (HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
return hash_create("Iceberg partitioned manifest entry hash for snapshot builder",
32, &hashInfo, hashFlags);
}
/*
* AddManifestEntryToHash adds a manifest entry to the hash table.
*/
static void
AddManifestEntryToHash(HTAB *hash, int32 partitionSpecId, IcebergManifestEntry * entry)
{
bool found = false;
PartitionSpecManifestsEntries *manifestEntries = hash_search(hash, &partitionSpecId, HASH_ENTER, &found);
if (!found)
{
manifestEntries->partitionSpecId = partitionSpecId;
manifestEntries->manifestEntries = NIL;
}
manifestEntries->manifestEntries = lappend(manifestEntries->manifestEntries, entry);
}
/*
* SetSnapshotOperation sets the operation of the snapshot.
*/
static void
SetSnapshotOperation(IcebergSnapshot * snapshot, SnapshotOperation operation)
{
Property *summary = palloc0(sizeof(Property));
summary->key = "operation";
switch (operation)
{
case SNAPSHOT_OPERATION_APPEND:
summary->value = "append";
break;
case SNAPSHOT_OPERATION_REPLACE:
summary->value = "replace";
break;
case SNAPSHOT_OPERATION_OVERWRITE:
summary->value = "overwrite";
break;
case SNAPSHOT_OPERATION_DELETE:
summary->value = "delete";
break;
default:
ereport(ERROR, (errmsg("Unsupported snapshot operation: %d", operation)));
}
snapshot->summary = summary;
snapshot->summary_length = 1;
}
/*
* SnapshotOperationSummary determines the summary of the given metadata operations.
* As per iceberg spec:
* The snapshot summary's operation field is used by some operations, like snapshot expiration, to skip processing certain snapshots. Possible operation values are:
* - append -- Only data files were added and no files were removed.
* - replace -- Data and delete files were added and removed without changing table data; i.e., compaction, changing the data file format, or relocating data files.
* - overwrite -- Data and delete files were added and removed in a logical overwrite operation.
* - delete -- Data files were removed and their contents logically deleted and/or delete files were added to delete rows.
*/
static SnapshotOperation
SnapshotOperationSummary(List *metadataOperations)
{
SnapshotOperation currentSummary = SNAPSHOT_OPERATION_INVALID;
ListCell *operationCell = NULL;
foreach(operationCell, metadataOperations)
{
TableMetadataOperation *operation = lfirst(operationCell);
switch (operation->type)
{
case DATA_FILE_ADD:
{
if (operation->content == CONTENT_DATA)
{
if (currentSummary == SNAPSHOT_OPERATION_INVALID ||
currentSummary == SNAPSHOT_OPERATION_APPEND)
{
currentSummary = SNAPSHOT_OPERATION_APPEND;
}
else
{
currentSummary = SNAPSHOT_OPERATION_OVERWRITE;
}
}
else if (operation->content == CONTENT_POSITION_DELETES)
{
if (currentSummary == SNAPSHOT_OPERATION_INVALID ||
currentSummary == SNAPSHOT_OPERATION_DELETE)
{
currentSummary = SNAPSHOT_OPERATION_DELETE;
}
else
{
currentSummary = SNAPSHOT_OPERATION_OVERWRITE;
}
}
else
{
ereport(ERROR, (errmsg("Unsupported operation content type: %d", operation->content)));
}
break;
}
case DATA_FILE_REMOVE_ALL:
case DATA_FILE_REMOVE:
{
if (currentSummary == SNAPSHOT_OPERATION_INVALID ||
currentSummary == SNAPSHOT_OPERATION_DELETE)
{
currentSummary = SNAPSHOT_OPERATION_DELETE;
}
else
{
currentSummary = SNAPSHOT_OPERATION_OVERWRITE;
}
break;
}
case DATA_FILE_MERGE_MANIFESTS:
case EXPIRE_OLD_SNAPSHOTS:
{
if (currentSummary == SNAPSHOT_OPERATION_INVALID ||
currentSummary == SNAPSHOT_OPERATION_REPLACE)
{
currentSummary = SNAPSHOT_OPERATION_REPLACE;
}
else
{
currentSummary = SNAPSHOT_OPERATION_OVERWRITE;
}
break;
}
case TABLE_DDL:
case TABLE_PARTITION_BY:
{
/*
* Spark doesn't push a new snapshot for the schema
* changes. But we do and we treat this as an overwrite,
* which is the highest level.
*/
currentSummary = SNAPSHOT_OPERATION_OVERWRITE;
break;
}
/* these do not affect the Iceberg metadata */
case DATA_FILE_UPDATE_DELETED_ROW_COUNT:
case DATA_FILE_ADD_DELETE_MAPPING:
case DATA_FILE_ADD_ROW_ID_MAPPING:
case DATA_FILE_DROP_TABLE:
case TABLE_CREATE:
{
break;
}
default:
ereport(ERROR, (errmsg("Unsupported operation type: %d", operation->type)));
}
}
return currentSummary;
}
/*
* ProcessIcebergMetadataOperations creates the manifest entries for the given metadata operations.
*/
static void
ProcessIcebergMetadataOperations(Oid relationId, List *metadataOperations,
IcebergSnapshotBuilder * builder)
{
ListCell *operationCell = NULL;
foreach(operationCell, metadataOperations)
{
TableMetadataOperation *operation = lfirst(operationCell);
switch (operation->type)
{
case DATA_FILE_ADD:
{
IcebergManifestEntry *manifestEntry =
CreateIcebergManifestEntryFromMetadataOperation(operation,
builder->newSnapshot->snapshot_id,
builder->newSnapshot->sequence_number);
if (operation->content == CONTENT_DATA)
{
AddManifestEntryToHash(builder->dataEntries,
operation->partitionSpecId,
manifestEntry);
}
else if (operation->content == CONTENT_POSITION_DELETES)
{
AddManifestEntryToHash(builder->positionalDeleteEntries,
operation->partitionSpecId,
manifestEntry);
}
else
{
ereport(ERROR, (errmsg("Unsupported operation content type: %d", operation->content)));
}
break;
}
case DATA_FILE_REMOVE:
{
IcebergManifestEntry *manifestEntry =
CreateIcebergManifestEntryFromMetadataOperation(operation,
builder->newSnapshot->snapshot_id,
builder->newSnapshot->sequence_number);
builder->removedEntries = lappend(builder->removedEntries, manifestEntry);
break;
}
case DATA_FILE_ADD_DELETE_MAPPING:
{
/*
* Iceberg metadata doesn't track delete mappings, so
* skip.
*/
break;
}
case DATA_FILE_ADD_ROW_ID_MAPPING:
{
/*
* Iceberg metadata doesn't track row id mappings, so
* skip.
*/
break;
}
case DATA_FILE_UPDATE_DELETED_ROW_COUNT:
{
/*
* Iceberg metadata doesn't track deleted row counts, so
* skip
*/
break;
}
case DATA_FILE_MERGE_MANIFESTS:
{
/*
* We are requested to merge manifests, and we'll handle
* this operation in TrackIcebergMetadataChangesInTx().
*/
builder->applyManifestCompaction = true;
break;
}
case TABLE_CREATE:
{
/*
* we expect one TABLE_CREATE command for all Postgres
* commands that affect iceberg schema and partition spec
* if the table is created in the same transaction
*/
Assert(!builder->createTable);
builder->createTable = true;
builder->schema = operation->newSchema;
builder->partitionSpecs = operation->partitionSpecs;
builder->defaultSpecId = operation->defaultSpecId;
break;
}
case TABLE_DDL:
{
/*
* we expect one TABLE_DDL command for all Postgres
* commands that affect iceberg schema during the
* transaction
*/
Assert(!builder->regenerateSchema);
builder->regenerateSchema = true;
/*
* We are requested to update the table schema, and we'll
* handle this operation in
* TrackIcebergMetadataChangesInTx().
*/
if (operation->ddlSchemaEffect == DDL_EFFECT_ADD_SCHEMA)
{
/* these two are mutually exclusive */
Assert(operation->existingSchemaId == -1);
Assert(operation->newSchema != NULL);
builder->schema = operation->newSchema;
}
else if (operation->ddlSchemaEffect == DDL_EFFECT_SET_EXISTING_SCHEMA)
{
/* these two are mutually exclusive */
Assert(operation->existingSchemaId != -1);
Assert(operation->newSchema == NULL);
builder->schemaId = operation->existingSchemaId;
}
else
{
ereport(ERROR, (errmsg("Unsupported DDL schema effect: %d", operation->ddlSchemaEffect)));
}
break;
}
case TABLE_PARTITION_BY:
{
/*
* We expect one TABLE_PARTITION_BY command at a time for
* all Postgres commands that affect iceberg partition
* spec during the transaction. This is already limited by
* Postgres, such that even if you provide multiple SET
* partition_by, Postgres only keeps the last one.
*/
Assert(!builder->regeneratePartitionSpec);
/*
* We are requested to update the partition spec, and
* we'll handle this operation in
* TrackIcebergMetadataChangesInTx().
*/
builder->regeneratePartitionSpec = true;
builder->partitionSpecs = operation->partitionSpecs;
builder->defaultSpecId = operation->defaultSpecId;
break;
}
case EXPIRE_OLD_SNAPSHOTS:
{
/*
* We are requested to expire old snapshots, and we'll
* handle this operation in
* TrackIcebergMetadataChangesInTx().
*/
builder->expireOldSnapshots = true;
break;
}
case DATA_FILE_DROP_TABLE:
{
/*
* We are not requested to remove all files from the
* iceberg metadata, but only from the pg_lake catalog. We
* skip this operation.
*/
break;
}
case DATA_FILE_REMOVE_ALL:
{
builder->removeAllEntries = true;
break;
}
default:
ereport(ERROR, (errmsg("Unsupported operation type: %d", operation->type)));
}
}
}
/*
* FinalizeNewSnapshot creates a new snapshot from an IcebergSnapshotBuilder.
*
* It creates new manifest files for the new data files and positional
* delete files and appends them to the existing manifest files in the current
* snapshot. If needed, we also apply manifest compaction.
*/
static IcebergSnapshot *
FinalizeNewSnapshot(IcebergSnapshotBuilder * builder, Oid relationId, const char *metadataLocation,
int32_t currentSchemaId, List *allTransforms, bool isVerbose)
{
IcebergSnapshot *currentSnapshot = builder->baseSnapshot;
IcebergSnapshot *newSnapshot = builder->newSnapshot;
HTAB *newDataManifestEntries = builder->dataEntries;
HTAB *newPositionalDeleteManifestEntries = builder->positionalDeleteEntries;
List *removedEntries = builder->removedEntries;
bool removeAllEntries = builder->removeAllEntries;
bool applyManifestCompaction = builder->applyManifestCompaction;
int64_t snapshotId = newSnapshot->snapshot_id;
const char *snapshotUUID = GenerateUUID();
/* within the new same snapshot, we might have multiple manifests */
int manifestIndex = 0;
int manifestListIndex = 1;
/* regenerate schema or partition spec should always create new snapshot */
bool createNewSnapshot =
builder->regenerateSchema || builder->regeneratePartitionSpec;
/*
* Always create a new manifest file for the new data and positional
* delete file(s) and append it to the existing data files in the current
* snapshot.
*/
const List *existingDataManifests =
FetchManifestsFromSnapshot(currentSnapshot, IsManifestOfFileContentAdd);
const List *existingDeleteManifests =
FetchManifestsFromSnapshot(currentSnapshot, IsManifestOfFileContentDeletes);
/* do not modify existing manifests */
List *finalDataManifestList = list_copy(existingDataManifests);
List *finalDeleteManifestList = list_copy(existingDeleteManifests);
if (applyManifestCompaction || EnableManifestMergeOnWrite)
{
/*
* RemoveDeletedManifestEntries goes through old snapshot's manifests
* and removes any entries that are marked as deleted.
*/
bool anyDataManifestModified = RemoveDeletedManifestEntries(currentSnapshot, allTransforms, &finalDataManifestList,
ICEBERG_MANIFEST_FILE_CONTENT_DATA, metadataLocation,
snapshotUUID, isVerbose, &manifestIndex);
bool anyDeleteManifestModified = RemoveDeletedManifestEntries(currentSnapshot, allTransforms, &finalDeleteManifestList,
ICEBERG_MANIFEST_FILE_CONTENT_DELETES, metadataLocation,
snapshotUUID, isVerbose, &manifestIndex);
if (anyDataManifestModified || anyDeleteManifestModified)
createNewSnapshot = true;
}
/*
* Iterate on the newDataManifestEntries HTAB, which is already grouped by
* partitionSpecId. For each partitionSpecId, create a new manifest.
*/
if (hash_get_num_entries(newDataManifestEntries) > 0)
{
HASH_SEQ_STATUS status;
hash_seq_init(&status, newDataManifestEntries);
PartitionSpecManifestsEntries *entry = NULL;
while ((entry = hash_seq_search(&status)) != NULL)
{
int32 partitionSpecId = entry->partitionSpecId;
List *manifestEntries = entry->manifestEntries;
char *remoteManifestPath =
GenerateRemoteManifestPath(metadataLocation,
snapshotUUID,
manifestIndex++, "");
int64_t manifestSize = UploadIcebergManifestToURI(manifestEntries, remoteManifestPath);
IcebergManifest *newDataManifest =
CreateNewIcebergManifest(newSnapshot, partitionSpecId, allTransforms,
manifestSize, ICEBERG_MANIFEST_FILE_CONTENT_DATA,
remoteManifestPath, manifestEntries);
finalDataManifestList = lappend(finalDataManifestList, newDataManifest);
createNewSnapshot = true;
}
}
/*
* Iterate on the newPositionalDeleteManifestEntries HTAB, which is
* already grouped by partitionSpecId. For each partitionSpecId, create a
* new manifest.
*/
if (hash_get_num_entries(newPositionalDeleteManifestEntries) > 0)
{
HASH_SEQ_STATUS status;
hash_seq_init(&status, newPositionalDeleteManifestEntries);
PartitionSpecManifestsEntries *entry = NULL;
while ((entry = hash_seq_search(&status)) != NULL)
{
int32 partitionSpecId = entry->partitionSpecId;
List *manifestEntries = entry->manifestEntries;
char *remoteManifestPath =
GenerateRemoteManifestPath(metadataLocation,
snapshotUUID,
manifestIndex++, "");
int64_t manifestSize = UploadIcebergManifestToURI(manifestEntries, remoteManifestPath);
IcebergManifest *newDeleteManifest =
CreateNewIcebergManifest(newSnapshot, partitionSpecId, allTransforms, manifestSize,
ICEBERG_MANIFEST_FILE_CONTENT_DELETES, remoteManifestPath,
manifestEntries);
finalDeleteManifestList = lappend(finalDeleteManifestList, newDeleteManifest);
createNewSnapshot = true;
}
}
/*
* If we have any files to be marked as removed, we need to update the
* manifest entries to mark them as deleted. We do no create anything new
* here, we just update the existing manifest entries. If any entry
* changes in a manifest, we write a new manifest file.
*/
if (removedEntries != NIL || removeAllEntries)
{
/* do not modify input lists */
List *manifestList = list_concat_copy(finalDataManifestList,
finalDeleteManifestList);
ListCell *manifestCell = NULL;
foreach(manifestCell, manifestList)
{
IcebergManifest *manifest = lfirst(manifestCell);
IcebergManifestContentType content = manifest->content;
List *manifestEntries =
ReadManifestEntries(manifest->manifest_path);
List *deletedManifestEntries =
FindAndAdjustDeletedManifestEntries(manifest, manifestEntries, removedEntries,
snapshotId, removeAllEntries);
if (deletedManifestEntries != NIL)
{
List *newManifests =
CreateNewManifestsForDeletedEntries(manifestEntries, deletedManifestEntries,
newSnapshot, metadataLocation, snapshotUUID,
&manifestIndex, manifest->partition_spec_id,