|
| 1 | +import dataclasses |
| 2 | +import logging |
| 3 | +import sqlalchemy as sa |
| 4 | +import polars as pl |
| 5 | +import pyarrow.parquet as pq |
| 6 | +from boltons.urlutils import URL |
| 7 | +from pyiceberg.catalog import load_catalog, Catalog |
| 8 | +from sqlalchemy_cratedb import insert_bulk |
| 9 | + |
| 10 | +from cratedb_toolkit.model import DatabaseAddress |
| 11 | + |
| 12 | +logger = logging.getLogger(__name__) |
| 13 | + |
| 14 | + |
| 15 | +CHUNK_SIZE = 75_000 |
| 16 | + |
| 17 | + |
| 18 | +@dataclasses.dataclass |
| 19 | +class IcebergAddress: |
| 20 | + path: str |
| 21 | + catalog: str |
| 22 | + table: str |
| 23 | + |
| 24 | + @classmethod |
| 25 | + def from_url(cls, url: str): |
| 26 | + iceberg_url = URL(url) |
| 27 | + if iceberg_url.host == ".": |
| 28 | + iceberg_url.path = iceberg_url.path.lstrip("/") |
| 29 | + return cls(path=iceberg_url.path, catalog=iceberg_url.query_params.get("catalog"), table=iceberg_url.query_params.get("table")) |
| 30 | + |
| 31 | + def load_catalog(self) -> Catalog: |
| 32 | + return load_catalog( |
| 33 | + self.catalog, |
| 34 | + **{ |
| 35 | + 'type': 'sql', |
| 36 | + "uri": f"sqlite:///{self.path}/pyiceberg_catalog.db", |
| 37 | + "warehouse": f"file://{self.path}", |
| 38 | + }, |
| 39 | + ) |
| 40 | + |
| 41 | + @property |
| 42 | + def identifier(self): |
| 43 | + return (self.catalog, self.table) |
| 44 | + |
| 45 | + def load_table(self) -> pl.LazyFrame: |
| 46 | + if self.catalog is not None: |
| 47 | + catalog = self.load_catalog() |
| 48 | + return catalog.load_table(self.identifier).to_polars() |
| 49 | + else: |
| 50 | + return pl.scan_iceberg(self.path) |
| 51 | + |
| 52 | + |
| 53 | +def from_iceberg(source_url, cratedb_url, progress: bool = False): |
| 54 | + """ |
| 55 | + Scan an Iceberg table from local filesystem or object store, and load into CrateDB. |
| 56 | + https://docs.pola.rs/api/python/stable/reference/api/polars.scan_iceberg.html |
| 57 | +
|
| 58 | + Synopsis |
| 59 | + -------- |
| 60 | + export CRATEDB_CLUSTER_URL=crate://crate@localhost:4200/testdrive/demo |
| 61 | + ctk load table "file+iceberg:var/lib/iceberg/default.db/taxi_dataset/metadata/00001-dc8e5ed2-dc29-4e39-b2e4-019e466af4c3.metadata.json" |
| 62 | + ctk load table "iceberg://./var/lib/iceberg/?catalog=default&table=taxi_dataset" |
| 63 | + """ |
| 64 | + |
| 65 | + iceberg_address = IcebergAddress.from_url(source_url) |
| 66 | + |
| 67 | + # Parse parameters. |
| 68 | + logger.info(f"Iceberg address: Path: {iceberg_address.path}, catalog: {iceberg_address.catalog}, table: {iceberg_address.table}") |
| 69 | + |
| 70 | + cratedb_address = DatabaseAddress.from_string(cratedb_url) |
| 71 | + cratedb_url, cratedb_table = cratedb_address.decode() |
| 72 | + if cratedb_table.table is None: |
| 73 | + raise ValueError("Table name is missing. Please adjust CrateDB database URL.") |
| 74 | + logger.info(f"Target address: {cratedb_address}") |
| 75 | + |
| 76 | + # Invoke copy operation. |
| 77 | + logger.info("Running Iceberg copy") |
| 78 | + engine = sa.create_engine(str(cratedb_url)) |
| 79 | + |
| 80 | + pl.Config.set_streaming_chunk_size(CHUNK_SIZE) |
| 81 | + table = iceberg_address.load_table() |
| 82 | + |
| 83 | + # This conversion to pandas is zero-copy, |
| 84 | + # so we can utilize their SQL utils for free. |
| 85 | + # https://github.com/pola-rs/polars/issues/7852 |
| 86 | + # Note: This code also uses the most efficient `insert_bulk` method with CrateDB. |
| 87 | + # https://cratedb.com/docs/sqlalchemy-cratedb/dataframe.html#efficient-insert-operations-with-pandas |
| 88 | + table.collect(streaming=True).to_pandas().to_sql( |
| 89 | + name=cratedb_table.table, schema=cratedb_table.schema, con=engine, if_exists="replace", index=False, chunksize=CHUNK_SIZE, method=insert_bulk, |
| 90 | + ) |
| 91 | + |
| 92 | + # Note: This was much slower. |
| 93 | + # table.to_polars().collect(streaming=True).write_database(table_name=table_address.fullname, connection=engine, if_table_exists="replace") |
| 94 | + |
| 95 | + |
| 96 | +def to_iceberg(source_url, target_url, progress: bool = False): |
| 97 | + """ |
| 98 | + Synopsis |
| 99 | + -------- |
| 100 | + export CRATEDB_CLUSTER_URL=crate://crate@localhost:4200/testdrive/demo |
| 101 | + ctk load table "iceberg://./var/lib/iceberg/?catalog=default&table=taxi_dataset" |
| 102 | + ctk save table "file+iceberg:var/lib/iceberg/default.db/taxi_dataset/metadata/00001-dc8e5ed2-dc29-4e39-b2e4-019e466af4c3.metadata.json" |
| 103 | + """ |
| 104 | + |
| 105 | + iceberg_address = IcebergAddress.from_url(target_url) |
| 106 | + catalog = iceberg_address.load_catalog() |
| 107 | + print("catalog:", catalog) |
| 108 | + |
| 109 | + # https://py.iceberg.apache.org/#write-a-pyarrow-dataframe |
| 110 | + df = pq.read_table("tmp/yellow_tripdata_2023-01.parquet") |
| 111 | + |
| 112 | + # Create a new Iceberg table. |
| 113 | + catalog.create_namespace_if_not_exists("default") |
| 114 | + table = catalog.create_table_if_not_exists( |
| 115 | + "default.taxi_dataset", |
| 116 | + schema=df.schema, |
| 117 | + ) |
| 118 | + |
| 119 | + # Append the dataframe to the table. |
| 120 | + table.append(df) |
| 121 | + len(table.scan().to_arrow()) |
0 commit comments