-
Notifications
You must be signed in to change notification settings - Fork 438
/
Copy pathdelta.rs
1794 lines (1596 loc) · 64.5 KB
/
delta.rs
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
//! Delta Table read and write implementation
// Reference: https://github.com/delta-io/delta/blob/master/PROTOCOL.md
//
use arrow::error::ArrowError;
use chrono::{DateTime, FixedOffset, Utc};
use futures::StreamExt;
use lazy_static::lazy_static;
use log::*;
use parquet::errors::ParquetError;
use parquet::file::{
reader::{FileReader, SerializedFileReader},
serialized_reader::SliceableCursor,
};
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use std::collections::HashMap;
use std::convert::TryFrom;
use std::fmt;
use std::io::{BufRead, BufReader, Cursor};
use std::time::{SystemTime, UNIX_EPOCH};
use std::{cmp::Ordering, collections::HashSet};
use uuid::Uuid;
use crate::action::Stats;
use super::action;
use super::action::{Action, DeltaOperation};
use super::delta_config;
use super::partitions::{DeltaTablePartition, PartitionFilter};
use super::schema::*;
use super::storage;
use super::storage::{parse_uri, StorageBackend, StorageError, UriError};
use crate::delta_config::DeltaConfigError;
/// Metadata for a checkpoint file
#[derive(Serialize, Deserialize, Debug, Default, Clone, Copy)]
pub struct CheckPoint {
/// Delta table version
version: DeltaDataTypeVersion, // 20 digits decimals
size: DeltaDataTypeLong,
parts: Option<u32>, // 10 digits decimals
}
impl CheckPoint {
/// Creates a new checkpoint from the given parameters.
pub(crate) fn new(
version: DeltaDataTypeVersion,
size: DeltaDataTypeLong,
parts: Option<u32>,
) -> Self {
Self {
version,
size,
parts,
}
}
}
impl PartialEq for CheckPoint {
fn eq(&self, other: &Self) -> bool {
self.version == other.version
}
}
impl Eq for CheckPoint {}
/// Delta Table specific error
#[derive(thiserror::Error, Debug)]
pub enum DeltaTableError {
/// Error returned when applying transaction log failed.
#[error("Failed to apply transaction log: {}", .source)]
ApplyLog {
/// Apply error details returned when applying transaction log failed.
#[from]
source: ApplyLogError,
},
/// Error returned when loading checkpoint failed.
#[error("Failed to load checkpoint: {}", .source)]
LoadCheckpoint {
/// Load checkpoint error details returned when loading checkpoint failed.
#[from]
source: LoadCheckpointError,
},
/// Error returned when reading the delta log object failed.
#[error("Failed to read delta log object: {}", .source)]
StorageError {
/// Storage error details when reading the delta log object failed.
#[from]
source: StorageError,
},
/// Error returned when reading the checkpoint failed.
#[error("Failed to read checkpoint: {}", .source)]
ParquetError {
/// Parquet error details returned when reading the checkpoint failed.
#[from]
source: ParquetError,
},
/// Error returned when converting the schema in Arrow format failed.
#[error("Failed to convert into Arrow schema: {}", .source)]
ArrowError {
/// Arrow error details returned when converting the schema in Arrow format failed
#[from]
source: ArrowError,
},
/// Error returned when the table has an invalid path.
#[error("Invalid table path: {}", .source)]
UriError {
/// Uri error details returned when the table has an invalid path.
#[from]
source: UriError,
},
/// Error returned when the log record has an invalid JSON.
#[error("Invalid JSON in log record: {}", .source)]
InvalidJson {
/// JSON error details returned when the log record has an invalid JSON.
#[from]
source: serde_json::error::Error,
},
/// Error returned when the DeltaTable has an invalid version.
#[error("Invalid table version: {0}")]
InvalidVersion(DeltaDataTypeVersion),
/// Error returned when the DeltaTable has no data files.
#[error("Corrupted table, cannot read data file {}: {}", .path, .source)]
MissingDataFile {
/// Source error details returned when the DeltaTable has no data files.
source: std::io::Error,
/// The Path used of the DeltaTable
path: String,
},
/// Error returned when the datetime string is invalid for a conversion.
#[error("Invalid datetime string: {}", .source)]
InvalidDateTimeString {
/// Parse error details returned of the datetime string parse error.
#[from]
source: chrono::ParseError,
},
/// Error returned when the action record is invalid in log.
#[error("Invalid action record found in log: {}", .source)]
InvalidAction {
/// Action error details returned of the invalid action.
#[from]
source: action::ActionError,
},
/// Error returned when it is not a DeltaTable.
#[error("Not a Delta table: {0}")]
NotATable(String),
/// Error returned when no metadata was found in the DeltaTable.
#[error("No metadata found, please make sure table is loaded.")]
NoMetadata,
/// Error returned when no schema was found in the DeltaTable.
#[error("No schema found, please make sure table is loaded.")]
NoSchema,
/// Error returned when no partition was found in the DeltaTable.
#[error("No partitions found, please make sure table is partitioned.")]
LoadPartitions,
/// Error returned when writes are attempted with data that doesn't match the schema of the
/// table
#[error("Data does not match the schema or partitions of the table: {}", msg)]
SchemaMismatch {
/// Information about the mismatch
msg: String,
},
/// Error returned when a partition is not formatted as a Hive Partition.
#[error("This partition is not formatted with key=value: {}", .partition)]
PartitionError {
/// The malformed partition used.
partition: String,
},
/// Error returned when a invalid partition filter was found.
#[error("Invalid partition filter found: {}.", .partition_filter)]
InvalidPartitionFilter {
/// The invalid partition filter used.
partition_filter: String,
},
/// Error returned when Vacuum retention period is below the safe threshold
#[error(
"Invalid retention period, retention for Vacuum must be greater than 1 week (168 hours)"
)]
InvalidVacuumRetentionPeriod,
/// Error returned when transaction is failed to be committed because given version already exists.
#[error("Delta transaction failed, version {0} already exists.")]
VersionAlreadyExists(DeltaDataTypeVersion),
/// Generic Delta Table error
#[error("Generic DeltaTable error: {0}")]
Generic(String),
}
/// Delta table metadata
#[derive(Clone, Debug, PartialEq)]
pub struct DeltaTableMetaData {
/// Unique identifier for this table
pub id: Guid,
/// User-provided identifier for this table
pub name: Option<String>,
/// User-provided description for this table
pub description: Option<String>,
/// Specification of the encoding for the files stored in the table
pub format: action::Format,
/// Schema of the table
pub schema: Schema,
/// An array containing the names of columns by which the data should be partitioned
pub partition_columns: Vec<String>,
/// The time when this metadata action is created, in milliseconds since the Unix epoch
pub created_time: Option<DeltaDataTypeTimestamp>,
/// table properties
pub configuration: HashMap<String, Option<String>>,
}
impl DeltaTableMetaData {
/// Create metadata for a DeltaTable from scratch
pub fn new(
name: Option<String>,
description: Option<String>,
format: Option<action::Format>,
schema: Schema,
partition_columns: Vec<String>,
configuration: HashMap<String, Option<String>>,
) -> Self {
// Reference implementation uses uuid v4 to create GUID:
// https://github.com/delta-io/delta/blob/master/core/src/main/scala/org/apache/spark/sql/delta/actions/actions.scala#L350
Self {
id: Uuid::new_v4().to_string(),
name,
description,
format: format.unwrap_or_default(),
schema,
partition_columns,
created_time: Some(Utc::now().timestamp_millis()),
configuration,
}
}
/// Return the configurations of the DeltaTableMetaData; could be empty
pub fn get_configuration(&self) -> &HashMap<String, Option<String>> {
&self.configuration
}
}
impl fmt::Display for DeltaTableMetaData {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"GUID={}, name={:?}, description={:?}, partitionColumns={:?}, createdTime={:?}, configuration={:?}",
self.id, self.name, self.description, self.partition_columns, self.created_time, self.configuration
)
}
}
impl TryFrom<action::MetaData> for DeltaTableMetaData {
type Error = serde_json::error::Error;
fn try_from(action_metadata: action::MetaData) -> Result<Self, Self::Error> {
let schema = action_metadata.get_schema()?;
Ok(Self {
id: action_metadata.id,
name: action_metadata.name,
description: action_metadata.description,
format: action_metadata.format,
schema,
partition_columns: action_metadata.partition_columns,
created_time: action_metadata.created_time,
configuration: action_metadata.configuration,
})
}
}
impl TryFrom<DeltaTableMetaData> for action::MetaData {
type Error = serde_json::error::Error;
fn try_from(metadata: DeltaTableMetaData) -> Result<Self, Self::Error> {
let schema_string = serde_json::to_string(&metadata.schema)?;
Ok(Self {
id: metadata.id,
name: metadata.name,
description: metadata.description,
format: metadata.format,
schema_string,
partition_columns: metadata.partition_columns,
created_time: metadata.created_time,
configuration: metadata.configuration,
})
}
}
/// Error related to Delta log application
#[derive(thiserror::Error, Debug)]
pub enum ApplyLogError {
/// Error returned when the end of transaction log is reached.
#[error("End of transaction log")]
EndOfLog,
/// Error returned when the JSON of the log record is invalid.
#[error("Invalid JSON in log record")]
InvalidJson {
/// JSON error details returned when reading the JSON log record.
#[from]
source: serde_json::error::Error,
},
/// Error returned when the storage failed to read the log content.
#[error("Failed to read log content")]
Storage {
/// Storage error details returned while reading the log content.
source: StorageError,
},
/// Error returned when reading delta config failed.
#[error("Failed to read delta config: {}", .source)]
Config {
/// Delta config error returned when reading delta config failed.
#[from]
source: DeltaConfigError,
},
/// Error returned when a line from log record is invalid.
#[error("Failed to read line from log record")]
Io {
/// Source error details returned while reading the log record.
#[from]
source: std::io::Error,
},
/// Error returned when the action record is invalid in log.
#[error("Invalid action record found in log: {}", .source)]
InvalidAction {
/// Action error details returned of the invalid action.
#[from]
source: action::ActionError,
},
}
impl From<StorageError> for ApplyLogError {
fn from(error: StorageError) -> Self {
match error {
StorageError::NotFound => ApplyLogError::EndOfLog,
_ => ApplyLogError::Storage { source: error },
}
}
}
/// Error related to checkpoint loading
#[derive(thiserror::Error, Debug)]
pub enum LoadCheckpointError {
/// Error returned when the JSON checkpoint is not found.
#[error("Checkpoint file not found")]
NotFound,
/// Error returned when the JSON checkpoint is invalid.
#[error("Invalid JSON in checkpoint: {source}")]
InvalidJson {
/// Error details returned while reading the JSON.
#[from]
source: serde_json::error::Error,
},
/// Error returned when it failed to read the checkpoint content.
#[error("Failed to read checkpoint content: {source}")]
Storage {
/// Storage error details returned while reading the checkpoint content.
source: StorageError,
},
}
impl From<StorageError> for LoadCheckpointError {
fn from(error: StorageError) -> Self {
match error {
StorageError::NotFound => LoadCheckpointError::NotFound,
_ => LoadCheckpointError::Storage { source: error },
}
}
}
/// State snapshot currently held by the Delta Table instance.
#[derive(Default, Debug, Clone)]
pub struct DeltaTableState {
// A remove action should remain in the state of the table as a tombstone until it has expired.
// A tombstone expires when the creation timestamp of the delta file exceeds the expiration
tombstones: Vec<action::Remove>,
files: Vec<action::Add>,
commit_infos: Vec<Map<String, Value>>,
app_transaction_version: HashMap<String, DeltaDataTypeVersion>,
min_reader_version: i32,
min_writer_version: i32,
current_metadata: Option<DeltaTableMetaData>,
tombstone_retention_millis: DeltaDataTypeLong,
}
impl DeltaTableState {
/// Full list of tombstones (remove actions) representing files removed from table state).
pub fn all_tombstones(&self) -> &Vec<action::Remove> {
self.tombstones.as_ref()
}
/// List of unexpired tombstones (remove actions) representing files removed from table state.
/// The retention period is set by `deletedFileRetentionDuration` with default value of 1 week.
pub fn unexpired_tombstones(&self) -> Vec<&action::Remove> {
let retention_timestamp = Utc::now().timestamp_millis() - self.tombstone_retention_millis;
self.tombstones
.iter()
.filter(|t| t.deletion_timestamp.unwrap_or(0) > retention_timestamp)
.collect()
}
/// Full list of add actions representing all parquet files that are part of the current
/// delta table state.
pub fn files(&self) -> &Vec<action::Add> {
self.files.as_ref()
}
/// HashMap containing the last txn version stored for every app id writing txn
/// actions.
pub fn app_transaction_version(&self) -> &HashMap<String, DeltaDataTypeVersion> {
&self.app_transaction_version
}
/// The min reader version required by the protocol.
pub fn min_reader_version(&self) -> i32 {
self.min_reader_version
}
/// The min writer version required by the protocol.
pub fn min_writer_version(&self) -> i32 {
self.min_writer_version
}
/// The most recent metadata of the table.
pub fn current_metadata(&self) -> Option<&DeltaTableMetaData> {
self.current_metadata.as_ref()
}
/// merges new state information into our state
pub fn merge(&mut self, mut new_state: DeltaTableState) {
self.files.append(&mut new_state.files);
if !new_state.tombstones.is_empty() {
let new_removals: HashSet<&str> = new_state
.tombstones
.iter()
.map(|s| s.path.as_str())
.collect();
self.files
.retain(|a| !new_removals.contains(a.path.as_str()));
}
self.tombstones.append(&mut new_state.tombstones);
if new_state.min_reader_version > 0 {
self.min_reader_version = new_state.min_reader_version;
self.min_writer_version = new_state.min_writer_version;
}
if new_state.current_metadata.is_some() {
self.tombstone_retention_millis = new_state.tombstone_retention_millis;
self.current_metadata = new_state.current_metadata.take();
}
new_state
.app_transaction_version
.drain()
.for_each(|(app_id, version)| {
*self
.app_transaction_version
.entry(app_id)
.or_insert(version) = version
});
if !new_state.commit_infos.is_empty() {
self.commit_infos.append(&mut new_state.commit_infos);
}
}
}
#[inline]
/// Return path relative to parent_path
fn extract_rel_path<'a, 'b>(
parent_path: &'b str,
path: &'a str,
) -> Result<&'a str, DeltaTableError> {
if path.starts_with(&parent_path) {
// plus one to account for path separator
Ok(&path[parent_path.len() + 1..])
} else {
Err(DeltaTableError::Generic(format!(
"Parent path `{}` is not a prefix of path `{}`",
parent_path, path
)))
}
}
/// In memory representation of a Delta Table
pub struct DeltaTable {
/// The version of the table as of the most recent loaded Delta log entry.
pub version: DeltaDataTypeVersion,
/// The URI the DeltaTable was loaded from.
pub table_uri: String,
state: DeltaTableState,
// metadata
// application_transactions
pub(crate) storage: Box<dyn StorageBackend>,
last_check_point: Option<CheckPoint>,
log_uri: String,
version_timestamp: HashMap<DeltaDataTypeVersion, i64>,
}
impl DeltaTable {
fn commit_uri_from_version(&self, version: DeltaDataTypeVersion) -> String {
let version = format!("{:020}.json", version);
self.storage.join_path(&self.log_uri, &version)
}
fn get_checkpoint_data_paths(&self, check_point: &CheckPoint) -> Vec<String> {
let checkpoint_prefix_pattern = format!("{:020}", check_point.version);
let checkpoint_prefix = self
.storage
.join_path(&self.log_uri, &checkpoint_prefix_pattern);
let mut checkpoint_data_paths = Vec::new();
match check_point.parts {
None => {
checkpoint_data_paths.push(format!("{}.checkpoint.parquet", checkpoint_prefix));
}
Some(parts) => {
for i in 0..parts {
checkpoint_data_paths.push(format!(
"{}.checkpoint.{:010}.{:010}.parquet",
checkpoint_prefix,
i + 1,
parts
));
}
}
}
checkpoint_data_paths
}
async fn get_last_checkpoint(&self) -> Result<CheckPoint, LoadCheckpointError> {
let last_checkpoint_path = self.storage.join_path(&self.log_uri, "_last_checkpoint");
let data = self.storage.get_obj(&last_checkpoint_path).await?;
Ok(serde_json::from_slice(&data)?)
}
async fn find_latest_check_point_for_version(
&self,
version: DeltaDataTypeVersion,
) -> Result<Option<CheckPoint>, DeltaTableError> {
lazy_static! {
static ref CHECKPOINT_REGEX: Regex =
Regex::new(r#"^*[/\\]_delta_log[/\\](\d{20})\.checkpoint\.parquet$"#).unwrap();
static ref CHECKPOINT_PARTS_REGEX: Regex = Regex::new(
r#"^*[/\\]_delta_log[/\\](\d{20})\.checkpoint\.\d{10}\.(\d{10})\.parquet$"#
)
.unwrap();
}
let mut cp: Option<CheckPoint> = None;
let mut stream = self.storage.list_objs(&self.log_uri).await?;
while let Some(obj_meta) = stream.next().await {
// Exit early if any objects can't be listed.
let obj_meta = obj_meta?;
if let Some(captures) = CHECKPOINT_REGEX.captures(&obj_meta.path) {
let curr_ver_str = captures.get(1).unwrap().as_str();
let curr_ver: DeltaDataTypeVersion = curr_ver_str.parse().unwrap();
if curr_ver > version {
// skip checkpoints newer than max version
continue;
}
if cp.is_none() || curr_ver > cp.unwrap().version {
cp = Some(CheckPoint {
version: curr_ver,
size: 0,
parts: None,
});
}
continue;
}
if let Some(captures) = CHECKPOINT_PARTS_REGEX.captures(&obj_meta.path) {
let curr_ver_str = captures.get(1).unwrap().as_str();
let curr_ver: DeltaDataTypeVersion = curr_ver_str.parse().unwrap();
if curr_ver > version {
// skip checkpoints newer than max version
continue;
}
if cp.is_none() || curr_ver > cp.unwrap().version {
let parts_str = captures.get(2).unwrap().as_str();
let parts = parts_str.parse().unwrap();
cp = Some(CheckPoint {
version: curr_ver,
size: 0,
parts: Some(parts),
});
}
continue;
}
}
Ok(cp)
}
fn apply_log_from_bufread<R: BufRead>(
&mut self,
reader: BufReader<R>,
) -> Result<(), ApplyLogError> {
let mut new_state = DeltaTableState::default();
for line in reader.lines() {
let action: Action = serde_json::from_str(line?.as_str())?;
process_action(&mut new_state, action)?;
}
self.state.merge(new_state);
Ok(())
}
async fn apply_log(&mut self, version: DeltaDataTypeVersion) -> Result<(), ApplyLogError> {
let commit_uri = self.commit_uri_from_version(version);
let commit_log_bytes = self.storage.get_obj(&commit_uri).await?;
let reader = BufReader::new(Cursor::new(commit_log_bytes));
self.apply_log_from_bufread(reader)
}
async fn restore_checkpoint(&mut self, check_point: CheckPoint) -> Result<(), DeltaTableError> {
let checkpoint_data_paths = self.get_checkpoint_data_paths(&check_point);
// process actions from checkpoint
self.state = DeltaTableState::default();
for f in &checkpoint_data_paths {
let obj = self.storage.get_obj(f).await?;
let preader = SerializedFileReader::new(SliceableCursor::new(obj))?;
let schema = preader.metadata().file_metadata().schema();
if !schema.is_group() {
return Err(DeltaTableError::from(action::ActionError::Generic(
"Action record in checkpoint should be a struct".to_string(),
)));
}
for record in preader.get_row_iter(None)? {
process_action(
&mut self.state,
Action::from_parquet_record(schema, &record)?,
)?;
}
}
Ok(())
}
async fn get_latest_version(&mut self) -> Result<DeltaDataTypeVersion, DeltaTableError> {
let mut version = match self.get_last_checkpoint().await {
Ok(last_check_point) => last_check_point.version + 1,
Err(LoadCheckpointError::NotFound) => {
// no checkpoint, start with version 0
0
}
Err(e) => {
return Err(DeltaTableError::LoadCheckpoint { source: e });
}
};
// scan logs after checkpoint
loop {
match self
.storage
.head_obj(&self.commit_uri_from_version(version))
.await
{
Ok(meta) => {
// also cache timestamp for version
self.version_timestamp
.insert(version, meta.modified.timestamp());
version += 1;
}
Err(e) => {
match e {
StorageError::NotFound => {
version -= 1;
if version < 0 {
let err = format!(
"No snapshot or version 0 found, perhaps {} is an empty dir?",
self.table_uri
);
return Err(DeltaTableError::NotATable(err));
}
}
_ => return Err(DeltaTableError::from(e)),
}
break;
}
}
}
Ok(version)
}
/// Load DeltaTable with data from latest checkpoint
pub async fn load(&mut self) -> Result<(), DeltaTableError> {
self.last_check_point = None;
self.version = -1;
self.state = DeltaTableState::default();
self.update().await
}
/// Updates the DeltaTable to the most recent state committed to the transaction log by
/// loading the last checkpoint and incrementally applying each version since.
pub async fn update(&mut self) -> Result<(), DeltaTableError> {
match self.get_last_checkpoint().await {
Ok(last_check_point) => {
if Some(last_check_point) == self.last_check_point {
self.update_incremental().await
} else {
self.last_check_point = Some(last_check_point);
self.restore_checkpoint(last_check_point).await?;
self.version = last_check_point.version;
self.update_incremental().await
}
}
Err(LoadCheckpointError::NotFound) => self.update_incremental().await,
Err(e) => Err(DeltaTableError::LoadCheckpoint { source: e }),
}
}
/// Updates the DeltaTable to the latest version by incrementally applying newer versions.
/// It assumes that the table is already updated to the current version `self.version`.
pub async fn update_incremental(&mut self) -> Result<(), DeltaTableError> {
self.version += 1;
loop {
match self.apply_log(self.version).await {
Ok(_) => {
self.version += 1;
}
Err(e) => {
match e {
ApplyLogError::EndOfLog => {
self.version -= 1;
if self.version == -1 {
let err = format!(
"No snapshot or version 0 found, perhaps {} is an empty dir?",
self.table_uri
);
return Err(DeltaTableError::NotATable(err));
}
}
_ => {
return Err(DeltaTableError::from(e));
}
}
return Ok(());
}
}
}
}
/// Loads the DeltaTable state for the given version.
pub async fn load_version(
&mut self,
version: DeltaDataTypeVersion,
) -> Result<(), DeltaTableError> {
// check if version is valid
let commit_uri = self.commit_uri_from_version(version);
match self.storage.head_obj(&commit_uri).await {
Ok(_) => {}
Err(StorageError::NotFound) => {
return Err(DeltaTableError::InvalidVersion(version));
}
Err(e) => {
return Err(DeltaTableError::from(e));
}
}
self.version = version;
let mut next_version;
// 1. find latest checkpoint below version
match self.find_latest_check_point_for_version(version).await? {
Some(check_point) => {
self.restore_checkpoint(check_point).await?;
next_version = check_point.version + 1;
}
None => {
// no checkpoint found, clear table state and start from the beginning
self.state = DeltaTableState::default();
next_version = 0;
}
}
// 2. apply all logs starting from checkpoint
while next_version <= self.version {
self.apply_log(next_version).await?;
next_version += 1;
}
Ok(())
}
async fn get_version_timestamp(
&mut self,
version: DeltaDataTypeVersion,
) -> Result<i64, DeltaTableError> {
match self.version_timestamp.get(&version) {
Some(ts) => Ok(*ts),
None => {
let meta = self
.storage
.head_obj(&self.commit_uri_from_version(version))
.await?;
let ts = meta.modified.timestamp();
// also cache timestamp for version
self.version_timestamp.insert(version, ts);
Ok(ts)
}
}
}
/// Returns provenance information, including the operation, user, and so on, for each write to a table.
/// The table history retention is based on the `logRetentionDuration` property of the Delta Table, 30 days by default.
pub fn history(
&mut self,
limit: Option<usize>,
) -> Result<Vec<Map<String, Value>>, DeltaTableError> {
let commit_infos_list = self.state.commit_infos.iter().rev().map(Map::clone);
match limit {
Some(l) => Ok(commit_infos_list.take(l).collect()),
None => Ok(commit_infos_list.collect()),
}
}
/// Returns the file list tracked in current table state filtered by provided
/// `PartitionFilter`s.
pub fn get_files_by_partitions(
&self,
filters: &[PartitionFilter<&str>],
) -> Result<Vec<String>, DeltaTableError> {
let files = self
.state
.files
.iter()
.filter(|add| {
let partitions = add
.partition_values
.iter()
.map(|p| DeltaTablePartition::from_partition_value(p, ""))
.collect::<Vec<DeltaTablePartition>>();
filters
.iter()
.all(|filter| filter.match_partitions(&partitions))
})
.map(|add| add.path.clone())
.collect();
Ok(files)
}
/// Return the file uris as strings for the partition(s)
#[deprecated(
since = "0.4.0",
note = "Please use the get_file_uris_by_partitions function instead"
)]
pub fn get_file_paths_by_partitions(
&self,
filters: &[PartitionFilter<&str>],
) -> Result<Vec<String>, DeltaTableError> {
self.get_file_uris_by_partitions(filters)
}
/// Return the file uris as strings for the partition(s)
pub fn get_file_uris_by_partitions(
&self,
filters: &[PartitionFilter<&str>],
) -> Result<Vec<String>, DeltaTableError> {
let files = self.get_files_by_partitions(filters)?;
Ok(files
.iter()
.map(|fname| self.storage.join_path(&self.table_uri, fname))
.collect())
}
/// Return a refernece to all active "add" actions present in the loaded state
pub fn get_active_add_actions(&self) -> &Vec<action::Add> {
&self.state.files
}
/// Returns an iterator of file names present in the loaded state
#[inline]
pub fn get_files_iter(&self) -> impl Iterator<Item = &str> {
self.state.files.iter().map(|add| add.path.as_str())
}
/// Returns a collection of file names present in the loaded state
#[inline]
pub fn get_files(&self) -> Vec<&str> {
self.get_files_iter().collect()
}
/// Returns file names present in the loaded state in HashSet
pub fn get_file_set(&self) -> HashSet<&str> {
self.state
.files
.iter()
.map(|add| add.path.as_str())
.collect()
}
/// Returns a URIs for all active files present in the current table version.
#[deprecated(
since = "0.4.0",
note = "Please use the get_file_uris function instead"
)]
pub fn get_file_paths(&self) -> Vec<String> {
self.get_file_uris()
}
/// Returns a URIs for all active files present in the current table version.
pub fn get_file_uris(&self) -> Vec<String> {
self.state
.files
.iter()
.map(|add| self.storage.join_path(&self.table_uri, &add.path))
.collect()
}
/// Returns statistics for files, in order
pub fn get_stats(&self) -> Vec<Result<Option<Stats>, DeltaTableError>> {
self.state
.files
.iter()
.map(|add| add.get_stats().map_err(DeltaTableError::from))
.collect()
}
/// Returns the currently loaded state snapshot.
pub fn get_state(&self) -> &DeltaTableState {
&self.state
}
/// Returns the metadata associated with the loaded state.
pub fn get_metadata(&self) -> Result<&DeltaTableMetaData, DeltaTableError> {
self.state
.current_metadata
.as_ref()
.ok_or(DeltaTableError::NoMetadata)
}
/// Returns a vector of active tombstones (i.e. `Remove` actions present in the current delta log).
pub fn get_tombstones(&self) -> Vec<&action::Remove> {
self.state.unexpired_tombstones()
}
/// Returns the current version of the DeltaTable based on the loaded metadata.
pub fn get_app_transaction_version(&self) -> &HashMap<String, DeltaDataTypeVersion> {
&self.state.app_transaction_version
}
/// Returns the minimum reader version supported by the DeltaTable based on the loaded
/// metadata.
pub fn get_min_reader_version(&self) -> i32 {
self.state.min_reader_version
}
/// Returns the minimum writer version supported by the DeltaTable based on the loaded
/// metadata.
pub fn get_min_writer_version(&self) -> i32 {
self.state.min_writer_version
}
/// List files no longer referenced by a Delta table and are older than the retention threshold.
fn get_stale_files(
&self,
retention_hours: Option<u64>,
) -> Result<HashSet<&str>, DeltaTableError> {
let retention_millis = retention_hours
.map(|hours| 3600000 * hours as i64)
.unwrap_or(self.state.tombstone_retention_millis);
if retention_millis < self.state.tombstone_retention_millis {
return Err(DeltaTableError::InvalidVacuumRetentionPeriod);
}
let tombstone_retention_timestamp = Utc::now().timestamp_millis() - retention_millis;
Ok(self
.state
.all_tombstones()
.iter()
.filter(|tombstone| {
// if the file has a creation time before the `tombstone_retention_timestamp`
// then it's considered as a stale file
tombstone.deletion_timestamp.unwrap_or(0) < tombstone_retention_timestamp
})
.map(|tombstone| tombstone.path.as_str())
.collect::<HashSet<_>>())
}
/// Whether a path should be hidden for delta-related file operations, such as Vacuum.
/// Names of the form partitionCol=[value] are partition directories, and should be
/// deleted even if they'd normally be hidden. The _db_index directory contains (bloom filter)
/// indexes and these must be deleted when the data they are tied to is deleted.