-
Notifications
You must be signed in to change notification settings - Fork 4
I/O: Add CSV file import, with transformations #747
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
amotl
wants to merge
3
commits into
main
Choose a base branch
from
io-files
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -7,7 +7,7 @@ on: | |
| - '*.*.*' | ||
|
|
||
| # Run on pull requests. | ||
| # pull_request: | ||
| pull_request: | ||
|
|
||
| # Run each night. | ||
| schedule: | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -7,7 +7,7 @@ on: | |
| - '*.*.*' | ||
|
|
||
| # Run on pull requests. | ||
| # pull_request: | ||
| pull_request: | ||
|
|
||
| # Run each night. | ||
| schedule: | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,152 @@ | ||
| """ | ||
| CSV file integration for CrateDB Toolkit. | ||
|
|
||
| This module provides functionality to transfer data between CSV files | ||
| and CrateDB database tables, supporting both import and export operations. | ||
| """ | ||
|
|
||
| import dataclasses | ||
| import logging | ||
| from typing import Dict, List, Optional | ||
|
|
||
| import polars as pl | ||
| from boltons.urlutils import URL | ||
|
|
||
| from cratedb_toolkit.io.util import parse_uri, polars_to_cratedb | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| DEFAULT_SEPARATOR = "," | ||
| DEFAULT_QUOTE_CHAR = '"' | ||
| DEFAULT_BATCH_SIZE = 75_000 | ||
|
|
||
|
|
||
| @dataclasses.dataclass | ||
| class CsvFileAddress: | ||
| """ | ||
| Represent a CSV file location and provide loader methods. | ||
| """ | ||
|
|
||
| url: URL | ||
| location: str | ||
| pipeline: Optional[List[str]] = dataclasses.field(default_factory=list) | ||
| batch_size: int = DEFAULT_BATCH_SIZE | ||
| # TODO: What about other parameters? See `polars.io.csv.functions`. | ||
| separator: Optional[str] = DEFAULT_SEPARATOR | ||
| quote_char: Optional[str] = DEFAULT_QUOTE_CHAR | ||
|
|
||
| @classmethod | ||
| def from_url(cls, url: str) -> "CsvFileAddress": | ||
| """ | ||
| Parse a CSV file location and return a CsvFileAddress object. | ||
|
|
||
| Examples: | ||
|
|
||
| csv://./var/lib/example.csv | ||
| https://guided-path.s3.us-east-1.amazonaws.com/demo_climate_data_export.csv | ||
| """ | ||
| url_obj, location = parse_uri(url, "csv") | ||
| try: | ||
| batch_size = int(url_obj.query_params.get("batch-size", DEFAULT_BATCH_SIZE)) | ||
| except ValueError as ex: | ||
| raise ValueError("Invalid value for batch size") from ex | ||
| return cls( | ||
| url=url_obj, | ||
| location=location, | ||
| pipeline=url_obj.query_params.getlist("pipe"), | ||
| batch_size=batch_size, | ||
| separator=url_obj.query_params.get("separator", DEFAULT_SEPARATOR), | ||
| quote_char=url_obj.query_params.get("quote-char", DEFAULT_QUOTE_CHAR), | ||
| ) | ||
|
|
||
| @property | ||
| def storage_options(self) -> Dict[str, str]: | ||
| """ | ||
| Provide file storage options. | ||
|
|
||
| TODO: Generalize. | ||
| """ | ||
| prefixes = ["aws_", "azure_", "google_", "delta_"] | ||
| return self.collect_properties(self.url.query_params, prefixes) | ||
|
|
||
| @staticmethod | ||
| def collect_properties(query_params: Dict, prefixes: List) -> Dict[str, str]: | ||
| """ | ||
| Collect parameters from URL query string. | ||
|
|
||
| TODO: Generalize. | ||
| """ | ||
| opts = {} | ||
| for name, value in query_params.items(): | ||
| for prefix in prefixes: | ||
| if name.lower().startswith(prefix) and value is not None: | ||
| opts[name.upper()] = value | ||
| break | ||
| return opts | ||
|
|
||
| def load_table(self, lazy: bool = True) -> pl.LazyFrame: | ||
| """ | ||
| Load the CSV file as a Polars LazyFrame. | ||
| """ | ||
|
|
||
| # Read from data source. | ||
| kwargs = { | ||
| "separator": self.separator, | ||
| "quote_char": self.quote_char, | ||
| "storage_options": self.storage_options, | ||
| } | ||
| # Note: Type checker ignores are only for Python 3.9. | ||
| if lazy: | ||
| lf = pl.scan_csv(self.location, **kwargs) # ty: ignore[invalid-argument-type] | ||
| else: | ||
| lf = pl.read_csv(self.location, **kwargs).lazy() # ty: ignore[invalid-argument-type] | ||
|
|
||
| # Optionally apply transformations. | ||
| if self.pipeline: | ||
| from macropipe import MacroPipe | ||
|
|
||
| mp = MacroPipe.from_recipes(*self.pipeline) | ||
| lf = mp.apply(lf) | ||
|
|
||
| return lf | ||
|
|
||
|
|
||
| def from_csv(source_url, target_url, progress: bool = False) -> bool: | ||
| """ | ||
| Scan a CSV file from local filesystem or object store, and load into CrateDB. | ||
| Documentation: https://cratedb-toolkit.readthedocs.io/io/file/csv.html | ||
|
|
||
| See also: https://docs.pola.rs/api/python/stable/reference/api/polars.scan_csv.html | ||
|
|
||
| # Synopsis: Load from filesystem. | ||
| ctk load \ | ||
| "csv://./var/lib/example.csv" \ | ||
| "crate://crate@localhost:4200/demo/example" | ||
| """ | ||
| source = CsvFileAddress.from_url(source_url) | ||
| logger.info(f"File address: {source.location}") | ||
|
|
||
| try: | ||
| return polars_to_cratedb( | ||
| frame=source.load_table(), | ||
| target_url=target_url, | ||
| chunk_size=source.batch_size or DEFAULT_BATCH_SIZE, | ||
| ) | ||
|
|
||
| # OSError: object-store error: Generic S3 error: Error performing PUT http://169.254.169.254/latest/api/token | ||
| # in 218.979617ms, after 2 retries, max_retries: 2, retry_timeout: 10s - HTTP error: | ||
| # error sending request (path: s3://guided-path/demo_climate_data_export.csv) | ||
| except OSError as ex: | ||
| msg = str(ex) | ||
| if "Generic S3 error" in msg and "/api/token" in msg: | ||
| logger.warning( | ||
| "Storage backend authentication is required for streaming reads but failed. " | ||
| "Falling back to non-streaming mode: This may result in inefficient reads." | ||
| ) | ||
| return polars_to_cratedb( | ||
| frame=source.load_table(lazy=False), | ||
| target_url=target_url, | ||
| chunk_size=source.batch_size, | ||
| ) | ||
| raise OSError(f"Loading data from CSV failed: {source_url}: {msg}") from ex |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| CREATE TABLE "{schema}".climate_data | ||
| ( | ||
| "timestamp" TIMESTAMP WITHOUT TIME ZONE, | ||
| "geo_location" GEO_POINT, | ||
| "data" OBJECT(DYNAMIC) AS ( | ||
| "temperature" DOUBLE PRECISION, | ||
| "u10" DOUBLE PRECISION, | ||
| "v10" DOUBLE PRECISION, | ||
| "pressure" DOUBLE PRECISION, | ||
| "latitude" DOUBLE PRECISION, | ||
| "longitude" DOUBLE PRECISION, | ||
| "humidity" DOUBLE PRECISION | ||
| ) | ||
| ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| timestamp,geo_location,data | ||
| 1754784000000,'[14.988999953493476, 51.10299998894334]','{"temperature": 19.704827880859398, "pressure": 99310.625, "v10": -1.545882225036621, "u10": 1.7978938817977905, "latitude": 51.102999999999945, "longitude": 14.989}' | ||
| 1754784000000,'[7.088122218847275, 51.0029999865219]','{"temperature": 19.347802734375023, "pressure": 101470.9609375, "v10": -1.256191611289978, "u10": 0.02778780460357666, "latitude": 51.00299999999994, "longitude": 7.0881222222222195}' | ||
| 1754784000000,'[7.58817776106298, 51.0029999865219]','{"temperature": 17.713037109375023, "pressure": 98837.3984375, "v10": -1.5747417211532593, "u10": -0.19953763484954834, "latitude": 51.00299999999994, "longitude": 7.588177777777774}' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| timestamp,geo_location,data | ||
| 1754784000000,"[14.988999953493476, 51.10299998894334]","{'temperature': 19.704827880859398, 'pressure': 99310.625, 'v10': -1.545882225036621, 'u10': 1.7978938817977905, 'latitude': 51.102999999999945, 'longitude': 14.989}" | ||
| 1754784000000,"[7.088122218847275, 51.0029999865219]","{'temperature': 19.347802734375023, 'pressure': 101470.9609375, 'v10': -1.256191611289978, 'u10': 0.02778780460357666, 'latitude': 51.00299999999994, 'longitude': 7.0881222222222195}" | ||
| 1754784000000,"[7.58817776106298, 51.0029999865219]","{'temperature': 17.713037109375023, 'pressure': 98837.3984375, 'v10': -1.5747417211532593, 'u10': -0.19953763484954834, 'latitude': 51.00299999999994, 'longitude': 7.588177777777774}" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| timestamp,geo_location,data | ||
| 1754784000000,'POINT ( 14.988999953493476 51.10299998894334 )','{"temperature": 19.704827880859398, "pressure": 99310.625, "v10": -1.545882225036621, "u10": 1.7978938817977905, "latitude": 51.102999999999945, "longitude": 14.989}' | ||
| 1754784000000,'POINT ( 7.088122218847275 51.0029999865219 )','{"temperature": 19.347802734375023, "pressure": 101470.9609375, "v10": -1.256191611289978, "u10": 0.02778780460357666, "latitude": 51.00299999999994, "longitude": 7.0881222222222195}' | ||
| 1754784000000,'POINT ( 7.58817776106298 51.0029999865219 )','{"temperature": 17.713037109375023, "pressure": 98837.3984375, "v10": -1.5747417211532593, "u10": -0.19953763484954834, "latitude": 51.00299999999994, "longitude": 7.588177777777774}' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| from importlib.resources import files | ||
|
|
||
| import pytest | ||
|
|
||
| import tests.io.file.data | ||
| from cratedb_toolkit import DatabaseCluster, InputOutputResource, TableAddress | ||
| from tests.conftest import TESTDRIVE_DATA_SCHEMA | ||
|
|
||
| data_folder = files(tests.io.file.data) | ||
| ddl = (data_folder / "climate_ddl.sql").read_text().format(schema=TESTDRIVE_DATA_SCHEMA) | ||
| climate_json_json = ( | ||
| str(data_folder / "climate_json_json.csv") + "?quote-char='&pipe=json_array_to_wkt_point:geo_location" | ||
| ) | ||
| climate_json_python_local = ( | ||
| str(data_folder / "climate_json_python.csv") | ||
| + '?quote-char="&pipe=json_array_to_wkt_point:geo_location&pipe=python_to_json:data' | ||
| ) | ||
| climate_wkt_json = str(data_folder / "climate_wkt_json.csv") + "?quote-char='" | ||
|
Comment on lines
+11
to
+18
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
| climate_json_python_s3 = "https://guided-path.s3.us-east-1.amazonaws.com/demo_climate_data_export.csv?pipe=json_array_to_wkt_point:geo_location&pipe=python_to_json:data" | ||
|
|
||
| table_address = TableAddress(schema=TESTDRIVE_DATA_SCHEMA, table="climate_data", if_exists="append") | ||
|
|
||
|
|
||
| @pytest.fixture(scope="function") | ||
| def provision_ddl(cratedb_synchronized) -> None: | ||
| cratedb_synchronized.database.run_sql(ddl) | ||
|
|
||
|
|
||
| def test_load_csv_wkt_json(cratedb_synchronized, provision_ddl): | ||
| """Load a CSV file that does not need any geo transformations.""" | ||
| cluster = DatabaseCluster.create(cluster_url=cratedb_synchronized.database.dburi) | ||
| cluster.load_table(InputOutputResource(climate_wkt_json), target=table_address) | ||
| cluster.adapter.refresh_table(table_address.fullname) | ||
| assert cluster.adapter.count_records(table_address.fullname) == 3, "Wrong number of records returned" | ||
|
|
||
|
|
||
| def test_load_geo_csv_json_json(cratedb_synchronized, provision_ddl): | ||
| """Load a CSV file that needs geo transformations.""" | ||
| pytest.importorskip("polars_st", reason="CSV import needs geo transformations") | ||
| cluster = DatabaseCluster.create(cluster_url=cratedb_synchronized.database.dburi) | ||
| cluster.load_table(InputOutputResource(climate_json_json), target=table_address) | ||
| cluster.adapter.refresh_table(table_address.fullname) | ||
| assert cluster.adapter.count_records(table_address.fullname) == 3, "Wrong number of records returned" | ||
|
|
||
|
|
||
| def test_load_geo_csv_json_python_local(cratedb_synchronized, provision_ddl): | ||
| """Load a CSV file that needs geo transformations.""" | ||
| pytest.importorskip("polars_st", reason="CSV import needs geo transformations") | ||
| cluster = DatabaseCluster.create(cluster_url=cratedb_synchronized.database.dburi) | ||
| cluster.load_table(InputOutputResource(climate_json_python_local), target=table_address) | ||
| cluster.adapter.refresh_table(table_address.fullname) | ||
| assert cluster.adapter.count_records(table_address.fullname) == 3, "Wrong number of records returned" | ||
|
|
||
|
|
||
| @pytest.mark.skip( | ||
| "Test takes too long to complete. When aiming to test a remote data source, please use a smaller dataset." | ||
| ) | ||
| def test_load_geo_csv_json_python_s3(cratedb_synchronized, provision_ddl): | ||
| """Load a CSV file that needs geo transformations.""" | ||
| pytest.importorskip("polars_st", reason="CSV import needs geo transformations") | ||
| cluster = DatabaseCluster.create(cluster_url=cratedb_synchronized.database.dburi) | ||
| cluster.load_table(InputOutputResource(climate_json_python_s3), target=table_address) | ||
| cluster.adapter.refresh_table(table_address.fullname) | ||
| assert cluster.adapter.count_records(table_address.fullname) == 22650, "Wrong number of records returned" | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.