|
| 1 | +import os |
| 2 | +from typing import Any, Dict, List, Tuple |
| 3 | + |
| 4 | +import pyarrow as pa |
| 5 | +from deltalake import DeltaTable, write_deltalake |
| 6 | +from pyarrow import Schema, Table |
| 7 | + |
| 8 | +from servc.svc.com.storage.lake import Lake, LakeTable |
| 9 | +from servc.svc.config import Config |
| 10 | + |
| 11 | + |
| 12 | +class Delta(Lake[DeltaTable]): |
| 13 | + _storageOptions: Dict[str, str] = {} |
| 14 | + |
| 15 | + _location_prefix: str |
| 16 | + |
| 17 | + _table: LakeTable |
| 18 | + |
| 19 | + def __init__(self, config: Config, table: LakeTable): |
| 20 | + super().__init__(config, table) |
| 21 | + |
| 22 | + self._table = table |
| 23 | + |
| 24 | + catalog_properties_raw = config.get("catalog_properties") |
| 25 | + if not isinstance(catalog_properties_raw, dict): |
| 26 | + catalog_properties_raw = {} |
| 27 | + |
| 28 | + # TODO: make generic for all storage types |
| 29 | + if catalog_properties_raw.get("type") == "local": |
| 30 | + self._location_prefix = str( |
| 31 | + catalog_properties_raw.get("location", "/tmp/delta") |
| 32 | + ) |
| 33 | + self._storageOptions = {} |
| 34 | + else: |
| 35 | + self._location_prefix = os.path.join( |
| 36 | + str(catalog_properties_raw.get("warehouse")), |
| 37 | + str(catalog_properties_raw.get("s3.access-key-id")), |
| 38 | + ) |
| 39 | + self._storageOptions = { |
| 40 | + "AWS_ACCESS_KEY_ID": str( |
| 41 | + catalog_properties_raw.get("s3.access-key-id") |
| 42 | + ), |
| 43 | + "AWS_SECRET_ACCESS_KEY": str( |
| 44 | + catalog_properties_raw.get("s3.secret-access-key") |
| 45 | + ), |
| 46 | + "AWS_ENDPOINT_URL": str(catalog_properties_raw.get("s3.endpoint")), |
| 47 | + "AWS_ALLOW_HTTP": "true", |
| 48 | + "aws_conditional_put": "etag", |
| 49 | + } |
| 50 | + |
| 51 | + def _connect(self): |
| 52 | + if self.isOpen: |
| 53 | + return None |
| 54 | + |
| 55 | + tablename = self._get_table_name() |
| 56 | + uri = os.path.join(self._location_prefix, tablename) |
| 57 | + self._conn = DeltaTable.create( |
| 58 | + table_uri=uri, |
| 59 | + name=tablename, |
| 60 | + schema=self._table["schema"], |
| 61 | + partition_by=self._table["partitions"], |
| 62 | + mode="ignore", |
| 63 | + storage_options=self._storageOptions, |
| 64 | + ) |
| 65 | + |
| 66 | + return super()._connect() |
| 67 | + |
| 68 | + def optimize(self): |
| 69 | + table = self.getConn() |
| 70 | + |
| 71 | + print("Optimizing", self._get_table_name(), flush=True) |
| 72 | + table.optimize.compact() |
| 73 | + table.vacuum() |
| 74 | + table.cleanup_metadata() |
| 75 | + table.create_checkpoint() |
| 76 | + |
| 77 | + def getPartitions(self) -> Dict[str, List[Any]] | None: |
| 78 | + table = self.getConn() |
| 79 | + |
| 80 | + partitions: Dict[str, List[Any]] = {} |
| 81 | + for obj in table.partitions(): |
| 82 | + for key, value in obj.items(): |
| 83 | + if key not in partitions: |
| 84 | + partitions[key] = [] |
| 85 | + if value not in partitions[key]: |
| 86 | + partitions[key].append(value) |
| 87 | + |
| 88 | + return partitions |
| 89 | + |
| 90 | + def getCurrentVersion(self) -> str | None: |
| 91 | + table = self.getConn() |
| 92 | + return str(table.version()) |
| 93 | + |
| 94 | + def getVersions(self) -> List[str] | None: |
| 95 | + return [str(self.getCurrentVersion())] |
| 96 | + |
| 97 | + def insert(self, data: List[Any]) -> bool: |
| 98 | + table = self.getConn() |
| 99 | + write_deltalake( |
| 100 | + table, |
| 101 | + data=pa.Table.from_pylist(data, self.getSchema()), |
| 102 | + storage_options=self._storageOptions, |
| 103 | + mode="append", |
| 104 | + ) |
| 105 | + return True |
| 106 | + |
| 107 | + def _filters( |
| 108 | + self, |
| 109 | + partitions: Dict[str, List[Any]] | None = None, |
| 110 | + ) -> List[Tuple[str, str, Any]] | None: |
| 111 | + filters: List[Tuple[str, str, Any]] = [] |
| 112 | + if partitions is None: |
| 113 | + return None |
| 114 | + for key, value in partitions.items(): |
| 115 | + if len(value) == 1: |
| 116 | + filters.append((key, "=", value[0])) |
| 117 | + else: |
| 118 | + filters.append((key, "in", value)) |
| 119 | + return filters if len(filters) > 0 else None |
| 120 | + |
| 121 | + def overwrite( |
| 122 | + self, data: List[Any], partitions: Dict[str, List[Any]] | None = None |
| 123 | + ) -> bool: |
| 124 | + table = self.getConn() |
| 125 | + |
| 126 | + predicate: str | None = None |
| 127 | + filter = self._filters(partitions) |
| 128 | + if filter is not None: |
| 129 | + predicate = " & ".join([" ".join(x) for x in filter]) |
| 130 | + |
| 131 | + write_deltalake( |
| 132 | + table, |
| 133 | + data=pa.Table.from_pylist(data, self.getSchema()), |
| 134 | + storage_options=self._storageOptions, |
| 135 | + mode="overwrite", |
| 136 | + predicate=predicate, |
| 137 | + engine="rust", |
| 138 | + ) |
| 139 | + return True |
| 140 | + |
| 141 | + def readRaw( |
| 142 | + self, |
| 143 | + columns: List[str], |
| 144 | + partitions: Dict[str, List[Any]] | None = None, |
| 145 | + version: str | None = None, |
| 146 | + options: Any | None = None, |
| 147 | + ) -> Table: |
| 148 | + table = self.getConn() |
| 149 | + if version is not None: |
| 150 | + table.load_as_version(int(version)) |
| 151 | + |
| 152 | + if options is None or not isinstance(options, dict): |
| 153 | + options = {} |
| 154 | + |
| 155 | + rcolumns = columns if columns[0] != "*" else None |
| 156 | + |
| 157 | + if options.get("filter", None) is not None: |
| 158 | + return table.to_pyarrow_dataset( |
| 159 | + partitions=self._filters(partitions), |
| 160 | + ).to_table( |
| 161 | + filter=options.get("filter"), |
| 162 | + columns=rcolumns, |
| 163 | + ) |
| 164 | + return table.to_pyarrow_table( |
| 165 | + columns=rcolumns, |
| 166 | + partitions=self._filters(partitions), |
| 167 | + ) |
| 168 | + |
| 169 | + def read( |
| 170 | + self, |
| 171 | + columns: List[str], |
| 172 | + partitions: Dict[str, List[Any]] | None = None, |
| 173 | + version: str | None = None, |
| 174 | + options: Any | None = None, |
| 175 | + ) -> Table: |
| 176 | + return self.readRaw(columns, partitions, version, options) |
| 177 | + |
| 178 | + def getSchema(self) -> Schema | None: |
| 179 | + table = self.getConn() |
| 180 | + |
| 181 | + return table.schema().to_pyarrow() |
| 182 | + |
| 183 | + def _close(self): |
| 184 | + if self._isOpen: |
| 185 | + self._isReady = False |
| 186 | + self._isOpen = False |
| 187 | + return True |
| 188 | + return False |
0 commit comments