Datasets:
File size: 6,525 Bytes
7e5adcc | 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 | """Write the star schema as Parquet (typed as the ClickHouse DDL declares it) and as CSVWithNames with \\N for NULL."""
from __future__ import annotations
import csv
import hashlib
from pathlib import Path
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
MONEY = pa.decimal128(18, 2)
RATE = pa.decimal128(5, 4)
# table -> [(column, arrow type, scale of the integer it is held as: 2 for cents, 4 for basis points, None for as is)]
SCHEMA: dict[str, list[tuple[str, pa.DataType, int | None]]] = {
"dim_date": [("date_key", pa.uint32(), None), ("date", pa.date32(), None), ("year", pa.uint16(), None), ("quarter", pa.uint8(), None),
("quarter_name", pa.string(), None), ("month", pa.uint8(), None), ("month_name", pa.string(), None),
("year_month", pa.uint32(), None), ("day_of_week", pa.uint8(), None), ("day_name", pa.string(), None),
("is_weekend", pa.uint8(), None)],
"dim_product": [("product_id", pa.uint32(), None), ("product_name", pa.string(), None), ("subcategory", pa.string(), None),
("category", pa.string(), None), ("brand", pa.string(), None), ("list_price", MONEY, 2), ("unit_cost", MONEY, 2)],
"dim_customer": [("customer_id", pa.uint32(), None), ("customer_name", pa.string(), None), ("segment", pa.string(), None),
("country", pa.string(), None), ("region", pa.string(), None), ("city", pa.string(), None), ("signup_date", pa.date32(), None)],
"dim_store": [("store_id", pa.uint16(), None), ("store_name", pa.string(), None), ("channel", pa.string(), None),
("country", pa.string(), None), ("region", pa.string(), None), ("city", pa.string(), None)],
"orders": [("order_id", pa.uint32(), None), ("order_date", pa.date32(), None), ("customer_id", pa.uint32(), None), ("store_id", pa.uint16(), None)],
"order_lines": [("order_line_id", pa.uint32(), None), ("order_id", pa.uint32(), None), ("date_key", pa.uint32(), None),
("order_date", pa.date32(), None), ("customer_id", pa.uint32(), None), ("store_id", pa.uint16(), None),
("product_id", pa.uint32(), None), ("quantity", pa.uint16(), None), ("unit_price", MONEY, 2), ("discount_pct", RATE, 4),
("net_amount", MONEY, 2), ("unit_cost", MONEY, 2), ("cost_amount", MONEY, 2)],
"returns": [("return_id", pa.uint32(), None), ("order_line_id", pa.uint32(), None), ("order_id", pa.uint32(), None),
("product_id", pa.uint32(), None), ("customer_id", pa.uint32(), None), ("store_id", pa.uint16(), None),
("sale_date", pa.date32(), None), ("sale_date_key", pa.uint32(), None), ("return_date", pa.date32(), None),
("return_date_key", pa.uint32(), None), ("returned_qty", pa.uint16(), None), ("refund_amount", MONEY, 2), ("reason", pa.string(), None)],
}
NULLABLE = {("dim_customer", "segment"), ("orders", "customer_id"), ("order_lines", "customer_id"), ("returns", "customer_id")}
def _decimal_array(ints: np.ndarray, typ: pa.DataType) -> pa.Array:
"""Exact decimals from whole numbers of the smallest unit (cents, basis points): a decimal128 is that integer, stored
as 16 little-endian bytes, read at the type's scale."""
v = np.ascontiguousarray(ints, dtype=np.int64)
wide = np.empty((len(v), 2), dtype="<i8")
wide[:, 0], wide[:, 1] = v, v >> 63
return pa.Array.from_buffers(typ, len(v), [None, pa.py_buffer(wide.tobytes())])
def _decimal_text(ints: np.ndarray, scale: int) -> np.ndarray:
v = np.asarray(ints, dtype=np.int64)
unit = 10 ** scale
whole, frac = np.abs(v) // unit, np.abs(v) % unit
sign = np.where(v < 0, "-", "")
return np.char.add(np.char.add(np.char.add(sign, whole.astype(str)), "."), np.char.zfill(frac.astype(str), scale))
def to_arrow(name: str, df: pd.DataFrame) -> pa.Table:
cols, fields = [], []
for col, typ, scale in SCHEMA[name]:
s = df[col]
nullable = (name, col) in NULLABLE
if not nullable and s.isna().any():
raise ValueError(f"{name}.{col} has NULLs but is declared NOT NULL")
if scale is not None:
arr = _decimal_array(s.to_numpy(dtype=np.int64), typ)
elif pa.types.is_date32(typ):
arr = pa.array(pd.to_datetime(s).dt.date, type=typ)
elif pa.types.is_string(typ):
arr = pa.array(s.astype(object).where(s.notna(), None).tolist(), type=typ)
else:
arr = pa.array(s.astype("Int64").to_numpy(dtype=object, na_value=None) if nullable else s.to_numpy(dtype=np.int64), type=typ)
cols.append(arr)
fields.append(pa.field(col, typ, nullable=nullable))
return pa.Table.from_arrays(cols, schema=pa.schema(fields))
def to_csv_frame(name: str, df: pd.DataFrame) -> pd.DataFrame:
"""The table as the text CSVWithNames carries: decimals at their scale, ISO dates, whole numbers without a point."""
out = {}
for col, typ, scale in SCHEMA[name]:
s = df[col]
if scale is not None:
out[col] = _decimal_text(s.to_numpy(dtype=np.int64), scale)
elif pa.types.is_date32(typ):
out[col] = pd.to_datetime(s).dt.strftime("%Y-%m-%d")
elif pa.types.is_string(typ):
out[col] = s
else:
out[col] = s.astype("Int64")
return pd.DataFrame(out)
def write(tables: dict[str, pd.DataFrame], parquet_dir: Path, csv_dir: Path) -> dict[str, dict]:
"""Writes both formats and returns, per file, its rows, bytes and SHA-256."""
parquet_dir.mkdir(parents=True, exist_ok=True)
csv_dir.mkdir(parents=True, exist_ok=True)
manifest: dict[str, dict] = {}
for name in SCHEMA:
t = to_arrow(name, tables[name])
pq.write_table(t, parquet_dir / f"{name}.parquet", compression="zstd", row_group_size=1_000_000,
write_statistics=True, use_dictionary=True)
path = csv_dir / f"{name}.csv"
to_csv_frame(name, tables[name]).to_csv(path, index=False, na_rep="\\N", quoting=csv.QUOTE_MINIMAL, lineterminator="\n", encoding="utf-8")
for p in (parquet_dir / f"{name}.parquet", path):
manifest[f"{p.parent.name}/{p.name}"] = {"rows": t.num_rows, "bytes": p.stat().st_size, "sha256": sha256(p)}
return manifest
def sha256(path: Path) -> str:
h = hashlib.sha256()
with path.open("rb") as fh:
for chunk in iter(lambda: fh.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
|