-
Notifications
You must be signed in to change notification settings - Fork 435
/
Copy pathtable.py
1930 lines (1664 loc) · 75.2 KB
/
table.py
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
import json
import operator
import warnings
from dataclasses import dataclass
from datetime import datetime, timedelta
from enum import Enum
from functools import reduce
from pathlib import Path
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generator,
Iterable,
List,
Literal,
Mapping,
NamedTuple,
Optional,
Tuple,
Union,
cast,
)
import pyarrow
import pyarrow.dataset as ds
import pyarrow.fs as pa_fs
import pyarrow_hotfix # noqa: F401; addresses CVE-2023-47248; # type: ignore
from pyarrow.dataset import (
Expression,
FileSystemDataset,
ParquetFileFormat,
ParquetFragmentScanOptions,
ParquetReadOptions,
)
if TYPE_CHECKING:
import os
import pandas
from deltalake._internal import DeltaDataChecker as _DeltaDataChecker
from deltalake._internal import RawDeltaTable
from deltalake._internal import create_deltalake as _create_deltalake
from deltalake._util import encode_partition_value
from deltalake.data_catalog import DataCatalog
from deltalake.exceptions import DeltaProtocolError
from deltalake.fs import DeltaStorageHandler
from deltalake.schema import Schema as DeltaSchema
MAX_SUPPORTED_READER_VERSION = 1
MAX_SUPPORTED_WRITER_VERSION = 2
class Compression(Enum):
UNCOMPRESSED = "UNCOMPRESSED"
SNAPPY = "SNAPPY"
GZIP = "GZIP"
BROTLI = "BROTLI"
LZ4 = "LZ4"
ZSTD = "ZSTD"
LZ4_RAW = "LZ4_RAW"
@classmethod
def from_str(cls, value: str) -> "Compression":
try:
return cls(value.upper())
except ValueError:
raise ValueError(
f"{value} is not a valid Compression. Valid values are: {[item.value for item in Compression]}"
)
def get_level_range(self) -> Tuple[int, int]:
if self == Compression.GZIP:
MIN_LEVEL = 0
MAX_LEVEL = 10
elif self == Compression.BROTLI:
MIN_LEVEL = 0
MAX_LEVEL = 11
elif self == Compression.ZSTD:
MIN_LEVEL = 1
MAX_LEVEL = 22
else:
raise KeyError(f"{self.value} does not have a compression level.")
return MIN_LEVEL, MAX_LEVEL
def get_default_level(self) -> int:
if self == Compression.GZIP:
DEFAULT = 6
elif self == Compression.BROTLI:
DEFAULT = 1
elif self == Compression.ZSTD:
DEFAULT = 1
else:
raise KeyError(f"{self.value} does not have a compression level.")
return DEFAULT
def check_valid_level(self, level: int) -> bool:
MIN_LEVEL, MAX_LEVEL = self.get_level_range()
if level < MIN_LEVEL or level > MAX_LEVEL:
raise ValueError(
f"Compression level for {self.value} should fall between {MIN_LEVEL}-{MAX_LEVEL}"
)
else:
return True
@dataclass(init=True)
class WriterProperties:
"""A Writer Properties instance for the Rust parquet writer."""
def __init__(
self,
data_page_size_limit: Optional[int] = None,
dictionary_page_size_limit: Optional[int] = None,
data_page_row_count_limit: Optional[int] = None,
write_batch_size: Optional[int] = None,
max_row_group_size: Optional[int] = None,
compression: Optional[
Literal[
"UNCOMPRESSED",
"SNAPPY",
"GZIP",
"BROTLI",
"LZ4",
"ZSTD",
"LZ4_RAW",
]
] = None,
compression_level: Optional[int] = None,
):
"""Create a Writer Properties instance for the Rust parquet writer:
Args:
data_page_size_limit: Limit DataPage size to this in bytes.
dictionary_page_size_limit: Limit the size of each DataPage to store dicts to this amount in bytes.
data_page_row_count_limit: Limit the number of rows in each DataPage.
write_batch_size: Splits internally to smaller batch size.
max_row_group_size: Max number of rows in row group.
compression: compression type.
compression_level: If none and compression has a level, the default level will be used, only relevant for
GZIP: levels (1-9),
BROTLI: levels (1-11),
ZSTD: levels (1-22),
"""
self.data_page_size_limit = data_page_size_limit
self.dictionary_page_size_limit = dictionary_page_size_limit
self.data_page_row_count_limit = data_page_row_count_limit
self.write_batch_size = write_batch_size
self.max_row_group_size = max_row_group_size
self.compression = None
if compression_level is not None and compression is None:
raise ValueError(
"""Providing a compression level without the compression type is not possible,
please provide the compression as well."""
)
if isinstance(compression, str):
compression_enum = Compression.from_str(compression)
if compression_enum in [
Compression.GZIP,
Compression.BROTLI,
Compression.ZSTD,
]:
if compression_level is not None:
if compression_enum.check_valid_level(compression_level):
parquet_compression = (
f"{compression_enum.value}({compression_level})"
)
else:
parquet_compression = f"{compression_enum.value}({compression_enum.get_default_level()})"
else:
parquet_compression = compression_enum.value
self.compression = parquet_compression
def __str__(self) -> str:
return (
f"WriterProperties(data_page_size_limit: {self.data_page_size_limit}, dictionary_page_size_limit: {self.dictionary_page_size_limit}, "
f"data_page_row_count_limit: {self.data_page_row_count_limit}, write_batch_size: {self.write_batch_size}, "
f"max_row_group_size: {self.max_row_group_size}, compression: {self.compression})"
)
def _to_dict(self) -> Dict[str, Optional[str]]:
values = {}
for key, value in self.__dict__.items():
values[key] = str(value) if isinstance(value, int) else value
return values
@dataclass(init=False)
class Metadata:
"""Create a Metadata instance."""
def __init__(self, table: RawDeltaTable):
self._metadata = table.metadata()
@property
def id(self) -> int:
"""Return the unique identifier of the DeltaTable."""
return self._metadata.id
@property
def name(self) -> str:
"""Return the user-provided identifier of the DeltaTable."""
return self._metadata.name
@property
def description(self) -> str:
"""Return the user-provided description of the DeltaTable."""
return self._metadata.description
@property
def partition_columns(self) -> List[str]:
"""Return an array containing the names of the partitioned columns of the DeltaTable."""
return self._metadata.partition_columns
@property
def created_time(self) -> int:
"""
Return The time when this metadata action is created, in milliseconds since the Unix epoch of the DeltaTable.
"""
return self._metadata.created_time
@property
def configuration(self) -> Dict[str, str]:
"""Return the DeltaTable properties."""
return self._metadata.configuration
def __str__(self) -> str:
return (
f"Metadata(id: {self._metadata.id}, name: {self._metadata.name}, "
f"description: {self._metadata.description}, partition_columns: {self._metadata.partition_columns}, "
f"created_time: {self.created_time}, configuration: {self._metadata.configuration})"
)
class ProtocolVersions(NamedTuple):
min_reader_version: int
min_writer_version: int
FilterLiteralType = Tuple[str, str, Any]
FilterConjunctionType = List[FilterLiteralType]
FilterDNFType = List[FilterConjunctionType]
FilterType = Union[FilterConjunctionType, FilterDNFType]
def _check_contains_null(value: Any) -> bool:
"""
Check if target contains nullish value.
"""
if isinstance(value, bytes):
for byte in value:
if isinstance(byte, bytes):
compare_to = chr(0)
else:
compare_to = 0
if byte == compare_to:
return True
elif isinstance(value, str):
return "\x00" in value
return False
def _check_dnf(
dnf: FilterDNFType,
check_null_strings: bool = True,
) -> FilterDNFType:
"""
Check if DNF are well-formed.
"""
if len(dnf) == 0 or any(len(c) == 0 for c in dnf):
raise ValueError("Malformed DNF")
if check_null_strings:
for conjunction in dnf:
for col, op, val in conjunction:
if (
isinstance(val, list)
and all(_check_contains_null(v) for v in val)
or _check_contains_null(val)
):
raise NotImplementedError(
"Null-terminated binary strings are not supported "
"as filter values."
)
return dnf
def _convert_single_predicate(column: str, op: str, value: Any) -> Expression:
"""
Convert given `tuple` to [pyarrow.dataset.Expression].
"""
import pyarrow.dataset as ds
field = ds.field(column)
if op == "=" or op == "==":
return field == value
elif op == "!=":
return field != value
elif op == "<":
return field < value
elif op == ">":
return field > value
elif op == "<=":
return field <= value
elif op == ">=":
return field >= value
elif op == "in":
return field.isin(value)
elif op == "not in":
return ~field.isin(value)
else:
raise ValueError(
f'"{(column, op, value)}" is not a valid operator in predicates.'
)
def _filters_to_expression(filters: FilterType) -> Expression:
"""
Check if filters are well-formed and convert to an [pyarrow.dataset.Expression].
"""
if isinstance(filters[0][0], str):
# We have encountered the situation where we have one nesting level too few:
# We have [(,,), ..] instead of [[(,,), ..]]
dnf = cast(FilterDNFType, [filters])
else:
dnf = cast(FilterDNFType, filters)
dnf = _check_dnf(dnf, check_null_strings=False)
disjunction_members = []
for conjunction in dnf:
conjunction_members = [
_convert_single_predicate(col, op, val) for col, op, val in conjunction
]
disjunction_members.append(reduce(operator.and_, conjunction_members))
return reduce(operator.or_, disjunction_members)
_DNF_filter_doc = """
Predicates are expressed in disjunctive normal form (DNF), like [("x", "=", "a"), ...].
DNF allows arbitrary boolean logical combinations of single partition predicates.
The innermost tuples each describe a single partition predicate. The list of inner
predicates is interpreted as a conjunction (AND), forming a more selective and
multiple partition predicates. Each tuple has format: (key, op, value) and compares
the key with the value. The supported op are: `=`, `!=`, `in`, and `not in`. If
the op is in or not in, the value must be a collection such as a list, a set or a tuple.
The supported type for value is str. Use empty string `''` for Null partition value.
Example:
```
("x", "=", "a")
("x", "!=", "a")
("y", "in", ["a", "b", "c"])
("z", "not in", ["a","b"])
```
"""
@dataclass(init=False)
class DeltaTable:
"""Represents a Delta Table"""
def __init__(
self,
table_uri: Union[str, Path, "os.PathLike[str]"],
version: Optional[int] = None,
storage_options: Optional[Dict[str, str]] = None,
without_files: bool = False,
log_buffer_size: Optional[int] = None,
):
"""
Create the Delta Table from a path with an optional version.
Multiple StorageBackends are currently supported: AWS S3, Azure Data Lake Storage Gen2, Google Cloud Storage (GCS) and local URI.
Depending on the storage backend used, you could provide options values using the ``storage_options`` parameter.
Args:
table_uri: the path of the DeltaTable
version: version of the DeltaTable
storage_options: a dictionary of the options to use for the storage backend
without_files: If True, will load table without tracking files.
Some append-only applications might have no need of tracking any files. So, the
DeltaTable will be loaded with a significant memory reduction.
log_buffer_size: Number of files to buffer when reading the commit log. A positive integer.
Setting a value greater than 1 results in concurrent calls to the storage api.
This can decrease latency if there are many files in the log since the last checkpoint,
but will also increase memory usage. Possible rate limits of the storage backend should
also be considered for optimal performance. Defaults to 4 * number of cpus.
"""
self._storage_options = storage_options
self._table = RawDeltaTable(
str(table_uri),
version=version,
storage_options=storage_options,
without_files=without_files,
log_buffer_size=log_buffer_size,
)
@classmethod
def from_data_catalog(
cls,
data_catalog: DataCatalog,
database_name: str,
table_name: str,
data_catalog_id: Optional[str] = None,
version: Optional[int] = None,
log_buffer_size: Optional[int] = None,
) -> "DeltaTable":
"""
Create the Delta Table from a Data Catalog.
Args:
data_catalog: the Catalog to use for getting the storage location of the Delta Table
database_name: the database name inside the Data Catalog
table_name: the table name inside the Data Catalog
data_catalog_id: the identifier of the Data Catalog
version: version of the DeltaTable
log_buffer_size: Number of files to buffer when reading the commit log. A positive integer.
Setting a value greater than 1 results in concurrent calls to the storage api.
This can decrease latency if there are many files in the log since the last checkpoint,
but will also increase memory usage. Possible rate limits of the storage backend should
also be considered for optimal performance. Defaults to 4 * number of cpus.
"""
table_uri = RawDeltaTable.get_table_uri_from_data_catalog(
data_catalog=data_catalog.value,
data_catalog_id=data_catalog_id,
database_name=database_name,
table_name=table_name,
)
return cls(
table_uri=table_uri, version=version, log_buffer_size=log_buffer_size
)
@classmethod
def create(
cls,
table_uri: Union[str, Path],
schema: Union[pyarrow.Schema, DeltaSchema],
mode: Literal["error", "append", "overwrite", "ignore"] = "error",
partition_by: Optional[Union[List[str], str]] = None,
name: Optional[str] = None,
description: Optional[str] = None,
configuration: Optional[Mapping[str, Optional[str]]] = None,
storage_options: Optional[Dict[str, str]] = None,
custom_metadata: Optional[Dict[str, str]] = None,
) -> "DeltaTable":
"""`CREATE` or `CREATE_OR_REPLACE` a delta table given a table_uri.
Args:
table_uri: URI of a table
schema: Table schema
mode: How to handle existing data. Default is to error if table already exists.
If 'append', returns not support error if table exists.
If 'overwrite', will `CREATE_OR_REPLACE` table.
If 'ignore', will not do anything if table already exists. Defaults to "error".
partition_by: List of columns to partition the table by.
name: User-provided identifier for this table.
description: User-provided description for this table.
configuration: A map containing configuration options for the metadata action.
storage_options: options passed to the object store crate.
custom_metadata: custom metadata that will be added to the transaction commit.
Returns:
DeltaTable: created delta table
Example:
```python
import pyarrow as pa
from deltalake import DeltaTable
dt = DeltaTable.create(
table_uri="my_local_table",
schema=pa.schema(
[pa.field("foo", pa.string()), pa.field("bar", pa.string())]
),
mode="error",
partition_by="bar",
)
```
"""
if isinstance(schema, DeltaSchema):
schema = schema.to_pyarrow()
if isinstance(partition_by, str):
partition_by = [partition_by]
if isinstance(table_uri, Path):
table_uri = str(table_uri)
_create_deltalake(
table_uri,
schema,
partition_by or [],
mode,
name,
description,
configuration,
storage_options,
custom_metadata,
)
return cls(table_uri=table_uri, storage_options=storage_options)
def version(self) -> int:
"""
Get the version of the DeltaTable.
Returns:
The current version of the DeltaTable
"""
return self._table.version()
def files(
self, partition_filters: Optional[List[Tuple[str, str, Any]]] = None
) -> List[str]:
"""
Get the .parquet files of the DeltaTable.
The paths are as they are saved in the delta log, which may either be
relative to the table root or absolute URIs.
Args:
partition_filters: the partition filters that will be used for
getting the matched files
Returns:
list of the .parquet files referenced for the current version of the DeltaTable
Predicates are expressed in disjunctive normal form (DNF), like [("x", "=", "a"), ...].
DNF allows arbitrary boolean logical combinations of single partition predicates.
The innermost tuples each describe a single partition predicate. The list of inner
predicates is interpreted as a conjunction (AND), forming a more selective and
multiple partition predicates. Each tuple has format: (key, op, value) and compares
the key with the value. The supported op are: `=`, `!=`, `in`, and `not in`. If
the op is in or not in, the value must be a collection such as a list, a set or a tuple.
The supported type for value is str. Use empty string `''` for Null partition value.
Example:
```
("x", "=", "a")
("x", "!=", "a")
("y", "in", ["a", "b", "c"])
("z", "not in", ["a","b"])
```
"""
return self._table.files(self.__stringify_partition_values(partition_filters))
def file_uris(
self, partition_filters: Optional[List[Tuple[str, str, Any]]] = None
) -> List[str]:
"""
Get the list of files as absolute URIs, including the scheme (e.g. "s3://").
Local files will be just plain absolute paths, without a scheme. (That is,
no 'file://' prefix.)
Use the partition_filters parameter to retrieve a subset of files that match the
given filters.
Args:
partition_filters: the partition filters that will be used for getting the matched files
Returns:
list of the .parquet files with an absolute URI referenced for the current version of the DeltaTable
Predicates are expressed in disjunctive normal form (DNF), like [("x", "=", "a"), ...].
DNF allows arbitrary boolean logical combinations of single partition predicates.
The innermost tuples each describe a single partition predicate. The list of inner
predicates is interpreted as a conjunction (AND), forming a more selective and
multiple partition predicates. Each tuple has format: (key, op, value) and compares
the key with the value. The supported op are: `=`, `!=`, `in`, and `not in`. If
the op is in or not in, the value must be a collection such as a list, a set or a tuple.
The supported type for value is str. Use empty string `''` for Null partition value.
Example:
```
("x", "=", "a")
("x", "!=", "a")
("y", "in", ["a", "b", "c"])
("z", "not in", ["a","b"])
```
"""
return self._table.file_uris(
self.__stringify_partition_values(partition_filters)
)
file_uris.__doc__ = ""
def load_as_version(self, version: Union[int, str, datetime]) -> None:
"""
Load/time travel a DeltaTable to a specified version number, or a timestamp version of the table. If a
string is passed then the argument should be an RFC 3339 and ISO 8601 date and time string format.
Args:
version: the identifier of the version of the DeltaTable to load
Example:
**Use a version number**
```
dt = DeltaTable("test_table")
dt.load_as_version(1)
```
**Use a datetime object**
```
dt.load_as_version(datetime(2023,1,1))
```
**Use a datetime in string format**
```
dt.load_as_version("2018-01-26T18:30:09Z")
dt.load_as_version("2018-12-19T16:39:57-08:00")
dt.load_as_version("2018-01-26T18:30:09.453+00:00")
```
"""
if isinstance(version, int):
self._table.load_version(version)
elif isinstance(version, datetime):
self._table.load_with_datetime(version.isoformat())
elif isinstance(version, str):
self._table.load_with_datetime(version)
else:
raise TypeError(
"Invalid datatype provided for version, only int, str or datetime are accepted."
)
def load_version(self, version: int) -> None:
"""
Load a DeltaTable with a specified version.
!!! warning "Deprecated"
Load_version and load_with_datetime have been combined into `DeltaTable.load_as_version`.
Args:
version: the identifier of the version of the DeltaTable to load
"""
warnings.warn(
"Call to deprecated method DeltaTable.load_version. Use DeltaTable.load_as_version() instead.",
category=DeprecationWarning,
stacklevel=2,
)
self._table.load_version(version)
def load_with_datetime(self, datetime_string: str) -> None:
"""
Time travel Delta table to the latest version that's created at or before provided `datetime_string` argument.
The `datetime_string` argument should be an RFC 3339 and ISO 8601 date and time string.
!!! warning "Deprecated"
Load_version and load_with_datetime have been combined into `DeltaTable.load_as_version`.
Args:
datetime_string: the identifier of the datetime point of the DeltaTable to load
Example:
```
"2018-01-26T18:30:09Z"
"2018-12-19T16:39:57-08:00"
"2018-01-26T18:30:09.453+00:00"
```
"""
warnings.warn(
"Call to deprecated method DeltaTable.load_with_datetime. Use DeltaTable.load_as_version() instead.",
category=DeprecationWarning,
stacklevel=2,
)
self._table.load_with_datetime(datetime_string)
@property
def table_uri(self) -> str:
return self._table.table_uri()
def schema(self) -> DeltaSchema:
"""
Get the current schema of the DeltaTable.
Returns:
the current Schema registered in the transaction log
"""
return self._table.schema
def metadata(self) -> Metadata:
"""
Get the current metadata of the DeltaTable.
Returns:
the current Metadata registered in the transaction log
"""
return Metadata(self._table)
def protocol(self) -> ProtocolVersions:
"""
Get the reader and writer protocol versions of the DeltaTable.
Returns:
the current ProtocolVersions registered in the transaction log
"""
return ProtocolVersions(*self._table.protocol_versions())
def history(self, limit: Optional[int] = None) -> List[Dict[str, Any]]:
"""
Run the history command on the DeltaTable.
The operations are returned in reverse chronological order.
Args:
limit: the commit info limit to return
Returns:
list of the commit infos registered in the transaction log
"""
def _backwards_enumerate(
iterable: List[str], start_end: int
) -> Generator[Tuple[int, str], None, None]:
n = start_end
for elem in iterable:
yield n, elem
n -= 1
commits = list(self._table.history(limit))
history = []
for version, commit_info_raw in _backwards_enumerate(
commits, start_end=self._table.get_latest_version()
):
commit = json.loads(commit_info_raw)
commit["version"] = version
history.append(commit)
return history
def vacuum(
self,
retention_hours: Optional[int] = None,
dry_run: bool = True,
enforce_retention_duration: bool = True,
custom_metadata: Optional[Dict[str, str]] = None,
) -> List[str]:
"""
Run the Vacuum command on the Delta Table: list and delete files no longer referenced by the Delta table and are older than the retention threshold.
Args:
retention_hours: the retention threshold in hours, if none then the value from `configuration.deletedFileRetentionDuration` is used or default of 1 week otherwise.
dry_run: when activated, list only the files, delete otherwise
enforce_retention_duration: when disabled, accepts retention hours smaller than the value from `configuration.deletedFileRetentionDuration`.
custom_metadata: custom metadata that will be added to the transaction commit.
Returns:
the list of files no longer referenced by the Delta Table and are older than the retention threshold.
"""
if retention_hours:
if retention_hours < 0:
raise ValueError("The retention periods should be positive.")
return self._table.vacuum(
dry_run,
retention_hours,
enforce_retention_duration,
custom_metadata,
)
def update(
self,
updates: Optional[Dict[str, str]] = None,
new_values: Optional[
Dict[str, Union[int, float, str, datetime, bool, List[Any]]]
] = None,
predicate: Optional[str] = None,
writer_properties: Optional[WriterProperties] = None,
error_on_type_mismatch: bool = True,
custom_metadata: Optional[Dict[str, str]] = None,
) -> Dict[str, Any]:
"""`UPDATE` records in the Delta Table that matches an optional predicate. Either updates or new_values needs
to be passed for it to execute.
Args:
updates: a mapping of column name to update SQL expression.
new_values: a mapping of column name to python datatype.
predicate: a logical expression.
writer_properties: Pass writer properties to the Rust parquet writer.
error_on_type_mismatch: specify if update will return error if data types are mismatching :default = True
custom_metadata: custom metadata that will be added to the transaction commit.
Returns:
the metrics from update
Example:
**Update some row values with SQL predicate**
This is equivalent to `UPDATE table SET deleted = true WHERE id = '3'`
```py
from deltalake import write_deltalake, DeltaTable
import pandas as pd
df = pd.DataFrame(
{"id": ["1", "2", "3"],
"deleted": [False, False, False],
"price": [10., 15., 20.]
})
write_deltalake("tmp", df)
dt = DeltaTable("tmp")
dt.update(predicate="id = '3'", updates = {"deleted": 'True'})
{'num_added_files': 1, 'num_removed_files': 1, 'num_updated_rows': 1, 'num_copied_rows': 2, 'execution_time_ms': ..., 'scan_time_ms': ...}
```
**Update all row values**
This is equivalent to ``UPDATE table SET deleted = true, id = concat(id, '_old')``.
```py
dt.update(updates = {"deleted": 'True', "id": "concat(id, '_old')"})
{'num_added_files': 1, 'num_removed_files': 1, 'num_updated_rows': 3, 'num_copied_rows': 0, 'execution_time_ms': ..., 'scan_time_ms': ...}
```
**Use Python objects instead of SQL strings**
Use the `new_values` parameter instead of the `updates` parameter. For example,
this is equivalent to ``UPDATE table SET price = 150.10 WHERE id = '1'``
```py
dt.update(predicate="id = '1_old'", new_values = {"price": 150.10})
{'num_added_files': 1, 'num_removed_files': 1, 'num_updated_rows': 1, 'num_copied_rows': 2, 'execution_time_ms': ..., 'scan_time_ms': ...}
```
"""
if updates is None and new_values is not None:
updates = {}
for key, value in new_values.items():
if isinstance(value, (int, float, bool, list)):
value = str(value)
elif isinstance(value, str):
value = f"'{value}'"
elif isinstance(value, datetime):
value = str(
int(value.timestamp() * 1000 * 1000)
) # convert to microseconds
else:
raise TypeError(
"Invalid datatype provided in new_values, only int, float, bool, list, str or datetime or accepted."
)
updates[key] = value
elif updates is not None and new_values is None:
for key, value in updates.items():
print(type(key), type(value))
if not isinstance(value, str) or not isinstance(key, str):
raise TypeError(
f"The values of the updates parameter must all be SQL strings. Got {updates}. Did you mean to use the new_values parameter?"
)
elif updates is not None and new_values is not None:
raise ValueError(
"Passing updates and new_values at same time is not allowed, pick one."
)
else:
raise ValueError(
"Either updates or new_values need to be passed to update the table."
)
metrics = self._table.update(
updates,
predicate,
writer_properties._to_dict() if writer_properties else None,
safe_cast=not error_on_type_mismatch,
custom_metadata=custom_metadata,
)
return json.loads(metrics)
@property
def optimize(
self,
) -> "TableOptimizer":
"""Namespace for all table optimize related methods.
Returns:
TableOptimizer: TableOptimizer Object
"""
return TableOptimizer(self)
@property
def alter(
self,
) -> "TableAlterer":
"""Namespace for all table alter related methods.
Returns:
TableAlterer: TableAlterer Object
"""
return TableAlterer(self)
def merge(
self,
source: Union[
pyarrow.Table,
pyarrow.RecordBatch,
pyarrow.RecordBatchReader,
ds.Dataset,
"pandas.DataFrame",
],
predicate: str,
source_alias: Optional[str] = None,
target_alias: Optional[str] = None,
error_on_type_mismatch: bool = True,
writer_properties: Optional[WriterProperties] = None,
large_dtypes: bool = True,
custom_metadata: Optional[Dict[str, str]] = None,
) -> "TableMerger":
"""Pass the source data which you want to merge on the target delta table, providing a
predicate in SQL query like format. You can also specify on what to do when the underlying data types do not
match the underlying table.
Args:
source: source data
predicate: SQL like predicate on how to merge
source_alias: Alias for the source table
target_alias: Alias for the target table
error_on_type_mismatch: specify if merge will return error if data types are mismatching :default = True
writer_properties: Pass writer properties to the Rust parquet writer
large_dtypes: If True, the data schema is kept in large_dtypes.
custom_metadata: custom metadata that will be added to the transaction commit.
Returns:
TableMerger: TableMerger Object
"""
invariants = self.schema().invariants
checker = _DeltaDataChecker(invariants)
from .schema import (
convert_pyarrow_dataset,
convert_pyarrow_recordbatch,
convert_pyarrow_recordbatchreader,
convert_pyarrow_table,
)
if isinstance(source, pyarrow.RecordBatchReader):
source = convert_pyarrow_recordbatchreader(source, large_dtypes)
elif isinstance(source, pyarrow.RecordBatch):
source = convert_pyarrow_recordbatch(source, large_dtypes)
elif isinstance(source, pyarrow.Table):
source = convert_pyarrow_table(source, large_dtypes)
elif isinstance(source, ds.Dataset):
source = convert_pyarrow_dataset(source, large_dtypes)
elif isinstance(source, pandas.DataFrame):
source = convert_pyarrow_table(
pyarrow.Table.from_pandas(source), large_dtypes
)
else:
raise TypeError(
f"{type(source).__name__} is not a valid input. Only PyArrow RecordBatchReader, RecordBatch, Table or Pandas DataFrame are valid inputs for source."
)
def validate_batch(batch: pyarrow.RecordBatch) -> pyarrow.RecordBatch:
checker.check_batch(batch)
return batch
source = pyarrow.RecordBatchReader.from_batches(
source.schema, (validate_batch(batch) for batch in source)
)
return TableMerger(
self,
source=source,
predicate=predicate,
source_alias=source_alias,
target_alias=target_alias,
safe_cast=not error_on_type_mismatch,
writer_properties=writer_properties,
custom_metadata=custom_metadata,
)
def restore(
self,
target: Union[int, datetime, str],
*,
ignore_missing_files: bool = False,
protocol_downgrade_allowed: bool = False,
custom_metadata: Optional[Dict[str, str]] = None,
) -> Dict[str, Any]:
"""
Run the Restore command on the Delta Table: restore table to a given version or datetime.
Args:
target: the expected version will restore, which represented by int, date str or datetime.
ignore_missing_files: whether the operation carry on when some data files missing.
protocol_downgrade_allowed: whether the operation when protocol version upgraded.
custom_metadata: custom metadata that will be added to the transaction commit.
Returns:
the metrics from restore.
"""
if isinstance(target, datetime):
metrics = self._table.restore(
target.isoformat(),
ignore_missing_files=ignore_missing_files,
protocol_downgrade_allowed=protocol_downgrade_allowed,
custom_metadata=custom_metadata,
)
else:
metrics = self._table.restore(
target,
ignore_missing_files=ignore_missing_files,
protocol_downgrade_allowed=protocol_downgrade_allowed,