|
| 1 | +""" |
| 2 | +CSV file integration for CrateDB Toolkit. |
| 3 | +
|
| 4 | +This module provides functionality to transfer data between CSV files |
| 5 | +and CrateDB database tables, supporting both import and export operations. |
| 6 | +""" |
| 7 | + |
| 8 | +import dataclasses |
| 9 | +import logging |
| 10 | +from typing import Dict, List, Optional |
| 11 | + |
| 12 | +import polars as pl |
| 13 | +from boltons.urlutils import URL |
| 14 | + |
| 15 | +from cratedb_toolkit.io.util import parse_uri, polars_to_cratedb |
| 16 | + |
| 17 | +logger = logging.getLogger(__name__) |
| 18 | + |
| 19 | + |
| 20 | +DEFAULT_SEPARATOR = "," |
| 21 | +DEFAULT_QUOTE_CHAR = '"' |
| 22 | +DEFAULT_BATCH_SIZE = 75_000 |
| 23 | + |
| 24 | + |
| 25 | +@dataclasses.dataclass |
| 26 | +class CsvFileAddress: |
| 27 | + """ |
| 28 | + Represent a CSV file location and provide loader methods. |
| 29 | + """ |
| 30 | + |
| 31 | + url: URL |
| 32 | + location: str |
| 33 | + pipeline: Optional[List[str]] = dataclasses.field(default_factory=list) |
| 34 | + batch_size: Optional[int] = DEFAULT_BATCH_SIZE |
| 35 | + # TODO: What about other parameters? See `polars.io.csv.functions`. |
| 36 | + separator: Optional[str] = DEFAULT_SEPARATOR |
| 37 | + quote_char: Optional[str] = DEFAULT_QUOTE_CHAR |
| 38 | + |
| 39 | + @classmethod |
| 40 | + def from_url(cls, url: str) -> "CsvFileAddress": |
| 41 | + """ |
| 42 | + Parse a CSV file location and return a CsvFileAddress object. |
| 43 | +
|
| 44 | + Examples: |
| 45 | +
|
| 46 | + csv://./var/lib/example.csv |
| 47 | + https://guided-path.s3.us-east-1.amazonaws.com/demo_climate_data_export.csv |
| 48 | + """ |
| 49 | + url_obj, location = parse_uri(url, "csv") |
| 50 | + return cls( |
| 51 | + url=url_obj, |
| 52 | + location=location, |
| 53 | + pipeline=url_obj.query_params.getlist("pipe"), |
| 54 | + batch_size=int(url_obj.query_params.get("batch-size", DEFAULT_BATCH_SIZE)), |
| 55 | + separator=url_obj.query_params.get("separator", DEFAULT_SEPARATOR), |
| 56 | + quote_char=url_obj.query_params.get("quote-char", DEFAULT_QUOTE_CHAR), |
| 57 | + ) |
| 58 | + |
| 59 | + @property |
| 60 | + def storage_options(self) -> Dict[str, str]: |
| 61 | + """ |
| 62 | + Provide file storage options. |
| 63 | +
|
| 64 | + TODO: Generalize. |
| 65 | + """ |
| 66 | + prefixes = ["aws_", "azure_", "google_", "delta_"] |
| 67 | + return self.collect_properties(self.url.query_params, prefixes) |
| 68 | + |
| 69 | + @staticmethod |
| 70 | + def collect_properties(query_params: Dict, prefixes: List) -> Dict[str, str]: |
| 71 | + """ |
| 72 | + Collect parameters from URL query string. |
| 73 | +
|
| 74 | + TODO: Generalize. |
| 75 | + """ |
| 76 | + opts = {} |
| 77 | + for name, value in query_params.items(): |
| 78 | + for prefix in prefixes: |
| 79 | + if name.lower().startswith(prefix) and value is not None: |
| 80 | + opts[name.upper()] = value |
| 81 | + break |
| 82 | + return opts |
| 83 | + |
| 84 | + def load_table(self) -> pl.LazyFrame: |
| 85 | + """ |
| 86 | + Load the CSV file as a Polars LazyFrame. |
| 87 | + """ |
| 88 | + |
| 89 | + # Read from data source. |
| 90 | + lf = pl.scan_csv( |
| 91 | + self.location, |
| 92 | + separator=self.separator, |
| 93 | + quote_char=self.quote_char, |
| 94 | + storage_options=self.storage_options, |
| 95 | + ) |
| 96 | + |
| 97 | + # Optionally apply transformations. |
| 98 | + if self.pipeline: |
| 99 | + from macropipe import MacroPipe |
| 100 | + |
| 101 | + mp = MacroPipe.from_recipes(*self.pipeline) |
| 102 | + lf = mp.apply(lf) |
| 103 | + |
| 104 | + return lf |
| 105 | + |
| 106 | + |
| 107 | +def from_csv(source_url, target_url, progress: bool = False) -> bool: |
| 108 | + """ |
| 109 | + Scan a CSV file from local filesystem or object store, and load into CrateDB. |
| 110 | + Documentation: https://cratedb-toolkit.readthedocs.io/io/file/csv.html |
| 111 | +
|
| 112 | + See also: https://docs.pola.rs/api/python/stable/reference/api/polars.scan_csv.html |
| 113 | +
|
| 114 | + # Synopsis: Load from filesystem. |
| 115 | + ctk load \ |
| 116 | + "csv://./var/lib/example.csv" \ |
| 117 | + "crate://crate@localhost:4200/demo/example" |
| 118 | + """ |
| 119 | + source = CsvFileAddress.from_url(source_url) |
| 120 | + logger.info(f"File address: {source.location}") |
| 121 | + return polars_to_cratedb( |
| 122 | + frame=source.load_table(), |
| 123 | + target_url=target_url, |
| 124 | + chunk_size=source.batch_size, |
| 125 | + ) |
0 commit comments